diff --git "a/5334.jsonl" "b/5334.jsonl" new file mode 100644--- /dev/null +++ "b/5334.jsonl" @@ -0,0 +1,773 @@ +{"seq_id":"119314893","text":"import theano\nfrom theano import tensor as T\nimport numpy as np\n\"\"\"\nThis module contains different optimization methods\n\"\"\"\n# TODO: Implementation of AdaGrad, Nesterov Momentum, and AdaDelta\n\n\ndef sgd(params, dparams, config=None):\n \"\"\"\n Stochastic gradient descent method: param = param - learning_rate*dparam\n :param params: parameters of nn\n :param dparams: parameters' gradients with respect to loss\n :param config: a dictionary contains learning rate\n :return: updates: a list of tuple contains the updates method:\n [(param, param-learning_rate*dparam)]\n \"\"\"\n if config is None:\n config = {}\n config.setdefault('learning_rate', 1e-3)\n updates = [(param, param - (config['learning_rate'] * dparam)) for param, dparam in zip(params, dparams)]\n return updates\n\n\ndef sgd_momentum(params, dparams, config=None):\n \"\"\"\n Performs momentum sgd updates\n :param params:\n :param dparams:\n :param config: configuration of sgd_momentum: default values are learning_rate=1e-3, momentum = 9e-1\n :return:\n \"\"\"\n if config is None:\n config = {}\n config.setdefault('learning_rate', 1e-3)\n config.setdefault('momentum', 0.9)\n momentum = config['momentum']\n learning_rate = config['learning_rate']\n updates = []\n for param, grad in zip(params, dparams):\n # init velocity to zeros with the same type and shape as param\n v = theano.shared(param.get_value()*0., borrow=True)\n\n # perform v update\n new_v = momentum * v - (learning_rate * grad)\n\n # use the updated v to perform parameters update\n new_param = param + new_v\n\n # add the updates into a list\n updates.append((v, new_v))\n updates.append((param, new_param))\n return updates\n\n\ndef rmsprop(params, dparams, config=None):\n \"\"\"\n Uses the RMSProp update rule, which uses a moving average of squared gradient\n values to set adaptive per-parameter learning rates.\n :param params: nn parameters(weight, gamma, beta, bias)\n :param dparams: gradient with respect to loss\n :param config: a dictionary contains learning_rate, decay_rate, and eps\n :return:\n \"\"\"\n if config is None:\n config = {}\n config.setdefault('learning_rate', 1e-3)\n config.setdefault('decay_rate', 0.95)\n config.setdefault('eps', 1e-8)\n learning_rate = config['learning_rate']\n decay_rate = config['decay_rate']\n eps = config['eps']\n updates = []\n for param, grad in zip(params, dparams):\n running_grad = theano.shared(param.get_value()*0.0, borrow=True)\n new_running_grad = decay_rate*running_grad + (1-decay_rate) * grad**2\n gradient_scaling = T.sqrt(new_running_grad+eps)\n grad = grad/gradient_scaling\n updates.append((running_grad, new_running_grad))\n updates.append((param, param - learning_rate*grad))\n return updates\n\n\ndef adam(params, dparams, config=None):\n \"\"\"\n Use the Adam update rule. Still trying to figure out the math details.\n Paper can be found here:\n :param params: nn parameters\n :param dparams: gradient with respect to loss\n :param config: contains learning_rate, beta1, beta2, and eps\n :return:\n \"\"\"\n if config is None:\n config = {}\n config.setdefault('learning_rate', 1e-3)\n config.setdefault('beta1', 0.9)\n config.setdefault('beta2', 0.999)\n config.setdefault('eps', 1e-8)\n learning_rate = config['learning_rate']\n beta1 = config['beta1']\n beta2 = config['beta2']\n eps = config['eps']\n updates = []\n t = theano.shared(np.float32(1.0), borrow=True)\n for param, dparam in zip(params, dparams):\n m = theano.shared(param.get_value()*0., borrow=True)\n v = theano.shared(param.get_value()*0., borrow=True)\n new_m = beta1*m + ((1-beta1)*dparam)\n new_v = beta2*v + (1-beta2)*(dparam ** 2)\n updates.append((m, new_m))\n updates.append((v, new_v))\n alpha = learning_rate * T.sqrt(1 - beta2**t)/(1 - beta1**t)\n new_param = param - (alpha * new_m)/(T.sqrt(new_v)+eps)\n updates.append((param, new_param))\n updates.append((t, t+1))\n return updates\n","sub_path":"optim_method.py","file_name":"optim_method.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"570511980","text":"import tensorflow as tf\nimport numpy as np\n\nkeras = tf.keras\n\n# model with a layer with a single neuron being fed a single value, x\nmodel = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])\n# compiling the model with an optimizer and a loss function\n# the optimizer makes a guess, and the loss function evaluates the guess\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\n\nxs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)\nys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)\n\nmodel.fit(xs, ys, epochs=5000)\n\n# guessing the y-value for a given x\nprint(model.predict([10.0]))","sub_path":"Artificial Intelligence/TensorFlow Snippets/model-fitting-series.py","file_name":"model-fitting-series.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"578974663","text":"from random import randint\r\nintput = input(\"Enter any string of numbers.\\n\")\r\nfound = False\r\nguessNum = 0\r\nminNum = len(str(10**(int(intput)-1)))\r\nmaxNum = len(str(10**(int(intput))))\r\n\r\ndef random(n):\r\n rangeStart = 10**(n-1)\r\n rangeEnd = (10**n)\r\n return randint(rangeStart, rangeEnd)\r\n\r\nguess = random(len(str(intput)))\r\n\r\nwhile not found:\r\n if guess == int(intput):\r\n print(\"I found the number!\")\r\n print(\"It is \" + intput + \"!\")\r\n print(\"I took \" + str(guessNum) + \" guesses to get it.\")\r\n found = True\r\n elif guess > int(intput):\r\n print(str(guess))\r\n guess = random(len(str(intput)))\r\n guessNum += 1\r\n else:\r\n print(str(guess))\r\n guess = random(len(str(intput)))\r\n guessNum += 1","sub_path":"modifiedasd.py","file_name":"modifiedasd.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"47882173","text":"import numpy as np\nimport cv2\n\nfrom skimage.feature import hog\n\nfrom scipy.ndimage.measurements import label\n\ndef convert_color(img, conv='RGB2YCrCb'):\n\tif conv == 'RGB2YCrCb':\n\t\treturn cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n\tif conv == 'BGR2YCrCb':\n\t\treturn cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\n\tif conv == 'RGB2LUV':\n\t\treturn cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n\ndef get_hog_features(img, orient, pix_per_cell, cell_per_block, \n\t\t\t\t\t\tvis=False, feature_vec=True):\n\t# Call with two outputs if vis==True\n\tif vis == True:\n\t\tfeatures, hog_image = hog(img, orientations=orient, \n\t\t\t\t\t\t\t\t pixels_per_cell=(pix_per_cell, pix_per_cell),\n\t\t\t\t\t\t\t\t cells_per_block=(cell_per_block, cell_per_block),\n\t\t\t\t\t\t\t\t block_norm= 'L2-Hys',\n\t\t\t\t\t\t\t\t transform_sqrt=False, \n\t\t\t\t\t\t\t\t visualise=vis, feature_vector=feature_vec)\n\t\treturn features, hog_image\n\t# Otherwise call with one output\n\telse: \n\t\tfeatures = hog(img, orientations=orient, \n\t\t\t\t\t pixels_per_cell=(pix_per_cell, pix_per_cell),\n\t\t\t\t\t cells_per_block=(cell_per_block, cell_per_block),\n\t\t\t\t\t block_norm= 'L2-Hys',\n\t\t\t\t\t transform_sqrt=False, \n\t\t\t\t\t visualise=vis, feature_vector=feature_vec)\n\t\treturn features\n\ndef bin_spatial(img, size=(32, 32)):\n\tcolor1 = cv2.resize(img[:,:,0], size).ravel()\n\tcolor2 = cv2.resize(img[:,:,1], size).ravel()\n\tcolor3 = cv2.resize(img[:,:,2], size).ravel()\n\treturn np.hstack((color1, color2, color3))\n\t# features = cv2.resize(img, size).ravel()\n\t# return features\n\t\t\t\t\t\t\ndef color_hist(img, nbins=32): #bins_range=(0, 256)\n\n\tchannel1_hist = np.histogram(img[:,:,0], bins=nbins)\n\tchannel2_hist = np.histogram(img[:,:,1], bins=nbins)\n\tchannel3_hist = np.histogram(img[:,:,2], bins=nbins)\n\n\thist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n\n\treturn hist_features\n\n\ndef find_cars(img, ystart, ystop, scale, svc, X_scaler, orient, pix_per_cell, cell_per_block, spatial_size):\n\t\n\tdraw_img = np.copy(img)\n\n\t\n\timg_tosearch = img[ystart:ystop,:,:]\n\tctrans_tosearch = convert_color(img_tosearch, conv='BGR2YCrCb')\n\tif scale != 1:\n\t\timshape = ctrans_tosearch.shape\n\t\tctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale)))\n\t\t\n\tch1 = ctrans_tosearch[:,:,0]\n\tch2 = ctrans_tosearch[:,:,1]\n\tch3 = ctrans_tosearch[:,:,2]\n\n\n\tnxblocks = (ch1.shape[1] // pix_per_cell) - cell_per_block + 1\n\tnyblocks = (ch1.shape[0] // pix_per_cell) - cell_per_block + 1 \n\tnfeat_per_block = orient*cell_per_block**2\n\t\n\n\twindow = 64\n\tnblocks_per_window = (window // pix_per_cell) - cell_per_block + 1\n\tcells_per_step = 2 # Instead of overlap, define how many cells to step\n\tnxsteps = (nxblocks - nblocks_per_window) // cells_per_step + 1\n\tnysteps = (nyblocks - nblocks_per_window) // cells_per_step + 1\n\t\n\n\thog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, feature_vec=False)\n\thog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False)\n\thog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False)\n\n\tboxes = []\n\t\n\tfor xb in range(nxsteps):\n\t\tfor yb in range(nysteps):\n\t\t\typos = yb*cells_per_step\n\t\t\txpos = xb*cells_per_step\n\t\t\t# Extract HOG for this patch\n\t\t\thog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() \n\t\t\thog_feat2 = hog2[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() \n\t\t\thog_feat3 = hog3[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() \n\t\t\thog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))\n\n\t\t\txleft = xpos*pix_per_cell\n\t\t\tytop = ypos*pix_per_cell\n\n\t\t\tsubimg = cv2.resize(ctrans_tosearch[ytop:ytop+window, xleft:xleft+window], (64,64))\n\t\t \n\t\t\tspatial_features = bin_spatial(subimg, size=spatial_size)\n\t\t\t# hist_features = color_hist(subimg, nbins=hist_bins)\n\n\t\t\ttest_features = X_scaler.transform(np.hstack((spatial_features, hog_features)).reshape(1, -1)) \n \n\t\t\t\n\t\t\t# test_prediction = svc.predict_prob(test_features)\n\t\t\ttest_prediction = svc.predict(test_features)\n\t\t\t\n\t\t\tif test_prediction == 1:\n\t\t\t# if test_prediction[0][1] > 0.75:\n\t\t\t\txbox_left = np.int(xleft*scale)\n\t\t\t\tytop_draw = np.int(ytop*scale)\n\t\t\t\twin_draw = np.int(window*scale)\n\t\t\t\t# cv2.rectangle(draw_img,(xbox_left, ytop_draw+ystart),(xbox_left+win_draw,ytop_draw+win_draw+ystart),(0,0,255),3)\n\t\t\t\tboxes.append(((xbox_left, ytop_draw+ystart),(xbox_left+win_draw,ytop_draw+win_draw+ystart)))\n\n\treturn boxes\n\n\ndef extract_features(image, orient, pix_per_cell, cell_per_block, spatial_size):\n\timage = convert_color(image, conv='BGR2YCrCb')\n\n\tch1 = image[:,:,0]\n\tch2 = image[:,:,1]\n\tch3 = image[:,:,2]\n\n\n\thog_feat1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, feature_vec=False).ravel()\n\thog_feat2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False).ravel()\n\thog_feat3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False).ravel()\n\n\thog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))\n\n\tspatial_features = bin_spatial(image, size=spatial_size)\n\t# hist_features = color_hist(image, nbins=hist_bins)\n\treturn np.hstack((spatial_features, hog_features))","sub_path":"P5-Vehicle-Detection/fn.py","file_name":"fn.py","file_ext":"py","file_size_in_byte":5111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"558285197","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nfrom bayes_opt import BayesianOptimization\nfrom matplotlib import pyplot as plt\n\nimport argparse\nimport copy\nimport datetime\nimport functools\nimport itertools\nimport json\nimport numba\nimport numpy as np\nimport os.path\nimport pandas as pd\nimport sklearn.neighbors\nimport sklearn.preprocessing\nimport sys\nimport time\nimport xgboost\n\n# This is from Run A3 in my notebook.\n# With last 10% in time as validation set,\n# this produces a nearest neighbor MAP3\n# of 0.54844. NX = NY = 10.\n# the leaderboard score is 0.57920\n#\n# check knn_bayes_4.log\nknn_opt_params_0 = {\n 'th': 3.1, # modified from 0.3993\n 'w_x': 560.4030,\n 'w_y': 1000.,\n 'w_hour': 2.7613,\n 'w_log10acc': 23.7475,\n 'w_weekday': 2.3018,\n 'w_month': 5.2547,\n 'w_year': 10.6362,\n 'n_neighbors': 16\n}\n\n# Loosely based on default XGBoost params\n# with a lower learning rate.\nxgboost_params_0 = {\n 'cut_threshold': 4,\n 'n_estimators': 100,\n 'learning_rate': 0.1,\n 'gamma': 0.0,\n 'subsample': 1.0,\n 'colsample_bytree': 1.0,\n 'colsample_bylevel': 1.0,\n 'reg_alpha': 0.0,\n 'reg_lambda': 1.0,\n 'min_child_weight': 1,\n 'max_depth': 5\n}\n\nxgboost_params_1 = {\n 'cut_threshold' : 3,\n 'n_estimators': 100,\n 'learning_rate': 0.075,\n 'gamma': 0.05,\n 'subsample': 0.6,\n 'colsample_bytree': 0.4,\n 'colsample_bylevel': 0.3,\n 'reg_alpha': 0.04,\n 'reg_lambda': 1.2,\n 'min_child_weight': 0.5,\n 'max_depth': 4\n}\n\nxgboost_params_2 = {\n 'cut_threshold': 5,\n 'n_estimators': 120,\n 'learning_rate': 0.05,\n 'gamma': 0.03,\n 'subsample': 0.8,\n 'colsample_bytree': 0.6,\n 'colsample_bylevel': 0.7,\n 'reg_alpha': 0.05,\n 'reg_lambda': 0.7,\n 'min_child_weight': 0.7,\n 'max_depth': 5\n}\n\n\nxgboost_params_3 = {\n 'cut_threshold': 6,\n 'n_estimators': 120,\n 'learning_rate': 0.04,\n 'gamma': 0.05,\n 'subsample': 0.5,\n 'colsample_bytree': 0.4,\n 'colsample_bylevel': 0.5,\n 'reg_alpha': 0.03,\n 'reg_lambda': 0.7,\n 'min_child_weight': 0.6,\n 'max_depth': 5\n}\n\nxgboost_params_4 = {\n 'cut_threshold': 5,\n 'n_estimators': 150,\n 'learning_rate': 0.035,\n 'gamma': 0.03,\n 'subsample': 0.4,\n 'colsample_bytree': 0.7,\n 'colsample_bylevel': 0.6,\n 'reg_alpha': 0.06,\n 'reg_lambda': 0.8,\n 'min_child_weight': 0.8,\n 'max_depth': 5\n}\n\n\n# Set important parameters of the script.\nsize = 10.\nNX = 100\nNY = 100\nx_step = size/float(NX)\ny_step = size/float(NY)\nx_cell_margin = x_step*0.2\ny_cell_margin = y_step*0.2\n\nXGB_PARAMS_USE = xgboost_params_4\nKNN_PARAMS_USE = knn_opt_params_0\nRUN_NAME = 'run9'\n\n\ndef load_data():\n df_train = pd.read_csv('../input/train.csv')\n df_train.sort_values('time', inplace=True)\n\n df_test = pd.read_csv('../input/test.csv')\n\n ninety_percent_mark = int(df_train.shape[0]*0.9)\n df_valifold = df_train[ninety_percent_mark:].copy()\n df_trainfold = df_train[:ninety_percent_mark].copy()\n\n return df_train, df_test, df_trainfold, df_valifold\n\n\ndef map_k_precision(truthvalues, predictions):\n '''\n This is a faster implementation of MAP@k valid for numpy arrays.\n It is only valid when there is one single truth value.\n\n m ~ number of observations\n k ~ MAP at k -- in this case k should equal 3\n\n truthvalues.shape = (m,)\n predictions.shape = (m, k)\n '''\n z = (predictions == truthvalues[:, None]).astype(np.float32)\n weights = 1./(np.arange(predictions.shape[1], dtype=np.float32) + 1.)\n z = z * weights[None, :]\n return float(np.mean(np.sum(z, axis=1)))\n\n\ndef prepare_data_xgboost(dataframe):\n minute = dataframe['time'] % 60\n dataframe['hour'] = dataframe['time']//60\n dataframe['weekday'] = dataframe['hour']//24\n dataframe['month'] = dataframe['weekday']//30\n dataframe['year'] = (dataframe['weekday']//365+1)\n dataframe['hour'] = ((dataframe['hour'] % 24+1)+minute/60.0)\n dataframe['weekday'] = (dataframe['weekday'] % 7+1)\n dataframe['month'] = (dataframe['month'] % 12+1)\n dataframe['log10acc'] = np.log10(dataframe['accuracy'].values)\n dataframe.drop(['time'], axis=1, inplace=True)\n\n\n# Call the Numba JIT compiler ... write the loops manually like I would in C\n@numba.autojit\ndef generate_dist_features(encoded_placeids, distances, n_categories):\n\n assert(encoded_placeids.shape == distances.shape)\n assert(encoded_placeids.ndim == 2)\n\n sh = encoded_placeids.shape\n\n o = np.zeros((sh[0], n_categories, ), dtype=np.float32)\n\n for i in range(sh[0]):\n for j in range(sh[1]):\n o[i, encoded_placeids[i, j]] += distances[i, j]\n\n return o\n\n\ndef add_knn_features(df_train, df_test, knn_params):\n\n weighted_df_train = df_train.copy()\n weighted_df_test = df_test.copy()\n\n # divide the train set into two pieces,\n # 1. with place_ids that occur more than 'th' times\n # 2. less than 'th' times\n # and there's the test set, for a total of three pieces\n\n place_counts = weighted_df_train.place_id.value_counts()\n mask = (place_counts[weighted_df_train.place_id.values]\n >= knn_params['th']).values\n\n # weighted_df_train_masked contains less than 'th' times rows\n weighted_df_train_masked = weighted_df_train.loc[~mask]\n\n # more than 'th' times rows\n weighted_df_train = weighted_df_train.loc[mask]\n\n # save these for later.\n weighted_df_train_place_ids = weighted_df_train.place_id.values\n\n # drop some columns, 'place_id' can occur in test set under\n # certain validation or cross-validation conditions.\n weighted_df_train.drop(['accuracy', 'place_id'], axis=1, inplace=True)\n weighted_df_train_masked.drop(\n ['accuracy', 'place_id'], axis=1, inplace=True)\n weighted_df_test.drop('accuracy', axis=1, inplace=True)\n if 'place_id' in weighted_df_test.columns:\n weighted_df_test.drop('place_id', axis=1, inplace=True)\n\n # -------\n # This block reweights all three pieces\n weighted_df_train.loc[:, 'x'] *= knn_params['w_x']\n weighted_df_train.loc[:, 'y'] *= knn_params['w_y']\n weighted_df_train.loc[:, 'hour'] *= knn_params['w_hour']\n weighted_df_train.loc[:, 'weekday'] *= knn_params['w_weekday']\n weighted_df_train.loc[:, 'month'] *= knn_params['w_month']\n weighted_df_train.loc[:, 'year'] *= knn_params['w_year']\n weighted_df_train.loc[:, 'log10acc'] *= knn_params['w_log10acc']\n\n weighted_df_train_masked.loc[:, 'x'] *= knn_params['w_x']\n weighted_df_train_masked.loc[:, 'y'] *= knn_params['w_y']\n weighted_df_train_masked.loc[:, 'hour'] *= knn_params['w_hour']\n weighted_df_train_masked.loc[:, 'weekday'] *= knn_params['w_weekday']\n weighted_df_train_masked.loc[:, 'month'] *= knn_params['w_month']\n weighted_df_train_masked.loc[:, 'year'] *= knn_params['w_year']\n weighted_df_train_masked.loc[:, 'log10acc'] *= knn_params['w_log10acc']\n\n weighted_df_test.loc[:, 'x'] *= knn_params['w_x']\n weighted_df_test.loc[:, 'y'] *= knn_params['w_y']\n weighted_df_test.loc[:, 'hour'] *= knn_params['w_hour']\n weighted_df_test.loc[:, 'weekday'] *= knn_params['w_weekday']\n weighted_df_test.loc[:, 'month'] *= knn_params['w_month']\n weighted_df_test.loc[:, 'year'] *= knn_params['w_year']\n weighted_df_test.loc[:, 'log10acc'] *= knn_params['w_log10acc']\n # ------- End reweighting block -----\n\n # --- Find distances block -----\n\n nn_ = sklearn.neighbors.NearestNeighbors(metric='manhattan')\n\n nn_.fit(weighted_df_train[\n 'x y hour weekday month year log10acc'.split()].values)\n dists_train, indices_train = nn_.kneighbors(\n weighted_df_train[\n 'x y hour weekday month year log10acc'.split()].values,\n n_neighbors=knn_params['n_neighbors']+1)\n dists_train_masked, indices_train_masked = nn_.kneighbors(\n weighted_df_train_masked[\n 'x y hour weekday month year log10acc'.split()].values,\n n_neighbors=knn_params['n_neighbors'])\n dists_test, indices_test = nn_.kneighbors(\n weighted_df_test[\n 'x y hour weekday month year log10acc'.split()].values,\n n_neighbors=knn_params['n_neighbors'])\n\n # --- Find distances complete -----\n\n # For a sensible feature that behaves identically in the training and testing\n # datasets, we have to eliminate the \"memorization\" that occurs with the\n # nearest neighbor algorithm. This means, eliminate points with identically\n # zero distance, as they are just the training example.\n\n # eliminate the self-distance in the training neighbors dataset,\n # and take reciprocal distance for all three pieces\n dists_train = 1. / dists_train[:, 1:]\n indices_train = indices_train[:, 1:]\n dists_train_masked = 1. / dists_train_masked\n dists_test = 1. / dists_test\n\n # Find the predicted place_id for all three pieces\n place_ids_knn_train = np.take(weighted_df_train_place_ids, indices_train)\n place_ids_knn_train_masked = np.take(\n weighted_df_train_place_ids, indices_train_masked)\n place_ids_knn_test = np.take(weighted_df_train_place_ids, indices_test)\n\n # By using this method, the labels in LabelEncoder are sorted by place_id\n unique_place_ids = np.unique(place_ids_knn_train.ravel())\n unique_place_ids.sort()\n le = sklearn.preprocessing.LabelEncoder()\n le.fit_transform(unique_place_ids)\n\n # encode place_id for all three pieces.\n place_ids_knn_train_enc = le.transform(place_ids_knn_train)\n place_ids_knn_train_masked_enc = le.transform(place_ids_knn_train_masked)\n place_ids_knn_test_enc = le.transform(place_ids_knn_test)\n\n # Take the encoded labels and build a weighted matrix of place_id\n # weights based on it. Shape is (m, p) where m is number of\n # observations in that piece (train, train_masked, test), and\n # p is the number of place_ids in the training dataset. By\n # construction, the encoded place_ids go from 0 to p-1, allowing\n # easy coding into a matrix.\n train_dist_feat = generate_dist_features(place_ids_knn_train_enc,\n dists_train,\n unique_place_ids.shape[0])\n train_dist_masked_feat = generate_dist_features(\n place_ids_knn_train_masked_enc,\n dists_train_masked,\n unique_place_ids.shape[0])\n test_dist_feat = generate_dist_features(place_ids_knn_test_enc,\n dists_test,\n unique_place_ids.shape[0])\n\n # Now we turn this into a dataframe.\n column_labels = ['d{}'.format(x) for x in unique_place_ids]\n\n new_df_train = pd.DataFrame(train_dist_feat,\n index=weighted_df_train.index.values,\n columns=column_labels)\n new_df_train_masked = pd.DataFrame(\n train_dist_masked_feat,\n index=weighted_df_train_masked.index.values,\n columns=column_labels)\n new_df_test = pd.DataFrame(test_dist_feat,\n index=weighted_df_test.index.values,\n columns=column_labels)\n\n new_df_train = new_df_train.append(new_df_train_masked)\n\n # do an inner join on row_id\n new_df_train = pd.merge(\n df_train, new_df_train, left_index=True, right_index=True)\n new_df_test = pd.merge(\n df_test, new_df_test, left_index=True, right_index=True)\n\n return new_df_train, new_df_test\n\n\ndef xgboost_predict(train, test, xgboost_params={}, map_at_k_K=3):\n\n par = copy.deepcopy(xgboost_params)\n del par['cut_threshold']\n\n y_train = train.place_id.values\n x_train = train.drop('place_id', axis=1).values\n\n if 'place_id' in test.columns:\n x_test = test.drop('place_id', axis=1).values\n else:\n x_test = test.values\n\n clf = xgboost.XGBClassifier(objective='multi:softprob', seed=42,\n nthread=-1,\n **par)\n clf.fit(x_train, y_train)\n predict_y_test = clf.predict_proba(x_test)\n\n # heapq top k algorithm is benchmarked to be slower in this case\n predict_y_test_idx = np.argsort(\n predict_y_test, axis=1)[:, -map_at_k_K:][:, ::-1]\n predicted_test_place_id = clf.classes_.take(predict_y_test_idx)\n\n return test.index.values, predicted_test_place_id\n\n\ndef process_one_cell(df_train, df_test, trainfold, valifold, \n x_min, x_max, y_min, y_max, xgb_params={},\n knn_params={}):\n if np.abs(x_max - size) < 0.001:\n x_max += 1.0e-5\n if np.abs(y_max - size) < 0.001:\n y_max += 1.0e-5\n\n train_in_cell = df_train[(df_train.x >= x_min - x_cell_margin) &\n (df_train.x < x_max + x_cell_margin) &\n (df_train.y >= y_min - y_cell_margin) &\n (df_train.y < y_max + y_cell_margin)\n ]\n\n trainfold_in_cell = trainfold[(trainfold.x >= x_min - x_cell_margin) &\n (trainfold.x < x_max + x_cell_margin) &\n (trainfold.y >= y_min - y_cell_margin) &\n (trainfold.y < y_max + y_cell_margin)\n ]\n\n valifold_in_cell = valifold[(valifold.x >= x_min) &\n (valifold.x < x_max) &\n (valifold.y >= y_min) &\n (valifold.y < y_max)\n ]\n\n test_in_cell = df_test[(df_test.x >= x_min) &\n (df_test.x < x_max) &\n (df_test.y >= y_min) &\n (df_test.y < y_max)\n ]\n\n #train_in_cell, test_in_cell = add_knn_features(train_in_cell, test_in_cell,\n # knn_params)\n #trainfold_in_cell, valifold_in_cell = add_knn_features(\n # trainfold_in_cell, valifold_in_cell,\n # knn_params)\n\n place_counts = train_in_cell.place_id.value_counts()\n mask = (place_counts[train_in_cell.place_id.values]\n >= xgb_params['cut_threshold']).values\n train_in_cell = train_in_cell.loc[mask]\n\n place_counts = trainfold_in_cell.place_id.value_counts()\n mask = (place_counts[trainfold_in_cell.place_id.values]\n >= xgb_params['cut_threshold']).values\n trainfold_in_cell = trainfold_in_cell.loc[mask]\n\n row_id_test, pred_place_id_test = xgboost_predict(\n train_in_cell, test_in_cell, xgboost_params=xgb_params)\n row_id_vali, pred_place_id_vali = xgboost_predict(\n trainfold_in_cell, valifold_in_cell, xgboost_params=xgb_params)\n\n map3 = map_k_precision(valifold_in_cell.place_id.values, pred_place_id_vali)\n print(map3)\n\n N_test = row_id_test.shape[0]\n N_vali = row_id_vali.shape[0]\n\n test_predictions = pd.DataFrame(pred_place_id_test, \n columns='pred1 pred2 pred3'.split(),\n index=row_id_test)\n test_predictions.index.rename('row_id', inplace=True)\n test_predictions['map3'] = map3\n\n vali_predictions = pd.DataFrame(pred_place_id_vali, \n columns='pred1 pred2 pred3'.split(),\n index=row_id_vali)\n vali_predictions.index.rename('row_id', inplace=True)\n vali_predictions['map3'] = map3\n\n print(\"X: [{:.4f},{:.4f}) Y: [{:.4f},{:.4f}) MAP3: {:.4f}\"\n .format(x_min, x_max, y_min, y_max, map3))\n\n return test_predictions, vali_predictions\n\n\ndef iterate_over_grid(train_data, test_data, trainfold, valifold,\n njobs, ijob, bayes):\n if bayes:\n raise NotImplementedError(\"Per bin optimization is not set up.\")\n \n x, y = np.meshgrid(np.arange(NX), np.arange(NY))\n pairs = np.array([x.ravel(), y.ravel()]).T\n pairs = pairs[ijob::njobs]\n\n for (i, j) in pairs:\n print((i,j))\n vali_filename = '{0}/vali_{1:03d}_{2:03d}.csv'.format(RUN_NAME, i, j)\n test_filename = '{0}/test_{1:03d}_{2:03d}.csv'.format(RUN_NAME, i, j)\n\n if os.path.isfile(vali_filename) and os.path.isfile(test_filename):\n continue\n\n x_min, x_max, y_min, y_max = \\\n (i*x_step, (i+1)*x_step, j*y_step, (j+1)*y_step)\n test_pred, vali_pred = process_one_cell(\n train_data, test_data, trainfold, valifold,\n x_min, x_max, y_min, y_max, xgb_params=XGB_PARAMS_USE,\n knn_params=KNN_PARAMS_USE)\n test_pred.to_csv(test_filename, index=True, index_label='row_id')\n vali_pred.to_csv(vali_filename, index=True, index_label='row_id')\n\ndef main():\n\n train_data, test_data, trainfold, valifold = load_data()\n\n for x in (train_data, test_data, trainfold, valifold):\n prepare_data_xgboost(x)\n\n if 'NJOBS' in os.environ:\n njobs = int(os.environ['NJOBS'])\n else:\n njobs = 1\n if 'IJOB' in os.environ:\n ijob = int(os.environ['IJOB'])\n else:\n ijob = 0\n\n if 'BAYES' in os.environ:\n per_bin_optimize = True\n else:\n per_bin_optimize = False\n\n iterate_over_grid(train_data, test_data, trainfold, valifold,\n njobs, ijob, bayes=per_bin_optimize)\n\nif __name__ == '__main__':\n main()\n","sub_path":"L14_xgb.py","file_name":"L14_xgb.py","file_ext":"py","file_size_in_byte":17104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"583772696","text":"\"\"\"A library containing functions for writing a set containing the same channel of different YCbCr images.\"\"\"\n\nimport numpy\nimport os\n\n# The name of the module `Queue` has been changed\n# in Python 3.x .\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\nimport tensorflow as tf\nimport threading\n\nimport hevc.running\nimport sets.common\nimport tools.tools as tls\n\nWIDTH_CROP = 320\n\n# The functions are sorted in alphabetic order.\n\ndef compute_mean_intensities(paths_to_rgbs, queue_threads):\n \"\"\"Computes three mean pixels intensities, each over the same channel of different YCbCr images.\n \n Parameters\n ----------\n paths_to_rgbs : list\n Each string in this list is the path to a RGB image.\n queue_threads\n Queue for storing the returned 1D array with\n data-type `numpy.float64`. The three elements\n in this array are the mean pixels intensities\n computed over the luminance channel, the blue\n chrominance channel and the red chrominance channel\n respectively of different YCbCr images.\n \n \"\"\"\n accumations_float64 = numpy.zeros(3)\n nb_used = 0\n for path_to_rgb in paths_to_rgbs:\n if path_to_rgb.endswith('n02105855_2933.JPEG'):\n continue\n try:\n ycbcr_uint8 = tls.rgb_to_ycbcr(tls.read_image_mode(path_to_rgb, 'RGB'))\n except (TypeError, ValueError):\n continue\n accumations_float64 += numpy.mean(ycbcr_uint8,\n axis=(0, 1))\n nb_used += 1\n queue_threads.put(accumations_float64/nb_used)\n\ndef compute_mean_intensities_threading(paths_to_rgbs, nb_threads):\n \"\"\"Computes three mean pixels intensities, each over the same channel of different YCbCr images, via multi-threading.\n \n Parameters\n ----------\n paths_to_rgbs : list\n Each string in this list is the path to\n a RGB image. If the number of RGB images\n is very small, `nb_threads` must be equal\n to 1. Indeed, if the number of RGB images\n is very small and multi-threading is used,\n there may be imbalance in the number of RGB\n images processed by each thread. This may lead\n to some inaccuracy in the returned mean pixels\n intensities.\n nb_threads : int\n Number of threads.\n \n Returns\n -------\n numpy.ndarray\n 1D array with data-type `numpy.float64`.\n The three elements in this array are the mean\n pixels intensities computed over the luminance\n channel, the blue chrominance channel and the\n red chrominance channel respectively of different\n YCbCr images.\n \n \"\"\"\n nb_paths_to_rgbs = len(paths_to_rgbs)\n nb_rgbs_per_thread = int(numpy.ceil(float(nb_paths_to_rgbs)/nb_threads).item())\n list_threads = []\n coordinator = tf.train.Coordinator()\n \n # The queue collects the array returned by each thread.\n # The keyworded argument `maxsize` is set for safety.\n queue_threads = queue.Queue(maxsize=nb_threads)\n for i in range(nb_threads):\n args = (\n paths_to_rgbs[i*nb_rgbs_per_thread:min(nb_paths_to_rgbs, (i + 1)*nb_rgbs_per_thread)],\n queue_threads\n )\n single_thread = threading.Thread(target=compute_mean_intensities,\n args=args)\n list_threads.append(single_thread)\n single_thread.start()\n coordinator.join(list_threads)\n \n # For each YCbCr image channel separately, the mean\n # pixels intensity is averaged over the different threads.\n accumulations_float64 = numpy.zeros(3)\n for _ in range(nb_threads):\n accumulations_float64 += queue_threads.get()\n return accumulations_float64/nb_threads\n\ndef count_examples_in_files_tfrecord(path_to_directory_threads):\n \"\"\"Counts the total number of examples in several files \".tfrecord\".\n \n Parameters\n ----------\n path_to_directory_threads : str\n Path to the directory whose subdirectories,\n named {\"thread_i\", i = 0 ... `nb_threads` - 1},\n store the files \".tfrecord\".\n \n Returns\n -------\n int\n Total number of examples in the files \".tfrecord\".\n \n \"\"\"\n paths_to_tfrecords = tls.collect_paths_to_files_in_subdirectories(path_to_directory_threads,\n '.tfrecord')\n nb_examples = 0\n for path_to_tfrecord in paths_to_tfrecords:\n for _ in tf.python_io.tf_record_iterator(path_to_tfrecord):\n nb_examples += 1\n return nb_examples\n\ndef create_example_channel_single_or_pair(channel_single_or_pair_uint8):\n \"\"\"Creates a Tensorflow example and fills it with the raw data bytes of the image channel.\n \n Parameters\n ----------\n channel_single_or_pair_uint8 : numpy.ndarray\n 3D array with data-type `numpy.uint8`.\n If `channel_single_or_pair_uint8.shape[2]` is equal\n to 1, `channel_single_or_pair_uint8` is an image channel.\n If `channel_single_or_pair_uint8.shape[2]` is equal to 2,\n `channel_single_or_pair_uint8[:, :, 0:1]` is an image\n channel and `channel_single_or_pair_uint8[:, :, 1:2]`\n is this image channel with HEVC compression artifacts.\n \n Returns\n -------\n tf.train.Example\n Tensorflow example filled with the raw data bytes\n of the image channel.\n \n Raises\n ------\n TypeError\n If `channel_single_or_pair_uint8.dtype` is not equal\n to `numpy.uint8`.\n ValueError\n If `channel_single_or_pair_uint8.ndim` is not equal to 3.\n ValueError\n `channel_single_or_pair_uint8.shape[2]` does not belong\n to {1, 2}.\n \n \"\"\"\n if channel_single_or_pair_uint8.dtype != numpy.uint8:\n raise TypeError('`channel_single_or_pair_uint8.dtype` is not equal to `numpy.uint8`.')\n \n # If the check below did not exist, `create_example_channel_single_or_pair`\n # would not crash if `channel_single_or_pair_uint8.ndim` is strictly larger\n # than 3.\n if channel_single_or_pair_uint8.ndim != 3:\n raise ValueError('`channel_single_or_pair_uint8.ndim` is not equal to 3.')\n if channel_single_or_pair_uint8.shape[2] not in (1, 2):\n raise ValueError('`channel_single_or_pair_uint8.shape[2]` does not belong to {1, 2}.')\n return tf.train.Example(\n features=tf.train.Features(\n feature={\n 'channel_single_or_pair': tf.train.Feature(\n bytes_list=tf.train.BytesList(\n value=[channel_single_or_pair_uint8.tostring()]\n )\n )\n }\n )\n )\n\ndef create_example_context_portions_target(portion_above_uint8, portion_left_uint8, target_uint8):\n \"\"\"Creates a Tensorflow example and fills it with the raw data bytes of the target patch and its two context portions.\n \n Parameters\n ----------\n portion_above_uint8 : numpy.ndarray\n 3D array with data-type `numpy.uint8`.\n Context portion located above the target patch.\n `portion_above_uint8.shape[2]` is equal to 1.\n portion_left_uint8 : numpy.ndarray\n 3D array with data-type `numpy.uint8`.\n Context portion located on the left side of the\n target patch. `portion_left_uint8.shape[2]` is\n equal to 1.\n target_uint8 : numpy.ndarray\n 3D array with data-type `numpy.uint8`.\n Target patch. `target_uint8.shape[2]` is equal to 1.\n \n Returns\n -------\n tf.train.Example\n Tensorflow example filled with the raw data bytes\n of the target patch and its two context portions.\n \n Raises\n ------\n TypeError\n If `portion_above_uint8.dtype` is not equal to `numpy.uint8`.\n TypeError\n If `portion_left_uint8.dtype` is not equal to `numpy.uint8`.\n TypeError\n If `target_uint8.dtype` is not equal to `numpy.uint8`.\n \n \"\"\"\n if portion_above_uint8.dtype != numpy.uint8:\n raise TypeError('`portion_above_uint8.dtype` is not equal to `numpy.uint8`.')\n if portion_left_uint8.dtype != numpy.uint8:\n raise TypeError('`portion_left_uint8.dtype` is not equal to `numpy.uint8`.')\n if target_uint8.dtype != numpy.uint8:\n raise TypeError('`target_uint8.dtype` is not equal to `numpy.uint8`.')\n return tf.train.Example(\n features=tf.train.Features(\n feature={\n 'portion_above': tf.train.Feature(\n bytes_list=tf.train.BytesList(\n value=[portion_above_uint8.tostring()]\n )\n ),\n 'portion_left': tf.train.Feature(\n bytes_list=tf.train.BytesList(\n value=[portion_left_uint8.tostring()]\n )\n ),\n 'target': tf.train.Feature(\n bytes_list=tf.train.BytesList(\n value=[target_uint8.tostring()]\n )\n )\n }\n )\n )\n\ndef create_tfrecord(path_to_tfrecord, paths_to_rgbs, width_target, index_channel, dict_pair):\n \"\"\"Creates a file \".tfrecord\" and fills it with raw data bytes.\n \n For each RGB image, the RGB image is read, converted\n into YCbCr, and randomly cropped.\n If `width_target` is None, if `dict_pair` is None, the\n file \".tfrecord\" is filled with the raw data bytes of the\n same channel from each YCbCr image. If `dict_pair` is not\n None, the file \".tfrecord\" is filled with the raw data bytes\n of the same channel from each YCbCr image and this channel\n with HEVC compression artifacts.\n If `width_target` is not None, several target patches, each\n paired with its two context portions, are randomly extracted\n from the same channel from each YCbCr image. Then, the file\n \".tfrecord\" is filled with the raw data bytes of each target\n patch and its two context portions. If `dict_pair` is not\n None, the context portions have HEVC compression artifacts.\n \n Parameters\n ----------\n path_to_tfrecord : str\n Path to the file \".tfrecord\".\n paths_to_rgbs : list\n Each string in this list is the path to a RGB image.\n width_target : either int or None\n Width of the target patch.\n index_channel : int\n Channel index. 0 means the luminance channel.\n 1 and 2 mean respectively the blue chrominance\n and the red chrominance channels.\n dict_pair : either dict or None.\n path_to_before_encoding_hevc : str\n Path to the file storing an image before the\n encoding via HEVC. `path_to_before_encoding_hevc`\n ends with \".yuv\".\n path_to_after_encoding_hevc : str\n Path to the file storing the reconstructed image\n after the encoding via HEVC. `path_to_after_encoding_hevc`\n ends with \".yuv\".\n path_to_cfg : str\n Path to the configuration file. `path_to_cfg` ends with \".cfg\".\n path_to_bitstream : str\n Path to the bitstream file. `path_to_bitstream` ends with \".bin\".\n path_to_exe_encoder : str\n Path to the executable of the HEVC encoder.\n qps_int : numpy.ndarray\n 1D array whose data-type is smaller than `numpy.integer`\n in type hierarchy.\n Quantization parameters. The quantization parameter\n for encoding an image via HEVC is uniformly drawn from\n this array.\n \n Raises\n ------\n ValueError\n If `index_channel` does not belong to {0, 1, 2}.\n IOError\n If a file at `path_to_tfrecord` already exists.\n \n \"\"\"\n if index_channel not in (0, 1, 2):\n raise ValueError('`index_channel` does not belong to {0, 1, 2}.')\n if os.path.isfile(path_to_tfrecord):\n raise IOError('\"{}\" already exists. A file \".tfrecord\" cannot be overwritten.'.format(path_to_tfrecord))\n with tf.python_io.TFRecordWriter(path_to_tfrecord) as file:\n for path_to_rgb in paths_to_rgbs:\n \n # The image named \"n02105855_2933.JPEG\" in the ILSVRC2012 training\n # set is PNG, although its extension is not \".png\".\n if path_to_rgb.endswith('n02105855_2933.JPEG'):\n continue\n try:\n ycbcr_uint8 = tls.rgb_to_ycbcr(tls.read_image_mode(path_to_rgb, 'RGB'))\n except (TypeError, ValueError):\n continue\n \n # If `width_target` is None, `image_before_encoding_hevc_uint8.shape[0]`\n # and `image_before_encoding_hevc_uint8.shape[1]` have to be equal to \n # `WIDTH_CROP`. Note that HEVC only encodes images whose height\n # and width are divisible by the minimum CU size, i.e 8 pixels.\n # Therefore, `WIDTH_CROP` has to be divisible by 8.\n # Otherwise, `image_before_encoding_hevc_uint8.shape[0]` and\n # `image_before_encoding_hevc_uint8.shape[1]` have to be divisible\n # by 8 and be larger than `3*width_target`.\n if width_target is None:\n try:\n \n # If `ycbcr_uint8.shape[0]` is strictly smaller\n # than `WIDTH_CROP`, `numpy.random.choice` raises a\n # `ValueError` exception.\n row_start = numpy.random.choice(ycbcr_uint8.shape[0] - WIDTH_CROP + 1)\n \n # If `ycbcr_uint8.shape[1]` is strictly smaller than\n # `WIDTH_CROP`, `numpy.random.choice` raises a `ValueError`\n # exception.\n col_start = numpy.random.choice(ycbcr_uint8.shape[1] - WIDTH_CROP + 1)\n except ValueError:\n continue\n image_before_encoding_hevc_uint8 = ycbcr_uint8[row_start:row_start + WIDTH_CROP, col_start:col_start + WIDTH_CROP, :]\n else:\n height_divisible_by_8 = 8*(ycbcr_uint8.shape[0]//8)\n width_divisible_by_8 = 8*(ycbcr_uint8.shape[1]//8)\n try:\n \n # If `height_divisible_by_8` is strictly smaller than\n # `3*width_target`, `numpy.random.randint` raises a\n # `ValueError` exception.\n # 10 target patches, each paired with its two context\n # portions, are extracted from each YCbCr image.\n row_1sts = numpy.random.randint(0,\n high=height_divisible_by_8 - 3*width_target + 1,\n size=10)\n \n # If `width_divisible_by_8` is strictly smaller than\n # `3*width_target`, `numpy.random.randint` raises a\n # `ValueError` exception.\n col_1sts = numpy.random.randint(0,\n high=width_divisible_by_8 - 3*width_target + 1,\n size=10)\n except ValueError:\n continue\n image_before_encoding_hevc_uint8 = ycbcr_uint8[0:height_divisible_by_8, 0:width_divisible_by_8, :]\n if dict_pair is None:\n channel_single_or_pair_uint8 = image_before_encoding_hevc_uint8[:, :, index_channel:index_channel + 1]\n else:\n qp = numpy.random.choice(dict_pair['qps_int']).item()\n reconstructed_image_after_encoding_hevc_uint8 = hevc.running.encode_image(image_before_encoding_hevc_uint8,\n dict_pair['path_to_before_encoding_hevc'],\n dict_pair['path_to_after_encoding_hevc'],\n dict_pair['path_to_cfg'],\n dict_pair['path_to_bitstream'],\n dict_pair['path_to_exe_encoder'],\n qp,\n None)\n \n # The channel extraction is done after the encoding\n # of the YCbCr image via HEVC.\n tuple_before_after = (\n image_before_encoding_hevc_uint8[:, :, index_channel:index_channel + 1],\n reconstructed_image_after_encoding_hevc_uint8[:, :, index_channel:index_channel + 1]\n )\n channel_single_or_pair_uint8 = numpy.concatenate(tuple_before_after,\n axis=2)\n if width_target is None:\n write_channel_single_or_pair(channel_single_or_pair_uint8,\n file)\n else:\n extract_context_portions_targets_plus_writing(channel_single_or_pair_uint8,\n width_target,\n row_1sts,\n col_1sts,\n file)\n\ndef create_tfrecord_batch(path_to_directory_tfrecords, paths_to_rgbs, width_target, index_channel,\n nb_rgbs_per_tfrecord, dict_pair):\n \"\"\"Creates a batch of files \".tfrecord\" and fills the files with raw data bytes.\n \n Parameters\n ----------\n path_to_directory_tfrecords : str\n Path to the directory in which the files\n \".tfrecord\" are saved.\n paths_to_rgbs : list\n Each string in this list is the path to a RGB image.\n width_target : either int or None\n Width of the target patch.\n index_channel : int\n Channel index. 0 means the luminance channel.\n 1 and 2 mean respectively the blue chrominance\n and the red chrominance channels.\n nb_rgbs_per_tfrecord : int\n Maximum number of RGB images that are\n preprocessed to fill a file \".tfrecord\".\n dict_pair : either dict or None.\n path_to_before_encoding_hevc : str\n Path to the file storing an image before the encoding\n via HEVC. `path_to_before_encoding_hevc` ends with \".yuv\".\n path_to_after_encoding_hevc : str\n Path to the file storing the reconstructed image after\n the encoding via HEVC. `path_to_after_encoding_hevc` ends\n with \".yuv\".\n path_to_cfg : str\n Path to the configuration file. `path_to_cfg` ends with \".cfg\".\n path_to_bitstream : str\n Path to the bitstream file. `path_to_bitstream` ends with \".bin\".\n path_to_exe_encoder : str\n Path to the executable of the HEVC encoder.\n qps_int : numpy.ndarray\n 1D array whose data-type is smaller than `numpy.integer`\n in type hierarchy.\n Quantization parameters. The quantization parameter\n for encoding an image via HEVC is uniformly drawn from\n this array.\n \n \"\"\"\n nb_paths_to_rgbs = len(paths_to_rgbs)\n \n # In Python 2.x, the standard division between two\n # integers returns an integer whereas, in Python 3.x,\n # the standard division between two integers returns\n # a float.\n nb_tfrecords = int(numpy.ceil(float(nb_paths_to_rgbs)/nb_rgbs_per_tfrecord).item())\n for i in range(nb_tfrecords):\n path_to_tfrecord = os.path.join(path_to_directory_tfrecords, 'data_{}.tfrecord'.format(i))\n create_tfrecord(path_to_tfrecord,\n paths_to_rgbs[i*nb_rgbs_per_tfrecord:min(nb_paths_to_rgbs, (i + 1)*nb_rgbs_per_tfrecord)],\n width_target,\n index_channel,\n dict_pair)\n\ndef create_tfrecord_threading(paths_to_directories_tfrecords, paths_to_rgbs, width_target, index_channel,\n nb_rgbs_per_tfrecord, dict_pair_threads):\n \"\"\"Creates several batches of files \".tfrecord\", each batch being handled by a thread.\n \n Parameters\n ----------\n paths_to_directories_tfrecords : list\n Each string in this list is the path to a thread\n directory storing files \".tfrecord\".\n paths_to_rgbs : list\n Each string in this list is the path to a RGB image.\n width_target : either int or None\n Width of the target patch.\n index_channel : int\n Channel index. 0 means the luminance channel.\n 1 and 2 mean respectively the blue chrominance\n and the red chrominance channels.\n nb_rgbs_per_tfrecord : int\n Maximum number of RGB images that are\n preprocessed to fill a file \".tfrecord\".\n dict_pair_threads : either dict or None.\n paths_to_before_encoding_hevc : list\n `paths_to_before_encoding_hevc[i]` is the path to\n the file storing an image before the encoding via\n HEVC for the thread of index i. Each path ends with\n \".yuv\".\n paths_to_after_encoding_hevc : list\n `paths_to_after_encoding_hevc[i]` is the path to the\n file storing the reconstructed image after the encoding\n via HEVC for the thread of index i. Each path ends with\n \".yuv\".\n path_to_cfg : str\n Path to the configuration file. `path_to_cfg` ends with \".cfg\".\n paths_to_bitstream : list\n `paths_to_bitstream[i]` is the path to the bitstream file\n for the thread of index i. Each path ends with \".bin\".\n path_to_exe_encoder : str\n Path to the executable of the HEVC encoder.\n qps_int : numpy.ndarray\n 1D array whose data-type is smaller than `numpy.integer`\n in type hierarchy.\n Quantization parameters. The quantization parameter for\n encoding an image via HEVC is uniformly drawn from this\n array.\n \n \"\"\"\n nb_threads = len(paths_to_directories_tfrecords)\n nb_paths_to_rgbs = len(paths_to_rgbs)\n nb_rgbs_per_thread = int(numpy.ceil(float(nb_paths_to_rgbs)/nb_threads).item())\n list_threads = []\n coordinator = tf.train.Coordinator()\n for i in range(nb_threads):\n \n # If `dict_pair_threads` is None, `dict_pair` is None too.\n if dict_pair_threads is None:\n dict_pair = None\n else:\n dict_pair = {\n 'path_to_before_encoding_hevc': dict_pair_threads['paths_to_before_encoding_hevc'][i],\n 'path_to_after_encoding_hevc': dict_pair_threads['paths_to_after_encoding_hevc'][i],\n 'path_to_cfg': dict_pair_threads['path_to_cfg'],\n 'path_to_bitstream': dict_pair_threads['paths_to_bitstream'][i],\n 'path_to_exe_encoder': dict_pair_threads['path_to_exe_encoder'],\n 'qps_int': dict_pair_threads['qps_int']\n }\n args = (\n paths_to_directories_tfrecords[i],\n paths_to_rgbs[i*nb_rgbs_per_thread:min(nb_paths_to_rgbs, (i + 1)*nb_rgbs_per_thread)],\n width_target,\n index_channel,\n nb_rgbs_per_tfrecord,\n dict_pair\n )\n single_thread = threading.Thread(target=create_tfrecord_batch,\n args=args)\n list_threads.append(single_thread)\n \n # `threading.Thread.start` calls `threading.Thread.run`\n # in a separate thread of control.\n single_thread.start()\n \n # If a thread raises an exception,\n # the coordinator blocks it until\n # the other threads finish their task.\n coordinator.join(list_threads)\n\ndef create_training_subset(paths_to_rgbs, path_to_training_subset, nb_examples):\n \"\"\"Creates a subset of the set of YCbCr images that was used for creating a training set.\n \n Parameters\n ----------\n paths_to_rgbs : list\n Each string in this list is the path to a RGB image.\n path_to_training_subset : str\n Path to the file in which the training\n subset is saved. The path ends with \".npy\".\n nb_examples : int\n Number of YCbCr images in the training subset.\n \n Raises\n ------\n RuntimeError\n If the training subset is not filled with `nb_examples`\n YCbCr images.\n \n \"\"\"\n if os.path.isfile(path_to_training_subset):\n print('\"{}\" already exists.'.format(path_to_training_subset))\n else:\n ycbcrs_uint8 = numpy.zeros((nb_examples, WIDTH_CROP, WIDTH_CROP, 3),\n dtype=numpy.uint8)\n i = 0\n for path_to_rgb in paths_to_rgbs:\n if path_to_rgb.endswith('n02105855_2933.JPEG'):\n continue\n try:\n ycbcr_uint8 = tls.rgb_to_ycbcr(tls.read_image_mode(path_to_rgb, 'RGB'))\n except (TypeError, ValueError):\n continue\n if ycbcr_uint8.shape[0] < WIDTH_CROP or ycbcr_uint8.shape[1] < WIDTH_CROP:\n continue\n ycbcrs_uint8[i, :, :, :] = ycbcr_uint8[0:WIDTH_CROP, 0:WIDTH_CROP, :]\n i += 1\n if i == nb_examples:\n break\n \n # If `i` is strictly smaller than `nb_examples`,\n # at least one YCbCr image in the training subset\n # is filled with 0s.\n if i != nb_examples:\n raise RuntimeError('The training subset is not filled with {} YCbCr images.'.format(nb_examples))\n numpy.save(path_to_training_subset,\n ycbcrs_uint8)\n\ndef extract_context_portions_targets_plus_writing(channel_single_or_pair_uint8, width_target, row_1sts, col_1sts, file):\n \"\"\"Extracts several target patches, each paired with its two context portions, from the image channel and writes them to the file \".tfrecord\".\n \n Parameters\n ----------\n channel_single_or_pair_uint8 : numpy.ndarray\n 3D array with data-type `numpy.uint8`.\n If `channel_single_or_pair_uint8.shape[2]` is equal\n to 1, `channel_single_or_pair_uint8` is an image channel.\n If `channel_single_or_pair_uint8.shape[2]` is equal to 2,\n `channel_single_or_pair_uint8[:, :, 0:1]` is an image\n channel and `channel_single_or_pair_uint8[:, :, 1:2]`\n is this image channel with HEVC compression artifacts.\n width_target : int\n Width of the target patch.\n row_1sts : numpy.ndarray\n 1D array whose data-type is smaller than `numpy.integer`\n in type hierarchy.\n `row_1sts[i]` is the row in the image channel of the 1st\n pixel of the context portion located above the target patch\n of index i.\n col_1sts : numpy.ndarray\n 1D array whose data-type is smaller than `numpy.integer`\n in type hierarchy.\n `col_1sts[i]` is the column in the image channel of the 1st\n pixel of the context portion located above the target patch\n of index i.\n file : TFRecordWriter\n File to which each target patch and its two context portions\n are written.\n \n \"\"\"\n (portions_above_uint8, portions_left_uint8, targets_uint8) = \\\n sets.common.extract_context_portions_targets_from_channel_numpy(channel_single_or_pair_uint8,\n width_target,\n row_1sts,\n col_1sts)\n write_context_portions_targets(portions_above_uint8,\n portions_left_uint8,\n targets_uint8,\n file)\n\ndef write_channel_single_or_pair(channel_single_or_pair_uint8, file):\n \"\"\"Writes the image channel to the file \".tfrecord\".\n \n Parameters\n ----------\n channel_single_or_pair_uint8 : numpy.ndarray\n 3D array with data-type `numpy.uint8`.\n If `channel_single_or_pair_uint8.shape[2]` is equal\n to 1, `channel_single_or_pair_uint8` is an image channel.\n If `channel_single_or_pair_uint8.shape[2]` is equal to 2,\n `channel_single_or_pair_uint8[:, :, 0:1]` is an image\n channel and `channel_single_or_pair_uint8[:, :, 1:2]`\n is this image channel with HEVC compression artifacts.\n file : TFRecordWriter\n File to which the image channel is written.\n \n \"\"\"\n example = create_example_channel_single_or_pair(channel_single_or_pair_uint8)\n file.write(example.SerializeToString())\n\ndef write_context_portions_targets(portions_above_uint8, portions_left_uint8, targets_uint8, file):\n \"\"\"Writes each target patch and its two context portions to the file \".tfrecord\".\n \n WARNING! For computation efficiency, the shape of each\n array in the function arguments is not checked.\n \n Parameters\n ----------\n portions_above_uint8 : numpy.ndarray\n 4D array with data-type `numpy.uint8`.\n Context portions, each being located above\n a different target patch. `portions_above_uint8[i, :, :, :]`\n is the context portion located above the\n target patch of index i. `portions_above_uint8.shape[3]`\n is equal to 1.\n portions_left_uint8 : numpy.ndarray\n 4D array with data-type `numpy.uint8`.\n Context portions, each being located on the\n left side of a different target patch. `portions_left_uint8[i, :, :, :]`\n is the context portion located on the left side\n of the target patch of index i. `portions_left_uint8.shape[3]`\n is equal to 1.\n targets_uint8 : numpy.ndarray\n 4D array with data-type `numpy.uint8`.\n Target patches. `targets_uint8[i, :, :, :]` is\n the target patch of index i. `target_uint8.shape[3]`\n is equal to 1.\n file : TFRecordWriter\n File to which each target patch and its two context\n portions are written.\n \n \"\"\"\n for i in range(targets_uint8.shape[0]):\n example = create_example_context_portions_target(portions_above_uint8[i, :, :, :],\n portions_left_uint8[i, :, :, :],\n targets_uint8[i, :, :, :])\n file.write(example.SerializeToString())\n\n\n","sub_path":"sets/writing.py","file_name":"writing.py","file_ext":"py","file_size_in_byte":30696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"109460712","text":"from collections import defaultdict, OrderedDict\nfrom datetime import datetime\nfrom locale import atof\n\nfrom se_challenge import PERMITTED_FILE_EXTENSION\n\n\ndef check_file_extension(filename):\n \"\"\"Method checks for filename extension (must end with '.csv').\"\"\"\n return filename.lower().endswith(\".{}\".format(PERMITTED_FILE_EXTENSION))\n\n\ndef process_expenses(csv_frame):\n \"\"\"Method processes a CSV data-frame to calculate expenses. Adds total amounts,\n and couples that total per date of expense.\"\"\"\n total_tax = []\n columns = csv_frame.pretax_amount.values, csv_frame.tax_amount.values, csv_frame.date.values\n for pretax_amount, tax_amount, date in zip(*columns):\n pretax_amount_sanitized = atof(pretax_amount) if isinstance(pretax_amount, basestring) else pretax_amount\n tax_amount_sanitized = atof(tax_amount) if isinstance(tax_amount, basestring) else tax_amount\n total_amount = pretax_amount_sanitized + tax_amount_sanitized\n total_tax.append((date, total_amount)) # List of tuple pairs (date -> total expense).\n return sort_expenses(total_tax)\n\n\ndef sort_expenses(date_expense):\n \"\"\"Sorts expenses according to date spent. This method also groups expense by Month/Year\n instead of the exact date in which the expenses are recorded.\"\"\"\n expenses = defaultdict(int) # Expenses dictionary -> date : expense.\n for entry in date_expense:\n unformatted_date = entry[0]\n expense = entry[1]\n date_obj = datetime.strptime(unformatted_date, '%m/%d/%Y')\n date = date_obj.strftime('%B/%Y')\n expenses[date] += expense\n sorted_expenses = OrderedDict(sorted(expenses.items(), key=lambda d: datetime.strptime(d[0], '%B/%Y')))\n return sorted_expenses","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"136522595","text":"from pgdrive.envs.pgdrive_env_v2 import PGDriveEnvV2\nfrom pgdrive.tests.test_env.test_pgdrive_env import _act\n\n\ndef test_pgdrive_env_v2():\n env = PGDriveEnvV2()\n assert env.observation_space.shape[0] == 120 + 19\n try:\n obs = env.reset()\n assert env.observation_space.contains(obs)\n _act(env, env.action_space.sample())\n for x in [-1, 0, 1]:\n env.reset()\n for y in [-1, 0, 1]:\n _act(env, [x, y])\n finally:\n env.close()\n\n\nif __name__ == '__main__':\n test_pgdrive_env_v2()\n","sub_path":"pgdrive/tests/test_env/test_pgdrive_env_v2.py","file_name":"test_pgdrive_env_v2.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"400397846","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\n Django settings for tap project.\n \n Generated by 'django-admin startproject' using Django 1.9.7.\n \n For more information on this file, see\n https://docs.djangoproject.com/en/1.9/topics/settings/\n \n For the full list of settings and their values, see\n https://docs.djangoproject.com/en/1.9/ref/settings/\n \"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nfrom secret import *\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = MY_SECRET_KEY\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = ['*']\n\nSITE_ROOT = os.path.realpath(os.path.dirname(os.path.dirname(__file__)))\n\nSITE_ID = 1\n\n# Email integration setup\nEMAIL_USE_TLS = True\nEMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'\nEMAIL_PORT = 587\nEMAIL_HOST_USER = 'AKIAJJDM2ZC67STGF4IA'\nEMAIL_HOST_PASSWORD = MY_EMAIL_PASSWORD\n\n# Configurable email addresses\n# These are addresses where mail is sent from...\nEMAIL_FROM_NOMINAL_ADDRESS = \"onlinetesting@xdataonline.com\"\nEMAIL_FROM_ERROR_ADDRESS = \"no-reply@xdataonline.com\"\n# These are addresses used to send mail to...\nEMAIL_TO_ERROR_ADDRESS = \"errors@xdataonline.com\"\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'grappelli', # must be before django.contrib.admin\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.sites',\n 'django.contrib.staticfiles',\n 'custom_user',\n 'app_mgr',\n 'axes',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'guardian',\n 'webpack_loader',\n )\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'tap.middleware.DisableCSRF',\n )\n\nROOT_URLCONF = 'tap.urls'\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'guardian.backends.ObjectPermissionBackend',\n )\nGUARDIAN_MONKEY_PATCH = False\n\nAUTH_USER_MODEL = 'app_mgr.UserProfile'\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n )\n}\nLOGIN_REDIRECT_URL = '/app_mgr/users'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(SITE_ROOT, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n ]\n\nWSGI_APPLICATION = 'tap.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.9/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': MY_DB_NAME,\n 'USER': MY_DB_USER,\n 'PASSWORD': MY_DB_PASSWORD,\n 'HOST': MY_DB_HOST,\n 'PORT': '',\n}\n}\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.8/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'America/New_York'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n#STATIC_ROOT = os.path.join(BASE_DIR, '../static')\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, '../static'),\n ]\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'NOTSET',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose'\n }\n},\n 'loggers': {\n '': {\n 'handlers': ['console'],\n 'level': 'NOTSET',\n },\n 'django.request': {\n 'handlers': ['console'],\n 'propagate': False,\n 'level': 'ERROR'\n }\n}\n}\n","sub_path":"tap/settings/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"103948158","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom pb_app import views\nfrom registration.backends.simple.views import RegistrationView\n\n# This class redirects the user to the index page after account creation/login\nclass MyRegistrationView(RegistrationView):\n def get_success_url(self, user):\n return '/'\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^accounts/', include('registration.backends.simple.urls')),\n url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),\n url(r'^$', views.index, name='index'),\n url(r'^index/$', views.index, name='index'),\n url(r'^paste/', views.paste, name='paste'), #login_required\n url(r'^mypastes/', views.paste_list, name='my_pastes'),\n]\n\n\"\"\"\nDjango Registration Redux Urls\n\n registration: '/accounts/register/' -- 'registration_register'\n registration complete: '/accounts/register/complete/'\n login: '/accounts/login/' -- 'auth_login'\n logout: '/accounts/logout/' -- 'auth_logout'\n password change: '/password/change/'\n password reset: '/password/reset/'\n\"\"\"\n","sub_path":"pb_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"149795647","text":"#! /usr/bin/env python\n# -*-coding:utf-8 -*-\n# Author:Monkey\n\nimport pickle,os,sys\nConf_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(Conf_dir)\n\n\ndef check_file(file,init_str=[]):\n if not os.path.isfile(file):\n fdata = open(file, 'wb')\n pickle.dump(init_str, fdata)\n fdata.close()\n\ndef get_data(file,init_str=[]):\n check_file(file,init_str)\n fdata = open(file,'rb')\n product_list = pickle.load(fdata)\n fdata.close()\n return product_list\n\ndef save_data(data,file):\n fdata = open(file,'wb')\n pickle.dump(data,fdata)\n fdata.close()\n\nif __name__ == '__main__':\n from config.setting import porduct_list_name\n get_data(porduct_list_name)\n save_data([1,21],porduct_list_name)","sub_path":"day4/worker/Bank/core/data_drive.py","file_name":"data_drive.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"462552342","text":"# Приветствие с опциями\nfrom tkinter import *\n\n# Константы текста\nAnswer = [\"Супер\", \"Хорошо\", \"Так себе\", \"Плохо\", \"Ужасно\", \"Не скажу\"]\nDiagnose = [\"Это здорово!\", \"Это радует!\", \"Все возможно.\", \\\n \"Это огорчает!\", \"Это плохо!\", \"Раз ты так думаешь ...\"]\n\n# Функция события\ndef buttonClick() :\n Display.config(text=Diagnose[Nummer.get()])\n\n# Основная программа\nWindow = Tk()\nWindow.title(\"Привет!\")\nWindow.minsize(width=260, height=260)\nDisplay = Label(Window, text=\"Как это сделать?\")\nDisplay.pack()\n\n# Вспомогательная переменная\nNummer = IntVar()\nNummer.set(-1)\n\n# Опции\nOption = []\nfor Nr in range(0,6) :\n Option.append(Radiobutton(Window, variable=Nummer, value=Nr, text=Answer[Nr]))\n Option[Nr].config(command=buttonClick)\n Option[Nr].pack(anchor=\"w\")\n\n# Цикл событий\nWindow.mainloop()\n\n","sub_path":"python_for_kids/book/Projects/hallo6.py","file_name":"hallo6.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"9592704","text":"#encoding:utf-8\n__author__ = 'zy'\nimport redis,csv\nimport MySQLdb\nimport settings\nr = redis.Redis(host='192.168.32.116',port=6378,db=0)\ncompare= {'zhejiang':'浙江',\n 'jiangsu':'江苏',\n 'shanghai':'上海',\n 'beijing':'北京',\n 'tianjin':'天津',\n 'shandong':'山东',\n 'hebei':'河北',\n 'henan':'河南',\n 'jilin':'吉林',\n 'liaoning':'辽宁',\n 'heilongjiang':'黑龙江',\n 'neimenggu':'内蒙古',\n 'ningxia':'宁夏',\n 'hunan':'湖南',\n 'hubei':'湖北',\n 'chongqin':'重庆',\n 'sichuan':'四川',\n 'guizhou':'贵州',\n 'yunnan':'云南',\n 'guangxi':'广西',\n 'guangdong':'广东',\n 'fujian':'福建',\n 'jiangxi':'江西',\n 'anhui':'安徽',\n 'qinghai':'青海',\n 'xizang':'西藏',\n 'xinjiang':'新疆',\n 'hainan':'海南',\n 'shanxi':'山西',\n 'gansu':'甘肃',\n 'shan3xi':'陕西'\n }\ndb=MySQLdb.connect(host=\"192.168.35.232\",user=\"reader\",passwd=\"UC1uRSeZ\",db=\"seed\",charset=\"utf8\")\ncursor = db.cursor()\nsql = \"select open_id,mobile from user where create_time <= '%s';\" % settings.DEFAULT_TIME\ncursor.execute(sql)\nresult = []\nmobiles = []\nwhile 1:\n data = cursor.fetchone()\n if data != None:\n if data[1] != '':\n result.append([data[0],data[1]])\n mobiles.append(data[1][:7])\n else:\n result.append([data[0],''])\n mobiles.append('')\n else:\n break\nwheres = r.mget(mobiles)\nfor i in xrange(len(wheres)):\n try:\n result[i].append(compare[wheres[i]])\n except:\n result[i].append('')\n\n\nwriter = csv.writer(file(settings.USER_INFO_FILE,'wb'))\nfor line in result:\n writer.writerow(line)\n","sub_path":"seed/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"18587588","text":"import itertools\nimport numpy as np\nfrom random import shuffle\nfrom typing import Tuple, Optional, List, Dict, Any\n\nfrom snc.agents.hedgehog.strategic_idling.compute_dual_effective_cost \\\n import ComputeDualEffectiveCost\nfrom snc.agents.hedgehog.strategic_idling.strategic_idling import StrategicIdlingCore, \\\n StrategicIdlingOutput\nfrom snc.agents.hedgehog.params import StrategicIdlingParams\nfrom snc.agents.hedgehog.strategic_idling.strategic_idling_utils import is_pull_model\nfrom snc.agents.solver_names import SolverNames\nfrom snc.utils.exceptions import e_assert\nimport snc.utils.exceptions as exceptions\nfrom snc.utils.snc_types import StateSpace, WorkloadSpace\nimport snc.utils.snc_types as types\n\n\nclass StrategicIdlingHedging(StrategicIdlingCore):\n\n def __init__(self,\n workload_mat: types.WorkloadMatrix,\n neg_log_discount_factor: float,\n load: WorkloadSpace,\n cost_per_buffer: types.StateSpace,\n model_type: str,\n strategic_idling_params: Optional[StrategicIdlingParams] = None,\n workload_cov: Optional[types.WorkloadCov] = None,\n debug_info: bool = False) -> None:\n \"\"\"\n StrategicIdling class is responsible for online identification of idling directions for\n bottlenecks to reduce effective running cost in the network.\n\n :param workload_mat: workload matrix, with rows being workload vectors.\n :param neg_log_discount_factor: negative log of the discount factor given by environment.\n :param load: vector with loads for every workload vector.\n :param cost_per_buffer: cost per unit of inventory per buffer.\n :param model_type: String indicating if this is a `'pull'` or `'push'` model.\n :param strategic_idling_params: tolerance levels, convex solver and other params\n for navigating effective cost space.\n :param workload_cov: asymptotic covariance of the workload process.\n :param debug_info: Boolean flag that indicates whether printing useful debug info.\n \"\"\"\n super().__init__(workload_mat, load, cost_per_buffer, model_type,\n strategic_idling_params, debug_info)\n self._workload_cov = workload_cov\n self._neg_log_discount_factor = neg_log_discount_factor\n\n self.check_strategic_idling_parameters(strategic_idling_params)\n self.strategic_idling_params = strategic_idling_params\n\n self._psi_plus_cone_list: Optional[List[WorkloadSpace]] = None\n self._beta_star_cone_list: Optional[List[float]] = None\n\n # Create linear programs that will be used at each iteration.\n convex_solver = strategic_idling_params.convex_solver\n self.c_minus_solver = ComputeDualEffectiveCost(workload_mat, cost_per_buffer, convex_solver)\n self.c_plus_solver = ComputeDualEffectiveCost(workload_mat, cost_per_buffer, convex_solver)\n\n if workload_cov is not None:\n self.update_workload_cov(workload_cov)\n\n @property\n def psi_plus_cone_list(self):\n return self._psi_plus_cone_list\n\n @property\n def beta_star_cone_list(self):\n return self._beta_star_cone_list\n\n @staticmethod\n def check_strategic_idling_parameters(strategic_idling_params):\n assert strategic_idling_params is not None\n assert strategic_idling_params.convex_solver in SolverNames.CVX, \\\n f'Convex solver {strategic_idling_params.convex_solver} is not valid. ' \\\n f'It must be one of these options: {SolverNames.CVX}.'\n assert strategic_idling_params.epsilon >= 0, \\\n f'epsilon parameter to create the artificial cone when monotone region is empty must ' \\\n f'be nonnegative: {strategic_idling_params.epsilon}.'\n assert strategic_idling_params.shift_eps >= 0, \\\n f'shift_eps parameter to compute distance around w_star when obtaining the level sets' \\\n f'that define the monotone region must be nonnegative: ' \\\n f'{strategic_idling_params.shift_eps}.'\n assert strategic_idling_params.penalty_coeff_w_star >= 0, \\\n 'Penalty coefficient used to ensure w_star close to the lower boundary of the ' \\\n f'monotone region must be nonnegative: .'\n assert strategic_idling_params.hedging_scaling_factor >= 0, \\\n 'Scaling factor to multiply the hedging threshold resulting from the diffusion ' \\\n f'heuristic must be nonnegative: {strategic_idling_params.penalty_coeff_w_star}. '\n\n def update_workload_cov(self, workload_cov: Optional[types.WorkloadCov] = None) -> None:\n self._workload_cov = workload_cov\n self._compute_cone_envelope()\n\n def _compute_cone_envelope(self, max_points: Optional[int] = 200) -> None:\n \"\"\"\n Pre-computes a conservative envelope of the monotone region of the effective cost cone. This\n cone envelope is only used to have an idea of the hedging threshold when the current\n workload is in the negative quadrant. The cone envelope has as many faces as dimensions on\n the workload space. This function returns the normal vector and the hedging threshold for\n each face of the cone envelope.\n\n :param max_points: Maximum number of points to compute the cone envelope.\n \"\"\"\n assert max_points is None or (isinstance(max_points, int) and max_points > 0)\n\n self._psi_plus_cone_list = []\n self._beta_star_cone_list = []\n\n if not is_pull_model(self.model_type):\n return\n\n w_list = self._build_workloads_for_computing_cone_envelope(self._workload_mat,\n max_points=max_points)\n for w in w_list:\n # Update `psi_plus_cone_list` and `beta_star_cone_list` inside `standard_hedging`.\n if not self._is_negative_orthant(w) or self._is_1d_workload_relaxation(w):\n output = self._non_negative_workloads(w)\n if not self._is_decision_not_to_idle(output['k_idling_set']):\n _ = self._add_standard_hedging(w, output)\n\n assert self.psi_plus_cone_list and self.beta_star_cone_list\n\n @staticmethod\n def _compute_height_process(w: WorkloadSpace, psi_plus: WorkloadSpace) -> np.ndarray:\n \"\"\"\n One way of infering height process using the psi_plus vector. Height process is\n one particular system state observable instrumental to idling decision.\n\n :param w: current state in workload space, i.e. w = Xi @ x.\n :param psi_plus: vector normal to the closest face.\n \"\"\"\n assert psi_plus is not None\n assert w is not None\n return np.squeeze(-(psi_plus.T @ w))\n\n @staticmethod\n def _get_height_process_statistics(psi_plus: WorkloadSpace, workload_cov: types.WorkloadCov,\n load: types.WorkloadSpace) -> Tuple[float, float]:\n \"\"\"\n Obtain drift and variance of the (asymptotically large workload) 1-dim \"height\" process\n along the \"reflection\" direction on the closest face (to the current state in workload\n space).\n\n :param psi_plus: vector normal to the closest face.\n :param workload_cov: asymptotic covariance matrix of the workload process.\n :param load: vector with loads for every workload vector.\n :return:\n - delta_h: drift of the 1-dim \"height\" process.\n - sigma_2_h: asymptotic variance of the 1-dim \"height\" process.\n \"\"\"\n drift = 1 - load\n delta_h = (drift.T @ psi_plus)[0]\n sigma_2_h = (psi_plus.T @ workload_cov @ psi_plus)[0]\n return delta_h, sigma_2_h\n\n @staticmethod\n def _is_monotone_region_a_ray(c_plus: WorkloadSpace, eps: float = 1e-7) -> bool:\n \"\"\"\n The monotone region is a ray if c_plus has both positive and negative components.\n\n :param c_plus: vector defining the level set a bit farther than the projection w_star.\n :param eps: tolerance to evaluate the sign of each components of the c_plus vector.\n :return: True if c_plus has both negative and positive components.\n \"\"\"\n # casting to bool to satisfy mypy disagreement with type np.bool_\n return bool(np.any(c_plus < -eps) and np.any(c_plus > eps))\n\n @staticmethod\n def _get_c_plus_when_monotone_region_is_a_ray_or_boundary(c_minus: WorkloadSpace,\n w_star: WorkloadSpace,\n epsilon: float) -> WorkloadSpace:\n \"\"\"\n When the monotone effective-cost region is a ray or it is the boundary of the feasible\n workload, we build a proper cone around such ray. To do so, we take w_star as the direction\n defining the level sets of this artificial proper cone, and we scale with some\n hyperparameter (epsilon) which is positively correlated with the width of the cone\n (the higher epsilon, the bigger width of the cone and thus, the more conservative).\n If epsilon is equal to zero, then the returned c_plus will define a psi_plus which is\n orthogonal to the ray.\n\n :param c_minus: c_bar vector corresponding to current workload (i.e. \"below\" the ray)\n :param w_star: Projection of workload onto the ray\n :param epsilon: Hyperparameter to create the artificial cone that includes the ray.\n :return: c_plus: Vector in the direction of the ray or boundary.\n \"\"\"\n assert epsilon >= 0\n norm_w_star = np.linalg.norm(w_star)\n # epsilon_nought is the scalar projection of c_minus onto w_star\n epsilon_nought = (c_minus.T @ w_star) / (norm_w_star ** 2)\n assert epsilon_nought >= 0\n c_plus = (epsilon_nought + epsilon / norm_w_star) * w_star\n return c_plus\n\n @staticmethod\n def _get_closest_face_and_level_sets_for_ray_or_feasibility_boundary(c_minus: WorkloadSpace,\n w_star: WorkloadSpace,\n epsilon: float) \\\n -> Tuple[WorkloadSpace, WorkloadSpace]:\n \"\"\"\n When the monotone effective-cost region is a ray, we build a proper cone around such ray.\n To do so, we take w_star as the direction defining the level sets of this artificial proper\n cone, and we scale with some hyperparameter (epsilon) that gives the width of the cone\n (the higher epsilon, the more conservative).\n Similarly, when the monotone effective-cost region is the boundary of the feasible workload\n space, we take w_star as the direction for c_plus, and build an artificial cone with\n one face defined by the boundary of the feasible region.\n\n :param c_minus: c_bar vector corresponding to current workload (i.e. \"below\" the ray)\n :param w_star: Projection of workload onto the ray\n :param epsilon: Hyperparameter to create the artificial cone that includes the ray.\n :return:\n - psi_plus: vector normal to the closest face.\n - c_plus: Vector in the direction of the ray or boundary.\n \"\"\"\n assert epsilon >= 0\n c_plus = StrategicIdlingHedging._get_c_plus_when_monotone_region_is_a_ray_or_boundary(\n c_minus, w_star, epsilon)\n # @TODO: If np.any(c_plus < -eps), then we need another method to compute psi_plus.\n # See notes with new algorithm for that.\n psi_plus = c_plus - c_minus\n return psi_plus, c_plus\n\n @staticmethod\n def _is_w_inside_artificial_monotone_region(w: WorkloadSpace, psi_plus: WorkloadSpace) \\\n -> bool:\n \"\"\"\n When the monotone region is a ray, we build an artificial cone containing it, and obtain new\n c_plus and psi_plus vectors. This test checks whether the current workload state, w, is\n inside the new artificial cone.\n\n :param w: current state in workload space, i.e. w = Xi @ x.\n :param psi_plus: vector normal to the closest face.\n :return: True if w is in the monotone region. False otherwise.\n \"\"\"\n return psi_plus.T @ w >= 0\n\n @staticmethod\n def _get_price_lambda_star(c_plus: WorkloadSpace, psi_plus: WorkloadSpace,\n eps: float = 1e-6) -> float:\n \"\"\"\n Returns lambda_star i.e. the price of random oscillations along the closest face. There are\n multiple ways of computing lambda_star. This function takes the minimum of the component-\n wise ratio of c_plus over psi_plus. Alternative methods are implemented in alt_methods_test.\n We have proved this method only when w is outside the monotone region, so that w_star > w, a\n nd Slater's condition holds.\n\n :param c_plus: vector normal to the level set in the monotone region 'right above' the face.\n :param psi_plus: vector normal to the closest face.\n :param eps: tolerance to evaluate positive components of psi_plus.\n :return: lambda_star: price of random oscillations along the closest face.\n \"\"\"\n e_assert(bool(np.all(c_plus >= -eps)), exceptions.ArraySignError(array_name=\"c_plus\",\n all_components=True,\n positive=True,\n strictly=False))\n c_plus = np.array(np.clip(c_plus, a_min=0., a_max=None)) # Remove numerical errors\n e_assert(bool(np.any(c_plus > eps)), exceptions.ArraySignError(array_name=\"c_plus\",\n all_components=False,\n positive=True,\n strictly=True))\n ratio = np.divide(c_plus[psi_plus > eps], psi_plus[psi_plus > eps])\n # Reshape to avoid 'np.where' thinking that there are 2-dim\n ratio = ratio.reshape((ratio.shape[0],))\n e_assert(ratio.size > 0, exceptions.EmptyArrayError(array_name=\"ratio\"))\n lambda_star = float(np.nanmin(ratio)) # We take 0/0 = inf.\n return lambda_star\n\n def _compute_hedging_threshold(self, c_plus: WorkloadSpace, psi_plus: WorkloadSpace,\n eps: float = 1e-5) -> Tuple[float, float, float, float, float]:\n \"\"\"\n Returns the hedging threshold as a single scalar for the 1-dim height process along the\n reflection direction, with respect to the closest face.\n\n :param c_plus: vector normal to the level set in the monotone region 'right above' the face.\n :param psi_plus: vector normal to the closest face.\n :param eps: tolerance to evaluate positive components of psi_plus.\n :return:\n - beta_star: hedging threshold.\n - sigma_2_h: asymptotic variance of the 1-dim \"height\" process.\n - delta_h: drift of the high process.\n - lambda_star: price of random oscillations along the closest face.\n - theta_roots: positive root to the quadratic equation used to compute beta_star.\n \"\"\"\n delta_h, sigma_2_h = self._get_height_process_statistics(psi_plus,\n self._workload_cov, self._load)\n lambda_star = self._get_price_lambda_star(c_plus, psi_plus)\n\n assert -eps <= lambda_star < 1 + eps\n lambda_star = float(np.clip(lambda_star, a_min=0., a_max=1.))\n\n # Obtain positive root to the quadratic equation:\n # 0.5 * sigma_2_H * theta^2 - delta_h * theta - discount_factor = 0\n coeff = [0.5 * sigma_2_h, - delta_h, - self._neg_log_discount_factor]\n theta_roots = np.roots(coeff)\n theta_roots = theta_roots[theta_roots > 0]\n assert theta_roots.size == 1\n beta_star = (1 / theta_roots) * np.log(1 + lambda_star / (1 - lambda_star))\n beta_star *= self.strategic_idling_params.hedging_scaling_factor\n return beta_star, sigma_2_h, delta_h, lambda_star, theta_roots\n\n def _get_closest_face_and_level_sets(self,\n w_star: WorkloadSpace,\n v_star: WorkloadSpace) \\\n -> Tuple[Optional[WorkloadSpace], Optional[WorkloadSpace], Optional[WorkloadSpace]]:\n \"\"\"\n Obtains two alternative descriptions of the face of the monotone region that is closest to\n the current state in workload space, namely the normal vector to the face, and the\n level sets whose intersection define the face.\n\n :param w_star: projection of w onto the closest face along the direction of minimum cost.\n :param v_star: direction of projection from w to w_star.\n :return:\n - psi_plus: vector normal to the closest face.\n - c_plus: vector normal to the level set in the monotone region 'right above' the face.\n - c_minus: vector normal to the level set 'right below' the face.\n \"\"\"\n shift_eps = self.strategic_idling_params.shift_eps\n assert not np.any(np.isnan(v_star))\n assert 0 < shift_eps < 1\n shift_eps /= (1 + np.linalg.norm(v_star))\n\n w_r_minus = w_star - v_star * shift_eps # Stop bit before w_star (convex comb).\n w_r_plus = w_star + v_star * shift_eps # Go a bit farther than w_star.\n\n c_minus, _, _ = self.c_minus_solver.solve(w_r_minus)\n c_plus, _, _ = self.c_plus_solver.solve(w_r_plus)\n\n if c_plus is not None and c_minus is not None:\n psi_plus = c_plus - c_minus\n else:\n psi_plus = None\n return psi_plus, c_plus, c_minus\n\n @staticmethod\n def _get_possible_idling_directions(w: WorkloadSpace,\n beta_star: float,\n psi_plus: WorkloadSpace,\n v_star: WorkloadSpace,\n eps: float = 1e-6) -> types.IdlingSet:\n \"\"\"\n Return set of directions where we are allowed to idle. If we are far enough (more than\n beta_star) from the closest face (given by psi_plus), then we are allowed to idle in\n any convex combination of the directions that lead from w to w_star.\n\n Positive elements of v_star determine the set of bottlenecks for which short term idling\n will reduce instantaneous cost. However we only allow this idling when sufficiently far from\n the critical boundary. This sufficient separation is determined by hedging threshold.\n\n :param: w: current state in workload space, i.e. w = Xi @ x.\n :param: beta_star: hedging threshold.\n :param: psi_plus: vector orthogonal to the boundary of the monotone region.\n :param: v_star: direction from w to w_star.\n :return: k_idling_set: set of allowed idling directions.\n \"\"\"\n if psi_plus.T @ w < - beta_star:\n k_idling_set = np.where(v_star > eps)[0] # np.where returns a tuple.\n else:\n k_idling_set = np.array([])\n return k_idling_set\n\n @staticmethod\n def _build_state_list_for_computing_cone_envelope(num_buffers: int,\n init_x: int,\n max_points: Optional[int] = None) \\\n -> List[np.ndarray]:\n \"\"\"\n Returns a list of states with all possible combinations of buffers with positive value.\n\n :param num_buffers: number of buffers, i.e. dim of state space.\n :param init_x: initial value for the different components of the states in the list.\n :param max_points: Maximum number of points to compute the cone envelope.\n :return: state_list: List of states that will be used to compute workloads from which\n we will obtain a set of faces that will define the cone envelope.\n \"\"\"\n assert num_buffers > 0\n assert init_x > 0\n state_list = []\n num_points = 0\n buff_list_1 = list(range(num_buffers))\n shuffle(buff_list_1)\n buff_list_2 = list(range(num_buffers))\n shuffle(buff_list_2)\n for l in buff_list_1: # For each dimension of the workload space.\n for s in itertools.combinations(buff_list_2, l + 1):\n state = np.zeros((num_buffers, 1))\n for i in s:\n state[i] = init_x\n state_list.append(state)\n\n if max_points is not None and num_points == max_points - 1:\n return state_list\n num_points += 1\n return state_list\n\n @staticmethod\n def _build_workloads_for_computing_cone_envelope(workload_mat: types.WorkloadMatrix,\n init_x: int = 10,\n max_points: Optional[int] = None) \\\n -> List[np.ndarray]:\n \"\"\"\n Returns a list of workload values for which we will compute the closest faces\n in the monotone region. Such faces will define the initial version of the cone envelope.\n The length of the list equals the number of all possible combinations of buffers in state\n space. By building workloads from valid states, we ensure that they are feasible.\n\n :param workload_mat: workload matrix.\n :param init_x: initial value for the different components of the states in the list.\n :param max_points: Maximum number of points to compute the cone envelope.\n :return: w_list: list of workload values.\n \"\"\"\n num_buffers = workload_mat.shape[1]\n state_list = StrategicIdlingHedging._build_state_list_for_computing_cone_envelope(\n num_buffers, init_x, max_points)\n w_list = []\n for s in state_list:\n w_list.append(workload_mat @ s)\n return w_list\n\n def _add_face_to_cone_envelope(self,\n psi_plus: WorkloadSpace,\n beta_star: float,\n eps: float = 1e-2) -> None:\n \"\"\"\n Add the face given by psi_plus to the cone envelope if it was not already included.\n\n :param psi_plus: vector normal to the closest face.\n :param beta_star: hedging threshold.\n Threshold for each face of the pre-computed cone envelope.\n :param eps: Tolerance to verify that same face implies same hedging threshold.\n :return: (psi_plus_cone_list, beta_star_cone_list)\n - psi_plus_cone_list: Updated matrix with rows equal to the vector normal\n to the faces of the pre-computed cone envelope.\n - beta_star_cone_list: Updated vector with elements equal to the hedging\n threshold for each face of the pre-computed cone envelope.\n \"\"\"\n for i, (p, b) in enumerate(zip(self._psi_plus_cone_list, self._beta_star_cone_list)):\n if np.linalg.norm(psi_plus - p) / np.linalg.norm(psi_plus) < eps:\n if b > 1e-6 and abs(beta_star - b) / b < 0.05:\n return\n else:\n if beta_star > b:\n self.beta_star_cone_list[i] = beta_star # Update to be more conservative.\n return\n\n self._psi_plus_cone_list.append(psi_plus)\n self._beta_star_cone_list.append(beta_star)\n\n def _add_standard_hedging(self, w: WorkloadSpace,\n current_workload_variables: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Performs all steps needed to obtain the hedging threshold for the closest face.\n\n :param w: current state in workload space, i.e. w = Xi x.\n :current_workload_variables: dictionary containing all the current workload space variables\n :return: StrategicIdlingOutput\n - beta_star: hedging threshold.\n - k_idling_set: set of possibly idling directions.\n - sigma_2_h: asymptotic variance of the 1-dim \"height\" process.\n - psi_plus: vector normal to the closest face.\n - delta_h: drift projected in the direction of the \"height\" process.\n - lambda_star: price of random oscillations along the closest face.\n - theta_roots: root of quadratic equation used for computing hedging.\n \"\"\"\n c_bar = current_workload_variables['c_bar']\n w_star = current_workload_variables['w_star']\n v_star = current_workload_variables['v_star']\n\n psi_plus, c_plus, c_minus = self._get_closest_face_and_level_sets(w_star, v_star)\n hedging_case = 'standard'\n\n if self._is_infeasible(c_plus):\n psi_plus, c_plus = \\\n self._get_closest_face_and_level_sets_for_ray_or_feasibility_boundary(\n c_minus, w_star, self.strategic_idling_params.epsilon)\n hedging_case = 'infeasible'\n elif self._is_monotone_region_a_ray(c_plus):\n psi_plus, c_plus = \\\n self._get_closest_face_and_level_sets_for_ray_or_feasibility_boundary(\n c_minus, w_star, self.strategic_idling_params.epsilon)\n hedging_case = 'empty_interior'\n\n height_process = self._compute_height_process(w, psi_plus)\n\n if self._is_w_inside_artificial_monotone_region(w, psi_plus):\n current_workload_variables = {'w': w,\n 'w_star': w_star,\n 'c_plus': c_plus,\n 'c_bar': c_bar,\n 'psi_plus': psi_plus,\n 'height_process': height_process,\n 'hedging_case': hedging_case}\n return current_workload_variables\n\n beta_star, sigma_2_h, delta_h, lambda_star, theta_roots \\\n = self._compute_hedging_threshold(c_plus, psi_plus)\n k_idling_set = self._get_possible_idling_directions(w, beta_star, psi_plus, v_star)\n\n if is_pull_model(self.model_type) and not self._is_1d_workload_relaxation(w):\n # Update cone envelope with the current closest face if needed.\n self._add_face_to_cone_envelope(psi_plus, beta_star)\n\n current_workload_variables = {'w': w,\n 'beta_star': beta_star,\n 'k_idling_set': k_idling_set,\n 'sigma_2_h': sigma_2_h,\n 'psi_plus': psi_plus,\n 'height_process': height_process,\n 'w_star':w_star,\n 'c_plus': c_plus,\n 'c_bar': c_bar,\n 'psi_plus_cone_list': self.psi_plus_cone_list,\n 'beta_star_cone_list':self.beta_star_cone_list,\n 'delta_h':delta_h,\n 'lambda_star': lambda_star,\n 'theta_roots': theta_roots,\n 'hedging_case': hedging_case}\n\n return current_workload_variables\n\n def _negative_workloads(self, w: WorkloadSpace, eps: float = 1e-6) \\\n -> Dict[str, Any]:\n \"\"\"\n This function is only used when the current workload, w, is in the negative orthant,\n such that if we are below any of the faces of the cone envelope, then we are allowed\n to idle in the direction towards the origin.\n\n :param w: current state in workload space, i.e. w = Xi x.\n :param eps: tolerance value to check that we are in the negative orthant.\n :return: k_idling_set: set of possibly idling directions.\n \"\"\"\n assert self._is_negative_orthant(w, eps)\n # Cone envelope lists must be non-empty.\n assert self.psi_plus_cone_list and self.beta_star_cone_list\n k_idling_set = np.array([])\n beta_star = 0.\n c_bar = self._get_level_set_for_current_workload(w)\n for psi_plus, beta_star in zip(self.psi_plus_cone_list, self.beta_star_cone_list):\n height_process = self._compute_height_process(w, psi_plus)\n if height_process > beta_star:\n k_idling_set = np.arange(c_bar.size) # Use [0] since np.where returns a tuple.\n break # We are out of the monotone region\n\n current_workload_variables = {'w': w,\n 'k_idling_set': k_idling_set,\n 'beta_star': beta_star,\n 'c_bar': c_bar,\n 'height_process': height_process,\n 'psi_plus_cone_list': self.psi_plus_cone_list,\n 'beta_star_cone_list': self.beta_star_cone_list}\n\n return current_workload_variables\n\n def _verify_offline_preliminaries(self) -> None:\n assert self._workload_cov is not None, \\\n \"update workload covariance first to run policy with hedging\"\n\n def get_allowed_idling_directions(self, x: StateSpace) -> StrategicIdlingOutput:\n \"\"\"\n Method projects current worload onto the full monotone effective cost cone, or\n projects onto the precomputed envelope of the monotone effective cost cone.\n\n :param x: current buffer state of the network.\n :return: set of allowed idling resources with auxiliary variables\n \"\"\"\n w = self._workload_mat @ x\n self._verify_offline_preliminaries()\n if self._is_negative_orthant(w):\n idling_decision_dict = self._negative_workloads(w)\n else:\n current_workload_variables = self._non_negative_workloads(w)\n\n if self._is_decision_not_to_idle(current_workload_variables['k_idling_set']):\n idling_decision_dict = current_workload_variables\n else:\n idling_decision_dict = self._add_standard_hedging(w, current_workload_variables)\n\n idling_decision = self._get_null_strategic_idling_output(**idling_decision_dict)\n\n if self.debug_info:\n print(f\"beta_star: {idling_decision.beta_star}, \"\n f\"k_iling_set: {idling_decision.k_idling_set}, \"\n f\"sigma_2_h: {idling_decision.sigma_2_h}, \"\n f\"delta_h: {idling_decision.delta_h}\")\n return idling_decision\n","sub_path":"src/snc/agents/hedgehog/strategic_idling/strategic_idling_hedging.py","file_name":"strategic_idling_hedging.py","file_ext":"py","file_size_in_byte":30900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"75940046","text":"# 完成二元表达式求值\r\nfrom chap6.BitTree import BitTree\r\n\r\n\r\ndef make_Sum(a, b):\r\n '''构造一个小树完成a+b操作'''\r\n return BitTree('+', a, b)\r\n\r\n\r\ndef make_Prod(a, b):\r\n '''构造一个小树完成a*b操作'''\r\n return BitTree('*', a, b)\r\n\r\n\r\ndef make_Diff(a, b):\r\n '''构造一个小树完成a+b操作'''\r\n return BitTree('-', a, b)\r\n\r\n\r\ndef make_div(a, b):\r\n '''构造一个小树完成a/b操作'''\r\n return BitTree('/', a, b)\r\n\r\n\r\ndef is_Basic_Exp(e):\r\n '''判断e是否为基础表达式,这里传入的参数为bittree,判断左右两边是不是树'''\r\n return not isinstance(e, BitTree)\r\n\r\n\r\ndef is_number(x):\r\n '''检查x是否为数字'''\r\n return (isinstance(x, int) or (isinstance(x, float) or\r\n isinstance(x, complex)))\r\n\r\n\r\ndef eval_Sum(a, b):\r\n '''加法求值'''\r\n if is_number(a) and is_number(b):\r\n return a + b\r\n return make_Sum(a, b)\r\n\r\n\r\ndef eval_Sum(a, b):\r\n '''加法求值'''\r\n if is_number(a) and is_number(b):\r\n return a + b\r\n return make_Sum(a, b)\r\n\r\n\r\ndef eval_Prod(a, b):\r\n '''乘法求值'''\r\n if is_number(a) and is_number(b):\r\n return a * b\r\n return make_Prod(a, b)\r\n\r\n\r\ndef eval_Diff(a, b):\r\n '''减法求值'''\r\n if is_number(a) and is_number(b):\r\n return a - b\r\n return make_Diff(a, b)\r\n\r\n\r\ndef eval_Div(a, b):\r\n '''除法求值'''\r\n if b == 0:\r\n raise ZeroDivisionError\r\n if is_number(a) and is_number(b):\r\n return a / b\r\n return make_div(a, b)\r\n\r\n\r\ndef eval_Exp(e, values={'s': 50}):\r\n '''对表达式e求值'''\r\n if is_Basic_Exp(e): # 在这里检查e是不是values里面的bian'liang\r\n if e in values.keys():\r\n e = values[e]\r\n return e\r\n if e in values.items():\r\n e = values[e]\r\n print(e)\r\n option, a, b, = e.root(), eval_Exp(e.left()), eval_Exp(e.right())\r\n\r\n if option == '+':\r\n return eval_Sum(a, b)\r\n if option == '-':\r\n return eval_Diff(a, b)\r\n if option == '*':\r\n return eval_Prod(a, b)\r\n if option == '/':\r\n return eval_Div(a, b)\r\n\r\n\r\ndef variables(exp, li): # 递归里面用不了生成器???\r\n '''先序遍历二叉树'''\r\n if exp.root() is None:\r\n return\r\n if is_Variable(exp.root()) is not None:\r\n li.append(is_Variable(exp.root()))\r\n if not is_Basic_Exp(exp.left()): # 检查左边是不是树\r\n variables(exp.left(), li)\r\n else:\r\n if is_Variable(exp.left()) is not None:\r\n li.append(is_Variable(exp.left()))\r\n if not is_Basic_Exp(exp.right()): # 检查左边是不是树\r\n variables(exp.right(), li)\r\n else:\r\n if is_Variable(exp.right()) is not None:\r\n li.append(is_Variable(exp.right()))\r\n\r\n\r\ndef is_Variable(x):\r\n # '''求出exp里出现的所有变量的集合,这个集合包不包括数字呢?\r\n # 我这里不包括数字,不包括运算符号'''\r\n operators = ('+', '-', '*', '/')\r\n if not is_number(x) and x not in operators:\r\n return x\r\n return\r\n\r\n\r\ndef derive(exp, var): # 这里的exp只有加法和乘法运算\r\n '''表达式对变量var的导函数表达式'''\r\n if exp.root() is None:\r\n return\r\n\r\ndef interact_Eval_Exp():\r\n '''交互式二元表达式计算器'''\r\n while True:\r\n pass\r\n\r\n\r\ne1 = make_Prod(3, make_Sum('s', make_div(5, 1)))\r\nprint(e1) # 我是不是该定义一个函数,输出正常点\r\nprint(eval_Exp(e1))\r\nli = []\r\n'''将数组作为一个遍历函数的一个参数,遍历到一个节点,\r\n 就将该节点数值保存到数组中,由于数组的传递是地址传递,\r\n 所以函数中的改变会反应到外部,所以遍历结束,\r\n 数组中就是遍历的数据'''\r\nvariables(e1, li)\r\nprint(li)\r\n","sub_path":"datastructure/chap6/想不到什么可爱的名字.py","file_name":"想不到什么可爱的名字.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"649233086","text":"# -*- coding: utf-8 -*-\n# (C) Copyright IBM Corp. 2020.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTest the platform service Global Tagging API operations\n\"\"\"\n\nimport unittest\nimport pytest\nimport os\nfrom ibm_platform_services import GlobalTaggingV1\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\nfrom random import seed\nfrom random import randint\nfrom jproperties import Properties\nunittest.TestLoader.sortTestMethodsUsing = None\n\ndef getRandomIntegerString(length=8):\n if length < 0:\n length = 0\n res = ''\n for pos in range(length):\n res += str(randint(0, 10))\n return res\n\n# Read config file\nconfigFile = 'ghost.env'\nconfig = {}\nconfigLoaded = None\n\ntry:\n with open(configFile, \"rb\") as f:\n p = Properties()\n p.load(f, \"utf-8\")\n config['GST_API_URL'] = p['GST_API_URL'].data\n config['GST_TAGS_URL'] = p['GST_TAGS_URL'].data\n config['GST_RESOURCE_NAMES'] = p['GST_RESOURCE_NAMES'].data\n config['GST_IINTERNA_APIKEY'] = p['GST_IINTERNA_APIKEY'].data\n config['GST_IAM_URL'] = p['GST_IAM_URL'].data\n config['GST_QUERY'] = p['GST_QUERY'].data\n config['GST_RESOURCE_CRN'] = p['GST_RESOURCE_CRN'].data\n configLoaded = True\nexcept:\n print('External configuration was not found, skipping tests...')\n\n# Test class\nclass TestGlobalTaggingV1(unittest.TestCase):\n def setUp(self):\n if not configLoaded:\n self.skipTest(\"External configuration not available, skipping...\")\n \n # Create authenticator with IAM API key (it generates bearer token automatically)\n authenticator = IAMAuthenticator(config['GST_IINTERNA_APIKEY'], url=config['GST_IAM_URL'])\n self.global_tagging = GlobalTaggingV1(authenticator=authenticator)\n self.global_tagging.set_service_url(config['GST_TAGS_URL'])\n seed(1)\n self.tag_generated = 'python-sdk-' + getRandomIntegerString(8)\n resource = {}\n resource['resource_id'] = config['GST_RESOURCE_CRN']\n resource['resource_type'] = \"cf-application\"\n self.res = [ resource ]\n\n def tearDown(self):\n # Delete the resources\n print(\"Clean up complete\")\n\n def test_1_list_tags(self):\n env = self.global_tagging.list_tags()\n assert env is not None\n results = env.get_result()\n items = results.get('items')\n assert items is not None\n\n def test_2_attach_tag(self):\n # Attach the tag\n env = self.global_tagging.attach_tag(tag_name=self.tag_generated, resources=self.res)\n assert env is not None\n\n # Check if the tag is attached to the resource\n env = self.global_tagging.list_tags(attached_to=config['GST_RESOURCE_CRN'])\n assert env is not None\n results = env.get_result()\n items = results.get('items')\n assert items is not None\n flag_found = False\n for item in items:\n if item.get('name') == self.tag_generated:\n flag_found = True\n break\n assert flag_found is True\n\n def test_3_detach_tag(self):\n # Detach the tag\n env = self.global_tagging.detach_tag(tag_name=self.tag_generated, resources=self.res)\n assert env is not None\n\n # Check if the tag is detached\n env = self.global_tagging.list_tags(attached_to=config['GST_RESOURCE_CRN'])\n assert env is not None\n results = env.get_result()\n items = results.get('items')\n assert items is not None\n flag_found = False\n for item in items:\n if item.get('name') == self.tag_generated:\n flag_found = True\n break\n assert flag_found is False\n\n def test_4_delete_tag(self):\n # Delete the tag\n env = self.global_tagging.delete_tag(tag_name=self.tag_generated)\n assert env is not None\n\n # Check if the tag is deleted\n env = self.global_tagging.list_tags()\n assert env is not None\n results = env.get_result()\n items = results.get('items')\n assert items is not None\n flag_found = False\n for item in items:\n if item.get('name') == self.tag_generated:\n flag_found = True\n break\n assert flag_found is False\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/integration/test_global_tagging_v1.py","file_name":"test_global_tagging_v1.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"324025219","text":"\r\nfrom datetime import datetime, timedelta\r\n# import datetime\r\nimport logging\r\nimport flask\r\nimport pandas as pd\r\nimport re\r\nimport json\r\nfrom flask import jsonify, make_response\r\nfrom calendar import monthrange\r\nimport collections\r\n\r\n\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\napp = flask.Flask(__name__)\r\n\r\ndef read_file(file):\r\n # filename = file.filename\r\n # report_id =\r\n data = pd.read_csv(file)\r\n app.logger.info(\"read file\")\r\n # app.logger.info(data)\r\n return 200, \"uploaded successfully\", data\r\n\r\n\r\ndef check_csv_specification(data, filename):\r\n # ensure there is well-informed file name\r\n filename_split = re.findall('time-report-\\d{2}',filename)\r\n if not filename_split:\r\n return False\r\n # ensure there is a well-informed headerline\r\n ideal_header = ['date', 'hours worked', 'employee id', 'job group']\r\n result = all(map(lambda x, y: x == y, data.columns, ideal_header))\r\n\r\n # app.logger.debug(result)\r\n if not result:\r\n return False\r\n\r\n return True\r\n\r\ndef get_report_id(filename):\r\n filename_split = re.findall('\\d{2}',filename)\r\n report_id = int(filename_split[0])\r\n # app.logger.info(f'report_id: {report_id}')\r\n return 200, \"retrived report id\",report_id\r\n\r\n# parse data\r\ndef parse_employee_logs(data, report_id):\r\n\r\n date = pd.to_datetime(data['date'])\r\n hours_worked = data['hours worked'].astype(float)\r\n employee_id = data['employee id'].astype(int)\r\n job_group = data['job group']\r\n\r\n df = pd.DataFrame({'date':date, 'employee_id':employee_id, 'hours_worked': hours_worked, 'job_group': job_group, 'report_id':report_id})\r\n\r\n return 200, \"successfully parsed employee data\", df\r\n\r\n# Make a report detailing how much each employee should be paid in each pay period\r\n\r\ndef make_payroll_report(rows):\r\n\r\n temp_list = []\r\n for row in rows:\r\n employee_id = row[\"employee_id\"]\r\n pay_period = get_pay_period(row['date'])\r\n end_date = pay_period[\"endDate\"] # could use endDate or startDate..\r\n amount_paid = calculate_amount_paid(row['hours_worked'], row['job_group'])\r\n\r\n check_list = check_log_with_same_pay_period(temp_list, employee_id,end_date, amount_paid)\r\n if(check_list):\r\n temp_list = check_list\r\n continue\r\n\r\n temp_list.append({\r\n 'employee_id':str(employee_id),\r\n 'payPeriod':pay_period,\r\n 'amountPaid': amount_paid\r\n }\r\n )\r\n\r\n # sorted by employee id and then pay period start\r\n # newlist = sorted(temp_list, key=itemgetter('employee_id', 'startDate'))\r\n employeeReports_list = sorted(temp_list, key=lambda x: (\r\n x['employee_id'],\r\n x['payPeriod']['startDate']\r\n )\r\n )\r\n\r\n payrollReport = {'payrollReport': {'employeeReports':employeeReports_list}}\r\n # app.logger.info(json.dumps(test_dict, indent = 4))\r\n\r\n return 200, payrollReport\r\n\r\ndef check_log_with_same_pay_period(curr_list, employee_id, end_date, amount_paid):\r\n check_list = curr_list.copy()\r\n for i in range(0,len(check_list)):\r\n curr_log = check_list[i]\r\n if int(curr_log['employee_id']) == employee_id:\r\n if curr_log[\"payPeriod\"][\"endDate\"] == end_date:\r\n amount_1_str = curr_log[\"amountPaid\"]\r\n amount_1_int = int(re.findall('\\d+', amount_1_str)[0])\r\n amount_2_str = amount_paid\r\n amount_2_int = int(re.findall('\\d+', amount_2_str)[0])\r\n tot_amount = amount_1_int + amount_2_int\r\n curr_log[\"amountPaid\"] = \"$\"+\"{:.2f}\".format(tot_amount)\r\n return check_list\r\n return None\r\n\r\n\r\ndef get_pay_period(date_str):\r\n date_datetime = datetime.strptime(date_str, \"%Y-%m-%d %H:%M:%S\")\r\n\r\n if 1 <= date_datetime.day <= 15:\r\n start_datetime = date_datetime.replace(day = 1)\r\n end_datetime = date_datetime.replace(day = 15)\r\n # end_date = datetime.date(start_datetime.year, start_datetime.month,15)\r\n elif 16 <= date_datetime.day <= 31:\r\n _,num_day=monthrange(date_datetime.year, date_datetime.month)\r\n start_datetime = date_datetime.replace(day = 16)\r\n end_datetime = date_datetime.replace(day = num_day)\r\n\r\n start_date = start_datetime.date()\r\n end_date = end_datetime.date()\r\n\r\n return {'startDate': start_date.strftime(\"%Y-%m-%d\"), 'endDate': end_date.strftime(\"%Y-%m-%d\")}\r\n\r\ndef calculate_amount_paid(hours_worked, job_group):\r\n if job_group == \"A\":\r\n return \"$\"+\"{:.2f}\".format((hours_worked*20))\r\n # return \"$\"+\"%.2f\"%(hours_worked*20)\r\n return \"$\"+\"{:.2f}\".format((hours_worked*30))\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"368725420","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : huxiansheng (you@example.org)\nfrom Public.Common import *\nfrom Public.Mysqldb import Mysql\n\n\nclass login_check():\n '''\n 登录的业务逻辑校验\n '''\n def __init__(self):\n self.sql = Mysql()\n\n def check_username_pwd_Legality(self,username,pwd):\n '''\n 校验账号密码的合法性\n :param username:\n :param pwd:\n :return:None 账号密码长度不符 True没有包含中文字符 False包含中文字符\n '''\n if len(username)<5 or len(username)>15 or len(pwd)<5 or len(pwd)>15 :\n return None\n else:\n chinese_user = Str_manager().check_contain_chinese(username)\n chinese_pwd = Str_manager().check_contain_chinese(pwd)\n if chinese_user==None and chinese_pwd==None:\n return True\n else:\n return False\n\n\n def check_user_state(self,username,pwd):\n '''\n 校验用户名的正确的,是否存在\n :param username: 用户名\n :param pwd: 密码\n :return:None 用户名不存在 True 账号密码正确 False 密码错误\n '''\n Legality = self.check_username_pwd_Legality(username,pwd)\n if Legality==True:\n select_satatu = self.sql.selete(table_name='user_info',check_field='pwd',condition=\"username='%s'\"%username)\n if str(select_satatu)=='()':\n return None\n elif select_satatu[0][0]==pwd:\n return True\n else:\n return False\n elif Legality==False:\n return 'chinese_error'\n else:\n return 'len_error'\n\n\n\nclass sign_up_check():\n '''\n 注册的业务逻辑校验\n '''\n def input_user_pwd(self,username,pwd,phone):\n '''\n 插入注册信息\n :param username: 用户名\n :param pwd:密码\n :param phone:手机号码\n :return:add_state=1 注册成功 add_state=0 注册失败 username_exite 用户名已存在 phone_exite 手机已存在\n Legality_error 账号密码不合法 phone_len_error 手机号码长度不正确\n '''\n now = WhidowsInfo().get_window_time()\n log_check = login_check()\n Legality = log_check.check_username_pwd_Legality(username,pwd)\n # 验证注册信息的合法性\n if len(phone)==11 :\n if Legality==True:\n select_state = log_check.sql.selete(table_name='user_info',check_field='phone',condition='phone=%s'%phone)\n # 验证手机号码是否被注册\n if str(select_state) == '()':\n select_state2 = log_check.sql.selete(table_name='user_info',check_field='username',condition='username=%s'%username)\n if str(select_state2) == '()':\n c1='username,pwd,creadtime,phone'\n VALUES = \"'%s','%s','%s','%s'\"%(username,pwd,now,phone)\n add_state = log_check.sql.add(table_name='user_info',field_str=c1,value_str=VALUES)\n return add_state\n else:\n return 'username_exite'\n else:\n return 'phone_exite'\n else:\n return 'Legality_error'\n else:\n return 'phone_len_error'","sub_path":"Business/Check.py","file_name":"Check.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"651361184","text":"import gzip\nimport re\nimport editdistance\nfrom tqdm import tqdm\nimport pandas as pd\nfrom typing import Generator, Tuple, Optional, List\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom .config import logger\n\nplt.rcParams[\"svg.fonttype\"] = \"none\"\n\n\nclass BarcodeExtractor:\n def __init__(\n self,\n read1_file: str,\n read2_file: str,\n left_flank: Optional[str] = None,\n right_flank: Optional[str] = None,\n barcode_length: Optional[int] = None,\n max_dist: int = 3,\n max_read_length: int = 200,\n disable_progress_bar: bool = False,\n ):\n \"\"\"\n Extract barcodes from paired-end FASTQ files. The files can be gunzip.\n\n :param read1_file: Read 1 FASTQ file\n :param read2_file: Read 2 FASTQ file\n :param left_flank: Left primer sequence\n :param right_flank: Right primer sequence\n :param barcode_length: Length of the barcode sequence\n :param max_dist: Maximum allowed distance between barcode sequence from match pair.\n :param max_read_length: Maximum read length\n :param disable_progress_bar: If True, then progress bars are not shown\n \"\"\"\n self.r1Fn = read1_file\n self.r2Fn = read2_file\n self.leftFlank = left_flank\n self.rightFlank = right_flank\n self.barcodeLength = barcode_length\n self.maxDist = max_dist\n self.maxReadLength = max_read_length\n self.nucComp: Optional[pd.Series] = None\n self.rawCounts: Optional[pd.Series] = None\n self.disablePb = disable_progress_bar\n\n @staticmethod\n def _read_fastq(fn: str) -> Generator[str, None, None]:\n n = 1\n if fn.endswith(\".gz\"):\n to_str = lambda x: x.decode(\"UTF-8\").rstrip(\"\\n\")\n handle = gzip.open(fn)\n else:\n to_str = lambda x: x.rstrip(\"\\n\")\n handle = open(fn)\n for line in handle:\n if n % 2 == 0 and n % 4 != 0:\n yield to_str(line)\n n += 1\n handle.close()\n\n def identify_flanks(\n self,\n max_frac_threshold: float = 0.6,\n flank_size: int = 6,\n n_rows: Optional[int] = None,\n ):\n \"\"\"\n\n :param max_frac_threshold:\n :param flank_size:\n :param n_rows:\n :return:\n \"\"\"\n nuc_comp = {x: {x: 0 for x in \"ATGCN\"} for x in range(self.maxReadLength)}\n n = 0\n for seq1 in tqdm(\n self._read_fastq(self.r1Fn),\n desc=\"Identifying flank sequences\",\n disable=self.disablePb,\n ):\n for p, i in enumerate(seq1):\n nuc_comp[p][i] += 1\n n += 1\n if n_rows is not None and n > n_rows:\n break\n nuc_comp = pd.DataFrame(nuc_comp).T.sort_index()\n ncs = nuc_comp.sum(axis=1).values\n length_thresh = np.where(ncs > ncs[0] / 2)[0].max()\n nuc_comp = nuc_comp[:length_thresh]\n frac = nuc_comp.max(axis=1) / nuc_comp.sum(axis=1)\n p = np.where(frac < max_frac_threshold)[0]\n s, e = p[0], p[-1]\n if p.shape[0] == e - s + 1:\n self.leftFlank = \"\".join(nuc_comp[s - flank_size : s].idxmax(axis=1).values)\n self.rightFlank = \"\".join(\n nuc_comp[e + 1 : e + flank_size + 1].idxmax(axis=1).values\n )\n self.barcodeLength = len(p)\n else:\n logger.error(\n \"Flank detection failed due to non-contiguous variable base composition \"\n )\n self.nucComp = nuc_comp\n\n @staticmethod\n def _rev_comp(seq: str) -> str:\n rev_map = {\"A\": \"T\", \"T\": \"A\", \"G\": \"C\", \"C\": \"G\", \"N\": \"N\"}\n return \"\".join([rev_map[x] for x in seq[::-1]])\n\n def _extract_seq_with_flanks(\n self, seq: str, up_seq: str, down_seq: str\n ) -> Optional[str]:\n \"\"\"\n\n :param seq:\n :param up_seq:\n :param down_seq:\n :return:\n \"\"\"\n up_pos = [x.start() for x in re.finditer(up_seq, seq)]\n down_pos = [x.start() for x in re.finditer(down_seq, seq)]\n adjust_start = len(up_seq)\n barcode_len = self.barcodeLength + adjust_start\n if len(up_pos) > 0 and len(down_pos) > 0:\n valid_comb = []\n for i in up_pos:\n for j in down_pos:\n if j - i == barcode_len:\n valid_comb.append((i + adjust_start, j))\n if len(valid_comb) == 1:\n return seq[valid_comb[0][0] : valid_comb[0][1]]\n return None\n\n def _stream_reads(self) -> Generator[Tuple[str, str], None, None]:\n for seq1, seq2 in zip(self._read_fastq(self.r1Fn), self._read_fastq(self.r2Fn)):\n yield seq1, seq2\n return None\n\n def count_barcodes(\n self,\n ) -> None:\n \"\"\"\n\n :return:\n \"\"\"\n if (\n self.leftFlank is None\n or self.rightFlank is None\n or self.barcodeLength is None\n ):\n logger.error(\n \"Flank sequence(s) and/or barcode length is unknown. Please run `identify_flanks` \"\n \"to detect automatically or provide them manually when calling `BarcodesPE`\"\n )\n return None\n counts = {}\n n, f1, f2 = 0, 0, 0\n max_len = 0\n nuc_comp = {x: {x: 0 for x in \"ATGCN\"} for x in range(self.maxReadLength)}\n for seq1, seq2 in tqdm(\n self._stream_reads(), disable=self.disablePb, desc=\"Counting barcodes\"\n ):\n if len(seq1) > max_len:\n max_len = len(seq1)\n for p, i in enumerate(seq1):\n nuc_comp[p][i] += 1\n b1, b2 = (\n self._extract_seq_with_flanks(seq1, self.leftFlank, self.rightFlank),\n self._extract_seq_with_flanks(\n seq2,\n self._rev_comp(self.rightFlank),\n self._rev_comp(self.leftFlank),\n ),\n )\n if b1 is not None and b2 is not None:\n b2 = self._rev_comp(b2)\n if editdistance.eval(b1, b2) <= self.maxDist:\n if b1 not in counts:\n counts[b1] = 0\n counts[b1] += 1\n else:\n f2 += 1\n else:\n f1 += 1\n n += 1\n\n f1 = 100 * f1 / n\n f2 = 100 * f2 / n\n f1 = \"%.2f\" % f1\n f2 = \"%.2f\" % f2\n logger.info(\n f\"{n} sequences processed. {len(counts)} unique(uncorrected) barcodes found.\"\n )\n logger.warning(\n f\"Unable to find barcodes in {f1}% reads. {f2}% reads had too many mismatches.\"\n )\n if max_len > self.maxReadLength:\n logger.warning(\n f\"Maximum observed read length ({max_len}) is higher than provided ({self.maxReadLength}). \"\n \"The nucleotide composition table is likely to be truncated.\"\n )\n else:\n logger.info(f\"Maximum observed read length is {max_len}\")\n self.maxReadLength = max_len\n self.nucComp = pd.DataFrame(nuc_comp).T.sort_index()[: self.maxReadLength]\n self.rawCounts = pd.Series(\n dict(sorted(counts.items(), key=lambda item: item[1], reverse=True))\n )\n\n def plot_composition(\n self,\n save_name: str = None,\n verts: List[int] = None,\n fig_size: Tuple[int, int] = (12, 3),\n ) -> None:\n \"\"\"\n\n :param save_name:\n :param verts:\n :param fig_size:\n :return:\n \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=fig_size)\n self.nucComp.plot(kind=\"bar\", stacked=True, ax=ax, cmap=\"Set3\")\n if verts is not None:\n for i in verts:\n ax.axvline(i, color=\"k\", lw=3.5, ls=\"--\")\n ax.set_xlabel(\"Position in read\")\n ax.set_ylabel(\"Nucleotide frequency\")\n plt.tight_layout()\n if save_name is not None:\n plt.savefig(save_name, dpi=300)\n plt.close()\n else:\n plt.show()\n\n def plot_barcode_frequency(\n self, save_name: str = None, fig_size: Tuple[int, int] = (6, 5)\n ) -> None:\n \"\"\"\n\n :param save_name:\n :param fig_size:\n :return:\n \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=fig_size)\n x = self.rawCounts.apply(np.log10).sort_values(ascending=False).reset_index()[0]\n x.plot(kind=\"line\", ax=ax, lw=4)\n ax.set_xlabel(\"Barcodes sorted by frequency\", fontsize=12)\n ax.set_ylabel(\"Log10 frequency\", fontsize=12)\n plt.tight_layout()\n if save_name is not None:\n plt.savefig(save_name, dpi=300)\n plt.close()\n else:\n plt.show()\n","sub_path":"bartide/paired_extractor.py","file_name":"paired_extractor.py","file_ext":"py","file_size_in_byte":8801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"365481548","text":"import ctypes\nfrom six import iterkeys, itervalues, iteritems\nimport numpy as np\nfrom cimageio import __lib__\nfrom cimageio._common import ARRAY_BUFFER, BYTE_BUFFER, get_array_header\n\n\n__PNG_COLOR_TYPE__ = {\n 'GRAY': 0,\n 'RGB': 2,\n 'PALETTE': 3,\n 'RGBA': 2 | 4,\n}\n\n__PNG_ALLOWABLE__ = [\n (8, 'GRAY'),\n (16, 'GRAY'),\n (8, 'RGB'),\n (8, 'RGBA'),\n]\n\n__lib__.encode_to_png.argtypes = [\n ctypes.POINTER(ARRAY_BUFFER),\n ctypes.POINTER(BYTE_BUFFER),\n ctypes.c_uint,\n]\n__lib__.encode_to_png.restype = ctypes.c_int\n\n__lib__.decode_from_png.argtypes = [\n ctypes.POINTER(BYTE_BUFFER),\n ctypes.POINTER(ARRAY_BUFFER),\n]\n__lib__.decode_from_png.restype = ctypes.c_int\n\n\ndef encode_to_png(array,\n compression_level=6,\n color_type='auto'):\n \"\"\"\n Encode numpy.ndarray to PNG format byte-string\n :param array: (numpy.ndarray) Image array to encode. dtype of array should be uint8 or uint16.\n :param compression_level: (int) Compression level. One of 0~9\n :param color_type: (str) Specification of how color channel consisted of. See\n __PNG_COLOR_TYPE__\n :return: (bytes) byte-string formatted with PNG\n \"\"\"\n # Parse information from array\n color_type = None if color_type == 'auto' else color_type\n bit_depth, color_type = get_array_header(array, 'png', color_type, __PNG_ALLOWABLE__)\n\n # Change to big-endian order\n array = array.astype('>u' + str(bit_depth // 8))\n\n # Pack to C array\n array_buffer = ARRAY_BUFFER(\n array.ctypes.data_as(ctypes.c_void_p),\n array.shape[0],\n array.shape[1],\n __PNG_COLOR_TYPE__[color_type],\n bit_depth,\n )\n byte_buffer = BYTE_BUFFER(\n None,\n 0\n )\n\n # Run C code\n code = __lib__.encode_to_png(ctypes.byref(array_buffer),\n ctypes.byref(byte_buffer),\n compression_level)\n if code:\n raise RuntimeError('Encoding failed')\n\n # Unpack to numpy.ndarray\n byte_string = (ctypes.c_byte * byte_buffer.size).from_address(byte_buffer.data)\n byte_string = bytearray(byte_string)\n return byte_string\n\n\ndef decode_from_png(byte_string):\n \"\"\"\n Decode PNG format byte-string to np.ndarray\n :param byte_string: (bytes) Byte-string to decode.\n :return: (numpy.ndarray) Decoded image array.\n \"\"\"\n # Pack to C array\n byte_buffer = BYTE_BUFFER(\n ctypes.cast(byte_string, ctypes.c_void_p),\n len(byte_string),\n )\n array_buffer = ARRAY_BUFFER(\n None,\n 0,\n 0,\n 0,\n 0,\n )\n\n # Run C code\n code = __lib__.decode_from_png(ctypes.byref(byte_buffer), ctypes.byref(array_buffer))\n if code:\n raise RuntimeError('Decoding failed')\n height, width = array_buffer.height, array_buffer.width\n bit_depth = array_buffer.bit_depth\n color_type = None\n for k, v in iteritems(__PNG_COLOR_TYPE__):\n if array_buffer.color_type == v:\n color_type = k\n break\n if color_type is None:\n raise ValueError('Unsupported PNG color type %d' % array_buffer.color_type)\n color_channel = 1 if color_type == 'GRAY' else \\\n 2 if color_type == 'GRAYA' else \\\n 3 if color_type == 'PALETTE' else \\\n 3 if color_type == 'RGB' else \\\n 4\n\n # Get array length\n array_length = height * width * (bit_depth // 8) * color_channel\n array_string = (ctypes.c_byte * array_length).from_address(array_buffer.data)\n array = np.frombuffer(array_string, dtype='>u' + str(bit_depth // 8))\n array = array.astype('=u' + str(bit_depth // 8))\n array = np.resize(array, [height, width, color_channel])\n array = array.squeeze()\n return array\n","sub_path":"_cimageio/png.py","file_name":"png.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"563877067","text":"import pandas as pd\nimport os.path\nfrom sqlalchemy import create_engine\nimport requests\n\n# acquisition functions\n\ndef validate_file(path): # Checking if file exists\n if (os.path.isfile(f'./{path}')):\n return True\n else:\n return False\n\ndef data_connect(path):\n engine_connection = create_engine(f'sqlite:///./{path}') # data/raw/raw_data_project_m1.db\n my_tables=engine_connection.table_names()\n for i in range(0,len(my_tables)):\n x=my_tables[i]\n query=f'SELECT * FROM {x}'\n df_i = pd.read_sql(query, con=engine_connection)\n if i==0:\n df_new=df_i\n else:\n df_new=pd.merge(df_new,df_i, how='left', on='uuid')\n # df_new.to_csv(f'./data/raw/df_new') # we save the 1st version of dataframe\n return df_new\n\n#the function to bring information from scraping a web for country codes management\ndef bring_web_country():\n url = 'https://ec.europa.eu/eurostat/statistics-explained/index.php/Glossary:Country_codes'\n my_html = pd.read_html(url) # this is a list of dataframes\n countries = dict()\n now = 'C'\n for df in my_html:\n for f in range(0, len(df.index)):\n for c in range(0, len(df.columns)):\n if (isinstance(df.iloc[f, c], str)):\n if (now == 'C'):\n my_country = df.iloc[f, c]\n now = 'CC'\n else:\n my_country_code = df.iloc[f, c]\n my_country_code = my_country_code.replace('(', '')\n my_country_code = my_country_code.replace(')', '')\n now = 'C'\n countries[my_country] = my_country_code\n df_countries = pd.DataFrame(countries.items(), columns=['country', 'country_code'])\n return df_countries\n\ndef validate_country(one_country, df_countries):\n if ((one_country in df_countries['country'].unique()) or (one_country is None)):\n return True\n else:\n return False\n\n# the function to bring information from jobs API\ndef bring_api_data(df_new):\n# 1st I create a list with uniq values of normalized_jod_code in the table\n my_l = list(set(df_new['normalized_job_code'].to_list()))\n long=len(my_l)\n my_result = []\n cont=0\n print(f'Log: started bringing jobs information from API')\n for i in my_l:\n cont +=1\n response = requests.get(f'http://api.dataatwork.org/v1/jobs/{i}')\n results = response.json()\n my_result.append(results)\n print(f'Processing {cont} of {long} records')\n# Creation a dataframe with information from API\n df_jobs = pd.DataFrame(my_result)\n df_jobs = df_jobs.drop('error', axis=1) # Cleaning\n df_jobs = df_jobs.rename(columns={'uuid':'normalized_job_code'}) # Rename a column\n return df_jobs\n\n","sub_path":"p_acquisition/m_acquisition.py","file_name":"m_acquisition.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"364264966","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\ndataset=pd.read_csv('F:\\MachineLearningA2Zdatasets\\Machine Learning A2Z\\Clustering\\K-Means Clustering\\Mall_Customers.csv')\r\nprint(dataset.head())\r\nprint(dataset.info())\r\nX=dataset.iloc[:,[3,4]].values\r\n\r\nfrom sklearn.cluster import KMeans\r\nwcss=[]\r\nfor i in range(1,11):\r\n kmeans=KMeans(n_clusters=i,init='k-means++',n_init=10,max_iter=300,random_state=0)\r\n kmeans.fit(X)\r\n wcss.append(kmeans.inertia_)\r\nplt.plot(range(1,11),wcss)\r\n\r\nkmeans=KMeans(n_clusters=5,init='k-means++',n_init=10,max_iter=300,random_state=0)\r\ny_kmeans=kmeans.fit_predict(X)\r\nplt.figure(figsize=(10,10))\r\nplt.scatter(X[y_kmeans==0,0],X[y_kmeans==0,1],s=100,c='red',label='cluster1')\r\nplt.scatter(X[y_kmeans==1,0],X[y_kmeans==1,1],s=100,c='green',label='cluster2')\r\nplt.scatter(X[y_kmeans==2,0],X[y_kmeans==2,1],s=100,c='yellow',label='cluster3')\r\nplt.scatter(X[y_kmeans==3,0],X[y_kmeans==3,1],s=100,c='cyan',label='cluster4')\r\nplt.scatter(X[y_kmeans==4,0],X[y_kmeans==4,1],s=100,c='blue',label='cluster5')\r\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=100,c='black',label='centroids')\r\nplt.xlabel('y_kmeans')\r\nplt.ylabel('wcss')\r\nplt.title('no of clusters')\r\nplt.legend()\r\nplt.show() ","sub_path":"MachineLearningA2Z/KMeansClustering.py","file_name":"KMeansClustering.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"308527979","text":"import discord\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import has_permissions\r\nfrom discord.ext.commands.cooldowns import BucketType\r\nfrom discord.ext.commands.errors import CommandOnCooldown, MissingPermissions, CheckFailure\r\nimport json\r\nimport datetime\r\nimport time\r\nimport asyncio\r\n\r\n\r\nclass Polls(commands.Cog):\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command(name=\"poll\", description=\"creates a poll\", pass_context=True, usage=\"title; amount of options; option1; option2; option3(etc.)(max = 10); ExpirationTime(defaults to 12h)(formatted like [2h 32m]) \")\r\n @commands.cooldown(1, 60, BucketType.member)\r\n #@has_permissions(manage_messages=True)\r\n async def poll(self, ctx):\r\n if not ctx.message.author.bot:\r\n try:\r\n MsgContent = ctx.message.content\r\n MsgContentList = MsgContent.split('; ')\r\n title = ''\r\n for i in MsgContentList[0].split(' '):\r\n if i != \">poll\" and i != \"<@!716640483471917176> poll\":\r\n title += i + ' '\r\n AmountOfOptions = int(MsgContentList[1])\r\n if AmountOfOptions > 10:\r\n AmountOfOptions = 10\r\n Options = MsgContentList[2:]\r\n Options = Options[:AmountOfOptions]\r\n Expiration = MsgContentList[-1]\r\n TotalTime = 0\r\n minutes = 0\r\n hours = 0\r\n try:\r\n ListExpiration = Expiration.split(\" \")\r\n if len(ListExpiration) == 1:\r\n if ListExpiration[0].endswith(\"h\"):\r\n hours = int(ListExpiration[0].strip(\"h\"))\r\n TotalTime = hours * 60 * 60\r\n elif ListExpiration[0].endswith(\"m\"):\r\n minutes = int(ListExpiration[0].strip(\"m\"))\r\n if minutes > 60:\r\n hours += round(minutes/60)\r\n minutes -= hours*60\r\n TotalTime = minutes * 60 + hours * 60 * 60\r\n TotalTime = minutes * 60\r\n elif len(ListExpiration) == 2:\r\n if ListExpiration[0].endswith(\"h\") and ListExpiration[1].endswith(\"m\"):\r\n hours = int(ListExpiration[0].strip(\"h\"))\r\n minutes = int(ListExpiration[1].strip(\"m\"))\r\n TotalTime = hours * 60 * 60 + minutes * 60\r\n else:\r\n await ctx.channel.send(\"invalid expiration time, did you format it like '[hours]h [minutes]m'? [ex. 2h 30m]\")\r\n return\r\n except:\r\n await ctx.channel.send(\"invalid expiration time, did you format it like '[hours]h [minutes]m'? [ex. 2h 30m]\")\r\n return\r\n await ctx.message.delete()\r\n if TotalTime == 0:\r\n TotalTime = 12 * 60 * 60\r\n hours = 12\r\n minutes = 0\r\n PollEmbed = discord.Embed(title=f\"__{title}__\", color=0x9B59B6)\r\n PollEmbed.set_author(name=f\"requested by {ctx.message.author.name}\", icon_url=ctx.message.author.avatar_url)\r\n PollEmbed.set_thumbnail(url=self.client.user.avatar_url)\r\n OptionCounter= 0\r\n Emotes = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟']\r\n EmoteDict = {Emotes[0]:\":one:\", Emotes[1]:\":two:\", Emotes[2]:\":three:\", Emotes[3]:\":four:\", Emotes[4]:\":five:\", Emotes[5]:\":six:\", Emotes[6]:\":seven:\", Emotes[7]:\":eight:\", Emotes[8]:\":nine:\", Emotes[9]:\":keycap_ten:\"}\r\n for i in Options:\r\n OptionCounter += 1\r\n PollEmbed.add_field(name=\"\\u200b\", value=f\"**{OptionCounter}**: {i}\", inline=False)\r\n PollEmbed.set_footer(text=f\"expires in {hours}h {minutes}m\")\r\n message = await ctx.channel.send(embed=PollEmbed)\r\n MESSAGE_ID=message.id\r\n AddedReactions = []\r\n for i in range(OptionCounter):\r\n await message.add_reaction(Emotes[i])\r\n AddedReactions.append(Emotes[i])\r\n TimeMessageCreated = time.time()\r\n timeleft = TotalTime\r\n while round(time.time() - TimeMessageCreated) < TotalTime:\r\n await asyncio.sleep(60)\r\n timeleft -= 60\r\n workingTime = timeleft\r\n ReFormatHours = 0\r\n if workingTime/60 >= 60:\r\n ReFormatHours += round(timeleft/60/60)\r\n workingTime -= 60*60*ReFormatHours\r\n ReformatMinutes = round(workingTime/60)\r\n if ReformatMinutes < 0:\r\n ReFormatHours -= 1\r\n ReformatMinutes += 60\r\n \r\n else:\r\n ReFormatHours = 0\r\n ReformatMinutes = round(workingTime/60)\r\n PollEmbed.set_footer(text=f\"Expires in {ReFormatHours}h {ReformatMinutes}m\")\r\n await message.edit(embed=PollEmbed)\r\n poll = await ctx.channel.fetch_message(MESSAGE_ID)\r\n Results_unrefined = {}\r\n Results = {}\r\n RefiningResultCounter = 0\r\n for i in poll.reactions:\r\n if RefiningResultCounter < 3:\r\n Results.update({EmoteDict[i.emoji]:i.count-1})\r\n RefiningResultCounter += 1\r\n TotalScore = 0\r\n for i in [int(Results[i]) for i in list(Results.keys())]:\r\n TotalScore += i\r\n EmbedResults = {}\r\n\r\n for i in Results.keys():\r\n try:\r\n EmbedResults.update({i:[Results[i], round(Results[i]/TotalScore*100, 2)]})\r\n except DivisionByZero as e:\r\n EmbedResults.update({i:[Results[i], 0]})\r\n print(e)\r\n\r\n FinalPollEmbed = discord.Embed(title=title+\"[POLL OVER]\", color=0x9B59B6)\r\n PollEmbed.set_author(name=f\"requested by {ctx.message.author.name}\", icon_url=ctx.message.author.avatar_url)\r\n FinalPollEmbed.set_thumbnail(url=self.client.user.avatar_url)\r\n OptionsToEmotes = {0:\":one:\", 1:\":two:\", 2:\":three:\", 3:\":four:\", 4:\":five:\", 5:\":six:\", 6:\":seven:\", 7:\":eight:\", 8:\":nine:\", 9:\":keycap_ten:\"}\r\n OptionCounter= 0\r\n for i in Options:\r\n try:\r\n FinalPollEmbed.add_field(name=\"\\u200b\", value=f\"`{OptionCounter}:` {i}\\t**{EmbedResults[OptionsToEmotes[OptionCounter]][1]}%** with **{EmbedResults[OptionsToEmotes[OptionCounter]][0]}** votes\", inline=False)\r\n OptionCounter += 1\r\n except Exception as e:\r\n print(e)\r\n FinalPollEmbed.set_footer(text=\"expired\")\r\n await message.edit(embed=FinalPollEmbed)\r\n \r\n\r\n except Exception as e:\r\n print(e)\r\n await ctx.channel.send(\"Error, did you use the correct format? (>help Polls for more info)\")\r\n @poll.error\r\n async def poll_error(obj, ctx, error):\r\n if isinstance(error, CommandOnCooldown):\r\n await ctx.channel.send(f\"That command is on a cooldown, try again after **{round(error.retry_after, 2)}s**\")\r\n elif isinstance(error, MissingPermissions):\r\n ToSend = ''\r\n for i in error.missing_perms:\r\n if error.missing_perms[0] == i:\r\n ToSend += str(i)\r\n else:\r\n ToSend += ', ' + str(i)\r\n if len(error.missing_perms) == 1:\r\n await ctx.channel.send(f\"You are missing the following perm: **{ToSend}**\", delete_after=3)\r\n await ctx.message.delete()\r\n else:\r\n await ctx.channel.send(f\"You are missing the following perms: **{ToSend}**\", delete_after=3)\r\n await ctx.message.delete()\r\n\r\n\r\n\r\n\r\n\r\ndef setup(client):\r\n client.add_cog(Polls(client))","sub_path":"cogs/DiscordPoll.py","file_name":"DiscordPoll.py","file_ext":"py","file_size_in_byte":8511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"433891392","text":"#!/user/bin/env python3\n# -*- coding:utf-8 -*-\n\nage = 3\nif age >= 18:\n print('adult')\nelif age >= 6:\n print('teenager')\nelse:\n print('kid')\n\n## 这里返回的是字符串\ns = input('birth: ')\nbirth = int(s)\nif birth < 2000:\n print('00前')\nelse:\n print('00后') ","sub_path":"if.py","file_name":"if.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"581882425","text":"\"\"\"Implement the server side of Socket.IO.\n\n https://github.com/learnboost/socket.io-spec\n\nAh, abstraction! This is a whole convoluted mess to provide some pretty nice\nAPI inside socket resources. Here are the objects involved on the server side,\nfrom the inside out:\n\n Message a Socket.IO message, a colon-delimited set of bytestrings\n Packet a Socket.IO packet, a message or series of framed messages\n Buffer a Socket.IO buffer, buffers incoming and outgoing messages\n Loop an object responsible for repeatedly calling socket.tick\n Socket a Socket.IO socket, maintains state\n Channel an object that represents all connections to a single Resource\n Transport a Socket.IO transport mechanism, does HTTP work\n Resource an HTTP resource, a file on your filesystem, application logic\n Response an HTTP Response message\n Request an HTTP Request message\n\n Engine fits somewhere, handles networking implementation; Buffer and\n Loop attributes point to implementations of the above\n\n\nA specially-crafted HTTP request creates a new Socket. That socket object\nexists until one of these conditions is met:\n\n - the application explicitly disconnects\n - the client explicitly disconnects\n - the client disappears (for some definition of \"disappears\")\n\nA second specially-crafted HTTP request negotiates a Transport. Subsequent\nspecially-crafted HTTP requests are marshalled into socket reads and writes\naccording to the Transport negotiated.\n\nThe Loop object is responsible for running socket.tick until it is told to stop\n(as a result of one of the above three conditions). socket.tick exec's the\nthird page of the application's socket resource in question. This code is\nexpected to block. For ThreadedLoop that means we can't stop the loop inside of\nnative code. The ThreadedBuffer object cooperates with ThreadedLoop, so if your\napplication only ever blocks on socket.recv then you are okay. CooperativeLoops\nshould be immediately terminable assuming your application and its dependencies\ncooperate ;-).\n\n\"\"\"\nfrom aspen import Response\n\nFFFD = u'\\ufffd'.encode('utf-8')\nHEARTBEAT = 15\nTIMEOUT = 10\nTRANSPORTS = ['xhr-polling']\n\nfrom aspen.sockets.channel import Channel\nfrom aspen.sockets.socket import Socket\nfrom aspen.sockets.transport import XHRPollingTransport\n\n\n__sockets__ = {}\n__channels__ = {}\n\n\ndef get(request):\n \"\"\"Takes a Request object and returns a Response or Transport object.\n\n When we get the request it has socket set to a string, the path part after\n *.sock, which is something like 1/websocket/43ef6fe7?foo=bar.\n\n 1 protocol (we only support 1)\n websocket transport\n 43ef6fe7 socket id (sid)\n ?foo=bar querystring\n\n The Socket.IO handshake is a GET request to 1/. We return Response for the\n handshake. After the handshake, subsequent messages are to the full URL as\n above. We return a Transported instance for actual messages.\n\n \"\"\"\n\n # Exit early.\n # ===========\n\n if request.socket is None:\n return None\n\n\n # Parse and validate the socket URL.\n # ==================================\n\n parts = request.socket.split('/')\n nparts = len(parts)\n if nparts not in (2, 3):\n msg = \"Expected 2 or 3 path parts for Socket.IO socket, got %d.\"\n raise Response(400, msg % nparts)\n\n protocol = parts[0]\n if protocol != '1':\n msg = \"Expected Socket.IO protocol version 1, got %s.\"\n raise Response(400, msg % protocol)\n\n\n # Handshake\n # =========\n\n if len(parts) == 2:\n path = request.line.uri.path.raw\n if path in __channels__:\n channel = __channels__[path]\n else:\n channel = Channel(path, request.website.network_engine.Buffer)\n __channels__[path] = channel\n\n socket = Socket(request, channel)\n assert socket.sid not in __sockets__ # sanity check\n __sockets__[socket.sid] = socket\n socket.loop.start()\n\n return socket.shake_hands() # a Response\n\n\n # More than a handshake.\n # ======================\n\n transport = parts[1]\n sid = parts[2]\n\n if transport not in TRANSPORTS:\n msg = \"Expected transport in {%s}, got %s.\"\n msg %= (\",\".join(TRANSPORTS), transport)\n raise Response(400, msg)\n\n if sid not in __sockets__:\n msg = \"Expected %s in cache, didn't find it\"\n raise Response(400, msg % sid)\n\n if type(__sockets__[sid]) is Socket:\n # This is the first request after a handshake. It's not until this\n # point that we know what transport the client wants to use.\n Transport = XHRPollingTransport # XXX derp\n __sockets__[sid] = Transport(__sockets__[sid])\n\n transport = __sockets__[sid]\n return transport\n","sub_path":"aspen/sockets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"86231347","text":"#! /usr/bin/env python3\n\nfrom os import sys, path\nthisdir = path.dirname(path.abspath(__file__))\nsys.path.append(thisdir + \"/IoticAgent\")\n\nfrom IoticAgent import IOT\nfrom IoticAgent.Core.Const import R_FEED # YUK\nclient = IOT.Client()\nrackpi1 = None\n\n\ndef connect():\n \"\"\"connect to Iotic Space, with retries\"\"\"\n global client\n print(\"connecting...\")\n while True:\n try:\n client.start()\n print(\"connected\")\n break\n except:\n print(\"retrying...\")\n\n\ndef disconnect():\n \"\"\"disconnect safely\"\"\"\n print(\"disconnecting...\")\n client.stop()\n print(\"disconnected\")\n\n\ndef bind_thing(name):\n \"\"\"Bind to a thing of a specific name\"\"\"\n print(\"binding to %s....\" % name) \n thing = client.create_thing(name)\n print(\"bound\")\n return thing\n\n\ndef bind_feeds_for_thing(thing):\n \"\"\"Find all feeds for this thing, and knit up a generic callback\"\"\"\n connections = thing.list_connections()\n for key in connections:\n id = connections[key]['id']\n if connections[key]['type'] == R_FEED:\n print(\"feed id %s\" % id)\n feed = thing.follow(id, process_feed_data)\n # hmm, not possible to get_meta on a RemoteFeed\n #meta = feed.get_meta()\n #print(\"just bound feed, metadata=%s\" % str(meta))\n # TODO keep feed and meta in a cache keyed by this thing\n # perhaps auto generate a proxy object based on it's metadata\n\n # try to get last feeddata value\n try:\n data = feed.get_last()\n print(\"last stored data:%s\" % str(data))\n except KeyError as e:\n print(\"No last_data: %s\" % e)\n\ndef subscriptions_changed(data):\n print(\"subscription count changed:%s\" % str(data))\n #TODO are there any parameters?\n #seems this is client wide (i.e. all things)\n #so we have to for each thing call list_connections\n #and basically diff against a local cache and work out what changed\n #and propagate those changes through the app.\n\n\ndef process_feed_data(args):\n \"\"\"feed data for a specific feed is routed here\"\"\"\n #print(\"process_feed_data:%s\" % args)\n data = args['data']\n pid = args['pid']\n #print(\"feed_data:%s\" % data)\n value = data['value']\n print(\"feed %s generates value:%s\" % (pid, value))\n\n\n# main processing loop\ndef main_loop():\n tick = 0\n import time\n while True:\n time.sleep(1)\n tick += 1\n print(\"tick %d\" % tick)\n\n\n#---- MAIN ----\n\nconnect()\n\ntry:\n print(\"connected=%s\" % str(client.is_connected()))\n\n rackpi1 = bind_thing(\"rackpi1\")\n bind_feeds_for_thing(rackpi1)\n client.register_callback_subscription(subscriptions_changed)\n\n main_loop()\n\nfinally:\n disconnect()\n\n","sub_path":"test1/hello2.py","file_name":"hello2.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"320782775","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport urllib.parse\nfrom lxml import etree\nfrom ..items import Job51SlaveItem\nimport datetime\nfrom scrapy_redis.spiders import RedisSpider\n\n\nclass SlaveSpider(RedisSpider):\n name = 'slave'\n allowed_domains = ['51job.com']\n redis_key = 'job51:slave_url'\n\n\n def make_requests_from_url(self, data: str):\n result = data.split(\"|\")\n return scrapy.Request(\n url=result[0],\n callback=self.parse_job_list,\n meta={'keyword': result[1]},\n dont_filter=True\n )\n\n def parse_job_list(self,response):\n job_list = response.xpath(\"//div[@id='resultList']/div[@class='el']\")\n keyword = response.meta['keyword']\n for job in job_list:\n yield scrapy.Request(\n url=job.xpath(\"p/span/a/@href\").extract_first(''),\n callback=self.parse_job_info,\n meta={'keyword':keyword},\n dont_filter=False\n )\n\n def parse_job_info(self,response):\n html = etree.HTML(response.text)\n\n job = html.xpath(\"//div[@class='cn']/h1/text()\") #职位\n company = html.xpath(\"//a[@class='catn']/text()\") #公司名称\n salary = html.xpath(\"//div[@class='cn']//strong/text()\") #工资\n contact = html.xpath(\"//div[@class='bmsg inbox']//p[@class='fp']/text()\") #联系方式\n message_company = html.xpath(\"//div[@class='tmsg inbox']/text()\") #公司信息\n job_category = html.xpath(\"//div[@class='mt10']//p[@class='fp']/a/text()\") #职能类别\n job_information = html.xpath(\"//div[@class='bmsg job_msg inbox']/p/text()\") #职位信息\n place = html.xpath(\"//p[@class='msg ltype']/text()\") #工作地点,招聘要点\n welfare = html.xpath(\"//div[@class='t1']/span/text()\") #福利\n company_message = html.xpath(\"//div[@class='com_tag']/p/text()\") #公司详细信息\n company_direction = html.xpath(\"//p[@class='at']//a/text()\") #公司类型\n item = Job51SlaveItem()\n try:\n item['place'] = place[0].strip() #工作地点\n except:\n item['place'] = None\n try:\n item['requirement'] = \"\".join(\",\".join(place[1:]).split()) # 招聘要点\n except:\n item['requirement'] = None\n try:\n item['job'] = job[0].strip() #职位名称\n except:\n item['job'] = None\n try:\n item['company'] = company[0].strip() #公司名称\n except:\n item['company'] = None\n try:\n item['salary'] = \",\".join(salary).strip() #工资\n except:\n item['salary'] = None\n try:\n item['contact'] = contact[1].strip() #联系方式\n except:\n item['contact'] = None\n try:\n item['job_category'] = \"\".join(\",\".join(job_category).split()) #职能类别\n except:\n item['job_category'] = None\n try:\n item['job_information'] = \"\".join(job_information).strip() #职位信息\n except:\n item['job_information'] = None\n try:\n item['welfare'] = \",\".join(welfare).strip()#福利\n except:\n item['welfare'] = None\n try:\n item['company_category'] = company_message[0].strip() #公司性质\n except:\n item['company_category'] = None\n try:\n item['company_member'] = company_message[1].strip() #公司人数\n except:\n item['company_member'] = None\n try:\n item['company_direction'] = \",\".join(company_direction).strip() #公司类别\n except:\n item['company_direction'] = None\n try:\n item['company_information'] = \"\".join(message_company).strip() #公司类别\n except:\n item['company_information'] = None\n item['keyword'] = response.meta['keyword']\n item['link'] = response.url\n item['time'] = str(datetime.date.today())\n yield item\n","sub_path":"job51_slave/job51_slave/spiders/slave.py","file_name":"slave.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"116533137","text":"import copy\nimport itertools\nimport math\nimport re\nimport string\nfrom collections import defaultdict, OrderedDict\nfrom pyleri import Grammar, Regex, Choice, Sequence, Token, Keyword, Repeat, Ref\n\nimport explanation_rewrites\n\nclass ExplanationGrammar(Grammar):\n name_inner = Regex('[A-Za-z0-9:\\'_#]+')\n quoted_name = Regex('\"[A-Za-z0-9:\\'_ #]+\"')\n angle_name = Regex('<[A-Za-z0-9:\\'_ #]+>')\n imm_name = Regex('#[0-9]+')\n name = Choice(quoted_name, angle_name, imm_name, name_inner)\n types = Choice(Keyword('WREG_ZR'),\n Keyword('XREG_ZR'),\n Keyword('WREG_SP'),\n Keyword('XREG_SP'),\n Keyword('FPREG'),\n Keyword('FPREG_128'),\n Keyword('FPREG_64'),\n Keyword('FPREG_32'),\n Keyword('FPREG_16'),\n Keyword('FPREG_8'),\n Keyword('IMMEDIATE'),\n Keyword('SIGNED_IMMEDIATE'),\n Keyword('BITMASK_IMMEDIATE_32'),\n Keyword('BITMASK_IMMEDIATE_64'),\n Keyword('CONDITION'),\n Keyword('INVERTED_CONDITION'),\n Keyword('SYSREG'),\n Keyword('PREFETCH_OP'),\n Keyword('AT_INSTRUCTION'),\n Keyword('TLBI_INSTRUCTION'),\n Keyword('IC_INSTRUCTION'),\n Keyword('DC_INSTRUCTION'),\n Keyword('CONSTANT'),\n Keyword('BARRIER_SCOPE'))\n type_property = Sequence(Keyword('TYPE'), types)\n bits = Regex('\\'[0-9]+\\'')\n integer = Regex('[0-9]+')\n number = Choice(bits, integer)\n multiple = Sequence(name, Token('*'), number)\n division = Sequence(name, Token('/'), number)\n addition = Sequence(name, Token('+'), number)\n subtraction = Sequence(name, Token('-'), number)\n subtraction_from = Sequence(number, Token('-'), name)\n encoded_property = Sequence(Keyword('ENCODED'), Choice(name, multiple, division, addition, subtraction, subtraction_from))\n default_property = Sequence(Keyword('DEFAULT'), Choice(name, number))\n multiple_of_property = Sequence(Keyword('MULTIPLE_OF'), number)\n constant_value_property = Sequence(Keyword('CONSTANT_VALUE'), imm_name)\n expr_property = Sequence(Keyword('EXPR'), Choice(name, multiple, division, addition, subtraction, subtraction_from, Keyword('PRESENCE')))\n prop = Choice(type_property,\n encoded_property,\n default_property,\n multiple_of_property,\n expr_property,\n constant_value_property)\n START = Repeat(prop, mi=1)\n\nexp_grammar = ExplanationGrammar()\n\nclass Explanation:\n def __init__(self, type, props, values=None):\n self.type = type\n self.props = props\n if values == None:\n self.values = []\n else:\n self.values = values\n\n def __str__(self):\n return 'Explanation(type={!r}, props={!r}, values={!r})'.format(self.type, self.props, self.values)\n\ndef unquote_name(name):\n assert name.element.name == 'name'\n inner_name = name.children[0]\n if inner_name.element.name == 'name_inner' or inner_name.element.name == 'imm_name':\n return inner_name.string\n elif inner_name.element.name == 'quoted_name' or inner_name.element.name == 'angle_name':\n return inner_name.string[1:-1]\n else:\n 'unknown property type in unquote_name: ' + name.element.name\n\ndef prop_to_kv(prop):\n assert prop.element.name == 'prop'\n inner_prop = prop.children[0]\n if inner_prop.element.name == 'type_property':\n type_kw = 'asm_' + inner_prop.children[1].children[0].string.lower()\n return 'type', type_kw\n elif inner_prop.element.name == 'encoded_property':\n if inner_prop.children[1].children[0].element.name == 'name':\n encoded_in = unquote_name(inner_prop.children[1].children[0])\n elif inner_prop.children[1].children[0].element.name == 'multiple':\n name = unquote_name(inner_prop.children[1].children[0].children[0])\n multiple = int(inner_prop.children[1].children[0].children[2].string)\n pow2 = int(math.log2(multiple))\n assert 2 ** pow2 == multiple, 'non-power-of-2 multiple in encoding'\n assert pow2 >= 1\n encoded_in = \"({}):'{}'\".format(name, '0' * pow2)\n elif inner_prop.children[1].children[0].element.name == 'division':\n assert False, 'division not yet implemented'\n elif inner_prop.children[1].children[0].element.name == 'subtraction':\n assert False, 'subtraction not yet implemented'\n elif inner_prop.children[1].children[0].element.name == 'subtraction_from':\n name = unquote_name(inner_prop.children[1].children[0].children[2])\n minuend = int(inner_prop.children[1].children[0].children[0].string)\n encoded_in = '{} - {}'.format(minuend, name)\n else:\n assert False, 'unknown name type in grammar: ' + inner_prop.children[1].children[0].element.name\n return 'encoded_in', encoded_in\n elif inner_prop.element.name == 'multiple_of_property':\n multiple_of = inner_prop.children[1].children[0].string\n return 'multiple_of', multiple_of\n elif inner_prop.element.name == 'default_property':\n default = inner_prop.children[1].children[0].string\n return 'default', default\n elif inner_prop.element.name == 'expr_property':\n expr = inner_prop.children[1].children[0].string\n return 'expr', expr\n elif inner_prop.element.name == 'constant_value_property':\n constant = inner_prop.children[1].string\n return 'constant', constant\n else:\n assert False, 'unknown property type in grammar: ' + inner_prop.element.name\n\ndiv_expr_re = re.compile(r'?\\s*/\\s*([0-9]+)')\n\ndef apply_div_exprs(d):\n if 'expr' in d and d['expr'] != 'PRESENCE':\n match = div_expr_re.match(d['expr'])\n if match:\n multiple = int(match.group(1))\n pow2 = int(math.log2(multiple))\n assert 2 ** pow2 == multiple, 'non-power-of-2 division in expr'\n assert pow2 >= 1\n d['encoded_in'] = \"({}):'{}'\".format(d['encoded_in'], '0' * pow2)\n if 'multiple_of' in d:\n del d['multiple_of']\n del d['expr']\n else:\n assert False, 'unparsable div-expr'\n\ndef apply_hacks(d):\n for k, v in d.items():\n if v == '\"LSL|UXTW\"':\n d[k] = '\"UXTW\"'\n if v == '\"LSL|UXTX\"':\n d[k] = '\"UXTX\"'\n\nbitlit_re = re.compile(r\"'([01]+?)'\")\n\ndef asl_bitexpr_to_sail(expr):\n expr = bitlit_re.sub(r'0b\\1', expr)\n expr = expr.replace(':', '@')\n return expr\n\nbuiltin_explanations = OrderedDict([\n ('_SUBS_64S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_64', {})),\n ('_SUB_64_addsub_ext', Explanation('asm_extendedreg_hack_twoSP_64', {})),\n ('_ADDS_64S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_64', {})),\n ('_ADD_64_addsub_ext', Explanation('asm_extendedreg_hack_twoSP_64', {})),\n ('_SUBS_32S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_32', {})),\n ('_SUB_32_addsub_ext', Explanation('asm_extendedreg_hack_twoSP_32', {})),\n ('_ADDS_32S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_32', {})),\n ('_ADD_32_addsub_ext', Explanation('asm_extendedreg_hack_twoSP_32', {})),\n ('_CMN_ADDS_32S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_32', {})),\n ('_CMN_ADDS_64S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_64', {})),\n ('_CMP_SUBS_32S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_32', {})),\n ('_CMP_SUBS_64S_addsub_ext', Explanation('asm_extendedreg_hack_oneSP_64', {})),\n ('_LSL_UBFM_32M_bitfield', Explanation('lsl_shift_hack_32', {})),\n ('_LSL_UBFM_64M_bitfield', Explanation('lsl_shift_hack_64', {})),\n ('_BFXIL_BFM_32M_bitfield', Explanation('lsb_width_hack', {})),\n ('_BFXIL_BFM_64M_bitfield', Explanation('lsb_width_hack', {})),\n ('_UBFX_UBFM_32M_bitfield', Explanation('lsb_width_hack', {})),\n ('_UBFX_UBFM_64M_bitfield', Explanation('lsb_width_hack', {})),\n ('_UBFIZ_UBFM_32M_bitfield', Explanation('lsb_mod_hack_32', {})),\n ('_UBFIZ_UBFM_64M_bitfield', Explanation('lsb_mod_hack_64', {})),\n ('_SBFX_SBFM_32M_bitfield', Explanation('lsb_width_hack', {})),\n ('_SBFX_SBFM_64M_bitfield', Explanation('lsb_width_hack', {})),\n ('_SBFIZ_SBFM_32M_bitfield', Explanation('lsb_mod_hack_32', {})),\n ('_SBFIZ_SBFM_64M_bitfield', Explanation('lsb_mod_hack_64', {})),\n ('_BFC_BFM_32M_bitfield', Explanation('lsb_mod_hack_32', {})),\n ('_BFC_BFM_64M_bitfield', Explanation('lsb_mod_hack_64', {})),\n ('_BFI_BFM_32M_bitfield', Explanation('lsb_mod_hack_32', {})),\n ('_BFI_BFM_64M_bitfield', Explanation('lsb_mod_hack_64', {})),\n ('_CNEG_CSNEG_32_condsel', Explanation('matching_Wn', {})),\n ('_CNEG_CSNEG_64_condsel', Explanation('matching_Xn', {})),\n ('_CINC_CSINC_32_condsel', Explanation('matching_Wn', {})),\n ('_CINC_CSINC_64_condsel', Explanation('matching_Xn', {})),\n ('_CINV_CSINV_32_condsel', Explanation('matching_Wn', {})),\n ('_CINV_CSINV_64_condsel', Explanation('matching_Xn', {})),\n ('_ROR_EXTR_32_extract', Explanation('matching_Wn', {})),\n ('_ROR_EXTR_64_extract', Explanation('matching_Xn', {})),\n ('_MOV_MOVZ_32_movewide', Explanation('movewide_imm_hack_32', {})),\n ('_MOV_MOVZ_64_movewide', Explanation('movewide_imm_hack_64', {})),\n ('_MOV_MOVN_32_movewide', Explanation('movewide_inverted_imm_hack_32', {})),\n ('_MOV_MOVN_64_movewide', Explanation('movewide_inverted_imm_hack_64', {})),\n ('_B_only_condbranch', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_B_only_branch_imm', Explanation('label_hack_28', {'encoded_in': 'imm26@0b00'})),\n ('_BL_only_branch_imm', Explanation('label_hack_28', {'encoded_in': 'imm26@0b00'})),\n ('_CBNZ_32_compbranch', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_CBNZ_64_compbranch', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_CBZ_32_compbranch', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_CBZ_64_compbranch', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_TBZ_only_testbranch', Explanation('label_hack_16', {'encoded_in': 'imm14@0b00'})),\n ('_TBNZ_only_testbranch', Explanation('label_hack_16', {'encoded_in': 'imm14@0b00'})),\n ('_PRFM_P_loadlit', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_LDR_32_loadlit', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_LDR_64_loadlit', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_LDRSW_32_loadlit', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_LDRSW_64_loadlit', Explanation('label_hack_21', {'encoded_in': 'imm19@0b00'})),\n ('_ADRP_only_pcreladdr', Explanation('label_hack_33', {'encoded_in': 'immhi@immlo@0b000000000000'})),\n ('_ADR_only_pcreladdr', Explanation('label_hack_21', {'encoded_in': 'immhi@immlo'})),\n ('_CASP_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rs'})),\n ('_CASP_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rt'})),\n ('_CASPA_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rs'})),\n ('_CASPA_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rt'})),\n ('_CASPAL_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rs'})),\n ('_CASPAL_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rt'})),\n ('_CASPL_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rs'})),\n ('_CASPL_CP32_ldstexcl', Explanation('casp_hack_wplusone', {'encoded_in': 'Rt'})),\n ('_CASP_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rs'})),\n ('_CASP_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rt'})),\n ('_CASPA_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rs'})),\n ('_CASPA_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rt'})),\n ('_CASPAL_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rs'})),\n ('_CASPAL_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rt'})),\n ('_CASPL_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rs'})),\n ('_CASPL_CP64_ldstexcl', Explanation('casp_hack_xplusone', {'encoded_in': 'Rt'})),\n])\n\n\ndef apply_enclist_hacks(enclist):\n supplements = {\n 'STSMAXB_LDSMAXB_32_memop': 'STSMAXLB_LDSMAXLB_32_memop',\n 'STSMAXH_LDSMAXH_32_memop': 'STSMAXLH_LDSMAXLH_32_memop',\n 'STUMAXB_LDUMAXB_32_memop': 'STUMAXLB_LDUMAXLB_32_memop',\n 'STUMAXH_LDUMAXH_32_memop': 'STUMAXLH_LDUMAXLH_32_memop',\n 'STSMAX_LDSMAX_32_memop': 'STSMAXL_LDSMAXL_32_memop',\n 'STSMAX_LDSMAX_64_memop': 'STSMAXL_LDSMAXL_64_memop',\n 'STUMAX_LDUMAX_32_memop': 'STUMAXL_LDUMAXL_32_memop',\n 'STUMAX_LDUMAX_64_memop': 'STUMAXL_LDUMAXL_64_memop',\n 'STSMINB_LDSMINB_32_memop': 'STSMINLB_LDSMINLB_32_memop',\n 'STSMINH_LDSMINH_32_memop': 'STSMINLH_LDSMINLH_32_memop',\n 'STUMINB_LDUMINB_32_memop': 'STUMINLB_LDUMINLB_32_memop',\n 'STUMINH_LDUMINH_32_memop': 'STUMINLH_LDUMINLH_32_memop',\n 'STSMIN_LDSMIN_32_memop': 'STSMINL_LDSMINL_32_memop',\n 'STSMIN_LDSMIN_64_memop': 'STSMINL_LDSMINL_64_memop',\n 'STUMIN_LDUMIN_32_memop': 'STUMINL_LDUMINL_32_memop',\n 'STUMIN_LDUMIN_64_memop': 'STUMINL_LDUMINL_64_memop',\n 'STCLRB_LDCLRB_32_memop': 'STCLRLB_LDCLRLB_32_memop',\n 'STCLRH_LDCLRH_32_memop': 'STCLRLH_LDCLRLH_32_memop',\n 'STCLR_LDCLR_32_memop': 'STCLRL_LDCLRL_32_memop',\n 'STCLR_LDCLR_64_memop': 'STCLRL_LDCLRL_64_memop',\n 'STSETB_LDSETB_32_memop': 'STSETLB_LDSETLB_32_memop',\n 'STSETH_LDSETH_32_memop': 'STSETLH_LDSETLH_32_memop',\n 'STSET_LDSET_32_memop': 'STSETL_LDSETL_32_memop',\n 'STSET_LDSET_64_memop': 'STSETL_LDSETL_64_memop',\n 'STADDB_LDADDB_32_memop': 'STADDLB_LDADDLB_32_memop',\n 'STADDH_LDADDH_32_memop': 'STADDLH_LDADDLH_32_memop',\n 'STADD_LDADD_32_memop': 'STADDL_LDADDL_32_memop',\n 'STADD_LDADD_64_memop': 'STADDL_LDADDL_64_memop',\n 'STEORB_LDEORB_32_memop': 'STEORLB_LDEORLB_32_memop',\n 'STEORH_LDEORH_32_memop': 'STEORLH_LDEORLH_32_memop',\n 'STEOR_LDEOR_32_memop': 'STEORL_LDEORL_32_memop',\n 'STEOR_LDEOR_64_memop': 'STEORL_LDEORL_64_memop',\n }\n\n for indicator, missing in supplements.items():\n if indicator in enclist and missing not in enclist:\n enclist.append(missing)\n\n\ndef read_asm_explanations(instr_name, xml):\n explanations = copy.copy(builtin_explanations)\n for exp in xml.findall('.//explanation'):\n symbol = ''.join(exp.find('.//symbol').itertext())\n account = exp.find('.//account')\n definition = exp.find('.//definition/table/..')\n if account is not None and definition is not None:\n assert False, 'both account and definition given in explanation tag'\n elif account is not None:\n orig_text = text = ''.join(exp.find('.//account/intro').itertext())\n for regex, rep in explanation_rewrites.rewrites:\n text = regex.sub(rep, text)\n parse = exp_grammar.parse(text)\n assert parse.is_valid\n start = parse.tree.children[0] if parse.tree.children else parse.tree # pyleri bug workaround?\n props = dict(prop_to_kv(prop) for prop in start.children)\n apply_div_exprs(props)\n assert 'type' in props\n if 'encoded_in' in props:\n props['encoded_in'] = asl_bitexpr_to_sail(props['encoded_in'])\n apply_hacks(props)\n #print('{:>60} ** {:>15} ** {!s}'.format(instr_name, symbol, props))\n enclist = exp.get('enclist').split(', ')\n apply_enclist_hacks(enclist)\n for enc in enclist:\n newsym = symbol + '_' + enc\n assert newsym not in explanations\n explanations[newsym] = Explanation(props['type'], props)\n elif definition is not None:\n encoded_in = definition.get('encodedin')\n assert encoded_in\n orig_text = text = ''.join(exp.find('.//definition/intro').itertext())\n for regex, rep in explanation_rewrites.rewrites:\n text = regex.sub(rep, text)\n parse = exp_grammar.parse(text)\n assert parse.is_valid\n start = parse.tree.children[0] if parse.tree.children else parse.tree # pyleri bug workaround?\n props = dict(prop_to_kv(prop) for prop in start.children)\n #print('{:>60} ** {:>15} ** {!s} ** {}'.format(instr_name, symbol, props, orig_text))\n\n # we assume the entries are in the same order as in encoded_in\n props['encoded_in'] = encoded_in\n table = definition.find('table')\n values = []\n for row in table.findall('.//row')[1:]:\n raw_bitfields = ''.join([e.text for e in row.findall('entry[@class=\"bitfield\"]')])\n n_bits = len(raw_bitfields)\n props['arg_type'] = 'bits({})'.format(n_bits)\n bitfields = asl_bitexpr_to_sail(\"'\" + raw_bitfields + \"'\")\n value = '\"' + row.find('entry[@class=\"symbol\"]').text + '\"'\n values.append((bitfields, value))\n assert 'type' in props\n apply_hacks(props)\n enclist = exp.get('enclist').split(', ')\n apply_enclist_hacks(enclist)\n for enc in enclist:\n newsym = symbol + '_' + enc\n assert newsym not in explanations\n explanations[newsym] = Explanation('TABLE', props, values)\n else:\n assert False\n return explanations\n\ndef sanitize(name):\n new_name = \"\"\n for c in name:\n if c not in string.ascii_letters and c not in string.digits:\n new_name += \"_\"\n else:\n new_name += c\n return new_name\n\nexclude_explanations_res = [\n r'<(R|extend)>_(ADD|SUB)S?_(32|64)S?_addsub_ext', # width specifier from extended reg addsub, contains unknowns and is hacked away elsewhere\n r'<(R|extend)>_CM(P|N)_(ADD|SUB)S?_(32|64)S?_addsub_ext', # width specifier from extended reg addsub, contains unknowns and is hacked away elsewhere\n]\nexclude_explanations_res = [re.compile(r) for r in exclude_explanations_res]\n\ndef emit_explanation(file, previous_explanations, name, exp):\n assert isinstance(exp, Explanation)\n if exp.type == 'TABLE' and not any(r.match(name) for r in exclude_explanations_res):\n mapping_name = sanitize(name)\n if mapping_name in previous_explanations:\n return\n previous_explanations.add(mapping_name)\n clauses = [' {} <-> {}'.format(k, v) for k, v in exp.values if v != '\"RESERVED\"']\n top = 'mapping {} : {} <-> string = {{'.format(mapping_name, exp.props['arg_type'])\n bottom = '}'\n print(top, file=file)\n print(',\\n'.join(clauses), file=file)\n print(bottom, file=file)\n","sub_path":"bin/explanations.py","file_name":"explanations.py","file_ext":"py","file_size_in_byte":21532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"111579071","text":"import torch.nn as nn\nimport torch\nfrom torch.autograd import Variable\nimport torch.utils.model_zoo as model_zoo\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\nBN_MOMENTUM = 0.1\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)\n self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,\n bias=False)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion,\n momentum=BN_MOMENTUM)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, num_classes, block, layers, **kwargs):\n super(ResNet, self).__init__()\n self.inplanes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.conv6 = nn.Conv2d(2048, 256, kernel_size=3, stride=2, padding=1)\n self.conv7 = nn.Conv2d( 256, 256, kernel_size=3, stride=2, padding=1)\n\n\n def forward(self, inputs):\n img_batch = inputs\n x = self.conv1(img_batch)\n x = self.bn1(x)\n x = self.relu(x)\n x0 = self.maxpool(x)\n\n x1 = self.layer1(x0)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n\n return [x2, x3, x4]\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = [block(self.inplanes, planes, stride, downsample)]\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def freeze_bn(self):\n '''Freeze BatchNorm layers.'''\n for layer in self.modules():\n if isinstance(layer, nn.BatchNorm2d):\n layer.eval()\n\n\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\nclass PrunedBottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, activated_planes=None, stride=1, downsample=None):\n super(PrunedBottleneck, self).__init__()\n self.conv1 = conv1x1(inplanes, activated_planes[0])\n self.bn1 = nn.BatchNorm2d(activated_planes[0])\n self.conv2 = conv3x3(activated_planes[0], activated_planes[1], stride)\n self.bn2 = nn.BatchNorm2d(activated_planes[1])\n self.conv3 = conv1x1(activated_planes[1], planes * self.expansion)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def add_residual(self, x, y):\n y = self.conv3(y)\n y = self.bn3(y)\n if self.downsample is not None:\n x = self.downsample(x)\n y += x\n return self.relu(y)\n\n def forward(self, x):\n identity = x\n\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n\n out = self.add_residual(identity, x)\n\n return out\n\ndef get_str_num(value, str):\n return str.count(value,0,len(str))\n\ndef get_activate_channel_norm(model, global_percent=0.2):\n import numpy as np\n index_weights = []\n layer_keep = 0.01\n new_indices = []\n layer_channels_weights = []\n model = model.backbone\n for layer in model.modules():\n if isinstance(layer, nn.Sequential) and \"Bottleneck\" in str(layer):\n for m1 in layer.modules() :\n if \"Bottleneck\" in str(m1) and len(list(m1.named_children())) > 6 and len(list(m1.named_children())) != 23 and len(list(m1.named_children())) != 36 and get_str_num(\"Bottleneck\", str(m1)) !=8: #\n channels_1, N_1, H_1, W_1 = m1.conv1.weight.data.shape\n channels_2, N_2, H_2, W_2 = m1.conv2.weight.data.shape\n channels_sum_conv1 = torch.sum(m1.conv1.weight.data.abs().reshape((channels_1, -1)), dim=1)\n channels_sum_conv2 = torch.sum(m1.conv2.weight.data.abs().reshape((channels_2, -1)), dim=1)\n layer_channels_weights.append(channels_sum_conv1 / (N_1 * H_1 * W_1))\n layer_channels_weights.append(channels_sum_conv2 / (N_2 * H_2 * W_2))\n index_weights.extend(channels_sum_conv1.cpu().numpy() / (N_1 * H_1 * W_1))\n index_weights.extend(channels_sum_conv2.cpu().numpy() / (N_2 * H_2 * W_2))\n sort_weights = np.sort(index_weights)\n # print(\"sorted weights is\", sort_weights)\n # print(\"global_percent is\", global_percent)\n thr_weight = sort_weights[int(len(sort_weights) * global_percent)]\n # print(\"thr is\", thr_weight)\n for curren_layer_weights in layer_channels_weights:\n # print(\"curren_layer_weights is\", curren_layer_weights)\n mask = curren_layer_weights.cuda().gt(thr_weight).float()\n # print(\"mask is\", mask)\n min_channel_num = int(len(curren_layer_weights) * layer_keep) if int(len(curren_layer_weights) * layer_keep) > 0 else 1\n if int(torch.sum(mask)) < min_channel_num:\n _, sorted_index_weights = torch.sort(curren_layer_weights, descending=True)\n mask[sorted_index_weights[:min_channel_num]] = 1.\n new_indices.append([i for i, x in enumerate(mask.cpu().numpy()) if x == 1])\n saved_channels = []\n for indice in new_indices:\n saved_channels.append(len(indice))\n print(\"warming: saved channels is: \", saved_channels)\n print(\"warming: new indices is: \", new_indices)\n return new_indices, saved_channels\n\ndef get_activate_channel_sliming(model, global_percent=0.2):\n import numpy as np\n layer_keep = 0.01\n new_indices = []\n ori_channels = []\n layer_bn_weights = []\n if isinstance(model, torch.nn.DataParallel):\n model = model.module\n model = model.backbone\n bn_weights = []\n for layer in model.modules():\n if isinstance(layer, nn.Sequential) and \"Bottleneck\" in str(layer):\n for m1 in layer.modules() :\n if \"Bottleneck\" in str(m1) and len(list(m1.named_children())) > 6 and len(list(m1.named_children())) != 23 and len(list(m1.named_children())) != 36 and get_str_num(\"Bottleneck\", str(m1)) !=8: #\n bn_weights.extend(torch.abs(m1.bn1.weight.data).cpu().numpy())\n layer_bn_weights.append(torch.abs(m1.bn1.weight.data) )\n ori_channels.append(torch.abs(m1.bn1.weight.data).shape[0])\n bn_weights.extend(torch.abs(m1.bn2.weight.data).cpu().numpy())\n layer_bn_weights.append(torch.abs(m1.bn2.weight.data))\n ori_channels.append(torch.abs(m1.bn2.weight.data).shape[0])\n sort_bn_weights = np.sort(bn_weights)\n # print(\"sorted weights is\", sort_bn_weights)\n # print(\"global_percent is\", global_percent)\n thr_bn_weight = sort_bn_weights[int(len(sort_bn_weights) * global_percent)]\n # print(\"thr is\", thr_bn_weight)\n for curren_layer_weights in layer_bn_weights:\n # print(\"curren_layer_weights is\", curren_layer_weights)\n mask = curren_layer_weights.cuda().gt(thr_bn_weight).float()\n # print(\"mask is\", mask)\n min_channel_num = int(len(curren_layer_weights) * layer_keep) if int(len(curren_layer_weights) * layer_keep) > 0 else 1\n if int(torch.sum(mask)) < min_channel_num:\n _, sorted_index_weights = torch.sort(curren_layer_weights, descending=True)\n mask[sorted_index_weights[:min_channel_num]] = 1.\n new_indices.append([i for i, x in enumerate(mask.cpu().numpy()) if x == 1])\n saved_channels = []\n for indice in new_indices:\n saved_channels.append(len(indice))\n print(\"warming: orignal channels is : \", ori_channels)\n print(\"warming: saved channels is : \", saved_channels)\n print(\"warming: new indices is : \", new_indices)\n return new_indices, saved_channels\n\n\n\n sort_weights = np.sort(index_weights)\n # print(\"sorted weights is\", sort_weights)\n # print(\"global_percent is\", global_percent)\n thr_weight = sort_weights[int(len(sort_weights) * global_percent)]\n # print(\"thr is\", thr_weight)\n for curren_layer_weights in layer_channels_weights:\n # print(\"curren_layer_weights is\", curren_layer_weights)\n mask = curren_layer_weights.cuda().gt(thr_weight).float()\n # print(\"mask is\", mask)\n min_channel_num = int(len(curren_layer_weights) * layer_keep) if int(len(curren_layer_weights) * layer_keep) > 0 else 1\n if int(torch.sum(mask)) < min_channel_num:\n _, sorted_index_weights = torch.sort(curren_layer_weights, descending=True)\n mask[sorted_index_weights[:min_channel_num]] = 1.\n new_indices.append([i for i, x in enumerate(mask.cpu().numpy()) if x == 1])\n saved_channels = []\n for indice in new_indices:\n saved_channels.append(len(indice))\n print(\"warming: saved channels is: \", saved_channels)\n print(\"warming: new indices is: \", new_indices)\n return new_indices, saved_channels\n\nclass PrunedResNet(nn.Module):\n def __init__(self, num_class, layers, activate_channels_list, save_channels_list):\n super(PrunedResNet, self).__init__()\n # self.activated_channels = net.activated_channels.tolist()\n self.save_channels_list = save_channels_list\n self.activate_channels_list = activate_channels_list\n self.num_class = num_class\n self.inplanes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer_count = 0\n block = PrunedBottleneck\n self.layer1 = self._make_layer_prune(block, 64, layers[0])\n self.layer2 = self._make_layer_prune(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer_prune(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer_prune(block, 512, layers[3], stride=2)\n\n self.proportion = 0.5\n\n def _make_layer_prune(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes*block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n nn.BatchNorm2d(planes * block.expansion),\n )\n layers = []\n local_activated = self.save_channels_list[self.layer_count:self.layer_count+2]\n layers.append(block(self.inplanes, planes, local_activated, stride=stride, downsample=downsample))\n self.layer_count += 2\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n local_activated = self.save_channels_list[self.layer_count:self.layer_count+2]\n layers.append(block(self.inplanes, planes, local_activated))\n self.layer_count += 2\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x0 = self.maxpool(x)\n x1 = self.layer1(x0)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n return [x2, x3, x4]\n\ndef prune_net_parameter_init(prune_net, ori_net):\n count = 0\n import numpy as np\n indices = prune_net.backbone.activate_channels_list\n print(\"indices is\", indices)\n if isinstance(ori_net, torch.nn.DataParallel):\n ori_net = ori_net.module\n prune_net.backbone.conv1.weight.data = ori_net.backbone.conv1.weight.data\n prune_net.backbone.bn1.weight.data = ori_net.backbone.bn1.weight.data\n prune_net.backbone.bn1.bias.data = ori_net.backbone.bn1.bias.data\n for m1, m2 in zip(prune_net.modules(), ori_net.modules()):\n if isinstance(m1, PrunedBottleneck):\n index = indices[count]\n # prune\n print(\"---copying block index {}...\".format(count+1))\n m1.conv1.weight.data = m2.conv1.weight.data[index, :, :, :]\n m1.bn1.weight.data = m2.bn1.weight.data[index]\n m1.bn1.bias.data = m2.bn1.bias.data[index]\n count += 1\n\n index = indices[count]\n print(\"---copying block index {}...\".format(count + 1))\n temp = m2.conv2.weight.data[:, indices[count-1], :, :]\n m1.conv2.weight.data = temp[index, :, :, :]\n m1.bn2.weight.data = m2.bn2.weight.data[index]\n m1.bn2.weight.data = m2.bn2.bias.data[index]\n count += 1\n\n m1.conv3.weight.data = m2.conv3.weight.data[:, index, :, :]\n m1.bn3.weight.data = m2.bn3.weight.data\n m1.bn3.weight.data = m2.bn3.bias.data\n if m1.downsample is not None:\n for dm1, dm2 in zip(m1.downsample.modules(), m2.downsample.modules()):\n if isinstance(dm1, nn.Conv2d):\n dm1.weight.data = dm2.weight.data\n if isinstance(dm1, nn.BatchNorm2d):\n dm1.weight.data = dm2.weight.data\n dm1.bias.data = dm2.bias.data\n print(\"--------------------------\")\n if isinstance(m1, nn.Linear):\n m1.weight.data = m2.weight.data\n m1.bias.data = m2.bias.data\n\n # for m1 in prune_net.backbone.modules():\n # if isinstance(m1, nn.Conv2d):\n # print(m1.weight.shape)\n return prune_net\n\ndef pruning(prune_net, ori_net):\n prune_net = prune_net_parameter_init(prune_net, ori_net)\n return prune_net\n\ndef prune_resnet_50(num_classes, activate_channels_list, save_channels_list, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n # model = PrunedResNet(net, num_classes, PrunedBottleneck, [3, 4, 6, 3], **kwargs)\n model = PrunedResNet(num_classes, [3, 4, 6, 3], activate_channels_list, save_channels_list, **kwargs)\n return model\n\ndef prune_resnet_101(num_classes, activate_channels_list, save_channels_list, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n # model = PrunedResNet(net, num_classes, PrunedBottleneck, [3, 4, 6, 3], **kwargs)\n model = PrunedResNet(num_classes, [3, 4, 23, 3], activate_channels_list, save_channels_list, **kwargs)\n return model\n\ndef prune_resnet_152(num_classes, activate_channels_list, save_channels_list, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n # model = PrunedResNet(net, num_classes, PrunedBottleneck, [3, 4, 6, 3], **kwargs)\n model = PrunedResNet(num_classes, [3, 8, 36, 3], activate_channels_list, save_channels_list, **kwargs)\n return model\n\ndef resnet18(num_classes, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(num_classes, BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18'], model_dir='.'), strict=False)\n return model\n\nif __name__ == \"__main__\":\n model = ResNet(5, Bottleneck, [3, 4, 6, 3])\n model.training = False\n pred = model(Variable(torch.randn(2, 3, 224, 224)))\n for i in range(len(pred)):\n print(\"pred_{}_shape is {}\".format(i, pred[i].shape))\n\n # loc_preds, cls_preds = model(Variable(torch.randn(2,3,224,224)))\n # print(loc_preds.size())\n # print(cls_preds.size())\n # loc_grads = Variable(torch.randn(loc_preds.size()))\n # cls_grads = Variable(torch.randn(cls_preds.size()))\n # loc_preds.backward(loc_grads, retain_graph=True)\n # cls_preds.backward(cls_grads,retain_graph=True)","sub_path":"models/backbone/prune_resnet.py","file_name":"prune_resnet.py","file_ext":"py","file_size_in_byte":18994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"70809217","text":"import pycurl\nfrom io import BytesIO\nfrom urllib.parse import urljoin, urlencode, unquote, quote\nimport json\nfrom Crypto.Cipher import PKCS1_v1_5\nfrom Crypto.PublicKey import RSA\nfrom base64 import b64encode\nfrom time import sleep\n\nfrom .parser import JsVar\n\n\nclass SteamNetBase:\n\tdef __init__(self):\n\t\tself.__curl = pycurl.Curl()\n\t\tself.__curl.setopt(pycurl.TIMEOUT, 10)\n\t\tself.__curl.setopt(pycurl.FOLLOWLOCATION, 1)\n\t\tself.__curl.setopt(pycurl.MAXREDIRS, 1)\n\t\tself.__curl.setopt(pycurl.USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0')\n\t\tself.__curl.setopt(pycurl.ENCODING, 'gzip,deflate')\n\t\tself.__curl.setopt(pycurl.COOKIEFILE, '')\n\n\t\theaders = [\n\t\t\t'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',\n\t\t\t'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n\t\t\t'Accept-Language: en-US,en;q=0.5',\n\t\t\t'Connection: keep-alive',\n\t\t\t'Host: steamcommunity.com',\n\t\t\t'Pragma: no-cache',\n\t\t\t'Origin: http://steamcommunity.com',\n\t\t]\n\t\tself.set_headers(headers)\n\n\t\tself.__cookiefile = str()\n\t\tself.__interface = str()\n\n\tdef __del__(self):\n\t\tself.__curl.close()\n\n\tdef set_opt(self, option, value):\n\t\tself.__curl.setopt(option, value)\n\n\tdef get_info(self, info):\n\t\treturn self.__curl.getinfo(info)\n\n\tdef set_cookiefile(self, cookiefile):\n\t\tif cookiefile:\n\t\t\tself.set_opt(pycurl.COOKIEFILE, cookiefile)\n\t\t\tself.set_opt(pycurl.COOKIEJAR, cookiefile)\n\t\t\tself.__cookiefile = cookiefile\n\n\tdef get_cookiefile(self):\n\t\treturn self.__cookiefile\n\n\tdef set_interface(self, interface):\n\t\tif interface:\n\t\t\tself.set_opt(pycurl.INTERFACE, interface)\n\t\t\tself.__interface = interface\n\n\tdef get_interface(self):\n\t\treturn self.__interface\n\n\tdef set_headers(self, headers):\n\t\tself.set_opt(pycurl.HTTPHEADER, headers)\n\n\tdef set_referer(self, referer):\n\t\tself.set_opt(pycurl.REFERER, referer)\n\n\tdef set_cookielist(self, cookielist):\n\t\tfor c in cookielist:\n\t\t\tself.set_opt(pycurl.COOKIELIST, c)\n\n\tdef get_cookielist(self):\n\t\treturn self.get_info(pycurl.INFO_COOKIELIST)\n\n\tdef __req(self, url, params, method):\n\t\ttry:\n\t\t\tio = BytesIO()\n\t\t\tself.set_opt(pycurl.WRITEDATA, io)\n\t\t\tif method.upper() == 'GET':\n\t\t\t\tself.set_opt(pycurl.POST, 0)\n\t\t\t\tif params:\n\t\t\t\t\turl = urljoin(url, '?' + urlencode(params))\n\t\t\telif method.upper() == 'POST':\n\t\t\t\tself.set_opt(pycurl.POST, 1)\n\t\t\t\tif params:\n\t\t\t\t\tself.set_opt(pycurl.POSTFIELDS, urlencode(params))\n\t\t\tself.set_opt(pycurl.URL, url)\n\n\t\t\tself.__curl.perform()\n\n\t\t\treturn io.getvalue().decode('utf-8')\n\t\texcept:\n\t\t\treturn str()\n\n\tdef http_get(self, url, params=None):\n\t\treturn self.__req(url, params, 'GET')\n\n\tdef http_post(self, url, params=None):\n\t\treturn self.__req(url, params, 'POST')\n\n\nclass SteamLogin(SteamNetBase):\n\tdef __init__(self):\n\t\tSteamNetBase.__init__(self)\n\n\t\tself.__buffer = str()\n\t\tself.__captcha_gid = '-1'\n\t\tself.__captcha_text = str()\n\t\tself.__emailauth = str()\n\t\tself.__emailsteamid = str()\n\t\tself.__loginfriendlyname = str()\n\n\tdef login(self, username, password, cb_captcha, cb_emailauth):\n\t\tbuffer = self.http_get('https://store.steampowered.com/login/')\n\t\ttry:\n\t\t\tcaptcha_gid = buffer[buffer.index('captchagid'):]\n\t\t\tcaptcha_gid = captcha_gid[captcha_gid.index('value=\"') + 7:]\n\t\t\tcaptcha_gid = captcha_gid[:captcha_gid.index('\"')]\n\t\t\tself.__captcha_gid = captcha_gid\n\t\t\tif self.__captcha_gid != '-1':\n\t\t\t\tself.__captcha_text = cb_captcha(self.__captcha_gid)\n\t\texcept:\n\t\t\tpass\n\n\t\tif self.__getrsakey(username, password) is False:\n\t\t\treturn False\n\t\tif self.__dologin(username) is False:\n\t\t\treturn False\n\t\ttry:\n\t\t\tresponse = json.loads(self.__buffer)\n\t\t\tif response['success'] is False:\n\t\t\t\tif response.get('emailauth_needed') is True:\n\t\t\t\t\tself.__emailauth = cb_emailauth()\n\t\t\t\t\tself.__emailsteamid = response['emailsteamid']\n\t\t\t\t\tself.__loginfriendlyname = 'Firefox'\n\n\t\t\t\t\tif self.__getrsakey(username, password) is False:\n\t\t\t\t\t\treturn False\n\t\t\t\t\tif self.__dologin(username) is False:\n\t\t\t\t\t\treturn False\n\t\t\t\treturn self.__transfer()\n\t\t\telse:\n\t\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\n\tdef __getrsakey(self, username, password):\n\t\ttry:\n\t\t\tself.set_referer('https://store.steampowered.com/login/')\n\t\t\tself.__buffer = self.http_get('https://steamcommunity.com/login/getrsakey', {'username': username})\n\t\t\tresponse = json.loads(self.__buffer)\n\n\t\t\tif response['success'] is True:\n\t\t\t\tmod = int(response['publickey_mod'], 16)\n\t\t\t\texp = int(response['publickey_exp'], 16)\n\n\t\t\t\trsa = RSA.construct((mod, exp))\n\t\t\t\trsa = PKCS1_v1_5.new(rsa)\n\t\t\t\tself.__key = rsa.encrypt(password.encode('ascii'))\n\t\t\t\tself.__key = b64encode(self.__key)\n\t\t\t\tself.__key = self.__key.decode('utf-8')\n\t\t\t\tself.__timestamp = response['timestamp']\n\t\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\n\tdef __dologin(self, username):\n\t\ttry:\n\t\t\tparams = dict()\n\n\t\t\tparams.setdefault('captcha_text', self.__captcha_text)\n\t\t\tparams.setdefault('captchagid', self.__captcha_gid)\n\t\t\tparams.setdefault('donotcache', '')\n\t\t\tparams.setdefault('emailauth', self.__emailauth)\n\t\t\tparams.setdefault('emailsteamid', self.__emailsteamid)\n\t\t\tparams.setdefault('loginfriendlyname', self.__loginfriendlyname)\n\t\t\tparams.setdefault('password', self.__key)\n\t\t\tparams.setdefault('remember_login', True)\n\t\t\tparams.setdefault('rsatimestamp', self.__timestamp)\n\t\t\tparams.setdefault('username', username)\n\t\t\tparams.setdefault('twofactorcode', '')\n\n\t\t\tself.__buffer = self.http_get('https://steamcommunity.com/login/dologin', params)\n\n\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\n\tdef __transfer(self):\n\t\tresponse = json.loads(self.__buffer)\n\t\tif response['success'] is False:\n\t\t\treturn False\n\t\telse:\n\t\t\ttransfer_params = response['transfer_parameters']\n\t\t\tparams = dict()\n\t\t\tparams.setdefault('steamid', transfer_params['steamid'])\n\t\t\tparams.setdefault('token', transfer_params['token'])\n\t\t\tparams.setdefault('auth', transfer_params['auth'])\n\t\t\tparams.setdefault('webcookie', transfer_params['webcookie'])\n\t\t\tparams.setdefault('token_secure', transfer_params['token_secure'])\n\t\t\tparams.setdefault('remember_login', True)\n\t\t\tself.http_post('https://steamcommunity.com/login/transfer/', params)\n\t\treturn True\n\n\nclass SteamNet(SteamNetBase):\n\tdef __init__(self):\n\t\tSteamNetBase.__init__(self)\n\t\tself.__steamid = str()\n\n\tdef get_steamid(self):\n\t\treturn self.__steamid\n\n\tdef get_sessionid(self):\n\t\tfor c in self.get_cookielist():\n\t\t\tarray = c.split('\\t')\n\t\t\tif array[5] == 'sessionid':\n\t\t\t\treturn unquote(array[6])\n\t\treturn str()\n\n\tdef is_login(self):\n\t\tcount = 0\n\t\tfor c in self.get_cookielist():\n\t\t\tif 'steamLogin' in c:\n\t\t\t\tcount += 1\n\t\t\telif 'steamLoginSecure' in c:\n\t\t\t\tcount += 1\n\t\tif count == 2:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef prepare(self):\n\t\t\tbuffer = self.http_get('http://steamcommunity.com/market')\n\t\t\tif self.is_login():\n\t\t\t\tself.__steamid = JsVar(buffer).get('g_steamID')\n\t\t\t\tif self.__steamid:\n\t\t\t\t\treturn True\n\t\t\treturn True\n\n\tdef login_wait(self, username, password, cb_captcha, cb_emailauth):\n\t\twhile True:\n\t\t\tif self.is_login():\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tsl = SteamLogin()\n\t\t\t\tsl.set_cookiefile(self.get_cookiefile())\n\t\t\t\tsl.set_interface(self.get_interface())\n\t\t\t\tif sl.login(username, password, cb_captcha, cb_emailauth):\n\t\t\t\t\tself.set_cookielist(sl.get_cookielist())\n\t\t\t\t\treturn True\n\t\t\t\tsleep(1)\n\n\tdef buylisting(self, listingid, currency, subtotal, fee, total, appid, market_hash_name, quantity=1):\n\t\turl = urljoin('https://steamcommunity.com/market/buylisting/', str(listingid))\n\t\tparams = {\n\t\t\t'currency': currency, 'subtotal': subtotal, 'fee': fee, 'total': total, 'quantity': quantity,\n\t\t\t'sessionid': self.get_sessionid(),\n\t\t}\n\n\t\treferer = urljoin('http://steamcommunity.com/market/listings/', str(appid))\n\t\treferer = urljoin(referer, quote(market_hash_name))\n\t\tself.set_referer(referer)\n\n\t\tbuffer = self.http_post(url, params)\n\t\ttry:\n\t\t\tresponse = json.loads(buffer)\n\t\t\twallet_info = response.get('wallet_info')\n\t\t\tif wallet_info:\n\t\t\t\treturn {'success': True}\n\t\t\telse:\n\t\t\t\treturn {'success': False, 'message': response.get('message')}\n\t\texcept:\n\t\t\treturn {'success': False, 'message': None}\n\n\tdef sellitem(self, appid, contextid, assetid, amount, price):\n\t\turl = 'https://steamcommunity.com/market/sellitem'\n\t\tparams = {\n\t\t\t'sessionid': self.get_sessionid(), 'appid': appid, 'contextid': contextid, 'assetid': assetid,\n\t\t\t'amount': amount, 'price': price\n\t\t}\n\t\treferer = urljoin('http://steamcommunity.com/profiles/{}'.format(self.get_steamid()), 'inventory')\n\t\tself.set_referer(referer)\n\n\t\tif self.http_post(url, params):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef removelisting(self, listingid):\n\t\turl = urljoin('http://steamcommunity.com/market/removelisting/', str(listingid))\n\t\tparams = {'sessionid': self.get_sessionid()}\n\t\tself.set_referer('http://steamcommunity.com/market')\n\n\t\treturn self.http_post(url, params)\n","sub_path":"steamcommunity/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":8710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"110384357","text":"from django.conf.urls import url\nfrom apps.user.views import Login, RegisterView, ActiveView\n\n\nurlpatterns = [\n url(r'^login$', Login.as_view(), name='login'), # 登录页面\n url(r'^register$', RegisterView.as_view(), name='register'), # 注册页面\n url(r'^active/(?P.*)', ActiveView.as_view(), name='active'), # 激活\n # url(r'^user_center_info$', views.user_info, name='user_center_info'), # 信息中心\n # url(r'^user_center_order$', views.user_order, name='user_center_order'), # 订单中心\n # url(r'^user_center_site$', views.user_site, name='user_center_site'), # 地址信息\n]\n","sub_path":"daily_fresh/apps/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"583969581","text":"\"\"\"\nthis example show how to open a file for binary write/read\nand how to use int.to_bytes and int.from_bytes to convert the data to\nand from binary\n\"\"\"\n\na,b = 0,0\nFILENAME = \"data.bin\"\n\nSIZE = 4 #how many bytes we want to store for each number\n\nORDER = \"little\" #in what order we wnat to store those files\n #little=from the least significat byte (LSB) to the most significant byte (MSB)\n #big = from the MSB to the LSB\n\nwhile 1:\n\n #print(\"a = {}; b = {}\".format(a,b))\n print(\"a = %d; b = %d\" % (a,b))\n\n print(\"\"\"\n set (A)\n set (B)\n (S)ave\n (L)oad\n (Q)uit\n \n \"\"\")\n\n option = input(\"Option: \").upper()\n\n if option == \"A\":\n a = int(input(\"enter new value for A:\"))\n\n elif option == \"B\":\n b = int(input(\"enter new value for B:\"))\n\n elif option == \"S\":\n f = open(FILENAME, \"wb\") # the \"b\" in mode is important, otherwise it will open as text file\n f.write(a.to_bytes(SIZE,ORDER))\n f.write(b.to_bytes(SIZE,ORDER))\n f.close()\n\n elif option == \"L\":\n f = open(FILENAME, \"rb\") # the \"b\" in mode is important, otherwise it will open as text file\n a = int.from_bytes(f.read(SIZE), ORDER)\n b = int.from_bytes(f.read(SIZE), ORDER)\n f.close()\n\n elif option == \"Q\":\n break\n\n else:\n print(\"\\ninvalid option!\\n\")\n\n\n\n\n\n","sub_path":"ab_binary.py","file_name":"ab_binary.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"653785560","text":"import random\n\n\ndef monte_carlo_pi(points_count: int) -> float:\n num_points_in_circle: int = 0\n center_x: int = 1\n center_y: int = 1\n radius: int = 1\n x: float = 0\n y: float = 0\n distance: float = 0\n for _ in range(points_count):\n x = random.random() * 2.0\n y = random.random() * 2.0\n distance = ((x - center_x) ** 2) + ((y - center_y) ** 2)\n if distance <= radius ** 2:\n num_points_in_circle += 1\n\n return (4 * num_points_in_circle) / points_count\n\n\npoints_count: int = int(input('Number of points: '))\nprint(f'Estimated value of PI is: {monte_carlo_pi(points_count)}')\n","sub_path":"numerical/monte_carlo_pi.py","file_name":"monte_carlo_pi.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"223641303","text":"\"\"\"\nFaça um programa que peça o tamanho de um arquivo para download (em MB) \ne a velocidade de um link de Internet (em Mbps), calcule e informe o \ntempo aproximado de download do arquivo usando este link (em minutos).\n\"\"\"\n\n\n\"\"\"\nVelocidade em Mbps\tDownload de MB por segundo\n 1\t 0.125\n 2\t 0.25\n 10\t 1.25\n 20\t 2.5\n\n\n\n100 Mbps --->>> 12,5 MB/s\n\nMbps -> MB/s => 1Mbps/8 = MB/s\n\"\"\"\n\ntamanhoDoArquivoParaDownload = float(input(\"Digite o tamanho do arquivo em MB: \"))\nvelocidadeDaInternet = float(input(\"Digite a velocidade da internet em Mbps: \"))\n\nmegaBytesPorSegundo = velocidadeDaInternet / 8\n\ntempoEmSegundos = tamanhoDoArquivoParaDownload / megaBytesPorSegundo\n\ntempoEmMinutos = tempoEmSegundos / 60\n\n","sub_path":"01-estrutura sequencial/18-velocidadeDownload.py","file_name":"18-velocidadeDownload.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"47875255","text":"#!/usr/bin/env python\n\nfrom collections import namedtuple\nimport csv\nimport operator\nfrom fractions import gcd\n\n#named tuple for procedure timings\nProcedureTiming = namedtuple('Event', ['agent', 'step', 'start', 'duration'])\n\ndef grab_timing(csvfile):\n '''returns a list of named tuples corresponding to procedure map timing'''\n timings = []\n for event in map(ProcedureTiming._make, csv.reader(open(csvfile, 'rb'))):\n timings.append(event)\n try:\n timings = [ProcedureTiming(str(x.agent), int(x.step), int(x.start), int(x.duration)) for x in timings]\n except TypeError:\n timings = [ProcedureTiming(str(x.agent), str(x.step), int(x.start), int(x.duration)) for x in timings]\n return timings\n\n\ndef get_steps(timing):\n '''return a list of all unique steps'''\n try:\n return sorted(map(int, list(set([x.step for x in timing]))))\n except TypeError:\n return sorted(list(set([x.step for x in timing])))\n\n\ndef get_agents(timing):\n '''return a list of AgentData objects; one for each unique agent'''\n agentIDs = sorted(list(set([x.agent for x in timing])))\n agents = []\n for i in agentIDs:\n agents.append(AgentData(i, timing))\n return agents\n\ndef all_action_ends(agent_list):\n '''return int representing the point at which all action ends'''\n return max([x.end_action for x in agent_list])\n\n\ndef find_divisor(timing):\n '''return greatest common divisor of all numbers'''\n starts = [x.start for x in timing]\n durations = [x.duration for x in timing]\n all_nums = starts + durations\n return reduce(lambda x,y: gcd(x,y), all_nums)\n\n\nclass AgentData(object):\n '''an object representing an agent in a procedure mapping'''\n\n def __init__(self, agentID, proc_timing):\n self.agentID = agentID\n self.events = [x for x in proc_timing if x.agent == agentID]\n\n last_event = self.events[self.events.index(max(self.events, key=operator.itemgetter(2)))]\n self.end_action = last_event.start + last_event.duration\n\n\nif __name__ == \"__main__\":\n import sys\n timing = grab_timing(sys.argv[1])\n print(timing)\n print(get_steps(timing))\n print(get_agents(timing))\n print(all_action_ends(get_agents(timing)))\n print(find_divisor(timing))\n\n\n AgentData('nathan', timing)\n\n\n","sub_path":"timing_reader.py","file_name":"timing_reader.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"442190446","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n# Copyright:\n# 2014 brtz \n# 2014 perfide \n# License: Apache License 2.0+\n# http://www.apache.org/licenses/LICENSE-2.0\n\n\"\"\"srvinv - a command-line-interface to the srvinv server inventory server\n\nusage examples:\n---------------\nsrvinv get srv srvid --attribute interfaces\n returns a srvid's interfaces formatted as json\nsrvinv set srv srvid --attribute is_provisioned --value \"true\"\n sets is_provisioned to true on a srvid\nsrvinv register srv srvid\n will register a new srvid in inventory\nsrvinv delete srv srvid\n will remove a srvid from inventory\n\"\"\"\n\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport sys\n\nimport srvinv\nimport srvinv.bson_helper as json\n\n\ndef main(verb, resource, resourceid, attribute, value, pretty=False):\n i_ret = 0\n\n if verb == 'get':\n if value is not None:\n print('value set in get operation', file=sys.stderr)\n else:\n (i_ret, x_text) = srvinv.get(resource, resourceid, attribute)\n if i_ret == 0:\n srvinv.print_json(x_text, pretty)\n elif i_ret == 1:\n print('resource not found', file=sys.stderr)\n elif i_ret == 2:\n print('attribute not set', file=sys.stderr)\n elif i_ret == 3:\n print('error communicating with srvinv daemon',\n file=sys.stderr)\n elif i_ret == 9:\n print('error unable to build srv-id', file=sys.stderr)\n else:\n print('unknown error {}'.format(i_ret), file=sys.stderr)\n\n elif verb == 'set':\n if attribute is None:\n print('missing attribute', file=sys.stderr)\n elif value is None:\n print('missing value', file=sys.stderr)\n else:\n i_ret = srvinv.set(resource, resourceid, attribute, value)\n if i_ret == -1:\n print('value unchanged', file=sys.stderr)\n elif i_ret == 0:\n pass\n elif i_ret in (1, 2):\n print('error communicating with srvinv daemon',\n file=sys.stderr)\n elif i_ret == 3:\n print('resource not found', file=sys.stderr)\n elif i_ret == 4:\n print('attribute unchanged', file=sys.stderr)\n elif i_ret == 9:\n print('error unable to build srv-id', file=sys.stderr)\n else:\n print('unknown error {}'.format(i_ret), file=sys.stderr)\n\n elif verb == 'add':\n return_code = srvinv.add(resource, resourceid, attribute, value)\n if return_code == -1:\n print('item exists', file=sys.stderr)\n elif return_code == 1:\n print('failed to get attribute', file=sys.stderr)\n elif return_code == 2:\n print('attribute is not a list', file=sys.stderr)\n elif return_code == 3:\n print('failed to set attribute', file=sys.stderr)\n elif return_code == 9:\n print('error unable to build srv-id', file=sys.stderr)\n\n elif verb == 'remove':\n return_code = srvinv.remove(resource, resourceid, attribute, value)\n if return_code == -1:\n print('item does not exist', file=sys.stderr)\n elif return_code == 1:\n print('failed to get attribute', file=sys.stderr)\n elif return_code == 2:\n print('attribute is not a list', file=sys.stderr)\n elif return_code == 3:\n print('failed to set attribute', file=sys.stderr)\n elif return_code == 9:\n print('error unable to build srv-id', file=sys.stderr)\n\n elif verb == 'register':\n i_ret = srvinv.register(resource, resourceid)\n if i_ret == 1:\n print('conflict: already registered', file=sys.stderr)\n elif i_ret == 2:\n print('error communicating with srvinv daemon', file=sys.stderr)\n elif i_ret == 9:\n print('error unable to build srv-id', file=sys.stderr)\n elif i_ret != 0:\n print('error failed with error-code {}'.format(i_ret),\n file=sys.stderr)\n\n elif verb == 'purge' or verb == 'delete':\n i_ret = srvinv.purge(resource, resourceid)\n if i_ret == 1:\n print('resource not found', file=sys.stderr)\n elif i_ret == 9:\n print('error unable to build srv-id', file=sys.stderr)\n elif i_ret != 0:\n print('error communicating with srvinv daemon', file=sys.stderr)\n\n else:\n print('error unknown verb: {}'.format(verb), file=sys.stderr)\n\n return i_ret\n# end def main\n\n\ndef run():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"verb\",\n type=str,\n help=\"verbs to be used\",\n choices=['get', 'set', 'add', 'remove', 'register', 'purge'],\n )\n parser.add_argument(\n \"resource\",\n type=str,\n help=\"resources to be used\",\n choices=('env', 'net', 'srv'),\n )\n parser.add_argument(\n \"resourceid\",\n type=str,\n help=\"the resource ids (comma-separated list)\",\n )\n parser.add_argument(\n 'attribute',\n type=str,\n help='the attribute to be accessed',\n nargs='?',\n default=None,\n )\n parser.add_argument(\n 'value',\n type=str,\n help='the value to be setted in an attribute',\n nargs='?',\n default=None,\n )\n parser.add_argument(\n \"--attribute\",\n type=str,\n help=\"the attribute to be accessed (deprecated)\",\n )\n parser.add_argument(\n \"--value\",\n type=str,\n help=\"the value to be setted in an attribute (deprecated)\",\n )\n parser.add_argument(\n \"-p\",\n \"--pretty\",\n action='store_true',\n help=\"prettify json output\",\n )\n\n args = parser.parse_args()\n\n if args.value is not None:\n if args.value.startswith(\"@\"):\n try:\n args.value = open(args.value.lstrip(\"@\")).read()\n except IOError as e:\n print(e)\n return 665\n if args.value[0] not in ('{', '[', '\"'):\n args.value = '\"{}\"'.format(args.value)\n try:\n args.value = json.loads(args.value)\n except ValueError:\n # No JSON object could be decoded\n print('unable to parse value with JSON', file=sys.stderr)\n return 666\n\n i_out = 0\n for resourceid in args.resourceid.split(','):\n i_ret = main(args.verb, args.resource, resourceid,\n args.attribute, args.value, args.pretty)\n if i_ret:\n i_out = i_ret\n\n return i_out\n\n\nif __name__ == \"__main__\":\n sys.exit(run())\n\n# [EOF]\n","sub_path":"srvinv/bin/_srvinv.py","file_name":"_srvinv.py","file_ext":"py","file_size_in_byte":6810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"475121546","text":"# Copyright (c) 2009-2019 The Regents of the University of Michigan\n# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.\n\nR\"\"\" Deprecated analyzers.\n\"\"\"\n\nfrom hoomd.analyze import _analyzer;\nfrom hoomd.deprecated import _deprecated;\nimport hoomd;\n\nclass msd(_analyzer):\n R\"\"\" Mean-squared displacement.\n\n Args:\n filename (str): File to write the data to.\n groups (list): List of groups to calculate the MSDs of.\n period (int): Quantities are logged every *period* time steps.\n header_prefix (str): (optional) Specify a string to print before the header.\n r0_file (str): hoomd_xml file specifying the positions (and images) to use for :math:`\\vec{r}_0`.\n overwrite (bool): set to True to overwrite the file *filename* if it exists.\n phase (int): When -1, start on the current time step. When >= 0, execute on steps where *(step + phase) % period == 0*.\n\n .. deprecated:: 2.0\n analyze.msd will be replaced by a more general system capable of window averaging in a future release.\n\n :py:class:`msd` can be given any number of groups of particles. Every *period* time steps, it calculates the mean squared\n displacement of each group (referenced to the particle positions at the time step the command is issued at) and prints\n the calculated values out to a file.\n\n The mean squared displacement (MSD) for each group is calculated as:\n\n .. math::\n \\langle |\\vec{r} - \\vec{r}_0|^2 \\rangle\n\n and values are correspondingly written in units of distance squared.\n\n The file format is the same convenient delimited format used by :py:class`hoomd.analyze.log`.\n\n :py:class:`msd` is capable of appending to an existing msd file (the default setting) for use in restarting in long jobs.\n To generate a correct msd that does not reset to 0 at the start of each run, save the initial state of the system\n in a hoomd_xml file, including position and image data at a minimum. In the continuation job, specify this file\n in the *r0_file* argument to analyze.msd.\n\n Examples::\n\n msd = analyze.msd(filename='msd.log', groups=[group1, group2],\n period=100)\n\n analyze.msd(groups=[group1, group2, group3], period=1000,\n filename='msd.log', header_prefix='#')\n\n analyze.msd(filename='msd.log', groups=[group1], period=10,\n header_prefix='Log of group1 msd, run 5\\n')\n\n\n A group variable (*groupN* above) can be created by any number of group creation functions.\n See group for a list.\n\n By default, columns in the file are separated by tabs, suitable for importing as a\n tab-delimited spreadsheet. The delimiter can be changed to any string using :py:meth:`set_params()`.\n\n The *header_prefix* can be used in a number of ways. It specifies a simple string that\n will be printed before the header line of the output file. One handy way to use this\n is to specify header_prefix='#' so that ``gnuplot`` will ignore the header line\n automatically. Another use-case would be to specify a descriptive line containing\n details of the current run. Examples of each of these cases are given above.\n\n If *r0_file* is left at the default of None, then the current state of the system at the execution of the\n analyze.msd command is used to initialize :math:`\\vec{r}_0`.\n\n \"\"\"\n\n def __init__(self, filename, groups, period, header_prefix='', r0_file=None, overwrite=False, phase=0):\n hoomd.util.print_status_line();\n\n # initialize base class\n _analyzer.__init__(self);\n\n # create the c++ mirror class\n self.cpp_analyzer = _deprecated.MSDAnalyzer(hoomd.context.current.system_definition, filename, header_prefix, overwrite);\n self.setupAnalyzer(period, phase);\n\n # it is an error to specify no groups\n if len(groups) == 0:\n hoomd.context.msg.error('At least one group must be specified to analyze.msd\\n');\n raise RuntimeError('Error creating analyzer');\n\n # set the group columns\n for cur_group in groups:\n self.cpp_analyzer.addColumn(cur_group.cpp_group, cur_group.name);\n\n if r0_file is not None:\n self.cpp_analyzer.setR0(r0_file);\n\n def set_params(self, delimiter=None):\n R\"\"\" Change the parameters of the msd analysis\n\n Args:\n delimiter (str): New delimiter between columns in the output file (if specified).\n\n Examples::\n\n msd.set_params(delimiter=',');\n \"\"\"\n hoomd.util.print_status_line();\n\n if delimiter:\n self.cpp_analyzer.setDelimiter(delimiter);\n","sub_path":"hoomd/deprecated/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"460723508","text":"# 215. 数组中的第 K 个最大元素\n# 在未排序的数组中找到第 k 个最大的元素。\n# 请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。\nimport heapq\nclass Solution:\n\n # 数组中的第 K 个最大元素\n # 数组中第 k 大的元素,它的索引是 len(nums) - k\n\n def _findKthLargest(self, nums, k):\n\n L = []\n for i in range(k):\n heapq.heappush(L, nums[i])\n for j in range(k, len(nums)):\n if nums[j] > L[0]:\n heapq.heapreplace(L, nums[j])\n\n\n return L[0]\n\n\n def findKthLargest(self, nums, k):\n\n length = len(nums)\n # if k > length:\n # return 'error'\n left = 0\n right = length - 1\n\n while True:\n index = self.partition(nums, left, right)\n if index == length - k:\n return nums[index]\n\n elif index < length - k: # 第k大的数在后面的区间\n left = index+1\n else:\n right = index-1\n\n\n\n def partition(self, nums, left, right):\n \"\"\"返回第一个数是第几小的,并把比它小的放到前面\"\"\"\n\n first_value = nums[left]\n j = left\n\n for i in range(left+1, right+1):\n if nums[i] < first_value:\n j += 1\n nums[j], nums[i] = nums[i], nums[j]\n nums[j], nums[left] = nums[left], nums[j]\n return j\n\nif __name__ == '__main__':\n\n obj = Solution()\n while True:\n nums_str = input().strip().split()\n nums = list(map(int, nums_str))\n k = int(input().strip())\n res = obj.findKthLargest(nums, k)\n print(res)\n","sub_path":"00-每日一题/20200219_215.py","file_name":"20200219_215.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"249944378","text":"import itertools\n\nfrom vyper.exceptions import (\n StateAccessViolation,\n StructureException,\n TypeMismatch,\n)\nfrom vyper.parser.lll_node import LLLnode\nfrom vyper.parser.parser_utils import getpos, pack_arguments\nfrom vyper.signatures.function_signature import FunctionSignature\nfrom vyper.types import (\n BaseType,\n ByteArrayLike,\n ListType,\n TupleLike,\n get_size_of_type,\n get_static_size_of_type,\n has_dynamic_data,\n)\n\n\ndef _call_lookup_specs(stmt_expr, context):\n from vyper.parser.expr import Expr\n\n method_name = stmt_expr.func.attr\n\n if len(stmt_expr.keywords):\n raise TypeMismatch(\n \"Cannot use keyword arguments in calls to functions via 'self'\", stmt_expr,\n )\n expr_args = [Expr(arg, context).lll_node for arg in stmt_expr.args]\n\n sig = FunctionSignature.lookup_sig(context.sigs, method_name, expr_args, stmt_expr, context,)\n\n return method_name, expr_args, sig\n\n\ndef make_call(stmt_expr, context):\n method_name, _, sig = _call_lookup_specs(stmt_expr, context)\n\n if context.is_constant() and sig.mutability not in (\"view\", \"pure\"):\n raise StateAccessViolation(\n f\"May not call state modifying function \"\n f\"'{method_name}' within {context.pp_constancy()}.\",\n getpos(stmt_expr),\n )\n\n if not sig.internal:\n raise StructureException(\"Cannot call external functions via 'self'\", stmt_expr)\n\n return _call_self_internal(stmt_expr, context, sig)\n\n\ndef _call_make_placeholder(stmt_expr, context, sig):\n if sig.output_type is None:\n return 0, 0, 0\n\n output_placeholder = context.new_placeholder(typ=sig.output_type)\n out_size = get_size_of_type(sig.output_type) * 32\n returner = output_placeholder\n\n if not sig.internal and isinstance(sig.output_type, ByteArrayLike):\n returner = output_placeholder + 32\n\n return output_placeholder, returner, out_size\n\n\ndef _call_self_internal(stmt_expr, context, sig):\n # ** Internal Call **\n # Steps:\n # (x) push current local variables\n # (x) push arguments\n # (x) push jumpdest (callback ptr)\n # (x) jump to label\n # (x) pop return values\n # (x) pop local variables\n\n method_name, expr_args, sig = _call_lookup_specs(stmt_expr, context)\n pre_init = []\n pop_local_vars = []\n push_local_vars = []\n pop_return_values = []\n push_args = []\n\n # Push local variables.\n var_slots = [(v.pos, v.size) for name, v in context.vars.items() if v.location == \"memory\"]\n if var_slots:\n var_slots.sort(key=lambda x: x[0])\n mem_from, mem_to = var_slots[0][0], var_slots[-1][0] + var_slots[-1][1] * 32\n\n i_placeholder = context.new_placeholder(BaseType(\"uint256\"))\n local_save_ident = f\"_{stmt_expr.lineno}_{stmt_expr.col_offset}\"\n push_loop_label = \"save_locals_start\" + local_save_ident\n pop_loop_label = \"restore_locals_start\" + local_save_ident\n\n if mem_to - mem_from > 320:\n push_local_vars = [\n [\"mstore\", i_placeholder, mem_from],\n [\"label\", push_loop_label],\n [\"mload\", [\"mload\", i_placeholder]],\n [\"mstore\", i_placeholder, [\"add\", [\"mload\", i_placeholder], 32]],\n [\"if\", [\"lt\", [\"mload\", i_placeholder], mem_to], [\"goto\", push_loop_label]],\n ]\n pop_local_vars = [\n [\"mstore\", i_placeholder, mem_to - 32],\n [\"label\", pop_loop_label],\n [\"mstore\", [\"mload\", i_placeholder], \"pass\"],\n [\"mstore\", i_placeholder, [\"sub\", [\"mload\", i_placeholder], 32]],\n [\"if\", [\"ge\", [\"mload\", i_placeholder], mem_from], [\"goto\", pop_loop_label]],\n ]\n else:\n push_local_vars = [[\"mload\", pos] for pos in range(mem_from, mem_to, 32)]\n pop_local_vars = [\n [\"mstore\", pos, \"pass\"] for pos in range(mem_to - 32, mem_from - 32, -32)\n ]\n\n # Push Arguments\n if expr_args:\n inargs, inargsize, arg_pos = pack_arguments(\n sig, expr_args, context, stmt_expr, is_external_call=False\n )\n push_args += [inargs] # copy arguments first, to not mess up the push/pop sequencing.\n\n static_arg_size = 32 * sum([get_static_size_of_type(arg.typ) for arg in expr_args])\n static_pos = int(arg_pos + static_arg_size)\n needs_dyn_section = any([has_dynamic_data(arg.typ) for arg in expr_args])\n\n if needs_dyn_section:\n ident = f\"push_args_{sig.method_id}_{stmt_expr.lineno}_{stmt_expr.col_offset}\"\n start_label = ident + \"_start\"\n end_label = ident + \"_end\"\n i_placeholder = context.new_placeholder(BaseType(\"uint256\"))\n\n # Calculate copy start position.\n # Given | static | dynamic | section in memory,\n # copy backwards so the values are in order on the stack.\n # We calculate i, the end of the whole encoded part\n # (i.e. the starting index for copy)\n # by taking ceil32(len) + offset + arg_pos\n # for the last dynamic argument and arg_pos is the start\n # the whole argument section.\n idx = 0\n for arg in expr_args:\n if isinstance(arg.typ, ByteArrayLike):\n last_idx = idx\n idx += get_static_size_of_type(arg.typ)\n push_args += [\n [\n \"with\",\n \"offset\",\n [\"mload\", arg_pos + last_idx * 32],\n [\n \"with\",\n \"len_pos\",\n [\"add\", arg_pos, \"offset\"],\n [\n \"with\",\n \"len_value\",\n [\"mload\", \"len_pos\"],\n [\"mstore\", i_placeholder, [\"add\", \"len_pos\", [\"ceil32\", \"len_value\"]]],\n ],\n ],\n ]\n ]\n # loop from end of dynamic section to start of dynamic section,\n # pushing each element onto the stack.\n push_args += [\n [\"label\", start_label],\n [\"if\", [\"lt\", [\"mload\", i_placeholder], static_pos], [\"goto\", end_label]],\n [\"mload\", [\"mload\", i_placeholder]],\n [\"mstore\", i_placeholder, [\"sub\", [\"mload\", i_placeholder], 32]], # decrease i\n [\"goto\", start_label],\n [\"label\", end_label],\n ]\n\n # push static section\n push_args += [[\"mload\", pos] for pos in reversed(range(arg_pos, static_pos, 32))]\n elif sig.args:\n raise StructureException(\n f\"Wrong number of args for: {sig.name} (0 args given, expected {len(sig.args)})\",\n stmt_expr,\n )\n\n # Jump to function label.\n jump_to_func = [\n [\"add\", [\"pc\"], 6], # set callback pointer.\n [\"goto\", f\"priv_{sig.method_id}\"],\n [\"jumpdest\"],\n ]\n\n # Pop return values.\n returner = [0]\n if sig.output_type:\n output_placeholder, returner, output_size = _call_make_placeholder(stmt_expr, context, sig)\n if output_size > 0:\n dynamic_offsets = []\n if isinstance(sig.output_type, (BaseType, ListType)):\n pop_return_values = [\n [\"mstore\", [\"add\", output_placeholder, pos], \"pass\"]\n for pos in range(0, output_size, 32)\n ]\n elif isinstance(sig.output_type, ByteArrayLike):\n dynamic_offsets = [(0, sig.output_type)]\n pop_return_values = [\n [\"pop\", \"pass\"],\n ]\n elif isinstance(sig.output_type, TupleLike):\n static_offset = 0\n pop_return_values = []\n for name, typ in sig.output_type.tuple_items():\n if isinstance(typ, ByteArrayLike):\n pop_return_values.append(\n [\"mstore\", [\"add\", output_placeholder, static_offset], \"pass\"]\n )\n dynamic_offsets.append(\n ([\"mload\", [\"add\", output_placeholder, static_offset]], name)\n )\n static_offset += 32\n else:\n member_output_size = get_size_of_type(typ) * 32\n pop_return_values.extend(\n [\n [\"mstore\", [\"add\", output_placeholder, pos], \"pass\"]\n for pos in range(\n static_offset, static_offset + member_output_size, 32\n )\n ]\n )\n static_offset += member_output_size\n\n # append dynamic unpacker.\n dyn_idx = 0\n for in_memory_offset, _out_type in dynamic_offsets:\n ident = f\"{stmt_expr.lineno}_{stmt_expr.col_offset}_arg_{dyn_idx}\"\n dyn_idx += 1\n start_label = \"dyn_unpack_start_\" + ident\n end_label = \"dyn_unpack_end_\" + ident\n i_placeholder = context.new_placeholder(typ=BaseType(\"uint256\"))\n begin_pos = [\"add\", output_placeholder, in_memory_offset]\n # loop until length.\n o = LLLnode.from_list(\n [\n \"seq_unchecked\",\n [\"mstore\", begin_pos, \"pass\"], # get len\n [\"mstore\", i_placeholder, 0],\n [\"label\", start_label],\n [ # break\n \"if\",\n [\"ge\", [\"mload\", i_placeholder], [\"ceil32\", [\"mload\", begin_pos]]],\n [\"goto\", end_label],\n ],\n [ # pop into correct memory slot.\n \"mstore\",\n [\"add\", [\"add\", begin_pos, 32], [\"mload\", i_placeholder]],\n \"pass\",\n ],\n # increment i\n [\"mstore\", i_placeholder, [\"add\", 32, [\"mload\", i_placeholder]]],\n [\"goto\", start_label],\n [\"label\", end_label],\n ],\n typ=None,\n annotation=\"dynamic unpacker\",\n pos=getpos(stmt_expr),\n )\n pop_return_values.append(o)\n\n call_body = list(\n itertools.chain(\n [\"seq_unchecked\"],\n pre_init,\n push_local_vars,\n push_args,\n jump_to_func,\n pop_return_values,\n pop_local_vars,\n [returner],\n )\n )\n # If we have no return, we need to pop off\n pop_returner_call_body = [\"pop\", call_body] if sig.output_type is None else call_body\n\n o = LLLnode.from_list(\n pop_returner_call_body,\n typ=sig.output_type,\n location=\"memory\",\n pos=getpos(stmt_expr),\n annotation=f\"Internal Call: {method_name}\",\n add_gas_estimate=sig.gas,\n )\n o.gas += sig.gas\n return o\n","sub_path":"vyper/parser/self_call.py","file_name":"self_call.py","file_ext":"py","file_size_in_byte":11324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"488061261","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 1999-2017 Alibaba Group Holding Ltd.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nfrom odps.tests.core import TestBase, tn\nfrom odps.compat import six\nfrom odps.utils import to_str\nfrom odps.models import PartedVolume, FSVolume, VolumeFSDir, VolumeFSFile\n\nFILE_CONTENT = to_str(\"\"\"\nFour score and seven years ago our fathers brought forth,\nupon this continent,\na new nation,\nconceived in liberty,\nand dedicated to the proposition that \"all men are created equal\"\n\"\"\")\nFILE_CONTENT2 = to_str(\"\"\"\nWere it to benefit my country I would lay down my life;\nWhat then is risk to me?\n\"\"\")\nTEST_PARTED_VOLUME_NAME = tn('pyodps_test_parted_volume')\nTEST_FS_VOLUME_NAME = tn('pyodps_test_fs_volume')\n\nTEST_PARTITION_NAME = 'pyodps_test_partition'\nTEST_FILE_NAME = 'test_output_file'\nTEST_FILE_NAME2 = 'test_output_file2'\nTEST_NEW_FILE_NAME = 'test_new_output_file'\n\nTEST_DIR_NAME = 'pyodps_test_dir'\n\n\nclass Test(TestBase):\n def tearDown(self):\n if self.odps.exist_volume(TEST_PARTED_VOLUME_NAME):\n self.odps.delete_volume(TEST_PARTED_VOLUME_NAME)\n if self.odps.exist_volume(TEST_FS_VOLUME_NAME):\n self.odps.delete_volume(TEST_FS_VOLUME_NAME)\n super(Test, self).tearDown()\n\n def testVolumes(self):\n if self.odps.exist_volume(TEST_PARTED_VOLUME_NAME):\n self.odps.delete_volume(TEST_PARTED_VOLUME_NAME)\n self.odps.create_parted_volume(TEST_PARTED_VOLUME_NAME)\n\n if self.odps.exist_volume(TEST_FS_VOLUME_NAME):\n self.odps.delete_volume(TEST_FS_VOLUME_NAME)\n self.odps.create_fs_volume(TEST_FS_VOLUME_NAME)\n\n volume = self.odps.get_volume(TEST_PARTED_VOLUME_NAME)\n self.assertIsInstance(volume, PartedVolume)\n self.assertIs(volume, self.odps.get_volume(TEST_PARTED_VOLUME_NAME))\n volume.reload()\n self.assertEqual(volume.name, TEST_PARTED_VOLUME_NAME)\n\n volume = self.odps.get_volume(TEST_FS_VOLUME_NAME)\n self.assertIsInstance(volume, FSVolume)\n self.assertIs(volume, self.odps.get_volume(TEST_FS_VOLUME_NAME))\n volume.reload()\n self.assertEqual(volume.name, TEST_FS_VOLUME_NAME)\n\n self.assertTrue(self.odps.exist_volume(TEST_PARTED_VOLUME_NAME))\n self.assertTrue(self.odps.exist_volume(TEST_FS_VOLUME_NAME))\n self.assertFalse(self.odps.exist_volume('non_existing_volume'))\n\n for vol in self.odps.list_volumes():\n self.assertIsNotNone(vol.name)\n\n def testVolumePartitionAndFile(self):\n if self.odps.exist_volume(TEST_PARTED_VOLUME_NAME):\n self.odps.delete_volume(TEST_PARTED_VOLUME_NAME)\n self.odps.create_parted_volume(TEST_PARTED_VOLUME_NAME)\n\n vol = self.odps.get_volume(TEST_PARTED_VOLUME_NAME)\n partition_path = '/'.join(('', TEST_PARTED_VOLUME_NAME, TEST_PARTITION_NAME))\n partition = vol.get_partition(TEST_PARTITION_NAME)\n self.assertIs(partition, self.odps.get_volume_partition(partition_path))\n with partition.open_writer() as writer:\n writer.write(TEST_FILE_NAME, FILE_CONTENT)\n writer.write(TEST_FILE_NAME2, FILE_CONTENT2)\n partition.reload()\n self.assertEqual(partition.name, TEST_PARTITION_NAME)\n\n file_path = '/'.join(('', TEST_PARTED_VOLUME_NAME, TEST_PARTITION_NAME, TEST_FILE_NAME))\n file_obj = self.odps.get_volume_file(file_path)\n self.assertEqual(file_obj.name, TEST_FILE_NAME)\n self.assertEqual(self.odps.project + '/volumes/' + file_path.lstrip('/'), file_obj.path)\n\n with partition.files[TEST_FILE_NAME].open_reader() as reader:\n out_content = reader.read()\n if not six.PY2:\n out_content = out_content.decode('utf-8')\n self.assertEqual(out_content, FILE_CONTENT)\n\n self.assertTrue(vol.exist_partition(TEST_PARTITION_NAME))\n self.assertFalse(vol.exist_partition('non_existing_partition'))\n\n for part in self.odps.list_volume_partitions(TEST_PARTED_VOLUME_NAME):\n self.assertIsNotNone(part.name)\n\n for f in partition.list_files():\n self.assertIsNotNone(f.name)\n self.assertEqual(len(list(self.odps.list_volume_files(partition_path))), 2)\n self.assertTrue(any(f.name == TEST_FILE_NAME for f in self.odps.list_volume_files(partition_path)))\n\n self.odps.delete_volume_partition(partition_path)\n self.assertFalse(self.odps.exist_volume_partition(partition_path))\n\n def testVolumeFS(self):\n if self.odps.exist_volume(TEST_FS_VOLUME_NAME):\n self.odps.delete_volume(TEST_FS_VOLUME_NAME)\n self.odps.create_fs_volume(TEST_FS_VOLUME_NAME)\n\n vol = self.odps.get_volume(TEST_FS_VOLUME_NAME)\n\n self.odps.create_volume_directory(vol.path + '/' + TEST_DIR_NAME)\n dir_obj = vol[TEST_DIR_NAME]\n self.assertIsInstance(dir_obj, VolumeFSDir)\n self.assertIs(dir_obj, self.odps.get_volume_file(vol.path + '/' + TEST_DIR_NAME))\n self.assertEqual(dir_obj.path, '/' + TEST_FS_VOLUME_NAME + '/' + TEST_DIR_NAME)\n self.assertTrue(any(f.path in (dir_obj.path, dir_obj.path + '/')\n for f in self.odps.list_volume_files(vol.path)))\n\n with self.odps.open_volume_writer(dir_obj.path + '/' + TEST_FILE_NAME) as writer:\n writer.write(FILE_CONTENT)\n self.assertNotIn('non_existing_file', dir_obj)\n self.assertIn(TEST_FILE_NAME, dir_obj)\n self.assertTrue(any(f.basename == TEST_FILE_NAME\n for f in self.odps.list_volume_files(dir_obj.path)))\n with self.odps.open_volume_reader(dir_obj.path + '/' + TEST_FILE_NAME) as reader:\n content = reader.read()\n self.assertEqual(to_str(content), FILE_CONTENT)\n\n file_obj = dir_obj[TEST_FILE_NAME]\n self.assertIsInstance(file_obj, VolumeFSFile)\n self.assertIs(file_obj, dir_obj[TEST_FILE_NAME])\n with file_obj.open_reader() as reader:\n content = reader.read()\n self.assertEqual(to_str(content), FILE_CONTENT)\n file_obj.replication = 5\n self.assertEqual(file_obj.replication, 5)\n\n old_dir_name = file_obj.dirname\n self.odps.move_volume_file(file_obj.path, './/' + TEST_NEW_FILE_NAME, replication=10)\n self.assertEqual(old_dir_name, file_obj.dirname)\n self.assertEqual(file_obj.basename, TEST_NEW_FILE_NAME)\n self.assertEqual(file_obj.replication, 10)\n self.assertNotIn(TEST_FILE_NAME, dir_obj)\n self.odps.delete_volume_file(file_obj.path)\n self.assertNotIn(TEST_NEW_FILE_NAME, dir_obj)\n\n dir_obj.delete()\n self.assertNotIn(TEST_DIR_NAME, vol)\n","sub_path":"odps/models/tests/test_volumes.py","file_name":"test_volumes.py","file_ext":"py","file_size_in_byte":7256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"31406868","text":"from dataPrep import k_fold_cross_validation\n\npath = '../out_85175'\n\nfor i, (X_train, y_train, X_test, y_test) in enumerate(k_fold_cross_validation(path, 10,randomize=True)):\n f1 = open(\"sets1/\"+str(i)+\".train\",\"w\")\n f2 = open(\"sets1/\"+str(i)+\".test\",\"w\")\n \n for X_seq, y_seq in zip(X_train, y_train):\n \n for obs, tag in zip(X_seq, y_seq): \n # extract token\n w = str(obs[0])\n token = w.split(\"=\")[1]\n \n while len(obs)<24:\n obs.append(\" \")\n \n o_feat = \"\"\n for feat in obs:\n if \"word\" == str(feat)[:4]:\n continue\n o_feat+=str(feat)+\"\\t\"\n \n\n \n line = token+\"\\t\"+o_feat+tag \n f1.write(line)\n f1.write(\"\\n\")\n \n f1.close()\n \n \n for X_seq, y_seq in zip(X_test, y_test):\n \n for obs, tag in zip(X_seq, y_seq): \n # extract token\n w = str(obs[0])\n token = w.split(\"=\")[1]\n \n while len(obs)<24:\n obs.append(\" \")\n \n o_feat = \"\"\n for feat in obs:\n if \"word\" == str(feat)[:4]:\n continue\n o_feat+=str(feat)+\"\\t\"\n \n\n \n line = token+\"\\t\"+o_feat+tag \n f2.write(line)\n f2.write(\"\\n\")\n \n f2.close()\n\n ","sub_path":"crf/m3ndataprep.py","file_name":"m3ndataprep.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"50703266","text":"#test\nfrom collections import OrderedDict\nimport re\nfrom pprint import pprint\n\n\n#Order of sample for plot in top_only \nplots_top_order = [ \"vbfV+VV+VVV\", 'Vg+VgS', 'DY', 'Fake', 'Wjets','top','VBS']\nplots_wjets_order = [ \"vbfV+VV+VVV\", 'Vg+VgS', 'DY', 'Fake', 'top','Wjets', 'VBS']\n\n# '#FF3D00',F57C00\nwjets_palette = ['#FFC400','#FFAB00', '#FF6D00','#FF3D00','#DD2C00','#c41e08']\n\n\ndef filter_cuts(cuts, filter):\n new_cuts = {}\n for k, c in cuts.items():\n if re.search(filter, k):\n new_cuts[k] = c \n return new_cuts\n\ndef reorder_plots(groupPlot, order):\n new_group = OrderedDict()\n for g in order:\n new_group[g] = groupPlot[g]\n return new_group\n\n\n\ndef define_bins_res(groupPlot,plot):\n new_plots = { k:v for k,v in plot.items() if k != \"Wjets_HT\"}\n new_group = { k:v for k,v in groupPlot.items() if k != \"Wjets\"}\n wjets_list = []\n for ir in range(1,7):\n sname = \"Wjets_HT_res_\"+str(ir)\n wjets_list.append(sname)\n new_plots[sname] = {\n 'color': 1,\n 'isSignal' : 0,\n 'isData' : 0, \n 'scale' : 1.0 \n }\n new_group[sname] = {\n 'nameHR' : 'W+Jets bin'+str(ir),\n 'isSignal' : 0,\n 'color': wjets_palette[ir-1],\n 'samples' : [sname],\n 'fill': 1001\n }\n new_group = reorder_plots(new_group, [ \"vbfV+VV+VVV\", 'Vg+VgS', 'DY', 'Fake', 'top'] + wjets_list + ['VBS'] )\n return new_group, new_plots\n\ndef define_bins_boost(groupPlot,plot):\n new_plots = { k:v for k,v in plot.items() if k != \"Wjets_HT\"}\n new_group = { k:v for k,v in groupPlot.items() if k != \"Wjets\"}\n wjets_list = []\n for ir in range(1,6):\n sname = \"Wjets_HT_boost_\"+str(ir)\n wjets_list.append(sname)\n new_plots[sname] = {\n 'color': 1,\n 'isSignal' : 0,\n 'isData' : 0, \n 'scale' : 1.0 \n }\n new_group[sname] = {\n 'nameHR' : 'W+Jets bin'+str(ir),\n 'isSignal' : 0,\n 'color': wjets_palette[ir-1],\n 'samples' : [sname],\n 'fill': 1001\n }\n new_group = reorder_plots(new_group, [ \"vbfV+VV+VVV\", 'Vg+VgS', 'DY', 'Fake', 'top'] + wjets_list + ['VBS'] )\n return new_group, new_plots\n\n\nnorm_factors = {\n \"Wjets_HT_res_1\": \n {\n \"res_wjetcr_ele\":1.386,\n \"res_wjetcr_mu\": 1.178\n },\n \"Wjets_HT_res_2\": \n {\n \"res_wjetcr_ele\":1.130,\n \"res_wjetcr_mu\": 1.028\n },\n \"Wjets_HT_res_3\": \n {\n \"res_wjetcr_ele\":0.784,\n \"res_wjetcr_mu\": 0.871\n },\n \"Wjets_HT_res_4\": \n {\n \"res_wjetcr_ele\":0.619,\n \"res_wjetcr_mu\": 0.687\n },\n \"Wjets_HT_res_5\": \n {\n \"res_wjetcr_ele\":0.470,\n \"res_wjetcr_mu\": 0.523\n }, \n \"Wjets_HT_res_6\": \n {\n \"res_wjetcr_ele\":0.370,\n \"res_wjetcr_mu\": 0.432\n }, \n \"Wjets_HT_boost_1\": \n {\n \"boost_wjetcr_ele\":0.878,\n \"boost_wjetcr_mu\": 0.701\n },\n \"Wjets_HT_boost_2\": \n {\n \"boost_wjetcr_ele\":0.848,\n \"boost_wjetcr_mu\": 0.684\n },\n \"Wjets_HT_boost_3\": \n {\n \"boost_wjetcr_ele\":0.783,\n \"boost_wjetcr_mu\": 0.741\n },\n \"Wjets_HT_boost_4\": \n {\n \"boost_wjetcr_ele\":0.606,\n \"boost_wjetcr_mu\": 0.696\n },\n \"Wjets_HT_boost_5\": \n {\n \"boost_wjetcr_ele\":0.510,\n \"boost_wjetcr_mu\": 0.574\n }, \n\n}\n\n\ndef scaleBins(plot, cut):\n for bin,w in norm_factors.items():\n if cut not in bin: continue\n plot[bin]['cuts'] = w\n plot[bin].pop(\"scale\")\n print(plot[bin])\n return plot\n\n\n\n\ndef customize(samples,cuts,variables,nuisances,plot,groupPlot, key=None):\n if key==\"top_only\":\n new_cuts = filter_cuts(cuts, r\".*_topcr_.*\")\n new_groupPlot = reorder_plots(groupPlot, plots_top_order)\n return samples, new_cuts, variables, nuisances, plot, new_groupPlot\n\n if key==\"wjets_only\":\n new_cuts = filter_cuts(cuts, r\".*_wjetcr_.*\")\n new_groupPlot = reorder_plots(groupPlot, plots_wjets_order)\n return samples, new_cuts, variables, nuisances, plot, new_groupPlot\n\n if key==\"signal_only\":\n new_cuts = filter_cuts(cuts, r\".*_sig_.*\")\n new_groupPlot = reorder_plots(groupPlot, plots_wjets_order)\n return samples, new_cuts, variables, nuisances, plot, new_groupPlot\n\n if key==\"bins_res\":\n new_cuts = filter_cuts(cuts, r\"res_.*_.*\")\n new_groupPlot, new_plot = define_bins_res(groupPlot, plot)\n return samples, new_cuts, variables, nuisances, new_plot, new_groupPlot\n\n if key==\"bins_boost\":\n new_cuts = filter_cuts(cuts, r\"boost_.*_.*\")\n new_groupPlot, new_plot = define_bins_boost(groupPlot, plot)\n return samples, new_cuts, variables, nuisances, new_plot, new_groupPlot\n \n # if key==\"bins_res_scale\":\n # new_cuts = [\"res_wjetcr_mu\",\"res_wjetcr_ele\"]\n # new_groupPlot, new_plot = define_bins_res(groupPlot, plot)\n # scale_plot = scaleBins(new_plot, 'res')\n # return samples, new_cuts, variables, nuisances, scale_plot, new_groupPlot\n\n # if key==\"bins_boost_scale\":\n # new_cuts = [\"boost_wjetcr_mu\",\"boost_wjetcr_ele\"]\n # new_groupPlot, new_plot = define_bins_boost(groupPlot, plot)\n # scale_plot = scaleBins(new_plot, 'boost')\n # return samples, new_cuts, variables, nuisances, scale_plot, new_groupPlot\n\n \n\n else:\n return samples,cuts,variables,nuisances,plot,groupPlot","sub_path":"Configurations/VBSjjlnu/Full2017v7/conf_fit_v4_Ele32/customize.py","file_name":"customize.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"340095042","text":"# -*- coding: utf-8 -*-\n# vim: ft=python:sw=4:ts=4:sts=4:et:\nfrom __future__ import absolute_import\n\nfrom celery import shared_task\n\nfrom rest_hooks_delivery.models import StoredHook\n\nfrom django.conf import settings\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nimport requests, json, redis\n\nBATCH_DELIVERER = 'rest_hooks_delivery.deliverers.batch'\nHOOK_DELIVERER = getattr(settings, 'HOOK_DELIVERER', None)\nHOOK_DELIVERER_SETTINGS = getattr(settings, 'HOOK_DELIVERER_SETTINGS', None)\n\nBATCH_LOCK = 'batch_lock'\n\nif HOOK_DELIVERER == BATCH_DELIVERER and\\\n HOOK_DELIVERER_SETTINGS is None:\n raise Exception(\"You need to define settings.HOOK_DELIVERER_SETTINGS!\")\n\n@shared_task\ndef store_hook(*args, **kwargs):\n target_url = kwargs.get('url')\n current_count = store_and_count(*args, **kwargs)\n\n # If first in queue and batching by time\n if 'time' in settings.HOOK_DELIVERER_SETTINGS:\n if current_count == 1:\n batch_and_send.apply_async(args=(target_url,),\n countdown=settings.HOOK_DELIVERER_SETTINGS['time'],\n link_error=fail_handler.s(target_url))\n \n if 'size' in settings.HOOK_DELIVERER_SETTINGS:\n # (>=) because if retry is True count can be > size\n if current_count >= settings.HOOK_DELIVERER_SETTINGS['size']:\n batch_and_send.apply(args=(target_url,),\n countdown=0,\n link_error=fail_handler.s(target_url))\n\ndef store_and_count(*args, **kwargs):\n count = None\n target_url = kwargs.pop('url')\n hook_event = kwargs.pop('_hook_event')\n hook_user_id = kwargs.pop('_hook_user_id')\n hook_payload = kwargs.get('data', '{}')\n hook = kwargs.pop('_hook_id')\n\n with redis.Redis().lock(BATCH_LOCK):\n StoredHook.objects.create(\n target=target_url,\n event=hook_event,\n user_id=hook_user_id,\n payload=hook_payload,\n hook_id=hook\n )\n\n count = StoredHook.objects.filter(target=target_url).count()\n\n return count\n\n@shared_task\ndef fail_handler(uuid, target_url):\n clear_events(target_url)\n\ndef clear_events(target_url):\n with redis.Redis().lock(BATCH_LOCK):\n events = StoredHook.objects.filter(target=target_url).delete()\n\n@shared_task\ndef batch_and_send(target_url):\n have_lock = False\n _lock = redis.Redis().lock(BATCH_LOCK)\n try:\n have_lock = _lock.acquire(blocking=True)\n finally:\n if have_lock:\n events = None\n try:\n events = StoredHook.objects.filter(target=target_url)\n batch_data_list = []\n for event in events:\n batch_data_list.append(json.loads(event.payload))\n\n if len(batch_data_list):\n r = requests.post(\n target_url,\n data=json.dumps(batch_data_list, cls=DjangoJSONEncoder),\n headers={'Content-Type': 'application/json'})\n if (r.status_code > 299 and not 'retry' in \\\n settings.HOOK_DELIVERER_SETTINGS) or (r.status_code < 300):\n events.delete()\n elif (r.status_code > 299 and 'retry' in \\\n settings.HOOK_DELIVERER_SETTINGS):\n if batch_and_send.request.retries == \\\n settings.HOOK_DELIVERER_SETTINGS['retry']['retries']:\n events.delete()\n else:\n _lock.release()\n have_lock = False\n raise batch_and_send.retry(\n args=(target_url,),\n countdown=\\\n settings.HOOK_DELIVERER_SETTINGS['retry']['retry_interval'])\n if have_lock:\n _lock.release()\n have_lock = False\n except requests.exceptions.ConnectionError as exc:\n if 'retry' in settings.HOOK_DELIVERER_SETTINGS:\n if batch_and_send.request.retries == \\\n settings.HOOK_DELIVERER_SETTINGS['retry']['retries']:\n events.delete()\n else:\n _lock.release()\n have_lock = False\n raise batch_and_send.retry(\n args=(target_url,), exc=exc,\n countdown=\\\n settings.HOOK_DELIVERER_SETTINGS['retry']['retry_interval'])\n else:\n events.delete()\n\n if have_lock:\n _lock.release()\n have_lock = False\n","sub_path":"rest_hooks_delivery/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"43718877","text":"from __future__ import print_function\n\nfrom six.moves.urllib.parse import urlencode\n\nfrom globus_sdk import config\nfrom globus_sdk.base import BaseClient, merge_params\nfrom globus_sdk.authorizers import AccessTokenAuthorizer\nfrom globus_sdk.auth.token_response import OAuthTokenResponse\n\n\nclass AuthClient(BaseClient):\n \"\"\"\n Client for the\n `Globus Auth API `_\n\n This class provides helper methods for most common resources in the\n Auth API, and the common low-level interface from\n :class:`BaseClient ` of ``get``, ``put``,\n ``post``, and ``delete`` methods, which can be used to access any API\n resource.\n\n There are generally two types of resources, distinguished by the type\n of authentication which they use. Resources available to end users of\n Globus are authenticated with a Globus Auth Token\n (\"Authentication: Bearer ...\"), while resources available to OAuth\n Clients are authenticated using Basic Auth with the Client's ID and\n Secret.\n Some resources may be available with either authentication type.\n\n Initializing an ``AuthClient`` to authenticate a user making calls to the\n Globus Auth service with an access token takes the form\n\n >>> from globus_sdk import AuthClient\n >>> # AccessTokenAuthorizer is used, loading from the auth_token value in\n >>> # your configuration\n >>> ac = AuthClient()\n\n or explicitly as\n\n >>> from globus_sdk import AuthClient, AccessTokenAuthorizer\n >>> ac = AuthClient(authorizer=AccessTokenAuthorizer(''))\n \"\"\"\n def __init__(self, environment=config.get_default_environ(),\n client_id=None, authorizer=None, app_name=None):\n self.client_id = client_id\n\n # an AuthClient may contain a GlobusOAuth2FlowManager in order to\n # encapsulate the functionality of various different types of flow\n # managers\n self.current_oauth2_flow_manager = None\n\n access_token = config.get_auth_token(environment)\n if authorizer is None and access_token is not None:\n authorizer = AccessTokenAuthorizer(access_token)\n\n BaseClient.__init__(self, \"auth\", environment, authorizer=authorizer,\n app_name=app_name)\n\n def get_identities(self, **params):\n r\"\"\"\n GET /v2/api/identities\n\n Given ``usernames=`` or (exclusive) ``ids=`` as keyword\n arguments, looks up identity information for the set of identities\n provided.\n ```` and ```` in this case are comma-delimited strings listing\n multiple Identity Usernames or Identity IDs.\n\n Available with any authentication/client type.\n\n >>> ac = globus_sdk.AuthClient()\n >>> # by IDs\n >>> r = ac.get_identities(ids=\"46bd0f56-e24f-11e5-a510-131bef46955c\")\n >>> r.data\n {u'identities': [{u'email': None,\n u'id': u'46bd0f56-e24f-11e5-a510-131bef46955c',\n u'identity_provider': u'7daddf46-70c5-45ee-9f0f-7244fe7c8707',\n u'name': None,\n u'organization': None,\n u'status': u'unused',\n u'username': u'globus@globus.org'}]}\n >>> ac.get_identities(\n >>> identities=\",\".join(\n >>> (\"46bd0f56-e24f-11e5-a510-131bef46955c\",\n >>> \"168edc3d-c6ba-478c-9cf8-541ff5ebdc1c\"))\n ...\n >>> # or by usernames\n >>> ac.get_identities(usernames='globus@globus.org')\n ...\n >>> ac.get_identities(\n >>> usernames='globus@globus.org,auth@globus.org')\n ...\n\n See\n `Identities Resources \\\n `_\n in the API documentation for details.\n \"\"\"\n return self.get(\"/v2/api/identities\", params=params)\n\n def token_introspect(self, token, **kw):\n \"\"\"\n POST /v2/oauth2/token/introspect\n\n Get information about a Globus Auth token.\n\n Requires that your client is of type\n ``CLIENT_TYPE_CONFIDENTIAL_APP``.\n\n >>> # parameters as discussed above\n >>> ac = globus_sdk.AuthClient(...)\n >>> ac.token_introspect('')\n ...\n\n See\n `Token Introspection \\\n `_\n in the API documentation for details.\n \"\"\"\n merge_params(kw, token=token)\n return self.post(\"/v2/oauth2/token/introspect\",\n text_body=urlencode(kw))\n\n def oauth2_get_authorize_url(self):\n \"\"\"\n Get the authorization URL to which users should be sent.\n This method may only be called after an ``oauth2_start_flow_*`` method\n has been called on this ``AuthClient``.\n\n :rtype: ``string``\n \"\"\"\n if not self.current_oauth2_flow_manager:\n raise ValueError(\n ('Cannot get authorize URL until starting an OAuth2 flow. '\n 'Call one of the oauth2_start_flow_*() methods on this '\n 'AuthClient to resolve'))\n return self.current_oauth2_flow_manager.get_authorize_url()\n\n def oauth2_exchange_code_for_tokens(self, auth_code):\n \"\"\"\n Exchange an authorization code for a token or tokens.\n\n :rtype: :class:`OAuthTokenResponse \\\n `\n\n ``auth_code``\n An auth code typically obtained by sending the user to the authorize\n URL. The code is a very short-lived credential which this method is\n exchanging for tokens. Tokens are the credentials used to\n authenticate against Globus APIs.\n \"\"\"\n if not self.current_oauth2_flow_manager:\n raise ValueError(\n ('Cannot exchange auth code until starting an OAuth2 flow. '\n 'Call one of the oauth2_start_flow_*() methods on this '\n 'AuthClient to resolve'))\n\n return self.current_oauth2_flow_manager.exchange_code_for_tokens(\n auth_code)\n\n def oauth2_refresh_token(self, refresh_token):\n r\"\"\"\n Exchange a refresh token for a :class:`OAuthTokenResponse\n `, containing\n an access token.\n\n Does a token call of the form\n\n .. code-block:: none\n\n refresh_token=\n grant_type=refresh_token\n\n plus any additional parameters you may specify.\n\n ``refresh_token``\n A raw Refresh Token string\n\n ``additional_params``\n A dict of extra params to encode in the refresh call.\n \"\"\"\n form_data = {'refresh_token': refresh_token,\n 'grant_type': 'refresh_token'}\n\n return self.oauth2_token(form_data)\n\n def oauth2_token(self, form_data):\n \"\"\"\n This is the generic form of calling the OAuth2 Token endpoint.\n It takes ``form_data``, a dict which will be encoded in a form POST\n body on the request, and may suppress the Authorization header to allow\n flexibility when the governing ``AuthClient`` has credentials that\n could impede an OAuth2 flow.\n\n Generally, users of the SDK should not call this method unless they are\n implementing OAuth2 flows.\n\n :rtype: :class:`OAuthTokenResponse \\\n `\n \"\"\"\n # use the fact that requests implicitly encodes the `data` parameter as\n # a form POST\n return self.post(\n '/v2/oauth2/token', response_class=OAuthTokenResponse,\n text_body=form_data)\n","sub_path":"globus_sdk/auth/client_types/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"372279340","text":"#A first class example\r\n\r\nclass Song(object):\r\n def __init__(self, lyrics):\r\n self.lyrics = lyrics\r\n\r\n def sing_me_a_song(self):\r\n for line in self.lyrics:\r\n print(line)\r\n\r\nhappy_bday = Song([\"Happy birthday to you\",\r\n \"I dont's want to get sued\",\r\n \"So I'll stop right there\"])\r\n\r\nbulls_on_parade = Song([\"Tey rally around tha family\",\r\n \"With pockets full of shells\"])\r\n\r\nmy_song = [\"Lalalalalala\",\r\n \"Hahahahahaha\",\r\n \"Heiheiheihei\"]\r\nmy_bad_song = Song(my_song)\r\nmy_bad_song.sing_me_a_song()\r\nhappy_bday.sing_me_a_song()\r\nbulls_on_parade.sing_me_a_song()","sub_path":"hand_way/ex40.py","file_name":"ex40.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"275544164","text":"# Make predictions with coefficients\ndef predict(row, coefficients):\n yhat = coefficients[0]\n for i in range(len(row)-1):\n yhat += coefficients[i+1] * row[i]\n return yhat\n\n# Estimate linear regression coefficients using stochastic gradient descent\ndef coefficients_sgd(train, l_rate, n_epoch):\n coef = [0.0 for i in range(len(train[0]))]\n for epoch in range(n_epoch):\n sum_error = 0\n for row in train:\n yhat = predict(row, coef)\n error = yhat - row[-1]\n sum_error += error**2\n coef[0] = coef[0] - l_rate * error\n for i in range(len(row)-1):\n coef[i+1] = coef[i+1] - l_rate * error * row[i]\n print('>epoch=%d, lrate=%.3f, error=%.3f'% (epoch, l_rate, sum_error))\n return coef\n\n# Linear Regression Algorithm with Stochastic Gradient Descent\ndef linear_regression_sgd(train, test, l_rate, n_epoch):\n predictions = list()\n coef = coefficients_sgd(train, l_rate, n_epoch)\n for row in test:\n yhat = predict(row, coef)\n predictions.append(yhat)\n return (predictions)\n","sub_path":"Materials_from_books/01 - Machine Learning Algorithms from Scratch with Python /Codes/ch08_mlr.py","file_name":"ch08_mlr.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"266407991","text":"import time\nfrom torch.utils.data import TensorDataset\nfrom .reader import *\n\n\nclass DataSet(TensorDataset):\n\n def __init__(self, cfg, data_type, debug=True):\n self.cfg, self.data_type = cfg, data_type\n\n reader = DataReader(self.cfg, debug)\n\n if debug:\n p('Loading raw dataset \"{}\".'.format(data_type_name(data_type)))\n\n t0 = time.time()\n self.data, self.labels = reader[data_type]\n\n if debug:\n p('Done loading raw data in {:.3} secs.'.format(time.time() - t0))\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, i):\n label = [-1]\n if self.labels is not None:\n label = self.labels[i]\n if not hasattr(label, '__iter__'):\n label = [label]\n return to_tensor(np.array(self.data[i])), to_tensor(np.array(label))\n","sub_path":"venv/Lib/site-packages/to/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"541935552","text":"import json\n\nwith open('data.json') as f:\n data = json.load(f)\n\nconvo = 0\ninteract = 0\n\nbase = data[\"conversations\"][convo][\"interactions\"][interact][\"conversationResponse\"]\n\nqueryText = base[\"queryText\"]\nsessionId = base[\"sessionId\"]\nintentName = base[\"intent\"][\"displayName\"]\n\n\nprint(\"query is: \" + queryText)\nprint(\"session id is: \" + sessionId)\nprint(\"intent is: \" + intentName)\n","sub_path":"aa_tests/json-extract.py","file_name":"json-extract.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"583460064","text":"import torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nimport torch.optim as optim\r\nfrom timeit import default_timer as timer\r\n\r\n\r\nfsampling = 350 # sampling frequency\r\nx = torch.unsqueeze(torch.linspace(0,2*np.pi,fsampling), dim = 1) # dividing 0-2*pi interval into (fsampling) pieces with same length, x data\r\ny = torch.sin(x) # create sine wave for x points, y data\r\ny_noisy = torch.sin(x) + 0.25 * torch.rand(x.size()) # noisy y data\r\n\r\n# model FCN with 3 layers created 10 neurons used, parameters can be changed to intended values\r\nclass FCN_3L(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n self.fc1 = nn.Linear(in_features = 1, out_features = 10)\r\n self.fc2 = nn.Linear(in_features = 10, out_features = 10)\r\n self.fc3 = nn.Linear(in_features = 10, out_features = 1)\r\n\r\n def forward(self, x):\r\n x = x.reshape(x.size(0), -1)\r\n x = torch.sigmoid(self.fc1(x)) # use activation function to add non-linearity\r\n x = torch.sigmoid(self.fc2(x)) # I tried both relu and sigmoid for activation function\r\n x = self.fc3(x) # most of the time relu stucks but sigmoid helps our model on training session\r\n return x # still loss is decent amount\r\n\r\nnet = FCN_3L() # fully connected neural network \r\n\r\nprint('Network = ', net.parameters) # print information about FCN_3L (our model)\r\n\r\ncriterion = nn.MSELoss() # loss function for regression mean squared loss\r\noptimizer = optim.SGD(net.parameters(), lr = 0.005, momentum = 0.9) # SGD optimizer, tried to optimize \r\n # learning rate by manually change it\r\nepochs = 20000 # number of epochs\r\n\r\ntarget_list = [y, y_noisy] # list of targets, both with and without noise\r\ntarget_number = len(target_list) # create iterable number for training loop\r\n# training loop\r\nfor target in range(target_number):\r\n start = timer() # start timer to see the training time\r\n # if situation for printing information about corresponded target\r\n if target == 0:\r\n print('----- Training sine wave without noise -----')\r\n else:\r\n print('\\n----- Training sine wave with noise ------')\r\n for i in range(epochs):\r\n running_loss = 0.0 # zero the loss when initialize\r\n optimizer.zero_grad() # zero the parameter gradients\r\n prediction = net(x) # prediction of model for x data\r\n loss = criterion(prediction, target_list[target]) # target_list[target] = target (actual value), loss function compares model's prediction and target\r\n loss.backward() # compute gradients, backpropagation\r\n optimizer.step() # apply gradients\r\n running_loss += loss.item() # calculate loss for corresponded epoch\r\n if i % 2000 == 1999: # print every 2000 epochs and its loss\r\n print('[epoch: %d] ----- [loss: %.3f]' % (i + 1, running_loss)) # print epoch and its loss\r\n running_loss = 0.0 # zero the loss\r\n end = timer() # end timer\r\n elapsed_time = format((end - start)/60, '.3f') # calculate elapsed time for training session\r\n print('\\nCompleted! \\nElapsed time: ', elapsed_time, 'mins') # print the progress and elapsed time of training\r\n","sub_path":"timeseries/sine-generator/sine_wave_FCN_total_sine.py","file_name":"sine_wave_FCN_total_sine.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"188889536","text":"#!/usr/bin/env python2\n# -*- coding: utf-8-*-\nimport os\nimport wave\nimport json\nimport tempfile\nimport logging\nimport urllib\nimport urlparse\nimport re\nimport subprocess\nfrom abc import ABCMeta, abstractmethod\nimport requests\nimport yaml\nimport jasperpath\nimport diagnose\nimport vocabcompiler\n\n\nclass AbstractSTTEngine(object):\n \"\"\"\n Generic parent class for all STT engines\n \"\"\"\n\n __metaclass__ = ABCMeta\n VOCABULARY_TYPE = None\n\n @classmethod\n def get_config(cls):\n return {}\n\n @classmethod\n def get_instance(cls, vocabulary_name, phrases):\n config = cls.get_config()\n if cls.VOCABULARY_TYPE:\n vocabulary = cls.VOCABULARY_TYPE(vocabulary_name,\n path=jasperpath.config(\n 'vocabularies'))\n if not vocabulary.matches_phrases(phrases):\n vocabulary.compile(phrases)\n config['vocabulary'] = vocabulary\n instance = cls(**config)\n return instance\n\n @classmethod\n def get_passive_instance(cls):\n phrases = vocabcompiler.get_keyword_phrases()\n return cls.get_instance('keyword', phrases)\n\n @classmethod\n def get_active_instance(cls):\n phrases = vocabcompiler.get_all_phrases()\n return cls.get_instance('default', phrases)\n\n @classmethod\n @abstractmethod\n def is_available(cls):\n return True\n\n @abstractmethod\n def transcribe(self, fp):\n pass\n\n\n\nclass WitAiSTT(AbstractSTTEngine):\n \"\"\"\n Speech-To-Text implementation which relies on the Wit.ai Speech API.\n\n This implementation requires an Wit.ai Access Token to be present in\n profile.yml. Please sign up at https://wit.ai and copy your instance\n token, which can be found under Settings in the Wit console to your\n profile.yml:\n ...\n stt_engine: witai\n witai-stt:\n access_token: ERJKGE86SOMERANDOMTOKEN23471AB\n \"\"\"\n\n SLUG = \"witai\"\n\n def __init__(self, access_token):\n self._logger = logging.getLogger(__name__)\n self.token = access_token\n\n @classmethod\n def get_config(cls):\n # FIXME: Replace this as soon as we have a config module\n config = {}\n # Try to get wit.ai Auth token from config\n profile_path = jasperpath.config('profile.yml')\n if os.path.exists(profile_path):\n with open(profile_path, 'r') as f:\n profile = yaml.safe_load(f)\n if 'witai-stt' in profile:\n if 'access_token' in profile['witai-stt']:\n config['access_token'] = \\\n profile['witai-stt']['access_token']\n return config\n\n @property\n def token(self):\n return self._token\n\n @token.setter\n def token(self, value):\n self._token = value\n self._headers = {'Authorization': 'Bearer %s' % self.token,\n 'accept': 'application/json',\n 'Content-Type': 'audio/wav'}\n\n @property\n def headers(self):\n return self._headers\n\n def transcribe(self, fp):\n data = fp.read()\n r = requests.post('https://api.wit.ai/speech?v=20150101',\n data=data,\n headers=self.headers)\n try:\n r.raise_for_status()\n text = r.json()['_text']\n except requests.exceptions.HTTPError:\n self._logger.critical('Request failed with response: %r',\n r.text,\n exc_info=True)\n return []\n except requests.exceptions.RequestException:\n self._logger.critical('Request failed.', exc_info=True)\n return []\n except ValueError as e:\n self._logger.critical('Cannot parse response: %s',\n e.args[0])\n return []\n except KeyError:\n self._logger.critical('Cannot parse response.',\n exc_info=True)\n return []\n else:\n transcribed = []\n if text:\n transcribed.append(text.upper())\n self._logger.info('Transcribed: %r', transcribed)\n return transcribed\n\n @classmethod\n def is_available(cls):\n return diagnose.check_network_connection()\n\n\ndef get_engine_by_slug(slug=None):\n \"\"\"\n Returns:\n An STT Engine implementation available on the current platform\n\n Raises:\n ValueError if no speaker implementation is supported on this platform\n \"\"\"\n\n if not slug or type(slug) is not str:\n raise TypeError(\"Invalid slug '%s'\", slug)\n\n selected_engines = filter(lambda engine: hasattr(engine, \"SLUG\") and\n engine.SLUG == slug, get_engines())\n if len(selected_engines) == 0:\n raise ValueError(\"No STT engine found for slug '%s'\" % slug)\n else:\n if len(selected_engines) > 1:\n print((\"WARNING: Multiple STT engines found for slug '%s'. \" +\n \"This is most certainly a bug.\") % slug)\n engine = selected_engines[0]\n if not engine.is_available():\n raise ValueError((\"STT engine '%s' is not available (due to \" +\n \"missing dependencies, missing \" +\n \"dependencies, etc.)\") % slug)\n return engine\n\n\ndef get_engines():\n def get_subclasses(cls):\n subclasses = set()\n for subclass in cls.__subclasses__():\n subclasses.add(subclass)\n subclasses.update(get_subclasses(subclass))\n return subclasses\n return [tts_engine for tts_engine in\n list(get_subclasses(AbstractSTTEngine))\n if hasattr(tts_engine, 'SLUG') and tts_engine.SLUG]\n","sub_path":"client/stt.py","file_name":"stt.py","file_ext":"py","file_size_in_byte":5848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"30175108","text":"import os.path\n\nimport tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nfrom tornado.options import define, options\nfrom tornado.web import url\n\nfrom .handlers import *\n\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\n\nclass Application(tornado.web.Application):\n\n def __init__(self):\n handlers = [\n url(r'/', MainHandler, name='index'),\n url(r'/signup', SignupHandler, name='signup'),\n url(r'/login', LoginHandler, name='login'),\n url(r'/logout', LogoutHandler, name='logout'),\n ]\n settings = dict(\n template_path=os.path.join(os.path.dirname(__file__), 'templates'),\n static_path=os.path.join(os.path.dirname(__file__), 'static'),\n xsrf_cookies=True,\n cookie_secret='__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__',\n login_url='/login',\n debug=True,\n )\n super(Application, self).__init__(handlers, **settings)\n # Have one global connection to the blog DB across all handlers\n self.db = torndb.Connection(\n host=options.mysql_host, database=options.mysql_database,\n user=options.mysql_user, password=options.mysql_password)\n\n self.cookie_name = 'user'\n\n self.maybe_create_tables()\n\n def maybe_create_tables(self):\n try:\n self.db.get(\"SELECT COUNT(*) from entries;\")\n except MySQLdb.ProgrammingError:\n subprocess.check_call(['mysql',\n '--host=' + options.mysql_host,\n '--database=' + options.mysql_database,\n '--user=' + options.mysql_user,\n '--password=' + options.mysql_password],\n stdin=open('schema.sql'))\n\n\ndef main():\n options.parse_command_line()\n app = Application()\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"auth/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"488096484","text":"temp = list()\nprinc = list()\nmai = men = 0\nwhile True:\n temp.append(str(input('Nome: ')))\n temp.append(int(input('Peso: ')))\n if len(princ) == 0:\n mai = men = temp[1]\n else:\n if temp[1] > mai:\n mai = temp[1]\n if temp[1] < men:\n men = temp[1]\n princ.append(temp[:])\n temp.clear()\n sn = str(input('Quer continuar? [S/N] ')).upper().strip()[0]\n while sn not in 'SN':\n sn = str(input('Quer continuar? [S/N] ')).upper().strip()[0]\n if sn == 'N':\n break\nprint('-=' * 24)\nprint(f'Ao todo você cadastrou {len(princ)} pessoas.')\nprint(f'O maior peso foi de {mai} Kg, ', end='')\nfor p in princ:\n if p[1] == mai:\n print(f'[{p[0]}] ', end='')\nprint(f'\\nO menor peso foi de {men} Kg, ', end='')\nfor p in princ:\n if p[1] == men:\n print(f'[{p[0]}] ', end='')\n","sub_path":"exercicios/ex 081 a 090/ex084.py","file_name":"ex084.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"147582500","text":"import pickle\nimport nltk\nfrom hashIndex import is_ascii\nfrom fullStopWordList import stopwords as stop_words\n\n\ndef pre_process_query(query):\n stemmer = nltk.stem.snowball.EnglishStemmer()\n tokens = nltk.word_tokenize(query)\n ascii_tokens = [ascii_token for ascii_token in tokens if is_ascii(ascii_token)]\n filtered = [token.lower() for token in ascii_tokens if token not in stop_words]\n processed_tokens = [stemmer.stem(token) for token in filtered if token.isalpha()]\n final_tokens = [token for token in processed_tokens if token not in stop_words]\n\n return final_tokens\n\n\ndef search_index(term):\n \"\"\"\n Load the index and look for documents related to a term\n\n :param term: Term to find documents for\n :return: List of documents related to the term\n \"\"\"\n\n # Set up storage variables\n token_docs = list()\n current_index = None\n shortest = list()\n final_final_documents = dict()\n\n # Pre-process the search term, same as we do for generating the index\n search_tokens = pre_process_query(term)\n\n # Iterate through each index we have, and look for any documents for the term\n for token in search_tokens:\n potential_docs = list()\n for num in range(1, 9):\n with open(f\"hashed-tfidf/hashTFIDFPickle{num}\", \"rb\") as index_file:\n current_index = pickle.load(index_file)\n potential_docs.extend(current_index.get(token))\n\n token_docs.append(potential_docs)\n if current_index:\n current_index.clear()\n token_docs.sort(key=len)\n\n if len(search_tokens) > 1:\n def compare(item):\n return item.split(\":\")[0] in shortest_doc_ids\n\n shortest = token_docs[0]\n shortest_doc_ids = [doc_id.split(\":\")[0] for doc_id in shortest]\n if len(token_docs) > 1:\n for token_doc in token_docs[1:]:\n matches = list(filter(compare, token_doc))\n if len(matches) > 0:\n shortest = matches\n shortest_doc_ids = [doc_id.split(\":\")[0] for doc_id in shortest]\n else:\n for token_doc in token_docs:\n shortest.extend(token_doc)\n for token_finalDoc in shortest:\n splitArray = token_finalDoc.split(\":\")\n splitID = splitArray[0]\n splitTFIDF = float(splitArray[1])\n if splitID in final_final_documents:\n pastTFIDF = float(final_final_documents.get(splitID).split(\":\")[1])\n final_final_documents.update({splitID: f\"{splitID}:{((pastTFIDF + splitTFIDF) / len(search_tokens))}\"})\n else:\n final_final_documents.update({splitID: f\"{splitID}:{splitTFIDF}\"})\n return sorted(list(final_final_documents.values()), key=lambda x: x.split(\":\")[1], reverse=True)\n\n\nif __name__ == \"__main__\":\n search_term = input(\"Give me a term: \")\n documents = search_index(search_term)\n print(f\"Found {len(documents)} related documents:\\n\\n\")\n","sub_path":"search_index.py","file_name":"search_index.py","file_ext":"py","file_size_in_byte":2927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"301791414","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nimport flask\nimport PyPDF2 \nimport textract\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport nltk\nnltk.download('punkt')\n\nfrom nltk import word_tokenize,sent_tokenize\nfrom flask import request, jsonify\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n\n@app.route('/', methods=['GET'])\ndef home():\n \n return {\"name\":\"ali\"}\n\n@app.route('/api', methods=['GET'])\ndef api_id():\n \n if 'id' in request.args:\n ide = str(request.args['id'])\n else:\n return \"Error: No id field provided. Please specify an id.\"\n results = []\n d={}\n b={}\n #write a for-loop to open many files -- leave a comment if you'd #like to learn how\n filename = ide+'.pdf'\n #open allows you to read the file\n pdfFileObj = open(filename,'rb')\n #The pdfReader variable is a readable object that will be parsed\n pdfReader = PyPDF2.PdfFileReader(pdfFileObj)\n\n #discerning the number of pages will allow us to parse through all #the pages\n num_pages = pdfReader.numPages\n count = 0\n text = \"\"\n #The while loop will read each page\n while count < num_pages:\n pageObj = pdfReader.getPage(count)\n count +=1\n text += pageObj.extractText()\n #This if statement exists to check if the above library returned #words. It's done because PyPDF2 cannot read scanned files.\n if text != \"\":\n text = text\n #If the above returns as False, we run the OCR library textract to #convert scanned/image based PDF files into text\n else:\n text = textract.process(filename, method='tesseract', language='eng')\n print(type(text))\n text=text.replace('\\n',' ')\n l=[]\n l=text.split(' ')\n l=[x.upper() for x in l]\n\n for i in l:\n if '@' in i:\n mail=i\n d['email']=mail\n \n tokens = word_tokenize(text)\n #we'll create a new list which contains punctuation we wish to clean\n punctuations = ['(',')',';',':','[',']',',',':',' ']\n skills=['Matlab','matlab','MATLAB','C++','Pascal','c++','PHP','SQL']\n for i in range(0,len(tokens)-1):\n l.append(tokens[i]+tokens[i+1])\n keywords = [word for word in tokens if word in skills ]\n keyw=[word for word in l if word in skills ]\n s=set(keywords+keyw)\n k=list()\n l1=list(s)\n for j in l1:\n\n f={}\n f['libele']=j\n k.append(f)\n\n \n b['competence']=k\n \n results.append(d)\n results.append(b)\n return jsonify(results)\n\n \napp.run()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Python web service/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"539070418","text":"import machine\nimport dht\nfrom machine import Pin, SPI, ADC\nfrom time import sleep\nfrom ssd1351 import Display, color565\nfrom xglcd_font import XglcdFont\n\ndef setup_display():\n #mosi=sda\n spi = SPI(2, 14500000, miso=Pin(19), mosi=Pin(18), sck=Pin(5))\n display = Display(spi, rst=Pin(26), dc=Pin(25), cs=Pin(4))\n return display\n\ndef cleanup_display(display):\n if display is not None:\n print('clearing display')\n display.clear()\n display.cleanup()\n\nbutton = machine.Pin(27, machine.Pin.IN, machine.Pin.PULL_UP)\ndisplay=setup_display()\nd = dht.DHT22(machine.Pin(22))\nfont = XglcdFont('fonts/Bally7x9.c', 7, 9)\n\ndef interrupt(p):\n d.measure()\n display.clear()\n display.draw_text(40, 30, \"Temp: \" + str(d.temperature()), font, color565(0, 0, 255))\n display.draw_text(38, 40, \"Hum: \" + str(d.humidity()), font, color565(0, 0, 255))\n\nbutton.irq(trigger=Pin.IRQ_FALLING, handler=interrupt)\n\nadcl = ADC(Pin(32))\nadcl.atten(ADC.ATTN_11DB)\nadcr = ADC(Pin(35))\nadcr.atten(ADC.ATTN_11DB)\n\nshow_temp = True\nsleep_count = 0\nold_measurement = \"\"\n\nwhile True:\n if sleep_count % 20 == 0:\n d.measure()\n if show_temp:\n measurement = \"Temp: \" + str(d.temperature())\n else:\n measurement = \"Humidity: \" + str(d.humidity())\n\n x_first=adcl.read()\n sleep(0.05)\n sleep_count += 1\n x_second=adcl.read()\n if x_second - x_first > 1000:\n show_temp = not show_temp\n else:\n if measurement == old_measurement:\n continue\n\n display.clear()\n #display.draw_text(80, 10, \"EDC2018!\", font, color565(0, 0, 255))\n display.draw_text(20, 30, measurement, font, color565(0, 0, 255))\n\n old_measurement = measurement\n","sub_path":"joystick-temp-oled.py","file_name":"joystick-temp-oled.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"14417981","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Реализация функционала обработчика csv файлов\n\nclass Product:\n \"\"\"Класс Товар \"\"\"\n def __init__(self, name, price, quantity):\n self.name = name\n self.price = int(price)\n self.quantity = int(quantity)\n \n def __str__(self):\n return (\n f'наименование: {self.name},' +\n f'цена: {self.price}, ' +\n f'количество: {self.quantity}'\n )\n \n \nclass ProductList:\n \"\"\"Класс список товаров \"\"\"\n def __init__(self, productlist):\n if productlist == []:\n raise IndexError('Получен пустой список')\n self.productlist = [Product(i[0], i[1], i[2]) for i in productlist]\n \n def product_midle_price(self):\n \"\"\"Вычисление средней цены товаров\"\"\"\n total_quantity = 0\n total_sum = 0\n for elem in self.productlist:\n total_quantity += elem.quantity\n total_sum += elem.quantity * elem.price\n \n return \"%.2f\" % (total_sum / total_quantity)\n \n def most_expensive(self):\n \"\"\"Определение самого дорогого товара\"\"\"\n most_exp = self.productlist[0]\n for elem in self.productlist:\n if elem.price > most_exp.price:\n most_exp = elem\n \n return most_exp\n \n def most_cheapest(self):\n \"\"\"Определение самого дешевого товара\"\"\"\n most_cheap = self.productlist[0]\n for elem in self.productlist:\n if elem.price < most_cheap.price:\n most_cheap = elem\n \n return most_cheap\n \n def max_quantity(self):\n \"\"\"Определение товара с максимальным количеством\"\"\"\n maxq = self.productlist[0]\n for elem in self.productlist:\n if elem.quantity > maxq.quantity:\n maxq = elem\n \n return maxq\n \n def min_quantity(self):\n \"\"\"Определение товара с минимальным количеством\"\"\"\n minq = self.productlist[0]\n for elem in self.productlist:\n if elem.quantity < minq.quantity:\n minq = elem\n \n return minq\n \n def __str__(self):\n \"\"\"Формирование текстового вывода\"\"\"\n text = ' Начало списка' + '\\n'\n for elem in self.productlist:\n text += elem.__str__() + '\\n'\n text += ' Конец списка'\n \n return text\n\n\nif __name__ == \"__main__\":\n print('Это файл описания классов для товаров и списка товаров')\n print('Для тестирования программы запускать interface.py')\n","sub_path":"Core.py","file_name":"Core.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"379665320","text":"from django.contrib import auth\nfrom django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse,HttpResponseRedirect\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import *\nfrom .models import ResourceForProduct, ResourceForModule\nfrom django.db.models import Q\nfrom django.db.models import Sum, Count\nfrom django.contrib.auth.models import User\nfrom .models import ResourceForRequests\nfrom urllib import parse\n\n\n\ndef request_index(request):\n \"\"\"\n 接口列表首页\n :param request:\n :return:\n \"\"\"\n product_list = ResourceForProduct.objects.filter(abandon_flag=1)\n request_list = ResourceForRequests.objects.all()\n return render(request, 'request_index.html', locals())\n\n\ndef request_info(request):\n \"\"\"\n 接口信息首页\n :param request:\n :return:\n \"\"\"\n if request.method == \"GET\":\n id = request.GET.get('id')\n request_info = ResourceForRequests.objects.get(id=id)\n return render(request, 'request_info.html', locals())\n\n\ndef add_request(request):\n \"\"\"\n 添加接口信息的接口\n :param request:\n :return:\n \"\"\"\n if request.method == \"POST\":\n # .POST,可以获取请求中的所有数据\n info = request.POST\n user_id = request.user.id\n date = ResourceForRequests()\n # 先判断,字段是否存在,如果存在,则添加如果不存在,pass\n if info.__contains__('des-input'):\n date.des = str(info['des-input'])\n if info.__contains__('module-select'):\n date.module_id = int(info['module-select'])\n if info.__contains__('type-select'):\n date.type = str(info['type-select'])\n if info.__contains__('sendtype-select'):\n date.send_type = str(info['sendtype-select'])\n if info.__contains__('path-input'):\n date.path = str(info['path-input'])\n if info.__contains__('headers-input'):\n date.headers = str(info['headers-input'])\n if info.__contains__('params-input'):\n date.params = str(info['params-input'])\n date.created_by_id = user_id\n date.updated_by_id = user_id\n date.save()\n if str(date.id).isdigit():\n return JsonResponse({'status': 200, 'message': '添加接口成功'})\n else:\n return JsonResponse({'status': 201, 'message': '添加接口失败'})\n\n\ndef update_request(request):\n \"\"\"\n 更新接口信息的接口\n :param request:\n :return:\n \"\"\"\n if request.method == \"POST\":\n # .POST,可以获取请求中的所有数据\n info = request.POST\n user_id = request.user.id\n date_id = request.POST.get('id')\n print(info)\n date = ResourceForRequests.objects.get(id=date_id)\n # 先判断,字段是否存在,如果存在,则添加如果不存在,pass\n if info.__contains__('des'):\n date.des = str(info['des'])\n if info.__contains__('type'):\n date.type = str(info['type'])\n if info.__contains__('path'):\n # 前端url的转码\n date.path = parse.unquote(str(info['path']))\n if info.__contains__('abandon_flag'):\n date.abandon_flag = int(info['abandon_flag'])\n if info.__contains__('headers'):\n date.headers = str(info['headers'])\n date.updated_by_id = user_id\n date.save()\n if str(date.id).isdigit():\n return JsonResponse({'status': 200, 'message': '更新接口成功'})\n else:\n return JsonResponse({'status': 201, 'message': '更新接口失败'})","sub_path":"study/views_request.py","file_name":"views_request.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"68541880","text":"# -*- coding:utf-8 -*-\nimport struct\nimport time\nimport threading\nimport sys\nfrom Crypto.Cipher import AES\n\nimport pygatt\nimport websocket\n\nclass BLEAdapter:\n\tdef __init__(self, adapter):\n\t\tself.status = 0\n\t\tself.adapter = adapter\n\n\tdef connect(self, mac):\n\t\tself.adapter.start()\n\t\tprint('Connecting to %s...' % mac)\n\t\tdevice = self.adapter.connect(mac, address_type=pygatt.BLEAddressType.random)\n\t\tprint('Succeed')\n\t\treturn device\n\n\tdef wait4Unlock(self):\n\t\twhile (self.status == 1):\n\t\t\tpass\n\n\nclass itDEAL:\n\tdef __init__(self, dev_mac, adapter, wsc, dev_id=None, update_rate=-1):\n\t\tself.MAC_BAND = dev_mac\n\t\tself.UUID_NOITFY = 'f0080002-0451-4000-b000-000000000000'\n\t\tself.adapter = adapter\n\t\tself.wsc = wsc\n\t\tself.dev_id = dev_id\n\t\tif dev_id == None:\n\t\t\tself.dev_id = dev_mac\n\t\tself.update_rate = update_rate\n\t\tself.heartrate = -1\n\n\tdef cb_ble_notify(self, handle, value):\n\t\t_ = struct.unpack('>BB', value[:2])\n\t\tiHeader = _[0]\n\t\tiValue = _[1]\n\t\tif iHeader == 0xd0:\n\t\t\t# Heart rate\n\t\t\tself.heartrate = iValue\n\t\t\tprint('%s|%d' % (self.dev_id, iValue))\n\n\tdef start_hr(self):\n\t\tdevice = self.adapter.connect(self.MAC_BAND)\n\t\tdevice.subscribe(self.UUID_NOITFY, callback=self.cb_ble_notify, indication=True)\n\t\tdevice.char_write_handle(0x0011, b'\\xa1\\x00\\x00\\x00\\x07\\xe3\\x05\\x1e\\x13\\x09\\x09\\x01\\x00')\n\t\tdevice.char_write_handle(0x000e, b'\\x01\\x00')\n\t\tdevice.char_write_handle(0x0011, b'\\xd0\\x01')\n\t\tself.ts = time.time()\n\t\twhile True:\n\t\t\ttime.sleep(self.update_rate)\n\t\t\tif self.wsc != None:\n\t\t\t\tself.wsc.send('%s|%d' % (self.dev_id, self.heartrate))\n\n\tdef start(self):\n\t\tth = threading.Thread(target=self.start_hr)\n\t\tth.start()\n\n\nclass EPSON100:\n\tdef __init__(self, dev_mac, adapter, wsc, dev_id=None, update_rate=-1):\n\t\tself.MAC_BAND = dev_mac\n\t\tself.UUID_NOITFY = '00002a37-0000-1000-8000-00805f9b34fb'\n\t\tself.adapter = adapter\n\t\tself.wsc = wsc\n\t\tself.dev_id = dev_id\n\t\tif dev_id == None:\n\t\t\tself.dev_id = dev_mac\n\t\tself.ts = None\n\t\tself.update_rate = update_rate\n\t\tself.heartrate = 0\n\n\tdef cb_ble_notify(self, handle, value):\n\t\t_ = struct.unpack('>BB', value[:2])\n\t\tiValue = _[1]\n\t\t# Heart rate\n\t\tself.heartrate = iValue\n\t\tprint('%s|%d' % (self.dev_id, iValue))\n\n\tdef start_hr(self):\n\t\tdevice = self.adapter.connect(self.MAC_BAND)\n\t\tdevice.char_write_handle(0x0013, b'\\x01\\x00')\n\t\tprint('CMD sent')\n\t\tdevice.subscribe(self.UUID_NOITFY, callback=self.cb_ble_notify)\n\t\tself.ts = time.time()\n\t\twhile True:\n\t\t\ttime.sleep(self.update_rate)\n\t\t\tif self.wsc != None:\n\t\t\t\tself.wsc.send('%s|%d' % (self.dev_id, self.heartrate))\n\n\tdef start(self):\n\t\tth = threading.Thread(target=self.start_hr)\n\t\tth.start()\n\n\nclass Amazfit:\n\tdef __init__(self, dev_mac, adapter, wsc, dev_id=None, update_rate=-1):\n\t\tself.MAC_BAND = dev_mac\n\t\tself.UUID_NOITFY = '00000009-0000-3512-2118-0009af100700'\n\t\tself.UUID_HEART = '00002a37-0000-1000-8000-00805f9b34fb'\n\t\tself.KEY = b'\\x68\\x7b\\xdb\\xa8\\x75\\x2c\\xca\\xd5\\x25\\x6e\\x62\\x47\\x05\\xb0\\x9f\\xb9'\n\t\tself.adapter = adapter\n\t\tself.device = None\n\t\tself.status = 0\n\t\t# -1: auth failed\n\t\t# 0: none\n\t\t# 1: new device\n\t\t# 2: auth pass\n\t\tself.flag_key = 0\n\t\tself.flag_auth = 0\n\t\tself.randomFromDevice = None\n\t\tself.wsc = wsc\n\t\tself.dev_id = dev_id\n\t\tif dev_id == None:\n\t\t\tself.dev_id = dev_mac\n\t\tself.ts_ping = None\n\t\tself.ts_up = None\n\t\tself.update_rate = update_rate\n\t\tself.heartrate = -1\n\n\tdef __del__(self):\n\t\tself.device.char_write_handle(0x0067, b'\\x15\\x01\\x00')\n\n\tdef cb_ble_notify(self, handle, value):\n\t\tif self.status == 0:\n\t\t\tprint(value)\n\t\t\tif value[:3] == b'\\x10\\x01\\x01':\n\t\t\t\tself.status = 1\n\t\t\telif value[:3] == b'\\x10\\x02\\x01':\n\t\t\t\tself.randomFromDevice = bytes(value[3:])\n\t\t\telif value[:3] == b'\\x10\\x03\\x01':\n\t\t\t\tself.status = 2\n\t\t\telif value[:3] == b'\\x10\\x03\\x08':\n\t\t\t\tself.status = -1\n\t\telse:\n\t\t\t_ = struct.unpack('>BB', value)\n\t\t\tiValue = _[1]\n\t\t\t# Heart rate\n\t\t\tself.heartrate = iValue\n\t\t\tprint('%s|%d' % (self.dev_id, iValue))\n\n\tdef start_hr(self):\n\t\tself.device = self.adapter.connect(self.MAC_BAND)\n\t\tself.device.char_write_handle(0x000f, b'\\x02\\x00')\n\t\tself.device.char_write_handle(0x004c, b'\\x01\\x00')\n\t\tself.device.subscribe(self.UUID_NOITFY, callback=self.cb_ble_notify, indication=True)\n\t\t\n\t\t\n\t\twhile True:\n\t\t\tself.device.char_write_handle(0x004b, b'\\x02\\x00\\x01', wait_for_response=False)\n\t\t\t# The band should send the random string\n\t\t\twhile (self.randomFromDevice == None):\n\t\t\t\tpass\n\t\t\taes = AES.new(self.KEY, AES.MODE_ECB)\n\t\t\treply = b'\\x03\\x00' + aes.encrypt(self.randomFromDevice)\n\t\t\tself.device.char_write_handle(0x004b, reply, wait_for_response=False)\n\t\t\tprint('Encrypted string has been sent.')\n\t\t\twhile (self.status not in [-1, 2]):\n\t\t\t\tpass\n\n\t\t\tif self.status == -1:\n\t\t\t\tself.device.char_write_handle(0x004b, b'\\x01\\x00' + self.KEY, wait_for_response=False)\n\t\t\t\twhile (self.status == -1):\n\t\t\t\t\tpass\n\t\t\telif self.status == 2:\n\t\t\t\tbreak\n\n\t\tself.device.subscribe(self.UUID_HEART, callback=self.cb_ble_notify, indication=True)\n\t\tself.device.char_write_handle(0x0067, b'\\x15\\x01\\x01')\n\t\tself.device.char_write_handle(0x0067, b'\\x01\\x00')\n\t\tself.ts_up = time.time()\n\t\tself.ts_ping = time.time()\n\n\t\twhile True:\n\t\t\tif (self.wsc != None) and (time.time() - self.ts_up >= self.update_rate):\n\t\t\t\tself.wsc.send('%s|%d' % (self.dev_id, self.heartrate))\n\t\t\t\tself.ts_up = time.time()\n\t\t\tif time.time() - self.ts_ping >= 10.:\n\t\t\t\tself.device.char_write_handle(0x0067, b'\\x16')\n\t\t\t\tprint('Ping sent')\n\t\t\t\tself.ts_ping = time.time()\n\n\tdef start(self):\n\t\tth = threading.Thread(target=self.start_hr)\n\t\tth.start()\n\n\nif __name__ == '__main__':\n\n\tadapter = BLEAdapter(pygatt.GATTToolBackend())\n\n\ttry:\n\t\twsc = websocket.create_connection('ws://henchat.ml:9999')\n\texcept:\n\t\tprint('No websocket server.')\n\t\twsc = None\n\n\tif sys.argv[1] == 'itdeal':\n\t\tband1 = itDEAL('FA:81:66:C4:2B:28', adapter, wsc, update_rate=5.)\n\t\tband1.start()\n\n\telif sys.argv[1] == 'epson100':\n\t\tband2 = EPSON100('ff:ff:5e:20:aa:f1', adapter, wsc, update_rate=5.)\n\t\tband2.start()\n\n\telif sys.argv[1] == 'amazfit':\n\t\tband3 = Amazfit('d3:b9:0e:15:0f:27', adapter, wsc, update_rate=5.)\n\t\tband3.start()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"531554038","text":"# -*- coding: utf-8 -*-\n\nfrom django.db import migrations\nfrom django.contrib.auth.models import Group, Permission\n\nfrom dehaat.settings import ALL_GROUP_NAMES, ALL_PERMISSIONS\n\n\ndef link_permissions(apps, schema_editor):\n for g_name, p_names in ALL_PERMISSIONS.items():\n group = Group.objects.filter(name=g_name).first()\n if not group:\n continue\n permissions = Permission.objects.filter(codename__in=p_names)\n group.permissions.set(permissions)\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('useraccount', '0001_create_groups')\n ]\n\n operations = [\n migrations.RunPython(link_permissions)\n ]","sub_path":"dehaat/useraccount/migrations/0002_link_permissions.py","file_name":"0002_link_permissions.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"643023673","text":"import torch\n# import logging\nimport torch.nn as nn\nimport os\nfrom torch.utils.data.sampler import BatchSampler\nimport time\n\nfrom mean_teacher import architectures, datasets, cli\nfrom mean_teacher.data import NO_LABEL\nfrom mean_teacher.utils import *\n\n# LOG = logging.getLogger('main')\n\n\ndef create_model(arch, num_classes, word_vocab_embed, word_vocab_size,\n wordemb_size, hidden_size, ema=False):\n print(\"=> creating {pretrained}{ema}model '{arch}'\".format(\n pretrained='pre-trained ' if False else '',\n ema='EMA ' if ema else '',\n arch=arch))\n\n model_factory = architectures.__dict__[arch]\n model_params = dict(pretrained=False, num_classes=num_classes)\n\n model_params['word_vocab_embed'] = word_vocab_embed\n model_params['word_vocab_size'] = word_vocab_size\n model_params['wordemb_size'] = wordemb_size\n model_params['hidden_size'] = hidden_size\n model_params['update_pretrained_wordemb'] = False\n\n model = model_factory(**model_params)\n model = model.cpu() # nn.DataParallel(model).cpu() .. # NOTE: Disabling data parallelism\n\n if ema:\n for param in model.parameters():\n param.detach_()\n\n return model\n\n\ndef generate_prediction_minibatch(min_batch_id, mini_batch_outputs, dataset, batch_size, category_labels):\n\n min_batch_predictions_gold = list()\n softmax = nn.Softmax(dim=1)\n scores = softmax(mini_batch_outputs)\n res_max = torch.max(scores, dim=1)\n results = list(zip(res_max[0].data, res_max[1].data))\n\n for idx, (max_value, predictionId) in enumerate(results):\n dataset_id = (min_batch_id * batch_size) + idx\n mention_str = dataset.entity_vocab.get_word(dataset.mentions[dataset_id])\n gold_label = dataset.labels_str[dataset_id]\n min_batch_predictions_gold.append((mention_str, gold_label, category_labels[predictionId], max_value, list(scores[idx].data)))\n\n return min_batch_predictions_gold\n\n\ndef predict_validate(eval_loader, model, model_type, arch, dataset, batch_size, result_filename):\n class_criterion = nn.CrossEntropyLoss(size_average=False, ignore_index=NO_LABEL).cpu()\n meters = AverageMeterSet()\n\n category_labels = dict(enumerate(sorted(list({l for l in dataset.labels_str}))))\n # switch to evaluate mode\n model.eval()\n\n entity_prediction_gold_list = list()\n\n end = time.time()\n for i, datapoint in enumerate(eval_loader):\n meters.update('data_time', time.time() - end)\n\n if args.dataset in ['conll', 'ontonotes']:\n entity = datapoint[0][0]\n patterns = datapoint[0][1]\n target = datapoint[1]\n\n entity_var = torch.autograd.Variable(entity, volatile=True).cpu()\n patterns_var = torch.autograd.Variable(patterns, volatile=True).cpu()\n \n elif args.dataset in ['riedel']:\n inputs = datapoint[0]\n target = datapoint[1]\n\n input_entity1 = inputs[0]\n input_entity2 = inputs[1]\n input_inbetween_chunk = inputs[2]\n\n entity1_var = torch.autograd.Variable(input_entity1, volatile=True).cpu()\n entity2_var = torch.autograd.Variable(input_entity2, volatile=True).cpu()\n inbetween_chunk_var = torch.autograd.Variable(input_inbetween_chunk, volatile=True).cpu()\n\n target_var = torch.autograd.Variable(target.cpu(), volatile=True)\n\n minibatch_size = len(target_var)\n labeled_minibatch_size = target_var.data.ne(NO_LABEL).sum()\n meters.update('labeled_minibatch_size', labeled_minibatch_size)\n\n # compute output\n\n if arch == \"custom_embed\":\n output1, entity_custom_embed, pattern_custom_embed = model(entity_var, patterns_var)\n elif args.dataset in ['riedel'] and args.arch == 'simple_MLP_embed_RE':\n output1 = model(entity1_var, entity2_var, inbetween_chunk_var)\n else:\n output1 = model(entity_var, patterns_var)\n\n entity_prediction_gold_list += generate_prediction_minibatch(i, output1, dataset, batch_size, category_labels)\n\n class_loss = class_criterion(output1, target_var) / minibatch_size\n\n # measure accuracy and record loss\n prec1, prec2 = accuracy(output1.data, target_var.data, topk=(1, 2)) #Note: Ajay changing this to 2 .. since there are only 4 labels in CoNLL dataset\n meters.update('class_loss', class_loss.data[0], labeled_minibatch_size)\n meters.update('top1', prec1[0], labeled_minibatch_size)\n meters.update('error1', 100.0 - prec1[0], labeled_minibatch_size)\n meters.update('top2', prec2[0], labeled_minibatch_size)\n meters.update('error2', 100.0 - prec2[0], labeled_minibatch_size)\n\n # measure elapsed time\n meters.update('batch_time', time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print(\n 'Test: [{0}/{1}]\\t'\n 'ClassLoss {meters[class_loss]:.4f}\\t'\n 'Prec@1 {meters[top1]:.3f}'.format(\n i, len(eval_loader), meters=meters))\n\n print(' * Prec@1 {top1.avg:.3f}\\tClassLoss {class_loss.avg:.3f}'\n .format(top1=meters['top1'], class_loss=meters['class_loss']))\n\n result_filename += \"_\"+model_type+\".txt\"\n print(\"Writing the predictions and the gold labels to the file :=> \" + result_filename)\n with open(result_filename, 'w') as rf:\n for item in entity_prediction_gold_list:\n scores = \", \".join([str(v) for v in item[4]])\n rf.write(item[0] + \"\\t\" + item[1] + \"\\t\" + item[2] + \"\\t\" + str(item[3]) + \"\\t\" + scores+\"\\n\")\n rf.close()\n print(\"DONE ..\")\n return meters['top1'].avg\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n labeled_minibatch_size = max(target.ne(NO_LABEL).sum(), 1e-8)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / labeled_minibatch_size))\n return res\n\n\ndef create_data_loaders(train_transformation,\n eval_transformation,\n datadir,\n args):\n\n evaldir = os.path.join(datadir, args.eval_subdir) # NOTE: test data is the same as train data. To load the word_vectors using the train_subdir\n print(\"evaldir : \" + evaldir)\n\n if args.dataset in ['conll', 'ontonotes']:\n dataset_test = datasets.NECDataset(evaldir, args, eval_transformation)\n\n eval_loader = torch.utils.data.DataLoader(dataset_test,\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=2 * args.workers,\n pin_memory=False,\n drop_last=False)\n elif args.dataset in ['riedel']:\n dataset_test = datasets.REDataset(evaldir, args, eval_transformation, 'test')\n\n eval_loader = torch.utils.data.DataLoader(dataset_test,\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=2 * args.workers,\n pin_memory=False,\n drop_last=False)\n\n return eval_loader, dataset_test\n\n\nif __name__ == '__main__':\n\n # 1. Set the following arguments\n ckpt_file = sys.argv[1] # \"best.ckpt\"\n dataset_name = sys.argv[2] # 'conll'\n result_file_name = sys.argv[3] # \"predictions\"\n print (\"Loading the checkpoint from : \" + ckpt_file)\n print (\"Working on the dataset :=> \" + dataset_name)\n\n word_embed_size = 300\n hidden_size = 50\n batch_size = 64\n\n # 2. Initialize the configuration\n ckpt = torch.load(ckpt_file)\n arch = ckpt['arch']\n parser = cli.create_parser()\n parser.set_defaults(dataset=dataset_name,\n train_subdir='train',\n eval_subdir='val',\n arch=arch,\n pretrained_wordemb=True,\n word_noise='drop:1',\n batch_size=batch_size)\n args = parser.parse_known_args()[0]\n\n # 3. Load the eval data\n dataset_config = datasets.__dict__[args.dataset]()\n num_classes = dataset_config.pop('num_classes')\n eval_loader, dataset = create_data_loaders(**dataset_config, args=args)\n word_vocab_embed = dataset.word_vocab_embed\n word_vocab_size = dataset.word_vocab.size()\n\n # 4. Load the models\n student_model = create_model(arch, num_classes, word_vocab_embed,\n word_vocab_size, word_embed_size, hidden_size, ema=False)\n\n teacher_model = create_model(arch, num_classes, word_vocab_embed,\n word_vocab_size, word_embed_size, hidden_size, ema=True)\n\n # 5. Init model state dicts\n student_model.load_state_dict(ckpt['state_dict'])\n teacher_model.load_state_dict(ckpt['ema_state_dict'])\n\n # 6. Call the evaluation code AND # 7. Generate the predictions file for the student model and the teacher model\n predict_validate(eval_loader, student_model, \"student\", args.arch, dataset, args.batch_size, result_file_name)\n predict_validate(eval_loader, teacher_model, \"teacher\", args.arch, dataset, args.batch_size, result_file_name)\n\n\n\n","sub_path":"pytorch/generate_predictions.py","file_name":"generate_predictions.py","file_ext":"py","file_size_in_byte":9670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"601723549","text":"import logging\nimport random\n\nfrom django.contrib import messages\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse\nfrom django.views.generic import View, CreateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http.response import JsonResponse\nfrom .models import Match, Response, Like\nfrom .forms import ResponseForm\n\nlogeer = logging.getLogger(__name__)\n\n\nclass IndexView(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'janken/index.html')\n\n\nindex = IndexView.as_view()\n\n\nclass ResultView(View):\n def get(self, request, pk, *args, **kwargs):\n match = get_object_or_404(Match, pk=pk)\n # match.opponent_handを文字へ変換\n if match.opponent_hand == 0:\n opponent_hand = 'rock'\n elif match.opponent_hand == 1:\n opponent_hand = 'peace'\n elif match.opponent_hand == 2:\n opponent_hand = 'paper'\n else:\n opponent_hand == ''\n # そのレスポンスをLikeしているか, ゲストのときError回避のため分岐\n if request.user.is_active: \n is_like = Like.objects.filter(user=request.user, response=match.response).exists()\n else: \n is_like = False\n return render(request, 'janken/result.html',context={'match': match, 'opponent_hand': opponent_hand, 'is_like': is_like})\n\n\nresult = ResultView.as_view()\n\n\nclass MatchView(View):\n \"\"\"\n LoginUserならばPOSTメソッドで処理し、DB保存リダリレクト。GuestUserならばGETメソッドで処理し、DB不保存レンダリング。\n \"\"\"\n\n def post(self, request, *args, **kwargs):\n user_hand = int(request.POST.get('user_hand'))\n result, opponent_hand = janken(user_hand)\n # レスポンスを結果からランダム選択\n response_list = Response.objects.filter(result=result)\n response = random.choice(response_list)\n match = Match(\n user=request.user,\n response = response,\n user_hand = user_hand,\n opponent_hand = opponent_hand,\n result = result\n )\n match.save()\n return redirect('janken:result', pk=match.pk, )\n\n def get(self, request, *args, **kwargs):\n user_hand = int(request.GET.get('user_hand'))\n result, opponent_hand = janken(user_hand)\n response_list = Response.objects.filter(result=result)\n response = random.choice(response_list)\n if opponent_hand == 0:\n opponent_hand = 'rock'\n elif opponent_hand == 1:\n opponent_hand = 'peace'\n elif opponent_hand == 2:\n opponent_hand = 'paper'\n else:\n opponent_hand == ''\n context = {\n 'user_hand': user_hand,\n 'result': result, \n 'opponent_hand': opponent_hand,\n 'response': response,\n }\n return render(request, 'janken/result.html', context=context)\n\n\n\n\nmatch = MatchView.as_view()\n\n\ndef janken(user_hand):\n \"\"\"user_handを引数に、(result, opponent_hand)を返す.それぞれの確率は等しい。\n \n Parameters\n ----------\n user_hand : [int]\n [0 or 1 or 2 でそれぞれ グー チョキ パー。]\n \n Return\n ----------\n [result, opponent_hand] : [int, int]\n [-1 or 0 or 1 でそれぞれ 負け あいこ 勝ち。], [0 or 1 or 2]\n \"\"\"\n # 結果を確率で求める\n result = random.random()\n if result >= 2/3:\n result = 1\n elif result >= 1/3:\n result = 0\n else:\n result = -1\n \n # 結果からopponent_handを求める\n if result == 0:\n opponent_hand = user_hand\n elif user_hand + result == 3:\n opponent_hand = 0\n elif user_hand + result == -1:\n opponent_hand = 2\n else:\n opponent_hand = user_hand + result\n\n return result, opponent_hand\n \n\n\nclass ProfileView(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'janken/profile.html')\n\n\nprofile = ProfileView.as_view()\n\n\nclass ResponseLikeAjaxView(LoginRequiredMixin, View):\n \"\"\"\n いいねが押されたときデータをAjaxで返す\n \"\"\"\n def post(self, request, response_id, *args, **kwargs):\n response = get_object_or_404(Response, pk=response_id)\n is_like = Like.objects.filter(user=request.user, response=response).exists()\n # unlike\n if is_like:\n liking = Like.objects.get(user=request.user, response=response)\n liking.delete()\n response.like_num -= 1\n response.save()\n data = {\n 'is_like': is_like,\n 'like_num': response.like_num\n }\n return JsonResponse(data)\n # like\n response.like_num += 1\n response.save()\n like = Like()\n like.user = request.user\n like.response = response\n like.save()\n data = {\n 'is_like': is_like,\n 'like_num': response.like_num\n }\n return JsonResponse(data) \n\n\nresponseLikeAjax = ResponseLikeAjaxView.as_view()\n\n\nclass ResponseNewView(LoginRequiredMixin, View):\n \"\"\"\n Responseデータを作成\n \"\"\"\n def get(self, request, *args, **kwargs):\n return render(request, 'janken/response_edit.html', {'form': ResponseForm()})\n\n def post(self, request, *args, **kwargs):\n form = ResponseForm(request.POST)\n if not form.is_valid():\n return render(request, 'janken/response_edit.html', {'form': form})\n \n response = form.save(commit=False)\n response.author = request.user\n response.save()\n return redirect('janken:response_detail', response_id=response.pk)\n\n\nresponseNew = ResponseNewView.as_view()\n\n\nclass ResponseEditView(LoginRequiredMixin, View):\n \"\"\"\n Responseデータを編集\n \"\"\"\n def get(self, request, response_id, *args, **kwargs):\n response = get_object_or_404(Response, pk=response_id, author=request.user)\n form = ResponseForm(instance=response) \n return render(request, 'janken/response_edit.html', {'form': form})\n\n def post(self, request, response_id, *args, **kwargs):\n response = get_object_or_404(Response, pk=response_id, author=request.user)\n form = ResponseForm(request.POST, instance=response)\n if not form.is_valid():\n render(request, 'janken/response_edit.html', {'form': form})\n \n response.save()\n return redirect('janken:response_detail', response_id=response.pk)\n\n\nresponseEdit = ResponseEditView.as_view()\n\n\nclass ResponseRemoveView(LoginRequiredMixin, View):\n \"\"\"\n Responseデータを削除\n \"\"\"\n def get(self, request, response_id, *args, **kwargs):\n response = get_object_or_404(Response, pk=response_id, author=request.user)\n return render(request, 'janken/response_confirm_delete.html', {'response': response})\n\n def post(self, request, response_id, *args, **kwargs):\n response = get_object_or_404(Response, pk=response_id, author=request.user)\n response.delete()\n return redirect('janken:response_list')\n \n\nresponseRemove = ResponseRemoveView.as_view()\n\n\nclass ResponseListView(LoginRequiredMixin, View):\n \"\"\"\n Responseのリスト表示\n \"\"\"\n def get(self, request, *args, **kwargs):\n response_list = Response.objects.filter(author=request.user).order_by('-created_at')\n return render(request, 'janken/response_list.html', {'response_list': response_list})\n\n\nresponseList = ResponseListView.as_view()\n\n\nclass ResponseDetailView(LoginRequiredMixin, View):\n \"\"\"\n Responseの詳細表示\n \"\"\"\n def get(self, request, response_id, *args, **kwargs):\n response = get_object_or_404(Response, pk=response_id)\n is_like = Like.objects.filter(user=request.user, response=response).exists() \n return render(request, 'janken/response_detail.html', {'response': response, 'is_like': is_like})\n\n\nresponseDetail = ResponseDetailView.as_view()\n\n\nclass MatchListView(LoginRequiredMixin, View):\n \"\"\"\n Matchのリスト表示\n \"\"\"\n def get(self, request, *args, **kwargs):\n match_list = Match.objects.filter(user=request.user).order_by('-match_time')\n return render(request, 'janken/match_list.html', {'match_list': match_list})\n\n\nmatchList = MatchListView.as_view()\n\n\nclass MatchDetailView(LoginRequiredMixin, View):\n \"\"\"\n Matchの詳細表示\n \"\"\"\n def get(self, request, match_id, *args, **kwargs):\n match = get_object_or_404(Match, pk=match_id)\n # match.opponent_handを文字へ変換\n if match.opponent_hand == 0:\n opponent_hand = 'rock'\n elif match.opponent_hand == 1:\n opponent_hand = 'peace'\n elif match.opponent_hand == 2:\n opponent_hand = 'paper'\n else:\n opponent_hand == ''\n is_like = Like.objects.filter(user=request.user, response=match.response).exists()\n return render(request, 'janken/match_detail.html', {'match': match, 'is_like': is_like, 'opponent_hand': opponent_hand})\n\n\nmatchDetail = MatchDetailView.as_view()\n\n\nclass MatchLikeListView(LoginRequiredMixin, View):\n \"\"\"\n MatchのLikeリスト表示\n \"\"\"\n def get(self, request, *args, **kwargs):\n responseLikeList = Response.objects.filter(like__user=request.user)\n matchLike_list = []\n for responseLike in responseLikeList:\n matchLike = Match.objects.filter(user=request.user, response=responseLike)[0]\n matchLike_list.append(matchLike)\n # matchLike_list = Match.objects.filter(response__like__user=request.user, user=request.user)\n return render(request, 'janken/matchLike_list.html', {'matchLike_list': matchLike_list})\n\n\nmatchList = MatchListView.as_view()","sub_path":"janken/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"353292241","text":"# Notes from video lectures\n\n# Part of the standard library\nfrom datetime import datetime\nfrom datetime import date\n\n# datetime is a Python module used for dates and times\n\nprint(datetime.today())\n# prints 2018-09-08 23:13:39.124279\n\nprint(date.today())\n# prints 2018-09-08\n\nchristmas = date(2018, 12, 25)\n\nchristmas - todaydate\n# datetime.timedelta(x amount of days)\n\n# timedelta is used to specify time calculations\nfrom datetime import datetime\nfrom datetime import timedelta\n\nt = timedelta(days=4, hours=10)\n\n# Seconds has limitation of max of one day\nt.seconds\nt.days\n\neta = timedelta(hours=6)\n\ntoday = datetime.today()\n\ntoday + eta\n\nstr(today + eta)\n\n\n","sub_path":"100_Days_of_Code/Days_1-3/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"153181581","text":"import sys\n\ndef max_length(h1, h2, h3):\n l1, l2, l3 = 0, 0, 0\n for each in h1:\n l1 = l1 + each\n for each in h2:\n l2 = l2 + each\n for each in h3:\n l3 = l3 + each\n while l1 !=0 and l2 != 0 and l3 != 0 and (l1!=l2 or l2!=l3):\n if max(l1, l2, l3) == l1:\n l1 = l1 - h1[0]\n h1.pop(0)\n elif max(l1, l2, l3) == l2:\n l2 = l2 - h2[0]\n h2.pop(0)\n else:\n l3 = l3 - h3[0]\n h3.pop(0)\n else:\n if l1==l2 and l2==l3:\n return l1\n else:\n return 0\n \n\n\nn1,n2,n3 = input().strip().split(' ')\nn1,n2,n3 = [int(n1),int(n2),int(n3)]\nh1 = [int(h1_temp) for h1_temp in input().strip().split(' ')]\nh2 = [int(h2_temp) for h2_temp in input().strip().split(' ')]\nh3 = [int(h3_temp) for h3_temp in input().strip().split(' ')]\n##\nprint(max_length(h1, h2, h3))","sub_path":"equalstack.py","file_name":"equalstack.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"512376399","text":"from pystac.models.base import STACObject\nfrom marshmallow import (\n Schema,\n fields\n)\n\n\nclass Band(STACObject):\n def __init__(self, common_name, gsd,\n center_wavelength, effective_bandwidth,\n image_band_index):\n \"\"\"Band object used in product specifications\n\n Args:\n common_name (str): common, human readable name for band used in UIs\n gsd (float): ground sampling distance\n center_wavelength (float): central wavelength\n effective_bandwidth (float): bandwidth of band\n image_band_index (int): index of band in source file\n\n \"\"\"\n self.common_name = common_name\n self.gsd = gsd\n self.center_wavelength = center_wavelength\n self.effective_bandwidth = effective_bandwidth\n self.image_band_index = image_band_index\n\n @property\n def dict(self):\n return dict(\n common_name=self.common_name,\n gsd=self.gsd,\n center_wavelength=self.center_wavelength,\n effective_bandwidth=self.effective_bandwidth,\n image_band_index=self.image_band_index\n )\n \n @property\n def json(self):\n return BandSchema().dumps(\n self\n )\n\n\nclass BandSchema(Schema):\n\n common_name = fields.Str()\n gsd = fields.Float()\n center_wavelength = fields.Float()\n effective_bandwidth = fields.Float()\n image_band_index = fields.Integer()","sub_path":"pystac/models/extensions/band.py","file_name":"band.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"578929306","text":"\"\"\"\nExtension that implements tags, a way to store pieces of useful text for later.\n\"\"\"\n\nimport datetime\nimport re\nfrom collections import namedtuple\nfrom typing import Union\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import clean_content, guild_only\n\nfrom dog import Cog\nfrom dog.core import checks, utils\nfrom dog.core.context import DogbotContext\n\nTag = namedtuple('Tag', 'name value creator created_at uses')\n\n\nclass Tagging(Cog):\n async def create_tag(self, ctx: DogbotContext, name: str, value: str):\n insert = \"\"\"\n INSERT INTO tags\n (name, guild_id, creator_id, value, uses, created_at)\n VALUES ($1, $2, $3, $4, 0, $5)\n \"\"\"\n await self.bot.pgpool.execute(insert, name, ctx.guild.id,\n ctx.author.id, value,\n datetime.datetime.utcnow())\n\n async def edit_tag(self, name: str, value: str):\n await self.bot.pgpool.execute(\n 'UPDATE tags SET value = $1 WHERE name = $2', value, name)\n\n async def get_tag(self, ctx: DogbotContext, name: str) -> Union[None, Tag]:\n \"\"\"Finds a tag, and returns it as a :class:``Tag`` object.\"\"\"\n query = \"\"\"\n SELECT * FROM tags\n WHERE guild_id = $1 AND name = $2\n \"\"\"\n record = await self.bot.pgpool.fetchrow(query, ctx.guild.id, name)\n\n if not record:\n return None\n\n creator = ctx.guild.get_member(\n record['creator_id']) or record['creator_id']\n return Tag(\n value=record['value'],\n creator=creator,\n uses=record['uses'],\n name=name,\n created_at=record['created_at'])\n\n async def delete_tag(self, ctx: DogbotContext, name: str):\n \"\"\"Deletes a tag.\"\"\"\n await self.bot.pgpool.execute(\n 'DELETE FROM tags WHERE guild_id = $1 AND name = $2', ctx.guild.id,\n name)\n\n def can_touch_tag(self, ctx: DogbotContext, tag: Tag) -> bool:\n \"\"\"Returns whether someone can touch a tag (modify, delete, or edit it).\"\"\"\n perms = ctx.author.guild_permissions\n\n predicates = [\n # they can manage the server\n perms.manage_guild,\n\n # they own the server\n ctx.author.guild.owner == ctx.author,\n\n # they created the tag\n tag.creator == ctx.author,\n\n # is dogbot moderator\n checks.member_is_moderator(ctx.author)\n ]\n\n return any(predicates)\n\n @commands.group(invoke_without_command=True)\n @commands.guild_only()\n async def tag(self,\n ctx,\n name: clean_content,\n *,\n value: clean_content = None):\n \"\"\"\n Tag related operations.\n\n If you provide a value, a tag is created if it doesn't exist. If it\n does exist, it will be overwritten provided that you can touch that\n tag.\n\n If you don't provide a value, the tag's contents are sent.\n\n You may only touch a tag if any of the following conditions are met:\n You have the \"Manage Server\" permission,\n you are the owner of the server.\n you have created that tag.\n you are a Dogbot Moderator.\n \"\"\"\n\n # a value was provided, create or overwrite a tag\n if value:\n tag = await self.get_tag(ctx, name)\n\n # tag already exists, check if we can touch it\n if tag and not self.can_touch_tag(ctx, tag):\n # cannot overwrite\n return await ctx.send(\n \"\\N{NO PEDESTRIANS} You can't overwrite that tag's contents.\"\n )\n\n # set a tag\n if tag:\n await self.edit_tag(name, value)\n else:\n await self.create_tag(ctx, name, value)\n\n # we good\n await ctx.ok('\\N{MEMO}' if tag else '\\N{DELIVERY TRUCK}')\n\n return\n\n # see the value of a tag\n tag = await self.get_tag(ctx, name)\n\n if tag:\n # send the tag's value\n await ctx.send(tag.value)\n\n # increment usage count\n update = \"\"\"\n UPDATE tags\n SET uses = uses + 1\n WHERE name = $1 AND guild_id = $2\n \"\"\"\n await self.bot.pgpool.execute(update, name, ctx.guild.id)\n else:\n await ctx.send('Tag not found.')\n\n @tag.command(name='list', aliases=['ls'])\n @guild_only()\n async def tag_list(self, ctx):\n \"\"\"Lists tags in this server.\"\"\"\n tags = await self.bot.pgpool.fetch(\n 'SELECT * FROM tags WHERE guild_id = $1', ctx.guild.id)\n tag_names = [record['name'] for record in tags]\n\n if not tags:\n return await ctx.send('There are no tags in this server.')\n\n try:\n await ctx.send(\n f'**{len(tag_names)} tag(s):** ' + ', '.join(tag_names))\n except discord.HTTPException:\n await ctx.send('There are too many tags to display.')\n\n @tag.command(name='delete', aliases=['rm', 'remove', 'del'])\n @guild_only()\n async def tag_delete(self, ctx: DogbotContext, name):\n \"\"\"\n Deletes a tag.\n\n You may only do so if you can touch that tag. For more information,\n see d?help tag.\n \"\"\"\n tag = await self.get_tag(ctx, name)\n\n if not tag:\n return await ctx.send('Tag not found.')\n\n if not self.can_touch_tag(ctx, tag):\n return await ctx.send('\\N{NO PEDESTRIANS} You can\\'t do that.')\n\n await self.delete_tag(ctx, name)\n await ctx.ok('\\N{PUT LITTER IN ITS PLACE SYMBOL}')\n\n @tag.command(name='markdown', aliases=['raw'])\n @guild_only()\n async def tag_markdown(self, ctx: DogbotContext, name):\n \"\"\"Views the markdown of a tag.\"\"\"\n tag = await self.get_tag(ctx, name)\n\n if not tag:\n return await ctx.send('Tag not found.')\n\n content = tag.value\n escape_regex = r'(`|\\*|~|_|<|\\\\)'\n # no, those two strings can't be together\n content = re.sub(escape_regex, r'\\\\' + '\\\\1', content)\n\n await ctx.send(content)\n\n @tag.command(name='info', aliases=['about'])\n @guild_only()\n async def tag_info(self, ctx: DogbotContext, name):\n \"\"\"Shows you information about a certain tag.\"\"\"\n tag = await self.get_tag(ctx, name)\n\n if tag:\n embed = discord.Embed(title=tag.name, description=tag.value)\n embed.add_field(\n name='Created',\n value=utils.standard_datetime(tag.created_at) + ' UTC')\n embed.add_field(\n name='Created by', value=tag.creator.mention, inline=False)\n embed.add_field(name='Uses', value=tag.uses)\n await ctx.send(embed=embed)\n else:\n await ctx.send('Tag not found.')\n\n\ndef setup(bot):\n bot.add_cog(Tagging(bot))\n","sub_path":"dog/ext/tagging.py","file_name":"tagging.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"6386147","text":"import os.path\nimport logging\nlogger = logging.getLogger('giza.operations.deploy')\n\nfrom giza.config.helper import fetch_config, new_credentials_config\nfrom giza.core.app import BuildApp\nfrom giza.deploy import Deploy, deploy_target\nfrom giza.operations.sphinx import sphinx_publication\nfrom giza.tools.command import command\nfrom giza.tools.serialization import ingest_yaml_list, dict_from_list\n\nimport argh\nimport onetimepass as otp\n\n@argh.arg('--target', '-t', nargs='*', dest='push_targets')\n@argh.arg('--dry-run', '-d', action='store_true', dest='dry_run')\n@argh.named('deploy')\n@argh.expects_obj\ndef main(args):\n c = fetch_config(args)\n app = BuildApp(c)\n\n deploy_worker(c, app)\n\n@argh.arg('--deploy', '-d', nargs='*', dest='push_targets')\n@argh.arg('--edition', '-e', nargs='*', dest='editions_to_build')\n@argh.arg('--language', '-l', nargs='*',dest='languages_to_build')\n@argh.arg('--builder', '-b', nargs='*', default='html')\n@argh.arg('--serial_sphinx', action='store_true')\n@argh.named('push')\n@argh.expects_obj\ndef publish_and_deploy(args):\n c = fetch_config(args)\n app = BuildApp(c)\n\n sphinx_ret = sphinx_publication(c, args, app)\n if sphinx_ret == 0 or c.runstate.force is True:\n deploy_worker(c, app)\n else:\n logger.warning(sphinx_ret + ' sphinx build(s) failed, and build not forced. not deploying.')\n\ndef deploy_worker(c, app):\n pconf = c.system.files.data.push\n pconf = dict_from_list('target', pconf)\n\n backgrounds = []\n\n for target in c.runstate.push_targets:\n d = Deploy(c)\n\n target_pconf = pconf[target]\n\n if target_pconf['env'] == 'publication':\n target_pconf['env'] = 'production'\n\n d.load(target_pconf)\n\n for cmd in d.deploy_commands():\n task = app.add('task')\n task.args = ' '.join(cmd)\n task.job = deploy_target\n task.target = \"\"\n task.depends = os.path.join(c.paths.projectroot, c.paths.public_site_output)\n\n if c.runstate.dry_run is True:\n logger.info('dry run: {0}'.format(' '.join(cmd)))\n\n if c.runstate.dry_run is False:\n app.run()\n\n logger.info('completed deploy for: {0}'.format(' '.join(c.runstate.push_targets)))\n\n@argh.named('code')\n@argh.expects_obj\ndef twofa_code(args):\n creds = new_credentials_config()\n\n print(otp.get_totp(creds.corp.seed))\n","sub_path":"giza/giza/operations/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"210706175","text":"## SETUP\nimport pygame ## For using pygame functions.\nimport random \n\npygame.init() ## Initialize the pygame environment.\npygame.display.set_caption(\"Lab 1: 2D Sidescroller\")\nscreenWidth = 720\nscreenHeight = 480\nwin = pygame.display.set_mode((screenWidth, screenHeight))\npygame.mixer.init()\n\n#Music/sound effects initialized\nmusec = pygame.mixer.music.load('./lasagna time.wav')\npygame.mixer.music.play(-1)\n\ndef bonk():\n pygame.mixer.Sound.play(pygame.mixer.Sound('./fart.wav'))\n\n## VARIABLES\ns = 0\nTIME_DELAY = 25 ## Control keypress sensitivity\nvelocity = 8\nxposMax = 7200\nisJumping = False ## To know if player is in the \"air\" or not\nmovingForward = False\njonleft = False\ntime = 0.0 ## To calculate player's height when jumping\nhalfScreenWidth = screenWidth / 2\n\n## FONTS\npygame.font.init() \nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\ntimerfont = pygame.font.SysFont('Times New Roman', 30)\n\n## TARGETS\nTarget = dict()\nnTargets = 10 ##number of targets\ndistanceBetweenTargets = 9 * screenWidth / nTargets\ntargetName = './Target.png'\nasurf = pygame.image.load(targetName)\nfor i in range(0, nTargets):\n n = random.randint(170,220)\n dictEntryTargets = {'name': targetName,\n 'x': 480 + i * distanceBetweenTargets, ##make uniform\n 'y': n,##make random\n 'width':64,\n 'height':64,\n 'img': asurf,\n 'blit':True,\n 'score':False,\n 'lock':False,\n 'TargetNum':i}\n Target[i] = dictEntryTargets\n\n## AVATAR\nAVATAR = {'colour': [255,255,255], 'width': 40, 'height': 75}\nplayer = {'x': screenWidth / 2, 'y': screenHeight / 2, 'name': 'Jon'}\ncamera = {'x': None, 'y': 0, 'name': 'Camera 0', 'misc': None} ## Camera x-pos relies on player.\njonl = './Cursedjonbutactuallyleftcursedjon.png'\njonr = './CursedJon.png'\ngoingright = pygame.image.load(jonr)\ngoingleft = pygame.image.load(jonl)\njonsprite = {'name': jonr,\n 'x': screenWidth,\n 'y': 0,\n 'width':40,\n 'height':60,\n 'img': goingright}\n\ndef drawAvatar(avatar): \n if (jonleft == True):\n jonsprite['name'] = jonl\n jonsprite['img'] = goingleft\n\n if (jonleft == False):\n jonsprite['name'] = jonr\n jonsprite['img'] = goingright\n\n win.blit(jonsprite['img'], (screenWidth/2 - int(avatar['width']/2),\n 398 - int(avatar['height']/2),\n avatar['width'],\n avatar['height']))\n\n## BACKGROUND IMAGES\nBG = dict() ## Add images to dictionary. (key,name, xy position, colour)\nnBG = 10 ## Number of backgrounds\nfor i in range(0, nBG):\n imageName = './Bck_' + str(i) + '.png' ## Set the input path.\n asurf = pygame.image.load(imageName) ## Load the image onto a surface.\n ## Set up a dictionary, add image as an entry. Dictionaries can contain multiple entries.\n dictEntry = {'name': imageName,\n 'x': i * screenWidth,\n 'y': 0,\n 'img': asurf}\n BG[i] = dictEntry\n\n## clamp(x) = x if xmin <= x <= xmax, xmin if x < xmin, xmax if x > xmax\ndef clamp(x,xmin,xmax):\n if (x > xmax): return xmax\n elif (x < xmin): return xmin\n else: return x\n\nRUN = True\nDRAW = True\n\n## MAIN GAME LOOP #####################################################################################\nwhile (RUN):\n ticks = pygame.time.get_ticks() ## Update time\n\n if (player['x'] < xposMax):\n ## find correct images to display, based on starting position\n camera['x'] = clamp(player['x'], halfScreenWidth, nBG * screenWidth - halfScreenWidth)\n it = 0 \n while ((camera['x'] - BG[it]['x']) >= screenWidth):\n it += 1\n xpos = BG[it]['x'] - camera['x'] + halfScreenWidth ## Set the x position. \n \n ## Draw the image at the proper location.\n if (DRAW):\n win.blit(BG[it]['img'], (BG[it]['x'] - camera['x'] + halfScreenWidth, BG[it]['y']))\n\n ## Draw previous or next image if necessary. If xpos=0, only one image needs to be drawn.\n if (xpos != 0):\n if (xpos < 0):\n it +=1 ## Next image needs to be drawn.\n else:\n it -= 1 ## Previous image needs to be drawn.\n ## Draw the other image.\n win.blit(BG[it]['img'], (BG[it]['x'] - camera['x'] + halfScreenWidth, BG[it]['y']))\n\n ##draw targets\n for i in range(0,nTargets):\n if (Target[i]['blit']==True):\n win.blit(Target[i]['img'], (Target[i]['x'] - camera['x'] + halfScreenWidth, Target[i]['y']))\n \n ## Draw the avatar last, ontop of the images.\n drawAvatar(AVATAR)\n\n win.blit(BG[it]['img'], (BG[it]['x'] - camera['x'] + halfScreenWidth, BG[it]['y']))\n\n ## Draw game objects\n drawAvatar(AVATAR)\n win.blit(timerfont.render('Time: ' + str(ticks/1000), False, (0,0,0)), (20,10))\n win.blit(myfont.render('Score = ' + str(s), False, (0,0,0)), (560,10))\n \n ## DEBUG STUFF (feel free to remove this later)\n debugfont = pygame.font.SysFont('Times New Roman', 17)\n win.blit(debugfont.render('playerX = ' + str(player['x']), False, (0,0,0)), (10,70))\n win.blit(debugfont.render('playerY = ' + str(player['y']), False, (0,0,0)), (10,90))\n win.blit(debugfont.render('cameraX = ' + str(camera['x']), False, (0,0,0)), (10,110))\n win.blit(debugfont.render('cameraY = ' + str(camera['y']), False, (0,0,0)), (10,130))\n win.blit(debugfont.render('avatarWidth = ' + str(AVATAR['width']), False, (0,0,0)), (10,150))\n win.blit(debugfont.render('avatarHeight = ' + str(AVATAR['height']), False, (0,0,0)), (10,170))\n fontLocation = 50\n for i in range(0, nTargets):\n fontLocation = fontLocation + 20\n win.blit(debugfont.render('target' + str(i) + 'X = ' + str(Target[i]['x']), False, (0,0,0)), (580,fontLocation))\n fontLocation = fontLocation + 15\n win.blit(debugfont.render('target' + str(i) + 'Y = ' + str(Target[i]['y']), False, (0,0,0)), (580,fontLocation))\n\n ## TARGET / SCORE\n for i in range(0,nTargets):\n if (Target[i]['blit']==True):\n win.blit(Target[i]['img'], (Target[i]['x'] - camera['x'] + halfScreenWidth, Target[i]['y']))\n if (Target[i]['score']==True and Target[i]['lock']==False):\n s+=1\n bonk()\n Target[i]['score']=False\n Target[i]['lock']=True\n\n ## CHECK FOR EVENTS\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n RUN = False\n if ((ticks/1000) >= 90):\n print('game ended')\n pygame.quit()\n\n ## UPDATE DISPLAY \n pygame.display.update()\n pygame.time.delay(TIME_DELAY) ## Decrease sensitivity\n\n ## Player Movement\n keys = pygame.key.get_pressed() ## Check input\n if (keys[pygame.K_LEFT]):\n player['x'] -= velocity\n jonleft = True\n movingForward = False ## Left is not forward.\n elif (keys[pygame.K_RIGHT]):\n player['x'] += velocity\n jonleft = False\n movingForward = True\n elif (keys[pygame.K_ESCAPE]):\n RUN = False\n else: ##If player is not moving, they are not moving forward\n movingForward = False\n\n## PLAYER JUMPING SYSTEM\n ## Calculate character's height as a function of time\n AVATAR['height'] = 76 + (-time)*(time - 45)\n ## Ensure time will keep calculating until player hits ground\n if (isJumping == False and keys[pygame.K_UP]):\n isJumping = True\n if (isJumping == True):\n time = time + 1\n DRAW = True\n ## Keep player on ground after a jump\n if (AVATAR['height'] < 75):\n time = 0\n isJumping = False\n AVATAR['height'] = 75\n\n##Collision detection\n ##might need to do 10 if statements\n ##because only register x value\n ##loop for every target\n for i in range(0, nTargets):\n if (player['x'] < Target[i]['x'] + Target[i]['width'] and\n player['x'] + jonsprite['width'] > Target[i]['x'] and\n AVATAR['height'] < Target[i]['y'] + Target[i]['height'] and\n AVATAR['height'] + jonsprite['height'] > Target[i]['y'] and\n movingForward == True):\n Target[i]['blit'] = False\n Target[i]['score'] = True ## update score, cant be reused\n \n ## Ensure the player stays in the game world\n player['x'] = clamp(player['x'], halfScreenWidth, xposMax)\n\n## Exit the pygame environment\npygame.quit()\n","sub_path":"pygameLab.py","file_name":"pygameLab.py","file_ext":"py","file_size_in_byte":8603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"395622931","text":"# This file is part of the Extra-P software (http://www.scalasca.org/software/extra-p)\n#\n# Copyright (c) 2020-2021, Technical University of Darmstadt, Germany\n#\n# This software may be modified and distributed under the terms of a BSD-style license.\n# See the LICENSE file in the base directory for details.\n\nimport math\nfrom typing import Optional, Sequence\n\nimport numpy\nfrom PySide2.QtCore import * # @UnusedWildImport\nfrom PySide2.QtGui import * # @UnusedWildImport\nfrom PySide2.QtWidgets import * # @UnusedWildImport\n\nfrom extrap.entities.calltree import Node\nfrom extrap.entities.metric import Metric\nfrom extrap.gui.ParameterValueSlider import ParameterValueSlider\nfrom extrap.gui.TreeModel import TreeModel\nfrom extrap.gui.TreeView import TreeView\nfrom extrap.modelers.model_generator import ModelGenerator\n\n\nclass SelectorWidget(QWidget):\n def __init__(self, mainWidget, parent):\n super(SelectorWidget, self).__init__(parent)\n self.main_widget = mainWidget\n self.tree_model = TreeModel(self)\n self.parameter_sliders = list()\n self.initUI()\n self._sections_switched = False\n\n # noinspection PyAttributeOutsideInit\n def initUI(self):\n self.grid = QGridLayout(self)\n self.setLayout(self.grid)\n\n # Model selection\n model_label = QLabel(\"Model:\", self)\n self.model_selector = QComboBox(self)\n self.model_selector.currentIndexChanged.connect(self.model_changed)\n\n # model_list = list()\n self.updateModelList()\n\n # Metric selection\n metric_label = QLabel(\"Metric:\", self)\n self.metric_selector = QComboBox(self)\n self.metric_selector.currentIndexChanged.connect(\n self.metric_index_changed)\n\n # Callpath selection\n self.tree_view = TreeView(self)\n\n # Input variable values\n self.asymptoticCheckBox = QCheckBox('Show model', self)\n self.asymptoticCheckBox.toggle()\n self.asymptoticCheckBox.stateChanged.connect(\n self.changeAsymptoticBehavior)\n\n # Positioning\n self.grid.addWidget(model_label, 0, 0)\n self.grid.addWidget(self.model_selector, 0, 1)\n self.grid.addWidget(metric_label, 1, 0)\n self.grid.addWidget(self.metric_selector, 1, 1)\n self.grid.addWidget(self.tree_view, 2, 0, 1, 2)\n self.grid.addWidget(self.asymptoticCheckBox, 3, 1, Qt.AlignRight)\n self.grid.setColumnStretch(1, 1)\n\n def createParameterSliders(self):\n for param in self.parameter_sliders:\n param.clearRowLayout()\n self.grid.removeWidget(param)\n del self.parameter_sliders[:]\n experiment = self.main_widget.getExperiment()\n parameters = experiment.parameters\n for i, param in enumerate(parameters):\n new_widget = ParameterValueSlider(self, param, self)\n self.parameter_sliders.append(new_widget)\n self.grid.addWidget(new_widget, i + 4, 0, 1, 2)\n\n def fillCalltree(self):\n self.tree_model = TreeModel(self)\n self.tree_view.setModel(self.tree_model)\n self.tree_view.header().setDefaultSectionSize(65)\n # increase width of \"Callpath\" and \"Value\" columns\n self.tree_view.setColumnWidth(0, 150)\n self.tree_view.setColumnWidth(3, 150)\n if not self._sections_switched:\n self.tree_view.header().swapSections(0, 1)\n self._sections_switched = True\n self.tree_view.header().setMinimumSectionSize(23)\n self.tree_view.header().resizeSection(1, 23)\n self.tree_view.header().resizeSection(2, 23)\n selectionModel = self.tree_view.selectionModel()\n selectionModel.selectionChanged.connect(\n self.callpath_selection_changed)\n\n def callpath_selection_changed(self):\n callpath_list = self.getSelectedCallpath()\n # self.dict_callpath_color = {}\n self.main_widget.populateCallPathColorMap(callpath_list)\n self.main_widget.updateAllWidget()\n\n def fillMetricList(self):\n self.metric_selector.clear()\n experiment = self.main_widget.getExperiment()\n if experiment is None:\n return\n metrics = experiment.metrics\n for metric in metrics:\n name = metric.name if metric.name != '' else ''\n self.metric_selector.addItem(name, metric)\n\n def changeAsymptoticBehavior(self):\n self.tree_model.valuesChanged()\n\n def getSelectedMetric(self) -> Metric:\n return self.metric_selector.currentData()\n\n def getSelectedCallpath(self) -> Sequence[Node]:\n indexes = self.tree_view.selectedIndexes()\n callpath_list = list()\n\n for index in indexes:\n # We only care for the first column, otherwise we would get the same callpath repeatedly for each column\n if index.column() != 0:\n continue\n callpath = self.tree_model.getValue(index)\n callpath_list.append(callpath)\n return callpath_list\n\n def getCurrentModel(self) -> Optional[ModelGenerator]:\n model = self.model_selector.currentData()\n return model\n\n def renameCurrentModel(self, newName):\n index = self.model_selector.currentIndex()\n self.getCurrentModel().name = newName\n self.model_selector.setItemText(index, newName)\n\n def getModelIndex(self):\n return self.model_selector.currentIndex()\n\n def selectLastModel(self):\n self.model_selector.setCurrentIndex(self.model_selector.count() - 1)\n\n def updateModelList(self):\n experiment = self.main_widget.getExperiment()\n if not experiment:\n return\n models_list = experiment.modelers\n self.model_selector.clear()\n for model in models_list:\n self.model_selector.addItem(model.name, model)\n # self.main_widget.data_display.updateWidget()\n # self.update()\n\n def model_changed(self):\n # index = self.model_selector.currentIndex()\n # text = str(self.model_selector.currentText())\n\n # Introduced \" and text != \"No models to load\" \" as a second guard since always when the text would be\n # \"No models to load\" the gui would crash.\n # if model != None and text != \"No models to load\":\n # generator = model._modeler\n self.main_widget.selector_widget.tree_model.valuesChanged()\n\n self.main_widget.updateAllWidget()\n self.update()\n\n def model_rename(self):\n index = self.getModelIndex()\n if index < 0:\n return\n result = QInputDialog.getText(self,\n 'Rename Current Model',\n 'Enter new name', QLineEdit.EchoMode.Normal)\n new_name = result[0]\n if result[1] and new_name:\n self.renameCurrentModel(new_name)\n\n def model_delete(self):\n reply = QMessageBox.question(self,\n 'Delete Current Model',\n \"Are you sure to delete the model?\",\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.No)\n if reply == QMessageBox.Yes:\n index = self.getModelIndex()\n experiment = self.main_widget.getExperiment()\n if index < 0:\n return\n\n self.model_selector.removeItem(index)\n del experiment.modelers[index]\n\n @staticmethod\n def get_all_models(experiment):\n if experiment is None:\n return None\n models = experiment.modelers\n if len(models) == 0:\n return None\n return models\n\n def metric_index_changed(self):\n self.main_widget.metricIndexChanged()\n self.tree_model.on_metric_changed()\n\n def getParameterValues(self):\n ''' This functions returns the parameter value list with the\n parameter values from the bottom of the calltree selection.\n This information is necessary for the evaluation of the model\n functions, e.g. to colot the severity boxes.\n '''\n value_list = []\n for param in self.parameter_sliders:\n value_list.append(param.getValue())\n return value_list\n\n def iterate_children(self, paramValueList, callpaths, metric):\n ''' This is a helper function for getMinMaxValue.\n It iterates the calltree recursively.\n '''\n value_list = list()\n for callpath in callpaths:\n model = self.getCurrentModel().models.get((callpath.path, metric))\n if model is None:\n continue\n\n formula = model.hypothesis.function\n value = formula.evaluate(paramValueList)\n if not math.isinf(value):\n value_list.append(value)\n children = callpath.childs\n value_list += self.iterate_children(paramValueList,\n children, metric)\n return value_list\n\n def getMinMaxValue(self):\n ''' This function calculated the minimum and the maximum values that\n appear in the call tree. This information is e.g. used to scale\n legends ot the color line at the bottom of the extrap window.\n '''\n value_list = list()\n experiment = self.main_widget.getExperiment()\n if experiment is None:\n value_list.append(1)\n return value_list\n selectedMetric = self.getSelectedMetric()\n if selectedMetric is None:\n value_list.append(1)\n return value_list\n param_value_list = self.getParameterValues()\n call_tree = experiment.call_tree\n nodes = call_tree.get_nodes()\n previous = numpy.seterr(divide='ignore', invalid='ignore')\n value_list.extend(self.iterate_children(param_value_list,\n nodes,\n selectedMetric))\n numpy.seterr(**previous)\n if len(value_list) == 0:\n value_list.append(1)\n return value_list\n","sub_path":"extrap/gui/SelectorWidget.py","file_name":"SelectorWidget.py","file_ext":"py","file_size_in_byte":10131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"34567622","text":"import numpy as np\nimport time\nimport datetime\nimport matplotlib.pyplot as ply\nimport talib\n\ndef get_sma(d, p):\n return np.average(d[-p:, 1])\n\ndef get_ema(d, p):\n sma = get_sma(d[:-1],p)\n part1 = d[-1,1] * (2/(1+p))\n part2 = sma * (1-(2/(1+p)))\n part3 = part1 + part2\n return part3\n\ndef get_action2(d):\n ma0 = talib.EMA(d[-500:,1],10)[-1]\n ma1 = talib.EMA(d[-500:,1],20)[-1]\n ma2 = talib.EMA(d[-500:,1],200)[-1]\n close = d[-1,1]\n if close > ma2 and ma0 > ma1:\n return 'call'\n elif close < ma2 and ma0 < ma1:\n return 'put'\n else:\n return None\n\ndef get_action(d):\n # 4, 9, 13\n ma0 = talib.EMA(d,4)\n ma1 = talib.EMA(d,9)\n ma2 = talib.EMA(d,13)\n data = [{'col':'Green','val':ma0},\n {'col':'Yellow','val':ma1},\n {'col':'Red','val':ma2},\n {'col':'Line','val':d[-1,1]}]\n data.sort(key=lambda a : a['val'], reverse=True)\n print([i['col'] for i in data])\n #print(f'{ma0:.5f} {ma1:.5f} {ma2:.5f}', end=' ')\n if ma0 > ma1 and ma1 > ma2 and d[-1,1] > ma0:\n #if ma0 > ma1:\n return 'call'\n elif ma0 < ma1 and ma1 < ma2 and d[-1,1] < ma0:\n #elif ma0 < ma1:\n return 'put'\n else:\n return None\n\ndef countdown():\n n = datetime.datetime.now().second\n while n != 58:\n print('counting down', n, end='\\r')\n time.sleep(1)\n n = datetime.datetime.now().second\n\ndef run_forex_temp(iq):\n initial_balance = iq.get_balance()\n print('initial_balance =', initial_balance)\n iq.buy_forex('buy')\n time.sleep(20)\n iq.close_forex()\n terminal_balance = iq.get_balance()\n print('termnal_balance =', terminal_balance)\n print(round(terminal_balance - initial_balance,2))\n\ndef final(iq, initial_balance):\n while not iq.all_positions_closed_forex():\n if iq.num_open_positions == 1:\n print(f'{iq.num_open_positions} position is still open', end='\\r')\n else:\n print(f'{iq.num_open_positions} positions are still open', end='\\r')\n time.sleep(10)\n terminal_balance = iq.get_balance()\n max_len = max(len(str(initial_balance)), len(str(terminal_balance)))\n net_profit = terminal_balance - initial_balance\n print(' '*40)\n print(f' initial_balance: {initial_balance:>{max_len}}')\n print(f'terminal_balance: {terminal_balance:>{max_len}}')\n print(f' net_profit: {net_profit:>{max_len}.2f} USD')\n print(f' net_profit: {net_profit * 30.09:>{max_len}.2f} THB')\n\ndef get_action3(d):\n ma2 = talib.EMA(d[:,1],50)[-1]\n close = d[-1,1]\n #print('ma2:', round(ma2,5), ' close:', close)\n if close > ma2:\n return 'call'\n elif close < ma2:\n return 'put'\n else:\n return None\n\ndef run_forex2(iq):\n actions = {'put':'sell', 'call':'buy',\n 'long':'buy','short':'sell',\n None:'None'}\n initial_balance = iq.get_balance()\n itt = 10\n iterations = itt\n while iterations > 0:\n iq.reconnect_after_30_minutes()\n data = np.array(iq.get_candles())\n init_action = get_action3(data)\n action = init_action\n while action == init_action:\n data = np.array(iq.get_candles())\n action = get_action3(data)\n print('action:', action, ' - init_action:', init_action)\n print('iterations:', iterations, ' itt:', itt, ' nums:')\n if iterations != itt:\n iq.close_all_forex()\n iq.buy_forex(actions[action])\n iterations -= 1\n print('iter:', iterations)\n final(iq,initial_balance)\n\ndef run_forex(iq):\n #iterations = 3\n initial_balance = iq.get_balance()\n print()\n print('initial_balance =', initial_balance)\n print()\n actions = {'put':'sell', 'call':'buy',\n 'long':'buy','short':'sell',\n None:'None'}\n b1 = None\n b2 = None\n current_action = None\n current_status = None\n info = {}\n profit = 0\n iterations = 10\n while iterations > 0:\n #countdown()\n iq.reconnect_after_30_minutes()\n data = np.array(iq.get_candles())\n #action = get_action(data)\n action = get_action2(data)\n info['newact'] = actions[action]\n '''\n print('current_action:',current_action,\n ' actions[action]:', actions[action],\n ' status:', current_status)\n '''\n if action == None:\n current_action = None\n time.sleep(2)\n continue\n # ===\n else:\n if iq.all_positions_closed_forex():\n iq.buy_forex(actions[action])\n current_action = action\n iterations -= 1\n print('iterations:', iterations)\n else:\n if action != current_action:\n iq.close_all_forex()\n\n # ===\n #===\n '''\n elif current_action != actions[action]:\n iterations -= 1\n if current_status == 'open':\n iq.close_forex()\n else:\n b1 = iq.get_balance()\n b2 = iq.get_balance()\n profit += b2 - b1\n b1 = b2\n iq.buy_forex(actions[action])\n elif current_action == actions[action]:\n if current_status == 'closed':\n iterations -= 1\n b2 = iq.get_balance()\n profit += b2-b1\n b1 = b2\n iq.buy_forex(actions[action])\n\n current_action, current_status = iq.get_position_forex()\n current_action = actions[current_action]\n info['action'] = current_action\n info['status'] = current_status\n info['P/L'] = round(profit,2)\n info['iter'] = iterations\n for k,v in info.items():\n print(f'{k}: {str(v):>6}', end=' | ')\n print()\n '''\n #===\n '''\n if action == 'call':\n if current_action == 'short':\n iq.close_forex()\n iq.buy_forex('buy')\n iterations -= 1\n elif current_action is None or current_status == 'closed':\n iq.buy_forex('buy')\n iterations -= 1\n elif action == 'put':\n if current_action == 'long':\n iq.close_forex()\n iq.buy_forex('sell')\n iterations -= 1\n elif current_action is None or current_status == 'closed':\n iq.buy_forex('sell')\n iterations -= 1\n current_action, current_status = iq.get_position_forex()\n info['action'] = current_action\n info['P/L'] = round(iq.get_balance() - initial_balance,2)\n for k,v in info.items():\n print(k,':',v, end=' ')\n print()\n '''\n\n #iq.close_forex()\n while not iq.all_positions_closed_forex():\n if iq.num_open_positions == 1:\n print(f'{iq.num_open_positions} position is still open', end='\\r')\n else:\n print(f'{iq.num_open_positions} positions are still open', end='\\r')\n time.sleep(10)\n terminal_balance = iq.get_balance()\n max_len = max(len(str(initial_balance)), len(str(terminal_balance)))\n net_profit = terminal_balance - initial_balance\n print(' '*40)\n print(f' initial_balance: {initial_balance:>{max_len}}')\n print(f'terminal_balance: {terminal_balance:>{max_len}}')\n print(f' net_profit: {net_profit:>{max_len}.2f} USD')\n print(f' net_profit: {net_profit * 30.09:>{max_len}.2f} THB')\n\ndef run(iq, expiration_mode):\n iterations = 3\n initial_balance = iq.get_balance()\n print('initial_balance =', initial_balance)\n while iterations > 0:\n countdown()\n data = iq.get_candles()\n data = np.array(data)\n action = get_action(data)\n if action is not None:\n print(f'action: {action:>{4}} balance: {iq.get_balance()-initial_balance:.2f}')\n iq.buy(action, check_result=False)\n iterations -= 1\n else:\n time.sleep(60*expiration_mode)\n\n time.sleep(60 * expiration_mode)\n terminal_balance = iq.get_balance()\n max_len = max(len(str(initial_balance)), len(str(terminal_balance)))\n net_profit = terminal_balance - initial_balance\n print()\n print(f' initial_balance: {initial_balance:>{max_len}}')\n print(f'terminal_balance: {terminal_balance:>{max_len}}')\n print(f' net_profit: {net_profit:>{max_len}.2f} USD')\n print(f' net_profit: {net_profit * 30.09:>{max_len}.2f} THB')\n\ndef back_test():\n import os, sys\n sys.path.append(os.getcwd())\n for _, i in enumerate(sys.path):\n print(_,i)\n from practice_data import practice_data\n ptd = practice_data()\n all_data = ptd.all_data\n num_data = 50\n for data in all_data:\n actions = []\n for idx in range(num_data,data.shape[0]):\n #print(data[idx-num_data:idx].shape)\n d = data[idx-num_data:idx]\n action = get_action3(d)\n #print(action)\n actions.append(action)\n print(set(actions))\n break\n\nif __name__ == '__main__':\n back_test()\n","sub_path":"strategies/three_emas.py","file_name":"three_emas.py","file_ext":"py","file_size_in_byte":9116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"409162666","text":"import os\r\nfrom setuptools import setup, find_packages\r\n\r\nwith open(os.path.join(os.path.dirname(__file__), 'README.txt')) as f:\r\n long_description = f.read()\r\n\r\nsetup(\r\n name=\"pyshark\",\r\n version=\"0.3.3\",\r\n packages=find_packages(),\r\n package_data={'': ['*.ini', '*.pcapng']},\r\n install_requires=['lxml', 'py', 'trollius', 'logbook'],\r\n url=\"sudo https_proxy=https://10.88.218.46:443 https://github.com/KimiNewt/pyshark\",\r\n long_description=long_description,\r\n author=\"KimiNewt\",\r\n description=\"Python wrapper for tshark, allowing python packet parsing using wireshark dissectors\",\r\n keywords=\"wireshark capture packets parsing packet\",\r\n use_2to3=True,\r\n)","sub_path":"pyshark_setup.py","file_name":"pyshark_setup.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"152278443","text":"import sys\r\nimport io\r\nfrom os import walk\r\n\r\nspecified_input = iter([\r\n \"45\", \"10.00\", \"50\", \"12.50\", \"30\", \"9.25\",\r\n \"11\", \"16\", \"21\",\r\n \"1900\", \"2008\", \"8000\",\r\n \"20\", \"6\", \"14\"\r\n])\r\n \r\nold_input = input\r\n\r\n#redefine input\r\ndef input(*x):\r\n global specified_input\r\n\r\n #a = old_input()\r\n a = next(specified_input)\r\n\r\n if x[0]:\r\n print(x[0], a, sep=\"\")\r\n else:\r\n print(a)\r\n\r\n return a\r\n\r\n# Path where all the lab files are\r\nfolder_path = \"Q:\\\\computer science\\\\Courses\\\\Bitterman\\\\19FA-COMP-150-01\\\\weaverz\\\\lab03\"\r\n# Place where the finished report is placed\r\noutput_path = \"output.txt\"\r\n\r\n# Getting all filenames from the folder\r\nf = []\r\nfor (dirpath, dirnames, filenames) in walk(folder_path):\r\n f.extend(filenames)\r\n break\r\n\r\n# Saving sys.stdout for later (as it gets overwritten)\r\nold_stdout = sys.stdout\r\n\r\n# Open the output file for further use\r\noutput_file = open(output_path, \"w\")\r\n\r\n# Loop through all the files found\r\nfor i in f:\r\n\r\n print(i)\r\n\r\n # Make sure this file is a python file\r\n if i.split(\".\")[-1] != \"py\":\r\n continue\r\n\r\n # Get the full filename\r\n filename = folder_path + \"\\\\\" + i\r\n\r\n # Write the file header (=====MyFile.py=====)\r\n output_file.write(\"=====\")\r\n output_file.write(i)\r\n output_file.write(\"=====\")\r\n output_file.write(\"\\n\\n\")\r\n\r\n # Write the content of the file\r\n with open(filename) as file:\r\n output_file.write(file.read())\r\n\r\n # Write the result header (-----result-----)\r\n output_file.write(\"\\n\")\r\n output_file.write(\"-----result-----\\n\")\r\n\r\n for i in range(3):\r\n \r\n output_file.write(\"\\n\")\r\n # Run the program plus save the printed thing \r\n sys.stdout = buffer = io.StringIO()\r\n exec(compile(open(filename, \"rb\").read(), filename, 'exec'), None, None)\r\n sys.stdout = old_stdout\r\n \r\n # Write output of the code and three GE signs to show the program finished\r\n output_file.write(buffer.getvalue())\r\n output_file.write(\">>>\\n\\n\")\r\n\r\n# Finish up\r\noutput_file.close()\r\nprint(\"done\")\r\n","sub_path":"make_report.py","file_name":"make_report.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"49018880","text":"import time\nimport json\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\nhostName = \"localhost\"\nhostPort = 8080\n\nclass MyServer(BaseHTTPRequestHandler):\n def do_all(self):\n # Assume that paths starts with stub/, just for testing right now\n path = self.path[6:]\n print(self.command)\n file_name = \"responses/%s/%s.json\" % (self.command, path.replace(\"/\", \"_\"))\n\n try:\n response_file = open(file_name)\n except FileNotFoundError:\n response_file = open(\"responses/defaultResponse.json\")\n json_data = json.load(response_file)\n response_file.close()\n\n # Build the response\n self.send_response(json_data[\"code\"])\n headers = json_data.get(\"headers\", {})\n for key in headers:\n self.send_header(key, headers[key])\n self.end_headers()\n self.wfile.write(bytes(json.dumps(json_data[\"body\"]), \"utf-8\"))\n\n def do_GET(self):\n json_data = self.do_all()\n \n def do_POST(self):\n json_data = self.do_all()\n\n\n# Initialize the server\nmyServer = HTTPServer((hostName, hostPort), MyServer)\nprint(time.asctime(), \"Server Starts - %s:%s\" % (hostName, hostPort))\n\ntry:\n myServer.serve_forever()\nexcept KeyboardInterrupt:\n pass\n\nmyServer.server_close()\nprint(time.asctime(), \"Server Stops - %s:%s\" % (hostName, hostPort))\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"176082420","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 5 19:20:52 2019\n\n@author: User1\n\"\"\"\nnums = [1,1,2]\nindex = [1,2]\n\ndef removeDuplicates(nums):\n result = 0\n index = []\n for num in nums:\n if num not in index:\n nums.insert(result,num)\n result += 1\n index.append(num)\n print(nums)\n return result\n\nprint(removeDuplicates(nums))","sub_path":"pythonscripts/removeDuplicates.py","file_name":"removeDuplicates.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"23001240","text":"from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nfrom . import views\n\n\napp_name = 'feed'\npost_list = views.PostViewSet.as_view(dict(get='list', post='create'))\npost_detail = views.PostViewSet.as_view(dict(get='retrieve',\n put='update',\n patch='partial_update',\n delete='destroy'\n ))\n\nurlpatterns = [\n\n path(r'posts/', post_list, name='post-list'),\n path(r'posts/create', post_list, name='post-create'),\n path(r'posts/', post_detail, name='post'),\n path(r'posts//update', post_detail, name='post-update'),\n path(r'posts//delete', post_detail, name='post-delete'),\n path(r'posts/rate', views.rate_post, name='rate'),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"feed/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"133521429","text":"# -*- coding:utf-8 -*-\nimport os\nimport sys\n\nfrom functools import wraps\nfrom argparse import Action, _SubParsersAction\n\n\nclass ArgparseHelper(Action):\n \"\"\"\n 显示格式友好的帮助信息\n \"\"\"\n\n def __init__(self,\n option_strings,\n dest=\"\",\n default=\"\",\n help=None):\n super(ArgparseHelper, self).__init__(\n option_strings=option_strings,\n dest=dest,\n default=default,\n nargs=0,\n help=help)\n\n def __call__(self, parser, namespace, values, option_string=None):\n parser.print_help()\n subparsers_actions = [\n action for action in parser._actions\n if isinstance(action, _SubParsersAction)]\n for subparsers_action in subparsers_actions:\n for choice, subparser in subparsers_action.choices.items():\n print(\"Command '{}'\".format(choice))\n print(subparser.format_usage())\n\n parser.exit()\n\n\ndef load_function(function_str):\n \"\"\"\n 返回字符串表示的函数对象\n :param function_str: module1.module2.function\n :return: function\n \"\"\"\n if not function_str:\n return\n mod_str, _sep, function_str = function_str.rpartition('.')\n return getattr(__import__(\n mod_str, fromlist=mod_str.split(\".\")[-1]), function_str)\n\n\ndef cache_property(func):\n \"\"\"\n 缓存属性,只计算一次\n :param func:\n :return:\n \"\"\"\n @property\n @wraps(func)\n def wrapper(*args, **kwargs):\n if func.__name__ not in args[0].__dict__:\n args[0].__dict__[func.__name__] = func(*args, **kwargs)\n return args[0].__dict__[func.__name__]\n return wrapper\n\n\nasync def readexactly(steam, n):\n if steam._exception is not None:\n raise steam._exception\n\n blocks = []\n while n > 0:\n block = await steam.read(n)\n if not block:\n break\n blocks.append(block)\n n -= len(block)\n\n return b''.join(blocks)\n\n\ndef find_source():\n sys.path.insert(0, os.getcwd())\n try:\n source = __import__(\"sources\")\n sources = dict()\n for k in dir(source):\n if k.endswith(\"Source\") and k != \"Source\":\n sources[k] = getattr(source, k)\n return sources\n except ImportError:\n pass","sub_path":"async_downloader/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"604943195","text":"# https://www.hackerrank.com/challenges/kangaroo/problem\n\ndef kangaroo(l):\n x1 = l[0]\n v1 = l[1]\n x2 = l[2]\n v2 = l[3]\n if x1 != x2 and v1 == v2:\n print(\"NO\")\n elif x1 == x2 and v1 == v2:\n print(\"YES\")\n \n elif x1 == x2 and v1 > v2 :\n print(\"NO\")\n \n elif x1 <= x2 and v1 <= v2 :\n print(\"NO\")\n \n else :\n if (x2 - x1) % (v1 - v2) == 0 : \n print(\"YES\")\n \n else :\n print(\"NO\")\n \n\nif __name__ == '__main__':\n n = list(map(int, input().rstrip().split()))\n kangaroo(n)\n","sub_path":"Problem Solving/Algorithms/Implementation/Kangaroo.py","file_name":"Kangaroo.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"528291121","text":"import click\nimport redis\nfrom prometheus_client import start_http_server\nimport signal\n\nfrom huey_exporter.signal_listener import SignalListener\nfrom huey_exporter.exporter_logging import logger\nfrom huey_exporter.queue_length.thread import QueueLengthThread\n\n\nqueue_length_thread: QueueLengthThread = None\n\n\n\n\n\n@click.command()\n@click.option('--connection-string', '-c',\n envvar='REDIS_CONNECTION_STRING',\n default='redis://localhost:6379',\n help='Connection string to redis including database. for example redis://localhost:6379/0'\n )\n@click.option('--port', '-p',\n envvar='EXPORTER_PORT',\n default=9100,\n type=click.IntRange(0, 65535),\n help='Port to expose the metrics on'\n )\n@click.option('--logging-level', '-l',\n envvar='LOGGING_LEVEL',\n default='INFO',\n help='Set the logging level of the huey-exporter'\n )\ndef run_exporter(connection_string, port, logging_level):\n logger.setLevel(logging_level)\n\n # Start up the server to expose the metrics.\n start_http_server(port)\n connection_pool = redis.BlockingConnectionPool.from_url(\n connection_string,\n max_connections=5,\n timeout=10\n )\n\n start_queue_length_monitoring(connection_pool)\n\n queue = SignalListener(connection_pool)\n queue.listen()\n\n\ndef exit_monitoring_gracefully(*args):\n queue_length_thread.exit_gracefully()\n queue_length_thread.join()\n logger.info('thread joined')\n exit()\n\n\ndef start_queue_length_monitoring(connection_pool):\n \"\"\"\n Start a thread which pulls the length of the huey queue.\n :param connection_pool:\n :return:\n \"\"\"\n global queue_length_thread\n queue_length_thread = QueueLengthThread(connection_pool)\n queue_length_thread.start()\n\n signal.signal(signal.SIGINT, exit_monitoring_gracefully)\n signal.signal(signal.SIGTERM, exit_monitoring_gracefully)\n\n\ndef main():\n run_exporter()\n\n\nif __name__ == '__main__':\n run_exporter()\n","sub_path":"huey_exporter/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"238276888","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nimport os\nimport pathlib\nimport subprocess\nimport unittest\nfrom pathlib import Path\nfrom typing import Tuple\n\nfrom eden.test_support.temporary_directory import TemporaryDirectoryMixin\n\nfrom .lib import edenclient, overlay as overlay_mod, repobase, testcase\n\n\nFSCK_RETCODE_OK = 0\nFSCK_RETCODE_SKIPPED = 1\nFSCK_RETCODE_WARNINGS = 2\nFSCK_RETCODE_ERRORS = 3\n\n\nclass FsckTest(testcase.EdenRepoTest):\n overlay: overlay_mod.OverlayStore\n\n def populate_repo(self) -> None:\n self.repo.write_file(\"README.md\", \"tbd\\n\")\n self.repo.write_file(\"proj/src/main.c\", \"int main() { return 0; }\\n\")\n self.repo.write_file(\"proj/src/lib.c\", \"void foo() {}\\n\")\n self.repo.write_file(\"proj/src/include/lib.h\", \"#pragma once\\nvoid foo();\\n\")\n self.repo.write_file(\n \"proj/test/test.sh\", \"#!/bin/bash\\necho test\\n\", mode=0o755\n )\n self.repo.write_file(\"doc/foo.txt\", \"foo\\n\")\n self.repo.write_file(\"doc/bar.txt\", \"bar\\n\")\n self.repo.symlink(\"proj/doc\", \"../doc\")\n self.repo.commit(\"Initial commit.\")\n\n def create_repo(self, name: str) -> repobase.Repository:\n return self.create_hg_repo(\"main\")\n\n def setup_eden_test(self) -> None:\n super().setup_eden_test()\n self.overlay = overlay_mod.OverlayStore(self.eden, self.mount_path)\n\n def run_fsck(self, *args: str) -> Tuple[int, str]:\n \"\"\"Run `eden fsck [args]` and return a tuple of the return code and\n the combined stdout and stderr.\n\n The command output will be decoded as UTF-8 and returned as a string.\n \"\"\"\n cmd_result = self.eden.run_unchecked(\n \"fsck\", *args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n )\n fsck_out = cmd_result.stdout.decode(\"utf-8\", errors=\"replace\")\n return (cmd_result.returncode, fsck_out)\n\n def test_fsck_force_and_check_only(self) -> None:\n \"\"\"Test the behavior of the --force and --check-only fsck flags.\"\"\"\n foo_overlay_path = self.overlay.materialize_file(pathlib.Path(\"doc/foo.txt\"))\n\n # Running fsck with the mount still mounted should fail\n returncode, fsck_out = self.run_fsck(self.mount)\n self.assertIn(f\"Not checking {self.mount}\", fsck_out)\n self.assertEqual(FSCK_RETCODE_SKIPPED, returncode)\n\n # Running fsck with --force should override that\n returncode, fsck_out = self.run_fsck(self.mount, \"--force\")\n self.assertIn(f\"warning: could not obtain lock\", fsck_out)\n self.assertIn(f\"scanning anyway due to --force\", fsck_out)\n self.assertIn(f\"Checking {self.mount}\", fsck_out)\n self.assertEqual(FSCK_RETCODE_OK, returncode)\n\n # fsck should perform the check normally without --force\n # if the mount is not mounted\n self.eden.run_cmd(\"unmount\", self.mount)\n returncode, fsck_out = self.run_fsck(self.mount)\n self.assertIn(f\"Checking {self.mount}\", fsck_out)\n self.assertIn(\"No issues found\", fsck_out)\n self.assertEqual(FSCK_RETCODE_OK, returncode)\n\n # Truncate the overlay file for doc/foo.txt to 0 length\n with foo_overlay_path.open(\"wb\"):\n pass\n\n # Running fsck with --check-only should report the error but not try to fix it.\n returncode, fsck_out = self.run_fsck(\"--check-only\")\n self.assertIn(f\"Checking {self.mount}\", fsck_out)\n self.assertRegex(\n fsck_out,\n r\"invalid overlay file for materialized file .* \\(doc/foo.txt\\).*: \"\n r\"zero-sized overlay file\",\n )\n self.assertRegex(fsck_out, r\"\\b1 errors\")\n self.assertRegex(fsck_out, \"Not fixing errors: --check-only was specified\")\n self.assertEqual(FSCK_RETCODE_ERRORS, returncode)\n\n # Running fsck with no arguments should attempt to fix the errors\n returncode, fsck_out = self.run_fsck()\n self.assertRegex(\n fsck_out,\n r\"invalid overlay file for materialized file .* \\(doc/foo.txt\\).*: \"\n r\"zero-sized overlay file\",\n )\n self.assertRegex(fsck_out, r\"\\b1 errors\")\n self.assertRegex(fsck_out, \"Beginning repairs\")\n self.assertRegex(\n fsck_out, \"replacing corrupt file inode 'doc/foo.txt' with an empty file\"\n )\n self.assertRegex(fsck_out, \"Fixed 1 of 1 issues\")\n self.assertEqual(FSCK_RETCODE_ERRORS, returncode)\n\n # There should be no more errors if we run fsck again\n returncode, fsck_out = self.run_fsck()\n self.assertIn(f\"Checking {self.mount}\", fsck_out)\n self.assertIn(\"No issues found\", fsck_out)\n self.assertEqual(FSCK_RETCODE_OK, returncode)\n\n def test_fsck_multiple_mounts(self) -> None:\n mount2 = Path(self.mounts_dir) / \"second_mount\"\n mount3 = Path(self.mounts_dir) / \"third_mount\"\n mount4 = Path(self.mounts_dir) / \"fourth_mount\"\n\n self.eden.clone(self.repo_name, mount2)\n self.eden.clone(self.repo_name, mount3)\n self.eden.clone(self.repo_name, mount4)\n\n # Unmount all but mount3\n self.eden.unmount(Path(self.mount))\n self.eden.unmount(mount2)\n self.eden.unmount(mount4)\n\n # Running fsck should check all but mount3\n returncode, fsck_out = self.run_fsck()\n self.assertIn(f\"Checking {self.mount}\", fsck_out)\n self.assertIn(f\"Checking {mount2}\", fsck_out)\n self.assertIn(f\"Not checking {mount3}\", fsck_out)\n self.assertIn(f\"Checking {mount4}\", fsck_out)\n self.assertEqual(FSCK_RETCODE_SKIPPED, returncode)\n\n # Running fsck with --force should check everything\n returncode, fsck_out = self.run_fsck(\"--force\")\n self.assertIn(f\"Checking {self.mount}\", fsck_out)\n self.assertIn(f\"Checking {mount2}\", fsck_out)\n self.assertIn(f\"Checking {mount3}\", fsck_out)\n self.assertIn(f\"Checking {mount4}\", fsck_out)\n self.assertEqual(FSCK_RETCODE_OK, returncode)\n\n\nclass FsckTestNoEdenfs(unittest.TestCase, TemporaryDirectoryMixin):\n def test_fsck_no_checkouts(self) -> None:\n tmp_dir = self.make_temporary_directory()\n eden = edenclient.EdenFS(tmp_dir)\n cmd_result = eden.run_unchecked(\n \"fsck\",\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n encoding=\"utf-8\",\n errors=\"replace\",\n )\n self.assertIn(\n \"No Eden checkouts are configured. Nothing to check.\", cmd_result.stderr\n )\n self.assertEqual(\"\", cmd_result.stdout)\n self.assertEqual(0, cmd_result.returncode)\n","sub_path":"eden/integration/fsck_test.py","file_name":"fsck_test.py","file_ext":"py","file_size_in_byte":6889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"555510729","text":"#Flask Imports\nfrom flask import Flask, render_template, g, request, url_for, session, redirect, flash\nfrom functools import wraps\nimport sqlite3\n\napp = Flask(__name__)\napp.database = \"data/formData.db\"\n# ideally you should use a random key generator to generate a secret key for security reasons\n# but for this project we won't\n# Session key proctects the session being accessed on the clients side\napp.secret_key = \"testLogin\"\n\n@app.route('/')\ndef index():\n g.db = connect_db()\n cur = g.db.execute('select * from results')\n posts = [dict(position=row[0], names=row[1]) for row in cur.fetchall()]\n g.db.close()\n # When routed here render home page template\n return render_template(\"homePage.html\", posts = posts)\n\n@app.route('/forum')\ndef forum():\n #establish connection to database\n g.db = connect_db()\n #execute query\n cur = g.db.execute('select * from postData')\n #convert into a dictionary so python can understand it\n posts = [dict(name=row[0], message=row[1]) for row in cur.fetchall()]\n g.db.close()\n # When routed here render forum template, pass through variable to the html template\n return render_template(\"forum.html\", posts=posts)\n\n# Login required Decorator\ndef login_required(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n flash('You Need To Login First')\n return redirect(url_for('login'))\n return wrap\n\n\n@app.route('/form', methods = ['GET','POST'])\ndef form():\n if request.method == 'POST':\n name = request.form['nameInput']\n message = request.form['messageInput']\n g.db = connect_db()\n g.db.execute('INSERT INTO postData values(?,?)', (name, message))\n g.db.commit()\n g.db.close()\n #if request is a post redirect to forum\n return redirect(url_for('forum'))\n else:\n #otherwise render form template\n return render_template(\"form.html\")\n\n@app.route('/teamEntry', methods = ['GET','POST'])\n@login_required\ndef teamEntry():\n if request.method == 'POST':\n position = request.form['positionInput']\n # position = position.upper()\n names = request.form['namesInput']\n\n g.db = connect_db()\n g.db.execute('update results set position=?,names=? ', (position, names))\n g.db.commit()\n g.db.close()\n return render_template(\"teamEntry.html\")\n\ndef connect_db():\n return sqlite3.connect(app.database)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'admin' or request.form['password'] != 'admin':\n flash('Invalid Credentials - Please Try Again!')\n else:\n # if the users credentials are correct then the value true is assigned to logged in key\n session['logged_in'] = True\n return redirect(url_for('teamEntry'))\n\n return render_template(\"login.html\", error=error)\n\n@app.route('/logout')\n@login_required\ndef logout():\n #session.pop deletes the key by setting logged_in from true to None\n session.pop('logged_in', None)\n #return to homepage after a logout\n return redirect(url_for('index'))\n\n#Run App\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"591169108","text":"from flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy \n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/user'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nclass User(db.Model):\n __tablename__ = 'user'\n\n UserID = db.Column(db.Integer, primary_key=True)\n UserName = db.Column(db.String(100), nullable=False)\n UserPhone = db.Column(db.Integer, nullable=False)\n Location = db.Column(db.String(100), nullable=False)\n\n def __init__(self, UserID, UserName, UserPhone, Location):\n self.UserID = UserID\n self.UserName = UserName\n self.UserPhone = UserPhone\n self.Location = Location\n\n def json(self):\n return {\n \"UserID\": self.UserID, \"UserName\": self.UserName, \"UserPhone\": self.UserPhone, \"Location\": self.Location\n }\n\nclass Child(db.Model):\n __tablename__ = 'child'\n\n UserID = db.Column(db.Integer, primary_key=True)\n ChildID = db.Column(db.Integer, primary_key=True)\n School = db.Column(db.String(100), nullable=False)\n Level = db.Column(db.String(100), nullable=False)\n Subjects = db.Column(db.String(100), nullable=False)\n\n def __init__(self, UserID, ChildID, School, Level, Subjects):\n self.UserID = UserID\n self.ChildID = ChildID\n self.School = School\n self.Level = Level\n self.Subjects = Subjects\n\n def json(self):\n return {\n \"UserID\": self.UserID, \"ChildID\": self.ChildID, \"School\": self.School, \"Level\": self.Level, \"Subjects\": self.Subjects\n }\n\n\n# GET all Users \n@app.route(\"/user\")\ndef get_all_users():\n userlist = User.query.all()\n if len(userlist):\n return jsonify(\n {\n \"code\": 200,\n \"data\": {\n \"users\": [user.json() for user in userlist]\n }\n }\n )\n return jsonify(\n {\n \"code\": 404,\n \"message\": \"There are no users.\"\n }\n ), 404\n\n# GET User Details By UserID \n@app.route(\"/user/\")\ndef find_by_UserID(UserID):\n userlist = User.query.filter_by(UserID=UserID).first()\n if userlist:\n return jsonify(userlist.json())\n return jsonify({\"message\": \"User is not found.\"}), 404\n\n# add new user using POST \n@app.route(\"/user/\", methods=['POST'])\ndef add_user(UserID):\n if (User.query.filter_by(UserID=UserID).first()):\n return jsonify(\n {\n \"code\": 400,\n \"data\": {\n \"UserID\": UserID\n },\n \"message\": \"User already exists.\"\n }\n ), 400\n \n data = request.get_json()\n user = User(UserID, **data)\n \n try:\n db.session.add(user)\n db.session.commit()\n except:\n return jsonify(\n {\n \"code\": 500,\n \"data\": {\n \"UserID\": UserID\n },\n \"message\": \"An error occurred creating the User.\"\n }\n ), 500\n \n return jsonify(\n {\n \"code\": 201,\n \"data\": user.json()\n }\n ), 201\n\n# Update user details using UserID --> PUT\n@app.route(\"/user/\", methods=['PUT'])\ndef update_user_details(UserID):\n try:\n userlist = User.query.filter_by(UserID=UserID).first()\n if not userlist:\n return jsonify(\n {\n \"code\": 404,\n \"data\": {\n \"UserID\": UserID\n },\n \"message\": \"UserID has not been updated\"\n }\n ), 404\n\n # update status\n data = request.get_json()\n if data['status']:\n userlist.status = data['status']\n db.session.commit()\n return jsonify(\n {\n \"code\": 200,\n \"data\": userlist.json()\n }\n ), 200\n except Exception as e:\n return jsonify(\n {\n \"code\": 500,\n \"data\": {\n \"UserID\": UserID\n },\n \"message\": \"An error occurred while updating the user. \" + str(e)\n }\n ), 500\n\n # PUT is not working will try to fix it up \n\n # def put(self, id):\n # user = [user for user in User if user['UserID'] == UserID]\n\n # if len(user) == 0:\n # abort(404)\n\n # user = user[0]\n\n # # Loop Through all the passed agruments\n # args = self.reqparse.parse_args()\n # for k, v in args.items():\n # # Check if the passed value is not null\n # if v is not None:\n # # if not, set the element in the books dict with the 'k' object to the value provided in the request.\n # user[k] = v\n\n # return{\"user\": marshal(book, bookFields)}\n\n# GET Child details \n@app.route(\"/user/child\")\ndef get_child():\n childlist = Child.query.all()\n if len(childlist):\n return jsonify(\n {\n \"code\": 200,\n \"data\": {\n \"Child\": [child.json() for child in childlist]\n }\n }\n )\n return jsonify(\n {\n \"code\": 404,\n \"message\": \"There are no child.\"\n }\n ), 404\n\n# GET Child Details using ChildID \n@app.route(\"/user//\")\ndef find_by_ChildID(UserID,ChildID):\n childlist = Child.query.filter_by(UserID = UserID, ChildID = ChildID).first()\n if childlist:\n return jsonify(childlist.json())\n return jsonify({\"message\": \"Child is not found.\"}), 404\n\n\nif __name__ ==\"__main__\":\n app.run(port=5000, debug=True)\n\n\n\n\n\n","sub_path":"UserMS/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"306199691","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 19 12:16:46 2018\n\n@author: mariarodriguez\n\"\"\"\n\nimport tolerance_principle\n\n######################################################################################\n\ndef dist_verbs(irr, no_i, no_r, match_i, match_r, match_err, liste, verb_root, child_line):\n \"\"\"\n This fonction checks if a verb is yet to be seen. It stores in a list\n distinct verbs.\n\n Parameters\n -----------\n irr: boolean that state if a verb if irregular or not\n no_i, no_r: counters for irregular and regular verbs\n match_i, match_r: store regex results for regular and irregular verbs\n match_err: store regex results for errors in the corpus\n liste: distinct verbs list, irregular or regular, based on the value of irr.\n If irr=True then liste=list of distincts irregular verbs\n If irr=False then liste=list of distincts regular verbs\n verb_root: dictionnary form of a verb\n child_line: store the child's line\n\n Output\n -----------\n no_i, no_r: counters for irregular and regular verbs\n\n \"\"\"\n if verb_root not in liste:\n if irr:\n no_i += 1\n else:\n no_r += 1\n liste.append(verb_root)\n productive, seuil = tolerance_principle.tolerance(no_i, no_r)\n if match_err:\n print(\"\\n\", child_line, \"\\n\\tNombre réguliers:\", no_r, \"\\n\\tNombre irréguliers:\", no_i, \"\\n\\tSeuil:\", seuil, \"\\n\\tProductivité?\", productive, \"\\n\\tErreur:\", bool(match_err), \"\\n\\tType d'erreur:\", match_err[0][0], \"\\n\\tAnalyse erreur:\", match_err[0][2], \"\\n\\tForme correcte:\", match_err[0][1], \"\\n\")\n else:\n print(\"\\n\", child_line, \"\\n\\tNombre réguliers:\", no_r, \"\\n\\tNombre irréguliers:\", no_i, \"\\n\\tSeuil:\", seuil, \"\\n\\tProductivité?\", productive, \"\\n\\tErreur:\", bool(match_err), \"\\n\") \n else:\n if match_err:\n productive, seuil = tolerance_principle.tolerance(no_i, no_r) \n print(\"\\n\", child_line, \"\\n\\tNombre réguliers:\", no_r, \"\\n\\tNombre irréguliers:\", no_i, \"\\n\\tSeuil:\", seuil, \"\\n\\tProductivité?\", productive, \"\\n\\tErreur:\", bool(match_err), \"\\n\\tType d'erreur:\", match_err[0][0], \"\\n\\tAnalyse erreur:\", match_err[0][2], \"\\n\\tForme correcte:\", match_err[0][1], \"\\n\")\n \n return no_i, no_r","sub_path":"code/distinct_verbs.py","file_name":"distinct_verbs.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"605747430","text":"from esper.prelude import *\nfrom scannerpy.stdlib import pipelines, readers\nfrom query.models import Labeler, Tag\n\nLABELER, _ = Labeler.objects.get_or_create(name='tinyfaces')\nLABELED_TAG, _ = Tag.objects.get_or_create(name='tinyfaces:labeled')\ncwd = os.path.dirname(os.path.abspath(__file__))\nfrom scannerpy.stdlib import pipelines, readers\n\nMETHOD = 'mtcnn'\n\n\ndef face_detect(videos, all_frames, force=False):\n def output_name(video, frames):\n return video.path + '_faces_' + str(hash(tuple(frames)))\n\n def loader():\n log.debug('Depickling')\n all_bboxes = pickle.load(open('/app/bboxes.pkl', 'rb'))\n\n def load_bboxes(tup):\n (video, vid_frames) = tup\n name = output_name(video, vid_frames)\n if name not in all_bboxes: return None\n return [[{\n 'bbox_x1': bbox.x1 / video.width,\n 'bbox_x2': bbox.x2 / video.width,\n 'bbox_y1': bbox.y1 / video.height,\n 'bbox_y2': bbox.y2 / video.height\n } for bbox in frame_bboxes] for _, frame_bboxes in all_bboxes[name]]\n\n return par_for(load_bboxes, zip(videos, all_frames))\n\n return pcache.get('all_bboxes', loader)\n\n existing_frames = Frame.objects.filter(\n video=videos[0], number__in=all_frames[0], tags=LABELED_TAG).count()\n needed_frames = len(all_frames[0])\n if force or existing_frames != needed_frames or True:\n log.debug('Faces not cached, missing {}/{} frames'.format(needed_frames - existing_frames,\n needed_frames))\n\n log.debug('Connecting to scanner database')\n with make_scanner_db(kube=False) as db:\n log.debug('Connected!')\n\n # ingest_if_missing(db, videos)\n\n def remove_already_labeled(video, frames):\n already_labeled = set([\n f['number']\n for f in Frame.objects.filter(video=video, tags=LABELED_TAG).values('number')\n ])\n return sorted(list(set(frames) - already_labeled))\n\n log.debug('Filtering frames')\n filtered_frames = [\n remove_already_labeled(video, vid_frames) if not force else vid_frames\n for video, vid_frames in tqdm(zip(videos, all_frames))\n ]\n\n log.debug('Depickling')\n all_bboxes = pickle.load(open('/app/bboxes.pkl', 'rb'))\n\n log.debug('Only keeping tables already generated')\n videos, filtered_frames = unzip(\n [(video, vid_frames) for video, vid_frames in tqdm(zip(videos, filtered_frames))\n if db.has_table(output_name(video, vid_frames))\n and db.table(output_name(video, vid_frames)).committed()\n and output_name(video, vid_frames) in all_bboxes])\n\n to_compute = [(video, vid_frames) for video, vid_frames in zip(videos, filtered_frames)\n if force or not db.has_table(output_name(video, vid_frames))\n or not db.table(output_name(video, vid_frames)).committed()]\n\n if len(to_compute) > 0:\n if METHOD == 'mtcnn':\n device = DeviceType.CPU\n log.debug('Registering Python op')\n try:\n db.register_op('MTCNN', [('frame', ColumnType.Video)], ['bboxes'])\n db.register_python_kernel(\n 'MTCNN', device, cwd + '/mtcnn_kernel.py', batch=50)\n except ScannerException:\n pass\n\n frame = db.ops.FrameInput()\n frame_strided = frame.sample()\n bboxes = db.ops.MTCNN(frame=frame_strided, device=device)\n output = db.ops.Output(columns=[bboxes])\n\n jobs = [\n Job(\n op_args={\n frame: db.table(video.path).column('frame'),\n frame_strided: db.sampler.gather(vid_frames),\n output: output_name(video, vid_frames)\n }) for video, vid_frames in to_compute\n ]\n\n log.debug('Running face detect on {} jobs'.format(len(jobs)))\n db.run(\n BulkJob(output=output, jobs=jobs),\n force=True,\n io_packet_size=50000,\n work_packet_size=500,\n pipeline_instances_per_node=1)\n log.debug('Done!')\n exit()\n\n elif METHOD == 'tinyfaces':\n pipelines.detect_faces(\n db, [db.table(video.path).column('frame') for video, _ in to_compute],\n [db.sampler.gather(vid_frames) for _, vid_frames in to_compute],\n [output_name(video, vid_frames) for video, vid_frames in to_compute])\n else:\n raise Exception(\"Invalid face detect method {}\".format(METHOD))\n\n log.debug('Saving metadata')\n\n log.debug('Collecting frames')\n all_frames = []\n for (video, video_frames) in tqdm(zip(videos, filtered_frames)):\n # video_faces = list(\n # db.table(output_name(video, video_frames)).load(\n # ['bboxes'], lambda lst, db: readers.bboxes(lst[0], db.protobufs)))\n\n all_frames.append([Frame(video=video, number=n) for n in video_frames])\n\n log.debug('Creating frames')\n Frame.objects.bulk_create(sum(all_frames, []))\n\n log.debug('Collecting people/tags')\n all_people = []\n all_tags = []\n for (video, video_frames, frames) in tqdm(zip(videos, filtered_frames, all_frames)):\n video_faces = all_bboxes[output_name(video, video_frames)]\n people = []\n tags = []\n for (_, frame_faces), frame in zip(video_faces, frames):\n tags.append(\n Frame.tags.through(tvnews_frame_id=frame.pk, tvnews_tag_id=LABELED_TAG.pk))\n for bbox in frame_faces:\n people.append(Person(frame=frame))\n all_people.append(people)\n all_tags.append(tags)\n\n log.debug('Creating people/tags')\n Frame.tags.through.objects.bulk_create(sum(all_tags, []))\n Person.objects.bulk_create(sum(all_people, []))\n\n log.debug('Collecting faces')\n all_faces = []\n for (video, video_frames, people) in tqdm(zip(videos, filtered_frames, all_people)):\n p_idx = 0\n for (_, frame_faces) in video_faces:\n for bbox in frame_faces:\n all_faces.append(\n Face(\n person=people[p_idx],\n bbox_x1=bbox.x1 / video.width,\n bbox_x2=bbox.x2 / video.width,\n bbox_y1=bbox.y1 / video.height,\n bbox_y2=bbox.y2 / video.height,\n bbox_score=bbox.score,\n labeler=LABELER))\n p_idx += 1\n\n log.debug('Creating faces')\n Face.objects.bulk_create(all_faces)\n\n log.debug('Done!')\n exit()\n\n return [\n group_by_frame(\n list(\n Face.objects.filter(\n person__frame__video=video,\n person__frame__number__in=vid_frames,\n labeler=LABELER).select_related('person', 'person__frame')),\n lambda f: f.person.frame.number,\n lambda f: f.id,\n include_frame=False) for video, vid_frames in zip(videos, all_frames)\n ]\n","sub_path":"app/esper/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":8058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"134652004","text":"\"\"\"\nAST renderers for inspecting the markdown parsing result.\n\"\"\"\nfrom __future__ import unicode_literals\nimport json\nfrom .renderer import Renderer\nfrom ._compat import string_types\nfrom .helpers import camel_to_snake_case\n\n\nclass ASTRenderer(Renderer):\n \"\"\"Render as AST structure.\n\n Example::\n\n >>> print(markdown('# heading', ASTRenderer))\n {'footnotes': [],\n 'link_ref_defs': {},\n 'children': [{'level': 1, 'children': ['heading'], 'element': 'heading'}],\n 'element': 'document'}\n \"\"\"\n\n def render_children(self, element):\n if isinstance(element, list):\n return [self.render_children(e) for e in element]\n if isinstance(element, string_types):\n return element\n rv = {k: v for k, v in element.__dict__.items() if not k.startswith(\"_\")}\n if \"children\" in rv:\n rv[\"children\"] = self.render(rv[\"children\"])\n rv[\"element\"] = camel_to_snake_case(element.__class__.__name__)\n return rv\n\n\nclass XMLRenderer(Renderer):\n \"\"\"Render as XML format AST.\n\n It will render the parsed result and XML string and you can print it or\n write it to a file.\n\n Example::\n\n >>> print(markdown('# heading', XMLRenderer))\n \n \n \n \n heading\n \n \n \"\"\"\n\n def __enter__(self):\n self.indent = 0\n return super(XMLRenderer, self).__enter__()\n\n def __exit__(self, *args):\n self.indent = 0\n return super(XMLRenderer, self).__exit__(*args)\n\n def render_children(self, element):\n lines = []\n if element is self.root_node:\n lines.append(\" \" * self.indent + '')\n lines.append(\n \" \" * self.indent + ''\n )\n attrs = {\n k: v\n for k, v in element.__dict__.items()\n if not k.startswith(\"_\") and k != \"children\"\n }\n attr_str = \"\".join(' {}=\"{}\"'.format(k, v) for k, v in attrs.items())\n element_name = camel_to_snake_case(element.__class__.__name__)\n lines.append(\" \" * self.indent + \"<{}{}>\".format(element_name, attr_str))\n if getattr(element, \"children\", None):\n self.indent += 2\n if isinstance(element.children, string_types):\n lines.append(\" \" * self.indent + json.dumps(element.children)[1:-1])\n else:\n lines.extend(self.render(child) for child in element.children)\n self.indent -= 2\n lines.append(\" \" * self.indent + \"\".format(element_name))\n else:\n lines[-1] = lines[-1][:-1] + \" />\"\n return \"\\n\".join(lines)\n","sub_path":"marko/ast_renderer.py","file_name":"ast_renderer.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"123635818","text":"# Создайте игру, в которой компьютер загадывает один из трех цветов светофора, а игрок должен его угадать.\n# Ермашов А.В., 26.05.2016\nimport random\ncvet = random.randint(1,3)\nif cvet == 1: cvet=\"Красный\"\nelif cvet ==2: cvet=\"Желтый\"\nelif cvet ==3: cvet=\"Зеленый\"\nprint(\"Угадайте цвет светофора: \")\notvet = input(\"\\nВведите цвет: \")\nwhile(otvet != cvet):\n print(\"\\nНеправильно. Попробуй еще раз\")\n otvet = input(\"\\nВведите цвет: \")\n \nprint(\"Правильно! Это\", cvet,\"цвет!\")\ninput(\"Нажмите ENTER для продолжения\")\n","sub_path":"INBa/2015/Ermashov_A_V/task_6_5.py","file_name":"task_6_5.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"381700253","text":"# Actividad 2 - Juego Vibora.\n# Autores: Leonardo Delgado Rios-A00827915, Saul Jimenez Torres-A01283849.\n# Aplicacion que desarrolla el minijuego de la vibora \n# Fecha de ultima modificacion: 10/28/2020.\n# Se importan las librerias que se utilizaran para el correcto desarrollo de\n# la aplicación.\nfrom turtle import *\nfrom random import randrange\nfrom freegames import square, vector\n\nfood = vector(0, 0)\nsnake = [vector(10, 0)]\naim = vector(0, -10)\n\n# Funcion color, devuelve un color al azar de los establecidos\ndef color():\n colors = ['green', 'blue', 'pink', 'yellow', 'gray']\n return colors[randrange(0,len(colors))]\n\n# Funcion change, cambia las coordenadas de la serpiente, es decir, es el que\n# dira en que direccion se movera la snake dependiendo de la instruccion dada.\ndef change(x, y):\n \"Change snake direction.\"\n aim.x = x\n aim.y = y\n\n# Funcion inside, verifica a traves de un valor booleano si la cabeza de la\n# snake se encuentra dentro de los limites establecidos para su ejecucion.\ndef inside(head):\n \"Return True if head inside boundaries.\"\n return -200 < head.x < 190 and -200 < head.y < 190\n\n# Funcion control, verifica la posibilidad de movimiento de la comida dentro de\n# la ventana, debido a la precondicion dada, se analizan 8 posibles movimientos\n# que podria tener (derecha, izquierda, arriba, abajo, derecha-arriba,\n# derecha-abajo, izquierda-arriba e izquierda-abajo). Anexa las combinaciones a\n# una lista donde se utilizara dentro de los mov posibles un valor random para\n# seleccionar el movimiento a realizar de la comida.\ndef control(food):\n #Establecer el valor de las variables a utilizar\n l1 = []\n ax = food.x\n ay = food.y\n b = -200\n f = 190\n for i in range(0,8):\n #Evalua si puede moverse a la derecha\n if((ax+10) in range(b,f) and ay in range(b,f) and len(l1)==0):\n l1.append([food.x+10,food.y])\n #Evalua si puede moverse a la izquierda\n elif((ax-10) in range(b,f) and ay in range(b,f) and len(l1)<=1):\n l1.append([food.x-10,food.y])\n #Evalua si puede moverse arriba\n elif(ax in range(b,f) and (ay+10) in range(b,f) and len(l1)<=2):\n l1.append([food.x,food.y+10])\n #Evalua si puede moverse abajo\n elif(ax in range(b,f) and (ay-10) in range(b,f) and len(l1)<=3):\n l1.append([food.x,food.y-10])\n #Evalua si puede moverse a la derecha y arriba\n elif((ax+10) in range(b,f) and (ay+10) in range(b,f) and len(l1)<=4):\n l1.append([food.x+10,food.y+10])\n #Evalua si puede moverse a la derecha y abajo\n elif((ax+10) in range(b,f) and (ay-10) in range(b,f) and len(l1)<=5):\n l1.append([food.x+10,food.y-10])\n #Evalua si puede moverse a la izquierda y arriba\n elif((ax-10) in range(b,f) and (ay+10) in range(b,f) and len(l1)<=6):\n l1.append([food.x-10,food.y+10])\n #Evalua si puede moverse a la izquierda y abajo\n elif((ax-10) in range(b,f) and (ay-10) in range(b,f) and len(l1)<=7):\n l1.append([food.x-10,food.y-10])\n return l1\n\n# Funcion move, menciona los posibles escenarios de la snake, en caso de que\n# no haya comido/haya comido/se haya comido a si misma, respectivamente cambia\n# su direccion, aumenta su tamaño o termina el programa.\ndef move():\n \"Move snake forward one segment.\"\n head = snake[-1].copy()\n head.move(aim)\n\n if not inside(head) or head in snake:\n square(head.x, head.y, 9, 'red')\n update()\n return\n\n snake.append(head)\n ltmp = control(food)\n aux = ltmp[randrange(0,len(ltmp))]\n food.x = aux[0]\n food.y = aux[1]\n \n if head == food:\n print('Snake:', len(snake))\n print(food)\n else:\n snake.pop(0)\n\n clear()\n \n for body in snake:\n square(body.x, body.y, 9, randsnake)\n\n square(food.x, food.y, 9, randfood)\n update()\n ontimer(move, 100)\n\n# Se definen los valores default, como el color de la snake y de la comida que\n# se utilizara por cada ejecucion del programa, ademas del tamaño de la ventana\n# y las instrucciones para cambiar la direccion de la snake.\nrandfood = color()\nrandsnake = color()\nwhile randfood == randsnake:\n randfood = color()\n randsnake = color()\nsetup(420, 420, 370, 0)\nhideturtle()\ntracer(False)\nlisten()\nonkey(lambda: change(10, 0), 'Right')\nonkey(lambda: change(-10, 0), 'Left')\nonkey(lambda: change(0, 10), 'Up')\nonkey(lambda: change(0, -10), 'Down')\nmove()\ndone()","sub_path":"Actividad 2 Juego Vibora Mov Continuo.py","file_name":"Actividad 2 Juego Vibora Mov Continuo.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"121491068","text":"import os\nimport glob\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\nseed_arr = []\n\n# parse xml information \n\nfor xml_file in glob.glob('./annotations/*.xml'):\n root = ET.parse(xml_file).getroot()\n filename = root.find('filename').text\n\n #for type_tag in root.findall('size'):\n #file_name = type_tag.find('filename').text\n #width = type_tag.find('width').text\n #height = type_tag.find('height').text\n\n for type_tag in root.findall('object'):\n class_name = type_tag.find('name').text\n #xmin = type_tag.find('bndbox/xmin').text\n #ymin = type_tag.find('bndbox/ymin').text\n #xmax = type_tag.find('bndbox/xmax').text\n #ymax = type_tag.find('bndbox/ymax').text\n #all_list = [filename, width,height,class_name,xmin, ymin, xmax,ymax]\n all_list = [class_name]\n seed_arr.append(all_list)\n \nseed_arr.sort()\n# convert sublist to tuple\n\nmy_list = set(map(tuple,seed_arr))\n\n# generate csv win information my_list(my_list= classes)\ncolumn_name = ['classes']\nxml_df = pd.DataFrame(my_list, columns=column_name)\nxml_df.to_csv(('class.csv'), index=None)\nprint('Successfully generated csv file.')\n \n\n\n\n\n\n","sub_path":"Python-Projects/codes/classes_generator.py","file_name":"classes_generator.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"223387247","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/11/1 14:39\n# @Author : sch\n# @File : test8.py\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.style.use('ggplot')\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\nplt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n\n# plt.plot(np.arange(10))\nfig = plt.figure()\nax1 = fig.add_subplot(2, 2, 1)\nax2 = fig.add_subplot(2, 2, 2)\nax3 = fig.add_subplot(2, 2, 3)\n\nfrom numpy.random import randn\nplt.plot(randn(50).cumsum(), 'k--')\nax2.scatter(np.arange(30), np.arange(30) + 3 * randn(30))\n_ = ax1.hist(randn(100), bins=20, color='k', alpha=0.3)\nfig, axes = plt.subplots(2, 3)\naxes\n\n# 调整subplot周围的间距\n# subplots_adjust(left=None, bottom=None, right=None, top=None,\n# wspace=None, haspac=None)\n# wspace和hspace用于控制宽度和高度的百分比,可以用作subplot之间的间距\nfig, axes = plt.subplots(2, 2, sharex=True, sharey=True)\nfor i in range(2):\n for j in range(2):\n axes[i, j].hist(randn(500), bins=50, color='k', alpha=0.5)\nplt.subplots_adjust(wspace=0, hspace=0)\n\n# 颜色、标记和线型\nplt.plot(randn(30).cumsum(), 'ko--')\nplt.plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o')\ndata = randn(30).cumsum()\nplt.plot(data, 'k--', linestyle='dashed', marker='o')\nplt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')\nplt.legend(loc='best')\n\n# 刻度、标签和图例\n# 设置标题、轴标签、刻度以及刻度标签\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot(randn(1000).cumsum())\nticks = ax.set_xticks([0, 250, 500, 750, 1000])\nlabels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],\n rotation=30, fontsize='small')\nax.set_title('My first matplotlib plot')\nax.set_xlabel('Stages')\n\n# 添加图例\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot(randn(1000).cumsum(), 'k', label='one')\nax.plot(randn(1000).cumsum(), 'k--', label='two')\nax.plot(randn(1000).cumsum(), 'k.', label='three')\nax.legend(loc='best')\n\n# 注解以及在subplot上绘图\n# 注解可以通过text、arrow和annotate等函数进行添加,text可以将文本\n# 绘制在图表的指定坐标(x, y),还可以加上一些自定义格式\n# ax.text(x, y, 'Hello world!',\n# famliy='monospace', fontsize=10)\n\n# from datetime import datetime\n# fig = plt.figure()\n# ax = fig.add_subplot(1, 1, 1)\n# data = pd.read_csv('test/test8/spx.csv')\n# spx = data['SPX']\n# spx.plot(ax=ax, style='k-')\n# crisis_data = [\n# (datetime(2007, 10, 11), 'Peak of bull market'),\n# (datetime(2008, 3, 12), 'Bear Stearns Fails'),\n# (datetime(2008, 9, 15), 'Lehman Bankruptcy')\n# ]\n# for date, label in crisis_data:\n# ax.annotate(label, xy=(date, spx.asof(date) + 50),\n# xytext=(date, spx.asof(date) + 200),\n# arrowprops=dict(facecolor='black'),\n# horizontalalignment='left', verticalalignment='top')\n# # 放大到2007-2010\n# ax.set_xlim(['1/1/2007', '1/1/2011'])\n# ax.set_ylim([600, 1800])\n# ax.set_title('Import dates in 2008-2009 financial crisis')\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nrect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)\ncirc = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)\npgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],\n color='g', alpha=0.5)\nax.add_patch(rect)\nax.add_patch(circ)\nax.add_patch(pgon)\n\n# 将图表保存到文件\n# plt.savefig将当前图表保存到文件\n# plt.savefig('figpath.png', dpi=400, bbox_inches='tight')\n\n# matplotlib配置\n# plt.rc('figure', figsize=(10, 10))\n'''\nfont_options = {'famliy': 'monospace',\n 'weight': 'bold',\n 'size': 'small'}\nplt.rc('font', **font_options)\n'''\n\n# pandas中的绘图函数\n# 线型图\ns = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))\ns.plot()\ndf = pd.DataFrame(np.random.randn(10, 4).cumsum(0),\n columns=['A', 'B', 'C', 'D'],\n index=np.arange(0, 100, 10))\ndf.plot()\n'''\nSeries.plot方法的参数\nlabel 图例的标签\nax 要在其上进行绘制的matplotlib.subplot图像\nstyle 将要传给matplotlib的风格字符串(如'ko--')\nalpha 图表的填充不透明度\nkind 可以是line,bar,barh,kde\nlogy 在Y轴上使用对数标尺\nuse_index 将对象的索引用作刻度标签\nrot 旋转刻度标签\nxticks X轴刻度的值\nyticks Y轴刻度的值\nxlim X轴界限\nylim Y轴界限\ngrid 显示轴网格线\n'''\n'''\nDataFrame的plot参数\nsubplots 将各个DataFrame列绘制到单独的subplot中\nsharex 如果subplot=True,则共用一个X轴\nsharey 如果subplot=True,则共用一个Y轴\nfigsize 绘图大小\ntitle 绘图标题\nlegend 添加一个subplot图例\nsort_columns 以字母表绘制各列\n'''\n\n# 柱状图\nfig, axes = plt.subplots(2, 1)\ndata = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))\ndata.plot(kind='bar', ax=axes[0], color='k', alpha=0.7)\ndata.plot(kind='bar', ax=axes[1], color='k', alpha=0.7)\n\ndf = pd.DataFrame(np.random.rand(6, 4),\n index=['one', 'two', 'three', 'four', 'five', 'six'],\n columns=pd.Index(['A', 'B', 'C', 'D']))\ndf\ndf.plot(kind='bar')\ndf.plot(kind='barh', stacked=True, alpha=0.5)\n\n# tips = pd.read_csv('test/test8/tips.csv')\n# party_counts = pd.crosstab(tips.day, tips.size)\n# party_counts = party_counts.iloc[:, 2: 5]\n# party_pcts = party_counts.div(party_counts.sum(1).astype(float), axis=0)\n# party_pcts\n# party_pcts.plot(kind='bar', stacked=True)\n\n# 直方图和密度图\n# 直方图:hist(bins=50)\n# 密度图:plot(kind='kde')\ncomp1 = np.random.normal(0, 1, size=200)\ncomp2 = np.random.normal(10, 2, size=200)\nvalues = pd.Series(np.concatenate([comp1, comp2]))\nvalues.hist(bins=100, alpha=0.3, color='k', normed=True)\nvalues.plot(kind='kde', style='k')\n# concatenate函数\n\n# 散布图\nmacro = pd.read_csv('test/test8/macrodata.csv')\ndata = macro[['cpi', 'm1', 'tbilrate', 'unemp']]\ntrans_data = np.log(data).diff().dropna()\ntrans_data[-5:]\nplt.scatter(trans_data['m1'], trans_data['unemp'])\nplt.title('Changes in log %s vs. log %s' % ('m1', 'unemp'))\npd.scatter_matrix(trans_data, diagonal='kde', color='k', alpha=0.3)\n\n# 绘制地图:图形化显示海地地震危机数据\ndata = pd.read_csv('test/test8/Haiti.csv')\ndata\ndata[['INCIDENT DATE', 'LATITUDE', 'LONGITUDE']][:10]\ndata['CATEGORY'][:6]\ndata.describe()\ndata = data[(data['LATITUDE'] > 18) & (data['LATITUDE'] < 20) &\n (data['LONGITUDE'] > -75) & (data['LONGITUDE'] < -70) &\n data['CATEGORY'].notnull()]\ndef to_cat_list(catstr):\n stripped = (x.strip() for x in catstr.split(','))\n return [x for x in stripped if x]\ndef get_all_categories(cat_series):\n cat_sets = (set(to_cat_list(x)) for x in cat_series)\n return sorted(set.union(*cat_sets))\ndef get_english(cat):\n code, names = cat.split('.')\n if '|' in names:\n names = names.split('|')[1]\n return code, names.strip()\nget_english('2. Urgences logistiques | Vital Lines')\n\nall_cats = get_all_categories(data.CATEGORY)\nenglish_mapping = dict(get_english(x) for x in all_cats)\nenglish_mapping['2a']\nenglish_mapping['6c']\n\ndef get_code(seq):\n return [x.split('.')[0] for x in seq if x]\nall_codes = get_code(all_cats)\ncode_index = pd.Index(np.unique(all_codes))\ndummy_frame = pd.DataFrame(np.zeros((len(data),len(code_index))),\n index=data.index, columns=code_index)\ndummy_frame.iloc[:, :6]\nfor row, cat in zip(data.index, data.CATEGORY):\n codes = get_code(to_cat_list(cat))\n dummy_frame.loc[row, codes] = 1\ndata = data.join(dummy_frame.add_prefix('category_'))\n","sub_path":"test8/test8.py","file_name":"test8.py","file_ext":"py","file_size_in_byte":7784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"425296739","text":"import pickle\nimport random\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n# STEP 1: DATA MUNGING\nimport glob\nallfiles = glob.glob(\"example_LAMOST/Data_All/*fits\")\nallfiles = np.char.lstrip(allfiles, 'example_LAMOST/Data_All/')\ntr_ID = np.loadtxt(\"tr_files.txt\", dtype=str)\ntest_ID = np.setdiff1d(allfiles, tr_ID)\nfrom lamost import load_spectra, load_labels\ndir_dat = \"example_LAMOST/Data_All\"\ntr_IDs, wl, tr_flux, tr_ivar = load_spectra(dir_dat, tr_ID)\nlabel_file = \"reference_labels.csv\"\ntr_label = load_labels(label_file, tr_ID)\ntest_IDs, wl, test_flux, test_ivar = load_spectra(dir_dat, test_ID)\ngood = np.logical_and(tr_label[:,0] > 0, tr_label[:,2]>-5)\ntr_IDs = tr_IDs[good]\ntr_flux = tr_flux[good]\ntr_ivar = tr_ivar[good]\ntr_label = tr_label[good]\nfrom TheCannon import dataset\ndataset = dataset.Dataset(\n wl, tr_IDs, tr_flux, tr_ivar, tr_label, test_IDs, test_flux, test_ivar)\ndataset.set_label_names(['T_{eff}', '\\log g', '[M/H]', '[\\\\alpha/Fe]'])\ncont = pickle.load(open(\"cont.p\", \"r\"))\nnorm_tr_flux, norm_tr_ivar, norm_test_flux, norm_test_ivar = \\\n dataset.continuum_normalize(cont)\ntr_cont, test_cont = cont\ntr_cont[tr_cont==0] = dataset.tr_flux[tr_cont==0]\ntest_cont[test_cont==0] = dataset.test_flux[test_cont==0]\ncont = tr_cont, test_cont\nnorm_tr_flux, norm_tr_ivar, norm_test_flux, norm_test_ivar = \\\n dataset.continuum_normalize(cont)\ndataset.tr_flux = norm_tr_flux\ndataset.tr_ivar = norm_tr_ivar\ndataset.test_flux = norm_test_flux\ndataset.test_ivar = norm_test_ivar\nlabel_file = 'reference_labels.csv'\n# for each test ID, find its index in label_file IDs\nids = np.loadtxt(label_file, usecols=(0,), dtype=str, delimiter=',')\ninds = [np.where(ids==test_ID_val) for test_ID_val in test_ID]\nnames = ['T_{eff}', '\\log g', '[Fe/H]', '[\\\\alpha/Fe]']\nlims = [[3900,6000], [0,5], [-2, 1], [-0.1,0.4]]\n#id,teff,logg,feh,alpha,snr\nteff = np.loadtxt(label_file, usecols=(1,), dtype=float, delimiter=',')\nlogg = np.loadtxt(label_file, usecols=(2,), dtype=float, delimiter=',')\nfeh = np.loadtxt(label_file, usecols=(3,), dtype=float, delimiter=',')\nalpha = np.loadtxt(label_file, usecols=(4,), dtype=float, delimiter=',')\napogee_label_vals = np.vstack(\n (teff[inds].flatten(), logg[inds].flatten(), feh[inds].flatten(), alpha[inds].flatten())).T\nchoose = np.logical_and(orig<0.15, cannon>0.18)\nc=np.zeros(len(choose))\nc[choose] = 'r'\nc=np.zeros(len(choose), dtype='str')\nc[choose] = 'r'\nc[~choose] = 'k'\nscatter(orig, cannon, c=c)\n\n","sub_path":"examples/bad_stars.py","file_name":"bad_stars.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"423776846","text":"import math\r\nimport csv\r\n\r\nwith open(\"data_3_stnd.csv\", newline='') as f:\r\n file_object = csv.reader(f)\r\n data_list = list(file_object)\r\n\r\ndata = data_list[0]\r\n\r\ndef mean(data):\r\n n = len(data)\r\n sum = 0\r\n for a in data:\r\n sum+=int(a)\r\n\r\n mean = sum/n\r\n return(mean)\r\n\r\nsqrd_list = []\r\n\r\nfor x in data:\r\n dif = int(x) - mean(data)\r\n dif = dif**2\r\n sqrd_list.append(dif)\r\n print(dif)\r\n\r\ntot = 0\r\n\r\nfor a in sqrd_list:\r\n tot+=int(a)\r\n\r\nresult = tot/(len(data)-1)\r\n\r\nstnd_dev = math.sqrt(result)\r\nprint(str(stnd_dev) + \" is the standard deviation.\")","sub_path":"stnd_deviation.py","file_name":"stnd_deviation.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"98559917","text":"import tensorflow as tf\nimport cv2\nimport time\nimport os\nimport sys\nfrom picamera import PiCamera\nimport argparse\nimport math\nfrom posenet import *\nfrom picamera.array import PiRGBArray\nfrom posenet.utils import _process_input\nfrom easydict import EasyDict\nfrom liftoneleg import *\nfrom metric import test_per_frame\n# from playsound import playsound\n# from posenet.utils import read_cap\nfrom openvino.inference_engine import IENetwork, IECore\n\n#def parse_args():\n# parser = argparse.ArgumentParser()\n# parser.add_argument('--model', type=str, default='./posenet_input_337_449/model-mobilenet_v1_101.xml')\n# parser.add_argument('--cam_id', type=int, default=0)\n# parser.add_argument('--cam_width', type=int, default= 640)\n# parser.add_argument('--cam_height', type=int, default=480)\n# parser.add_argument('--scale_factor', type=float, default=0.7125)\n# parser.add_argument('--file', type=str, default=None, help=\"Optionally use a video file instead of a live camera\")\n# parser.add_argument(\"-l\", \"--cpu_extension\",\n# help=\"Optional. Required for CPU custom layers. Absolute path to a shared library with \"\n# \"the kernels implementations.\", type=str, default=None)\n# parser.add_argument(\"-d\", \"--device\",\n# help=\"Optional. Specify the target device to infer on; CPU, GPU, FPGA, HDDL or MYRIAD is\"\n# \" acceptable. The sample will look for a suitable plugin for device specified. \"\n# \"Default value is CPU\", default=\"MYRIAD\", type=str)\n# args = parser.parse_args()\n# return args\n\nargs = EasyDict()\nargs.model = './posenet_input_337_449/model-mobilenet_v1_101.xml'\nargs.device = 'MYRIAD'\nargs.scale_factor = 0.7125\nargs.cpu_extension = None\nprint(args)\n \ncamera = PiCamera()\ncamera.resolution = (640,480)\n#camera.framerate =32\n\n\ndef counting_rightarm(keypoint_coords, old_raiseup):\n Count = False\n raiseup = old_raiseup\n if keypoint_coords[0, :, :][10][0] < keypoint_coords[0, :, :][12][0] + 20:\n ready = \"ing\"\n shoulder_min = keypoint_coords[0, :, :][6][0] - 15\n shoulder_max = keypoint_coords[0, :, :][6][0] + 15\n\n if shoulder_min < keypoint_coords[0, :, :][10][0] < shoulder_max:\n raiseup = True\n hip_min = keypoint_coords[0, :, :][12][0] - 15\n hip_max = keypoint_coords[0, :, :][12][0] + 15\n if old_raiseup == True and hip_min < keypoint_coords[0, :, :][10][0] < hip_max:\n Count = True\n raiseup = False\n return Count, raiseup\n\n\ndef checking_rightarm(keypoint_coords, old_raiseup, old_rightarm):\n Check = False\n raiseup = old_raiseup\n max_rightarm = min(old_rightarm, keypoint_coords[0, :, :][10][0])\n hip = keypoint_coords[0, :, :][12][0]\n shoulder_min = keypoint_coords[0, :, :][6][0] + 30\n shoulder_max = keypoint_coords[0, :, :][6][0] + 15\n if keypoint_coords[0, :, :][10][0] < hip + 20:\n if shoulder_max < max_rightarm < shoulder_min:\n raiseup = True\n hip_min = hip - 15\n hip_max = hip + 15\n if raiseup == True and hip_min < keypoint_coords[0, :, :][10][0] < hip_max:\n if shoulder_max< max_rightarm < shoulder_min:\n Check = True\n raiseup = False\n max_rightarm = 1000\n return Check, raiseup, max_rightarm\n \ndef posenet2openpose(keypoints):\n \n keypoints = keypoints[0] # max score keypoint\n keypoints = np.flip(keypoints, 1) #(y,x) -> (x,y)\n # print(\"========after flip========\")\n # print(keypoints)\n \n # get keypoint for neck\n right_shoulder = keypoints[6]\n left_shoulder = keypoints[5]\n neck_x = right_shoulder[0] + (left_shoulder[0] - right_shoulder[0]) / 2\n neck_y = min(left_shoulder[1], right_shoulder[1])\n neck_top = np.array([0, 0])\n neck_bottom = np.array([neck_x, neck_y])\n keypoints = np.insert(keypoints, 0, neck_top, axis=0)\n keypoints = np.insert(keypoints, 1, neck_bottom, axis=0)\n #print(\"========after insert neck========\")\n #print(keypoints)\n \n # consist keypoints in openpose order\n openpose_order = [0,1,6,8,10,5,7,9,12,14,16,11,13,15]\n res_keypoints = [keypoints[i] for i in openpose_order]\n res_keypoints = np.array(res_keypoints)\n #print(\"========after reorder========\")\n #print(res_keypoints)\n return res_keypoints\n \n\ndef main(thres):\n \n #ankle_height = 0\n #counting = 0\n #old_raiseup = False\n #okay = False\n #raiseup = False\n #old_minwrist = 720\n \n #Global varaible\n LEG_LABEL = np.load('./groundtruth.npy')\n threshold = thres\n print(threshold)\n \n #Initialize analzing parameter\n previous_pose_kpts = []\n result = [-1, -1, -1, -1, -1]\n count = 0\n start_frame, end_frame = 1000000, -1\n max_angle = 0\n min_angle = 90\n completed_half = False\n total_len_frame = 0\n \n model_xml = args.model\n model_bin = os.path.splitext(model_xml)[0] + '.bin'\n \n \n with tf.Session() as sess:\n #model_cfg, model_outputs = posenet.load_model(101, sess)\n #output_stride = model_cfg['output_stride']\n output_stride = 16\n checkraiseup, rightarm = 0, 720 \n rawCapture = PiRGBArray(camera, size = (640,480))\n \n start = time.time()\n frame_count = 0\n framenum =0\n score_list = []\n ie = IECore()\n if args.cpu_extension and 'CPU' in args.device:\n ie.add_extension(args.cpu_extension, \"CPU\")\n # Read IR\n ie.set_config({'VPU_HW_STAGES_OPTIMIZATION':'NO'}, \"MYRIAD\")\n net = IENetwork(model=model_xml, weights=model_bin)\n \n n, c, w, h = net.inputs['image'].shape\n #print(\"width, height: \", w, h) #337, 513\n net.batch_size = n\n exec_net = ie.load_network(network=net, device_name=args.device,num_requests=2)\n del net\n #cap = cv2.VideoCapture(r\"./ligt_oneleg_correct.mp4\")\n \n #while True:\n for frame in camera.capture_continuous(rawCapture, format = \"bgr\", use_video_port = True, splitter_port=1):\n frame_start = time.time()\n pos_temp_data = []\n framenum +=1\n input_image = frame.array\n input_image, display_img, output_scale = _process_input(\n input_image,scale_factor=args.scale_factor, output_stride=output_stride)\n print(\"display: \", display_img.shape)\n print(\"preprocess : \", input_image.shape)\n input_image = np.expand_dims(input_image, 0)\n input_image = np.transpose(input_image, (0, 3, 1, 2))\n #print(input_image.shape)\n \n #file_path = (\"test%02d.png\" %framenum)\n #cv2.imwrite(file_path,display_img)\n res = exec_net.infer({'image': input_image})\n heatmaps_result = res['heatmap']\n offsets_result = res['offset_2/Add']\n displacement_fwd_result = res[\"displacement_fwd_2/Add\"]\n displacement_bwd_result = res[\"displacement_bwd_2/Add\"]\n #print(\"Heatmap: \", heatmaps_result.shape)\n \n heatmaps_result = np.transpose(heatmaps_result, (0, 2, 3, 1))\n offsets_result = np.transpose(offsets_result, (0, 2, 3, 1))\n displacement_fwd_result = np.transpose(displacement_fwd_result, (0, 2, 3, 1))\n displacement_bwd_result = np.transpose(displacement_bwd_result, (0, 2, 3, 1))\n\n pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses(\n heatmaps_result.squeeze(axis=0),\n offsets_result.squeeze(axis=0),\n displacement_fwd_result.squeeze(axis=0),\n displacement_bwd_result.squeeze(axis=0),\n output_stride=output_stride,\n max_pose_detections=10,\n min_pose_score=0.1)\n \n keypoint_coords *= output_scale \n \n # convert posenet keypoints 2 openpose format\n openpose_keypoints = posenet2openpose(keypoint_coords)\n \n #Select joints\n select_keypoints = np.concatenate((openpose_keypoints[2],openpose_keypoints[5],openpose_keypoints[8],\n openpose_keypoints[10],openpose_keypoints[11],openpose_keypoints[13])).reshape(-1, 2)\n \n #Analyze posture\n previous_pose_kpts.append(select_keypoints)\n liftoneleg = LiftOneLeg(previous_pose_kpts)\n angle, leg_status = liftoneleg.check_leg_up_down()\n \n if angle > max_angle:\n max_angle = angle\n max_frame = cv2.imwrite(\"./blog/static/img/best.png\", display_img)\n \n #Update status and count\n leg_status, completed_half, count_update, start_frame_update, end_frame_update= \\\n liftoneleg.count_repetition(angle, leg_status, completed_half, count, framenum, start_frame, end_frame)\n if (count_update == count +1):\n print(\"count : %d\" %count_update)\n score = test_per_frame(previous_pose_kpts[start_frame-total_len_frame:end_frame-total_len_frame], LEG_LABEL)\n print(\"**************************\")\n print(\"score : %d\" %score)\n score_list.append(score)\n f= open('score.txt', 'w')\n f.write(str(int(score)))\n f.close()\n total_len_frame += len(previous_pose_kpts)\n previous_pose_kpts = []\n \n count, start_frame, end_frame = count_update, start_frame_update, end_frame_update \n \n f = open('demofile.txt', 'w')\n f.write(str(count))\n f.close()\n \n # write for feedback!!\n if count == 5:\n exercise_time = time.time() - start\n # write max angle\n f = open('max_angle.txt', 'w')\n f.write(str(int(max_angle)))\n f.close() \n # write exercise time\n f= open('time.txt', 'w')\n f.write(str(int(exercise_time)))\n f.close()\n # write score \n f= open('final_score.txt', 'w')\n f.write(str(int(sum(score_list)/count)))\n f.close()\n sys.exit(0)\n #return 0\n\n overlay_image = posenet.draw_skel_and_kp(\n display_img, pose_scores, keypoint_scores, keypoint_coords,\n min_pose_score=0.1, min_part_score=0.1)\n \n #cv2.putText(overlay_image, str(counting), (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 1)\n cv2.imshow('posenet', overlay_image)\n rawCapture.truncate(0)\n frame_count += 1\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n print('Average FPS: ', (time.time() - frame_start))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"openvino_demo_224.py","file_name":"openvino_demo_224.py","file_ext":"py","file_size_in_byte":11061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"84963284","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 19 10:38:46 2021\n\n@author: mattwear\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n### Data Cleaning Functions\n\n# Getting rid of unecesarry columns\n\ndef remove_columns(df):\n \n \"\"\"Removes columns we agreed were useless\"\"\"\n columns = [\"Unnamed: 0\", \"id\", \"image_url\", \"VIN\", \"region_url\", \"id\", \"model\", \"size\",\"url\"]\n df.drop(columns, axis=1, inplace=True)\n return(df)\n\n\ndef price_range(df, lower = 0, higher = 60_000, sampling = False):\n \"\"\"\n Set the lower and upper limits of the price, if sampling true it chooses 40,000 samples at random\n \"\"\"\n if sampling == True:\n df = df.sample(n = 40_000)\n \n df = df.dropna(subset = [\"price\"])\n \n df = df.loc[df[\"price\"] < higher]\n df = df.loc[df[\"price\"] >= lower]\n \n return(df)\n\ndef dateToDatetime(df):\n df['posting_date'] = df['posting_date'].str[:10].astype('datetime64[ns]')\n return df\n\ndef basicImpute(df):\n #Here, impute missing values with a common number/value\n \n ###Description: Impute missing values as empty string\n ###posting_date: Not many so impute with mean posting date\n mean_posting_date = np.mean(df.posting_date)\n\n #Fill NA\n df.fillna(value={'description': '', 'posting_date':mean_posting_date}, inplace=True)\n \n return df\n\n\ndef imputeMissingByManufacturer(df, col):\n ###Impute missing values by taking the most common occurence of the items manufacturer\n #Use this for fuel and transmission. The remaining missing values have NaN manufacturer\n \n cars = df.copy()\n cars_unique = np.unique(cars.manufacturer.astype(str))\n man_dict = {}\n\n for car in cars_unique:\n if car != 'nan':\n max_occur = cars[cars.manufacturer==car][col].value_counts().index[0]\n man_dict[car] = max_occur\n\n cars.loc[cars[col].isnull(),col] = cars['manufacturer'].map(man_dict)\n return cars\n\n\ndef TF_IDF(df, number = 100):\n \n \"\"\"This function adds the TF-IDF values of the most important words to the dataframe,\n the number can be chosen above\"\"\"\n \n \"\"\"TF - term frequency \"\"\"\n \n \"\"\"Inverse Document Frequency (IDF)\n IDF is a measure of how important a term is\"\"\"\n \n vectorizer = TfidfVectorizer(stop_words='english',max_features = number)\n sentences = df[\"description\"].values\n vectorizer.fit(sentences)\n vector_spaces = vectorizer.transform(sentences)\n tfidf = vector_spaces.toarray()\n df.reset_index(drop=True, inplace=True)\n df = pd.concat([df, pd.DataFrame(tfidf)], axis = 1)\n return(df)\n\n\ndef color_clean(df, color_list=['white','black','silver']):\n\n #groups all the colors that are not in the list as \"other\"\n #one hot encoding of paint_color column\n \n df[\"paint_color\"]=df[\"paint_color\"].apply(lambda x: x if x in color_list else \"other\")\n df=pd.get_dummies(df, prefix=\"color\",columns=['paint_color'])\n \n return df\n\n\n\ndef drive_clean(df):\n \n #Assigns 4wd to all SUVs, pickups and offroads with nan drive type \n df.loc[(((df[\"type\"]==\"SUV\") | \n (df[\"type\"]==\"pickup\") | \n (df[\"type\"]==\"offroad\")) & (df['drive'].isnull()==True)),\"drive\"] = \"4wd\"\n \n #assign \"other\" to all nan values\n df.loc[(df['drive'].isnull()==True),\"drive\"]=\"other\"\n\n #one hot encoding 4wd, rwd, fwd, other\n df = pd.get_dummies(df,prefix=\"drive\",columns=['drive'])\n \n return df \n\n\ndef transmission_clean(df):\n \n #Groups nan values with \"other\" type of transmission\n df.loc[(df['transmission'].isnull()==True),\"transmission\"]=\"other\"\n \n #one hot encoding manual, automatic and other\n df = pd.get_dummies(df,prefix=\"transmission\",columns=['transmission'])\n \n return df\n\n\ndef titlestatus_clean(df):\n df = pd.get_dummies(df,prefix=\"status\",columns=['title_status'])\n return df\n\n\ndef fillLatLongNA(df):\n #Fills all missing lat, long values with the median of their respective region\n region_coords_ave_lat = df[['region','lat']].groupby(['region'])['lat'].median().to_dict()\n region_coords_ave_long = df[['region','long']].groupby(['region'])['long'].median().to_dict()\n df.loc[df['lat'].isnull(),'lat'] = df['region'].map(region_coords_ave_lat)\n df.loc[df['long'].isnull(),'long'] = df['region'].map(region_coords_ave_long)\n return df\n\ndef fillLatLongOutliers(df):\n latlong_outliers = (df.lat<20) | (df.lat>70) | (df.long < -160) | (df.long > -60)\n region_coords_ave_lat = df[['region','lat']].groupby(['region'])['lat'].median().to_dict()\n region_coords_ave_long = df[['region','long']].groupby(['region'])['long'].median().to_dict()\n df.loc[latlong_outliers,'lat'] = df['region'].map(region_coords_ave_lat)\n df.loc[latlong_outliers,'long'] = df['region'].map(region_coords_ave_long)\n return df\n\ndef cleanLatLong(df):\n df = fillLatLongNA(df)\n df = fillLatLongOutliers(df)\n return df\n\ndef cleanLocationFeatures(df):\n df = cleanLatLong(df)\n #one hot encoding state\n df = pd.get_dummies(df,prefix=\"state\",columns=['state'])\n #drop region\n df.drop(['region'], axis=1, inplace=True)\n \n return df \n\ndef groupStateByPrice(df, lower=10000, higher=15000):\n ### Adds binary feature indicating if car was sold in cheap, medium or expensive state\n \n cars = df.copy()\n #Find median price by state\n bar = cars[['price','state']].groupby(['state'])['price'].median()\n bar.sort_values(ascending=False, inplace=True)\n \n #Find expensive, mid price and cheap states according to thresholds\n expensive_states = np.array(bar[bar >higher].index)\n mediumprice_state = np.array(bar[(bar > lower) & (bar <= higher)].index)\n cheap_state = np.array(bar[bar <= lower].index)\n \n #Add on hot encoded features to dataset\n cars['state_expensive'] = cars.state.isin(expensive_states).astype(int)\n cars['state_medium'] = cars.state.isin(mediumprice_state).astype(int)\n cars['state_cheap'] = cars.state.isin(cheap_state).astype(int)\n \n return cars\n\ndef ultimateClean(df):\n #remove useless values\n df = remove_columns(df)\n df = price_range(df, lower = 50, higher = 60_000, sampling = False)\n print(\"Cleaned !\")\n \n #one hot encodings\n df = color_clean(df, color_list=['white','black','silver'])\n df = drive_clean(df)\n df = transmission_clean(df)\n df = titlestatus_clean(df)\n df = cleanLocationFeatures(df)\n print(\"One hot encodings done!\")\n \n #impute some missing values\n \n \n #remove remaining missing values\n df = df.dropna()\n print(\"Dropped NANs!\")\n\n \n return(df)\n\n\ndef normalise(df):\n cols_to_norm = [\"year\", \"odometer\", \"lat\", \"long\"]\n df[cols_to_norm] = MinMaxScaler().fit_transform(df[cols_to_norm])\n #FOR TRAIN TEST SPLIT USE SKLEARN train_test_split\n return(df)","sub_path":"DataMining/CleaningCars.py","file_name":"CleaningCars.py","file_ext":"py","file_size_in_byte":6862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"110179664","text":"\n# coding: utf-8\n\n# In[3]:\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n# In[1]:\n\n#plot the original plot\ndef plot_image(data,stuck,slices,features,alphapara,cmap):\n target_data=data[stuck][0][0][0][0][:,:,slices,features]\n target_image=target_data.reshape(target_data.shape[0],target_data.shape[1])\n plt.imshow(target_image,cmap,alpha=alphapara)\n plt.axis(\"off\")\n\n\n\n# In[2]:\n\n# plot the 5 features of one slice of the data\ndef plot_set_images(data,stuck,slices):\n alphapara = 1;\n cmap = matplotlib.cm.binary\n features = 0\n plt.subplot(151)\n plt.title(\"T2 weighted\")\n plot_image(data,stuck,slices,features,alphapara,cmap)\n\n plt.subplot(152)\n plt.title(\"ADC\")\n plot_image(data,stuck,slices,features+1,alphapara,cmap)\n\n plt.subplot(153)\n plt.title(\"Ktrans\")\n plot_image(data,stuck,slices,features+2,alphapara,cmap)\n \n plt.subplot(154)\n plt.title(\"Kep\")\n plot_image(data,stuck,slices,features+3,alphapara,cmap)\n\n plt.subplot(155)\n plt.title(\"PET\")\n plot_image(data,stuck,slices,features+4,alphapara,cmap)\n plt.show()\n\n#Based on the last plot. plot the prediction of the expert also. \ndef plot_orinale_image_with_prediction(data,stuck,index,slices,features):\n cmap1 = matplotlib.colors.LinearSegmentedColormap.from_list('my_cmap',['black','green','blue'],256)\n target_data=data[stuck][0][0][0][0][:,:,slices,features]\n target_image1=target_data.reshape(target_data.shape[0],target_data.shape[1])\n target_label=data[stuck][0][0][0][index][:,:,slices]\n target_image2=target_label.reshape(target_label.shape[0],target_label.shape[1])\n plt.imshow(target_image1,cmap = matplotlib.cm.binary,alpha=0.8)\n plt.imshow(target_image2,cmap = cmap1,interpolation=\"bilinear\",alpha=0.2)\n plt.axis(\"off\") #close the axis number\n plt.show()","sub_path":"task_1_version_3/plot_image.py","file_name":"plot_image.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"441757728","text":"'''\nOf all guards, which guard is most frequently asleep on the same minute?\n\nWhat is the ID of the guard you chose multiplied by the minute you chose?\n'''\n\nfrom collections import defaultdict\nfrom part_1 import guard_parser, time_parser\n\n\ndef shift_parser(input_list):\n '''\n Returns a dictionary where keys are guards and values are a list of\n tuples of sleep and awake minutes, given a sorted list of timestamps.\n\n Element 0 and Element 1 of the list are placeholders for minute guard slept\n most and frequency of minute slept\n '''\n record_dict = defaultdict(lambda: [0, 0]) # [0, 0] are placeholders\n for line in input_list:\n if line.endswith('shift'):\n guard_id = guard_parser(line)\n elif line.endswith('asleep'):\n sleep_time = time_parser(line)\n elif line.endswith('up'):\n wake_time = time_parser(line)\n\n record_dict[guard_id].append(\n (sleep_time[4], wake_time[4])\n )\n else:\n pass\n return record_dict\n\n\ndef max_minute_and_freq(input_list):\n '''\n Returns the minute slept most by a guard and the frequency,\n given a list where each tuple has the sleep minute followed by\n the awake minute\n '''\n minute_dict = {}\n for sleep, wake in input_list:\n for i in range(sleep, wake):\n minute_dict[i] = minute_dict.get(i, 0) + 1\n return max(minute_dict, key=minute_dict.get), max(minute_dict.values())\n\n\ndef update_dict(input_dict):\n '''\n Returns an updated dictionary -->\n\n Given a dictionary in the format:\n {guard_id}: [placeholder, placeholder, (sleep, wake), (sleep,wake) ... ]\n returns a dictionary in the format:\n {guard_id}: [\n minute_slept_most, total_times_slept_that_minute, (sleep, wake), ...\n ]\n '''\n for guard, values in input_dict.items():\n minute_slept_most, minute_slept_most_freq = max_minute_and_freq(\n values[2:]\n )\n input_dict[guard][0] = minute_slept_most\n input_dict[guard][1] = minute_slept_most_freq\n return input_dict\n\n\ndef guard_slept_most_freq(input_dict):\n '''\n Returns the guard that slept and minute more than any other guard,\n that minute and how many times the guard slept on that minute\n '''\n best_guard = max(input_dict, key=lambda i: input_dict[i][1])\n return best_guard, input_dict[best_guard][0], input_dict[best_guard][1]\n\n\ndef main():\n with open('input.txt') as input_file:\n input_list = input_file.read().split('\\n')\n sorted_list = sorted(input_list)\n\n guard_dictionary = update_dict(shift_parser(sorted_list))\n\n best_guard, minute_slept, minute_freq = guard_slept_most_freq(\n guard_dictionary\n )\n\n print(\n f'''The guard most frequently asleep on the same minute is Guard {\n best_guard\n }. He is most asleep on minute {\n minute_slept\n } and slept {minute_freq} times'''\n )\n print(\n f'''The ID of Guard {best_guard} multiplied by the minute is {\n int(best_guard) * minute_slept\n }'''\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Day 4/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"161159322","text":"import os\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\nimport tensors_saver\n\ntensors_saver.set_out_path(sys.argv[1])\n\nx = np.array([\n [1., 2.],\n [3., 4.],\n [5., 6.]\n])\n\nx_node = tf.Variable(x, dtype=tf.float32)\ny_node = tf.reduce_sum(x_node, axis=0)\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\ntf_y = sess.run(y_node)\ntensors_saver.add(tf_y)\n","sub_path":"tests/ref_mat_sum0.py","file_name":"ref_mat_sum0.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"347318698","text":"import json\nimport csv\nimport re\n\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom .models import Student\nfrom django.core.mail import send_mail\nfrom django.utils.encoding import smart_str\n\ndef try_rest_framework(request, id):\n if request.method == 'GET':\n return get(request, id)\n elif request.method == 'POST':\n return post(request)\n elif request.method == 'PUT':\n return put(request, id)\n elif request.method == 'DELETE':\n return delete(request, id)\n\ndef get(request, id=None):\n if id:\n try:\n data = serializers.serialize(\"json\", Student.objects.filter(id=id))\n return HttpResponse(data)\n except:\n return HttpResponse('No record found')\n data = serializers.serialize(\"json\", Student.objects.all())\n return HttpResponse(data)\n\ndef post(request):\n data = json.loads(request.body.decode('utf-8'))\n obj = Student()\n obj.name = data['name']\n obj.age = data['age']\n obj.email = data['email']\n obj.save()\n return HttpResponse('Student saved successfully')\n\ndef put(request, id=None):\n data = json.loads(request.body.decode('utf-8'))\n try:\n obj = Student.objects.get(id=id)\n obj.update(name=data['name'])\n return HttpResponse('Student updated successfully')\n except:\n return HttpResponse('No record found')\n\ndef delete(request, id=None):\n try:\n obj = Student.objects.get(id=id)\n obj.delete()\n return HttpResponse('Student deleted successfully')\n except:\n return HttpResponse('No record found')\n\ndef send_email(request):\n try:\n send_mail('Simple Mail',\n 'This is a sample SMTP message',\n 'pranesh24599@gmail.com',\n ['viperpranesh007@gmail.com'],\n )\n return HttpResponse(\"Email send successfully\")\n except:\n return HttpResponse(\"Unable to send mail\")\n\ndef database_to_csv(request):\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=mymodel.csv'\n writer = csv.writer(response, csv.excel)\n response.write(u'\\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)\n writer.writerow([\n smart_str(u\"ID\"),\n smart_str(u\"Name\"),\n smart_str(u\"Age\"),\n smart_str(u\"EmailID\"),\n ])\n queryset = Student.objects.all()\n for obj in queryset:\n writer.writerow([\n smart_str(obj.pk),\n smart_str(obj.name),\n smart_str(obj.age),\n smart_str(obj.email),\n ])\n return response\n\ndef csv_to_database(request):\n with open('sample_data.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n obj = Student(name=row['name'], age=row['age'], email=row['email'])\n obj.save()\n return HttpResponse('Saved to database successfully!')\n\ndef csv_to_database_with_validation(request):\n li = []\n count = 0\n regex = re.compile('[a-zA-Z0-9!@#$%^&*_]+')\n with open('sample_data.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n count += 1\n if regex.search(row['name']) and regex.search(row['age']) and regex.search(row['email']):\n obj = Student(name=row['name'], age=row['age'], email=row['email'])\n obj.save()\n else:\n li.append(count)\n print(li)\n return HttpResponse('Saved to database successfully!')","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"382864267","text":"# stdlib\nimport json\nimport os\nimport sys\nfrom typing import Any\nfrom typing import Generator\nfrom typing import Optional\n\n# third party\nimport requests\n\n# syft relative\nfrom ...core.common.environment import is_jupyter\nfrom ...core.node.common.client import Client\nfrom ...core.node.domain.domain import Domain\nfrom ...logger import error\nfrom ...logger import info\nfrom ...logger import traceback_and_raise\nfrom .bcolors import bcolors\nfrom .exchange_ids import DuetCredentialExchanger\nfrom .exchange_ids import OpenGridTokenFileExchanger\nfrom .exchange_ids import OpenGridTokenManualInputExchanger\nfrom .om_signaling_client import register\nfrom .ui import LOGO_URL\nfrom .webrtc_duet import Duet as WebRTCDuet # noqa: F811\n\nif is_jupyter:\n # third party\n from IPython.core.display import Image\n from IPython.core.display import display\n\n\nADDR_REPOSITORY = (\n \"https://raw.githubusercontent.com/OpenMined/OpenGridNodes/master/network_address\"\n)\n\n\ndef generate_donation_msg(name: str) -> str:\n donate_url = \"https://github.com/sponsors/OpenMined\"\n donate_msg = (\n f\"\\n > ❤️ {bcolors.FAIL}Love{bcolors.ENDC} {bcolors.OKGREEN}{name}{bcolors.ENDC}? \"\n + f\"{bcolors.WARNING}Please{bcolors.ENDC} {bcolors.OKBLUE}consider{bcolors.ENDC} \"\n + f\"{bcolors.HEADER}supporting{bcolors.ENDC} {bcolors.FAIL}our{bcolors.ENDC} \"\n + f\"{bcolors.WARNING}community!{bcolors.ENDC}\"\n + f\"\\n > {donate_url}\"\n )\n return donate_msg\n\n\nDUET_DONATE_MSG = generate_donation_msg(name=\"Duet\")\n\n\ndef get_available_network() -> str:\n network_addr = json.loads(requests.get(ADDR_REPOSITORY).content)\n for addr in network_addr:\n try:\n requests.get(addr + \"/metadata\")\n return addr\n except Exception as e:\n error(f\"Failed request addr: {e}\")\n continue\n traceback_and_raise(Exception(\"Couldn't find any available network.\"))\n\n\ndef begin_duet_logger(my_domain: Domain) -> None:\n # stdlib\n from contextlib import contextmanager\n import threading\n import time\n\n # we need a lock, so that other threads don't snatch control\n # while we have set a temporary parent\n stdout_lock = threading.Lock()\n\n @contextmanager\n def set_stdout_parent(parent: Any) -> Generator:\n \"\"\"a context manager for setting a particular parent for sys.stdout\n the parent determines the destination cell of output\n \"\"\"\n save_parent = sys.stdout.parent_header # type: ignore\n with stdout_lock:\n sys.stdout.parent_header = parent # type: ignore\n try:\n yield\n finally:\n # the flush is important, because that's when the parent_header actually has its effect\n sys.stdout.flush()\n sys.stdout.parent_header = save_parent # type: ignore\n\n class counterThread(threading.Thread):\n def run(self) -> None:\n # record the parent when the thread starts\n thread_parent = sys.stdout.parent_header # type: ignore\n iterator = 0\n while True:\n time.sleep(0.1)\n # then ensure that the parent is the same as when the thread started\n # every time we print\n with set_stdout_parent(thread_parent):\n\n n_objects = len(my_domain.store)\n n_requests = len(my_domain.requests)\n n_messages = my_domain.message_counter\n n_request_handlers = len(my_domain.request_handlers)\n\n blink_on = (int(iterator / 5) % 2) == 0\n\n if blink_on and n_requests > 0:\n left_blink = bcolors.BOLD + \">\" + bcolors.ENDC\n right_blink = bcolors.BOLD + \"<\" + bcolors.ENDC\n left_color = bcolors.FAIL\n right_color = bcolors.ENDC\n else:\n left_blink = \" \"\n right_blink = \" \"\n left_color = \"\"\n right_color = \"\"\n\n if blink_on:\n star = \"*\"\n else:\n star = \"-\"\n\n out = (\n \"♫♫♫ > DUET LIVE STATUS \"\n + star\n + \" Objects: \"\n + str(n_objects)\n + \" \"\n + left_color\n + \"Requests:\"\n + right_color\n + left_blink\n + str(n_requests)\n + right_blink\n + \" Messages: \"\n + str(n_messages)\n + \" Request Handlers: \"\n + str(n_request_handlers)\n )\n out += \" \"\n # STOP changing this to logging, this happens every fraction of a\n # second to update the jupyter display, logging this creates\n # unnecessary noise, in addition the end= parameter broke logging\n print(\"\\r\" + out, end=\"\\r\") # DO NOT change to log\n iterator += 1\n\n if hasattr(sys.stdout, \"parent_header\"):\n counterThread().start()\n\n\ndef duet(\n target_id: Optional[str] = None,\n logging: bool = True,\n network_url: str = \"\",\n loopback: bool = False,\n db_path: Optional[str] = None,\n) -> Client:\n if target_id is not None:\n return join_duet(\n target_id=target_id, loopback=loopback, network_url=network_url\n )\n else:\n return launch_duet(\n logging=logging, network_url=network_url, loopback=loopback, db_path=db_path\n )\n\n\ndef launch_duet(\n logging: bool = True,\n network_url: str = \"\",\n loopback: bool = False,\n credential_exchanger: DuetCredentialExchanger = OpenGridTokenManualInputExchanger(),\n db_path: Optional[str] = None,\n) -> Client:\n if os.path.isfile(LOGO_URL) and is_jupyter:\n display(\n Image(\n LOGO_URL,\n width=400,\n unconfined=True,\n )\n )\n info(\"🎤 🎸 ♪♪♪ Starting Duet ♫♫♫ 🎻 🎹\\n\", print=True)\n info(\n \"♫♫♫ >\\033[93m\"\n + \" DISCLAIMER\"\n + \"\\033[0m\"\n + \": \"\n + \"\\033[1m\"\n + \"Duet is an experimental feature currently in beta.\\n\"\n + \"♫♫♫ > Use at your own risk.\\n\"\n + \"\\033[0m\",\n print=True,\n )\n\n info(bcolors.BOLD + DUET_DONATE_MSG + bcolors.BOLD + \"\\n\", print=True)\n\n if not network_url:\n network_url = get_available_network()\n info(\"♫♫♫ > Punching through firewall to OpenGrid Network Node at:\", print=True)\n info(\"♫♫♫ > \" + str(network_url), print=True)\n info(\"♫♫♫ >\", print=True)\n info(\"♫♫♫ > ...waiting for response from OpenGrid Network... \", print=True)\n\n signaling_client = register(url=network_url)\n\n info(\"♫♫♫ > \" + bcolors.OKGREEN + \"DONE!\" + bcolors.ENDC, print=True)\n\n my_domain = Domain(name=\"Launcher\", db_path=db_path)\n\n if loopback:\n credential_exchanger = OpenGridTokenFileExchanger()\n target_id = credential_exchanger.run(credential=signaling_client.duet_id)\n\n info(\"♫♫♫ > Connecting...\", print=True)\n\n _ = WebRTCDuet(\n node=my_domain,\n target_id=target_id,\n signaling_client=signaling_client,\n offer=True,\n )\n info(print=True)\n info(\"♫♫♫ > \" + bcolors.OKGREEN + \"CONNECTED!\" + bcolors.ENDC, print=True)\n # return duet, my_domain.get_root_client()\n out_duet: Client = my_domain.get_root_client()\n\n if logging:\n begin_duet_logger(my_domain=my_domain)\n info(print=True)\n\n return out_duet\n\n\ndef join_duet(\n target_id: str = \"\",\n network_url: str = \"\",\n loopback: bool = False,\n credential_exchanger: DuetCredentialExchanger = OpenGridTokenManualInputExchanger(),\n) -> WebRTCDuet:\n if os.path.isfile(LOGO_URL) and is_jupyter:\n display(\n Image(\n LOGO_URL,\n width=400,\n unconfined=True,\n )\n )\n info(\"🎤 🎸 ♪♪♪ Joining Duet ♫♫♫ 🎻 🎹\\n\", print=True)\n info(\n \"♫♫♫ >\\033[93m\"\n + \" DISCLAIMER\"\n + \"\\033[0m\"\n + \": \"\n + \"\\033[1m\"\n + \"Duet is an experimental feature currently in beta.\\n\"\n + \"♫♫♫ > Use at your own risk.\\n\"\n + \"\\033[0m\",\n print=True,\n )\n\n info(bcolors.BOLD + DUET_DONATE_MSG + bcolors.BOLD + \"\\n\", print=True)\n\n if not network_url:\n network_url = get_available_network()\n info(\"♫♫♫ > Punching through firewall to OpenGrid Network Node at:\", print=True)\n info(\"♫♫♫ > \" + str(network_url), print=True)\n info(\"♫♫♫ >\", print=True)\n info(\"♫♫♫ > ...waiting for response from OpenGrid Network... \", print=True)\n\n signaling_client = register(url=network_url)\n\n info(\"♫♫♫ > \" + bcolors.OKGREEN + \"DONE!\" + bcolors.ENDC, print=True)\n\n my_domain = Domain(name=\"Joiner\")\n\n if loopback:\n credential_exchanger = OpenGridTokenFileExchanger()\n else:\n # we have target_id so we set it using set_responder_id\n credential_exchanger.set_responder_id(target_id)\n\n target_id = credential_exchanger.set_role(join=True).run(\n credential=signaling_client.duet_id\n )\n\n duet = WebRTCDuet(\n node=my_domain,\n target_id=target_id,\n signaling_client=signaling_client,\n offer=False,\n )\n info(print=True)\n info(\"♫♫♫ > \" + bcolors.OKGREEN + \"CONNECTED!\" + bcolors.ENDC, print=True)\n # begin_duet_client_logger(duet.node)\n\n return duet\n","sub_path":"packages/syft/src/syft/grid/duet/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"264257174","text":"import tkinter as tk\nimport sqlite3\nimport argparse\n\nCHECKBUTTON_ON_VALUE = 1\nCHECKBUTTON_OFF_VALUE = 0\nKEY_RIGHT_CODE = 39\nKEY_LEFT_CODE = 37\n\n\nclass PublicationsSorter:\n def __init__(self, db_path, sql_select=\"SELECT Title, Abstract FROM Publications\"):\n self.categories = {}\n self.curr_title = None\n self.curr_abstract = None\n\n self.root = tk.Tk() # create window\n self.root.bind('', self.key_pressed)\n self.root.geometry(\"900x700\")\n self.root.resizable(0, 0)\n self.connection = sqlite3.connect(db_path)\n cursor = self.connection.cursor()\n cursor.execute(sql_select)\n self.list_publications = cursor.fetchall()\n self.curr_idx = 0\n self.init_interface()\n self.load_publication(self.curr_idx)\n self.root.mainloop()\n\n def init_interface(self):\n frame_text = tk.Frame(self.root).pack(side=tk.LEFT)\n self.curr_title = tk.Label(frame_text, text=\"title\")\n self.curr_title.pack()\n self.curr_abstract = tk.Label(frame_text, wraplength=50, text=\"Annotation\")\n self.curr_abstract.pack()\n\n frame_categories = tk.Frame(self.root).pack(side=tk.TOP)\n cursor = self.connection.cursor()\n cursor.execute(\"SELECT * FROM Categories\")\n db_categories = cursor.fetchall()\n for category, description in db_categories:\n var = tk.IntVar()\n self.categories[category] = tk.Checkbutton(frame_categories, text=category, variable=var,\n onvalue=CHECKBUTTON_ON_VALUE, offvalue=CHECKBUTTON_OFF_VALUE)\n self.categories[category].var = var\n self.categories[category].pack(side=tk.TOP, anchor=\"w\")\n\n frame_buttons = tk.Frame(self.root).pack(side=tk.BOTTOM, expand=1)\n tk.Button(frame_buttons, text=\"Previous\", command=self.prev_pb).pack(side=tk.LEFT, anchor=\"w\")\n tk.Button(frame_buttons, text=\"Next\", command=self.next_pb).pack(side=tk.LEFT, anchor=\"w\")\n tk.Button(frame_buttons, text=\"Reset\", command=self.load_categories_from_db).pack(side=tk.LEFT, anchor=\"w\")\n\n def save_curr_publication(self):\n curr_categories = self.get_categories(self.list_publications[self.curr_idx][0])\n cursor = self.connection.cursor()\n for category, butt in self.categories.items():\n if butt.var.get() == CHECKBUTTON_ON_VALUE:\n if category not in curr_categories:\n cursor.execute(\"INSERT INTO PublicationsByCategories(Publication, Category) VALUES(?, ?)\",\n (self.list_publications[self.curr_idx][0], category))\n elif category in curr_categories:\n cursor.execute(\"DELETE FROM PublicationsByCategories WHERE Publication=? AND Category=?\",\n (self.list_publications[self.curr_idx][0], category))\n self.connection.commit()\n return\n\n def load_publication(self, idx):\n print(\"Load publication #\", idx)\n len_publications = len(self.list_publications)\n if idx not in range(0, len_publications):\n print(\"Cannot load publication! Index out of range: %s (min = 0, num publications = %s)\"\n % (idx, len_publications))\n return\n self.curr_idx = idx\n self.root.title('Publication %s/%s' % (idx+1, len(self.list_publications)))\n self.curr_title.config(text=self.list_publications[idx][0], wraplength=800)\n self.curr_abstract.config(text=self.list_publications[idx][1], wraplength=900)\n self.load_categories_from_db()\n return\n\n def next_pb(self):\n self.save_curr_publication()\n self.load_publication(self.curr_idx+1)\n return\n\n def prev_pb(self):\n self.save_curr_publication()\n self.load_publication(self.curr_idx - 1)\n return\n\n def load_categories_from_db(self):\n curr_categories = self.get_categories(self.list_publications[self.curr_idx][0])\n for category, butt in self.categories.items():\n if category in curr_categories:\n butt.select()\n else:\n butt.deselect()\n return\n\n def get_categories(self, publication):\n cursor = self.connection.cursor()\n cursor.execute(\"SELECT Category FROM PublicationsByCategories WHERE Publication=?\",\n (publication,))\n curr_categories = [db_line[0] for db_line in cursor.fetchall()]\n return curr_categories\n\n def key_pressed(self, event):\n if event.keycode == KEY_RIGHT_CODE:\n self.next_pb()\n elif event.keycode == KEY_LEFT_CODE:\n self.prev_pb()\n\n def __delete__(self, instance):\n self.save_curr_publication()\n self.connection.close()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Sort publications by categories')\n parser.add_argument('db', help='Path to database file')\n args = parser.parse_args()\n sql_select = \"SELECT Publications.Title, Publications.Abstract FROM Publications INNER JOIN PublicationsByCategories \" \\\n \"ON Publications.Title = PublicationsByCategories.Publication WHERE PublicationsByCategories.Category = 'Other'\"\n pb = PublicationsSorter(args.db, sql_select)\n\n\n","sub_path":"sort_by_categories.py","file_name":"sort_by_categories.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"24486799","text":"def maj(chaine):\r\n res=''\r\n for c in chaine:\r\n if ord(c)>=ord('a') and ord(c)<=ord('z'):\r\n res=res+chr(ord(c)+ord('A')-ord('a'))\r\n else: res=res+c\r\n return res\r\n \r\ndef pgcd(a,b):\r\n while b!= 0:\r\n a,b=b,a%b\r\n return a\r\n\r\ndef binaire(a):\r\n r=\"\"\r\n while a!=0:\r\n r=str(a%2)+r\r\n a=a//2\r\n return r\r\n \r\ndef arithmetico_geom(a,q,r,N):\r\n u=a\r\n for i in range(N):\r\n u=q*u+r\r\n return u\r\n \r\ndef plus_petit_entier_naturel():\r\n s=0\r\n k=0\r\n while s<6:\r\n k+= 1\r\n s=s+1/k\r\n return k\r\n\r\ndef fibonacci(n):\r\n L = [0,1]\r\n for i in range(2,n+1):\r\n L.append(L[i-1]+L[i-2])\r\n return L\r\n\r\ndef fibonacci1(n):\r\n L = [0]*(n+1)\r\n L[0]=0\r\n L[1]=1\r\n for i in range(2,n+1):\r\n L[i]=L[i-1]+L[i-2]\r\n return L\r\n \r\ndef syracuse(a,n):\r\n L = [a]\r\n for i in range(n):\r\n u = L[-1]\r\n if u%2 == 0:\r\n L.append(u//2)\r\n else:\r\n L.append(3*u+1)\r\n return L\r\n \r\ndef syracuse1(a,n):\r\n L = [0]*(n+1)\r\n L[0]=a\r\n for i in range(1,n+1):\r\n u = L[i-1]\r\n if u%2 == 0:\r\n L[i]=u//2\r\n else:\r\n L[i]=3*u+1\r\n return L\r\n\r\n\r\ndef compression(chaine):\r\n i=0\r\n res=''\r\n while i 1E10] = 1;\n #error[error < 1E-10] = 1;\n \n sinocompy = fillStirSpace(sinocomp, error)\n sinogram.set_segment(sinocompy)\n\n #backproject error\n backprojector.back_project(imspaceError, sinogram)\n image = stirextra.to_numpy(reconspace)\n error = stirextra.to_numpy(imspaceError)\n \n error = error/npNormMap\n #error[error > 1E10] = 0\n error[np.isinf(error)] = 0\n error[np.isnan(error)] = 1\n #pylab.imshow(error[0,:,:]), pylab.show()\n\n #update image\n image = image * error\n reconspace = fillStirSpace(reconspace, image)\n return reconspace\n\ndef forwardProjectionShiftError(yShift, forwardProjector, shiftingSino, referenceSino, image, shiftImage, iter, iFrame):\n \n npimage = stirextra.to_numpy(image)\n\n npshiftim = np.zeros(np.shape(npimage))\n ndimage.shift(npimage, [0, yShift, 0], output = npshiftim)\n shiftImage = fillStirSpace(shiftImage, npshiftim)\n \n #Forward project\n forwardProjector.forward_project(shiftingSino, shiftImage)\n\n #Calculate error measure\n shiftingSinoExtr = stirextra.to_numpy(shiftingSino.get_segment_by_sinogram(0))\n shiftingSinoExtr /= np.sum(shiftingSinoExtr)\n\n referenceSinoExtr = stirextra.to_numpy(referenceSino.get_segment_by_sinogram(0))\n referenceSinoExtr /= np.sum(referenceSinoExtr)\n\n npShiftingSino =shiftingSinoExtr - referenceSinoExtr\n\n npShiftingSino[np.isnan(npShiftingSino)] = 0\n npShiftingSino[np.isinf(npShiftingSino)] = 0\n\n return np.sum(npShiftingSino**2)\n\ndef OptimizeSinogramError(vShift, forwardProjector, sinogramList, measurementList, image, shiftImage, SurrogateSignal):\n iDim1 = 0\n localShift = vShift\n def calcError():\n error = 0\n modLocalShift = localShift[0] * SurrogateSignal + localShift[1]\n #print(modLocalShift)\n for iFrame in range(nFrames):\n error += forwardProjectionShiftError(modLocalShift[iFrame], forwardProjector, sinogramList[iFrame], measurementList[iFrame], image, shiftImage, iDim1, iFrame)\n return error\n\n nFrames = len(SurrogateSignal)\n #shift image\n yShift = vShift[0] * SurrogateSignal + vShift[1]\n \n #get start error\n startError = calcError()\n currentError = startError\n errorLog = [] \n\n tries = 0\n refDims = np.zeros(2)\n # while tries < 10:\n # tries += 1\n iDim2 = 0\n for iDim1 in range(16):\n localShift = np.array([ vShift[0] + iDim1, vShift[1] + iDim2])\n currentError = calcError()\n errorLog.append(currentError)\n if currentError < startError:\n startError = currentError\n \n refDims = [iDim1, iDim2]\n \n return [refDims[0], refDims[1]], errorLog\n\n \n","sub_path":"STIRTest/StirSupport.py","file_name":"StirSupport.py","file_ext":"py","file_size_in_byte":4726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"565068479","text":"from django.shortcuts import render\nfrom factura.models import Producto\n\n\n# Create your views here.\n\ndef lista(request):\n allProductos = Producto.objects.all()\n context = {\n \"productos\": allProductos,\n }\n return render(request, \"productos/lista.html\", context)","sub_path":"Semana14Hackaton/dgarcia/famapp/lista/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"390160224","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'training'\n\nurlpatterns = [\n url(r'trainingappt/$',views.TrainingAppt.as_view(),name='trainappt'),\n url(r'^update/(?P[0-9]+)/$', views.UpdateTraining.as_view(),name='update-training'),\n url(r'^delete/(?P[0-9]+)/$', views.DeleteTraining.as_view(),name='delete-training'),\n]\n","sub_path":"dogs_site/training/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"304371356","text":"import json\nimport urllib.request\nfrom utlis import singleton\nfrom log_utils import logger\n\n@singleton\nclass RequestManager:\n def __init__(self):\n self.host = 'localhost'\n self.port = None\n self.base_url = None\n\n def get_base_url(self):\n return self.base_url\n\n def on_port_ready(self, port: int):\n self.port = port\n self.base_url = f'http://{self.host}:{self.port}'\n\n def is_server_ready(self):\n return self.base_url != None\n\n def make_get_request(self, router_name:str):\n url = f'{self.base_url}{router_name}'\n try:\n logger.info(f'request {url}')\n output = urllib.request.urlopen(url).read().decode()\n logger.debug(f'output: {output}')\n objs = json.loads(output)\n return objs\n except Exception as ex:\n logger.exception(f'error on {url}', exc_info=ex)\n\n def make_post_request(self, router_name:str, values):\n url = f'{self.base_url}{router_name}'\n headers = {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n }\n data = json.dumps(values).encode(\"utf-8\")\n try:\n req = urllib.request.Request(url, data, headers)\n with urllib.request.urlopen(req) as f:\n output = f.read()\n logger.debug(f'output: {output}')\n return json.loads(output.decode())\n except Exception as ex:\n logger.exception(f'error on {url}', exc_info=ex)\n\nif __name__ == '__main__':\n RequestManager.on_port_ready(8081)\n aaa = RequestManager.make_get_request('/v1.0/app/footer/info')\n","sub_path":"requests_manager.py","file_name":"requests_manager.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"25386198","text":"\"\"\"A :py:class:`Register` is basically an :py:class:`Observable` container,\nthat notifies its :py:class:`Observer`s when entries are registered or\nunregistered.\n\n\"\"\"\n# Generic imports\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Iterator, Tuple, Union\nimport importlib\nimport logging\n\n# Toolbox imports\nfrom util.debug import debug_object\nfrom .observer import Observable\nfrom .busy import BusyObservable, busy\nfrom .prepare import Preparable\nfrom .fail import Failable\nfrom ..thirdparty import check_module_requirements\n\n\n# Logging\nLOG = logging.getLogger(__name__)\n\n\nclass Registrable(metaclass=ABCMeta):\n # pylint: disable=too-few-public-methods\n \"\"\"A :py:class:`Registrable` is an object that may be put into a\n :py:class:`Register`. This basically mean that it has a unique key\n (accessible via the :py:attr:`key` property).\n\n Attributes\n ----------\n key: str\n A (supposed to be unique) key for the new instance.\n \"\"\"\n @property\n @abstractmethod\n def key(self):\n \"\"\"Get the \"public\" key used to identify this entry in a register. The\n key is created upon initialization and should not be changed\n later on.\n\n \"\"\"\n # to be implemented by subclasses\n\n\nclass RegisterEntry(Registrable, debug_object):\n # pylint: disable=too-few-public-methods\n \"\"\"A :py:class:`RegisterEntry` is a base class for\n :py:class:`Registrable` objects. It realizes the :py:attr:`key`\n property by storing the key value as private property.\n\n Attributes\n ----------\n _key: str\n A (supposed to be unique) key for the new instance.\n\n Class Attributes\n ----------------\n _key_counter: int\n A counter for generating unique keys.\n\n \"\"\"\n\n _key_counter = 0\n\n def __init__(self, *args, key: str = None, **kwargs) -> None:\n \"\"\"Iniitalization of a :py:class:`RegisterEntry`. This will\n ensure that the object has a key.\n \"\"\"\n super().__init__(*args, **kwargs)\n self._key = key or self._generate_key()\n LOG.debug(\"RegisterEntry: init instance of class %s with key '%s'\",\n type(self).__name__, self.key)\n\n def _generate_key(self) -> str:\n \"\"\"Generate a key.\n \"\"\"\n type(self)._key_counter += 1\n return type(self).__name__ + str(self._key_counter)\n\n @property\n def key(self):\n \"\"\"Get the \"public\" key used to identify this entry in a register. The\n key is created upon initialization and should not be changed\n later on.\n\n \"\"\"\n return self._key\n\n\nclass Register(Observable, method='register_changed',\n changes={'entry_added', 'entry_changed', 'entry_removed'}):\n \"\"\"\n\n **Changes**\n\n 'entry_added':\n A new entry was added to this :py:class:`Register`.\n 'entry_changed'\n A register entry has changed.\n 'entry_removed':\n A key was remove from this :py:class:`Register`.\n \"\"\"\n\n def __init__(self, **kwargs) -> None:\n super().__init__(**kwargs)\n self._entries = {}\n\n def add(self, entry: Registrable) -> None:\n \"\"\"Add a new entry to this :py:class:`Register`\n \"\"\"\n key = entry.key\n self._entries[key] = entry\n self.register_change(key, 'entry_added')\n\n def remove(self, entry: Registrable) -> None:\n \"\"\"Remove an entry from this :py:class:`Register`\n \"\"\"\n key = entry.key\n del self._entries[key]\n self.register_change(key, 'entry_removed')\n\n #\n # The Container[Registrable] protocol\n #\n\n def __contains__(self, entry: Union[str, Registrable]) -> bool:\n \"\"\"Check if the given entry is registered.\n\n Argument\n --------\n entry: Union[str, Registrable]\n Either the entry or the key.\n \"\"\"\n return ((entry.key if isinstance(entry, Registrable) else entry)\n in self._entries)\n\n #\n # The Sized protocol\n #\n\n def __len__(self) -> int:\n \"\"\"The number of entries in this register.\n \"\"\"\n return len(self._entries)\n\n #\n # The Iterable interface\n #\n\n def __iter__(self) -> Iterator[Registrable]:\n \"\"\"Iterate the entries registered in this :py:class:`Register`.\n \"\"\"\n return map(lambda item: item[1], self._entries.items())\n\n #\n # item access\n #\n\n def __getitem__(self, key: str) -> Registrable:\n \"\"\"Lookup the entry for the given key in this :py:class:`Register`.\n \"\"\"\n return self._entries[key]\n\n def keys(self, **kwargs) -> Iterator[str]:\n \"\"\"Ieterate the keys of the entries registered\n in this :py:class:`Register`.\n \"\"\"\n return map(lambda entry: entry.key, self.entries(**kwargs))\n\n def entries(self) -> Iterator[str]:\n \"\"\"Iterate the entries of this :py:class:`Register`.\n \"\"\"\n return iter(self)\n\n def __iadd__(self, entry: Registrable) -> None:\n \"\"\"Add an new entry or change an existing entry\n in this :py:class:`Register`\n \"\"\"\n key = entry.key\n self._entries[key] = entry\n self.register_change(key, 'entry_added')\n\n def __delitem__(self, entry: Union[str, Registrable]) -> None:\n \"\"\"Remove an entry from this :py:class:`Register`\n \"\"\"\n key = entry if isinstance(entry, str) else entry.key\n del self._entries[key]\n self.register_change(key, 'entry_removed')\n\n def register_change(self, key: str, *args, **kwargs) -> None:\n \"\"\"Notify observers on a register change.\n \"\"\"\n changes = self.Change(*args, **kwargs)\n LOG.debug(\"register change on %s: %s with key='%s'\",\n self, changes, key)\n\n if not changes:\n return\n\n self.notify_observers(changes, key=key)\n\n\n#\n# The ClassRegister\n#\n\nclass StatefulRegisterEntry(BusyObservable, Registrable, Failable,\n method='entry_changed'):\n \"\"\"Base class for observable register items\n \"\"\"\n\n @property\n @abstractmethod\n def initialized(self) -> bool:\n \"\"\"A flag indicatining if the entry is initalized.\n \"\"\"\n\n\nclass StatefulRegister(Register, StatefulRegisterEntry.Observer):\n \"\"\"Base class for registers with stateful items.\n \"\"\"\n\n def add(self, entry: StatefulRegisterEntry) -> None:\n # pylint: ignore\n \"\"\"Add a new entry to this :py:class:`StatefulRegister`\n \"\"\"\n super().add(entry)\n # 'busy_changed', state_changed\n interests = StatefulRegisterEntry.Change('state_changed')\n self.observe(entry, interests=interests)\n\n def remove(self, entry: StatefulRegisterEntry) -> None:\n \"\"\"Remove an entry from this :py:class:`StatefulRegister`\n \"\"\"\n self.unobserve(entry)\n super().remove(entry)\n\n def entry_changed(self, entry: StatefulRegisterEntry,\n _change: StatefulRegisterEntry.Change) -> None:\n \"\"\"React to a change of the observed\n :py:class:`StatefulRegisterEntry`. Such a change will be\n propagated to observers of the register.\n \"\"\"\n self.register_change(entry.key, 'entry_changed')\n\n def entries(self, initialized: bool = None) -> Iterator[Registrable]:\n # pylint: disable=arguments-differ\n \"\"\"Iterate the entries of this register.\n \"\"\"\n return (super().entries() if initialized is None else\n filter(lambda entry: initialized is entry.initialized,\n super().entries()))\n\n#\n# The ClassRegister\n#\n\n\nclass ClassRegisterEntry(StatefulRegisterEntry):\n \"\"\"A :py:class:`ClassRegisterEntry` represents information that\n can be used to import a class. This includes module and class.\n \"\"\"\n\n def __init__(self, module_name: str = None, class_name: str = None,\n cls: type = None, **kwargs) -> None:\n \"\"\"\n\n Arguments\n ---------\n module_name: str\n Fully qualified Module name.\n class_name: str\n Class name, either short or fully qualified\n (including module name). In the latter case, no module\n name has to be provided.\n cls: type\n The instantiated class object. If given, `module_name`\n and `class_name` will be determined automatically and\n do not have to be provided.\n \"\"\"\n super().__init__(**kwargs)\n if not (module_name and class_name) and cls is None:\n raise ValueError(\"Provide either module and class name or class \"\n \"for ClassRegisterEntry\")\n\n if cls is not None:\n module_name, class_name = cls.__module__, cls.__name__\n elif module_name is None and '.' in class_name:\n module_name, class_name = class_name.rsplit('.', maxsplit=1)\n\n self.cls = cls\n self.module_name = module_name\n self.class_name = class_name\n\n def __str__(self) -> str:\n \"\"\"String representation of this :py:class:`ClassRegisterEntry`\n \"\"\"\n return (f\"{self.module_name}.{self.class_name}: \"\n f\"initialized={self.initialized}\")\n\n @property\n def key(self):\n \"\"\"The unique key identifying a class is the canonical (full)\n class name (including the module name).\n \"\"\"\n return self.module_name + '.' + self.class_name\n\n @property\n def initializable(self) -> bool:\n \"\"\"Check if this :py:class:`ClassRegisterEntry` can be initialized.\n Some classes may not be initializable due to unfulfilled requirements\n (like Python modules that have not been installed).\n \"\"\"\n return self.initialized or check_module_requirements(self.module_name)\n\n @property\n def initialized(self) -> bool:\n \"\"\"Check if the class represented by this Entry has been\n initialized.\n \"\"\"\n return self.cls is not None\n\n @busy(\"Initializing class\")\n def initialize(self) -> None:\n \"\"\"Initialize this class. This essentially means to load\n the module holding the class definition.\n \"\"\"\n if self.cls is not None:\n return # Nothing to do\n\n message = (f\"Initialization of class '{self.class_name}' \"\n f\"from module {self.module_name}\")\n with self.failure_manager(logger=LOG, message=message):\n module = importlib.import_module(self.module_name)\n self.cls = getattr(module, self.class_name)\n\n\nclass ClassRegister(StatefulRegister):\n \"\"\"A register for :py:class:`ClassRegisterEntry`s.\n \"\"\"\n\n def __init__(self, base_class: type = None, **kwargs) -> None:\n if base_class is None:\n raise ValueError(\"No base class was provided \"\n \"for the new ClassRegister.\")\n super().__init__(**kwargs)\n self._base_class = base_class\n\n @property\n def base_class(self) -> type:\n \"\"\"The base class of this :py:class:`ClassRegister`.\n All classes registered have to be subclasses of this base class.\n \"\"\"\n return self._base_class\n\n def __getitem__(self, key: Union[str, type]) -> Registrable:\n \"\"\"Lookup the entry for the given key in this :py:class:`Register`.\n \"\"\"\n if isinstance(key, type):\n key = f\"{key.__module__}.{key.__name__}\"\n return super().__getitem__(key)\n\n def initialized(self, full_name: str) -> bool:\n \"\"\"Check if a given class is initialized.\n \"\"\"\n return full_name in self and self[full_name].initialized\n\n def new_class(self, cls: type) -> None:\n \"\"\"Add a new class to this :py:class:`ClassRegisterEntry`.\n If there is already a :`ClassRegisterEntry` for this class,\n it will be updated, otherwise a new one will be created.\n \"\"\"\n key = cls.__module__ + '.' + cls.__name__\n if key in self:\n self[key].cls = cls\n self.register_change(key, 'entry_changed')\n else:\n self.add(ClassRegisterEntry(cls=cls))\n\n\nclass InstanceRegister(StatefulRegister):\n \"\"\"A register for :py:class:`InstanceRegisterEntry`s.\n \"\"\"\n\n def __init__(self, base_class: type = None, **kwargs) -> None:\n if base_class is None:\n raise ValueError(\"No base class was provided \"\n \"for the new InstanceRegister.\")\n super().__init__(**kwargs)\n self._base_class = base_class\n\n @property\n def base_class(self) -> type:\n \"\"\"The base class of this register. All instances registered\n have to be instances of this class (or one of its subclasses).\n \"\"\"\n return self._base_class\n\n\nclass InstanceRegisterEntry(StatefulRegisterEntry, RegisterEntry):\n \"\"\"A :py:class:`InstanceRegisterEntry` represents information that\n can be used to create an object. This includes module and\n class name as well as initialization parameters.\n \"\"\"\n\n def __init__(self, key: str = None, obj: object = None,\n cls: type = None, class_entry: ClassRegisterEntry = None,\n args=(), kwargs=None, **_kwargs) -> None:\n # pylint: disable=too-many-arguments\n # too-many-arguments:\n # It is fine to give all these arguments here, as they\n # are used to initialize one record of (initialization)\n # information.\n if key is None and obj is not None and isinstance(obj, Registrable):\n key = obj.key\n\n super().__init__(key=key, **_kwargs)\n\n if key is None:\n raise ValueError(\"No key provided for new InstanceRegisterEntry.\")\n\n if obj is not None:\n if cls is None:\n cls = type(obj)\n elif cls is not type(obj):\n raise TypeError(f\"Type mismatch between class {cls} \"\n f\"and object of type {type(obj)}.\")\n\n if cls is not None:\n if class_entry is None:\n class_entry = cls.class_register[cls]\n elif class_entry is not cls.class_register[cls]:\n raise TypeError(\"Type mismatch between class entry of \"\n f\"type {class_entry.cls} and class {cls}.\")\n\n if class_entry is None:\n raise ValueError(\"No class entry provided for \"\n \"InstancRegisterEntry.\")\n self._class_entry = class_entry\n self.obj = obj\n self.args, self.kwargs = args, (kwargs or {})\n\n def __str__(self) -> str:\n \"\"\"String representation of this :py:class:`InstancRegisterEntry`.\n \"\"\"\n return f\"{self.key}: {self._class_entry}\"\n\n @property\n def key(self) -> str:\n \"\"\"The unique key identifying a class is the canonical (full)\n class name (including the module name).\n \"\"\"\n return self._key\n\n @property\n def cls(self) -> type:\n \"\"\"The unique key identifying a class is the canonical (full)\n class name (including the module name).\n \"\"\"\n return self._class_entry.cls\n\n @property\n def initializable(self) -> bool:\n \"\"\"Check if this :py:class:`InstanceRegisterEntry` can be initialized.\n Some keys may not be initializable due to unfulfilled requirements\n (like Python modules that have not been installed).\n \"\"\"\n return self.initialized or self._class_entry.initializable\n\n @property\n def initialized(self) -> bool:\n \"\"\"A flag indicating if this :py:class:`InstanceRegisterEntry`\n is initialized (`True`) or not (`False`).\n \"\"\"\n return self.obj is not None and self.obj is not True\n\n @busy(\"Initializing instance\")\n def initialize(self, prepare: bool = False) -> None:\n # pylint: disable=arguments-differ\n \"\"\"Initialize this :py:class:`InstanceRegisterEntry`.\n When finished, the register observers will be informed on\n `entry_changed`, and the :py:attr:`initialized` property\n will be set to `False`.\n \"\"\"\n if self.obj is not None:\n return # Nothing to do\n\n # Initialize the class object\n self._class_entry.initialize(busy_async=False)\n\n message = (f\"Initialization of InstanceRegisterEntry '{self.key}' \"\n f\"from class {self._class_entry}\")\n with self.failure_manager(logger=LOG, message=message):\n self.obj = self._class_entry.cls(*self.args, key=self.key,\n **self.kwargs)\n\n self.change('state_changed')\n\n if prepare and isinstance(self.obj, Preparable):\n self.obj.prepare()\n\n @busy(\"Uninitializing instance\")\n def uninitialize(self) -> None:\n \"\"\"Unitialize this :py:class:`InstanceRegisterEntry`.\n When finished, the register observers will be informed on\n `entry_changed`, and the :py:attr:`initialized` property\n will be set to `False`.\n \"\"\"\n obj = self.obj\n if obj is None:\n return # nothing to do\n self.obj = None\n self.clean_failure()\n self.change('state_changed')\n del obj\n\n @property\n def register(self) -> InstanceRegister:\n \"\"\"The instance register of the :py:class:`RegisterClass` to\n which the object this :py:class:`InstanceRegisterEntry` belongs\n to.\n \"\"\"\n return (None if self._entry_class.cls is None else\n self._entry_class.cls.instance_register)\n\n\nclass RegisterClass(ABCMeta):\n # pylint: disable=no-value-for-parameter\n # no-value-for-parameter:\n # we disable this warning as there is actually a bug in pylint,\n # not recognizing `cls` as a valid first parameter instead\n # of `self` in metaclasses, and hence taking cls.method as\n # an unbound call, messing up the whole argument structure.\n \"\"\"A metaclass for classes that allow to register subclasses and\n instances.\n\n Class attributs\n ---------------\n\n A class assigned to this meta class will have the following\n attributes (these are considered private properties of the class,\n subject to change, that should be used outside the class):\n\n instance_register: InstanceRegister\n A InstanceRegister containing all registered keys for the class.\n The register contains :py:class:`InstanceRegisterEntry`s\n describing all registered instances, including all information\n required for instantiation. If an instances has been instantiated,\n `entry.obj` will be that instance.\n\n class_register: ClassRegister\n A ClassRegister containing all registered subclasses for\n the classes. The register contains :py:class:`ClassRegisterEntry`s\n describing all registered classes, including information\n for import and initialization. If a class has been created,\n `entry.cls` will be that class.\n\n Subclasses are automatically added to the `class_register` upon\n initialization, that is usually when the module defining the class\n is imported. Instances are also automatically added upon\n initialization. Instances are registered by a unique key (of type\n `str`).\n\n ** Preregistering classes and instances **\n\n It is also possible to preregister subclasses and instances.\n\n Subclasses can be preregistered by calling\n :py:meth:`register_class`. The idea of preregistering classes is\n to specify requirements that have to be fulfilled in order\n initialize (import) the class. This allows to filter out those\n subclasses with unmet requirements. The actual instantiation\n (import) of a class can be performed in a background thread by\n calling `py:meth:`ClassRegisterEntry.initialize`.\n\n Preregistering instances is done by the\n :py:meth:`register_instance` method, providing the class name and\n initialization parameters. Preregistering instances has mutliple\n purposes. It allows to provide initialization arguments and\n thereby store commonly used instances for fast access. As\n registration is fast (no additional imports or data loading takes\n place during registration), it can be done in the initialization\n phase of the toolbox without significant performance effects (only\n the abstract register base classes have to be imported). The\n actual instantiation can be done in a background thread by calling\n `py:meth:`InstancRegisterEntry.initialize`.\n\n A registered instance can be accessed by its key using the expression\n `Class[key]`. If not instantiated yet, the instance will be\n created (synchronously).\n \"\"\"\n\n class RegisterClassEntry(RegisterEntry):\n # pylint: disable=too-few-public-methods\n \"\"\"A registrable object that generates keys from a register.\n \"\"\"\n\n def _generate_key(self) -> str:\n # pylint: disable=no-member\n return (self.__class__.__name__ + \"-\" +\n str(len(self.instance_register)))\n\n def __new__(mcs, clsname: str, superclasses: Tuple[type],\n attributedict: dict, **class_parameters) -> None:\n # pylint: disable=bad-mcs-classmethod-argument\n \"\"\"A new class of the meta class scheme is defined.\n\n If this is a new base class, we add new class and key\n registers to that class.\n\n Parameters\n ----------\n clsname: str\n The name of the newly defined class.\n superclasses: str\n A list of superclasses of the new class.\n attributedict: dict\n The attributes (methods and class attributes ) of the\n newly defined class.\n class_parameters:\n Addition class parameters specificied in the class\n definition.\n \"\"\"\n is_base_class = not any(issubclass(supercls, mcs.RegisterClassEntry)\n for supercls in superclasses)\n if is_base_class:\n superclasses += (mcs.RegisterClassEntry, )\n\n # class_parameters are to be processed by __init_subclass__()\n # of some superclass of the newly created class ...\n cls = super().__new__(mcs, clsname, superclasses, attributedict,\n **class_parameters)\n if is_base_class:\n LOG.info(\"RegisterClass: new base class %s.%s\",\n cls.__module__, cls.__name__)\n cls.base_class = cls\n cls.instance_register = InstanceRegister(cls)\n cls.class_register = ClassRegister(cls)\n return cls\n\n def __init__(cls, clsname: str, _superclasses: Tuple[type],\n _attributedict: dict, **_class_parameters) -> None:\n \"\"\"Initialize a class declared with this :py:class:`RegisterClass`.\n This initialization will add a private class dictionary to\n hold the registered instances of the class.\n\n \"\"\"\n # super().__init__(clsname, superclasses, **class_parameters)\n super().__init__(clsname)\n\n # add the newly initialized class to the class register\n cls.class_register.new_class(cls)\n\n def __call__(cls, *args, **kwargs) -> None:\n \"\"\"A hook to adapt the initialization process for classes\n assigned to a :py:class:`RegisterClass`.\n This hook will automatically register all instances of that\n class in the register. If no register key is provided,\n a new one will be created from the class name.\n \"\"\"\n LOG.debug(\"RegisterClass: {cls.__name}.__call__({args}, {kwargs})\")\n new_entry = super().__call__(*args, **kwargs)\n\n if 'key' in kwargs and new_entry.key != kwargs['key']:\n LOG.warning(\"Key mismatch for new register entry: \"\n \"should be '%s' but is '%s'\",\n kwargs['key'], new_entry.key)\n\n # If the initialization has been invoked directly (not via\n # Register.instance_register.initialize), we will register the\n # new instance now.\n if new_entry not in cls.instance_register:\n entry = InstanceRegisterEntry(obj=new_entry,\n args=args, kwargs=kwargs)\n cls.instance_register.add(entry)\n\n LOG.info(\"RegisterClass: new instance of class %s with key '%s'\",\n type(new_entry).__name__, new_entry.key)\n return new_entry\n\n #\n # class related methods\n #\n\n def register_class(cls, name: str, module: str = None) -> None:\n \"\"\"Register a (sub)class of the :py:class:`RegisterClass`'s\n base class. These are the classes that upon initialization\n will be registered at this :py:class:`RegisterClass`.\n\n Subclasses of the base class will be automatically registered\n once the module defining the class is imported. However, it\n is possible to register classes in advance, allowing a user\n interface to offer the initialization (import) of that class.\n A class (registered or not) can be initialized by calling\n :py:class:`initializa_class`.\n\n Attributes\n ----------\n name: str\n The class name. Either the fully qualified name,\n including the module name, or just the class name.\n In the second case, the module name has to be provided\n by the argument.\n module: str\n The module name. Only required if not provided as part\n of the class name.\n \"\"\"\n full_name = name if module is None else \".\".join((module, name))\n if full_name not in cls.class_register:\n if module is None:\n module, name = name.rsplit('.', maxsplit=1)\n entry = ClassRegisterEntry(module_name=module, class_name=name)\n cls.class_register.add(entry)\n\n #\n # instance related methods\n #\n\n def register_instance(cls, key: str, module_name: str, class_name: str,\n *args, **kwargs) -> None:\n \"\"\"Register a key with this class. Registering a key will\n allow to initialize an instance of a class (or subclass)\n of this register.\n\n Arguments\n ---------\n key: str\n The unique key to be registered with this class.\n module_name: str\n The module in which the class is defined.\n class_name: str\n The name of the class.\n *args, **kwargs:\n Arguments to be passed to the constructor when initializing\n the key.\n \"\"\"\n if key in cls.instance_register:\n raise ValueError(f\"Duplcate registration of {cls.__name__}\"\n f\"with key '{key}'.\")\n\n full_name = module_name + '.' + class_name\n if full_name not in cls.class_register:\n cls.register_class(full_name)\n class_entry = cls.class_register[full_name]\n\n entry = InstanceRegisterEntry(key=key, class_entry=class_entry,\n args=args, kwargs=kwargs)\n\n cls.instance_register.add(entry)\n\n def __len__(cls):\n return len(cls.instance_register)\n\n def __contains__(cls, key) -> bool:\n \"\"\"Check if a given key was registered with this class.\n \"\"\"\n return key in cls.instance_register\n\n def __getitem__(cls, key: str) -> object:\n \"\"\"Access the instantiated entry for the given key.\n If the entry was not instantiated yet, it will be\n instantiated now.\n \"\"\"\n if key not in cls:\n raise KeyError(f\"No key '{key}' registered for class \"\n f\"{cls.instance_register.base_class}\"\n f\"[{cls.__name__}]. Valid keys are: \"\n f\"{list(cls.instance_register.keys())}\")\n entry = cls.instance_register[key]\n if not entry.initialized:\n entry.initialize(busy_async=False)\n\n return entry.obj\n\n #\n # Debugging\n #\n\n def debug_register(cls):\n \"\"\"Output debug information for this :py:class:`RegisterClass`.\n \"\"\"\n print(f\"debug: register {cls.__name__} \")\n print(f\"debug: {len(cls.class_register)} registered subclasses:\")\n for i, entry in enumerate(cls.class_register):\n print(f\"debug: ({i+1}) {entry.key}: \"\n f\"initialized={entry.initialized}\")\n print(f\"debug: {len(cls.instance_register)} registered instances:\")\n for i, entry in enumerate(cls.instance_register):\n print(f\"debug: ({i+1}) {entry.key}: \"\n f\"initialized={entry.initialized}\")\n","sub_path":"dltb/base/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":28577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"267362872","text":"import webapp2\nfrom webapp2_extras import jinja2\nimport time\n\nfrom webapp2_extras.users import users\nfrom model.mensaje import Mensaje\n\nclass ListaMensajesHandler(webapp2.RequestHandler):\n def get(self):\n url_usr = users.create_logout_url(\"/\")\n\n chat, mensajes = Mensaje.recupera_para(self.request)\n\n for mensaje in mensajes:\n if mensaje.usuario != users.get_current_user().email():\n mensaje.estado = True\n mensaje.put()\n time.sleep(1)\n\n if chat.usuario1 == users.get_current_user().email():\n usr = chat.usuario2\n elif chat.usuario2 == users.get_current_user().email():\n usr = chat.usuario1\n else:\n return self.redirect(\"/inicio\")\n\n valores_plantilla = {\n \"mensajes\": mensajes,\n \"chat\": chat,\n \"url_usr\": url_usr,\n \"usr\": usr\n }\n\n jinja = jinja2.get_jinja2(app=self.app)\n self.response.write(jinja.render_template(\"lista_mensajes.html\",\n **valores_plantilla))\n\napp = webapp2.WSGIApplication([\n ('/mensajes/lista', ListaMensajesHandler)\n], debug=True)\n","sub_path":"proyecto-als/handlers/mensajes/lista.py","file_name":"lista.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"415076566","text":"class Solution:\r\n # @return an integer\r\n def totalNQueens(self, n):\r\n \"\"\"\r\n Third iteration: copied from n-queen I.\r\n \"\"\"\r\n self.res, board = 0, [['.' for j in range(n)] for i in range(n)]\r\n self.addOne(0, n, board, self.res)\r\n return self.res\r\n\r\n def addOne(self, i, n, board, res):\r\n if i == n:\r\n self.res += 1\r\n return\r\n assert i < n\r\n for j in range(n):\r\n if all(board[k][j] != 'Q' for k in reversed(range(i))) and \\\r\n all(board[i - k][j - k] != 'Q' for k in range(1, min(i, j) + 1)) and \\\r\n all(board[i - k][j + k] != 'Q' for k in range(1, min(i, n - j - 1) + 1)):\r\n board[i][j] = 'Q'\r\n self.addOne(i + 1, n, board, res)\r\n board[i][j] = '.'\r\n\r\ndef run():\r\n sol = Solution()\r\n ret = sol.totalNQueens(4)\r\n assert ret == 2\r\n","sub_path":"052-n-queens-II.py","file_name":"052-n-queens-II.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"447640648","text":"# -*- coding: utf-8 -*-\n\nfrom pythinkutils.aio.jwt.tornado.handler.AuthHandler import AuthHandler\nfrom pythinkutils.common.StringUtils import *\n\nclass JWTHandler(AuthHandler):\n\n async def create_token(self, szAppId, szSecret):\n from pythinkutils.aio.jwt.TokenUtils import TokenUtils\n\n return await TokenUtils.auth_token(szAppId, szSecret)\n\n async def token_valid(self):\n from pythinkutils.aio.jwt.TokenUtils import TokenUtils\n\n szToken = await self.get_token()\n if is_empty_string(szToken):\n return False\n\n nExpire = await TokenUtils.expire_time(szToken)\n return nExpire > 0\n\n async def get_uid_name(self):\n try:\n dictUser = await self.get_userinfo()\n if dictUser is None:\n return None, None\n\n return dictUser[\"user\"][\"userId\"], dictUser[\"user\"][\"userName\"]\n except Exception as e:\n return None, None\n\n async def get_userinfo(self):\n from pythinkutils.aio.jwt.TokenUtils import TokenUtils\n\n szToken = await self.get_token()\n if is_empty_string(szToken):\n return None\n\n return await TokenUtils.get_info(szToken)\n\n async def get_token(self):\n szAuth = self.request.headers.get(\"Authorization\")\n if is_empty_string(szAuth):\n return None\n\n lstItem = szAuth.split(\" \")\n if lstItem is None or len(lstItem) <= 0 or \"Bearer\" != lstItem[0].strip():\n return None\n\n return lstItem[1]\n\n async def get_permission_list(self):\n try:\n dictUser = await self.get_userinfo()\n if dictUser is None:\n return None\n\n return dictUser[\"permissions\"]\n except Exception as e:\n return None, None","sub_path":"pythinkutils/aio/jwt/tornado/handler/JWTHandler.py","file_name":"JWTHandler.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"624321464","text":"#!/usr/bin/env python\r\n# 版權2020©John Melody Me\r\n# 根據Apache許可版本2.0(“許可”)許可;\r\n# 除非遵守許可,否則不得使用此文件。\r\n# 您可以在以下位置獲得許可的副本:\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n# 除非適用法律要求或書面同意,否則軟件\r\n# 根據許可分發的內容按“原樣”分發,\r\n# 沒有任何明示或暗示的保證或條件。\r\n# 有關特定語言的管理權限,請參閱許可證。\r\n# 許可中的限制。\r\n# @作者:John Melody Me\r\n# @URL: https://github.com/johnmelodyme/Machine-Learning-Porn-detection\r\n#https://aistudio.baidu.com/aistudio/projectdetail/267322\r\nimport sys\r\nimport subprocess\r\nimport pkg_resources\r\n\r\n# 檢查 [] 是否已經安裝:\r\nrequired_modules = {\"paddlehub\", \"matplotlib\"}\r\ninstalled = {pkg.key for pkg in pkg_resources.working_set}\r\nmissing = required_modules - installed\r\n\r\nif missing:\r\n python = sys.executable\r\n subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)\r\nelse:\r\n print(\"Dependencies Already Installed\", required_modules, \"\\n\")\r\n\r\nimport matplotlib.pyplot as plt \r\nimport matplotlib.image as mpimg \r\n# import paddlehub as hub\r\n\r\n# 獲取輸入進行分析 :: 待預測圖片\r\ninput_data = [\"assets/image/covid1.jpg\", \"assets/image/covid2.jpg\"]\r\nimage = mpimg.imread(input_data[1])\r\n# 展示待預測圖片\r\nplt.figure(figsize=(10,10))\r\nplt.imshow(image) \r\nplt.axis('off') \r\nplt.show()\r\n\r\nwith open(\"covid19faceMaskDetection/output.txt\", \"r\") as f:\r\n input_data = []\r\n for line in f:\r\n input_data.append(line.strip())\r\nprint(input_data)\r\n\r\n\r\n# module = hub.Module(name=\"pyramidbox_lite_mobile_mask\")","sub_path":"covid19faceMaskDetection/faceMaskDetection.py","file_name":"faceMaskDetection.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"20754829","text":"from dj_rql.filter_cls import RQLFilterClass\nfrom dj_rql.qs import SelectRelated\n\nfrom ..models import Product\n\n\nclass ProductFilters(RQLFilterClass):\n MODEL = Product\n SELECT = True\n FILTERS = (\n {\n 'filter': 'id',\n 'ordering': True,\n },\n {\n 'filter': 'name',\n 'search': True,\n },\n {\n 'namespace': 'category',\n 'filters': ('id', 'name'),\n 'qs': SelectRelated('category'),\n },\n {\n 'namespace': 'company',\n 'filters': ('id', 'name'),\n 'hidden': True,\n 'qs': SelectRelated('company'),\n },\n )","sub_path":"dukaapp/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"619246711","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n \r\ndef five():\r\n n_groups = 3\r\n means_ssc = (60, 50, 33)\r\n means_nonssc = (55,40 ,40)\r\n \r\n\r\n fig, ax = plt.subplots()\r\n index = np.arange(n_groups)\r\n bar_width = 0.35\r\n opacity = 0.8\r\n \r\n rects1 = plt.bar(index, means_ssc, bar_width,\r\n alpha=opacity,\r\n color='b',\r\n label='SSC')\r\n \r\n rects2 = plt.bar(index + bar_width, means_nonssc, bar_width,\r\n alpha=opacity,\r\n color='g',\r\n label='Non-SSC')\r\n \r\n plt.xlabel('College')\r\n plt.ylabel('Students')\r\n plt.title('Inter-college ssc and non-ssc members')\r\n plt.xticks(index + bar_width, ('SCOE', 'NBN', 'SKN'))\r\n plt.legend()\r\n \r\n plt.tight_layout()\r\n plt.show()\r\n\r\nfive()\r\n","sub_path":"graph5.py","file_name":"graph5.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"470113450","text":"import boto3\nimport time\nimport jwt\nimport hashlib\nimport os\nfrom flask import Flask, render_template, request, jsonify, redirect, url_for\nfrom flask_cors import CORS\nfrom datetime import datetime, timedelta\nfrom pymongo import MongoClient\n\napplication = Flask(__name__)\ncors = CORS(application, resources={r\"/*\": {\"origins\": \"*\"}})\n\n# client = MongoClient('mongodb://test:test@localhost', 27017)\n# client = MongoClient(\"mongodb://localhost\", 27017)\nclient = MongoClient(os.environ.get(\"MONGO_DB_PATH\"))\n\ndb = client.dbMuscle\n\nSECRET_KEY = os.environ.get('SECRET_KEY')\n\n\n###################### new Template 관련 def ########################\n\n@application.route('/', methods=['GET'])\ndef home():\n return render_template('index.html')\n\n\n# video 관련 된 것을 화면에 찍어주는 html 라우팅\n@application.route('/video', methods=['GET'])\ndef get_video_html():\n return render_template('video.html')\n\n\n@application.route('/video-list', methods=['GET'])\ndef get_video_list_html():\n return render_template('video-list.html')\n\n\n@application.route('/question', methods=['GET'])\ndef get_question():\n codes = list(db.question.find({}).distinct('group'))\n return jsonify(codes)\n\n\n@application.route('/codes', methods=['GET'])\ndef get_codes():\n group = request.args.get('group')\n codes = list(db.question.find({'group': group}, {'_id': False}))\n return jsonify(codes)\n\n\n# 전체 video 가져오기\n@application.route('/api/videos', methods=['POST'])\ndef get_videos():\n info = request.json\n videos = list(db.videos.find(info, {'_id': False}))\n return jsonify(videos)\n\n\n# 카테고리 별로 videos 가져오기\n@application.route('/api/videos/category', methods=['GET'])\ndef get_videos_by_category():\n category = request.args.get('category')\n category_videos = list(db.videos.find({'category': category}, {'_id': False}))\n return jsonify(category_videos)\n\n\n# 추천 비디오 가져오기\n@application.route('/api/videos/suggestion', methods=['GET'])\ndef get_suggestion_videos():\n info = request.args.get('data')\n experience = \"experience-\" + info.split('-')[1][:1]\n interest = \"interest-\" + info.split('-')[2][:1]\n videos = list(db.question_videos.find({\"experience\": experience, \"interest\": interest}, {'_id': False}))\n return jsonify(videos)\n\n###################### 로그인 & 회원가입 관련 def ###############\n\n\n# 로그인 페이지 라우팅\n@application.route('/login', methods=['GET'])\ndef login_page():\n return render_template('login.html')\n\n\n# 회원가입 ID와 비밀번호를 받아서 DB에 저장\n@application.route('/login/sign_up', methods=['POST'])\ndef sign_up():\n userid_receive = request.form['userid_give']\n password_receive = request.form['password_give']\n password_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()\n doc = {\n \"userid\": userid_receive,\n \"password\": password_hash\n }\n db.usersdata.insert_one(doc)\n return jsonify({'result': 'success'})\n\n\n# 회원가입 시 ID 중복검사\n@application.route('/sign_up/check_dup', methods=['POST'])\ndef check_dup():\n userid_receive = request.form['userid_give']\n exists = bool(db.usersdata.find_one({\"userid\": userid_receive}))\n return jsonify({'result': 'success', 'exists': exists})\n\n\n@application.route('/login/sign_in', methods=['POST'])\ndef sign_in():\n # 로그인\n userid_receive = request.form['userid_give']\n password_receive = request.form['password_give']\n\n pw_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()\n result = db.usersdata.find_one({'userid': userid_receive, 'password': pw_hash})\n\n if result is not None:\n payload = {\n 'id': userid_receive,\n 'exp': datetime.utcnow() + timedelta(seconds=60 * 60 * 24) # 로그인 24시간 유지\n }\n token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')\n\n return jsonify({'result': 'success', 'token': token})\n # 찾지 못하면\n else:\n return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})\n\n# login check\n@application.route('/login/logout', methods=['GET'])\ndef login_logout():\n\n token_receive = request.cookies.get('mytoken')\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n login_id = payload[\"id\"]\n\n return jsonify(login_id)\n\n\n###################### 득근 QnA ########################\n\n# QnA list 화면에 찍어주는 html 라우팅\n@application.route('/board-list', methods=['GET'])\ndef get_board_list_html():\n return render_template('board-list.html')\n\n\n# QnA 하나 화면에 찍어주는 html 라우팅\n@application.route('/board-detail')\ndef get_board_detail_html():\n return render_template('board-detail.html')\n\n\n# board update 화면에 찍어주는 html 라우팅\n@application.route('/board-update')\ndef get_board_update_html():\n return render_template('board-update.html')\n\n\n# QnA create 화면에 찍어주는 html 라우팅\n@application.route('/board-create')\ndef get_board_create_html():\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n user_info = db.users.find_one({\"username\": payload[\"id\"]})\n return render_template('board-create.html', user_info=user_info)\n except jwt.ExpiredSignatureError:\n return redirect(url_for(\"login_page\", msg=\"로그인 시간이 만료되었습니다.\"))\n except jwt.exceptions.DecodeError:\n return render_template('board-create.html')\n\n # return redirect(url_for(\"login_page\", msg=\"로그인 정보가 존재하지 않습니다.\"))\n\n\n# QnA 전체 가져오기\n@application.route(\"/get-posts\", methods=['GET'])\ndef get_posts():\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n # boards = list(db.boards.find({}).sort(\"date\", -1).limit(20))\n boards = list(db.boards.find({}).sort(\"date\", -1))\n for board in boards:\n board[\"_id\"] = str(board[\"_id\"])\n board[\"count_heart\"] = db.likes.count_documents({\"board_id\": board[\"_id\"], \"type\": \"heart\"})\n board[\"heart_by_me\"] = bool(\n db.likes.find_one({\"board_id\": board[\"_id\"], \"type\": \"heart\", \"userid\": payload['id']}))\n print(board[\"_id\"])\n print(type(board[\"_id\"]))\n print(board[\"heart_by_me\"])\n print(boards)\n print(board[\"heart_by_me\"])\n print(board[\"count_heart\"])\n return jsonify({\"result\": \"success\", \"msg\": \"포스팅을 가져왔습니다.\", \"boards\": boards})\n except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):\n return redirect(url_for(\"login_page\"))\n\n\n# QnA 조회수 증가\n@application.route('/api/views', methods=['POST'])\ndef update_views():\n idx_receive = int(request.form['idx_give'])\n\n target_post = db.boards.find_one({'idx': idx_receive})\n\n current_views = target_post['views']\n new_views = current_views + 1\n\n db.boards.update_one({'idx': idx_receive}, {'$set': {'views': new_views}})\n\n return jsonify({'msg': '조회수 업데이트 완료!'})\n\n\n# QnA 좋아요 코드\n@application.route('/update_like', methods=['POST'])\ndef like_star():\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n user_info = db.usersdata.find_one({\"userid\": payload[\"id\"]})\n board_id_receive = request.form[\"board_id_give\"]\n type_receive = request.form[\"type_give\"]\n action_receive = request.form[\"action_give\"]\n doc = {\n \"board_id\": board_id_receive,\n \"userid\": user_info[\"userid\"],\n \"type\": type_receive\n }\n if action_receive == \"like\":\n db.likes.insert_one(doc)\n else:\n db.likes.delete_one(doc)\n count = db.likes.count_documents({\"board_id\": board_id_receive, \"type\": type_receive})\n return jsonify({\"result\": \"success\", 'msg': 'updated', \"count\": count})\n except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):\n return redirect(url_for(\"login_page\"))\n\n\n# QnA 하나 가져오는 기능\n@application.route('/api/board/post', methods=['GET'])\ndef get_board_detail():\n token_receive = request.cookies.get('mytoken')\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n login_id = payload[\"id\"]\n\n idx_receive = int(request.args.get('idx_give'))\n data = db.boards.find_one({'idx': idx_receive}, {'_id': False})\n print(\"result:\", data)\n return jsonify({\"data\": data, \"login_id\": login_id})\n\n\n# QnA 작성(저장) 기능\n@application.route('/api/post', methods=['POST'])\ndef board_create():\n token_receive = request.cookies.get('mytoken')\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n user_info = db.usersdata.find_one({\"userid\": payload[\"id\"]})\n title_receive = request.form['title_give']\n content_receive = request.form['content_give']\n\n boards_count = db.boards.count()\n if boards_count == 0:\n max_value = 1\n else:\n max_value = db.boards.find_one(sort=[(\"idx\", -1)])['idx'] + 1\n\n if title_receive == \"\" or content_receive == \"\":\n return jsonify({'msg': '빈칸에 내용을 입력해주세요!'})\n\n doc = {\n 'idx': max_value,\n \"userid\": user_info[\"userid\"],\n 'title': title_receive,\n 'content': content_receive,\n 'created_at': time.strftime('%Y-%m-%d', time.localtime(time.time())),\n 'views': 0,\n }\n\n db.boards.insert_one(doc)\n return jsonify({\"result\": \"success\", 'msg': '포스팅 성공'})\n\n\n# QnA 수정 페이지에서 값 받아오기\n@application.route('/api/board-update', methods=['GET'])\ndef update_board():\n print(request.args.get('idx_give'))\n print(type(request.args.get('idx_give')))\n idx_receive = int(request.args.get('idx_give'))\n print(idx_receive)\n content_data = db.boards.find_one({'idx': idx_receive}, {'_id': False})\n print(content_data)\n return jsonify({'content_data': content_data})\n\n# QnA 수정 기능\n@application.route('/api/board-update', methods=['POST'])\ndef update_board_content():\n idx_receive = int((request.form['idx_give']))\n update_receive = request.form['update_content_give'] # 수정할 텍스트를 받아왔음\n title_receive = request.form['title_give'] # 받아온타이틀\n db.boards.update_one({'idx': idx_receive}, {\"$set\": {'title': title_receive}})\n db.boards.update_one({'idx': idx_receive}, {\"$set\": {'content': update_receive}})\n return jsonify({'msg': '저장 완료!'})\n\n\n# QnA 하나 제거하는 기능\n@application.route('/api/delete', methods=['POST'])\ndef delete_board():\n idx_receive = int((request.form['idx_give']))\n db.boards.delete_one({'idx': idx_receive}) # 받아온 이름으로 db 삭제하기\n return jsonify({'msg': '삭제 완료!'}) # 메세지 리턴해주기\n\n\n## 21-10-13 1차 푸시\n\n## 피드 작성 화면\n@application.route('/posting')\ndef posting_html():\n return render_template('posting-save.html')\n\n\n## 피드 상세 화면\n@application.route('/posting/detail')\ndef posting_detail_html():\n return render_template('posting-detail.html')\n\n\n## 피드 목록 화면\n@application.route('/posting/list')\ndef posting_list_html():\n return render_template('posting-list.html')\n\n## 피드 수정 화면\n@application.route('/posting/update')\ndef posting_update_html():\n return render_template('posting-update.html')\n\n\n## 업로드한 사진 S3 저장 / image url DB에 저장\n@application.route('/fileupload', methods=['POST'])\ndef file_upload():\n file = request.files['file']\n s3 = boto3.client('s3')\n s3.put_object(\n ACL=\"public-read\",\n Bucket=\"teamco-project\",\n Body=file,\n Key=file.filename,\n ContentType=file.content_type)\n\n location = s3.get_bucket_location(Bucket=\"teamco-project\")['LocationConstraint']\n print(location)\n image_url = f'https://{\"teamco-project\"}.s3.{location}.amazonaws.com/{file.filename}'\n print(image_url)\n\n image_count = db.image_url.find({}).count()\n\n if image_count == 0:\n max_value = 1\n else:\n max_value = db.image_url.find_one(sort=[(\"idx\", -1)])['idx'] + 1\n\n doc = {\n 'image_url': image_url,\n 'idx': max_value\n }\n\n db.image_url.insert_one(doc)\n\n posting_idx = db.image_url.find_one({'idx': int(max_value)})\n print(posting_idx)\n return jsonify({'result': 'success'})\n\n\n## 일지 DB 저장\n@application.route('/api/posting', methods=['POST'])\ndef posting():\n token_receive = request.cookies.get('mytoken')\n print(token_receive)\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n print(payload)\n userid = payload['id']\n print(userid)\n\n title_receive = request.form['title_give']\n content_receive = request.form['content_give']\n\n workout_receive_01 = request.form['workout_give_01']\n min_receive_01 = request.form['min_give_01']\n time_receive_01 = request.form['time_give_01']\n\n workout_receive_02 = request.form['workout_give_02']\n min_receive_02 = request.form['min_give_02']\n time_receive_02 = request.form['time_give_02']\n\n workout_receive_03 = request.form['workout_give_03']\n min_receive_03 = request.form['min_give_03']\n time_receive_03 = request.form['time_give_03']\n\n breakfast_receive = request.form['breakfast_give']\n lunch_receive = request.form['lunch_give']\n dinner_receive = request.form['dinner_give']\n posting_count = db.posting.count()\n\n if posting_count == 0:\n max_value = 1\n else:\n max_value = db.posting.find_one(sort=[(\"idx\", -1)])['idx'] + 1\n\n doc = {\n 'title': title_receive,\n 'content': content_receive,\n 'workout_01': workout_receive_01,\n 'min_01': min_receive_01,\n 'time_01': time_receive_01,\n 'workout_02': workout_receive_02,\n 'min_02': min_receive_02,\n 'time_02': time_receive_02,\n 'workout_03': workout_receive_03,\n 'min_03': min_receive_03,\n 'time_03': time_receive_03,\n 'breakfast': breakfast_receive,\n 'lunch': lunch_receive,\n 'dinner': dinner_receive,\n 'created_at': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),\n 'views': 0,\n 'idx': max_value,\n 'userid': userid\n }\n\n db.posting.insert_one(doc)\n return jsonify({'msg': '저장 완료!'})\n\n\n# 일지 상세내용 불러오기\n\n@application.route('/api/posting/detail', methods=['GET'])\ndef posting_detail():\n idx_receive = request.args.get('idx_give')\n print(idx_receive)\n data = db.posting.find_one({\"idx\": int(idx_receive)}, {\"_id\": False})\n print(data)\n\n image_data = db.image_url.find_one({\"idx\": int(idx_receive)}, {\"_id\": False})\n image = image_data['image_url']\n print(image)\n\n token_receive = request.cookies.get('mytoken')\n print(token_receive)\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n print(payload)\n login_id = payload[\"id\"]\n\n return jsonify(data, image, login_id)\n\n\n## 일지 피드에 불러오기\n@application.route('/api/posting/list', methods=['GET'])\ndef posting_list():\n image = list(db.image_url.find({}, {'_id': False}))\n print(\"result:\", image)\n\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n posts = list(db.posting.find({}).sort(\"date\", -1))\n for post in posts:\n # post['idx'] = str(post[\"idx\"])\n # print(\"확인1\", post['idx'])\n post[\"_id\"] = str(post[\"_id\"])\n print(\"result:아아\", post[\"_id\"])\n post[\"count_heart\"] = db.likes.count_documents({\"post_idx\": str(post[\"idx\"]), \"type\": \"heart\"})\n print(\"확인2\", post[\"count_heart\"])\n post[\"heart_by_me\"] = bool(\n db.likes.find_one({\"post_idx\": str(post[\"idx\"]), \"type\": \"heart\", \"userid\": payload['id']}))\n print(\"확인3\", post['heart_by_me'])\n\n return jsonify(posts, image)\n except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):\n return redirect(url_for(\"home\"))\n\n\n# 수정할 일지 상세내용 불러오기\n@application.route('/api/posting/update', methods=['GET'])\ndef posting_update():\n idx_receive = request.args.get('idx_give')\n print(idx_receive)\n data = db.posting.find_one({\"idx\": int(idx_receive)}, {\"_id\": False})\n print(data)\n\n image_data = db.image_url.find_one({\"idx\": int(idx_receive)}, {\"_id\": False})\n image = image_data['image_url']\n print(image)\n\n return jsonify(data, image)\n\n\n## 수정된 내용 db 업데이트하기\n@application.route('/api/posting/update', methods=['POST'])\ndef posting_db_update():\n idx_receive = request.form['idx_give']\n\n title_receive = request.form['title_give']\n content_receive = request.form['content_give']\n\n workout_receive_01 = request.form['workout_give_01']\n min_receive_01 = request.form['min_give_01']\n time_receive_01 = request.form['time_give_01']\n\n workout_receive_02 = request.form['workout_give_02']\n min_receive_02 = request.form['min_give_02']\n time_receive_02 = request.form['time_give_02']\n\n workout_receive_03 = request.form['workout_give_03']\n min_receive_03 = request.form['min_give_03']\n time_receive_03 = request.form['time_give_03']\n\n breakfast_receive = request.form['breakfast_give']\n lunch_receive = request.form['lunch_give']\n dinner_receive = request.form['dinner_give']\n\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'title': title_receive}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'content': content_receive}})\n\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'workout_01': workout_receive_01}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'min_01': min_receive_01}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'time_01': time_receive_01}})\n\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'workout_02': workout_receive_02}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'min_02': min_receive_02}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'time_02': time_receive_02}})\n\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'workout_03': workout_receive_03}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'min_03': min_receive_03}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'time_03': time_receive_03}})\n\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'breakfast': breakfast_receive}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'lunch': lunch_receive}})\n db.posting.update_one({\"idx\": int(idx_receive)}, {\"$set\": {'dinner': dinner_receive}})\n\n return jsonify({'msg': '수정완료!'})\n\n## 피드 좋아요\n@application.route('/posting/update/like', methods=['POST'])\ndef update_like():\n token_receive = request.cookies.get('mytoken')\n try:\n payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])\n # 좋아요 수 변경\n user_info = db.usersdata.find_one({\"userid\": payload[\"id\"]})\n print(\"userinfo\", user_info)\n post_idx_receive = request.form[\"post_idx_give\"]\n print(\"idxreceive\", post_idx_receive)\n type_receive = request.form[\"type_give\"]\n action_receive = request.form[\"action_give\"]\n print(\"action\", action_receive)\n doc = {\n \"post_idx\": post_idx_receive,\n \"userid\": user_info[\"userid\"],\n \"type\": type_receive\n }\n if action_receive == \"like\":\n db.likes.insert_one(doc)\n else:\n db.likes.delete_one(doc)\n count = db.likes.count_documents({\"post_idx\": post_idx_receive, \"type\": type_receive})\n return jsonify({\"result\": \"success\", 'msg': 'updated', \"count\": count})\n except (jwt.ExpiredSignatureError, jwt.exceptions.DecodeError):\n return redirect(url_for(\"home\"))\n\n\n## 피드 삭제하기\n@application.route('/api/posting/delete', methods=['POST'])\ndef posting_delete():\n idx_receive = request.form['idx_give']\n print(\"포스팅:\", idx_receive)\n db.posting.delete_one({\"idx\": int(idx_receive)})\n db.image_url.delete_one({\"idx\": int(idx_receive)})\n return jsonify({'msg': '삭제완료'})\n\n\nif __name__ == '__main__':\n application.run('0.0.0.0', port=5000, debug=True)","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":20613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"372510298","text":"# coding: utf-8\n\nimport time\nimport Tkinter as tkinter\n\nWIDTH = 640\nHEIGHT = 480\nLEFT = -2\nRIGHT = 0.5\nTOP = 1.25\nBOTTOM = -1.25\nITERATIONS = 40\nUPDATE_TIME = 0.75\n\n\nclass HumanDuration(object):\n CHUNKS = (\n (60 * 60 * 24 * 365, 'years'),\n (60 * 60 * 24 * 30, 'months'),\n (60 * 60 * 24 * 7, 'weeks'),\n (60 * 60 * 24, 'days'),\n (60 * 60, 'hours'),\n )\n def __call__(self, t):\n if t < 1:\n return \"%.1f ms\" % round(t * 1000, 1)\n if t < 60:\n return \"%.1f sec\" % round(t, 1)\n if t < 60 * 60:\n return \"%.1f min\" % round(t / 60, 1)\n\n for seconds, name in self.CHUNKS:\n count = t / seconds\n if count >= 1:\n count = round(count, 1)\n break\n return \"%.1f %s\" % (count, name)\nhuman_duration = HumanDuration()\n\n\nroot = tkinter.Tk()\nimage = tkinter.PhotoImage(width=WIDTH, height=HEIGHT)\nlb1 = tkinter.Label(root, image=image)\nlb1.pack()\n\n\nstart_time = time.time()\ntime_threshold = start_time + (UPDATE_TIME / 2)\n\n\npixel_count = 0\ntotal_count = HEIGHT * WIDTH\nfor y in range(HEIGHT):\n for x in range(WIDTH):\n z = complex(0, 0)\n c = complex(LEFT + x * (RIGHT - LEFT) / WIDTH, TOP + y * (BOTTOM - TOP) / HEIGHT)\n norm = abs(z) ** 2\n for count in xrange(ITERATIONS):\n if norm <= 4.0:\n z = z * z + c\n norm = abs(z * z)\n else:\n break\n\n if count <= 4:\n (r, g, b) = (128, 128, 128) # grey\n elif count <= 8:\n (r, g, b) = (0, 255, 0) # green\n elif count <= 10:\n (r, g, b) = (0, 0, 255) # blue\n elif count <= 12:\n (r, g, b) = (255, 0, 0) # red\n elif count <= 15:\n (r, g, b) = (255, 255, 0) # yellow\n else:\n (r, g, b) = (0, 0, 0) # black\n\n (r, g, b) = (count * 6, 0, 0)\n\n pixel_count += 1\n image.put(\"#%02x%02x%02x\" % (r, g, b), (x, y))\n\n current_time = time.time()\n if current_time > (time_threshold + UPDATE_TIME):\n\n elapsed = float(current_time - start_time) # Vergangene Zeit\n estimated = elapsed / pixel_count * total_count # Geschätzte Zeit\n remain = estimated - elapsed\n performance = pixel_count / elapsed\n percent = round(float(pixel_count) / total_count * 100.0, 2)\n\n print (\n \" \"\n \"%(percent).1f%%\"\n \" - current: %(elapsed)s\"\n \" - total: %(estimated)s\"\n \" - remain: %(remain)s\"\n \" - %(perf).1f pixel/sec\"\n \" \"\n ) % {\n \"percent\" : percent,\n \"elapsed\" : human_duration(elapsed),\n \"estimated\": human_duration(estimated),\n \"remain\" : human_duration(remain),\n \"perf\" : performance,\n }\n\n time_threshold = current_time\n\n root.update()\n\nroot.mainloop()\n","sub_path":"CodeSnippets/PyRayTracer/mandelbrot.py","file_name":"mandelbrot.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"534305623","text":"import math \nimport nltk\nimport operator\nimport random\nfrom itertools import chain\nfrom itertools import repeat\nfrom collections import Counter\n\n## This function allows the user to read in all the n_grams in a \n## corpus. \ndef n_gram_reader(n, text, add_one = True): \n \n ## Minor sanity check\n if n <= 0:\n sys.exit(\"invalid n\")\n\n ## Zip allows for element-wise combination.\n ## This way creates lists of n-words that are \n ## adjacent to each other\n n_gram_read = zip(* [text[i:] for i in range(n)]) \n \n ## Concatenate the list into strings for better data \n ## manipulation\n for i in range(len(n_gram_read)):\n n_gram_read[i] = ' '.join(n_gram_read[i])\n \n ## Give user the option to use add-1 counting or not\n ## Setting add_one is False is better for manipulation in\n ## the generator function \n if add_one:\n n_gram_count = Counter(n_gram_read + list(set(n_gram_read)))\n else:\n n_gram_count = Counter(n_gram_read)\n\n return(n_gram_count)\n\n## This function allows users to compute the log probabilities of n-grams\ndef log_prob(n, text): \n\n ## Minor sanity check\n if n <= 0:\n sys.exit(\"invalid n\")\n\n ## read in n_gram for level(n-1) and level(n)\n n_gram_count = n_gram_reader(n, text)\n if(n == 1):\n n_gram_prev = n_gram_count\n else:\n n_gram_prev = n_gram_reader(n - 1, text)\n\n word_type = len(set(text))\n\n ## check for number of total appearance for a n-gram\n ## by looking up what's in the level above\n for key in n_gram_count.keys():\n if n == 1: \n prev = key\n else: \n prev = ' '.join(key.split()[:n-1])\n\n ## compute log probability\n n_gram_count[key] = math.log(n_gram_count[key] / float(n_gram_prev[prev] - 1 + word_type))\n return(n_gram_count)\n\n## This function allows users to print out number of answers in a given order\n\ndef print_top(x, n, order):\n x = sorted(x.items(), key = operator.itemgetter(1), reverse = (order == \"descending\"))\n for i in range(n):\n print(x[i])\n return\n\n## This function generates text randomly by using the n-gram model and add-one smoothing\n\ndef generate(n, text):\n n_gram = n_gram_reader(n, text, False)\n\n ## If n is equal to 1, we don't filter based on ''\n if n == 1:\n sent = ''\n last = []\n\n ## Otherwise, filter for n-grams starting with '' and pick them based on \n ## the count for their appearance randomly\n ## Note: using split allows for easier filtering and token manipulation\n else:\n this_gram = {k:v for k, v in n_gram.items() if k.split()[0] == ''}\n this_gram = (list(repeat(k, v)) for k, v in this_gram.items())\n this_gram = [item for sub in this_gram for item in sub]\n sent = random.choice(this_gram)\n last = sent.split()[1:n]\n\n ## while statement checks for whether '' has been generated and sets\n ## a threshold of 20 words. \n while '' not in last and len(sent.split()) <= 20: \n \n ## this statement filters the phrases that contains 'last' and pick the last word. We then generate\n ## a list in which a word appears however many times it was counted in n_gram. Then we add the vocabulary\n ## in the corpus into this list to complete add-one smoothing\n this_gram = {' '.join(k.split()[n-1:n]):v for k, v in n_gram.items() if k.split()[:n-1] == last or len(k.split()) == 1} ## len(k.split()) == 1 ensures handling of n=1\n this_gram = (list(repeat(k, v)) for k, v in this_gram.items()) \n this_gram = [item for sub in this_gram for item in sub] + list(set(text))\n this_gram = random.choice(this_gram)\n\n ## update 'last' as well as the sentence \n last = last[1:n]\n last.append(this_gram)\n sent = sent + ' ' + this_gram\n\n ## check if threshold is reached or ' is generated'\n if sent.split()[-1] != '':\n sent = sent + ' '\n return(sent)\n\n \n \n \n \n## Question 2.1\n\ntext = open(\"Q1_corpus.txt\", \"r\").read().split()\nprint(\"\\nQuestion 2.1:\")\nprint_top(x = n_gram_reader(2, text), n = 10, order = \"descending\")\n\n## Question 2.2\n\ntext = open(\"Q1_corpus.txt\", \"r\").read().split()\nprint(\"\\nQuestion 2.2:\")\nprint_top(x = log_prob(2, text), n = 10, order = \"descending\")\n\n## Question 2.3\n\nfile = \"moviereview.txt\"\ntext = \"\"\n\n## append sentence symbols in front and at the end of sentences\nfor i in open(file, \"r\").read().splitlines():\n text = text + \" \" + i + \" \"\n\n## lower-casing all the text \ntext = text.lower().split()\nprint(\"\\nQuestion 2.3:\")\nprint_top(x = log_prob(2, text), n = 20, order = \"descending\")\n\n## Question 2.4\n\ntext = open(\"bronte_jane_eyre.txt\", \"r\").read()\n\n## uses nltk sentence tokenizer to tokenize text\nsent_token = nltk.sent_tokenize(text)\ntext = []\n\n## append '' and '' around sentences\n## then use word tokenizer \nfor sent in sent_token:\n sent = nltk.word_tokenize(sent)\n sent.append('')\n sent = [''] + sent\n text.append(sent)\ntext = list(chain(*text))\nprint(\"\\nQuestion 2.4:\")\nfor i in range(5):\n print(\"Generated by \" + str(i + 1) + \"-gram\")\n print(generate(i + 1, text))\n\n\n","sub_path":"HW1/HW1.py","file_name":"HW1.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"123888672","text":"\"\"\"\nНеобходимо сократить дробь, записанную в римской системе счисления. Напомним,\nчто в римской записи используются символы M, D, C, L, X, V и I. Приведем\nтаблицу с примерами перевода римских чисел в арабскую систему:\n\"\"\"\n\n\nclass IncorrectInputValue(Exception):\n def __init__(self, *args, **kwargs):\n Exception.__init__(self, *args, **kwargs)\n self.logger()\n\n def logger(self):\n with open(\"rome_numbers/OUTPUT.txt\", \"w\") as f:\n f.write(\"ERROR\")\n\n\nletterValues = {\n 'M': 1000,\n 'D': 500,\n 'C': 100,\n 'L': 50,\n 'X': 10,\n 'V': 5,\n 'I': 1\n}\n\n\ndef get_values(ch):\n num = letterValues.get(ch.upper(), \"\")\n if not isinstance(num, int):\n raise IncorrectInputValue(\n \"There is no number like that: %s\" % ch)\n else:\n return num\n\n\ndef convert_from_roman(number):\n result = 0\n lastValue = 0\n for ch in number:\n value = get_values(ch)\n if value > lastValue:\n result += value - 2 * lastValue\n else:\n result += value\n lastValue = value\n\n if result > 999:\n raise IncorrectInputValue(\"The number is too big: %d\" % result)\n else:\n return result\n\n\ndef convert_to_roman(num):\n roman = ''\n\n while num > 0:\n for i, r in letterValues.items():\n while num >= r:\n roman += i\n num -= r\n return roman\n\n\ndef find_nod(a, b):\n while a != b:\n if a > b:\n a = a - b\n else:\n b = b - a\n return a\n\n\ndef main():\n with open(\"rome_numbers/INPUT.txt\", 'r') as f:\n line = f.readline()\n if len(line) > 100:\n raise IncorrectInputValue()\n\n first_num, second_num = line.split(\"/\")\n first_num = convert_from_roman(first_num)\n second_num = convert_from_roman(second_num)\n\n nod = find_nod(first_num, second_num)\n\n f_n = convert_to_roman(first_num/nod)\n s_n = convert_to_roman(second_num/nod)\n\n with open(\"rome_numbers/OUTPUT.txt\", 'w') as f:\n if s_n == \"I\":\n f.write(str(f_n))\n else:\n f.write(\"%s/%s\" % (f_n, s_n))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rome_numbers/rome_numbers.py","file_name":"rome_numbers.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"243778867","text":"#!/usr/bin/env python\n\"\"\"\nUse this script to get prediction plots and prediction_statistics.npz \nfor a given trained model.\nThe first is used for debugging and for the paper.\nThe second is used to be able to plot the model's\nprediction score versus catalogue accuracy.\n\"\"\"\n\nprint(\"Setup detectron2 logger\")\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\nprint(\"Import some common detectron2 utilities\")\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer, ColorMode\nfrom detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_test_loader\nfrom detectron2.structures import BoxMode\nfrom detectron2.engine import DefaultPredictor, LOFARTrainer\nfrom detectron2.evaluation import COCOEvaluator, inference_on_dataset, LOFAREvaluator\n\n# import some common libraries\nimport numpy as np\nfrom sys import argv\nfrom cv2 import imread\nimport random\nimport os\nimport pickle\nfrom operator import itemgetter\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom collections import OrderedDict\nfrom astropy.table import Table\nfrom copy import deepcopy\n#from separation import separation\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nfrom shapely.geometry import Polygon\nfrom shapely.ops import cascaded_union\nrandom.seed(5455)\n\nassert len(argv) >= 4, (\"Insert 1) path of configuration file, 2) beginning of file path, 3) full \"\n \"path to model weights 4) optional the seed, when executing this script\")\ncfg = get_cfg()\ncfg.merge_from_file(argv[1])\n\n# Adjust beginning of file paths\nstart_dir = argv[2]\nprint(\"Beginning of paths:\", start_dir)\ncfg.DATASET_PATH = cfg.DATASET_PATH.replace(\"/data/mostertrij\",start_dir)\ncfg.OUTPUT_DIR = cfg.OUTPUT_DIR.replace(\"/data/mostertrij\",start_dir)\n\nif len(argv) == 5:\n cfg.SEED = int(argv[4])\n if cfg.OUTPUT_DIR.endswith('/'):\n cfg.OUTPUT_DIR = cfg.OUTPUT_DIR[:-1] + f'_seed{cfg.SEED}_eva'\n else:\n cfg.OUTPUT_DIR += f'_seed{cfg.SEED}_eva'\n print(\"Training seed is:\", cfg.SEED)\n\ncfg.DATASETS.IMAGE_DIR = cfg.DATASETS.IMAGE_DIR.replace(\"/data/mostertrij\",start_dir)\n\n# Read in path to weights that will be evaluated on its own train/test/val\n# For example: pretrained_model_path = \"/data/mostertrij/tridentnet/output/v3_precomputed_constantLR_withRot_no_box_reg/model_0005999.pth\"\npretrained_model_path = argv[3].replace('/data/mostertrij',start_dir)\n\nprint(f\"Loaded configuration file {argv[1]}\")\nDATASET_PATH= cfg.DATASET_PATH\nprint(f\"Experiment: {cfg.EXPERIMENT_NAME}\")\nprint(f\"Rotation enabled: {cfg.INPUT.ROTATION_ENABLED}\")\nprint(f\"Precomputed bboxes: {cfg.MODEL.PROPOSAL_GENERATOR}\")\nprint(f\"Output path: {cfg.OUTPUT_DIR}\")\nprint(f\"Attempt to load training data from: {DATASET_PATH}\")\nprint(\"Pretrained model path:\", pretrained_model_path)\nos.makedirs(cfg.OUTPUT_DIR,exist_ok=True)\n\n\nprint(\"Load our data\")\n#def get_lofar_dicts(annotation_filepath, n_cutouts=np.inf, rotation=False):\ndef get_lofar_dicts(annotation_filepath):\n with open(annotation_filepath, \"rb\") as f:\n dataset_dicts = pickle.load(f)\n new_data = []\n counter=1\n max_value = np.inf\n if annotation_filepath.endswith('train.pkl'): \n max_value = min(cfg.DATASETS.TRAIN_SIZE,len(dataset_dicts))\n for i in range(len(dataset_dicts)):\n if counter > max_value:\n break\n for ob in dataset_dicts[i]['annotations']:\n ob['bbox_mode'] = BoxMode.XYXY_ABS\n if cfg.MODEL.PROPOSAL_GENERATOR:\n dataset_dicts[i][\"proposal_bbox_mode\"] = BoxMode.XYXY_ABS\n\n if dataset_dicts[i]['file_name'].endswith('_rotated0deg.png'):\n if len(argv) >= 4:\n dataset_dicts[i]['file_name'] = dataset_dicts[i]['file_name'].replace(\"/data2/mostertrij\",start_dir)\n dataset_dicts[i]['file_name'] = dataset_dicts[i]['file_name'].replace(\"/data/mostertrij\",start_dir)\n new_data.append(dataset_dicts[i])\n counter+=1\n\n print('len dataset is:', len(new_data), annotation_filepath)\n return new_data\n\n# Register data inside detectron\n#for d in [\"train\", \"val\", \"test\"]:\nfor d in list(cfg.DATASETS.TEST):\n DatasetCatalog.register(d, \n lambda d=d:\n get_lofar_dicts(os.path.join(\n DATASET_PATH,f\"VIA_json_{d}.pkl\")))\n MetadataCatalog.get(d).set(thing_classes=[\"radio_source\"])\nlofar_metadata = MetadataCatalog.get(\"test\")\n\n# Inference mode\n\n# To implement the LOFAR relevant metrics I changed\n# DefaultTrainer into LOFARTrainer\n# where the latter calls LOFAREvaluator within build_hooks instead of the default evaluator\n# this works for the after the fact test eval\n# for train eval those things are somewhere within a model \n# specifically a model that takes data and retuns a dict of losses\nprint(\"Load model:\", pretrained_model_path)\ncfg.MODEL.WEIGHTS = os.path.join(pretrained_model_path) # path to the model we just trained\ntrainer = LOFARTrainer(cfg) \nos.makedirs(cfg.OUTPUT_DIR, exist_ok=True)\ntrainer.resume_or_load(resume=True)\n\n#for d in [\"train\", \"val\", \"test\"]:\nfor d in list(cfg.DATASETS.TEST):\n print(f\"For {d} set:\")\n print('Load inference loader.')\n inference_loader = build_detection_test_loader(cfg, d)\n print('Load LOFAR evaluator.')\n evaluator = LOFAREvaluator(d, cfg.OUTPUT_DIR, distributed=True, inference_only=False,\n remove_unresolved=cfg.TEST.REMOVE_UNRESOLVED,sigmabox=cfg.SIGMABOX,\n segmentation_dir=f'/data1/mostertrij/data/cache/segmentation_maps_{cfg.TEST.REMOVE_THRESHOLD}',\n save_predictions=True, kafka_to_lgm=False,component_save_name=\"bare_predicted_component_catalogue\")\n print('Start inference on dataset to get evaluation.')\n predictions = inference_on_dataset(trainer.model, inference_loader, evaluator, overwrite=True)\nprint(\"All done.\")\n\n","sub_path":"evaluate_lofar.py","file_name":"evaluate_lofar.py","file_ext":"py","file_size_in_byte":5849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"568873272","text":"def go():\r\n\tversion = 'v0.5'\r\n\r\n\tcontrol_quest_1 = 'НЕТ ДАННЫХ'\r\n\r\n\tdef scan():\r\n\t\tif sys.platform == 'win32':\r\n\t\t\tpass\r\n\t\telse:\r\n\t\t\tprint('ошибка: данная операционная система не поддерживается')\r\n\t\t\tinput('Нажмите Enter')\r\n\t\t\tsys.exit()\r\n\r\n\tdef data_look(connect_local,connect_internet,connect_problem):\r\n\t\tos.system('ver')\r\n\t\tprint('F.R:E.E.PCstat',version)\r\n\t\tprint('')\r\n\t\tprint('ДАННЫЕ О ПОДКЛЮЧЕНИЯХ:')\r\n\t\tprint('Локальная сеть: ',connect_local)\r\n\t\tprint('Internet-сеть: ',connect_internet)\r\n\t\tprint('Проблема: ',connect_problem)\r\n\t\tprint()\r\n\t\tprint('ДАННЫЕ О СИСТЕМЕ:')\r\n\t\tprint('Имя пользователя: ',os.getlogin())\r\n\t\tprint('Системное время: ',time.strftime('%B, %A %d, %X'))\r\n\t\tprint('Файловой система: ',sys.getfilesystemencoding())\r\n\t\tprint('С начала эпохи: ',time.time(),'секунд')\r\n\t\tprint()\r\n\t\tprint('ДАННЫЕ ОБ ОБНОВЛЕНИЯХ:')\r\n\t\tprint('Период: ',firstudate+',',lastudate)\r\n\t\tprint('Обновлений: ',log_updates)\r\n\t\tprint('Сбоев обновлений: ',log_errors)\r\n\t\tinput('Нажмите Enter')\r\n\t\tos.system('cls')\r\n\r\n\ttry:\r\n\t\tconnect_internet = 'НЕТ ДАННЫХ'\r\n\t\tconnect_local = 'НЕТ ДАННЫХ'\r\n\t\tconnect_problem = 'НЕТ ДАННЫХ'\r\n\r\n\t\tprint('Импорт стандартных библиотек...')\r\n\t\tprint('Импорт sys.py...')\r\n\t\timport sys\r\n\t\tprint('Импорт os.py...')\r\n\t\timport os\r\n\t\tprint('Импорт time.py...')\r\n\t\timport time\r\n\t\tprint('Импорт random.py...')\r\n\t\timport random\r\n\t\tprint('Импорт subprocess.py...')\r\n\t\timport subprocess\r\n\t\tprint('Импорт re.py...')\r\n\t\timport re\r\n\r\n\t\tos.chdir(os.getcwd())\r\n\r\n\t\tscan()\r\n\r\n\t\tos.system('cls')\r\n\r\n\t\tprint('Сбор данных о компьютере...')\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\t\t\tsubprocess.check_call([\"ping\",\"192.168.1.1\"])\r\n\t\t\t\tconnect_local = 'Подключено'\r\n\t\t\t\tos.system('cls')\r\n\t\t\t\tprint('Сбор данных о компьютере...')\r\n\t\t\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\t\t\tbreak\r\n\t\t\texcept subprocess.CalledProcessError:\r\n\t\t\t\tconnect_local = 'Не подключено'\r\n\t\t\t\tos.system('cls')\r\n\t\t\t\tprint('Сбор данных о компьютере...')\r\n\t\t\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\t\t\tbreak\r\n\r\n\t\twhile True:\r\n\t\t\ttry:\r\n\t\t\t\tprint(\">>Проверка Интернет-подключения...\")\r\n\t\t\t\tsubprocess.check_call([\"ping\",\"www.google.com\"])\r\n\t\t\t\tconnect_internet = 'Подключено'\r\n\t\t\t\ttime.sleep(0.1)\r\n\t\t\t\tos.system('cls')\r\n\t\t\t\tprint('Сбор данных о компьютере...')\r\n\t\t\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\t\t\tprint('>>Проверка Интернет-подключения...')\r\n\t\t\t\tbreak\r\n\t\t\texcept subprocess.CalledProcessError:\r\n\t\t\t\tconnect_internet = 'Не подключено'\r\n\t\t\t\ttime.sleep(0.1)\r\n\t\t\t\tos.system('cls')\r\n\t\t\t\tprint('Сбор данных о компьютере...')\r\n\t\t\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\t\t\tprint('>>Проверка Интернет-подключения...')\r\n\t\t\t\tbreak\r\n\r\n\t\tlog_errors = 0\r\n\t\tlog_updates = 0\r\n\t\tlinesfirst = 0\r\n\t\tcount_u = 0\r\n\r\n\t\tprogressbar_u = len(open('C:\\\\Windows\\\\WindowsUpdate.log', 'r').readlines())\r\n\t\tprogressbar_u_t = 0\r\n\r\n\t\tf = open('C:\\\\Windows\\\\WindowsUpdate.log') # если не указан режим, по умолчанию подразумевается\r\n\t\t\t\t\t\t\t\t# режим чтения ('r'eading)\r\n\t\tfirstudate = f.read(10)\r\n\r\n\t\twhile True:\r\n\t\t\tline = f.readline()\r\n\t\t\tif len(line) == 0: # Нулевая длина обозначает конец файла (EOF)\r\n\t\t\t\tbreak\r\n\t\t\tobrezline = line[0:55]\r\n\t\t\t#print(obrezline,end='...')\r\n\t\t\tlastudate = line[0:-72]\r\n\t\t\t#print()\r\n\t\t\tcount_u += 1\r\n\t\t\tif count_u == 100:\r\n\t\t\t\tos.system('cls')\r\n\t\t\t\tprint('Сбор данных о компьютере...')\r\n\t\t\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\t\t\tprint('>>Проверка Интернет-подключения...')\r\n\t\t\t\tprint('>>Чтение WindowsUpdate.log...')\r\n\t\t\t\tconproc = procent_bar\r\n\t\t\t\tif conproc == 100:\r\n\t\t\t\t\tconproc = str(procent_bar)\r\n\t\t\t\t\tobrezproc = conproc[0:3]\r\n\t\t\t\telif conproc >= 10:\r\n\t\t\t\t\tconproc = str(procent_bar)\r\n\t\t\t\t\tobrezproc = conproc[0:2]\r\n\t\t\t\telif conproc >= 0:\r\n\t\t\t\t\tconproc = str(procent_bar)\r\n\t\t\t\t\tobrezproc = conproc[0:1]\r\n\t\t\t\tprint('{0} %'.format(obrezproc))\r\n\t\t\t\tcount_u = 0\r\n\t\t\tprogressbar_u_t += 1\r\n\t\t\tprc_b = progressbar_u / progressbar_u_t \r\n\t\t\tprocent_bar = 100 / prc_b\r\n\t\t\tif re.search(r'Failed',line)\\\r\n\t\t\tor re.search(r'failed',line):\r\n\t\t\t\tlog_errors += 1\r\n\t\t\tif re.search(r'Added update',line):\r\n\t\t\t\tlog_updates += 1\r\n\t\tf.close() # закрываем файл\r\n\t\t\r\n\t\tif firstudate == 'Windows Up':\r\n\t\t\tfirstudate = 'НЕТ ДАННЫХ'\r\n\t\tif lastudate == 'For more':\r\n\t\t\tlastudate = 'НЕТ ДАННЫХ'\r\n\t\telse:\r\n\t\t\tif len(firstudate) > 10:\r\n\t\t\t\tfirstudate = firstudate[0:10]\r\n\t\t\tif len(lastudate) > 10:\r\n\t\t\t\tlastudate = lastudate[0:10]\r\n\r\n\t\tos.system('cls')\r\n\t\tprogressbar_u = 0\r\n\t\tprint('Сбор данных о компьютере...')\r\n\t\tprint('>>Проверка подключения к локальной сети...')\r\n\t\tprint('>>Проверка Интернет-подключения...')\r\n\t\tprint('>>Чтение WindowsUpdate.log...')\r\n\t\tprint(\">>Получение имени пользователя...\")\r\n\t\ttime.sleep(0.01)\r\n\t\tprint(\">>Получение системного времени...\")\r\n\t\ttime.sleep(0.01)\r\n\t\tprint(\">>Получение кодировки файловой системы...\")\r\n\t\ttime.sleep(0.01)\r\n\t\tprint(\">>Получение времени с начала эпохи...\")\r\n\t\ttime.sleep(0.01)\r\n\t\tprint(\">>Получение версии Windows...\")\r\n\t\ttime.sleep(0.01)\r\n\r\n\t\t\r\n\r\n\t\t\r\n\r\n\t\tprint('''Внимание! \r\nВы можете записать контрольные ответы в файле \"control_questions.txt\",\r\nчтобы при следующих запусках PCstat вам не приходилось заново отвечать.\r\nОтветы в файле контрольных ответов пишите верхним регистром!''')\r\n\t\tprint()\r\n\r\n\t\tprint('Контрольный вопрос: ваша сеть должна поддерживать доступ к Интернету?')\r\n\t\tprint('Y/N')\r\n\r\n\t\trun = True\r\n\t\twhile run:\r\n\t\t\tf = open('C:\\\\WindOS\\\\PCstat\\\\control_questions.txt') # если не указан режим, по умолчанию подразумевается\r\n\t\t\t# режим чтения ('r'eading)\r\n\t\t\twhile True:\r\n\t\t\t\tline = f.readline()\r\n\t\t\t\tif len(line) == 0: # Нулевая длина обозначает конец файла (EOF)\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif re.search(r'standart_intercon = ',line):\r\n\t\t\t\t\tif re.search(r'Y',line):\r\n\t\t\t\t\t\tcontrol_quest_1 = 'Y'\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tif re.search(r'N',line):\r\n\t\t\t\t\t\tcontrol_quest_1 = 'N'\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\tif control_quest_1 == '?':\r\n\t\t\t\t\t\tbreak\r\n\r\n\t\t\tf.close() # закрываем файл\r\n\r\n\t\t\tif control_quest_1 == 'Y':\r\n\t\t\t\tbreak\r\n\t\t\tif control_quest_1 == 'N':\r\n\t\t\t\tbreak\r\n\r\n\t\t\tcontrol_quest_1 = input('/')\r\n\t\t\tif control_quest_1 == 'Y':\r\n\t\t\t\tbreak\r\n\t\t\tif control_quest_1 == 'y':\r\n\t\t\t\tbreak\r\n\t\t\tif control_quest_1 == 'N':\r\n\t\t\t\tbreak\r\n\t\t\tif control_quest_1 == 'n':\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tprint('Ваш ответ - \"'+control_quest_1+'\", не является одним из вариантов ответа')\r\n\t\t\t\tprint('Пожалуйста, введите один из вариантов ответа')\r\n\r\n\t\tif connect_local == 'Подключено' and connect_internet == 'Не подключено':\r\n\t\t\t\tconnect_problem = 'Предполагается ошибка сети'\r\n\t\tif connect_local == 'Не подключено' and connect_internet == 'Не подключено':\r\n\t\t\tconnect_problem = 'Предполагается намеренное отключение от сети'\r\n\t\tif connect_local == 'Подключено' and connect_internet == 'Подключено':\r\n\t\t\tconnect_problem = 'Проблем не обнаружено'\r\n\t\tif control_quest_1 == 'N':\r\n\t\t\tconnect_internet = 'Не поддерживается'\r\n\t\t\tconnect_problem = 'Проблем не обнаружено'\r\n\t\tif control_quest_1 == 'n':\r\n\t\t\tconnect_internet = 'Не поддерживается'\r\n\t\t\tconnect_problem = 'Проблем не обнаружено'\r\n\t\tif connect_internet == 'Не поддерживается' and connect_local == 'Не подключено':\r\n\t\t\tconnect_problem = 'Предполагается намеренное отключение от сети'\r\n\r\n\t\tos.system('cls')\r\n\r\n\t\tdata_look(connect_local,connect_internet,connect_problem)\r\n\r\n\texcept StopIteration as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('StopIteration: в итераторе больше нет элементов')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept ArithmeticError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('ArithmeticError: арифметическая ошибка')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept AssertionError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('AssertionError: выражение в функции assert ложно')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept AttributeError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('AttributeError: объект не имеет данного атрибута, значения или метода')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept BufferError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('BufferError: операция, связанная с буфером, не можеть быть выполнена')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept EOFError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('EOFError: функция наткнулась на конец файла и не смогла прочитать то, что хотела')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept ImportError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('ImportError: не удалось импортирование модуля или его атрибута')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept LookupError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('LookupError: некорректный индекс или ключ')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept MemoryError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('MemoryError: недостаточно памяти')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept NameError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('NameError: не найденно переменной с таким именем')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept UnboundLocalError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('UnboundLocalError: сделана ссылка на локальную переменную в функции, но переменная не определена ранее')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept OSError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('OSError: системная ошибка')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept ReferenceError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('ReferenceError: попытка доступа к атрибуту со слабой ссылкой')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept RuntimeError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('RuntimeError: неизвестная ошибка')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept NotImplementedError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('NotImplementedError: абстрактные методы класса требуют переопределения в дочерних процессах')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept SyntaxError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('SyntaxError: синтаксическая ошибка')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept IndentationError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('IndentationError: неправильные отступы')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept TabError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('TabError: смешивание в отступах табуляции и пробелов')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept SystemError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('SystemError: внутренняя ошибка')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept TypeError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('TypeError: операция применена к объекту несоответствующего типа')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept ValueError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('ValueError: функция получила объект правильного типа, но некорректного значения')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept UnicodeError as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint('UnicodeError: ошибка кодирования/раскодирования Юникода')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')\r\n\texcept Error as exception:\r\n\t\tprint('ОШИБКА:')\r\n\t\tprint(': ')\r\n\t\tprint(exception)\r\n\t\tinput('Нажмите Enter')","sub_path":"PCstat/terminal.py","file_name":"terminal.py","file_ext":"py","file_size_in_byte":14024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"541006545","text":"from lolapi import LolApi\nfrom lib_config import RIOT_API_KEY\nimport json\n\nclass BsLol():\n def __init__(self):\n self.API_KEY = RIOT_API_KEY\n self.REGION = 'na'\n self.lol = LolApi(self.API_KEY,self.REGION)\n\n def getSummonerId(self,name):\n summonerProfile = self.lol.request('summoner/by-name', str(name))\n if summonerProfile == None:\n return None\n summonerId = summonerProfile['id']\n \n\n #print 'name:', name, 'id:', summonerId\n return summonerId\n\n def getLastgame(self,summonerId):\n gameData = self.lol.request('game',str(summonerId))\n gameDate = 0\n\n # error handling\n if gameData == None:\n return None\n\n # SUMMARY:\n # We add 10 games 'create date' and keep it as our score..\n #print 'processing ' + str(len(gameData['games'])) + ' games...'\n for a in range(len(gameData['games'])):\n gameDate += gameData['games'][a]['createDate']\n return gameDate\n \n def getRecentGameStats(self,summonerId):\n recentStats = None\n recentGameStats = self.lol.request('game',str(summonerId))['games']\n \n # error checks.. \n if recentGameStats == None:\n return None\n \n # get most recent game\n for gameStats in recentGameStats:\n if recentStats == None:\n recentStats = gameStats\n continue\n if recentStats['createDate'] < gameStats['createDate']:\n recentStats = gameStats\n \n return recentStats\n\nif __name__ == '__main__':\n l = BsLol()\n #print l.getGameDate(l.getSummonerId('soulwingz'))\n #print l.getSummonerId('soulwingzw')\n","sub_path":"lib/bslol.py","file_name":"bslol.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"527582214","text":"import pandas as pd\n\nfrom zipline.data.bundles import register\nfrom zipline.data.bundles.csvdir import csvdir_equities\n\n\nstart_session = pd.Timestamp('2009-5-20', tz='utc')\nend_session = pd.Timestamp('2020-5-15', tz='utc')\n\n\nregister(\n 'eod-nifty500',\n csvdir_equities(\n ['daily'],\n 'AI-Alpha/data',\n ),\n calendar_name='XBOM', \n start_session=start_session,\n end_session=end_session\n)\n","sub_path":"scripts/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"297304213","text":"# Full GTM Implementation\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.distance import cdist\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import scale\nfrom sklearn.preprocessing import normalize\nimport scipy.io as sio\n\n\nclass GTM(object):\n def __init__(self, input_data=sp.rand(100, 3), rbf_number=25,\n rbf_width=1, regularization=1, latent_space_size=3600,\n iterations=100):\n \"\"\" Initialization of the GTM procedure\n :param input_data: data to be visualized, where rows are samples and columns are features\n :param rbf_number: number of radial basis functions\n :param rbf_width: width of radial basis functions\n :param regularization: regularization parameter for maximum likelihood optimization\n :param latent_space_size: size of the grid, considering the total number of grid points\n :param iterations: number of cycle used for maximum likelihood training\n \"\"\"\n self.input_data = input_data\n self.rbf_number = rbf_number\n self.rbf_width = rbf_width\n self.regularization = regularization\n self.latent_space_size = latent_space_size\n self.iterations = iterations\n self.z = None\n self.fi = None\n self.gtm_distance = np.zeros((self.latent_space_size, self.input_data.shape[0]))\n self.gtm_responsibility = np.zeros((self.latent_space_size, self.input_data.shape[0]))\n self.centered_input_data = scale(self.input_data)\n self.input_reconstructed = np.zeros((self.latent_space_size, self.input_data.shape[1], iterations))\n\n @staticmethod\n def gtm_rectangular(dimension):\n \"\"\" Generation of a rectangular lattice for GTM 2D latent space\n :param dimension: size of each 1D latent coordinates\n :return: rectangular lattice: Latent 2D lattice\n \"\"\"\n [x, y] = np.meshgrid(np.linspace(0, 1, dimension), np.linspace(1, 0, dimension))\n x = np.ravel(x)\n x = 2 * x - max(x)\n y = np.ravel(y)\n y = 2 * y - max(y)\n rectangular_lattice = np.array([x, y])\n return rectangular_lattice\n\n def gtm_gaussian_basis_functions(self, mu, sigma):\n \"\"\" Calculation of the Gaussian basis functions for a given input set\n :param mu: centers of basis functions\n :param sigma: standard deviation of the radii-symmetric Gaussian basis functions\n :return: basis_functions_matrix: matrix of basis functions output values\n \"\"\"\n distance = cdist(np.transpose(self.z), np.transpose(mu), 'sqeuclidean')\n basis_functions_matrix = np.exp((-1 / (2 * sigma ** 2)) * distance)\n basis_functions_matrix = np.concatenate((basis_functions_matrix, np.ones((self.z.shape[1], 1))), 1)\n return basis_functions_matrix\n\n def gtm_pc_initialization(self):\n \"\"\" Calculation of weight matrix using principal components\n :return: w: Initialized weight matrix\n :return: beta: Initial scalar value of the inverse variance common to all components of the mixture\n \"\"\"\n # Calculation of principal components and their explained variance\n pca = PCA()\n pca.fit(self.centered_input_data)\n # Eigenvectors scaled by their respective eigenvalues\n [eigenvalues, eigenvector] = np.linalg.eig(pca.get_covariance())\n idx = np.argsort(eigenvalues)[::-1]\n eigenvalues = eigenvalues[idx]\n eigenvector = eigenvector[:, idx]\n eigenvector_scaled = np.dot(eigenvector[:, 0:self.z.shape[0]], np.diag(np.sqrt(eigenvalues\n [0:self.z.shape[0]])))\n # Normalized latent distribution and weight matrix initialization\n z_norm = np.dot(np.diag(1/np.std(self.z, axis=1)), self.z - np.dot(np.diag(np.mean(self.z, axis=1)),\n np.ones(self.z.shape)))\n # eigenvector_scaled[:, 1] = - eigenvector_scaled[:, 1]\n lhs = self.fi\n rhs = np.dot(np.transpose(z_norm), np.transpose(eigenvector_scaled))\n w = np.linalg.lstsq(lhs, rhs)[0]\n w[-1, :] = np.mean(self.centered_input_data, 0)\n rhs2 = np.linalg.pinv(rhs)\n w2 = np.dot(np.transpose(lhs), np.transpose(np.linalg.pinv(rhs)))\n\n # Beta initialization\n beta_matrix = np.dot(self.fi, w)\n inter_distance = cdist(beta_matrix, beta_matrix, 'sqeuclidean')\n np.fill_diagonal(inter_distance, np.inf)\n mean_nearest_neighbor = np.mean(np.min(inter_distance))\n beta = 2 / mean_nearest_neighbor\n if self.z.shape[0] < self.input_data.shape[1]:\n beta = min(beta, 1 / pca.explained_variance_[self.z.shape[0]])\n return w, beta\n\n def gtm_initialization(self):\n \"\"\" Generation of GTM components used with a 2D latent space\n :return: w: Initialized weight matrix\n :return: beta: Initial scalar value of the inverse variance common to all components of the mixture\n \"\"\"\n # Create GTM latent space grid vectors\n latent_space_dimension = np.sqrt(self.latent_space_size)\n self.z = self.gtm_rectangular(latent_space_dimension)\n self.z = self.z[::-1, ::-1]\n # Create GTM latent rbf grid vectors\n rbf_dimension = np.sqrt(self.rbf_number)\n mu = self.gtm_rectangular(rbf_dimension)\n mu = mu * rbf_dimension / (rbf_dimension - 1)\n mu = mu[::-1, ::-1]\n # Calculate the spread of the basis functions\n sigma = self.rbf_width * np.abs(mu[1, 0] - mu[1, 1])\n # Calculate the activations of the hidden unit when fed the latent variable samples\n self.fi = self.gtm_gaussian_basis_functions(mu, sigma)\n # Generate an initial set of weights [W, beta]\n w, beta = self.gtm_pc_initialization()\n return w, beta\n\n def gtm_responsibilities(self, beta):\n \"\"\" Log likelihood calculation and component responsibilities over a Gaussian mixture\n :param beta: scalar value of the inverse variance common to all components of the mixture\n :return: log_likelihood: log likelihood of data under a gaussian mixture\n \"\"\"\n\n dist_corr = np.minimum((self.gtm_distance.max(axis=0) + self.gtm_distance.min(axis=0))/2,\n self.gtm_distance.min(axis=0)+(700*2/beta))\n for i in range(0, self.gtm_distance.shape[1]):\n self.gtm_distance[:, i] = self.gtm_distance[:, i] - dist_corr[i]\n self.gtm_responsibility = np.exp((-beta / 2) * self.gtm_distance)\n responsibility_sum = np.sum(self.gtm_responsibility, 0)\n self.gtm_responsibility = self.gtm_responsibility / np.transpose(responsibility_sum[:, None])\n log_likelihood = np.sum(np.log(responsibility_sum) + dist_corr * (-beta/2)) + self.gtm_distance.shape[1] * \\\n ((self.input_data.shape[1] / 2.) * np.log(beta / (2 * np.pi)) - np.log(self.gtm_distance.shape[0]))\n return log_likelihood\n\n def gtm_training(self):\n \"\"\" Training of the map by updating w and beta over distinct cycles\n :return: w: optimal weight matrix\n :return: beta: optimal scalar value of the inverse variance common to all components of the mixture\n :return: log_likelihood_evol: all log likelihood values for each cycle\n \"\"\"\n [w, beta] = self.gtm_initialization()\n # Calculate Initial Distances\n self.gtm_distance = cdist(np.dot(self.fi, w), self.centered_input_data, 'sqeuclidean')\n # Training loop\n log_likelihood_evol = np.zeros((self.iterations, 1))\n for i in range(0, self.iterations):\n # Update log likelihood and responsibilities\n log_likelihood = self.gtm_responsibilities(beta)\n log_likelihood_evol[i] = log_likelihood\n # Printing diagnostic info\n print(\"Cycle: %d\\t log likelihood: %f\\t Beta: %f\\n \" % (i, float(log_likelihood), beta))\n # Calculate matrix to be inverted\n lbda = self.regularization * np.eye(self.fi.shape[1], self.fi.shape[1])\n intermediate_matrix = np.dot(np.transpose(self.fi), np.diag(np.sum(self.gtm_responsibility, 1)))\n maximization_matrix = np.dot(intermediate_matrix, self.fi) + lbda / beta\n inv_maximization_matrix = np.linalg.pinv(maximization_matrix)\n w = np.dot(inv_maximization_matrix, np.dot(np.transpose(self.fi), np.dot(self.gtm_responsibility,\n self.centered_input_data)))\n self.gtm_distance = cdist(np.dot(self.fi, w), self.centered_input_data, 'sqeuclidean')\n input_data_size = self.input_data.shape[0] * self.input_data.shape[1]\n beta = input_data_size / np.sum(self.gtm_distance * self.gtm_responsibility)\n self.input_reconstructed[:, :, i] = np.dot(self.fi, w)\n return w, beta, log_likelihood_evol\n\n def gtm_mean(self, w, beta):\n \"\"\" Find mean probability density values for each sample in the latent space\n :param w: optimal weight matrix\n :param beta: optimal scalar value of the inverse variance common to all components of the mixture\n \"\"\"\n self.gtm_distance = cdist(np.dot(self.fi, w), self.centered_input_data, 'sqeuclidean')\n self.gtm_responsibilities(beta)\n means = np.dot(np.transpose(self.gtm_responsibility), np.transpose(self.z))\n return means\n\n def gtm_mode(self, w):\n \"\"\" Find mode probability density values for each sample in the latent space\n :param w: optimal weight matrix\n \"\"\"\n self.gtm_distance = cdist(np.dot(self.fi, w), self.centered_input_data, 'sqeuclidean')\n min_idx = np.argmin(self.gtm_distance, 0)\n modes = np.transpose(self.z)[min_idx, :]\n return modes\n\n def gtm_pdf(self):\n \"\"\" Plot GTM's probability distribution in the form of a heat map for each sample in the latent space \"\"\"\n lat_dim = np.sqrt(self.latent_space_size)\n plt.pcolor(np.reshape(self.z[0, :], (lat_dim, lat_dim)), np.reshape(self.z[1, :], (lat_dim, lat_dim)),\n np.reshape(np.sum(self.gtm_responsibility, 1), (lat_dim, lat_dim)), cmap='magma', vmin=0, vmax=1)\n plt.colorbar()\n\n def similarity_matrix(self):\n \"\"\" Calculate the similarity matrix given all samples used for GTM map training\n :return: similarity_matrix: Matrix assessing the similarity between samples used for GTM map training\n \"\"\"\n print(\"Calculating similarity matrix...\")\n # Find one tenth of the highest and lowest probability distribution values for each sample in the latent space\n sim_size = int(round(self.latent_space_size/10))\n responsibility_indexes = np.zeros((sim_size * 2, self.input_data.shape[0]))\n corr_input = np.zeros((sim_size * 2, self.input_data.shape[0]))\n for i in range(0, self.input_data.shape[0]):\n responsibility_indexes[0:sim_size, i] = np.argpartition(self.gtm_responsibility[:, i],\n -sim_size)[-sim_size:]\n responsibility_indexes[sim_size:, i] = np.argpartition(self.gtm_responsibility[:, i], sim_size)[0:sim_size]\n responsibility_indexes = responsibility_indexes.astype(int)\n # Create correlation input matrix for similarity assessment\n for i in range(0, self.input_data.shape[0]):\n corr_input[:, i] = self.gtm_responsibility[responsibility_indexes[:, i], i]\n # Calculate correlation between all samples and build similarity matrix\n similarity_matrix = np.corrcoef(np.transpose(corr_input))\n # Plot heat map of the similarity matrix accordingly\n [x, y] = np.meshgrid(np.linspace(1, self.input_data.shape[0], self.input_data.shape[0]),\n np.linspace(1, self.input_data.shape[0], self.input_data.shape[0]))\n x = np.ravel(x)\n y = np.ravel(y)\n sim_lat = np.array([x, y])\n print(\"Plotting color mesh image...\")\n plt.pcolormesh(np.reshape(sim_lat[0, :], (self.input_data.shape[0], self.input_data.shape[0])),\n np.reshape(sim_lat[1, :], (self.input_data.shape[0], self.input_data.shape[0])), similarity_matrix,\n cmap='magma', vmin=0, vmax=1)\n plt.colorbar()\n plt.axis([x.min(), x.max(), y.min(), y.max()])\n plt.gca().invert_yaxis()\n return similarity_matrix\n","sub_path":"GTM/GTM.py","file_name":"GTM.py","file_ext":"py","file_size_in_byte":12578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"227979256","text":"message = 'April is the cruellest month, breeding Lilacs out of the ' \\\n 'dead land,exit mixing Memory and desire, stirring Dull roots ' \\\n 'with spring rain.'\n\ncount = {}\nfor character in message:\n count.setdefault(character,0)\n count[character] = count[character] + 1\n\nprint(count)","sub_path":"ch5/countchars.py","file_name":"countchars.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"495656439","text":"\n# coding: utf-8\n\n# In[18]:\n\n#get_ipython().magic('matplotlib inline')\n\nimport datetime\nimport time\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as dts\nfrom sklearn import linear_model as lm\n\n\n# In[21]:\nf = open(\"data_compteurgeneral_second_2015_09.csv\", \"r\")\n\nheaders = open(\"Headers_CompteurGeneral.txt\", \"w\")\nfor row in csv.reader(f):\n for i in range(0, len(row)):\n headers.write(row[i] + '\\n')\n break\nheaders.close()\n\ntime = []; gen = []; use = []; pp1 = []; pp2 = []; pp3 = []; ip1 = []; ip2 = []; ip3 = []; mcb = []\ntotal = [time, gen, use, pp1, pp2, pp3, ip1, ip2, ip3, mcb]\n\nfor row in csv.reader(f):\n n = len(total[0])\n time.insert(n,datetime.datetime.strptime(row[0], \"%Y-%m-%d %H:%M:%S\"))\n for i in range(1, len(total)):\n total[i].insert(n,row[i]);\n \n#print((time[0]))\n#print(type(time[0]))\n\n\n# In[5]:\n'''\nplt.scatter(gen,pp1)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Power Phase1 [kW]\")\nplt.title('Generation (kW) and Power Phase 1 (kW)')\nplt.show()\n#plt.savefig('Generation and Power Phase 1, September 2015.png')\n\nplt.scatter(gen,pp2)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Power Phase2 [kW]\")\nplt.title('Generation (kW) and Power Phase 2 (kW)')\nplt.show()\n#plt.savefig('Generation and Power Phase 2, September 2015.png')\n\nplt.scatter(gen,pp3)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Power Phase3 [kW]\")\nplt.title('Generation (kW) and Power Phase 3 (kW)')\nplt.show()\n#plt.savefig('Generation and Power Phase 3, September 2015.png')\n\nplt.scatter(gen,ip1)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Intensity Phase1 [A]\")\nplt.title('Generation (kW) and Intensity Phase 1 (A)')\nplt.show()\n#plt.savefig('Generation and Intensity Phase 1, September 2015.png')\n\nplt.scatter(gen,ip2)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Intensity Phase2 [A]\")\nplt.title('Generation (kW) and Intensity Phase 2 (A)')\nplt.show()\n#plt.savefig('Generation and Intensity Phase 2, September 2015.png')\n\nplt.scatter(gen,ip3)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Intensity Phase3 [A]\")\nplt.title('Generation (kW) and Intensity Phase 3 (A)')\nplt.show()\n#plt.savefig('Generation and Intensity Phase 3, September 2015.png')\n\nplt.scatter(gen,mcb)\nplt.xlabel(\"Generation [kW]\")\nplt.ylabel(\"Main Circuit Breaker [kW]\")\nplt.title('Generation (kW) and Main Circuit Breaker [kW]')\nplt.show()\n#plt.savefig('Generation and Main Circuit Breaker, September 2015.png')\n'''\n\n# In[22]:\n\ntime_plot = dts.date2num(time)\nplt.plot(time_plot, gen)\nplt.show()\n\n'''\nplt.plot(gen)\nplt.title('Generation (kW)')\nplt.show()\n#plt.savefig('Generation (kW), September 2015.png')\n\nplt.plot(pp3)\nplt.title('Power Phase 3 (kW)')\n#plt.show()\nplt.savefig('Power Phase 3 (kW), September 2015.png')\n\nplt.plot(ip1)\nplt.title('Intensity Phase 1 (A)')\n#plt.show()\nplt.savefig('Intensity Phase 1 (A), September 2015.png')\n\nplt.plot(mcb)\nplt.title('Main Circuit Breaker (kW)')\n#plt.show()\nplt.savefig('Main Circuit Breaker (kW), September 2015.png')\n'''\n\n\n# In[35]:\n\nsize = len(pp1)\nX_training = np.array(pp1[:-int(size/10)]).astype(np.float)\nX_training = np.reshape(X_training,(len(X_training),1))\n\nY_training = np.array(gen[:-int(size/10)]).astype(np.float)\nY_training = np.reshape(Y_training,(len(Y_training),1))\n\nX_test = np.array(pp1[-int(size/10):]).astype(np.float)\nX_test = np.reshape(X_test,(len(X_test),1))\n\nY_test = np.array(gen[-int(size/10):]).astype(np.float)\nY_test = np.reshape(Y_test,(len(Y_test),1))\n\nregr = lm.LinearRegression() #classifier\nregr.fit(X_training,Y_training)\n\n#USING SAME TRAINING SET AS TEST SET\n\n# The coefficients\nprint('Coefficients: \\n', regr.coef_)\n# The mean square error\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((regr.predict(X_test) - Y_test) ** 2))\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % regr.score(X_test, Y_test))\n\n# Plot outputs\nplt.scatter(X_test, Y_test, color='black')\nplt.plot(X_test, regr.predict(X_test), color='blue',\n linewidth=2)\nplt.ylabel(\"Generation [kW]\")\nplt.xlabel(\"Power Phase 1 [kW]\")\nplt.title(\"Predictor of Generation wrt P.P.1 (Linear Regression)\")\n\nplt.show()\n#plt.savefig('Generation and Irradiance in a day with Linear Regression.png')\n\n\n# In[4]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"Oct 3 (compteurgeneral 2015 09).py","file_name":"Oct 3 (compteurgeneral 2015 09).py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"468799329","text":"#!/usr/bin/env python\n\nimport sys\nimport paktools\n\n'''Merge (update/refill) PO from POT file (e.g. OneSky App removes untranslated msgids)'''\n\ndef main():\n if len(sys.argv) <= 1:\n print(\"Usage: {0} [translatedPO] [en-US.POT] [outputPO]\".format(sys.argv[0]))\n return\n \n translatedPo = sys.argv[1]\n enPot = sys.argv[2]\n outPo = sys.argv[3]\n \n paktools.MergePO(translatedPo, enPot, outPo)\n\nif __name__ == '__main__':\n main()\n","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"509408710","text":"\"\"\"Functions for genre inference using the tensorflow model, and recommendation inference using the KNN model.\"\"\"\n\nimport tensorflow as tf\nimport pandas as pd\nimport joblib\n\nfrom .spotify_functions import get_base_song_vector\n\ngenre_inference_features = ['acousticness', 'danceability', 'duration_ms', 'energy', 'instrumentalness', 'key','liveness', 'loudness', 'mode', 'speechiness', 'tempo', 'time_signature', 'valence']\ngenre_list = ['alternative', 'country', 'dance', 'folk', 'grunge', 'indie', 'jazz', 'metal', 'pop', 'punk', 'rap', 'rock']\ngenre_onehot_labels = ['genre_' + x for x in genre_list]\n\ngenre_NN = tf.keras.models.load_model('genre_NN')\ngenre_NN._make_predict_function()\nscaler = joblib.load('genre_NN_scaler')\n\n\ndef make_genre_vector(song_vector):\n \"\"\"takes a song vector and returns the onehot genre prediction for the song.\"\"\"\n\n feature_vector = song_vector[genre_inference_features].copy().to_numpy()\n\n scaled_vector = scaler.transform(feature_vector.reshape(1,-1))\n\n genre_vector = genre_NN.predict(scaled_vector)\n\n return genre_vector\n\n\ndef get_genre(genre_vector):\n \"\"\"takes a genre vector and returns the appropriate genre as a string.\"\"\"\n vector_list = genre_vector.tolist()[0]\n best_tuple = sorted(zip(vector_list, genre_list), reverse=True)[0]\n best_genre = best_tuple[1]\n return best_genre\n\n\ndef augment_song_vector(song_vector):\n \"\"\"takes a song vector and adds a genre string and onehot genre features.\"\"\"\n\n song_vector_output = song_vector.copy()\n genre_vector = make_genre_vector(song_vector)\n\n song_vector_output['genre'] = get_genre(genre_vector)\n\n genre_dict = dict(zip(genre_onehot_labels,genre_vector.tolist()[0]))\n\n genre_series = pd.Series(genre_dict)\n\n song_vector_output = pd.concat([song_vector_output, genre_series])\n\n return song_vector_output","sub_path":"api/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"616770949","text":"import cv2\nimport numpy as np\n\n\nfaceDetect=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\") #calling the classifier for face detection\n\n#to capture image from webcam\ncam=cv2.VideoCapture(0) #0 is id for webcam\n\n\n#identifier\nid=input(\"Enter user id:\")\n\nsampleNum=0\n\n#now capturing frames one by one and detect the faces and showing in window\n#creating a loop\n\n\nwhile(1):\n\tret,img=cam.read()\n\t#img will be coloured but for classifier we need greyscale image\n\tgray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\t#list for storing the faces\n\tfaces=faceDetect.detectMultiScale(gray,1.3,5) #this will detect all faces in current frame and return the coordinates of frame\n\tfor(x,y,w,h) in faces: #image frames\n\t\tsampleNum=sampleNum+1\n\t\t#after capturing we are writing it in a file\n\n\t\tcv2.imwrite(\"dataSet/User.\"+str(id)+\".\"+str(sampleNum)+\".jpg\",gray[y:y+h,x:x+w])\n\n\t\tcv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\n\n\t\tcv2.waitKey(100) #before continuing next loop,we are giving litle pause\n\n\t#showing image in another window\n\tcv2.imshow(\"Face\",img) #face is name of window\n\n\tcv2.waitKey(1)\n\t \n\tif(sampleNum>20):\t\t\t#taking 20 samples\n\t\tbreak\n\n\ncam.release()\n\ncv2.destroyAllWindows()\n","sub_path":"attendance/dataset_capture.py","file_name":"dataset_capture.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"644325585","text":"import torch\nimport logging\nimport pdb\n\nlogger = logging.getLogger('global')\n\ndef get_rois_target_levels(levels, base_scale, rois):\n \"\"\"\n Assign proposals to different level feature map to roi pooling\n\n Arguments:\n rois (FloatTensor): [R, 5] (batch_ix, x1, y1, x2, y2)\n levels (list of int): [L], levels. e.g.[2, 3, 4, 5, 6]\n base_scale: scale of the minimum level\n \"\"\"\n w = rois[:, 3] - rois[:, 1] + 1\n h = rois[:, 4] - rois[:, 2] + 1\n scale = (w * h)**0.5\n eps = 1e-6\n target_levels = (scale / base_scale + eps).log2().floor()\n target_levels = target_levels.to(dtype=torch.int64)\n min_level, max_level = min(levels), max(levels)\n return torch.clamp(target_levels, min=min_level, max=max_level)\n\n\ndef map_rois_to_level(levels, base_scale, rois, original_inds=False):\n target_lvls = get_rois_target_levels(levels, base_scale, rois)\n rois_by_level, rois_ix_by_level = [], []\n for lvl in levels:\n ix = torch.nonzero(target_lvls == lvl).reshape(-1)\n rois_by_level.append(rois[ix])\n rois_ix_by_level.append(ix)\n map_from_inds = torch.cat(rois_ix_by_level)\n map_back_inds = torch.zeros((rois.shape[0], ), dtype=torch.int64, device=rois.device)\n seq_inds = torch.arange(rois.shape[0], device=rois.device)\n map_back_inds[map_from_inds] = seq_inds\n if original_inds:\n return rois_by_level, map_from_inds\n return rois_by_level, map_back_inds\n\n\ndef get_rois_by_level(levels, base_scale, rois):\n target_lvls = get_rois_target_levels(levels, base_scale, rois)\n rois_by_level, rois_ix_by_level = [], []\n for lvl in levels:\n ix = torch.nonzero(target_lvls == lvl).reshape(-1)\n rois_by_level.append(rois[ix])\n rois_ix_by_level.append(ix)\n return rois_by_level, rois_ix_by_level\n\n\ndef assign_to_levels(levels, base_scale, rois, *args):\n \"\"\"\n Assign args to each level\n\n Arguments:\n rois (FloatTensor): [R, 5] (batch_ix, x1, y1, x2, y2)\n levels (list of int): [L], levels. e.g.[2, 3, 4, 5, 6]\n\n Returns:\n args: args(include rois) of each level\n \"\"\"\n args_foreach_level = []\n rois_foreach_level, rois_ix_foreach_level = get_rois_by_level(levels, base_scale, rois)\n if len(args) == 0:\n return rois_foreach_level\n args_foreach_level = [[arg[ix] for ix in rois_ix_foreach_level] for arg in args]\n return [rois_foreach_level] + args_foreach_level\n\n\ndef test():\n levels = [0, 1, 2, 3]\n base_scale = 56\n rois = torch.FloatTensor([[0, 0, 0, 160, 160], [1, 0, 0, 1080, 1080], [2, 0, 0, 240, 240], [3, 20, 20, 400, 400],\n [4, 4, 6, 80, 80]])\n _rois, recover_inds = map_rois_to_level(levels, base_scale, rois)\n _rois = torch.cat(_rois, dim=0)\n recover_rois = _rois[recover_inds]\n print(rois)\n print('*********')\n print(recover_rois)\n print('*********')\n print(_rois)\n print('*********')\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"unn/models/heads/utils/assigner.py","file_name":"assigner.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"162501179","text":"# Python RPG\n# Alex Galhardo Vieira\n# https://github.com/AlexGalhardo/Python-RPG\n# aleexgvieira@gmail.com\n# https://alexgalhardo.com\n\n# !/usr/bin/python3\n# coding: utf-8 \n\n# ./Python/Monsters/PitsOfInferno_Monsters/Infernalist.py\n\nfrom SuperClass.MagicMonster import MagicMonster\n\nfrom Global.GLOBAL_PITS_OF_INFERNO_VARIABLES import GLOBAL_INFERNALIST_LIFE, \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t GLOBAL_INFERNALIST_NAME, \\\n\t\t\t GLOBAL_INFERNALIST_MAGIC_ATTACK, \\\n\t\t\t GLOBAL_INFERNALIST_EXPERIENCE\n\nclass Infernalist(MagicMonster):\n\n\t'''\n\t-- Herance LivingBeing\n\n\tself.livingBeingtotalLife\n\tself.livingBeingCurrentlyLife\n\tdef setLiveBeingTotalLife( $setLiveBeingTotalLife )\n\tdef getLiveBeingTotalLife():int\n\t'''\n\n\t'''\n\t-- Herance MagicMonster\n\n\tself.magicMonsterSpellDamage = magicMonsterSpellDamage\n\tself.magicMonsterName = magicMonsterName\n\tself.magicMonsterExperienceForKill = magicMonsterExperienceForKill\n\tself.lootGoldCoins = randint(100, 500)\n\t'''\n\n\tdef __init__(self):\n\n\t\t# constructor Magic Monster\n\t\tsuper().__init__( GLOBAL_INFERNALIST_LIFE,\n\t\t\t\t\t\t\tGLOBAL_INFERNALIST_NAME,\n\t\t\t\t\t\t\tGLOBAL_INFERNALIST_MAGIC_ATTACK,\n\t\t\t\t\t\t\tGLOBAL_INFERNALIST_EXPERIENCE )\n","sub_path":"Monsters/Infernalist.py","file_name":"Infernalist.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"355568515","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$',views.Dashboard),\n url(r'census',views.Census),\n url(r'devplan',views.DP_2014_34),\n url(r'swm',views.SWM),\n url(r'water',views.Water),\n url(r'health',views.Health),\n url(r'transport',views.Transport),\n url(r'edu',views.Education),\n url(r'goamap',views.Goadashboards),\n url(r'iit',views.IITBombay),\n url(r'tdsc',views.tdsc),\n\n]","sub_path":"dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"8410357","text":"import json\nimport click\nimport tqdm\n\n@click.command()\n@click.argument('qanta_file')\n@click.argument('out_file')\ndef main(qanta_file: str, out_file: str):\n with open(qanta_file) as f:\n questions = [q for q in json.load(f)['questions'] if q['page'] is not None]\n \n with open(out_file, 'w') as f:\n for q in tqdm.tqdm(questions):\n for sent_id, (start, end) in enumerate(q['tokenizations']):\n sentence = q['text'][start:end]\n f.write(json.dumps({\n 'text': sentence,\n 'qanta_id': q['qanta_id'],\n 'sent_id': sent_id\n }))\n f.write('\\n')\n\n\nif __name__ == '__main__':\n main()","sub_path":"qanta_to_jsonl.py","file_name":"qanta_to_jsonl.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"36680694","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nimport argparse\n\n\nclass UploadWeightsCommand:\n\n def main(self, args):\n\n from aetros import keras_model_utils\n\n import aetros.const\n from aetros.backend import JobBackend\n from aetros.logger import GeneralLogger\n from aetros.Trainer import Trainer\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawTextHelpFormatter, prog=aetros.const.__prog__ + ' upload-weights')\n parser.add_argument('id', nargs='?', help='model name or job id')\n parser.add_argument('--api-key', help=\"Secure key. Alternatively use API_KEY environment varibale.\")\n parser.add_argument('--weights', help=\"Weights path. Per default we try to find it in the ./weights/ folder.\")\n parser.add_argument('--accuracy', help=\"If you specified model name, you should also specify the accuracy this weights got.\")\n parser.add_argument('--latest', action=\"store_true\", help=\"Instead of best epoch we upload latest weights.\")\n\n parsed_args = parser.parse_args(args)\n job_backend = JobBackend(api_key=parsed_args.api_key)\n\n if '/' in parsed_args.id and '@' not in parsed_args.id:\n job_backend.create(parsed_args.id)\n\n job_backend.load(parsed_args.id)\n\n if job_backend.job is None:\n raise Exception(\"Job not found\")\n\n job_model = job_backend.get_job_model()\n\n weights_path = job_model.get_weights_filepath_best()\n\n if parsed_args.weights:\n weights_path = parsed_args.weights\n\n print((\"Validate weights in %s ...\" % (weights_path, )))\n\n keras_model_utils.job_prepare(job_model)\n\n general_logger = GeneralLogger()\n trainer = Trainer(job_backend, general_logger)\n\n job_model.set_input_shape(trainer)\n\n print(\"Loading model ...\")\n model_provider = job_model.get_model_provider()\n model = model_provider.get_model(trainer)\n\n loss = model_provider.get_loss(trainer)\n optimizer = model_provider.get_optimizer(trainer)\n\n print(\"Compiling ...\")\n model_provider.compile(trainer, model, loss, optimizer)\n\n print((\"Validate weights %s ...\" % (weights_path,)))\n job_model.load_weights(model, weights_path)\n print(\"Validated.\")\n\n print(\"Uploading weights to %s of %s ...\" % (job_backend.job_id, job_backend.model_id))\n\n job_backend.upload_weights('best.hdf5', weights_path, float(parsed_args.accuracy) if parsed_args.accuracy else None)\n\n print(\"Done\")\n","sub_path":"aetros/commands/UploadWeightsCommand.py","file_name":"UploadWeightsCommand.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"231199977","text":"#!/usr/bin/env python\n\nfrom __future__ import division\nimport numpy as np\nimport sys\n\ndocstring = \"\"\"\nThis script takes in a table of raw read counts (either taxonomic or functional) and returns the max, min, mean, median, and standard devation for each row (tuple).\n\nThis script assumes that the first column contains labels (eg gene name or organism name) and that all other columns following the first contain numeric values.\n\"\"\"\n\n\nfile = sys.argv[1]\n# data = {}\n\nwith open(file, 'rU') as my_file:\n\tfor line in my_file:\n\t\t# if not line.strip().startswith('#'):\n\t\t# \tid = line.strip().split('\\t')[0]\n\t\t# \tvals = map(float, line.strip().split('\\t')[1:])\n\t\t# \tdata[id] = vals\n\n\t\t# Use \"dictionary comprehension\" to read contents of file into dictionary\n\t\tdata = { \\\n\t\t\tline.strip().split('\\t')[0]: np.array(map(float, line.strip().split('\\t')[1:])) \\\n\t\t\tfor line in my_file \\\n\t\t\tif not line.strip().startswith('#') \\\n\t\t}\n\n# print(data)\nprint(\"#id\\tmax\\tmin\\tmean\\tmedian\\tstd_dev\")\nfor key, value in data.iteritems():\n\tprint('\\t'.join([str(key), str(np.max(value)), str(np.min(value)), str(np.mean(value)), str(np.median(value)), str(np.std(value, ddof=1))]))\n","sub_path":"mean-median-sd-se.py","file_name":"mean-median-sd-se.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"338939434","text":"import numpy as np\nimport PIL\n\nclass NoiseTransform:\n def __init__(self, sigma):\n self.sigma = sigma\n\n def __call__(self, mnist_datapoint):\n img = np.asarray(mnist_datapoint)\n\n img = self.normalize(img)\n img = self.addnoise(img)\n img = self.denormalize(img)\n\n return PIL.Image.fromarray(img)\n\n def normalize(self, arr):\n mx = np.max(arr)\n arr = arr/mx\n return arr - np.mean(arr)\n\n def denormalize(self, arr):\n mx = np.max(arr)\n mn = np.min(arr)\n arr = (arr - mn)/(mx - mn)\n arr = arr * 255\n return np.uint8(arr)\n\n def addnoise(self, arr):\n noise = np.random.randn(arr.shape[0]*arr.shape[1]).reshape(arr.shape)\n noise = self.sigma * noise\n return arr + noise","sub_path":"sgld/sgld/preproc.py","file_name":"preproc.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"643770147","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ..items import PropertywalapunesaleItem\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\nimport re\nfrom datetime import datetime as dt\nfrom dateutil.relativedelta import relativedelta\n\n\nclass PropertyhousesforpunesaleSpider(scrapy.Spider):\n name = \"propertywalaPune\"\n allowed_domains = [\"propertywala.com\"]\n start_urls = [\n 'https://www.propertywala.com/properties/type-residential/for-sale/location-pune_maharashtra?orderby=date',\n 'https://www.propertywala.com/properties/type-residential/for-rent/location-pune_maharashtra?orderby=date',\n ]\n custom_settings = {\n 'DEPTH_LIMIT': 10000,\n 'DOWNLOAD_DELAY': 5\n }\n item = PropertywalapunesaleItem()\n\n def parse(self, response):\n try:\n record = Selector(response)\n data = record.xpath('//li[@class=\"posted\"]')\n txn = ''\n if 'rent' in response.url:\n txn = 'Rent'\n elif 'sale' in response.url:\n txn = 'Sale'\n\n for i in data:\n ids = i.xpath('text()').extract_first().strip().encode('ascii', 'ignore').decode('ascii').replace('ID: ', '').replace(' Posted:', '')\n checkprop = response.xpath('//*[@id=\"' + ids + '\"]/header/h4/a/text()').extract_first().strip()\n if 'Land' in checkprop:\n continue\n try:\n d = response.xpath(\"//*[contains(@id,'\" + ids + \"')]/div/ul/li[3]/span/@title\").extract_first()\n name_lister = response.xpath(\"//*[contains(@id,'\" + ids + \"')]/div/ul/li[3]/span/text()\").extract_first()\n if d is None:\n d = response.xpath(\"//*[contains(@id,'\" + ids + \"')]/div/ul/li[3]/a/@title\").extract_first()\n name_lister = response.xpath(\"//*[contains(@id,'\" + ids + \"')]/div/ul/li[3]/a/text()\").extract_first()\n\n if 'wner' in d.lower():\n d = 'Owner'\n elif 'uilder' in d.lower():\n d = 'Builder'\n elif 'roker' in d.lower():\n d = 'Agent'\n else:\n d = 'Propertywala User'\n\n url = 'https://www.propertywala.com/' + i.xpath('text()').extract_first().strip().encode('ascii', 'ignore').decode('ascii').replace('ID: ', '').replace(' Posted:', '')\n request = Request(url, callback=self.parse1, dont_filter=True)\n request.meta['agent'] = d\n request.meta['name'] = name_lister\n request.meta['data_id'] = ids\n request.meta['txn'] = txn\n yield request\n except Exception as e:\n print(e)\n nextPage = response.xpath('*//a[contains(@title,\"Next Page\")]/@href').extract_first()\n url = 'https://www.propertywala.com' + nextPage\n # print(url)\n # self.doc.add_paragraph(url)\n yield Request(url, callback=self.parse, dont_filter=True)\n\n except Exception as e:\n print(e)\n\n def parse1(self, response):\n self.item['Selling_price'] = '0'\n self.item['Possession'] = '0'\n self.item['Status'] = 'None'\n self.item['carpet_area'] = '0'\n self.item['management_by_landlord'] = 'None'\n self.item['areacode'] = '0'\n self.item['mobile_lister'] = 'None'\n self.item['google_place_id'] = '0'\n self.item['Launch_date'] = '0'\n self.item['age'] = '0'\n self.item['address'] = 'None'\n self.item['price_on_req'] = 'FALSE'\n self.item['Details'] = 'None'\n self.item['Monthly_Rent'] = '0'\n self.item['sublocality'] = 'None'\n self.item['price_per_sqft'] = '0'\n self.item['platform'] = 'Propertywala'\n\n self.item['listing_by'] = response.meta['agent']\n self.item['name_lister'] = response.meta['name']\n self.item['data_id'] = response.meta['data_id']\n self.item['txn_type'] = response.meta['txn']\n self.item['city'] = 'Pune'\n\n self.item['lat'] = response.xpath('//meta[@property=\"og:latitude\"]/@content').extract_first(default='0')\n\n self.item['longt'] = response.xpath('//meta[@property=\"og:longitude\"]/@content').extract_first(default='0')\n\n # self.item['data_id'] = response.url.split('/')[1]\n\n dat = response.xpath('//li[@class=\"noPrint\"]/time/@datetime').extract_first(default='0').split(' ')[0]\n\n self.item['listing_date'] = dt.strptime(dat, '%Y-%m-%d').strftime('%m/%d/%Y')\n\n self.item['updated_date'] = self.item['listing_date']\n\n conf = response.xpath('//h2[@id=\"AutoGeneratedTitle\"]/text()').extract_first()\n\n bed = re.findall('[0-9]', conf)\n if bed:\n self.item['config_type'] = bed[0] + 'BHK'\n if not bed:\n self.item['config_type'] = 'None'\n\n build = build1 = ''\n\n try:\n loc = response.xpath('//div[@id=\"PropertyDetails\"]/section/header/h4/text()').extract_first().strip().split(',')\n self.item['locality'] = loc[len(loc) - 2].strip()\n\n build = response.xpath('//div[@id=\"PropertyDetails\"]/section/header/h3/text()').extract_first().strip()\n build1 = response.xpath('//div[@id=\"PropertyDetails\"]/section/header/h4/text()').extract_first().strip()\n except Exception as e:\n self.item['locality'] = 'None'\n\n address = response.xpath('//div[@id=\"PropertyDetails\"]/section/header/h4/text()').extract_first(default=self.item['city']).strip().split(',')\n self.item['address'] = address\n\n buildname = ''\n\n if 'House' in conf:\n self.item['property_type'] = 'House'\n self.item['Building_name'] = 'None'\n else:\n self.item['property_type'] = 'Apartment'\n buildname = ''\n # response.xpath('//h2[@id=\"AutoGeneratedTitle\"]/text()').extract_first().strip().split(',')[0].split('in ')[1]\n # (response.xpath('//section[@id=\"PropertySummary\"]/header/h4/text()').extract_first().strip()).split(',')[0]\n try:\n try:\n buildname = response.xpath(\".//*[@id='PropertyAttributes']/li[contains(text(),'Society')]/span/a/text()\").extract_first().strip()\n except:\n buildname = response.xpath(\".//*[@id='PropertyAttributes']/li[contains(text(),'Society')]/span/text()\").extract_first()\n except:\n pass\n if buildname == '' or buildname == ' ' or buildname is None:\n buildname = address[0]\n if 'flat no' or 'room no' in buildname:\n buildname = address[1]\n\n if buildname is not None:\n if len(buildname) > 35:\n buildname = 'None'\n else:\n buildname = buildname.strip()\n if self.item['locality'] in buildname:\n buildname = ''.join(re.findall(' in (.*)', build))\n if buildname == '':\n buildname = ''.join(re.findall(' at (.*)', build))\n if buildname == '':\n buildname = ''.join(build1.split(',')[:1]).replace(self.item['locality'], '')\n\n if (self.item['city'] in buildname) or (self.item['locality'] in buildname) or (\n buildname in self.item['locality']):\n buildname = ''.join(build1.split(',')[:2]).replace(self.item['locality'], '')\n if buildname == ' ':\n buildname = 'None'\n\n if 'opp.' in buildname.lower():\n buildname = buildname.lower().split('opp.')[0]\n if 'near ' in buildname.lower():\n buildname = buildname.lower().split('near ')[0]\n if ' at ' in buildname.lower():\n buildname = buildname.lower().split(' at ')[1]\n if ',' in buildname:\n if buildname.split(',')[0] == '' or buildname.split(',')[0] == ' ':\n buildname = buildname.split(',')[1]\n else:\n buildname = buildname.split(',')[0]\n if '.' in buildname:\n buildname.replace('.', '')\n\n re.sub('for rent', '', buildname, flags=re.IGNORECASE)\n re.sub('for sale', '', buildname, flags=re.IGNORECASE)\n re.sub(' in ', '', buildname, flags=re.IGNORECASE)\n re.sub('for boys', '', buildname, flags=re.IGNORECASE)\n re.sub('for girls', '', buildname, flags=re.IGNORECASE)\n re.sub('bhk', '', buildname, flags=re.IGNORECASE)\n re.sub('flat no', '', buildname, flags=re.IGNORECASE)\n re.sub('room no', '', buildname, flags=re.IGNORECASE)\n re.sub(self.item['locality'], '', buildname, flags=re.IGNORECASE)\n re.sub(self.item['city'], '', buildname, flags=re.IGNORECASE)\n\n if buildname == '' or buildname == ' ' or buildname == 'None' or buildname is None:\n self.item['Building_name'] = 'None'\n else:\n self.item['Building_name'] = buildname.strip()\n\n if 'for boy' in [conf.lower(), build.lower(), build1.lower()]:\n self.item['management_by_landlord'] = 'Only for Boys'\n elif 'for girl' in [conf.lower(), build.lower(), build1.lower()]:\n self.item['management_by_landlord'] = 'Only for Girls'\n\n try:\n self.item['areacode'] = re.findall('[0-9]+', address[len(address)-1])[0]\n except:\n self.item['areacode'] = '0'\n\n value = response.xpath('//ul[@id=\"PropertyAttributes\"]/li/span/text()').extract()\n # if ' rent ' in conf:\n # self.item['txn_type'] = 'Rent'\n # if ' sale ' in conf:\n # try:\n # self.item['txn_type'] = [s.split(' ')[0] for s in value if ' Property' in s][0]\n # except:\n # self.item['txn_type'] = 'Sale'\n # if 'ew' in self.item['txn_type']:\n # self.item['txn_type'] = 'Sale'\n\n try:\n price = response.xpath('//div[@id=\"PropertyPrice\"]/text()').extract()[1].strip()\n if ',' in price:\n price = price.replace(',', '')\n if 'ale' in self.item['txn_type']:\n if 'la' in price:\n price = price.split(' la')[0]\n if (not '-' in price):\n self.item['Selling_price'] = str(float(price.split(' ')[0]) * 100000)\n elif '-' in price:\n self.item['Selling_price'] = str(float(price.split('-')[-1]) * 100000)\n elif 'crore' in price:\n price = price.split(' crore')[0]\n if (not '-' in price):\n self.item['Selling_price'] = str(float(price.split(' ')[0]) * 10000000)\n elif '-' in price:\n self.item['Selling_price'] = str(float(price.split('-')[-1]) * 10000000)\n else:\n if '-' in price:\n self.item['Selling_price'] = str(price.split('-')[1])\n else:\n self.item['Selling_price'] = price\n if 'Rent' in self.item['txn_type']:\n if 'la' in price:\n price = price.split(' lakh')[0]\n if (not '-' in price):\n self.item['Monthly_Rent'] = str(float(price.split(' ')[0]) * 100000)\n elif '-' in price:\n self.item['Monthly_Rent'] = str(float(price.split('-')[1]) * 100000)\n elif 'crore' in price:\n price = price.split(' crore')[0]\n if (not '-' in price):\n self.item['Monthly_Rent'] = str(float(price.split(' ')[0]) * 10000000)\n elif '-' in price:\n self.item['Monthly_Rent'] = str(float(price.split('-')[1]) * 10000000)\n else:\n if '-' in price:\n self.item['Monthly_Rent'] = str(price.split('-')[1])\n else:\n self.item['Monthly_Rent'] = price\n except Exception as e:\n print(e)\n try:\n price_square = response.xpath(\"//ul[@id='PropertyAttributes']/li[contains(text(),'Rate')]/span/text()\").extract_first(default='0').replace(',', '')\n self.item['price_per_sqft'] = price_square\n except:\n self.item['price_per_sqft'] = 0\n\n try:\n poss = [pos for pos in value if ('Immediate' in pos) or (('Within' in pos) and ('Year' in pos)) or (\n ('Within' in pos) and ('Month' in pos))][0]\n except:\n poss = 'None'\n\n if 'Immediate' in poss:\n self.item['Possession'] = dt.today().strftime('%m/%d/%Y')\n self.item['Status'] = 'Ready to move'\n if (('Within' in poss) and ('Year' in poss)):\n poss1 = int(poss.replace('Within ', '').split(' Year')[0])\n self.item['Possession'] = (dt.today() + relativedelta(years=poss1)).strftime('%m/%d/%Y')\n self.item['Status'] = 'Under Construction'\n if (('Within' in poss) and ('Month' in poss)):\n poss1 = int(poss.replace('Within ', '').split(' Month')[0])\n self.item['Possession'] = (dt.today() + relativedelta(months=poss1)).strftime('%m/%d/%Y')\n self.item['Status'] = 'Under Construction'\n\n try:\n self.item['Bua_sqft'] = response.xpath('//span[@class=\"areaUnit downArrow\"]/text()').extract_first(default='0').split(' ')[0]\n except:\n self.item['Bua_sqft'] = '0'\n\n if 'esale' in self.item['txn_type']:\n try:\n self.item['age'] = [age for age in value if 'Years' in age][0]\n except:\n self.item['age'] = '0'\n if not self.item['age']:\n self.item['age'] = '0'\n\n # if str(self.item['Building_name']).isdigit():\n # self.item['Building_name'] = 'None'\n\n self.item['scraped_time'] = dt.now().strftime('%m/%d/%Y')\n\n if (((not self.item['Monthly_Rent'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['Building_name'] == 'None') and (not self.item['lat'] == '0')) or ((not self.item['Selling_price'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['Building_name'] == 'None') and (not self.item['lat'] == '0')) or ((not self.item['price_per_sqft'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['Building_name'] == 'None') and (not self.item['lat'] == '0'))):\n self.item['quality4'] = 1\n elif (((not self.item['price_per_sqft'] == '0') and (not self.item['Building_name'] == 'None') and (not self.item['lat'] == '0')) or ((not self.item['Selling_price'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['lat'] == '0')) or ((not self.item['Monthly_Rent'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['lat'] == '0')) or ((not self.item['Selling_price'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['Building_name'] == 'None')) or ((not self.item['Monthly_Rent'] == '0') and (not self.item['Bua_sqft'] == '0') and (not self.item['Building_name'] == 'None'))):\n self.item['quality4'] = 0.5\n else:\n self.item['quality4'] = 0\n if ((not self.item['Building_name'] == 'None') and (not self.item['listing_date'] == '0') and (not self.item['txn_type'] == 'None') and (not self.item['property_type'] == 'None') and ((not self.item['Selling_price'] == '0') or (not self.item['Monthly_Rent'] == '0'))):\n self.item['quality1'] = 1\n else:\n self.item['quality1'] = 0\n\n if (not self.item['Launch_date'] == '0') or (not self.item['Possession'] == '0'):\n self.item['quality2'] = 1\n else:\n self.item['quality2'] = 0\n\n if ((not self.item['mobile_lister'] == 'None') or (not self.item['listing_by'] == 'None') or (\n not self.item['name_lister'] == 'None')):\n self.item['quality3'] = 1\n else:\n self.item['quality3'] = 0\n\n yield self.item\n","sub_path":"pune_scrape/propertywalaPune/propertywalaPune/spiders/propertywalaPune.py","file_name":"propertywalaPune.py","file_ext":"py","file_size_in_byte":16601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"311979409","text":"import quickstart\r\nimport httplib2\r\ncreds = quickstart.get_credentials()\r\nhttp = creds.authorize(httplib2.Http())\r\nservice = quickstart.discovery.build('drive', 'v2', http=http)\r\nmydocs = [\r\n ('RFS_Main', '1Ogy-u7FfAGC2KjajXdrMgauII7bNqvd6t4sbFrQSlTM'),\r\n ('FR_Paypal', '1H86eHCdzlILh-xk7ga3PoxlVs6lL_5_7U5baN28U3eI'),\r\n ('FR_Current', '1P3A5fL0cr02_M7eHN1D_1uQTfd4hVVbqEuw39gN6L84'),\r\n ('FR_Savings', '1lTGP-Uz64N1lQ-zvp3wvuE2chYxFazqC5OSzlvQ-73w'),\r\n ]\r\nfiles = service.files()\r\nfor name, fileId in mydocs:\r\n print(\"Downloading %s...\" % name)\r\n f = files.get(fileId=fileId).execute()\r\n exportLink = f['exportLinks']['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']\r\n header, data = http.request(exportLink)\r\n with open('%s.xlsx' % name, 'wb') as f2:\r\n f2.write(data)\r\n\r\n\r\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"26944017","text":"\n\nfrom xai.brain.wordbase.nouns._hero import _HERO\n\n#calss header\nclass _HEROS(_HERO, ):\n\tdef __init__(self,): \n\t\t_HERO.__init__(self)\n\t\tself.name = \"HEROS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"hero\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_heros.py","file_name":"_heros.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"238432018","text":"from __future__ import print_function\nimport sys\nimport libvirt\n\nconn = libvirt.open('qemu:///system')\nif conn == None:\n print('Failed to open connection to qemu:///system', file=sys.stderr)\n exit(1)\n\nnodeinfo = conn.getInfo()\nnumnodes = nodeinfo[4]\n\nmemlist = conn.getCellsFreeMemory(0, numnodes)\ncell = 0\nfor cellfreemem in memlist:\n print('Node '+str(cell)+': '+str(cellfreemem)+' bytes free memory')\n cell += 1\n\nconn.close()\nexit(0)\n","sub_path":"tfg/prueba/p4.py","file_name":"p4.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"283443229","text":"\"\"\"\nRetrain the YOLO model for your own dataset.\n\"\"\"\n\nimport argparse\nimport numpy as np\nimport keras.backend as K\nfrom keras.layers import Input, Lambda\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nimport sys\nfrom typing import List\n\nfrom yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss\nfrom yolo3.utils import get_random_data\n\nPHASE1_MINIBATCH = 16 #32\nPHASE1_EPOCHS = 20 #50\nPHASE1_INITIAL_EPOCHS = 0\n\nPHASE2_MINIBATCH = 16 #32\nPHASE2_EPOCHS = 40 #100\nPHASE2_INITIAL_EPOCHS = 20 #50\n\n\ndef get_ann(annotation_path: str) -> List[str]:\n with open(annotation_path) as f:\n lines = f.readlines()\n np.random.seed(10101)\n np.random.shuffle(lines)\n np.random.seed(None)\n\n\n return lines\n\n\ndef _main(args: argparse.Namespace):\n # Setup filenames\n train_ann_path = args.train_ann\n valid_ann_path = args.valid_ann\n classes_path = args.classes\n log_dir = args.log_dir\n anchors_path = args.anchors\n weights_path = args.weights\n\n # Load classes & anchors\n class_names = get_classes(classes_path)\n num_classes = len(class_names)\n anchors = get_anchors(anchors_path)\n\n # All images will be resized to this size.\n input_shape = (416,416) # multiple of 32, hw\n\n # Create model with pretrained weights\n is_tiny_version = len(anchors)==6 # default setting\n print('is_tiny_version =', is_tiny_version)\n if is_tiny_version:\n model = create_tiny_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path=weights_path)\n else:\n model = create_model(input_shape, anchors, num_classes,\n freeze_body=2, weights_path=weights_path) # make sure you know what you freeze\n\n # Setup logging & stopping criteria\n logging = TensorBoard(log_dir=log_dir)\n checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',\n monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)\n\n # Load train & validation annotations\n train_lines = get_ann(train_ann_path)\n valid_lines = get_ann(valid_ann_path)\n\n # Downsample train_lines, if requested.\n if args.train_ratio < 100:\n # Take the first x% of train data.\n downsampled_train_cnt = int(len(train_lines) * (args.train_ratio / 100))\n print(f'Use {downsampled_train_cnt} train samples out of {len(train_lines)}')\n train_lines = train_lines[:downsampled_train_cnt]\n\n # Concatenate train & validation lines into a single list. This prevents changing existing\n # code which expects train:valid splits = lines[:num_train], lines[num_train:].\n lines = train_lines + valid_lines\n num_train, num_val = len(train_lines), len(valid_lines)\n del train_lines, valid_lines\n\n # Train with frozen layers first, to get a stable loss.\n # Adjust num epochs to your dataset. This step is enough to obtain a not bad model.\n if True:\n model.compile(optimizer=Adam(lr=1e-3), loss={\n # use custom yolo_loss Lambda layer.\n 'yolo_loss': lambda y_true, y_pred: y_pred})\n\n batch_size = PHASE1_MINIBATCH\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=PHASE1_EPOCHS,\n initial_epoch=PHASE1_INITIAL_EPOCHS,\n callbacks=[logging, checkpoint])\n model.save_weights(log_dir + 'trained_weights_stage_1.h5')\n\n # Unfreeze and continue training, to fine-tune.\n # Train longer if the result is not good.\n if True:\n for i in range(len(model.layers)):\n model.layers[i].trainable = True\n model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change\n print('Unfreeze all of the layers.')\n\n batch_size = PHASE2_MINIBATCH # note that more GPU memory is required after unfreezing the body\n print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))\n model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),\n steps_per_epoch=max(1, num_train//batch_size),\n validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),\n validation_steps=max(1, num_val//batch_size),\n epochs=PHASE2_EPOCHS,\n initial_epoch=PHASE2_INITIAL_EPOCHS,\n callbacks=[logging, checkpoint, reduce_lr, early_stopping])\n model.save_weights(log_dir + 'trained_weights_final.h5')\n\n # Further training if needed.\n\n\ndef get_classes(classes_path):\n '''loads the classes'''\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\ndef get_anchors(anchors_path):\n '''loads the anchors from a file'''\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n\ndef create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,\n weights_path='model_data/yolo_weights.h5'):\n '''create the training model'''\n K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n\n y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \\\n num_anchors//3, num_classes+5)) for l in range(3)]\n\n model_body = yolo_body(image_input, num_anchors//3, num_classes)\n print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body in [1, 2]:\n # Freeze darknet53 body or freeze all but 3 output layers.\n num = (185, len(model_body.layers)-3)[freeze_body-1]\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n\n return model\n\ndef create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,\n weights_path='model_data/tiny_yolo_weights.h5'):\n '''create the training model, for Tiny YOLOv3'''\n K.clear_session() # get a new session\n image_input = Input(shape=(None, None, 3))\n h, w = input_shape\n num_anchors = len(anchors)\n\n y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \\\n num_anchors//2, num_classes+5)) for l in range(2)]\n\n model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes)\n print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))\n\n if load_pretrained:\n model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)\n print('Load weights {}.'.format(weights_path))\n if freeze_body in [1, 2]:\n # Freeze the darknet body or freeze all but 2 output layers.\n num = (20, len(model_body.layers)-2)[freeze_body-1]\n for i in range(num): model_body.layers[i].trainable = False\n print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))\n\n model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',\n arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})(\n [*model_body.output, *y_true])\n model = Model([model_body.input, *y_true], model_loss)\n\n return model\n\ndef data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):\n '''data generator for fit_generator'''\n n = len(annotation_lines)\n i = 0\n while True:\n image_data = []\n box_data = []\n for b in range(batch_size):\n if i==0:\n np.random.shuffle(annotation_lines)\n image, box = get_random_data(annotation_lines[i], input_shape, random=True)\n image_data.append(image)\n box_data.append(box)\n i = (i+1) % n\n image_data = np.array(image_data)\n box_data = np.array(box_data)\n y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)\n yield [image_data, *y_true], np.zeros(batch_size)\n\ndef data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):\n n = len(annotation_lines)\n if n==0 or batch_size<=0: return None\n return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-t', '--train-ann', help='Filename of train annotation', default=None)\n parser.add_argument('-d', '--valid-ann', help='Filename of validation annotation', default=None)\n parser.add_argument('-c', '--classes', help='Filename of classes', default=None)\n parser.add_argument('-l', '--log-dir', help='Directory to store logs', default='./logs')\n parser.add_argument('-a', '--anchors', help='Filename of anchors', default='./model_data/yolo_anchors.txt')\n parser.add_argument('-w', '--weights', help='Filename of .h5 weights', default='./model_data/yolo.h5')\n parser.add_argument('-r', '--train-ratio', help='Percentage of training data to use (1-100)', type=int, default=100)\n args = parser.parse_args()\n\n # Make sure these args are specified\n opts = vars(args)\n for i in ['train_ann', 'valid_ann', 'classes']:\n if opts[i] is None:\n print('Missing', i.upper())\n parser.print_help()\n sys.exit(-1)\n\n if not (0 <= args.train_ratio <= 100):\n print(f'Invalid train_ratio {args.train_ratio}; please specify 0-100.')\n\n # Display essential configurations\n print(f'Use {args.train_ratio}% of train data')\n\n _main(args)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"477506737","text":"import tkinter\nroot = tkinter.Tk()\nroot.minsize(600,400)\nroot.title(\"Neko Will Answer\")\nroot.option_add(\"*font\",[\"MSゴシック\",20])\ncan = tkinter.Canvas(bg=\"white\",width=600,height=400)\ncan.place(x=0,y=0)\nimg = tkinter.PhotoImage(file=\"image/cat2.png\")\ncan.create_image(300,200,image=img)\nqst = tkinter.Label(text=\"僕は何歳だと思う\",bg=\"white\",font=(\"MSゴシック\",20))\nqst.place(x=10,y=10)\nent = tkinter.Entry(width=6,bd=2)\nent.place(x=340, y=90)\nroot.mainloop()","sub_path":"Game/gui14.py","file_name":"gui14.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"122081721","text":"\nimport pandas as pd\n\npath_song = r'C:\\Utkarsh\\Spotify\\end_song_sample.csv'\npath_user = r'C:\\Utkarsh\\Spotify\\user_data_sample.csv'\nsong_df = pd.read_csv(path_song)\nuser_df = pd.read_csv(path_user)\n\n#Sorting two table before merging them\nresult_song = song_df.sort(['user_id'])\nresult_user = user_df.sort(['user_id'])\n\n#Merging two tables and eliminating null values in trackid\nresult = result_song.merge(result_user, on='user_id', how='left')\nresult = result[pd.notnull(result['track_id'])]\n\n# Creating most played minutes column\nresult['ms_played_min'] = result['ms_played']/60000\n\n#Calculating the listening session\nresult = result[result.acct_age_weeks != 0]\nresult['listening_session'] = result['ms_played_min']/result['acct_age_weeks']\n\n#Total listening between genders\ngender_listen = result[['gender','ms_played_min']]\ngender_listen = gender_listen.sort(['gender'])\ngender_listen_grp = gender_listen.groupby(['gender'])\ngender_group = gender_listen_grp.sum()\nprint(gender_group.head())\n\n#Calculating user's listening session per week in minutes\nuser_session = result[['user_id','listening_session']]\nuser_session = user_session.sort(['user_id'])\nuser_session_grp = user_session.groupby(['user_id'])\nuser_group = user_session_grp.sum()\nprint(user_group.head())\n\n#Determining most recently played tracks based on the end_timestamp\nrecent_tracks = result[['track_id','end_timestamp']]\nrecent_tracks = recent_tracks.sort(['end_timestamp'])\nrecent_tracks_grp = recent_tracks.groupby(['end_timestamp']) \nprint(recent_tracks_grp.head())\n\n#Calculating the popular tracks based on nationalities and age groups\npopular_tracks = result[['country','age_range','track_id']]\npopular_tracks = popular_tracks.sort(['country','age_range'])\npopular_tracks = popular_tracks.groupby(['country','age_range','track_id'])\npopular_tracks_grp = popular_tracks['track_id'].count()\nprint(popular_tracks_grp.head())\n\n#Determining the premium and open users based on nationalities and age groups\npremium_open = result[['country','age_range','product']]\npremium_open = premium_open.sort(['country','age_range'])\npremium_open = premium_open.groupby(['country','age_range','product'])\npremium_open_grp = premium_open['product'].count()\nprint(premium_open_grp.head())\n\n#Determine if a correlation exist between listening session and product type\ndef transform(data):#create a function for transformation of the product column\n if (data == 'premium'):\n data = 3\n elif (data == 'basic-desktop'):\n data = 2 \n elif (data == 'free'):\n data = 1\n else:\n data = 0\n return data\n\nuser_session_corr = result[['user_id','product','listening_session']] \nuser_session_corr['product'] = user_session_corr.apply(lambda row: transform(row['product']), axis = 1)\nprint(user_session_corr.corr())\n\n#Calculating the average listenig session and statistics based on demographics such as country and age\ndemograph = result[['country','age_range','ms_played_min','listening_session']]\ndemograph = demograph.sort(['country','age_range'])\ndemograph = demograph.groupby(['country','age_range'])\ndemograph_grp = demograph.mean()\nprint(demograph_grp.head())\nprint(demograph_grp.describe())\n","sub_path":"CustomerAnalysis.py","file_name":"CustomerAnalysis.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"374726881","text":"import pandas as pd\nimport tensorflow as tf\nimport os\nimport datalab.storage as gcs\n\nlabels = ['food','not food']\ndataset = ['VALIDATION', 'TEST', 'TRAIN']\ndata = []\nfor s in dataset:\n path = os.path.join('gs://food_resnet/dataset/',s)\n for l in labels:\n for file_path in tf.gfile.Glob(os.path.join(path, l+'/*')):\n data.append((s, file_path, l))\n\npd_data = pd.DataFrame(data)\ngcs.Bucket('food_resnet').item('dataset/data.csv').write_to(pd_data.to_csv(index=False, header=False),'text/csv')","sub_path":"data_to_csv.py","file_name":"data_to_csv.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"275151483","text":"''' What is a list. '''\n# it is a collection that holds, many objects in one place.\n# the objects can have the same type, or it can also be diffrent.\n\n''' How to declare a list. '''\n# fonction\nlol = list()\n\n# empty brackets\nll = []\n\n# brackets, with elements\n# as you can see, The -lol- list holds many objects of\n# different types.\nlol = [1, \"string\", [12], False, 1.23, (1 + 1j), True]\n\n''' Lenght of a list. '''\n# getting the lenght of the list\n# len(lol) = 7\nlenght = len(lol)\n\n''' Accessing elemnts. '''\n# index = position - 1\n# first element\nout = lol[0]\n\n# second element\nout = lol[1]\n\n# last element\nout = lol[-1]\nout = lol[len(lol) - 1]\n\n# before the last element\nout = lol[-2]\nout = lol[len(lol) - 2]\n\n''' Mutability notion'''\n# adding the refence\ntemp = lol\n\n# adding a new element to temp, that is the same lol\ntemp.append(1997)\n\n''' Slicing elemnts. '''\n# copying the all the list\ntest = lol[:] # method one\ntest = lol[0:] # method two\ntest = lol[:len(lol)] # method three\ntest = lol[0:len(lol)] # method four\n\n# copying the all the list, except the last element\n# return to the [2.1.2-data-types-strings.py] file\ntest = lol[:-1] # method one\ntest = lol[:len(lol) - 1] # method two\n\n# copying the list from, the first element to the third\n# len(lol) = 7\n# i = 0, becasue a have the index 0\n# j = i + 3, j = 0 + 3, j = 3\n# use [0:3]\ntest = lol[0:3] # method one\ntest = lol[:3] # method two\n\n# copying the list from, the third element to the fifth\n# len(lol) = 7\n# i = 2, becasue a have the index 2\n# j = 5, because it is the fifth element\n# use [2:5]\ntest = lol[2:5]\n\n# copying the all the list, but the step is by 2\n# so we'll be taking the index:: 0, 2, 4, 6 <= 6\n# it can be any thing\ntest = lol[::2]\n\n# copying the all the list, but the step is by 3\n# so we'll be taking the index:: 0, 3, 6 <= 6\n# it can be any thing\ntest = lol[::3]\n\n# printing the string in reverse\n# here the step is equal to -1\n# by going in reverse, 9, 8, 7, 6.....1\n# in our our case it is form index 0, to index 6\n# this means taking the following\n# 6, 5, 4, 3, 2, 1, 0 <= 0\ntest = lol[len(lol)::-1]\n\n''' Some functions with the lists'''\n# add a new elements\nlol.append(\"New Element\")\nlol.append(123)\n\n# delete an element\nlol.remove(123)\n\n# get the index of an element\nindex = lol.index()\n\n# indert a new element, at a spesific index\nlol.insert(\"Element\", 3)\n\n# it returns the last element of the list, and delets it\nlast = lol.pop()\n\n# empty the list, delete all the elements\nlol.clear()\n\n''' Extra '''\none = [1, 2, 3]\ntwo = [4, 5, 6]\ntemp = one + two\n\n'''\nPlease consider, veiwing the other functions on your own.\n'''\n","sub_path":"2.3-data-types--lists.py","file_name":"2.3-data-types--lists.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"586920019","text":"import numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport pdb\nimport pickle\nfrom PIL import Image, ImageDraw\nimport os\nimport sys\nimport seaborn as sns\nimport tensorflow as tf\nfrom models import *\nfrom sklearn.metrics import precision_score,recall_score,accuracy_score,f1_score,classification_report,confusion_matrix\n\nCLASIFIER_DIR = \"model_classifier\"\n\nsep_sAng = 0\n\n# x : confusion matrix\ndef sns_heatmap(x,name=\"\"):\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n sns.heatmap(x,annot=True,ax=ax,vmax=250,vmin=0,fmt=\"d\")\n path = \"{}/heatmap_{}.png\".format(dir,name)\n plt.savefig(path)\n\ndef label2class(label):\n start = sep_sAng\n classes = (((label+start)%360)//thre).astype(\"int\")\n return classes\n\ndef onehot2class(onehot):\n classes = np.argmax(onehot,axis=1)\n return classes\n\n# type : 評価指標のタイプ index : positiveとするクラスの番号\ndef calc_score(true,pred,type=\"\",index = 0,ave=None):\n result = []\n for q in pred:\n if type==\"precision\":\n score = precision_score(true,q,average=ave)\n elif type==\"recall\":\n score = recall_score(true,q,average=ave)\n elif type==\"f1-score\":\n score = f1_score(true,q,average=ave)\n elif type==\"accuracy\":\n pdb.set_trace()\n ave = 1\n score = accuracy_score(true,q)\n else:\n print(\"unexpected type\")\n\n if ave is None:\n result.append(score[index])\n else:\n result.append(score)\n\n return np.array(result)\n\nsAng = 300\neAng = 60\n# クラスの幅\nthre = 60\n# クラス数\nclNum = 6\n\ndir = sys.argv[1]\ndatapath = sys.argv[2]\ndatanum = 8\ndata = []\nrecord = []\n# 欠損クラスのリスト\ndrop = [0,5]\n\n# 実写データの読み込み\nrealData = pickle.load(open(\"data\"+os.sep+\"realData4reg.pickle\",\"rb\"))\n\n# Biternion placeholder\n\"\"\"\nx_train = tf.placeholder(tf.float32,shape=[None,50,50,3])\nx_valid = tf.placeholder(tf.float32,shape=[None,50,50,3])\nx_test = tf.placeholder(tf.float32,shape=[None,50,50,3])\ntrain_q_x = buildBiternion(x_train,clNum=clNum,rates=[0.2,0.5],name=\"a_Biternion\",type=\"cls\")\nvalid_q_x = buildBiternion(x_valid,clNum=clNum,reuse=True,isTrain=False,name=\"a_Biternion\",type=\"cls\")\ntest_q_x = buildBiternion(x_test,clNum=clNum,reuse=True,isTrain=False,name=\"a_Biternion\",type=\"cls\")\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess =tf.Session(config=config)\n\n# biternionの読み込み\nsaver_cl = tf.train.Saver()\nckpt = tf.train.get_checkpoint_state(CLASIFIER_DIR)\nif ckpt: # checkpointがある場合\n #last_model = ckpt.all_model_checkpoint_paths[3]\n last_model = ckpt.model_checkpoint_path # 最後に保存したmodelへのパス\n print (\"load \" + last_model)\n\n saver_cl.restore(sess, last_model) # 変数データの読み込み\n print(\"succeed restore model\")\nelse:\n print(\"checkpoints were not found.\")\n\n\nvalid_q_value,test_q_value = sess.run([valid_q_x,test_q_x],feed_dict={x_valid:realData.validate.images,x_test:realData.test.images})\n\nvalid_p = label2class(realData.validate.labels)\nvalid_q = [onehot2class(valid_q_value)]\n\ntest_p = label2class(realData.test.labels)\ntest_q = [onehot2class(test_q_value)]\n#pdb.set_trace()\nval_acc = calc_score(valid_p,valid_q,type=\"accuracy\")\ntest_acc = calc_score(test_p,test_q,type=\"accuracy\")\n\npdb.set_trace()\n\nval_ind = np.argmax(val_acc)\nprint(test_acc[val_ind])\n\"\"\"\n\nm2s=True\n\nif m2s:\n datanum = 12\n\n with open(datapath,\"rb\") as f:\n for _ in range(datanum): \n record.append(pickle.load(f))\n #pdb.set_trace()\n losstype = [\"train_cross_entropy\",\n \"test_cross_entropy\",\n \"train_accuracy\",\n \"train_F1score\",\n \"train_recall\",\n \"train_precision\",\n \"train_confmat\",\n \"test_accuracy\",\n \"test_f1-score\"\n \"test_recall\",\n \"test_precision\",\n \"test_confmat\"]\n\n last = [rec[-1] for rec in record]\n #sns_heatmap(last[11],name=\"m2s_{}_test\".format(dir))\n print(\"test: acc={}, F1={},recall={},precision={}\".format(last[7],last[8],last[9],last[10]))\n sys.exit()\n\n\n\n\nwith open(datapath,\"rb\") as f:\n for _ in range(datanum):\n record.append(pickle.load(f))\n\n\n\npdb.set_trace()\n# 欠損クラスとそれ以外に分ける(欠損クラスは全てdrop[0]に置き換える)\nvalid_q = record[5]\n# 欠損クラスを一つにまとめる\nvalid_q_c = [[drop[0] if (i in drop) else i for i in q] for q in valid_q]\nvalid_p = label2class(realData.validate.labels)\nvalid_p_c = [drop[0] if (i in drop) else i for i in valid_p]\n\ntest_q = record[6]\ntest_q_c = [[drop[0] if (i in drop) else i for i in q] for q in test_q]\ntest_p = label2class(realData.test.labels)\ntest_p_c = [drop[0] if (i in drop) else i for i in test_p]\n\n# cross entropy\ndata.append(np.array(record[0]))\ndata.append(np.array(record[1]))\ndata.append(np.array(record[2]))\n\n# accuracy\ndata.append(calc_score(test_p,test_q,type=\"accuracy\"))\ndata.append(calc_score(valid_p,valid_q,type=\"accuracy\"))\n\n# recall\ndata.append(calc_score(test_p_c,test_q_c,type=\"recall\"))\ndata.append(calc_score(valid_p_c,valid_q_c,type=\"recall\"))\n\n# precision\ndata.append(calc_score(test_p_c,test_q_c,type=\"precision\"))\ndata.append(calc_score(valid_p_c,valid_q_c,type=\"precision\"))\n\n# f1-score\ndata.append(calc_score(test_p_c,test_q_c,type=\"f1-score\"))\ndata.append(calc_score(valid_p_c,valid_q_c,type=\"f1-score\"))\n\n\nlosstype = [\"train_cross_entropy\",\n \"test_cross_entropy\",\n \"valid_cross_entropy\",\n # \"train_accuracy\",\n \"test_accuracy\",\n \"valid_accuracy\",\n # \"train_{}-{}_recall\".format(sAng,eAng),\n \"test_recall\",\n \"valid_recall\",\n # \"train_{}-{}_precision\".format(sAng,eAng),\n \"test_precision\",\n \"valid_precision\",\n # \"train_{}-{}_F1score\".format(sAng,eAng),\n \"test_f1-score\",\n \"valid_f1-score\"]\n\ndata_dict = dict(zip(losstype,data))\n\nfor i,type in enumerate(losstype):\n plt.close()\n d = data[i]\n num = d.shape[0]\n plt.plot(range(num),d)\n plt.xlabel(\"Iteration\")\n plt.ylabel(type)\n if (\"precision\" in type) or (\"recall\" in type) or (\"accuracy\" in type):\n plt.ylim(0,1)\n path = \"{}/{}.png\".format(dir,type)\n plt.savefig(path)\n\ns_ind = 100\n\n# accuracyの高い瞬間\nval_ind = np.argmax(data_dict[\"valid_accuracy\"][s_ind:])+s_ind\ntest_acc = data_dict[\"test_accuracy\"][val_ind]\ntest_rec = data_dict[\"test_recall\"][val_ind]\ntest_prec = data_dict[\"test_precision\"][val_ind]\ntest_f1 = data_dict[\"test_f1-score\"][val_ind]\n\n\n\n# miss_image\n#pdb.set_trace()\n#correct_ind = np.where(test_p==test_q)\n#cor_im = realData.test.images[correct_ind]\n#miss_ind = np.where\n\n\n\n#pdb.set_trace()\n# confusion_matrixの作成\ntest_conf = confusion_matrix(test_p, test_q[val_ind],labels=[i for i in range(clNum)])\nsns_heatmap(test_conf,name=\"test\")\n\nprint(\"#{}[ACC] test acc: {}, recall={}, precision={}, f1={}\".format(\n val_ind,test_acc,test_rec,test_prec,test_f1\n )\n )\n\nval_ind = np.argmax(data_dict[\"valid_f1-score\"][s_ind:])+s_ind\ntest_acc = data_dict[\"test_accuracy\"][val_ind]\ntest_rec = data_dict[\"test_recall\"][val_ind]\ntest_prec = data_dict[\"test_precision\"][val_ind]\ntest_f1 = data_dict[\"test_f1-score\"][val_ind]\n\nprint(\"#{}[F1] test acc: {}, recall={}, precision={}, f1={}\".format(\n val_ind,test_acc,test_rec,test_prec,test_f1\n )\n )\n","sub_path":"plot_classifier_score.py","file_name":"plot_classifier_score.py","file_ext":"py","file_size_in_byte":7427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"547348815","text":"import csv\nfrom datetime import datetime\n\nfrom models import DB\n\n\ndef load_ddl():\n db_client = DB()\n with open('./ddl.sql') as file:\n sql_statements = file.read().split(\"-- -----------------\")\n for sql_statement in sql_statements:\n sql_statement = sql_statement.strip()\n if sql_statement != '':\n db_client.execute_sql(sql_statement)\n db_client.close_connection()\n\n\ndef load_location_details_table():\n db_client = DB()\n # In the first pass create the events\n seller = [1, 2]\n with open('./sampleTickets.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n row_count = 0\n events = ['Live1', 'Live2', 'Live3']\n event_date = [datetime.strptime('28-11-18', '%d-%m-%y').date(),\n datetime.strptime('29-11-18', '%d-%m-%y').date(),\n datetime.strptime('30-11-18', '%d-%m-%y').date()]\n event_ids_set = set()\n event_ids = []\n for row in csv_reader:\n row_count += 1\n if row_count == 1:\n continue\n if row[0] not in event_ids_set:\n event_ids_set.add(row[0])\n event_ids.append(row[0])\n row_count = 0\n for event_id in events:\n db_client.insert_event(event_ids[row_count], events[row_count], event_date[row_count])\n row_count += 1\n # load the location details, and then save the listings\n # currently according to the seed data, location id is set to 1\n with open('sampleTickets.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n row_count = 0\n for row in csv_reader:\n row_count += 1\n if row_count == 1:\n continue\n # Setting the capacity for each row for every section\n id = db_client.insert_location_details(1, row[1], row[4], 50)\n price_in_cents = int(float(row[3]) * 100)\n for i in range(int(row[2])):\n db_client.add_listings(row[0], id, price_in_cents, seller[row_count % 2])\n\n db_client.close_connection()\n\n\nif __name__ == '__main__':\n load_ddl()\n load_location_details_table()\n","sub_path":"load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"199930826","text":"#!/usr/bin/env python3\n\"\"\"Utility for uploading Jekyll site files to an S3 bucket.\"\"\"\n\nimport hashlib\nimport mimetypes\nimport logging\nimport logging.config\nimport os\nimport urllib.request\nimport sys\n\nimport boto3\nimport yaml\n\n\ndef sync_bucket(\n bucket, mime_types, site_root, charset, strip_html, delete_old):\n \"\"\"Synchronize bucket with the contents of site_root.\n Files are uploaded when not present in the bucket. Files are only uploaded\n if file and object ETags don't match. File Content-Type will be guessed by\n file extension using mime_types. File Content-Type charset will be assigned\n to \"text\" subtype files. Files ending with \".html\" will be uploaded without\n extension if strip_html is True. Files in the bucket that do not exist in\n the local directory will be deleted if delete_old is True.\n\n Raise ValueError if a file's Content-Type can't be resolved.\n Raise botocore.exceptions.BotoCoreError if a Boto error occurs.\n Raise botocore.exceptions.ClientError if an S3 error occurs.\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info('Synchronizing bucket \"%s\"...', bucket.name)\n\n object_map = {\n obj.key: obj.e_tag\n for obj in bucket.objects.all()\n } # key -> e_tag\n\n file_paths = list(walk_file_paths(os.walk(site_root)))\n file_map = {\n make_key(site_root, path, strip_html): path\n for path in file_paths\n } # key -> file_path\n\n logger.info(\"Uploading new objects...\")\n file_map_items = sorted(file_map.items(), key=lambda item: item[1]) # path\n for key, file_path in file_map_items:\n with open(file_path, 'rb') as file:\n # upload if the object doesn't exist\n # or if the file ETag doesn't match the object ETag\n object_e_tag = object_map.get(key)\n if object_e_tag is None or calc_e_tag(file) != object_e_tag:\n content_type = guess_content_type(\n file_path, mime_types, charset)\n logger.info(\" + %s -> %s, %s\", file_path, key, content_type)\n file.seek(0) # rewind because calc_e_tag() reads entire file\n bucket.put_object(Key=key, ContentType=content_type, Body=file)\n\n if delete_old:\n logger.info(\"Deleting old objects...\")\n old_keys = object_map.keys() - file_map.keys()\n for key in sorted(old_keys):\n logger.info(\" - %s\", key)\n if old_keys:\n bucket.delete_objects(\n Delete={\n 'Objects': [\n {'Key': key} for key in old_keys\n ]\n })\n\n logger.info(\"Synchronization complete.\")\n\n\ndef walk_file_paths(walk_generator):\n \"\"\"Iterate a walk generator and yield file paths.\"\"\"\n for root, dirs, filenames in walk_generator:\n for filename in filenames:\n yield os.path.join(root, filename)\n\n\ndef make_key(site_root, file_path, strip_html):\n \"\"\"Make a bucket key from file_path relative to site_root.\n If strip_html is True \".html\" suffix will be removed.\n \"\"\"\n rel_path = os.path.relpath(file_path, site_root)\n if strip_html and file_path.endswith('.html'):\n rel_path = rel_path[:-len('.html')]\n return urllib.request.pathname2url(rel_path)\n\n\ndef guess_content_type(file_path, mime_types, charset):\n \"\"\"Guess the content type of a file based on filename.\n Charset will be assigned to a mime subtype of \"text\".\n\n Raise ValueError if the mime type of a file cannot be determined.\n \"\"\"\n content_type, encoding = mime_types.guess_type(file_path)\n if content_type is None:\n raise ValueError('Could not find mime type for \"%s\"' % file_path)\n if content_type.startswith('text/'):\n content_type += '; charset=' + charset\n return content_type\n\n\ndef calc_e_tag(file):\n \"\"\"Calculate an S3 ETag from the contents of a file.\n An S3 ETag is a double quoted MD5 hash of file contents.\n \"\"\"\n hash_md5 = hashlib.md5()\n for chunk in iter(lambda: file.read(4096), b''):\n hash_md5.update(chunk)\n return '\"%s\"' % hash_md5.hexdigest()\n\n\ndef load_config(path):\n \"\"\"Load configuration from a YAML file.\n\n Raise FileNotFoundError if path does not exist.\n Raise yaml.YAMLError if YAML file is invalid.\n Raise ValueError if YAML file does not contain a root object.\n Raise ValueError if YAML file is missing \"bucket\" value.\n \"\"\"\n with open(path, 'r') as yaml_file:\n config = yaml.safe_load(yaml_file)\n validate_config(config)\n return config\n\n\ndef validate_config(config):\n \"\"\"Validate the structure and required keys of a config dict.\n This is intended to raise a user-readable error message if a\n configuration problem exists.\n\n Raise ValueError if config is not a dict.\n Raise ValueError if config is missing \"bucket\" value.\n \"\"\"\n # validate basic structure\n if not isinstance(config, dict):\n raise ValueError(\"Config root must be a dictionary.\")\n # validate required values\n if 'bucket' not in config:\n raise ValueError('Config is missing required \"bucket\" value.')\n\n\ndef main():\n \"\"\"Standalone script entry-point.\"\"\"\n # silence boto unless something _really_ bad happens\n logging.getLogger('botocore').setLevel(logging.CRITICAL)\n logging.getLogger('boto3').setLevel(logging.CRITICAL)\n\n # set up logging for human consumption\n logging.basicConfig(level=logging.INFO, format='%(message)s')\n logger = logging.getLogger(__name__)\n\n try:\n config = load_config('_upload.yml')\n session = boto3.Session(profile_name=config.get('profile'))\n bucket = session.resource('s3').Bucket(config['bucket'])\n mime_types = mimetypes.MimeTypes()\n mime_types.types_map[1].update(config.get('mime_types', {}))\n sync_bucket(\n bucket, mime_types,\n config.get('site_root', '_site'),\n config.get('charset', 'utf-8'),\n config.get('strip_html', False),\n config.get('delete_old', False))\n except Exception as error:\n logger.error(\"Error: %s\", error)\n return 1\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"chanterelle.py","file_name":"chanterelle.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"219394810","text":"import requests\nfrom . import bis\nimport re\n\nbis_utils = bis.Utils()\n\nclass Itis:\n def __init__(self):\n self.description = \"Set of functions for interacting with ITIS Solr API and repackaging results for usability\"\n\n def package_itis_json(self, itisDoc):\n itis_data = {}\n\n if type(itisDoc) is not int:\n # Get rid of parts of the ITIS doc that we don't want/need to cache\n discard_keys = [\"hierarchicalSort\", \"hierarchyTSN\"]\n\n for key in discard_keys:\n itisDoc.pop(key, None)\n\n # Convert date properties to common property names\n itisDoc[\"date_created\"] = itisDoc.pop(\"createDate\")\n itisDoc[\"date_modified\"] = itisDoc.pop(\"updateDate\")\n\n # Parse geographicDivision and jurisdiction into a more useful format\n list_geographicDivision = itisDoc.pop(\"geographicDivision\", None)\n list_jurisdiction = itisDoc.pop(\"jurisdiction\", None)\n\n if list_geographicDivision is not None:\n itisDoc[\"geographicDivision\"] = list()\n for geodiv in list_geographicDivision:\n itisDoc[\"geographicDivision\"].append({\n \"geographic_value\": geodiv.split(\"$\")[1],\n \"update_date\": geodiv.split(\"$\")[2]\n })\n\n if list_jurisdiction is not None:\n itisDoc[\"jurisdiction\"] = list()\n for jur in list_jurisdiction:\n itisDoc[\"jurisdiction\"].append({\n \"jurisdiction_value\": jur.split(\"$\")[1],\n \"origin\": jur.split(\"$\")[2],\n \"update_date\": jur.split(\"$\")[3]\n })\n\n # Parse expert(s) into a more useful format\n list_expert = itisDoc.pop(\"expert\", None)\n\n if list_expert is not None:\n itisDoc[\"expert\"] = list()\n for exp in list_expert:\n itisDoc[\"expert\"].append({\n \"reference_type\": exp.split(\"$\")[1],\n \"expert_id\": exp.split(\"$\")[2],\n \"expert_name\": exp.split(\"$\")[3],\n \"expert_comment\": exp.split(\"$\")[4],\n \"create_date\": exp.split(\"$\")[5],\n \"update_date\": exp.split(\"$\")[6]\n })\n\n # Parse publications(s) into a more useful format\n list_publication = itisDoc.pop(\"publication\", None)\n\n if list_publication is not None:\n itisDoc[\"publication\"] = list()\n for pub in list_publication:\n pub_doc = {\n \"reference_type\": pub.split(\"$\")[1],\n \"reference_id\": pub.split(\"$\")[2],\n \"author\": pub.split(\"$\")[3],\n \"title\": pub.split(\"$\")[5],\n }\n for index, var in enumerate(pub.split(\"$\")[6:]):\n if len(var) > 0:\n pub_doc[f\"other_variable_{index}\"] = var\n itisDoc[\"publication\"].append(pub_doc)\n\n # Parse otherSource into a more useful format\n list_other_source = itisDoc.pop(\"otherSource\", None)\n\n if list_other_source is not None:\n itisDoc[\"otherSource\"] = list()\n for src in list_other_source:\n try:\n itisDoc[\"otherSource\"].append({\n \"reference_type\": src.split(\"$\")[1],\n \"source_id\": src.split(\"$\")[2],\n \"source_type\": src.split(\"$\")[3],\n \"source_name\": src.split(\"$\")[4],\n \"version\": src.split(\"$\")[5],\n \"acquisition_date\": src.split(\"$\")[6],\n \"source_comment\": src.split(\"$\")[7],\n \"create_date\": src.split(\"$\")[8],\n \"update_date\": src.split(\"$\")[9]\n })\n except:\n itisDoc[\"otherSource\"].append({\n \"raw_text\": src\n })\n\n # Parse comment into a more useful format\n list_comment = itisDoc.pop(\"comment\", None)\n\n if list_comment is not None:\n itisDoc[\"comment\"] = list()\n for comment in list_comment:\n try:\n itisDoc[\"comment\"].append({\n \"comment_id\": comment.split(\"$\")[1],\n \"commentator\": comment.split(\"$\")[2],\n \"comment_text\": comment.split(\"$\")[3],\n \"create_date\": comment.split(\"$\")[4],\n \"update_date\": comment.split(\"$\")[5]\n })\n except:\n itisDoc[\"comment\"].append({\n \"raw_text\": comment\n })\n\n # Make a clean structure of the taxonomic hierarchy\n # Make a clean structure of the taxonomic hierarchy\n itisDoc[\"biological_taxonomy\"] = []\n for rank in itisDoc['hierarchySoFarWRanks'][0][itisDoc['hierarchySoFarWRanks'][0].find(':$') + 2:-1].split(\n \"$\"):\n thisRankName = {}\n thisRankName[\"rank\"] = rank.split(\":\")[0]\n thisRankName[\"name\"] = rank.split(\":\")[1]\n itisDoc[\"biological_taxonomy\"].append(thisRankName)\n itisDoc.pop(\"hierarchySoFarWRanks\", None)\n\n # Make a clean, usable list of the hierarchy so far for display or listing\n itisDoc[\"hierarchy\"] = itisDoc[\"hierarchySoFar\"][0].split(\":\")[1][1:-1].split(\"$\")\n itisDoc.pop(\"hierarchySoFar\", None)\n\n # Make a clean structure of common names\n if \"vernacular\" in itisDoc:\n itisDoc[\"commonnames\"] = []\n for commonName in itisDoc['vernacular']:\n thisCommonName = {}\n thisCommonName[\"name\"] = commonName.split('$')[1]\n thisCommonName[\"language\"] = commonName.split('$')[2]\n itisDoc[\"commonnames\"].append(thisCommonName)\n itisDoc.pop(\"vernacular\", None)\n\n # Add the new ITIS doc to the ITIS data structure and return\n itis_data.update(itisDoc)\n\n return itis_data\n\n def get_itis_search_url(self, searchstr, fuzzy=False, validAccepted=True):\n fuzzyLevel = \"~0.8\"\n\n api_stub = \"https://services.itis.gov/?wt=json&rows=10&q=\"\n search_term = \"nameWOInd\"\n searchstr = str(searchstr)\n\n if searchstr.isdigit():\n search_term = \"tsn\"\n else:\n searchstr = '\\%20'.join(re.split(' +', searchstr))\n if searchstr.find(\"var.\") > 0 or searchstr.find(\"ssp.\") > 0 or searchstr.find(\" x \") > 0:\n search_term = \"nameWInd\"\n\n api = f\"{api_stub}{search_term}:{searchstr}\"\n\n if fuzzy:\n api = f\"{api}{fuzzyLevel}\"\n\n if validAccepted:\n api = f\"{api}%20AND%20(usage:accepted%20OR%20usage:valid)\"\n\n return api\n\n def search(self, name_or_tsn, name_source=None):\n itis_result = bis_utils.processing_metadata()\n itis_result[\"processing_metadata\"][\"status\"] = \"failure\"\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Not Matched\"\n itis_result[\"processing_metadata\"][\"details\"] = list()\n\n if name_or_tsn.isdigit():\n search_param = \"TSN\"\n else:\n search_param = \"Scientific Name\"\n\n itis_result[\"parameters\"] = {\n search_param: name_or_tsn\n }\n\n if name_source is not None:\n itis_result[\"parameters\"][\"Name Source\"] = name_source\n\n # Set up the primary search method for an exact match on scientific name\n url_exactMatch = self.get_itis_search_url(name_or_tsn, False, False)\n\n # We have to try the main search queries because the ITIS service does not return an elegant error\n try:\n r_exactMatch = requests.get(url_exactMatch).json()\n except:\n itis_result[\"processing_metadata\"][\"details\"].append({\"Hard Fail Query\": url_exactMatch})\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Hard Fail Query\"\n itis_result[\"processing_metadata\"][\"status\"] = \"error\"\n return itis_result\n\n if r_exactMatch[\"response\"][\"numFound\"] == 0:\n\n itis_result[\"processing_metadata\"][\"details\"].append({\"Exact Match Fail\": url_exactMatch})\n\n # if we didn't get anything with an exact name match, run the sequence using fuzziness level\n url_fuzzyMatch = self.get_itis_search_url(name_or_tsn, True, False)\n\n try:\n r_fuzzyMatch = requests.get(url_fuzzyMatch).json()\n except:\n itis_result[\"processing_metadata\"][\"details\"].append({\"Hard Fail Query\": url_fuzzyMatch})\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Hard Fail Query\"\n itis_result[\"processing_metadata\"][\"status\"] = \"error\"\n return itis_result\n\n if r_fuzzyMatch[\"response\"][\"numFound\"] == 0:\n # If we still get no results then provide the specific detailed result\n itis_result[\"processing_metadata\"][\"details\"].append({\"Fuzzy Match Fail\": url_fuzzyMatch})\n return itis_result\n\n elif r_fuzzyMatch[\"response\"][\"numFound\"] > 0:\n # If we got one or more results with a fuzzy match, we will just use the first result\n itis_result[\"data\"] = []\n\n # We need to check to see if the discovered ITIS record is accepted for use. If not, we need to follow\n # the accepted TSN in that document\n if r_fuzzyMatch[\"response\"][\"docs\"][0][\"usage\"] in [\"invalid\", \"not accepted\"]:\n url_tsnSearch = self.get_itis_search_url(\n r_fuzzyMatch[\"response\"][\"docs\"][0][\"acceptedTSN\"][0], False, False\n )\n r_tsnSearch = requests.get(url_tsnSearch).json()\n itis_result[\"data\"].append(self.package_itis_json(r_tsnSearch[\"response\"][\"docs\"][0]))\n itis_result[\"processing_metadata\"][\"status\"] = \"success\"\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Followed Accepted TSN\"\n itis_result[\"processing_metadata\"][\"details\"].append({\"TSN Search\": url_tsnSearch})\n else:\n itis_result[\"processing_metadata\"][\"status\"] = \"success\"\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Fuzzy Match\"\n\n # Whether or not we needed to follow an accepted TSN, we will also include the ITIS record that was\n # the point of discovery\n itis_result[\"processing_metadata\"][\"details\"].append({\"Fuzzy Match\": url_fuzzyMatch})\n itis_result[\"data\"].append(self.package_itis_json(r_fuzzyMatch[\"response\"][\"docs\"][0]))\n\n elif r_exactMatch[\"response\"][\"numFound\"] == 1:\n # If we found only one record with the exact match query, we treat that as a useful point of discovery\n\n itis_result[\"data\"] = list()\n\n # We need to check to see if the discovered ITIS record is accepted for use. If not, we need to follow\n # the accepted TSN in that document\n if r_exactMatch[\"response\"][\"docs\"][0][\"usage\"] in [\"invalid\", \"not accepted\"]:\n url_tsnSearch = self.get_itis_search_url(\n r_exactMatch[\"response\"][\"docs\"][0][\"acceptedTSN\"][0], False, False\n )\n r_tsnSearch = requests.get(url_tsnSearch).json()\n itis_result[\"data\"].append(self.package_itis_json(r_tsnSearch[\"response\"][\"docs\"][0]))\n itis_result[\"processing_metadata\"][\"status\"] = \"success\"\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Followed Accepted TSN\"\n itis_result[\"processing_metadata\"][\"details\"].append({\"TSN Search\": url_tsnSearch})\n else:\n itis_result[\"processing_metadata\"][\"status\"] = \"success\"\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Exact Match\"\n\n # Whether or not we needed to follow an accepted TSN, we will also include the ITIS record that was the\n # point of discovery\n itis_result[\"processing_metadata\"][\"details\"].append({\"Exact Match\": url_exactMatch})\n itis_result[\"data\"].append(self.package_itis_json(r_exactMatch[\"response\"][\"docs\"][0]))\n\n elif r_exactMatch[\"response\"][\"numFound\"] > 1:\n itis_result[\"processing_metadata\"][\"details\"].append({\"Multi Match\": url_exactMatch})\n itis_result[\"processing_metadata\"][\"details\"].append({\n \"Number Valid Results\": len([i for i in r_exactMatch[\"response\"][\"docs\"]\n if i[\"usage\"] in [\"valid\", \"accepted\"]])\n })\n itis_result[\"data\"] = [self.package_itis_json(i) for i in r_exactMatch[\"response\"][\"docs\"]]\n itis_result[\"processing_metadata\"][\"status\"] = \"success\"\n itis_result[\"processing_metadata\"][\"status_message\"] = \"Found multiple matches\"\n\n return itis_result\n","sub_path":"bispy/itis.py","file_name":"itis.py","file_ext":"py","file_size_in_byte":13577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"640744849","text":"from django.urls import include, path\nfrom rest_framework_nested import routers\n\nfrom apps.inventories.views import (PlaceViewSet,\n InventoryViewSet,\n InventoryItemViewSet,\n default_place)\n\nrouter = routers.SimpleRouter()\n\nrouter.register(r'places', PlaceViewSet) # places/\nrouter.register(r'inventories', InventoryViewSet) # inventories/\n\nplaces_router = routers.NestedSimpleRouter(router, r'places', lookup='place')\nplaces_router.register(r'items', InventoryItemViewSet, basename='items')\n\nurlpatterns = [\n path(\"\", include(router.urls)),\n path(\"\", include(places_router.urls)),\n path('default_place', default_place, name='default-place'),\n]\n","sub_path":"src/apps/inventories/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"578432432","text":"#자, Linear Regression을 시각화 해보자.\n#시각화 할 떄는 matplotlib.pyplot을 사용할꺼야.\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\nX = [1,2,3]\nY = [2,4,6]\n\nW = tf.placeholder(tf.float32)\nb = tf.placeholder(tf.float32)\n\n\nhypothesis = X * W\n\n\ncost = tf.reduce_mean(tf.square(hypothesis - Y))\n\n\n\n\nsess = tf.Session()\n\n#X축\nW_history = []\n#Y축\ncost_history = []\n\n\nfor i in range(-30,50):\n curr_W = i * 0.1\n curr_cost = sess.run(cost, feed_dict = {W: curr_W})\n W_history.append(curr_W)\n cost_history.append(curr_cost)\n\n\nplt.plot(W_history, cost_history)\nplt.show()\n","sub_path":"cost_시각화.py","file_name":"cost_시각화.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"302026427","text":"\"\"\" Recurrent Neural Network.\n\nA Recurrent Neural Network (LSTM) implementation example using TensorFlow library.\nThis example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)\n\nLinks:\n [Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf)\n [MNIST Dataset](http://yann.lecun.com/exdb/mnist/).\n\nAuthor: Aymeric Damien\nProject: https://github.com/aymericdamien/TensorFlow-Examples/\n\"\"\"\n\nfrom __future__ import print_function\nimport os\n\nfrom tensorflow.contrib import rnn\nimport tensorflow as tf\nimport numpy as np\n\nimport sys\nimport rnn_indices\ndata = rnn_indices.read_data_sets()\n\n\nlearning_rate = 0.001\ntraining_steps = 50000\nbatch_size = 128\ndisplay_step = 100\n\n# Network Parameters\nnum_input = 17 # MNIST data input (img shape: 28*28)\ntimesteps = 6 # timesteps\nnum_hidden = 120 # hidden layer num of features\nnum_classes = 9 # MNIST total classes (0-9 digits)\n\nX = tf.placeholder(\"float\", [None, timesteps, num_input], name='X')\nY = tf.placeholder(\"float\", [None, num_classes], name='Y')\n\n# Define weights\nweights = {\n 'out': tf.Variable(tf.random_normal([num_hidden, num_classes]))\n}\nbiases = {\n 'out': tf.constant(0.1, shape=([num_classes, ]))\n}\n\n\ndef RNN(x, weights, biases):\n\n # Prepare data shape to match `rnn` function requirements\n # Current data input shape: (batch_size, timesteps, n_input)\n # Required shape: 'timesteps' tensors list of shape (batch_size, n_input)\n\n # Unstack to get a list of 'timesteps' tensors of shape (batch_size, n_input)\n # x = tf.unstack(x, timesteps, 1)\n # Define a lstm cell with tensorflow\n gru_cell = rnn.GRUCell(num_hidden)\n # init_state = gru_cell.zero_state(dtype=tf.float32)\n # Get lstm cell output\n outputs, states = tf.nn.dynamic_rnn(gru_cell, x, dtype=tf.float32)\n # outputs, states = tf.nn.dynamic_rnn(lstm_cell, x, initial_state=init_state, time_major=False, dtype=tf.float32)\n\n # Linear activation, using rnn inner loop last output\n outputs = tf.unstack(tf.transpose(outputs, [1, 0, 2]))\n results = tf.matmul(outputs[-1], weights['out']) + biases['out']\n return results\n # return tf.matmul(states[1], weights['out']) + biases['out']\n\nlogits = RNN(X, weights, biases)\ntf.add_to_collection('pre_prob', logits)\nprediction = tf.nn.softmax(logits)\ntf.add_to_collection('rnn_pred_label', prediction)\n# Define loss and optimizer\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\ntf.summary.scalar('loss_op', loss_op)\n# train_op = tf.train.RMSPropOptimizer(learning_rate, 0.9).minimize(loss_op)\ntrain_op = tf.train.AdamOptimizer(learning_rate).minimize(loss_op)\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n# train_op = optimizer.minimize(loss_op)\n\n# Evaluate model (with test logits, for dropout to be disabled)\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\ntf.summary.scalar('batch_accuracy', accuracy)\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()\n\n# Start training\n\nsaver = tf.train.Saver(max_to_keep=50)\n\n\nwith tf.Session() as sess:\n best = 0.824\n # Run the initializer\n sess.run(init)\n # saver.restore(sess, \"/home/asdf/Documents/juyan/paper/co_training_code/newcode/model/pretrain_RNN.ckpt\")\n #\n merged = tf.summary.merge_all()\n train_summary_writer = tf.summary.FileWriter(\n '/home/asdf/Documents/juyan/paper/paviau/rnn/model/loss_record', sess.graph)\n # valid_summary_writer = tf.summary.FileWriter(\n # '/home/asdf/Documents/juyan/paper/co_training_code/newcode/valid/rnn_loss_record')\n for step in range(1, training_steps+1):\n batch_x, batch_y = data.train.next_batch(batch_size)\n # Reshape data to get 28 seq of 28 elements\n batch_x = batch_x.reshape((batch_size, timesteps, num_input))\n # Run optimization op (backprop)\n sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})\n if step % display_step == 0 or step == 1:\n # Calculate batch loss and accuracy\n summary, loss, acc = sess.run([merged, loss_op, accuracy], feed_dict={X: batch_x,\n Y: batch_y})\n print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(acc))\n train_summary_writer.add_summary(summary, step)\n #start validation\n if step % 2000 == 0:\n batch_sizeall = data.valid.num_examples\n val_batch_x, val_batch_y = data.valid.next_batch(batch_sizeall)\n val_batch_x = val_batch_x.reshape((val_batch_x.shape[0], timesteps, num_input))\n val_acc = sess.run(accuracy, feed_dict={X: val_batch_x, Y: val_batch_y})\n # valid_summary_writer.add_summary(summary, step)\n print(\"valid accuracy = \" + \"{:.3f}\".format(val_acc))\n if val_acc > best:\n best = val_acc\n print(\"Step \" + str(step))\n filename = ('RNN0509.ckpt')\n filename = os.path.join('/home/asdf/Documents/juyan/paper/paviau/rnn/model/',\n filename)\n saver.save(sess, filename)\n # filename = ('RNN0421'+str(name_index)+'.ckpt')\n # filename = os.path.join('/home/asdf/Documents/juyan/paper/no_kmeans/model'\n # '/'+str(name_index)+'_rnn', filename)\n # saver.save(sess, filename)\n print(\"best valid accuracy = \" + \"{:.3f}\".format(best))\n print(\"Optimization Finished!\")\n\n\n","sub_path":"training code/paviau/rnn/code/recurrent_network.py","file_name":"recurrent_network.py","file_ext":"py","file_size_in_byte":5773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"4405522","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 14 19:05:51 2020\n\n@author: robinvonbargen\n\"\"\"\nimport random\n\nimport TrainingData\nimport NearestNeighbors\nimport UserInterface\n\n\n# ------------------ Help functions for cluster generation ------------------\ndef create_data_cluster(number_of_data_points, x_start, x_end, y_start, y_end, label = \"?\"):\n data_cluster_list = []\n for i in range(number_of_data_points + 1):\n data_point = TrainingData.TrainingData()\n feature_vector = [random.randrange(x_start, x_end), random.randrange(y_start, y_end)]\n data_point.set_feature_vector(feature_vector)\n data_point.set_label(label)\n data_cluster_list.append(data_point)\n return data_cluster_list\n \ndef remove_duplicates(list_of_datapoints):\n stripped_list = []\n [stripped_list.append(data_point) for data_point in list_of_datapoints if not data_point in stripped_list]\n return stripped_list\n\n# ---------------------------------------------------------------------------\n \n\n\ndef main():\n training_data = []\n test_data = []\n \n # Cluster sizes\n cluster_one_size = 6\n cluster_two_size = 15\n cluster_three_size = 12\n \n # Cluster intervals\n cluster_one_interval = [-10, -5, -10, -5]\n cluster_two_interval = [0, 3, -2, 4]\n cluster_three_interval = [2, 6, 8, 10]\n \n # Cluster labels\n cluster_one_label = \"a\"\n cluster_two_label = \"b\"\n cluster_three_label = \"c\"\n \n # Create random clusters\n cluster_one = remove_duplicates(create_data_cluster(\n cluster_one_size,\n cluster_one_interval[0],\n cluster_one_interval[1],\n cluster_one_interval[2],\n cluster_one_interval[3],\n cluster_one_label\n ))\n cluster_two = remove_duplicates(create_data_cluster(\n cluster_two_size,\n cluster_two_interval[0],\n cluster_two_interval[1],\n cluster_two_interval[2],\n cluster_two_interval[3],\n cluster_two_label\n ))\n cluster_three = remove_duplicates(create_data_cluster(\n cluster_three_size,\n cluster_three_interval[0],\n cluster_three_interval[1],\n cluster_three_interval[2],\n cluster_three_interval[3],\n cluster_three_label\n ))\n \n # Add clusters to training data\n training_data = [*cluster_one, *cluster_two, *cluster_three]\n \n # Create test data\n number_of_test_points = 5\n test_data_interval = [\n min(\n [\n cluster_one_interval[0], \n cluster_two_interval[0], \n cluster_three_interval[0]\n ]\n ),\n max(\n [\n cluster_one_interval[1], \n cluster_two_interval[1], \n cluster_three_interval[1]\n ]\n ),\n min(\n [\n cluster_one_interval[2], \n cluster_two_interval[2], \n cluster_three_interval[2]\n ]\n ),\n max(\n [\n cluster_one_interval[3], \n cluster_two_interval[3], \n cluster_three_interval[3]\n ]\n )\n ]\n \n test_data = remove_duplicates(create_data_cluster(\n number_of_test_points,\n test_data_interval[0],\n test_data_interval[1],\n test_data_interval[2],\n test_data_interval[3]\n ))\n \n # Init the kNN - algorithm and classify data\n k = 3\n knn = NearestNeighbors.NearestNeighbors(training_data)\n classified_data = knn.classify_data(test_data, k)\n \n \n # Plot unclassified data\n ui = UserInterface.UserInterface()\n ui.load_training_data(training_data)\n ui.load_test_data(test_data)\n ui.update()\n ui.draw_plot(scale_axis = False)\n \n # Plot classified data\n ui = UserInterface.UserInterface()\n ui.load_training_data(training_data)\n ui.load_test_data(classified_data)\n ui.update()\n ui.draw_plot(scale_axis = False)\n \n \nmain()\n\n","sub_path":"kNN/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"27713900","text":"from config import database, helpers, db_context\nimport datetime\nimport base\nimport threading\nhelpers.extent_model(\n \"HCSSYS_DataDomain\",\n \"base\",\n [[\"dd_code\"]],\n dd_code=(\"text\",True),\n dd_name=(\"text\"),\n access_mode=(\"numeric\"),\n description=(\"text\"),\n created_on=(\"date\"),\n created_by=(\"text\"),\n modified_on=(\"date\"),\n modified_by=(\"text\"),\n detail=(\"list\",False,dict(\n department_code = (\"text\"),\n ))\n )\ndef on_before_insert(data):\n before_process\n\ndef on_before_update(data):\n before_process(data)\n\ndef before_process(data):\n data.update({\n \"detail\": [{\n \"department_code\":x['department_code'],\n } for x in data.get('detail',[])]\n })\n\nhelpers.events(\"HCSSYS_DataDomain\").on_before_insert(on_before_insert).on_before_update(on_before_update)\ndef HCSSYS_DataDomain():\n ret = db_context.collection(\"HCSSYS_DataDomain\")\n return ret","sub_path":"apps/performance/api/models/HCSSYS_DataDomain.py","file_name":"HCSSYS_DataDomain.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"65541946","text":"from sympy import Tuple, S, I, Plane\nfrom sympy.core.relational import Relational\nfrom sympy.logic.boolalg import Boolean\nfrom sympy.matrices.dense import DenseMatrix\nfrom sympy.vector import Vector\nfrom sympy.geometry.entity import GeometryEntity\nfrom spb.series import (\n LineOver1DRangeSeries,\n Parametric2DLineSeries,\n Parametric3DLineSeries,\n SurfaceOver2DRangeSeries,\n ParametricSurfaceSeries,\n ImplicitSeries,\n InteractiveSeries,\n _set_discretization_points,\n Vector2DSeries,\n Vector3DSeries,\n ContourSeries,\n ComplexSeries,\n ComplexInteractiveSeries,\n SliceVector3DSeries,\n GeometrySeries,\n PlaneInteractiveSeries,\n)\nfrom spb.backends.base_backend import Plot\nfrom spb.utils import _unpack_args, _plot_sympify, _check_arguments\nfrom spb.vectors import _split_vector\n\n\"\"\"\nTODO:\n 1. Implement smart_plot\n\"\"\"\n\n\ndef _build_series(*args, **kwargs):\n \"\"\"Read the docstring of get_plot_data to unsertand what args and kwargs\n are.\n \"\"\"\n\n mapping = {\n \"p\": [LineOver1DRangeSeries, 1, 1], # [cls, nexpr, npar]\n \"pp\": [Parametric2DLineSeries, 2, 1],\n \"p3dl\": [Parametric3DLineSeries, 3, 1],\n \"p3ds\": [ParametricSurfaceSeries, 3, 2],\n \"p3d\": [SurfaceOver2DRangeSeries, 1, 2],\n \"pi\": [ImplicitSeries, 1, 2],\n \"pinter\": [InteractiveSeries, 0, 0],\n \"v2d\": [Vector2DSeries, 2, 2],\n \"v3d\": [Vector3DSeries, 3, 3],\n \"v3ds\": [SliceVector3DSeries, 3, 3],\n \"pc\": [ContourSeries, 1, 2],\n \"c\": [ComplexSeries, 1, 1],\n \"g\": [GeometrySeries, 9, 9],\n }\n\n # In the following dictionary the key is composed of two characters:\n # 1. The first represents the number of sub-expressions. For example,\n # a line plot or a surface plot have 1 expression. A 2D parametric line\n # does have 2 parameters, ...\n # 2. The second represent the number of parameters.\n # There will be ambiguities due to the fact that some series use the same\n # number of expressions and parameters. This dictionary set a default series\n reverse_mapping = {\n \"11\": \"p\",\n \"21\": \"pp\",\n \"31\": \"p3dl\",\n \"32\": \"p3ds\",\n \"12\": \"p3d\",\n \"22\": \"v2d\",\n \"33\": \"v3d\",\n }\n\n args = _plot_sympify(args)\n exprs, ranges, label = _unpack_args(*args)\n args = [*exprs, *ranges, label]\n\n pt = kwargs.pop(\"pt\", None)\n if pt is None:\n # Automatic detection based on the number of free symbols and the number\n # of expressions\n\n pt = \"\"\n skip_check = False\n\n if (len(ranges) > 0) and (ranges[0][1].has(I) or ranges[0][2].has(I)):\n pt = \"c\"\n elif isinstance(exprs[0], GeometryEntity):\n if len(ranges) == 0:\n ranges = [None]\n args = [*exprs, *ranges, label]\n pt = \"g\"\n skip_check = True\n elif isinstance(exprs[0], (Boolean, Relational)):\n # implicit series\n pt = \"pi\"\n elif isinstance(exprs[0], (DenseMatrix, Vector)):\n split_expr, ranges = _split_vector(exprs[0], ranges)\n if split_expr[-1] is S.Zero:\n args = [split_expr[:2], *ranges, label]\n pt = \"v2d\"\n else:\n args = [split_expr, *ranges, label]\n pt = \"v3d\"\n elif isinstance(exprs[0], (list, tuple, Tuple)):\n if any(t.has(I) for t in exprs[0]):\n # list of complex points\n pt = \"c\"\n skip_check = True\n if len(args) == 2:\n # no range has been provided\n args = [args[0], None, args[1]]\n else:\n # Two possible cases:\n # 1. The actual parametric expression has been provided in the form\n # (expr1, expr2, expr3 [optional]), range1, range2 [optional]\n # 2. A vector has been written as a tuple/list\n fs = set().union(*[e.free_symbols for e in exprs[0]])\n npar = len(fs)\n nexpr = len(exprs[0])\n tmp = str(nexpr) + str(npar)\n if tmp in reverse_mapping.keys():\n pt = reverse_mapping[tmp]\n elif exprs[0].has(I):\n # complex series -> return complex numbers\n pt = \"c\"\n else:\n # the actual expression (parametric or not) is not contained in a\n # tuple. For example:\n # expr1, expr2, expr3 [optional]), range1, range2 [optional]\n fs = set().union(*[e.free_symbols for e in exprs])\n npar = len(fs)\n nexpr = len(exprs)\n tmp = str(nexpr) + str(npar)\n if tmp in reverse_mapping.keys():\n pt = reverse_mapping[tmp]\n\n params = kwargs.get(\"params\", dict())\n if len(params) > 0:\n # we are most likely dealing with an interactive series\n skip_check = True\n pt = \"pinter\"\n args = [exprs, ranges, label]\n\n if pt not in mapping.keys():\n raise ValueError(\n \"Don't know how to plot the expression:\\n\"\n + \"Received: {}\\n\".format(args)\n + \"Number of subexpressions: {}\\n\".format(nexpr)\n + \"Number of parameters: {}\".format(npar)\n )\n\n _cls, nexpr, npar = mapping[pt]\n if not skip_check:\n # In case of LineOver1DRangeSeries, Parametric2DLineSeries,\n # Parametric3DLineSeries, ParametricSurfaceSeries,\n # SurfaceOver2DRangeSeries, validate the provided expressions/ranges\n args = _check_arguments(args, nexpr, npar)[0]\n\n _slice = kwargs.pop(\"slice\", None)\n if pt == \"v3d\" and (_slice is not None):\n args = [_slice] + list(args)\n _cls, nexpr, npar = mapping[\"v3ds\"]\n\n else:\n if pt in mapping.keys():\n _cls, nexpr, npar = mapping[pt]\n k = str(nexpr) + str(npar)\n if k == \"00\":\n args = [exprs, ranges, label]\n if kwargs.get(\"is_complex\", False):\n _cls = ComplexInteractiveSeries\n args = [exprs[0], ranges[0], label]\n elif k == \"22\":\n if isinstance(args[0], (Vector, DenseMatrix)):\n split_expr, ranges = _split_vector(exprs[0], ranges)\n args = [split_expr[:2], *ranges, label]\n args = _check_arguments(args, 2, 2)[0]\n elif k == \"33\":\n if isinstance(args[0], (Vector, DenseMatrix)):\n split_expr, ranges = _split_vector(exprs[0], ranges)\n args = [split_expr, *ranges, label]\n args = _check_arguments(args, 3, 3)[0]\n\n _slice = kwargs.pop(\"slice\", None)\n if _slice is not None:\n args = [_slice] + list(args)\n _cls = SliceVector3DSeries\n elif k == \"99\":\n _cls = GeometrySeries\n if len(ranges) == 0:\n ranges = [None]\n args = [*exprs, *ranges, label]\n if (\n isinstance(exprs[0], Plane)\n and len(kwargs.get(\"params\", dict())) > 0\n ):\n _cls = PlaneInteractiveSeries\n args = [exprs, ranges, label]\n else:\n args = _check_arguments(args, nexpr, npar)[0]\n else:\n raise ValueError(\n \"Wrong `pt` value. Please, check the docstring \"\n + \"of `get_plot_data` to list the possible values.\"\n )\n kwargs = _set_discretization_points(kwargs, _cls)\n return _cls(*args, **kwargs)\n\n\ndef get_plot_data(*args, **kwargs):\n \"\"\"Return the numerical data associated to the a symbolic expression that\n we would like to plot. If a symbolic expression can be plotted with any of\n the plotting functions exposed by spb.functions or spb.vectors, then\n numerical data will be returned.\n\n Only one expression at a time can be processed by this function.\n The shape of the numerical data depends on the provided expression.\n\n Keyword Arguments\n =================\n\n pt : str\n Specify which kind of data you would like to obtain. Default value\n is None, indicating the function will use automatic detection.\n Possible values are:\n \"p\": to specify a line plot.\n \"pp\": to specify a 2d parametric line plot.\n \"p3dl\": to specify a 3d parametric line plot.\n \"p3d\": to specify a 3d plot.\n \"p3ds\": to specify a 3d parametric surface plot.\n \"pi\": to specify an implificit plot.\n \"pinter\": to specify an interactive plot. In such a case, you\n will also have to provide a `param` dictionary mapping\n theparameters to their values.\n \"v2d\": to specify a 2D vector plot.\n \"v3d\": to specify a 3D vector plot.\n \"c\": to specify a complex plot.\n\n Examples\n ========\n\n .. plot::\n :context: close-figs\n :format: doctest\n :include-source: True\n\n >>> from sympy import symbols, pi\n >>> from sympy.plotting.plot_data import get_plot_data\n >>> u, v, x, y = symbols('u, v, x, y')\n\n Data from a function with a single variable (2D line):\n\n .. get_plot_data::\n :context: close-figs\n :format: doctest\n :include-source: True\n\n >>> xx, yy = get_plot_data(cos(x), (x, -5, 5))\n\n Here, `xx` and `yy` are two lists of coordinates.\n\n Data from a function with two variables (surface):\n\n .. get_plot_data::\n :context: close-figs\n :format: doctest\n :include-source: True\n\n >>> xx, yy, zz = get_plot_data(cos(x * y), (x, -5, 5), (y, -10, 10))\n\n Here, `xx, yy, zz` are two-dimensional numpy arrays. `xx, yy` represent the\n mesh grid.\n\n Data from a 2D parametric function with one variable (2D line):\n\n .. get_plot_data::\n :context: close-figs\n :format: doctest\n :include-source: True\n\n >>> xx, yy = get_plot_data(cos(u), sin(u), (u, 0, 2 * pi))\n\n Here, `xx` and `yy` are two lists of coordinates.\n\n Data from a 3D parametric function with one variables (3D line):\n\n .. get_plot_data::\n :context: close-figs\n :format: doctest\n :include-source: True\n\n >>> xx, yy, zz = get_plot_data(cos(u), sin(u), u, (u, -5, 5))\n\n Here, `xx, yy, zz` are three lists of coordinates.\n\n Data from an implicit relation:\n\n .. get_plot_data::\n :context: close-figs\n :format: doctest\n :include-source: True\n\n >>> data = get_plot_data(x > y)\n\n Here, `data` depends on the specific case. Its shape could be:\n `data = ((xx, yy), 'fill')` where `xx, yy` are two lists of coordinates.\n `data = (xx, yy, zz, 'contour') where `xx, yy, zz` are two-dimensional numpy\n arrays. `xx, yy` represent the mesh grid. This is returned by objects of\n type Equality.\n `data = (xx, yy, zz, 'contourf') where `xx, yy, zz` are two-dimensional numpy\n arrays. `xx, yy` represent the mesh grid. This is returned by objects of\n type non-equalities (greater than, less than, ...).\n\n Get the necessary data to plot a 3D vector field over a slice plane:\n\n .. code-block:: python\n var(\"x:z\")\n xx, yy, zz, uu, vv, ww = get_plot_data(\n Matrix([z, y, x]), (x, -5, 5), (y, -5, 5), (z, -5, 5),\n slice = Plane((-2, 0, 0), (1, 1, 1)), n=5\n )\n\n Here `xx, yy, zz, uu, vv, ww` are three dimensional numpy arrays.\n\n Get the real and imaginary part of a complex function over a real range:\n\n .. code-block:: python\n z = symbols(\"z\")\n xx, real, imag = get_plot_data(sqrt(z), (z, -3, 3), pt=\"c\")\n\n Note the use of pt=\"c\" to specify a complex plot: the expression doesn't\n contain the imaginary unit, hence we need to aid the detection algorithm.\n\n Get the magnitude and argument of a complex function over a real range:\n\n .. code-block:: python\n z = symbols(\"z\")\n expr = 1 + exp(-Abs(z)) * sin(I * sin(5 * z))\n xx, mag, arg = get_plot_data(expr, (z, -3, 3), absarg=True)\n\n Compute a complex function over a complex range:\n\n .. code-block:: python\n z = symbols(\"z\")\n xx, yy, abs, arg, _, _ = get_plot_data(gamma(z), (z, -3 - 3*I, 3 + 3*I))\n\n Here, `xx, yy` are 2D arrays. `xx` is the real part of the domain.\n `yy` is the complex part of the domain. `abs` and `arg` are the absolute\n value and argument of the complex function.\n\n See also\n ========\n\n plot, plot_parametric, plot3d, plot3d_parametric_line,\n plot3d_parametric_surface, plot_contour, plot_implicit,\n vector_plot, complex_plot\n \"\"\"\n return _build_series(*args, **kwargs).get_data()\n\n\ndef smart_plot(*args, show=True, **kwargs):\n \"\"\"Smart plot interface. Using the same interface of the other plot\n functions, namely (expr, range, label), it unifies the plotting experience.\n If a symbolic expression can be plotted with any of the plotting functions\n exposed by spb.functions or spb.vectors, then this function will be able\n to plot it as well.\n\n Keyword Arguments\n =================\n The usual keyword arguments available on every other plotting functions\n are available (`xlabel`, ..., `adaptive`, `n`, ...). On top of that\n we can set:\n\n pt : str\n Specify which kind of plot we are intereseted. Default value\n is None, indicating the function will use automatic detection.\n Possible values are:\n \"p\": to specify a line plot.\n \"pp\": to specify a 2d parametric line plot.\n \"p3dl\": to specify a 3d parametric line plot.\n \"p3d\": to specify a 3d plot.\n \"p3ds\": to specify a 3d parametric surface plot.\n \"pi\": to specify an implificit plot.\n \"pinter\": to specify an interactive plot. In such a case, you\n will also have to provide a `param` dictionary mapping\n theparameters to their values.\n To specify a complex-interactive plot, set\n `is_complex=True`.\n \"v2d\": to specify a 2D vector plot.\n \"v3d\": to specify a 3D vector plot.\n \"c\": to specify a complex plot.\n \"g\": to specify a geometric entity plot.\n\n Examples\n ========\n\n Plotting different types of expressions with automatic detection:\n\n .. code-block:: python\n from sympy import symbols, sin, cos, Matrix\n from spb.backends.plotly import PB\n x, y = symbols(\"x, y\")\n smart_plot(\n (Matrix([-sin(y), cos(x)]), (x, -5, 5), (y, -3, 3), \"vector\"),\n (sin(x), (x, -5, 5)),\n aspect=\"equal\", n=20, legend=True,\n quiver_kw=dict(scale=0.25), line_kw=dict(line_color=\"cyan\"),\n backend=PB\n )\n\n Specify the kind of plot we are interested in:\n\n .. code-block:: python\n from sympy import symbols, cos\n x, y = symbols(\"x, y\")\n plot(cos(x**2 + y**2), (x, -3, 3), (y, -3, 3),\n xlabel=\"x\", ylabel=\"y\", pt=\"pc\")\n\n See also\n ========\n\n plot, plot_parametric, plot3d, plot3d_parametric_line,\n plot3d_parametric_surface, plot_contour, plot_implicit,\n vector_plot, complex_plot\n \"\"\"\n\n args = _plot_sympify(args)\n if not all([isinstance(a, (list, tuple, Tuple)) for a in args]):\n args = [args]\n series = []\n\n for arg in args:\n series.append(_build_series(*arg, **kwargs))\n\n if \"backend\" not in kwargs.keys():\n from spb.defaults import TWO_D_B, THREE_D_B\n\n is_3D = any([s.is_3D for s in series])\n kwargs[\"backend\"] = THREE_D_B if is_3D else TWO_D_B\n plots = Plot(*series, **kwargs)\n if show:\n plots.show()\n return plots\n","sub_path":"spb/plot_data.py","file_name":"plot_data.py","file_ext":"py","file_size_in_byte":16099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"71015238","text":"class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n lowest = 0xFFFFFFFF\n biggestGain = 0\n for price in prices:\n if price < lowest:\n lowest = price\n biggestGain = max(biggestGain, price - lowest)\n return biggestGain\n\n def maxProfit2(self, prices):\n highest = 0\n biggestGain = 0\n for i in range(len(prices),0,-1):\n if prices[i-1] > highest:\n highest = prices[i-1]\n biggestGain = max(biggestGain, highest - prices[i-1])\n return biggestGain\n\n# print(Solution().maxProfit2([7, 1, 5, 3, 6, 4]))\n\nclass Solution2:\n '''\n with 1 day sell->buy cooldown\n '''\n\n def maxProfit1(self, prices):\n if len(prices) < 2:\n return 0\n days = len(prices)\n negInf = -float('inf')\n buy, sell = [-prices[0]]+[negInf]*(days-1), [0]*days\n for i in range(1, days):\n buy[i] = max(buy[i-1], sell[i-2]-prices[i])\n sell[i] = max(sell[i-1], buy[i-1]+prices[i])\n print(buy, sell)\n return sell[-1]\n\n def maxProfit(self, prices):\n if len(prices) < 2:\n return 0\n sell, buy, prev_sell, prev_buy = 0, -prices[0], 0, 0\n for price in prices:\n print(sell, buy, prev_sell, prev_buy)\n prev_buy = buy\n buy = max(prev_sell - price, prev_buy)\n prev_sell = sell\n sell = max(prev_buy + price, prev_sell)\n print(sell, buy, prev_sell, prev_buy)\n return sell\n\nprint(Solution2().maxProfit([1,2,3,45,7,8,5,34,4,2]))\nprint(Solution2().maxProfit1([1,2,3,45,7,8,5,34,4,2]))","sub_path":"maxProfit.py","file_name":"maxProfit.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"429790305","text":"import barrel.cooper\nimport flask\nimport functools\nimport json\nimport math\nimport mongoengine\nimport mongoengine.queryset\nimport os\nfrom datetime import datetime\nfrom flask.ext.bootstrap import Bootstrap\nfrom pycon_bot import mongo\nfrom pycon_bot.models import Meeting, TalkProposal, Group, doc2dict\n\napp = flask.Flask(__name__)\napp.debug = 'PYCONBOT_DEBUG' in os.environ\nBootstrap(app)\nmongo.connect()\n\n#\n# Auth.\n#\n# If PYCONBOT_BASIC_AUTH is set, then it's a list of user/pass\n# pairs (of the form \"user:pass;user2:pass2\") to protect the app with basic\n# auth. If any of those users match users in PYCONBOT_SUPERUSERS, they're\n# admins and can do awesome admin stuff.\n#\nif 'PYCONBOT_BASIC_AUTH' in os.environ:\n users = [userpass.split(':', 1) for userpass in os.environ['PYCONBOT_BASIC_AUTH'].split(';')]\n auth = barrel.cooper.basicauth(users=users, realm='PCbot')\n app.wsgi_app = auth(app.wsgi_app)\n\n SUPERUSERS = os.environ.get('PYCONBOT_SUPERUSERS', '').split(',')\n\n def requires_superuser(func):\n @functools.wraps(func)\n def inner(*args, **kwargs):\n if flask.request.authorization['username'] not in SUPERUSERS:\n flask.abort(403)\n return func(*args, **kwargs)\n\n return inner\n\n @app.context_processor\n def inject_superuser():\n return {'user_is_superuser': flask.request.authorization['username'] in SUPERUSERS}\n\nelse:\n def requires_superuser(func):\n return func\n\n @app.context_processor\n def inject_superuser():\n return {'user_is_superuser': True}\n\n@app.route('/')\ndef index():\n total = len(TalkProposal.objects)\n reviewed = len(TalkProposal.objects(status__ne='unreviewed'))\n remaining = total - reviewed\n accepted = len(TalkProposal.objects(kittendome_result='thunderdome'))\n rejected = len(TalkProposal.objects(kittendome_result='rejected'))\n number_of_meetings = len(Meeting.objects)\n talks_per_meeting = float(reviewed) / number_of_meetings\n\n groups_total = len(Group.objects)\n groups_reviewed = len(Group.objects(decided=True))\n total_tdome_talks = sum(Group.objects.filter(decided=True).item_frequencies('talks').values())\n tdome_results = {}\n for result in ('accepted', 'damaged', 'rejected'):\n c = len(TalkProposal.objects(thunderdome_result=result))\n tdome_results[result] = {\n 'count': c,\n 'percent': float(c)/total_tdome_talks\n }\n\n talks_by_status = TalkProposal.objects.item_frequencies('status')\n talks_by_status.update(TalkProposal.objects.item_frequencies('alternative'))\n talks_by_status.pop(None)\n talks_by_status['rejected'] -= sum(talks_by_status.get(k, 0) for k,v in TalkProposal.TALK_ALTERNATIVES)\n talks_by_status = sorted(talks_by_status.items())\n\n return flask.render_template('index.html',\n total = total,\n reviewed = reviewed,\n remaining = remaining,\n kittendome_complete = (remaining == 0),\n percent_reviewed = float(reviewed) / total,\n accepted = accepted,\n percent_accepted = (float(accepted) / reviewed) if reviewed else 0,\n rejected = rejected,\n percent_rejected = (float(rejected) / reviewed) if reviewed else 0,\n number_of_meetings = number_of_meetings,\n talks_per_meeting = talks_per_meeting,\n meetings_left = int(math.ceil(float(remaining) / talks_per_meeting)),\n talks_by_status_json = json.dumps(talks_by_status),\n groups_total = groups_total,\n groups_reviewed = groups_reviewed,\n groups_remaining = groups_total - groups_reviewed,\n groups_reviewed_percent = float(groups_reviewed) / groups_total,\n thunderdome_results = tdome_results,\n )\n\n\n@app.route('/meetings')\ndef meeting_list():\n return flask.render_template('meeting_list.html',\n meetings = Meeting.objects.order_by('-number').exclude('transcript', 'talks_decided'),\n meeting = None)\n\n\n@app.route('/meetings/')\ndef meeting_detail(n):\n return flask.render_template('meeting_detail.html',\n meetings = Meeting.objects.order_by('-number').exclude('transcript', 'talks_decided'),\n meeting = get_or_404(Meeting.objects, number=n))\n\n\n@app.route('/talks')\ndef talk_list():\n talks = TalkProposal.objects.exclude('notes', 'kittendome_transcript') \\\n .order_by('talk_id')\n return flask.render_template('talk_list.html',\n title = \"All talks\",\n talks = talks,\n statuses = sorted(TalkProposal.STATUSES + TalkProposal.TALK_ALTERNATIVES),\n )\n\n@app.route('/talks/')\ndef talk_detail(n):\n \"\"\"View returning detailed information about a talk.\"\"\"\n\n # retrieve the talk\n talk = get_or_404(TalkProposal.objects, talk_id=n)\n\n return flask.render_template('talk_detail.html',\n talk=talk,\n )\n\n@app.route('/talks/')\ndef talks_by_status(status):\n\n if status in [k for k,v in TalkProposal.STATUSES]:\n talks = TalkProposal.objects.filter(status=status)\n elif status in [k for k,v in TalkProposal.TALK_ALTERNATIVES]:\n talks = TalkProposal.objects.filter(alternative=status)\n else:\n flask.abort(404)\n\n talks = talks.order_by('talk_id').exclude('notes', 'kittendome_transcript').order_by('talk_id')\n statuses = dict(TalkProposal.STATUSES + TalkProposal.TALK_ALTERNATIVES)\n\n return flask.render_template('talk_list.html',\n title = statuses[status],\n talks = talks,\n statuses = TalkProposal.STATUSES + TalkProposal.TALK_ALTERNATIVES,\n current_status = status\n )\n\n@app.route('/thunderdome/groups')\ndef thunderdome_group_list():\n return flask.render_template('thunderdome_group_list.html',\n groups = Group.objects.order_by('number').select_related(),\n title = \"all groups\",\n )\n\n@app.route('/thunderdome/groups/undecided')\ndef thunderdome_undecided_groups():\n return flask.render_template('thunderdome_group_list.html',\n groups = Group.objects.filter(decided__ne=True).order_by('number').select_related(),\n title = \"undecided groups\",\n )\n\n@app.route('/thunderdome/groups/decided')\ndef thunderdome_decided_groups():\n return flask.render_template('thunderdome_group_list.html',\n groups = Group.objects.filter(decided=True).order_by('number').select_related(),\n title = \"decided groups\",\n )\n\n@app.route('/thunderdome/groups/')\ndef thunderdome_group_detail(g):\n return flask.render_template('thunderdome_group_detail.html',\n group = get_or_404(Group.objects, number=g)\n )\n\n@app.route('/thunderdome/manage')\n@requires_superuser\ndef manage_thunderdome():\n ungrouped = _get_ungrouped_talks()\n return flask.render_template('manage_thunderdome.html',\n groups = Group.objects.all().select_related(),\n ungrouped = ungrouped\n )\n\n@app.route('/api/talks/ungrouped')\ndef api_talks_ungrouped():\n return _jsonify_talks(_get_ungrouped_talks())\n\n@app.route('/api/groups')\ndef api_groups():\n return flask.jsonify(objects=[\n doc2dict(g, fields=('number', 'name'))\n for g in Group.objects.all()\n ])\n\n@app.route('/api/groups', methods=['POST'])\n@requires_superuser\ndef new_group():\n g = Group.objects.create(name=flask.request.json['name'])\n for talk_id in flask.request.json['talks']:\n g.add_talk_id(talk_id)\n return flask.jsonify(doc2dict(g, fields=('number', 'name')))\n\n@app.route('/api/groups/', methods=['PUT'])\n@requires_superuser\ndef update_group(n):\n g = get_or_404(Group.objects, number=n)\n\n # Update name if given. Note that we don't update the number because\n # that's weird and I don't want to think through the ramifications.\n if 'name' in flask.request.json:\n g.update(set__name=flask.request.json['name'])\n\n # For each talk we have to remove it from an exsting group, if neccisary,\n # add it to this group, and make sure to mark it grouped.\n for talk_id in flask.request.json.get('talks', []):\n g.add_talk_id(talk_id)\n\n return flask.jsonify(doc2dict(g, fields=('number', 'name')))\n\n@app.route('/api/groups/', methods=['DELETE'])\n@requires_superuser\ndef delete_group(n):\n g = get_or_404(Group.objects, number=n)\n for t in g.talks:\n t.grouped = False\n t.save()\n g.delete()\n return (\"\", 204)\n\n@app.route('/api/groups//talks')\ndef api_group_talks(n):\n g = get_or_404(Group.objects, number=n)\n return _jsonify_talks(g.talks)\n\ndef _get_ungrouped_talks():\n return TalkProposal.objects.filter(status=\"thunderdome\", grouped__ne=True) \\\n .only('talk_id', 'title') \\\n .order_by('talk_id')\n\ndef _jsonify_talks(tl):\n return flask.jsonify(objects=[\n doc2dict(t, fields=('talk_id', 'title')) for t in tl\n ])\n\ndef get_or_404(qs, *args, **kwargs):\n try:\n return qs.get(*args, **kwargs)\n except mongoengine.queryset.DoesNotExist:\n flask.abort(404)\n\n# Force debug if run as main (i.e. python -m pycon_bot.web.app)\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"pycon_bot/web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"208770280","text":"from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update\r\nfrom telegram.ext import (\r\n Updater,\r\n CommandHandler,\r\n MessageHandler,\r\n Filters,\r\n ConversationHandler,\r\n CallbackContext,\r\n)\r\n\r\nHEIGHT, WEIGHT = range(2)\r\n\r\ndef bmi(update: Update, _: CallbackContext) -> int:\r\n update.message.reply_text(\r\n 'What is your height(cm)?\\n\\n'\r\n 'Send /cancel to stop talking to me.\\n',\r\n )\r\n return HEIGHT\r\n\r\ndef height(update: Update, _: CallbackContext) -> int:\r\n global height_input \r\n try:\r\n height_input = int(update.message.text)\r\n except ValueError:\r\n update.message.reply_text(\r\n 'Thats not a valid input!\\n'\r\n 'What is your height(cm)?\\n'\r\n ) \r\n return HEIGHT \r\n height_input = height_input/100 \r\n update.message.reply_text('What is your weight(kg)?')\r\n return WEIGHT\r\n\r\ndef weight(update: Update, _: CallbackContext) -> int:\r\n global weight_input \r\n weight_status = \"\"\r\n try:\r\n weight_input = int(update.message.text)\r\n except ValueError:\r\n update.message.reply_text(\r\n 'That is an invalid input!\\n'\r\n 'What is your weight(kg)?\\n'\r\n ) \r\n return WEIGHT \r\n bmi = weight_input / (height_input*height_input)\r\n bmi_str = \"{:.2f}\".format(bmi)\r\n if bmi < 18.50 :\r\n weight_status = 'Your weight status is: Underweight'\r\n elif 18.50 <= bmi < 25.00:\r\n weight_status = 'Your weight status is: Normal/Healthy Weight'\r\n elif 25.00 <= bmi < 30.00:\r\n weight_status = 'Your weight status is: Overweight'\r\n else: \r\n weight_status = 'Your weight status is: Obese'\r\n update.message.reply_text(\r\n 'Your BMI is: ' + bmi_str + '\\n' + weight_status\r\n )\r\n \r\n return ConversationHandler.END\r\n ","sub_path":"functions/bmifunc.py","file_name":"bmifunc.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"69534413","text":"from operator import itemgetter\nfrom math import inf\ndata = []\nnb_books = 0\nnb_libraries = 0\nnb_days = 0\nbooks = []\nlibraries = []\n\nclass Library:\n def __init__(self, nb_books, signup_time, books_per_day):\n self.nb_books = nb_books\n self.signup_time = signup_time\n self.books_per_day = books_per_day\n \n\nwith open('f_libraries_of_the_world.txt', 'r') as inputs:\n tmp = inputs.readline().strip(\"\\n\").split(\" \")\n nb_books = int(tmp[0])\n nb_libraries = int(tmp[1])\n nb_days = int(tmp[2])\n \n books = list(map(int, inputs.readline().strip(\"\\n\").split(\" \")))\n\n state = 0\n for line in inputs:\n if line.strip(\"\\n\").split(\" \") == ['']:\n continue\n if not state:\n tmp = list(map(int, line.strip(\"\\n\").split(\" \")))\n libraries.append(Library(tmp[0], tmp[1], tmp[2]))\n state = 1\n else:\n tmp = list(map(int, line.strip(\"\\n\").split(\" \")))\n libraries[-1].books = tmp\n state = 0\n\n#print(books)\n#print(libraries)\n\nlib_scores = []\n\nscanned_books = {}\n# Meer boeken POSITIEF\n# Lager aantal dagen POSTIEF\nmin_signup = inf\nmax_signup = 0\nmin_score = inf\nmax_score = 0\n\nfor i in range(len(libraries)):\n tmp_score = 0\n for book in libraries[i].books:\n tmp_score += books[book]\n if book in scanned_books:\n scanned_books[book] += (i)\n else:\n scanned_books[book] = (i)\n if libraries[i].signup_time > max_signup:\n max_signup = libraries[i].signup_time\n if libraries[i].signup_time < min_signup:\n min_signup = libraries[i].signup_time\n tmp_score = tmp_score/len(libraries[i].books)\n if tmp_score > max_score:\n max_score = tmp_score\n if tmp_score < min_score:\n min_score = tmp_score\n\n \nfor i in range(len(libraries)):\n tmp_score = 0\n for book in libraries[i].books:\n tmp_score += books[book]\n tmp_score = tmp_score/len(libraries[i].books)\n if max_score == min_score:\n tmp_score = 0\n else:\n tmp_score = (tmp_score - min_score)/(max_score-min_score)\n if max_signup == min_signup:\n tmp_signup = 0\n else:\n tmp_signup = 1 - (libraries[i].signup_time - min_signup)/(max_signup-min_signup)\n lib_scores.append([i, tmp_score+tmp_signup])\n\n\n\nlib_scores = sorted(lib_scores, key=itemgetter(1), reverse=True)\nprint(lib_scores)\ndays_occupied = 0\ni = 0\nfinal_libs = []\nwhile days_occupied < nb_days and i < len(lib_scores):\n final_libs.append(lib_scores[i][0])\n days_occupied += libraries[lib_scores[i][0]].signup_time\n i+=1\n\nfinal_books = []\nfor i in range(len(final_libs)):\n final_books.append(\" \".join(list(map(str, libraries[final_libs[i]].books))))\n\nresult = [f\"{len(final_libs)}\\n\"] + [(f\"{final_libs[i]} {libraries[final_libs[i]].nb_books}\\n\"+final_books[i]+\"\\n\") for i in range(len(final_libs))]\n#print(result)\nwith open('f2.out', 'w') as output:\n output.writelines(result)","sub_path":"solution19.py","file_name":"solution19.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"471623201","text":"\ndef arcs_to_graph(Arcs):\n\t\"\"\"\n\tConvert Arc's set to graph representation\n\t\"\"\"\n\tgraph = {}\n\tfor k,v in Arcs.items():\n\t\ttry:\n\t\t\tgraph[k[0]].append(k[1])\n\t\texcept KeyError:\n\t\t\tgraph[k[0]] =[]\n\t\t\tgraph[k[0]].append(k[1])\n\t\ttry:\n\t\t\tgraph[k[1]]\n\t\texcept KeyError:\n\t\t\tgraph[k[1]] =[]\n\t\t\t\n\t\n\treturn graph\n\ndef dfs_stack(graph,node,visited,stack):\n\t\"\"\"\n\t1st step of Kosaraju's algorithm. Create an empty stack and \n\tperform DFS on the original graph\n\t\"\"\"\n\tvisited[node]= True\n\tfor neighbour in graph[node]:\n\t\tif visited[neighbour] == False:\n\t\t\tdfs_stack(graph,neighbour,visited,stack)\n\tstack = stack.append(node)\n\ndef transpose_graph(graph):\n\t\"\"\"\n\t2nd step of Kosaraju's algorithm. Create the transpose of the\n\tgraph(reverse edge directions)\n\t\"\"\"\n\trev_graph = {}\n\tfor k,v in graph.items():\n\t\tfor node in v:\n\t\t\ttry:\n\t\t\t\trev_graph[node].append(k)\n\t\t\texcept KeyError:\n\t\t\t\trev_graph[node] =[]\n\t\t\t\trev_graph[node].append(k)\n\n\tfor k,v in graph.items():\n\t\ttry:\n\t\t\trev_graph[k]\n\t\texcept KeyError:\n\t\t\trev_graph[k] =[]\n\t\n\treturn rev_graph\n\n\ndef dfs(graph,node,visited,scc_list):\n\t\"\"\"\n\t3d step of Kosaraju's algorithm. Perform DFS on reversed\n\tgraph by poping one by one elemrnts of the stack\n\t\"\"\"\n\tvisited[node]= True\n\tscc_list.append(node)\n\tfor neighbour in graph[node]:\n\t\tif visited[neighbour] == False:\n\t\t\tscc_list = dfs(graph,neighbour,visited,scc_list)\n\t\n\treturn scc_list\n\ndef get_SCC(Arcs):\n\t\"\"\"\n\tGet a list of strongly connected components(SCC) of a given graph,\n\trepresented as a set of arcs\n\t\"\"\"\n\t\n\tgraph = arcs_to_graph(Arcs)\n\tstack =[]\n\tvisited = visited_false(graph)\n\tfor k,v in graph.items():\n\t\tif visited[k] == False:\n\t\t\tdfs_stack(graph,k,visited,stack)\n\n\trev_graph = transpose_graph(graph)\n\tvisited = visited_false(graph)\n\tSCC_list =[]\n\t\n\twhile (len(stack) > 0):\n node = stack.pop()\n if visited[node]==False:\n \tSCC_list.append(dfs(rev_graph,node,visited,[]))\n\treturn SCC_list\n\n\ndef visited_false(graph): \n\t#Initialize all nodes to visited = False\n\tvisited = {}\n\tfor k,v in graph.items():\n\t\tvisited[k] = False\n\treturn visited\n\n\n","sub_path":"Simple_parser/SCC.py","file_name":"SCC.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"356207933","text":"import sys\nimport time\nimport os.path\nimport os\n\nimport PyQt5\n\ndirname = os.path.dirname(PyQt5.__file__)\nplugin_path = os.path.join(dirname, 'plugins', 'platforms')\nos.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QCheckBox, QFileDialog, QVBoxLayout\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot\n\nfrom textmining import *\n\nLOCAL_PATH = os.path.dirname(os.path.dirname(TM_PATH))\n\nprint('LOCAL_PATH', LOCAL_PATH)\n\nclass TmEaTask(QObject):\n\n sig_done = pyqtSignal(int, int) # worker id: emitted at end of work()\n sig_msg = pyqtSignal(str) # message to be shown to user\n\n def __init__(self, id: int, config, pst_dir, text_dir, input_dir, emotion_dir, ax_dir, csv_dir, file_count, label_count):\n super().__init__()\n self.__id = id\n self.__abort = False\n self.notifyProgress = pyqtSignal(int)\n self.config = config\n self.pst_dir = pst_dir\n self.text_dir = text_dir\n self.input_dir = input_dir\n self.emotion_dir = emotion_dir\n self.ax_dir = ax_dir\n self.csv_dir = csv_dir\n self.file_count = file_count\n self.label_count = label_count\n\n def update_config(self, config):\n self.config = config\n\n @pyqtSlot()\n def work(self):\n thread_name = QThread.currentThread().objectName()\n thread_id = int(QThread.currentThreadId())\n\n self.sig_msg.emit('start process...')\n\n # self.notifyProgress.emit(i)\n #print('workflow configuration:', self.config)\n\n total_count = [self.file_count, self.label_count]\n\n # self.notifyProgress.emit(i)\n\n print(self.pst_dir)\n print(self.text_dir)\n print(self.input_dir)\n print(self.emotion_dir)\n print(self.ax_dir)\n print(self.csv_dir)\n\n if self.config[0]:\n print('pst folder is', self.pst_dir)\n print('raw text folder is', self.text_dir)\n for i in parse_pst_in_folder(\n self.pst_dir,\n self.text_dir,\n {\n \"sender\":\"sender\",\n \"sender_name\":\"sender_name\",\n \"subject\":\"subject\",\n \"time\":\"time\",\n \"email\":\"email\",\n \"receivers\":\"receivers\",\n }\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished parsing .PST files\")\n\n if self.config[1]:\n print('raw text folder is', self.text_dir)\n print('packed text folder is', self.input_dir)\n for i in transform_text_file_to_pickle(\n self.text_dir,\n self.input_dir,\n 'email_df_',\n ['sender', 'email', 'time', 'date'],\n total_count\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished regulating raw text\")\n self.file_count = total_count[0]\n\n if self.config[2]:\n print('packed text folder is', self.input_dir)\n print('labeled emotion folder is', self.emotion_dir)\n for i in app_extract_emotions(\n self.input_dir,\n 'email_df_',\n self.emotion_dir,\n 'emotion_',\n 'email', 'time', 'date',\n total_count\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished labeling emotions\")\n self.label_count = total_count[1]\n\n if self.config[3]:\n print('labeled emotion folder is', self.emotion_dir)\n print('individual analytics folder is', self.ax_dir)\n print('CSV folder is', self.csv_dir)\n for i in app_analyze_emotions(\n self.emotion_dir,\n 'emotion_',\n self.ax_dir,\n 'analytics_',\n self.csv_dir,\n self.config[7]\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished deep emotion analytics\")\n\n if self.config[4]:\n print('labeled emotion folder is', self.emotion_dir)\n print('individual analytics folder is', self.ax_dir)\n for i in app_plot_emotion_series(\n self.emotion_dir,\n 'emotion_',\n self.ax_dir,\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished plotting emotion detection results\")\n\n if self.config[5]:\n print('individual analytics folder is', self.ax_dir)\n for i in app_plot_analytics_results(\n self.ax_dir,\n 'analytics_',\n self.ax_dir,\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished plotting analytics results\")\n\n if self.config[6]:\n print('CSV folder is', self.csv_dir)\n for i in app_plot_csv_results(\n self.csv_dir,\n 'emotion_analysis_',\n self.csv_dir,\n ):\n self.sig_msg.emit(i)\n self.sig_msg.emit(\"finished plotting with CSV\")\n\n self.sig_done.emit(self.file_count, self.label_count)\n\n print('finish')\n\n def abort(self):\n self.sig_msg.emit('Task abort')\n self.__abort = True\n\n\nclass AppEmotionAnalysis(QWidget):\n\n sig_abort_tmea_task = pyqtSignal()\n\n def __init__(self, px, py):\n super().__init__()\n\n self.title = 'Deep Emotion Analysis'\n self.left = px\n self.top = py\n self.width = 600\n self.height = 300\n\n self.configure_fn = os.path.join(LOCAL_PATH, 'config.json')\n self.configure = read_from_json_file(self.configure_fn)\n\n self.pst_dir = self.expand_path(self.configure['pst_dir'])\n self.text_dir = self.expand_path(self.configure['text_dir'])\n self.input_dir = self.expand_path(self.configure['input_dir'])\n self.emotion_dir = self.expand_path(self.configure['emotion_dir'])\n self.individual_ax_dir = self.expand_path(self.configure['ax_dir'])\n self.org_ax_dir = self.expand_path(self.configure['csv_dir'])\n\n self.initUI()\n QThread.currentThread().setObjectName('main')\n\n self.tmEaTask = None\n self.thread = None\n\n\n def expand_path(self, path):\n #print('expand_path LOCAL_PATH', LOCAL_PATH)\n if len(path) > 2:\n if path.startswith('/'):\n return path\n elif path[1] == ':':\n return path\n elif path.startswith('\\\\'):\n path = path.replace('\\\\', '')\n return os.path.join(LOCAL_PATH, path)\n else:\n return os.path.join(LOCAL_PATH, path)\n return path\n\n\n def simplify_path(self, path):\n #print('simplify_path LOCAL_PATH', LOCAL_PATH)\n if path.startswith(LOCAL_PATH):\n text_dir = path.replace(LOCAL_PATH, '')\n if text_dir.startswith('/'):\n text_dir = text_dir[1:]\n elif text_dir.startswith('\\\\'):\n text_dir = text_dir.replace('\\\\', '')\n return text_dir\n return path\n\n\n def save_configure(self):\n d = {\n \"pst_dir\" : self.simplify_path(self.pst_dir),\n \"text_dir\" : self.simplify_path(self.text_dir),\n \"input_dir\" : self.simplify_path(self.input_dir),\n \"emotion_dir\" : self.simplify_path(self.emotion_dir),\n \"ax_dir\" : self.simplify_path(self.individual_ax_dir),\n \"csv_dir\" : self.simplify_path(self.org_ax_dir),\n \"file_count\" : self.configure['file_count'],\n \"label_count\" : self.configure['label_count'],\n \"check_box\" : self.configure['check_box']\n }\n save_to_json_file(d, self.configure_fn)\n\n\n def initUI(self):\n layout = QVBoxLayout()\n\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n self.btn_slct_dir_pst = QPushButton('Select *.PST files Directory', self)\n self.btn_slct_dir_pst.setToolTip('Select *.PST files directory, default is set')\n self.btn_slct_dir_pst.clicked.connect(self.slct_dir_pst)\n\n self.btn_slct_dir_raw_text = QPushButton('Select Raw Text Directory', self)\n self.btn_slct_dir_raw_text.setToolTip('Select raw text directory, default is set')\n self.btn_slct_dir_raw_text.clicked.connect(self.slct_dir_raw_text)\n\n self.btn_slct_dir_regulated_text = QPushButton('Select Regulated Text-List Directory', self)\n self.btn_slct_dir_regulated_text.setToolTip('Select regulated text-list directory, default is set')\n self.btn_slct_dir_regulated_text.clicked.connect(self.slct_dir_regulated_text)\n\n self.btn_slct_dir_labeled_emotions = QPushButton('Select Labeled Emotions Directory', self)\n self.btn_slct_dir_labeled_emotions.setToolTip('Select labeled emotions directory, default is set')\n self.btn_slct_dir_labeled_emotions.clicked.connect(self.slct_dir_labeled_emotions)\n\n self.btn_slct_dir_individual_analytics = QPushButton('Select Individual Analytics Directory', self)\n self.btn_slct_dir_individual_analytics.setToolTip('Select individual analytics directory, default is set')\n self.btn_slct_dir_individual_analytics.clicked.connect(self.slct_dir_individual_analytics)\n\n self.btn_slct_dir_org_analytics = QPushButton('Select Organization Analysis Directory', self)\n self.btn_slct_dir_org_analytics.setToolTip('Select organization analysis directory, default is set')\n self.btn_slct_dir_org_analytics.clicked.connect(self.slct_dir_org_analytics)\n\n layout.addWidget(self.btn_slct_dir_pst)\n layout.addWidget(self.btn_slct_dir_raw_text)\n layout.addWidget(self.btn_slct_dir_regulated_text)\n layout.addWidget(self.btn_slct_dir_labeled_emotions)\n layout.addWidget(self.btn_slct_dir_individual_analytics)\n layout.addWidget(self.btn_slct_dir_org_analytics)\n\n self.chkbx_pst = QCheckBox(\"Parse .pst files\")\n self.chkbx_rt = QCheckBox(\"Regulate Text files\")\n self.chkbx_de = QCheckBox(\"Detecting Emotions\")\n self.chkbx_cr = QCheckBox(\"Compute Colley's rating\")\n self.chkbx_ax = QCheckBox(\"Run Deep Analytics\")\n self.chkbx_ge = QCheckBox(\"Plot Detected Emotions\")\n self.chkbx_ga = QCheckBox(\"Plot Deep Analytics\")\n self.chkbx_gr = QCheckBox(\"Plot From CSV\")\n\n\n self.chkbx_pst.setChecked(True)\n self.chkbx_rt.setChecked(True)\n self.chkbx_de.setChecked(True)\n self.chkbx_cr.setChecked(True)\n self.chkbx_ax.setChecked(True)\n self.chkbx_ge.setChecked(True)\n self.chkbx_ga.setChecked(True)\n self.chkbx_gr.setChecked(True)\n\n layout.addWidget(self.chkbx_pst)\n layout.addWidget(self.chkbx_rt)\n layout.addWidget(self.chkbx_de)\n layout.addWidget(self.chkbx_cr)\n layout.addWidget(self.chkbx_ax)\n layout.addWidget(self.chkbx_ge)\n layout.addWidget(self.chkbx_ga)\n layout.addWidget(self.chkbx_gr)\n\n self.btn_run = QPushButton('RUN', self)\n self.btn_run.setToolTip('Run the process')\n self.btn_run.clicked.connect(self.run_analytics)\n layout.addWidget(self.btn_run)\n\n self.l_status = QLabel()\n self.l_status.setText(\"Click RUN to start!\")\n layout.addWidget(self.l_status)\n\n self.setLayout(layout)\n self.show()\n\n\n @pyqtSlot()\n def slct_dir_pst(self):\n self.pst_dir = str(QFileDialog.getExistingDirectory(self,\n \"Select Directory\",\n LOCAL_PATH,\n )\n )\n if PLATFORM == WIN:\n self.pst_dir = self.pst_dir.replace('/', '\\\\')\n elif PLATFORM == MAC:\n self.pst_dir = self.pst_dir.replace('\\\\', '/')\n if self.pst_dir is not None:\n print ('*.PST directory is: {0}'.format(self.pst_dir))\n\n\n @pyqtSlot()\n def slct_dir_raw_text(self):\n self.text_dir = str(QFileDialog.getExistingDirectory(self,\n \"Select Directory\",\n LOCAL_PATH,\n )\n )\n if PLATFORM == WIN:\n self.text_dir = self.text_dir.replace('/', '\\\\')\n elif PLATFORM == MAC:\n self.text_dir = self.text_dir.replace('\\\\', '/')\n if self.text_dir is not None:\n print ('input text directory is: {0}'.format(self.text_dir))\n\n\n @pyqtSlot()\n def slct_dir_regulated_text(self):\n self.input_dir = str(QFileDialog.getExistingDirectory(self,\n \"Select Directory\",\n LOCAL_PATH,\n )\n )\n if PLATFORM == WIN:\n self.input_dir = self.input_dir.replace('/', '\\\\')\n elif PLATFORM == MAC:\n self.input_dir = self.input_dir.replace('\\\\', '/')\n if self.input_dir is not None:\n print ('regulated file directory is: {0}'.format(self.input_dir))\n\n\n @pyqtSlot()\n def slct_dir_labeled_emotions(self):\n self.emotion_dir = str(QFileDialog.getExistingDirectory(self,\n \"Select Directory\",\n LOCAL_PATH,\n )\n )\n if PLATFORM == WIN:\n self.emotion_dir = self.emotion_dir.replace('/', '\\\\')\n elif PLATFORM == MAC:\n self.emotion_dir = self.emotion_dir.replace('\\\\', '/')\n if self.emotion_dir is not None:\n print ('labeled emotion directory is: {0}'.format(self.emotion_dir))\n\n\n @pyqtSlot()\n def slct_dir_individual_analytics(self):\n self.individual_ax_dir = str(QFileDialog.getExistingDirectory(self,\n \"Select Directory\",\n LOCAL_PATH,\n )\n )\n if PLATFORM == WIN:\n self.individual_ax_dir = self.individual_ax_dir.replace('/', '\\\\')\n elif PLATFORM == MAC:\n self.individual_ax_dir = self.individual_ax_dir.replace('\\\\', '/')\n if self.individual_ax_dir is not None:\n print ('individual analytics directory is: {0}'.format(self.individual_ax_dir))\n\n\n @pyqtSlot()\n def slct_dir_org_analytics(self):\n self.org_ax_dir = str(QFileDialog.getExistingDirectory(self,\n \"Select Directory\",\n LOCAL_PATH,\n )\n )\n if PLATFORM == WIN:\n self.org_ax_dir = self.org_ax_dir.replace('/', '\\\\')\n elif PLATFORM == MAC:\n self.org_ax_dir = self.org_ax_dir.replace('\\\\', '/')\n if self.org_ax_dir is not None:\n print ('organization output directory is: {0}'.format(self.org_ax_dir))\n\n\n @pyqtSlot(str)\n def update_progress(self, s):\n self.l_status.setText(s)\n\n\n @pyqtSlot(int, int)\n def task_completed(self, file_count, label_count):\n self.btn_run.setEnabled(True)\n self.l_status.setText(\"Task Finished\")\n self.configure['file_count'] = file_count\n self.configure['label_count'] = label_count\n self.save_configure()\n\n\n def check_input_folder(self):\n if not os.path.exists(self.pst_dir):\n if not os.path.isdir(self.pst_dir):\n return False, \".pst folder is not available\"\n\n if not os.path.exists(self.text_dir):\n if not os.path.isdir(self.text_dir):\n return False, \"raw text folder is not available\"\n\n if not os.path.exists(self.input_dir):\n if not os.path.isdir(self.input_dir):\n return False, \"regulated text folder is not available\"\n\n if not os.path.exists(self.emotion_dir):\n if not os.path.isdir(self.emotion_dir):\n return False, \"labeled emotion folder is not available\"\n\n if not os.path.exists(self.individual_ax_dir):\n if not os.path.isdir(self.individual_ax_dir):\n return False, \"emotion analytics folder is not available\"\n\n if not os.path.exists(self.org_ax_dir):\n if not os.path.isdir(self.org_ax_dir):\n return False, \"CSV folder is not available\"\n\n return True, \"Start analysis...\"\n\n\n @pyqtSlot()\n def run_analytics(self):\n ready, info = self.check_input_folder()\n if not ready:\n self.l_status.setText(info)\n return\n\n self.configure['check_box'] = [\n self.chkbx_pst.isChecked(),\n self.chkbx_rt.isChecked(),\n self.chkbx_de.isChecked(),\n self.chkbx_ax.isChecked(),\n self.chkbx_ge.isChecked(),\n self.chkbx_ga.isChecked(),\n self.chkbx_gr.isChecked(),\n self.chkbx_cr.isChecked(),\n ]\n self.l_status.setText(info)\n\n\n self.tmEaTask = TmEaTask(\n 0,\n config=self.configure['check_box'],\n pst_dir=self.pst_dir,\n text_dir=self.text_dir,\n input_dir=self.input_dir,\n emotion_dir=self.emotion_dir,\n ax_dir=self.individual_ax_dir,\n csv_dir=self.org_ax_dir,\n file_count=self.configure['file_count'],\n label_count=self.configure['label_count'],\n )\n\n\n self.thread = QThread(self)\n #print(self.thread)\n\n self.thread.setObjectName('thread_tmea')\n self.tmEaTask.moveToThread(self.thread)\n self.tmEaTask.sig_msg.connect(self.update_progress)\n self.tmEaTask.sig_done.connect(self.task_completed)\n self.sig_abort_tmea_task.connect(self.tmEaTask.abort)\n\n self.thread.started.connect(self.tmEaTask.work)\n # this will emit 'started' and start thread's event loop\n\n #print('start thread')\n\n self.btn_run.setEnabled(False)\n self.thread.start()\n\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n screen_resolution = app.desktop().screenGeometry()\n width, height = screen_resolution.width(), screen_resolution.height()\n ex = AppEmotionAnalysis(width/2-300, height/2-150)\n sys.exit(app.exec_())\n\n","sub_path":"EmoWebService/App/pyqt5_application.py","file_name":"pyqt5_application.py","file_ext":"py","file_size_in_byte":18022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"623354183","text":"__author__ = 'Paul Lo'\n__date__ = '2015-04-15'\n\nimport Queue\nimport threading\nimport time\nfrom datetime import datetime\nimport json\nfrom twitter_api_utils import send_search_request\nimport logging\nfrom pymongo.errors import BulkWriteError, DuplicateKeyError\n\nlogging.basicConfig(filename='collector.log',\n level=logging.DEBUG,\n format='%(threadName)s %(levelname)s %(asctime)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\nLOG = logging.getLogger(__name__)\n\n\nclass TweetProcessor(threading.Thread):\n \"\"\" Process and save tweets\n \"\"\"\n\n def __init__(self, worker_id, data_queue, db_connection, db_config):\n super(self.__class__, self).__init__()\n self.worker_id = worker_id\n self.data_queue = data_queue\n self.db_connection = db_connection\n self.collection_name = db_config['collection_name']\n self.collection_unique_index = db_config['unique_index']\n\n def run(self):\n \"\"\" Keep checking tweets from data_queue, processing and saving to database\n \"\"\"\n while True:\n try:\n tweets = self.data_queue.get()\n processed_tweet = self.process(tweets)\n self.save_to_db(processed_tweet)\n LOG.info('Worker #{} has finished processing {} tweets.'.format(self.worker_id, len(processed_tweet)))\n except Exception as e:\n LOG.exception(e.message) # log exception\n # TODO: narrow down the exception type and error handling\n finally:\n self.data_queue.task_done()\n\n def process(self, tweet_data):\n \"\"\"\n Read a list of tweet, do some pre-processing before calling save_to_db()\n :param tweet_data: raw data of tweet list\n :type tweet_data: list[dict]\n :returns: a list of tweet\n :rtype: list[dict]\n \"\"\"\n\n # as a quick prototype, we use only these few fields for simplicity.\n # for the real production, we need to include more fields on each tweet to mine/analyze more business insight\n filter_fields = ['id', 'text', 'created_at', 'collected_at', 'keyword']\n\n result = list()\n # format: based on https://dev.twitter.com/rest/reference/get/search/tweets\n for item in tweet_data:\n tweet = dict([(field, item[field]) for field in filter_fields if field in item])\n tweet[self.collection_unique_index] = tweet['id'] # append an additional uid field as unique index\n # more pre-processing could be added here\n result.append(tweet)\n return result\n\n def save_to_db(self, tweet_data):\n \"\"\" save tweet_data to storage\n :param tweet_data: a list of tweet we need to save\n :type tweet_data: list[dict]\n :returns: whether all tweet_data successfully saved\n :rtype: bool\n \"\"\"\n all_success = True\n try:\n\t # a small batch write job (no more than 15 tweets)\n # would be safely wrapped automatically in an atomic transaction in TokuMX\n self.db_connection[self.collection_name].insert_many(tweet_data)\n for tweet in tweet_data: # for logging purpose\n LOG.debug('inserted tweet (id: {}) {}'.format(tweet['id'], tweet['text'].encode('utf-8')))\n except BulkWriteError as e:\n LOG.error('BulkWriteError occurs on worker #{} while saving tweets {}: {}'\n .format(self.worker_id, [tweet['id'] for tweet in tweet_data], e.message))\n # the bulk insert are either all success or fail due to atomic characteristic of tokumx,\n # to handle the error, we re-try the action by inserting the tweet one by one\n for tweet in tweet_data:\n try:\n self.db_connection[self.collection_name].insert(tweet)\n LOG.debug('inserted tweet (id: {}) {}'.format(tweet['id'], tweet['text'].encode('utf-8')))\n except DuplicateKeyError as e:\n all_success = False\n LOG.error('DuplicateKeyError occurs on worker #{} when inserting tweet: {} :'.format(self.worker_id, tweet, e.message))\n return all_success\n\n\nclass TweetCollector:\n \"\"\" Keep getting the latest tweet containing query_keyword via twitter api,\n and assign few TweetProcessor instances to process those tweets and save to database\n \"\"\"\n\n def __init__(self, query_keyword, db_connection, db_config):\n if not query_keyword:\n raise ValueError(\"Query keyword must not be empty\")\n\n self.query_keyword = query_keyword\n self.consumer_count = 3\n self.data_queue = Queue.Queue()\n # storage setup\n self.db_connection = db_connection\n self.db_config = db_config\n\n def run(self):\n \"\"\" Start the collection job\n \"\"\"\n # one producer to collect tweets from twitter api\n # three consumer to process the tweets and save to database\n\n # initialize consumers/workers\n for i in xrange(self.consumer_count):\n worker = TweetProcessor((i+1), self.data_queue, self.db_connection, self.db_config)\n worker.daemon = True\n worker.start()\n LOG.info('Started TwitterProcessor #{}'.format((i+1)))\n\n # producer\n last_processed_tweet_id = None # keep track of the place we processed last time\n last_processed_created_time = None\n while True:\n try:\n LOG.debug('searching {}......'.format(self.query_keyword))\n response = send_search_request(self.query_keyword)\n\n current_time = datetime.now()\n str_current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')\n\n for line in response:\n data = json.loads(line)\n to_add_list = list()\n if not 'statuses' in data:\n LOG.warning('Unexpected format is received from twitter api: {}'.format(data))\n else:\n for tweet in data['statuses']:\n #print tweet['id'], tweet['text']\n created_time = tweet['created_at']\n created_time = time.strptime(created_time, '%a %b %d %H:%M:%S +0000 %Y')\n\n # avoid duplicate tweets here in advance of worker side\n # we can also avoid duplicates by querying database, but it might introduce much more overhead\n # prerequisite: the response from twitter api is sorted by time desc\n if (last_processed_created_time and created_time < last_processed_created_time) or \\\n (last_processed_tweet_id and tweet['id'] == last_processed_tweet_id):\n LOG.debug('duplicate is found, we have processed tweet with id {} already.'.format(last_processed_tweet_id))\n break\n\n # append two additional fields for info of collector\n tweet['collected_at'] = str_current_time\n tweet['keyword'] = self.query_keyword\n to_add_list.append(tweet)\n\n LOG.info('{} new tweets are collected'.format(len(to_add_list)))\n if len(to_add_list) > 0:\n LOG.debug('collected tweets: {}'.format([to_add['id'] for to_add in to_add_list]))\n self.data_queue.put(to_add_list)\n last_processed_tweet_id = to_add_list[0]['id']\n last_processed_created_time = time.strptime(to_add_list[0]['created_at'], '%a %b %d %H:%M:%S +0000 %Y')\n\n time.sleep(5) # per 180 requests/15 mins api usage limitation, 900 secs/180 requests = 5 secs\n time.sleep(15-len(to_add_list)) # dynamically sleep longer if more duplicated items are found this round\n except Exception as e:\n LOG.exception(e.message)\n # investigate into possible scenarios and handle errors accordingly later on\n\n self.data_queue.join()\n\n","sub_path":"tweet_collector.py","file_name":"tweet_collector.py","file_ext":"py","file_size_in_byte":8301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"573001594","text":"'''\nCreate a new report instance from an entry point and close several times,\nchecking memory consumption.\n'''\nimport os,sys\nimport unittest\nimport psutil\nfrom tkinter import (Tk)\nfrom arelle.CntlrWinMain import CntlrWinMain\nfrom pympler import (tracker)\nfrom arelle.plugin import DevTesting\nfrom arelle.PluginManager import pluginClassMethods\n\nclass TestNewSaveClose(unittest.TestCase):\n def test(self):\n process = psutil.Process(os.getpid())\n largeEntryPoint = \"http://www.eba.europa.eu/eu/fr/xbrl/crr/fws/corep/its-2014-05/2015-02-16/mod/corep_ind.xsd\"\n smallEntryPoint = \"http://eiopa.europa.eu/eu/xbrl/s2md/fws/solvency/solvency2/2015-05-31/mod/d1s.xsd\"\n application = Tk()\n cntlrWinMain = CntlrWinMain(application)\n application.protocol(\"WM_DELETE_WINDOW\", cntlrWinMain.quit)\n \n cntlrWinMain.setTestMode(True)\n for pluginMethod in pluginClassMethods(\"DevTesting.GetTestContext\"):\n testContext = pluginMethod()\n break\n testContext.checkMemoryOnClose = True\n testDir = os.path.dirname(os.path.abspath(sys.modules[__name__].__file__))\n testContext.saveFilePath = testDir + \"/tmp/a1.xbrl\"\n testContext.dumpFilePrefix = testDir + \"/tmp/dump_\"\n \n tr = tracker.SummaryTracker()\n \n prevMemoryConsumed = 0\n \n for idx in range(4):\n print(\"\\nIteration \" + str(idx))\n cntlrWinMain.fileOpenFile(largeEntryPoint)\n maxSize = DevTesting.humanizeSize(process.memory_info()[0])\n cntlrWinMain.logClear()\n cntlrWinMain.fileClose()\n \n tr.print_diff()\n memoryConsumed = process.memory_info()[0]\n print(\"Memory consumed: \" + DevTesting.humanizeSize(memoryConsumed) + \" max= \" + maxSize)\n diffMemeory = memoryConsumed - prevMemoryConsumed\n print(str(diffMemeory))\n if idx > 1:\n assert diffMemeory < 60000000, \"Check memory leaks regression\"\n prevMemoryConsumed = memoryConsumed\n \n # No need to explicitly quit and consume events\n #self.cntlrWinMain.quit()\n #application.mainloop()\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/newSaveCloseWinTest.py","file_name":"newSaveCloseWinTest.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"495890101","text":"import pymem\r\nimport re\r\n\r\npm = pymem.Pymem('Crab Game.exe')\r\nclient = pymem.process.module_from_name(pm.process_handle,\r\n 'GameAssembly.dll')\r\n\r\nclientModule = pm.read_bytes(client.lpBaseOfDll, client.SizeOfImage)\r\naddress = client.lpBaseOfDll + re.search(rb'\\x40\\x53\\x48\\x83\\xEC\\x20\\x48\\x8B\\xD9\\x48\\x85\\xC9\\x74\\x71',\r\n clientModule).start()\r\n\r\npm.write_bytes(address, b\"\\xC3\\x90\", 2)\r\npm.close_process()","sub_path":"ACPatch.py","file_name":"ACPatch.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"442318636","text":"import asyncio\nimport time\n\ndef function1_(loop,endtime):\n print(f'call function 1 {time.ctime()}')\n if (loop.time()+1 ) ts:\n ts = cts\n print(\"======================Reading files=====================\")\n\n idocs_file = open(\n \"./inputs.json\",\n )\n idocs = json.load(idocs_file)\n\n count = 0\n for doc in idocs[\"docs\"]:\n name = os.path.splitext(doc[\"path\"])[0]\n mwidth = doc[\"width\"]\n mheight = doc[\"height\"]\n print(\"Resizing logo==================\")\n resized_img = resize(logo, mwidth, mheight, doc[\"halign\"], doc[\"valign\"])\n resized_img.save(\"out/for_{}.png\".format(name))\n print(\"Putting Logo on Doc============\")\n paste_logo(doc, resized_img, count)\n\n count += 1\n\n return jsonify({\"message\": \"success\"})\n\n\n@app.route(\"/resize_all\", methods=[\"POST\"])\ndef resize_all():\n global ts\n global idocs\n\n if \"logo\" not in request.files:\n return jsonify({\"status\": \"error\", \"message\": \"logo file not provided\"})\n\n logo = request.files[\"logo\"]\n # logoname = request.form.get(\"folder_name\")\n\n # if not logoname:\n # logoname = os.path.splitext(logo.filename)[0]\n\n msg = \"\"\n\n cts = time.time()\n if cts - update_fq > ts:\n print(\"======================Reading files=====================\")\n try:\n idocs_file = open(\n input_json_path,\n )\n idocs = json.load(idocs_file)\n ts = cts\n except OSError:\n msg = \"JSON file not found\"\n except ValueError:\n msg = \"Incorrect json file format\"\n if msg == \"\":\n msg = \"Total docs updated: {}\".format(len(idocs[\"docs\"]))\n\n # out_folder = os.path.join(output_dir, logoname)\n # try:\n # os.makedirs(out_folder)\n # except OSError as error:\n # print(error)\n\n out_paths = {}\n timename = get_timename()\n for doc in idocs[\"docs\"]:\n name = os.path.splitext(doc[\"path\"])[0]\n resized_img = resize(\n logo, doc[\"width\"], doc[\"height\"], doc[\"halign\"], doc[\"valign\"]\n )\n filename = \"{}__{}.png\".format(timename, name)\n out_path = os.path.join(output_dir, filename)\n resized_img.save(out_path)\n out_paths[doc[\"path\"]] = filename\n\n return jsonify({\"status\": \"success\", \"message\": msg, \"paths\": out_paths})\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=3501)\n# https://www.image-map.net/\n# 18001200\n\n\n9425604658\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"190695411","text":"import sys\n\ninp = sys.stdin.readlines()\n\nx = [int(i) for i in inp.pop(0).split()]\n\nnum_stations = x[0]\nnum_lines = x[1]\n\nlines = [[] for i in range(num_lines)]\nrotations = [0 for i in range(num_lines)]\n\nstation_line = [[int(i)-1, -1] for i in inp.pop(0).split()]\nfor x in range(num_stations):\n\tn = int(station_line[x][0])\n\tstation_line[x][1] = len(lines[n-1])\n\tlines[n-1].append(x)\n\npopulations = [int(i) for i in inp.pop(0).split()]\nsums = [0, populations[0]]\nfor i in range(1, len(populations)):\n\tsums.append(populations[i]+sums[i])\n\nsummed = True\nfor action in inp:\n\taction = action.split()\n\n\tif action[0] == '1':\n\t\tif summed:\n\t\t\tprint(sums[int(action[2])] - sums[int(action[1])-1])\n\t\telse:\n\t\t\tsums[1] = populations[0]\n\t\t\tfor i in range(1, len(populations)):\n\t\t\t\tprint(\"D\", populations[lines[station_line[i][0]][(station_line[i][0]+rotations[station_line[i][0]])%len(lines[station_line[i][0]])]])\n\t\t\t\tsums[i+1] = sums[i]+populations[lines[station_line[i][0]][(station_line[i][0]+rotations[station_line[i][0]])%len(lines[station_line[i][0]])]]\n\t\t\tsummed = True\n\t\t\tprint(sums[int(action[2])] - sums[int(action[1])-1])\n\telse:\n\t\tsummed = False","sub_path":"2017/S5.py","file_name":"S5.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"104111747","text":"\"\"\"\nLicensed under GNU GPL-3.0-or-later\n\nThis file is part of RS Companion.\n\nRS Companion is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nRS Companion is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with RS Companion. If not, see .\n\nAuthor: Phillip Riskin\nAuthor: Nathan Rogers\nDate: 2020\nProject: Companion App\nCompany: Red Scientific\nhttps://redscientific.com/index.html\n\"\"\"\n\nfrom logging import getLogger, StreamHandler\nfrom PySide2.QtWidgets import QLabel, QGridLayout, QGroupBox\nfrom PySide2.QtCore import QSize, Qt\nfrom RSCompanionAsync.Resources.Strings.drive_info_strings import strings, StringsEnum, LangEnum\n\n\nclass DriveInfoBox(QGroupBox):\n \"\"\" This code is for displaying information about storage usage. \"\"\"\n def __init__(self, parent=None, size: QSize = QSize(10, 10), lang: LangEnum = LangEnum.ENG,\n log_handlers: [StreamHandler] = None):\n \"\"\"\n Initialize this view module.\n :param parent: parent of this view module.\n :param size: size this view module should occupy\n :param log_handlers:\n \"\"\"\n self._logger = getLogger(__name__)\n if log_handlers:\n for h in log_handlers:\n self._logger.addHandler(h)\n self._logger.debug(\"Initializing\")\n super().__init__(parent)\n self.setFixedSize(size)\n self.setLayout(QGridLayout())\n\n self._drive_name_label = QLabel()\n self._drive_name_label.setAlignment(Qt.AlignLeft)\n self.layout().addWidget(self._drive_name_label, 0, 0, 1, 1)\n\n self._drive_name_val = QLabel()\n self._drive_name_val.setAlignment(Qt.AlignRight)\n self.layout().addWidget(self._drive_name_val, 0, 1, 1, 1)\n\n self._drive_percent_label = QLabel()\n self._drive_percent_label.setAlignment(Qt.AlignLeft)\n self.layout().addWidget(self._drive_percent_label, 1, 0, 1, 1)\n\n self._drive_percent_val = QLabel()\n self._drive_percent_val.setAlignment(Qt.AlignRight)\n self.layout().addWidget(self._drive_percent_val, 1, 1, 1, 1)\n\n self._drive_gb_label = QLabel()\n self._drive_gb_label.setAlignment(Qt.AlignLeft)\n self.layout().addWidget(self._drive_gb_label, 2, 0, 1, 1)\n\n self._drive_gb_val = QLabel()\n self._drive_gb_val.setAlignment(Qt.AlignRight)\n self.layout().addWidget(self._drive_gb_val, 2, 1, 1, 1)\n\n self._drive_mb_label = QLabel()\n self._drive_mb_label.setAlignment(Qt.AlignLeft)\n self.layout().addWidget(self._drive_mb_label, 3, 0, 1, 1)\n\n self._drive_mb_val = QLabel()\n self._drive_mb_val.setAlignment(Qt.AlignRight)\n self.layout().addWidget(self._drive_mb_val, 3, 1, 1, 1)\n\n self._strings = dict()\n self.set_lang(lang)\n self._logger.debug(\"Initialized\")\n\n def set_lang(self, lang: LangEnum) -> None:\n \"\"\"\n Set the language for this view object.\n :param lang: The enum for the language.\n :return None:\n \"\"\"\n self._strings = strings[lang]\n self._set_texts()\n\n def set_name_val(self, value: str) -> None:\n \"\"\"\n Set the value for drive name\n :param value: the value to show\n :return: None\n \"\"\"\n self._drive_name_val.setText(value)\n\n def set_perc_val(self, value: str) -> None:\n \"\"\"\n Set the value for percentage\n :param value: the value to show\n :return: None\n \"\"\"\n self._drive_percent_val.setText(value + '%')\n\n def set_gb_val(self, value: str) -> None:\n \"\"\"\n Set the value for gb\n :param value: the value to show\n :return: None\n \"\"\"\n self._drive_gb_val.setText(value)\n\n def set_mb_val(self, value: str) -> None:\n \"\"\"\n Set the value for mb\n :param value: the value to show\n :return: None\n \"\"\"\n self._drive_mb_val.setText(value)\n\n def _set_texts(self) -> None:\n \"\"\"\n Set the text for each element in this view module\n :return: None\n \"\"\"\n self._logger.debug(\"running\")\n self.setTitle(self._strings[StringsEnum.TITLE])\n self._drive_name_label.setText(self._strings[StringsEnum.STORAGE_ID])\n self._drive_percent_label.setText(self._strings[StringsEnum.PERC_USED])\n self._drive_gb_label.setText(self._strings[StringsEnum.GB_FREE])\n self._drive_mb_label.setText(self._strings[StringsEnum.MB_FREE])\n self._drive_name_val.setText('-')\n self._drive_percent_val.setText('0%')\n self._drive_gb_val.setText('0')\n self._drive_mb_val.setText('0')\n self._logger.debug(\"Done\")\n","sub_path":"RSCompanionAsync/View/InfoWidgets/drive_info_box.py","file_name":"drive_info_box.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"319483463","text":"\r\nfrom flask import Flask, make_response,render_template\r\nfrom flask import render_template, request, redirect,send_from_directory\r\nfrom werkzeug.utils import secure_filename\r\nimport json\r\nimport re\r\nimport os\r\n\r\napp = Flask(__name__)\r\n\r\ndef transform(text_file_contents):\r\n config = text_file_contents\r\n parentkey= [*config]\r\n Parent = config[parentkey[0]]\r\n childkeys= [*Parent[0]]\r\n ChildID =childkeys[0]\r\n ChildName =childkeys[1]\r\n\r\n final=[]\r\n for x in Parent:\r\n mod = {}\r\n\r\n syno = x[ChildName].split() \r\n distNameSyno=[]\r\n temp = ''\r\n for i in range(len(syno)):\r\n temp = temp + syno[i] +' '\r\n distNameSyno.append(temp.rstrip())\r\n #m = {\"canonicalForm\":\"distID\",\"list\":[\"distName\"]}\r\n mod[\"canonicalForm\"] = x[ChildID]\r\n mod[\"list\"] = distNameSyno\r\n final.append(mod) \r\n \r\n # remove duplicate synonyms\r\n synoGenerated=[]\r\n for a in final:\r\n mod= {}\r\n newsyno= []\r\n temp= a[\"list\"]\r\n for j in range(len(a[\"list\"])):\r\n t = temp[j].upper()\r\n\r\n count= 0\r\n for b in final:\r\n for k in range(len(b[\"list\"])):\r\n if b[\"list\"][k].upper()==t:\r\n count= count + 1 \r\n\r\n if count == 1 :\r\n #remove tariling characters\r\n if re.search(r\"\\d+.\\d+\",t):\r\n t=re.sub(r\"(?\r\n \r\n

Synonyms generator for LUIS Intents

\r\n\r\n\r\n
\r\n \r\n \r\n
\r\n \r\n \r\n \"\"\"\r\n\r\n@app.route('/transform', methods=[\"POST\"])\r\ndef transform_view():\r\n request_file = request.files['data_file']\r\n myfile = request_file.read()\r\n if not request_file:\r\n return \"No file\"\r\n\r\n file_contents = json.loads(myfile, encoding='utf-8-sig')\r\n result = transform(file_contents)\r\n\r\n outputfile =\"result_\"+ request_file.filename\r\n outputattchment = \"attachment; filename=\" + outputfile\r\n resultres = json.dumps(result,indent=4, sort_keys=True)\r\n response = make_response(resultres)\r\n response.headers['my-custom-header'] = 'my-custom-status-0'\r\n response.headers[\"Content-Disposition\"] = outputattchment\r\n return response\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True) ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"580612514","text":"import argparse\n\nparser = argparse.ArgumentParser(description='manual to this script')\nparser.add_argument('--path', type=str, default = None)\nparser.add_argument('--lang', type=str, default = None)\nparser.add_argument('--src', type=str, default = None)\n\nargs = parser.parse_args()\nsplit_path = args.path.split('.')\nsplit_path.insert(-1, 'context')\nnew_path = '.'.join(split_path)\nlang = args.lang\nsrc = args.src\n\nwith open(args.path, encoding='utf-8') as file_to_bpe:\n sentences = file_to_bpe.readlines()\n context = []\n if lang == src:\n for index in range(len(sentences)-2):\n temp = sentences[index][:-1] + \" [SEP] \" + sentences[index+1][:-1] + \" [SEP] \" + sentences[index+2][:-1] + \"\\n\"\n context.append(temp)\n else:\n for index in range(1, len(sentences)-1):\n temp = sentences[index][:-1] + \"\\n\"\n context.append(temp)\n\nwith open(new_path, encoding='utf-8', mode='w') as new_file:\n for index in range(len(context)):\n new_file.write(context[index])\n\nif lang == src:\n print(\"{} src examples.\".format(len(context)))\nelse:\n print(\"{} tgt examples.\".format(len(context)))\n \nprint('Save to {}'.format(new_path))","sub_path":"make_context_triple.py","file_name":"make_context_triple.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"427691116","text":"import pytest\n\nfrom briefcase.commands import UpdateCommand\nfrom briefcase.config import AppConfig\n\n\nclass DummyUpdateCommand(UpdateCommand):\n \"\"\"\n A dummy update command that doesn't actually do anything.\n It only serves to track which actions would be performend.\n \"\"\"\n platform = 'tester'\n output_format = 'dummy'\n description = 'Dummy update command'\n\n def __init__(self, *args, apps, **kwargs):\n super().__init__(*args, apps=apps, **kwargs)\n\n self.actions = []\n\n def bundle_path(self, app):\n return self.platform_path / '{app.app_name}.dummy'.format(app=app)\n\n def binary_path(self, app):\n return self.platform_path / '{app.app_name}.dummy.bin'.format(app=app)\n\n def distribution_path(self, app):\n return self.platform_path / '{app.app_name}.dummy.dist'.format(app=app)\n\n def verify_tools(self):\n super().verify_tools()\n self.actions.append(('verify',))\n\n # Override all the body methods of a UpdateCommand\n # with versions that we can use to track actions performed.\n def install_app_dependencies(self, app):\n self.actions.append(('dependencies', app))\n with (self.bundle_path(app) / 'dependencies').open('w') as f:\n f.write(\"app dependencies\")\n\n def install_app_code(self, app):\n self.actions.append(('code', app))\n with (self.bundle_path(app) / 'code.py').open('w') as f:\n f.write(\"print('app')\")\n\n def install_app_resources(self, app):\n self.actions.append(('resources', app))\n with (self.bundle_path(app) / 'resources').open('w') as f:\n f.write(\"app resources\")\n\n\n@pytest.fixture\ndef update_command(tmp_path):\n return DummyUpdateCommand(\n base_path=tmp_path,\n apps={\n 'first': AppConfig(\n app_name='first',\n bundle='com.example',\n version='0.0.1',\n description='The first simple app',\n sources=['src/first'],\n ),\n 'second': AppConfig(\n app_name='second',\n bundle='com.example',\n version='0.0.2',\n description='The second simple app',\n sources=['src/second'],\n ),\n }\n )\n\n\n@pytest.fixture\ndef first_app(tmp_path):\n \"Populate skeleton app content for the first app\"\n bundle_dir = tmp_path / \"tester\" / \"first.dummy\"\n bundle_dir.mkdir(parents=True)\n with (bundle_dir / 'Content').open('w') as f:\n f.write(\"first app.bundle\")\n\n\n@pytest.fixture\ndef second_app(tmp_path):\n \"Populate skeleton app content for the second app\"\n bundle_dir = tmp_path / \"tester\" / \"second.dummy\"\n bundle_dir.mkdir(parents=True)\n with (bundle_dir / 'Content').open('w') as f:\n f.write(\"second app.bundle\")\n","sub_path":"tests/commands/update/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"272861284","text":"from copy import deepcopy\nfrom itertools import groupby\n\nfrom .utils import compute_one_match_ranking_data, add_ranking\nfrom ..date_full_dict import DateFullDict\n\nfrom ...client import client\n\n\nclass OneDayRankingData(object):\n\n def __init__(self, matches):\n self.data = {}\n for m in matches:\n self.data.update(compute_one_match_ranking_data(m))\n\n def __repr__(self):\n return str(self.data)\n\n\nclass AggregatedRankingData(object):\n\n def __init__(self):\n self.data = {}\n\n def add_one_day_ranking_data(self, ranking_data):\n for team_id, team_ranking_data in ranking_data.data.items():\n if team_id not in self.data:\n self.data[team_id] = deepcopy(team_ranking_data)\n else:\n for key, val in team_ranking_data.items():\n self.data[team_id][key] += val\n\n\ndef memoize(f):\n memo = {}\n\n def func_wrapper(obj_id):\n if obj_id not in memo:\n memo[obj_id] = f(obj_id)\n return memo[obj_id]\n return func_wrapper\n\n\n@memoize\ndef compute_ranking_data(competition_season_id: int) -> dict:\n \"\"\"Compute ranking data for a given competition id.\n The results of this function are cached after the first computation.\n\n :param competition_season_id (int):\n \"\"\"\n matches = client.matches(competition_season_id=competition_season_id)\n matches_per_date = groupby(matches, lambda m: m.date)\n ranking_data_per_date = {}\n for date, match_group in matches_per_date:\n ranking_data_per_date[date] = OneDayRankingData(match_group)\n aggregated_ranking_data = AggregatedRankingData()\n aggregated_data_per_date = DateFullDict()\n for date in sorted(ranking_data_per_date):\n aggregated_ranking_data.add_one_day_ranking_data(\n ranking_data_per_date[date])\n aggregated_data_per_date[date] = deepcopy(aggregated_ranking_data.data)\n add_ranking(aggregated_data_per_date[date])\n return aggregated_data_per_date\n","sub_path":"sdk/metabet_sdk/lib/ranking/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"565369752","text":"#!/usr/bin/env python\r\nfrom pymongo import MongoClient\r\n\r\nclass Connect(object):\r\n \"\"\"docstring for Connect\"\"\"\r\n def __init__(self, dbname, dbcollection):\r\n self.dbname = dbname\r\n self.dbcollection = dbcollection\r\n client = MongoClient('localhost', 27017)\r\n self.db = getattr(client, dbname)\r\n self._collection = getattr(self.db, dbcollection)\r\n\r\n @property\r\n def collection(self):\r\n return self._collection","sub_path":"conf/confbd.py","file_name":"confbd.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"5539224","text":"from base64 import b64encode\nimport logging\nimport os\nimport subprocess\nimport zipfile\n\nimport requests\n\nfrom django.conf import settings\n\nfrom golem_messages import message\nfrom golem_messages.shortcuts import dump\n\nfrom .constants import UNPACK_CHUNK_SIZE\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef clean_directory(directory_path: str):\n \"\"\" Removes all files from given directory path. \"\"\"\n for file in os.listdir(directory_path):\n file_path = os.path.join(directory_path, file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except OSError as exception:\n logger.warning(f'File {file} in directory {directory_path} was not deleted, exception: {exception}')\n\n\ndef prepare_storage_request_headers(file_transfer_token: message.FileTransferToken) -> dict:\n \"\"\" Prepare headers for request to storage cluster. \"\"\"\n dumped_file_transfer_token = dump(\n file_transfer_token,\n settings.CONCENT_PRIVATE_KEY,\n settings.CONCENT_PUBLIC_KEY,\n )\n headers = {\n 'Authorization': 'Golem ' + b64encode(dumped_file_transfer_token).decode(),\n 'Concent-Auth': b64encode(\n dump(\n message.concents.ClientAuthorization(\n client_public_key=settings.CONCENT_PUBLIC_KEY,\n ),\n settings.CONCENT_PRIVATE_KEY,\n settings.CONCENT_PUBLIC_KEY\n ),\n ).decode(),\n }\n return headers\n\n\ndef store_file_from_response_in_chunks(response: requests.Response, file_path: str):\n with open(file_path, 'wb') as f:\n for chunk in response.iter_content():\n f.write(chunk)\n\n\ndef run_blender(scene_file, output_format, script_file=''):\n return subprocess.run(\n [\n \"blender\",\n \"-b\", f\"{scene_file}\",\n \"-y\", # enable scripting by default\n \"-P\", f\"{script_file}\",\n \"-o\", f\"{settings.VERIFIER_STORAGE_PATH}/{scene_file}_out\",\n \"-noaudio\",\n \"-F\", f\"{output_format.upper()}\",\n \"-t\", f\"{1}\", # cpu_count\n \"-f\", f\"{1}\", # frame\n ],\n timeout=settings.BLENDER_MAX_RENDERING_TIME,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n\n\ndef unpack_archive(file_path):\n \"\"\" Unpacks archive in chunks. \"\"\"\n with zipfile.ZipFile(os.path.join(settings.VERIFIER_STORAGE_PATH, file_path), 'r') as zf:\n infos = zf.infolist()\n for ix in range(0, min(UNPACK_CHUNK_SIZE, len(infos))):\n zf.extract(infos[ix], settings.VERIFIER_STORAGE_PATH)\n zf.close()\n\n\ndef get_files_list_from_archive(file_path):\n \"\"\" Returns list of files from given zip archive. \"\"\"\n return zipfile.ZipFile.namelist(file_path)\n\n\ndef delete_file(file_path):\n file_path = os.path.join(settings.VERIFIER_STORAGE_PATH, file_path)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except OSError as exception:\n logger.warning(f'File with path {file_path} was not deleted, exception: {exception}')\n","sub_path":"concent_api/verifier/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"643517300","text":"__all__ = ['Factor']\n\nclass Factor(dict):\n \"\"\"\n Transit config (or \"factor\")\n All attributes are stored in the dictionary\n \"\"\"\n def __init__(self):\n dict.__init__(self)\n self.comment=''\n\n def __repr__(self):\n s = \"FACTOR \"\n\n fields = []\n for k in sorted(self.keys()):\n fields.append(\"{}={}\".format(k, self[k]))\n\n s += \", \".join(fields)\n s += self.comment\n\n return s\n","sub_path":"Wrangler/Factor.py","file_name":"Factor.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"100606605","text":"\"\"\"example URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.views.static import serve\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.contrib.sitemaps.views import sitemap\nfrom djcms_blog.sitemaps import PostsSitemap\n\nsitemaps = {\n 'blog': PostsSitemap,\n}\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^sitemap\\.xml$', sitemap, {'sitemaps': sitemaps}, name='sitemap'),\n]\n\nurlpatterns += i18n_patterns(\n url(r'^', include('djcms_blog.urls')),\n)\n\n# This is only needed when using runserver.\nif settings.DEBUG:\n urlpatterns = [\n url(r'^media/(?P.*)$', serve,\n {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),\n ] + staticfiles_urlpatterns() + urlpatterns\n urlpatterns = [\n url(r'^static/(?P.*)$', serve,\n {'document_root': settings.STATIC_ROOT, 'show_indexes': True}),\n ] + staticfiles_urlpatterns() + urlpatterns\n\n\n","sub_path":"example_project/example/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"529118821","text":"\"\"\"\n.. module:: storage_drivers.sftp_storage_driver\n :synopsis: SFTP implementation of the base StorageDriver\n\n.. moduleauthor:: Hasan Jawad \n\"\"\"\nimport os\nimport codecs\nimport pysftp\n\nfrom .storage_driver import StorageDriver, StorageDriverError\n\n\nclass SFTPStorageDriver(StorageDriver):\n \"\"\"\n Read and write to SFTP.\n \"\"\"\n\n def __init__(self, host, port, username, password, sftp_root_dir):\n \"\"\"\n Set up the credentials and remote root dir.\n\n :param str host: SFTP host.\n :param int port: SFTP port.\n :param str username: SFTP username.\n :param str password: SFTP password credentials.\n :param str sftp_root_dir: The remote SFTP root dir to use.\n \"\"\"\n super(SFTPStorageDriver, self).__init__()\n\n self.sftp_root_dir = sftp_root_dir\n\n cnopts = pysftp.CnOpts()\n cnopts.hostkeys = None\n self.sftp = pysftp.Connection(\n host=host,\n username=username,\n password=password,\n port=port,\n cnopts=cnopts)\n\n self.sftp.makedirs(self.sftp_root_dir)\n\n def get_filename(self, dag_id, task_id, execution_date):\n return os.path.join(\n self.sftp_root_dir,\n dag_id,\n task_id,\n self.execution_date_string(execution_date)\n )\n\n def get_path(self, dag_id, task_id):\n return os.path.join(self.sftp_root_dir, dag_id, task_id)\n\n def read(self, dag_id, task_id, execution_date, encoding='utf-8'):\n filename = self.get_filename(dag_id, task_id, execution_date)\n\n with self.sftp.open(filename, 'rb') as f:\n data = f.read()\n\n return data\n\n def get_read_stream(self, dag_id, task_id, execution_date):\n filename = self.get_filename(dag_id, task_id, execution_date)\n\n f = self.sftp.open(filename, 'rb')\n return f\n\n def write(self, dag_id, task_id, execution_date, data, *args, **kwargs):\n filename = self.get_filename(dag_id, task_id, execution_date)\n\n self.check_or_create_dir(os.path.dirname(filename))\n\n with self.sftp.open(filename, 'w') as f:\n f.write(data)\n\n def write_from_stream(self, dag_id, task_id, execution_date, stream, *args, **kwargs):\n self.write(dag_id, task_id, execution_date, data=stream.read())\n\n def list_filenames_in_path(self, path):\n return self.sftp.listdir(path)\n\n def check_or_create_dir(self, dir):\n \"\"\"\n Make sure our storage location exists.\n\n :param str dir: The directory name to look for and create if it\n doesn't exist..\n :return:\n \"\"\"\n self.sftp.makedirs(dir)\n","sub_path":"storage_drivers/sftp_storage_driver.py","file_name":"sftp_storage_driver.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"6174525","text":"# Create a simulation tool about multiple-vehicle tracking using UAV\n# Author: HaiLV\n# Email: levanhai2206@gmail.com\n# Date: 10/06/2020\n\nimport cv2\nimport numpy as np\nimport time\n\n# Define a vehicle with line trajectory\nclass lineTrajectory:\n 'linear equations: y=ax+b '\n def __init__(self, startx, a, b, color: (0, 0, 0), speed: int):\n self.startx=startx\n self.a=a\n self.b=b\n self.color=color\n self.speed=speed\n self.current_coordinate = (int(startx),int(a*startx+b))\n self.trajectory=[self.current_coordinate]\n \n def update(self):\n cur_x, cur_y = self.current_coordinate\n new_x = cur_x + self.speed\n new_y = self.a*new_x +self.b\n new_coordinate = (int(new_x),int(new_y))\n self.trajectory.append(new_coordinate)\n self.current_coordinate=new_coordinate\n \n def UAVmoveForward(self, UAVspeed):\n cur_x, cur_y = self.current_coordinate\n new_x = cur_x - UAVspeed\n new_y = cur_y\n new_coordinate = (int(new_x),int(new_y))\n self.current_coordinate = new_coordinate\n \n # def UAVturnRight(self, UAVspeed)\n\ndef drawVehicle(image: np.zeros((640,960,3), np.uint8), center_coordinates, color):\n\n # Radius of circle \n radius = 20\n \n # Line thickness of -1 px \n thickness = -1\n \n # Using cv2.circle() method \n # Draw a circle of red color of thickness -1 px \n image = cv2.circle(image, center_coordinates, radius, color, thickness) \n return image\n\ndef drawMotionVector(image, source, destination):\n # Green color in BGR \n color = (255, 255, 0) \n \n # Line thickness of 9 px \n thickness = 5\n \n # Using cv2.arrowedLine() method \n # Draw a diagonal green arrow line \n # with thickness of 9 px \n image = cv2.arrowedLine(image, source, destination, color, thickness)\n return image\n\ndef drawROI(image, start, end):\n # Blue color in BGR \n color = (0, 255, 255) \n \n # Line thickness of 2 px \n thickness = 2\n \n # Using cv2.rectangle() method \n # Draw a rectangle with blue line borders of thickness of 2 px \n image = cv2.rectangle(image, start, end, color, thickness) \n return image\n\n# Find region of interest - bouding box\ndef findROI(list_vehicle_coordinates:list):\n start_point = ()\n end_point = ()\n x_min = 960\n x_max = 0\n y_min = 640\n y_max = 0\n for vehicle_coordinate in list_vehicle_coordinates:\n if x_max < vehicle_coordinate[0]:\n x_max = vehicle_coordinate[0]\n if x_min > vehicle_coordinate[0]:\n x_min = vehicle_coordinate[0]\n\n if y_max < vehicle_coordinate[1]:\n y_max = vehicle_coordinate[1]\n if y_min> vehicle_coordinate[1]:\n y_min = vehicle_coordinate[1]\n\n start_point = (x_min, y_min)\n end_point = (x_max, y_max)\n return (start_point, end_point)\n\ndef drawPointVehicle(image: np.zeros((640,960,3), np.uint8), center_coordinates, color):\n\n # Radius of circle \n radius = 20\n \n # Line thickness of -1 px \n thickness = -1\n \n # Using cv2.circle() method \n # Draw a circle of red color of thickness -1 px \n image = cv2.circle(image, center_coordinates, radius, color, thickness) \n return image\n\n#Output video\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\noutput_movie = cv2.VideoWriter('simulation.mp4', fourcc, 10, (960, 640))\n\n#initialization vehicles \nvehicle1 = lineTrajectory(0, 0.1, 150, (255, 0, 0), 10)\nvehicle2 = lineTrajectory(50, 0.115, 300, (0, 255, 0), 13)\nvehicle3 = lineTrajectory(20, 0.11, 420, (0, 0, 255), 11)\nvehicle4 = lineTrajectory(-40, 0.099, 320, (180, 80, 255), 10)\n\ni=0\nuav_speed = 0\nuav_icon=cv2.imread('image.jpg',1)\n\n#ACTION \nwhile(1):\n i+=1\n frame = np.zeros((640,960,3), dtype=np.uint8)\n \n #Set Speed of Uav\n if i==50: \n uav_speed = 6\n #Put header text\n #Add icon UAV\n frame[0:40,400:466] = uav_icon\n \n frame = cv2.putText(frame, 'Speed: '+str(uav_speed)+'m/s', (500,30), cv2.FONT_HERSHEY_SIMPLEX , 0.6, (255,255,255), 1, cv2.LINE_AA)\n frame = cv2.putText(frame, 'H: 70m', (680,30), cv2.FONT_HERSHEY_SIMPLEX , 0.6, (255,255,255), 1, cv2.LINE_AA)\n frame = cv2.putText(frame, 'Time: '+str(i), (780,30), cv2.FONT_HERSHEY_SIMPLEX , 0.6, (255,255,255), 1, cv2.LINE_AA)\n\n list_vehicle = [vehicle1.current_coordinate, vehicle2.current_coordinate, vehicle3.current_coordinate, vehicle4.current_coordinate]\n \n frame = drawVehicle(frame, vehicle1.current_coordinate, vehicle1.color)\n vehicle1.update()\n vehicle1.UAVmoveForward(uav_speed)\n\n frame = drawVehicle(frame, vehicle2.current_coordinate, vehicle2.color)\n vehicle2.update()\n vehicle2.UAVmoveForward(uav_speed)\n\n frame = drawVehicle(frame, vehicle3.current_coordinate, vehicle3.color)\n vehicle3.update()\n vehicle3.UAVmoveForward(uav_speed)\n\n frame = drawVehicle(frame, vehicle4.current_coordinate, vehicle4.color)\n vehicle4.update()\n vehicle4.UAVmoveForward(uav_speed)\n\n ROI = findROI(list_vehicle)\n xcenter_ROI = int((ROI[0][0]+ROI[1][0])/2)\n ycenter_ROI = int((ROI[0][1]+ROI[1][1])/2)\n center_ROI =(xcenter_ROI, ycenter_ROI)\n if i >20:\n drawROI(frame, ROI[0], ROI[1])\n frame = cv2.circle(frame, (480,320), 7, (255,255,255), 2) \n if i >30:\n drawMotionVector(frame, (480,320), center_ROI)\n \n if i>50:\n if xcenter_ROI - 480 > -20 and uav_speed <= 15:\n uav_speed+=2\n if xcenter_ROI - 480 < 20 and uav_speed >=8:\n uav_speed-=1\n \n \n print(uav_speed)\n print(findROI(list_vehicle))\n print(vehicle1.current_coordinate)\n\n cv2.imshow('frame',frame)\n output_movie.write(frame)\n time.sleep(0.2)\n # Press 'q' to quit\n if cv2.waitKey(1) == ord('q'):\n break\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"multiple_following.py","file_name":"multiple_following.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"309468082","text":"#-*- coding: utf-8 -*-\n\nimport requests\nimport bs4\nimport re\nimport jpype\n#from konlpy.tag import Kkma\nfrom konlpy.tag import Mecab\n\nfrom .logic_adapter import LogicAdapter\nfrom cbot.conversation import Statement\nfrom textblob.classifiers import NaiveBayesClassifier\n\nclass ShopnaverLogicAdapter(LogicAdapter):\n \"\"\"\n The TimeLogicAdapter returns the current time.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(ShopnaverLogicAdapter, self).__init__(**kwargs)\n\n training_data = [\n (\"찾아줘\", 1),\n (\"찾다\", 1),\n (\"찾아주세요\", 1),\n (\"구입 구매해줘 싸줘\", 1),\n (\"알아봐줘\", 1),\n (\"검색해줘\", 1),\n (\"검색\", 1),\n (\"검색 또봇\", 1),\n (\"쇼핑 검색 구매\", 1),\n (\"추천해주세요\", 1),\n (\"싼 화환을 보내줘\", 1),\n (\"꽃배달\", 1),\n (\"결혼식장에 꽃배달을 부탁해\", 1),\n (\"싼꽃배달\", 1),\n (\"꽃만들기\", 0),\n (\"꽃제작\", 0),\n (\"화환제작\", 0),\n (\"공방\", 0),\n (\"제작\", 0)\n ]\n\n \"\"\"\n (\"what time is it\", 1),\n (\"do you know the time\", 1),\n (\"do you know what time it is\", 1),\n (\"what is the time\", 1),\n (\"do you know the time\", 0),\n (\"it is time to go to sleep\", 0),\n (\"what is your favorite color\", 0),\n (\"i had a great time\", 0),\n (\"what is\", 0)\n \"\"\"\n\n self.classifier = NaiveBayesClassifier(training_data)\n\n def can_process(self, statement):\n \"\"\"\n Determines whether it is appropriate for this\n adapter to respond to the user input.\n \"\"\"\n confidence, response = self.process(statement)\n print(\" navershop:: confidence:%s, response:%s\" % (confidence, response))\n return confidence == 1\n\n def process(self, statement):\n\n confidence = self.classifier.classify(statement.text.lower())\n user_input = statement.text\n\n #print(\"user_input:%s\" % user_input)\n\n # kkma = Kkma()\n # nouns = kkma.nouns(user_input)\n # print(nouns)\n #\n # if \"쇼핑\" not in nouns:\n # return 0, Statement(\"\")\n\n mecab = Mecab()\n nouns = mecab.nouns(user_input)\n print(\"Mecab 입력된 명사들:%s\" % (nouns))\n noSearchlist = ['쇼핑', '검색', '구매']\n searchlist = list(set(nouns) - set(noSearchlist)) # 순서 보존이 안됨\n # 또는\n #s = set(temp2)\n #temp3 = [x for x in temp1 if x not in s] # 순서 보존됨\n\n responsetxt = \"\"\n for keyword in searchlist:\n responsetxt += self.navershopsearch(keyword) + \"\\n\"\n #return 0, Statement(\"\")\n\n if responsetxt == \"\":\n confidence = 0\n response = Statement(responsetxt)\n return confidence, response\n\n\n def navershopsearch(self, keyword):\n\n NAVER_SHOPPING_URL = \"http://shopping.naver.com/search/all_search.nhn\"\n data = requests.get(NAVER_SHOPPING_URL,\n params={\n 'query': keyword\n # 여기에 추후에 가격정보나 다른 파라미터 추가\n })\n\n #print(\"data:%s\" % data.text)\n try:\n bs_data = bs4.BeautifulSoup(data.text)\n\n # first_price = bs_data.findAll(\"span\", attrs={'class': ['num', 'price_reload']})\n # print(first_price[0])\n # 이 경우에 숫자들이 전부 출력되는 문제가 발생한다.\n # 정성적으로 접근해서 차근차근 풀어가보자.\n\n \"\"\"\n # 이건 첫번째 아이템 뿐만 아니라,\n # 모든 아이템에 대한 정보를 가지고 온다.\n items = bs_data.find_all(\"li\", attrs={'class': '_model_list'})\n for item in items:\n price_span = item.find(\"span\", attrs={'class': 'price'})\n min_price = price_span.find(\"span\",\n attrs={\n 'class': ['num', 'price_reload']\n }).text\n print(min_price)\n \"\"\"\n try:\n item = bs_data.find(\"li\", attrs={'class': '_model_list'})\n except:\n try:\n item = bs_data.find(\"li\", attrs={'class': '_product_list'})\n except:\n print(\"검색어 1 :%s 로 naver shop 검색하면서 오류가 발생하였습니다.\" % (keyword))\n response = Statement(\"\")\n return response\n\n price_span = item.find(\"span\", attrs={'class': 'price'})\n min_price = price_span.find(\"span\",\n attrs={\n 'class': ['num', 'price_reload']\n }).text\n\n image_url = bs_data.find(\"img\", attrs={'class': '_productLazyImg'})[\"src\"].split(\"?\")[0]\n\n info_span = item.find(\"div\", attrs={'class': 'info'})\n info_title = info_span.find(\"a\",\n attrs={\n 'class': 'tit'\n }).text\n\n\n response = \"'\"+ keyword + \"' 추천정보 : \\n\"+info_title+\" : \"+ min_price+\"원 이며,\\n 이미지 \"+ image_url +\" 입니다.\"\n except:\n print(\"검색어 2 :%s 로 naver shop 검색하면서 오류가 발생하였습니다.\" % (keyword))\n response = \"\"\n #pass\n\n return response","sub_path":"cbot/adapters/logic/shopnaver_adapter.py","file_name":"shopnaver_adapter.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"440141101","text":"from PIL import Image, ImageDraw\nimport os, sys\nimport numpy as np\nfrom keras.models import load_model\n\ndirs = os.getcwd() + '/public/oldpic.png'\n\nmodel = load_model('public/Corn CNN.h5')\n\nmodel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\ndef crop():\n original_image = Image.open(dirs) #Opens the full size image\n width, height = original_image.size\n \n for x in range(0,width,50):\n for y in range(0,height,50):\n \n #crop(left,upper,right,lower)\n cropped_image = original_image.crop((x,y,x+100,y+100)) #Makes a 50x50 crop of the original image\n boxed_corn_image = ImageDraw.Draw(original_image) #Allows the full size image to have boxes drawn on it\n \n\n cropped_image = np.expand_dims(cropped_image, axis=0)\n \n if (model.predict(cropped_image) != 1):\n start_point = (x, y) \n end_point = (x + 100,y + 100) \n color = (255, 0, 0) \n thickness = 50\n \n boxed_corn_image.rectangle((start_point, end_point), fill=None, outline = color)\n \n original_image.save(\"public/newPic.png\",'PNG',quality=100)\n\nif __name__ == \"__main__\":\n crop()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"393120800","text":"# coding=utf-8\nimport os\nimport argparse\n\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('-root', '--dataset_root',\n type=str,\n help='path to dataset',\n default='../../data/tabula_muris')\n\n parser.add_argument('-exp', '--experiment_root',\n type=str,\n help='root where to store models, losses and accuracies',\n default='..' + os.sep + 'output')\n\n parser.add_argument('-nep', '--epochs',\n type=int,\n help='number of epochs to train for',\n default=100)\n\n parser.add_argument('-testep', '--test_epochs',\n type=int,\n help='number of epochs to test for',\n default=20)\n\n parser.add_argument('-lr', '--learning_rate',\n type=float,\n help='learning rate for the model, default=0.001',\n default=0.001)\n\n parser.add_argument('-lrS', '--lr_scheduler_step',\n type=int,\n help='StepLR learning rate scheduler step, default=20',\n default=20)\n\n parser.add_argument('-lrG', '--lr_scheduler_gamma',\n type=float,\n help='StepLR learning rate scheduler gamma, default=0.5',\n default=0.5)\n\n parser.add_argument('-its', '--iterations',\n type=int,\n help='number of episodes per epoch, default=100',\n default=100)\n\n parser.add_argument('-cTr', '--classes_per_it_tr',\n type=int,\n help='number of random classes per episode for training, default=20',\n default=20)\n\n parser.add_argument('-nsTr', '--num_support_tr',\n type=int,\n help='number of samples per class to use as support for training, default=5',\n default=5)\n\n parser.add_argument('-nqTr', '--num_query_tr',\n type=int,\n help='number of samples per class to use as query for training, default=5',\n default=15)\n\n parser.add_argument('-cVa', '--classes_per_it_val',\n type=int,\n help='number of random classes per episode for validation, default=5. Setting this to a very '\n 'high number will use all available classes in validation.',\n default=5)\n\n parser.add_argument('-nsVa', '--num_support_val',\n type=int,\n help='number of samples per class to use as support for validation, default=5',\n default=5)\n\n parser.add_argument('-nqVa', '--num_query_val',\n type=int,\n help='number of samples per class to use as query for validation, default=15',\n default=15)\n\n parser.add_argument('-cTe', '--classes_per_it_test',\n type=int,\n help='number of random classes per episode for test, default=5. Setting this to a very '\n 'high number will use all available classes in validation.',\n default=5)\n\n parser.add_argument('-nsTe', '--num_support_test',\n type=int,\n help='number of samples per class to use as support for test, default=5',\n default=5)\n\n parser.add_argument('-nqTe', '--num_query_test',\n type=int,\n help='number of samples per class to use as query for test, default=15',\n default=15)\n\n parser.add_argument('-seed', '--manual_seed',\n type=int,\n help='input for the manual seeds initializations',\n default=7)\n\n parser.add_argument('--cuda',\n type=bool,\n help='enables cuda',\n default=False)\n\n parser.add_argument('-gid', '--gpu_id',\n type=int,\n help='cuda dvice id',\n default=0)\n\n parser.add_argument('-arch', '--nn_architecture',\n type=str,\n help='Support convolutional (conv) or fully connected network (fully_connected).',\n default='fully_connected')\n\n parser.add_argument('-split', '--split_file',\n type=str,\n help='File that defines train, test, val split.',\n default=None)\n\n parser.add_argument('-res', '--test_result_file',\n type=str,\n help='File that the test results are written to.',\n default='test_metrics.txt')\n\n return parser\n","sub_path":"src/parser_util.py","file_name":"parser_util.py","file_ext":"py","file_size_in_byte":5113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"385682712","text":"import numpy as np\nfrom math import *\n\nclass Matrix(object):\n '''Una matriz construida a partir de una lista de listas usando numpy\n Attributes:\n matriz (ndarray): Arreglo de numpy\n m (int): Numero de filas\n n (int): Numero de columnas\n '''\n def __init__(self, arr):\n '''\n Args:\n arr (list): Una lista de listas\n '''\n self.matriz = np.array(arr)\n # self.m = len(arr)\n # self.n = len(arr[0])\n\n def __str__(self):\n return str(self.matriz)\n\n # def get_dimensions(self):\n # return self.m, self.n\n\n def inner_product(self, other):\n '''\n Args:\n other (Matrix): Matriz con la cual hacer producto punto\n Returns:\n float: Resultado del producto punto\n '''\n return np.sum(self.matriz * other.matriz)\n\n def norm(self):\n '''float: Norma de la matriz'''\n return sqrt(self.inner_product(self))\n\n def angle(self,other):\n '''\n Args:\n other (Matrix): otra matriz\n\n Returns:\n float: Ángulo en grados\n '''\n dot = self.inner_product(other)\n normU = self.norm()\n normV = other.norm()\n\n angle = acos(dot/(normU * normV))\n #convertimos a grados\n angle *= (180/pi)\n return angle\n\n\n\nclass Vector(Matrix):\n '''Subclase de Matriz, la verdad que esto es super redundante'''\n # Literal hará _lo mismo_ que Matrix, pero bajo el nombre de vector\n pass\n\ndef test():\n m = int(input(\"Ingresa m: \"))\n n = int(input(\"Ingresa n: \"))\n\n # La list comprehension en Python es la pura magia\n lista1 = [[float(input(\"Ingresa el componente [{},{}]: \".format(i, j))) for j in range(n)] for i in range(m)]\n M = Matrix(lista1)\n print(M)\n\n lista2 = [[1,2],[1,2]]\n lista3 = [[2,3],[2,3]]\n\n A = Matrix(lista2)\n B = Matrix(lista3)\n\n res = A.inner_product(B)\n print(res)\n\n lista4 = [1,1]\n v = Vector(lista4)\n magnitud = v.norm()\n print(magnitud)\n\n lista5 = [1, 0]\n u= Vector(lista5)\n\n angulo = v.angle(u)\n print(angulo)\n\n\nif __name__ == \"__main__\":\n test()\n\n","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"1569936","text":"\"\"\"Validator class for the Interface model.\"\"\"\n\nimport re\n\nfrom extras.validators import CustomValidator\n\nNETWORK_ROLES = (\"asw\", \"cr\", \"mr\", \"pfw\", \"cloudsw\")\n\n# For ergonomics the regexps that match interface names are placed in this tuple.\nINTERFACES_REGEXP = re.compile(\n (\n r\"|\".join(\n (\n r\"^fxp\\d-re\\d$\", # routing engine management\n r\"^[a-z]{2}-\\d+/\\d+/\\d+(:\\d+){0,1}(\\.\\d+){0,1}$\", # Juniper (eg et-0/0/0:0.0)\n r\"^[a-z]{1,4}(\\d+){0,1}(\\.\\d+){0,1}$\", # typical device names (eg. eth0, vlan.900, etc)\n r\"^\\d+$\", # Netgear switch (just numbers)\n r\"^Ethernet\\d+$\", # SONiC (eg. Ethernet1)\n r\"^Loopback\\d+$\", # SONiC (eg. Loopback0)\n r\"^Management\\d+$\", # SONiC (eg. Management0)\n r\"^Vlan\\d+$\", # SONiC (eg. Vlan1234)\n )\n )\n )\n)\n\n\nclass Main(CustomValidator):\n \"\"\"Main class referenced in the Netbox config\"\"\"\n\n def validate(self, instance):\n \"\"\"Mandatory entry point\"\"\"\n # Name\n if (\n instance.device.device_role.slug in NETWORK_ROLES\n and not INTERFACES_REGEXP.fullmatch(instance.name)\n ):\n self.fail(\"Invalid name (must match the INTERFACES_REGEXP options)\")\n\n # MTU\n if (\n hasattr(instance.connected_endpoint, \"device\")\n and instance.device.device_role.slug in NETWORK_ROLES # Network devices\n and instance.mtu != 9192 # Ignore good MTU\n and not instance.lag # Ignore LAG members\n and not (\n instance.device.tenant and instance.device.tenant.slug == \"fr-tech\"\n ) # Ignore frack devices\n and instance.enabled # Ignore disabled interfaces\n and not str(instance.name).startswith(\"vcp-\")\n ): # Ignore VC links\n self.fail(\"Invalid MTU (must be 9192)\")\n\n # Attributes\n attributes = [\n \"description\",\n \"lag\",\n \"mtu\",\n \"mode\",\n \"mac_address\",\n \"count_ipaddresses\",\n ]\n if (\n \"no-mon\"\n not in str(instance.description) # doesn't have \"no-mon\" in description\n and not instance.enabled # disabled interface\n and instance.device.device_role.slug in NETWORK_ROLES\n ): # network devices only\n for attribute in attributes:\n # Workaround bug T310590#8851738\n # At creation time, count_ipaddresses is briefly at 246 then goes back to 0\n if attribute == \"count_ipaddresses\" and not instance.id:\n continue\n if getattr(instance, attribute):\n self.fail(\n f\"Invalid {attribute} (must not be set on disabled interfaces)\"\n )\n","sub_path":"validators/dcim/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"404971889","text":"\"\"\"\n\nDerive a scaling between the values in the\nflux limit cubes and the completeness\nsimulations Gebhardt ran.\n\nDaniel Farrow (MPE) 2020\n\n\"\"\"\n\nfrom numpy import loadtxt, savetxt, transpose, interp, sqrt, mean, linspace, zeros\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom scipy.special import erf\nfrom scipy.optimize import leastsq\nfrom hetdex_api.flux_limits.hdf5_sensitivity_cubes import (return_biweight_one_sigma, return_sensitivity_hdf_path,\n SensitivityCubeHDF5Container)\nfrom hetdex_api.flux_limits.sensitivity_cube import fleming_function\nfrom hetdex_api.flux_limits.flim_models import (hdr2pt1_f50_from_noise, SimulationInterpolator, \n hdr2pt1pt1_f50_from_noise)\n\nmpl.rcParams[\"xtick.direction\"] = \"in\"\nmpl.rcParams[\"ytick.direction\"] = \"in\"\nmpl.use('tkagg')\n\nSQRT2 = sqrt(2.0)\n\ndef gaussian_det_frac(snr, snr_cut):\n \"\"\"\n Fraction of sources detected assuming\n a Gaussian noise field\n\n \"\"\" \n\n return 0.5*erf((snr - snr_cut)/SQRT2) + 0.5\n\ndef func(alpha, fluxes, tf50, data):\n \"\"\" Function for scipy leastsq to minimize \"\"\"\n model = fleming_function(fluxes, tf50, alpha) \n return model - data\n\ndef func_f50s(rescale, f50s, f50_pred):\n \"\"\" Function for scipy leastsq to minimize \"\"\"\n return f50s - rescale*f50_pred\n\ndef read_karl_file(fn):\n \"\"\" \n Read in the results from\n Karl's simulation\n \"\"\"\n karl_det_file = loadtxt(\"fcor.use\")\n waves = karl_det_file[0,1:]\n f50 = karl_det_file[1,1:]\n compl_curves = karl_det_file[2:, 1:].T\n fluxes = karl_det_file[2:, 0]\n\n return waves, f50, compl_curves, fluxes\n\n\ndef plot_f50(waves, f50, wlcube, sigma_cube):\n \"\"\"\n Plot the 50% compleness values and the\n sigma values from the flux limit\n cubes\n \"\"\"\n FS = 12.0\n plt.plot(wlcube, 1e17*hdr2pt1_f50_from_noise(sigma_cube, 5.0), \"b:\", \n label=\"HDR2.1 scaled sigmas (S/N=5.0)\")\n plt.plot(wlcube, 5e17*sigma_cube, \"k--\", \n label=\"5$\\sigma$ from cubes\")\n\n # fit a new scaling\n sigma_f50_pos = interp(waves, wlcube, sigma_cube)\n best, info = leastsq(func_f50s, [5.0], args=(f50[1:], 1e17*sigma_f50_pos[1:]))\n print(best[0], best[0]/hdr2pt1_f50_from_noise(1.0, 5.0))\n\n plt.plot(wlcube, 1e17*best[0]*sigma_cube, \"g-\", \n label=\"New scaling ({:3.2f}\".format(best[0]) + \"$\\sigma$)\")\n plt.plot(waves, f50, \"r*\", label=\"Karl sims\", markersize=9.0)\n\n plt.xlabel(\"Wavelength [AA]\", \n fontsize=FS)\n plt.ylabel(r\"50\\% flux [10$^{-17} erg/s/cm$^2$]\", \n fontsize=FS)\n\ndef return_completeness_from_shots(shots, fluxes, lambda_low, lambda_high,\n sncut, rescale_50 = None):\n \"\"\"\n Return the completeness over a range\n of shots\n\n \"\"\"\n\n bin_edges = linspace(0, 1e-16, 1000)\n bins = 0.5*(bin_edges[:-1] + bin_edges[1:])\n nbinned = zeros(len(bin_edges) - 1)\n\n cube_comp_all = []\n for shot in shots:\n fn, fnmask = return_sensitivity_hdf_path(shot, return_mask_fn = True)\n\n with SensitivityCubeHDF5Container(fn, mask_filename = fnmask) as hdf:\n cube_compl, tnbinned = hdf.return_shot_completeness(fluxes*1e-17, lambda_low, \n lambda_high, sncut,\n bin_edges = bin_edges)\n # rescale curve so 50% flux at rescale_50\n if rescale_50:\n f50 = interp(0.5, cube_compl/cube_compl[-1], fluxes)\n cube_compl = interp(fluxes, rescale_50*fluxes/f50, cube_compl) \n\n nbinned += tnbinned\n\n cube_comp_all.append(cube_compl)\n \n return mean(cube_comp_all, axis=0), bins, nbinned\n\n\ndef plot_completeness_curves(waves, f50, fluxes, compl_curves, shots):\n \n FS = 13.0\n alpha_fix = -3.5 \n\n alphas_fit = []\n colors =['r', 'g', 'b', 'k', 'm', 'c', 'y']\n\n fig1, ax1 = plt.subplots(nrows = 2, ncols = 4, \n figsize=(14.0, 7))\n fig2, ax2 = plt.subplots(nrows = 1, ncols = 1)\n ax1 = ax1.flatten()\n\n for i, (col, wl, tf50, compl) in enumerate(zip(colors, waves, f50, compl_curves)):\n\n sinterp = SimulationInterpolator(\"fcor.use\")\n #model = compl[-2]*sinterp(fluxes, tf50) \n\n rerun = True\n if rerun:\n\n wllo = wl - 272\n if wllo < 3500:\n wllo = 3500\n\n compl_hdfs, bins, noise_hist = return_completeness_from_shots(shots, fluxes, \n wllo, wl + 272,\n 5.0,\n rescale_50 = tf50)\n savetxt(\"av_cube_completeness_cal_{:4.1f}_rescale.txt\".format(wl), \n transpose([fluxes, compl_hdfs]))\n #savetxt(\"noise_hist_{:4.1f}.txt\".format(wl), \n # transpose([bins, noise_hist])) \n else:\n fluxes_check, compl_hdfs = loadtxt(\"av_cube_completeness_cal_{:4.1f}_rescale.txt\".format(wl), \n unpack=True)\n bins, noise_hist = loadtxt(\"noise_hist_{:4.1f}.txt\".format(wl),\n unpack = True)\n\n assert all((fluxes_check - fluxes)/fluxes < 1e-6) \n\n ax1[i].text(20, 0.2, r\"$\\lambda=\" + \"{:4.0f}\".format(wl) + r\"\\,\\mathrm{A}$\", fontsize=FS)\n ax1[i].plot(fluxes, compl, color=col, label=\"{:4.0f}\".format(wl))\n ax1[i].plot(fluxes, compl_hdfs, \"--\", color=col)\n ax1[i].axhline(1.0, color=\"k\", linestyle=\":\")\n\n if i > 3:\n ax1[i].set_xlabel(r\"flux [10$^{-17}$ erg/s/cm$^2$]\",\n fontsize=FS)\n \n ax1[7].plot(fluxes, (compl_hdfs - compl)/compl, color=col, label=None)\n\n ax2.plot(1e17*bins, noise_hist, color=col, label=\"{:4.0f}\".format(wl))\n\n\n ax1[0].set_ylabel(\"Completeness\", fontsize=FS)\n ax1[4].set_ylabel(\"Completeness\", fontsize=FS)\n\n ax1[7].set_ylabel(\"(Model - Sim.)/Sim.\", fontsize=FS)\n ax1[7].set_xlabel(r\"flux [10$^{-17}$ erg/s/cm$^2$]\",\n fontsize=FS)\n \n ax1[7].axhline(0.0, color=\"k\", linestyle=\":\")\n ax1[7].set_ylim(-1.0, 1.0)\n fig1.subplots_adjust(left=0.07, right=0.95, \n wspace=0.35, top=0.98)\n #plt.tight_layout()\n\n ax2.set_ylabel(\"N pixels\", fontsize=FS) \n ax2.set_xlabel(\"Noise [10^{-17} erg/s/cm^{-2}]\", fontsize=FS) \n ax2.legend(frameon=False, prop={\"size\" : FS})\n\n return None\n #return alphas_fit\n\nif __name__ == \"__main__\":\n\n waves, f50, compl_curves, fluxes = read_karl_file(\"fcor.use\")\n \n with open(\"calshots\", 'r') as fp:\n rshots = fp.readlines()\n \n shots = [x.strip() for x in rshots]\n\n remeasure = False \n if remeasure: \n wlcube, sigma_cube = return_biweight_one_sigma(shots)\n savetxt(\"average_one_sigma_cal.txt\", transpose([wlcube, sigma_cube]))\n else:\n wlcube, sigma_cube = loadtxt(\"average_one_sigma_cal.txt\").T\n\n\n #plt.figure(figsize=(11,4))\n #plot_f50(waves, f50, wlcube, sigma_cube)\n #plt.xlim(3600, 5500.)\n #plt.ylim(0, 30)\n #plt.legend(frameon=False, prop={\"size\" : 12.0})\n #plt.tight_layout()\n \n plot_completeness_curves(waves, f50, fluxes, compl_curves, shots)\n plt.tight_layout()\n plt.show()\n #plt.savefig(\"curves_with_model.png\") \n\n #plt.figure()\n #plt.plot(waves, alphas, \"k*\")\n #plt.xlabel(\"Wavelength\")\n #plt.ylabel(\"alpha\")\n #plt.show()\n \n #plt.show()\n","sub_path":"hetdex_tools/cal_on_karl_results.py","file_name":"cal_on_karl_results.py","file_ext":"py","file_size_in_byte":7654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"143454846","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 3 15:46:23 2020\r\n\r\n@author: 320054667\r\n\"\"\"\r\n\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport dash_bootstrap_components as dbc\r\nimport data_n_graphs as grf\r\n\r\npage_title = dbc.Row([dbc.Col(html.H2(\"Syamanthaka Balakrishnan\", style={'text-align' : 'center'}), width=12)])\r\n\r\n#----------------------------------------------------------- \r\ncareer_timeline = dbc.Card(children=[\r\n dbc.CardHeader(html.H5(\"Career Timeline\")),\r\n dbc.CardBody([\r\n dcc.Graph(id=\"career_tl\", \r\n figure = grf.career_tl\r\n ) \r\n ])\r\n])\r\n#-----------------------------------------------------------\r\n \r\nrow1_cards = dbc.Row([dbc.Col(career_timeline, width=12)], no_gutters=True)\r\n\r\ntab1_content = dbc.Container([\r\n row1_cards,\r\n# row2_cards,\r\n# row3_cards,\r\n# row5_cards\r\n], fluid=True)\r\n\r\ntabs = dbc.Tabs([\r\n dbc.Tab(tab1_content, label=\"Home\"),\r\n# dbc.Tab(erl.tab2_content, label=\"Error Analytics\"),\r\n# dbc.Tab(prl.prot_tab_content, label=\"Protocols\")\r\n])\r\n\r\nmain_page = dbc.Container([\r\n page_title,\r\n tabs\r\n], fluid=True)","sub_path":"Dashboard_SB/layouts.py","file_name":"layouts.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"178128221","text":"from collections import deque\r\nimport numpy as np\r\nfrom model import Model as m\r\nfrom larva_factory import larva_factory\r\nfrom arena import Arena\r\nfrom disperse_arena import DisperseArena\r\nfrom view_factory import view_factory\r\nfrom util import Error\r\n\r\ncommands_help_text = \"\"\"Commands:\r\na \r\n Adds a larva with initial position (pos_x, pos_y) and initial crawl\r\n velocity (vel_x, vel_y).\r\n Example: a OriginalLarva 2 3 1 1\r\n\r\nar \r\n Creates an arena with a non-dispersing source at position (pos_x, pos_y)\r\n and an source strength and standard deviation of sigma.\r\n Example: ar 0 0 10 5\r\n\r\nad \r\n Creates an arena with a dispersing source at position (pos_x, pos_y) and\r\n an initial source strength and intial standard deviation of sigma.\r\n Example: ad 0 0 10 5\r\n\r\nv\r\n Toggles verbosity.\r\n\r\nr []\r\n Runs the simulation for n_steps number of iterations. If n_steps is not\r\n given the simulation will run for a single time step.\r\n Example: r 100\r\n\r\np\r\n Prints out the current location and velocity vector of the larva.\r\n\r\nav \r\n Attaches a view to the controller. Valid options for view_type are:\r\n ArenaView\r\n TableView\r\n StatsView\r\n MovementStatsView\r\n PerceptionView\r\n Example: av ArenaView\r\n\r\nd \r\n Draws the specified view. If 'all' is given instead of a view_type, all\r\n attached views will be drawn.\r\n Example: d ArenaView\r\n\r\ne \r\n Export the specified view_type to the location given by output_path. The\r\n default format for images is .png while the default format for text is\r\n .txt.\r\n Example: e TableView tableAsFile.txt\r\n\"\"\"\r\n\r\nclass Controller:\r\n # Function dispatch table:\r\n # TODO: modify the 'p' = 'print_larva' function to be a command that\r\n # prints descriptions of ALL simulation objects.\r\n command_fcns = {'a': 'add_larva',\r\n 'ar': 'add_arena',\r\n 'ad': 'add_disperse_arena',\r\n 'v': 'toggle_verbosity',\r\n 'r': 'run_model',\r\n 'p': 'print_larva',\r\n 'av': 'attach_view',\r\n 'd': 'draw_view',\r\n 'e': 'export_view'}\r\n\r\n def __init__(self):\r\n self.all_views = {}\r\n\r\n def run(self, input_file):\r\n \"\"\"Run loop\r\n \"\"\"\r\n input_from_file = deque()\r\n # Get any input given from file\r\n if input_file:\r\n input_from_file = deque([line.rstrip('\\n') for line in open(input_file)])\r\n\r\n while True:\r\n try:\r\n input_str = ''\r\n # First read any commands given from a file, then begin to\r\n # take user input\r\n if len(input_from_file):\r\n input_str = input_from_file.popleft()\r\n else:\r\n input_str = input('Time: {0:.1f}, Enter command: '.format(m.get_instance().time))\r\n inputs = deque(input_str.split())\r\n cmd = 'h'\r\n if len(inputs):\r\n cmd = inputs.popleft()\r\n if cmd == 'q':\r\n print('Quiting')\r\n return\r\n if cmd == 'h':\r\n print(commands_help_text)\r\n continue\r\n fcn_name = self.command_fcns.get(cmd)\r\n if not fcn_name:\r\n raise Error('Invalid input!')\r\n continue\r\n fcn = getattr(self, fcn_name)\r\n fcn(inputs)\r\n except Error as err:\r\n print(err)\r\n except:\r\n print('Unexpected error!')\r\n raise\r\n\r\n def add_larva(self, args):\r\n \"\"\"Add a larva with specified characteristics\r\n \r\n Example:\r\n 'a NewLarva 1 1 1 1'\r\n or\r\n 'a OriginalLarva 1 1 1 1'\r\n \"\"\"\r\n larva_type = args.popleft()\r\n loc_x = float(args.popleft())\r\n loc_y = float(args.popleft())\r\n vel_x = float(args.popleft())\r\n vel_y = float(args.popleft())\r\n new_larva = larva_factory(larva_type, np.array([loc_x, loc_y]), np.array([vel_x, vel_y]))\r\n m.get_instance().add_larva(new_larva)\r\n print('Added a larva: ' + str(new_larva))\r\n\r\n def add_arena(self, args):\r\n loc_x = float(args.popleft())\r\n loc_y = float(args.popleft())\r\n strength = float(args.popleft())\r\n decay_rate = float(args.popleft())\r\n new_arena = Arena(source_position=np.array([loc_x, loc_y]), source_strength=strength, source_decay_rate=decay_rate)\r\n m.get_instance().add_arena(new_arena)\r\n print('Added Arena: ' + str(new_arena))\r\n \r\n def add_disperse_arena(self, args):\r\n loc_x = float(args.popleft())\r\n loc_y = float(args.popleft())\r\n strength = float(args.popleft())\r\n sigma = float(args.popleft())\r\n new_arena = DisperseArena(source_position=np.array([loc_x, loc_y]), source_strength=strength, sigma=sigma)\r\n m.get_instance().add_arena(new_arena)\r\n print('Added Arena: ' + str(new_arena))\r\n\r\n def toggle_verbosity(self, args):\r\n \"\"\"Toggle if Larva prints on each update\r\n \"\"\"\r\n for l in m.get_instance().larvae:\r\n l.verbose = not l.verbose\r\n\r\n def run_model(self, args):\r\n \"\"\"Run specified number of iterations, or just one if no arg given\r\n \"\"\"\r\n iters = 0\r\n if not len(args):\r\n iters = 1\r\n else:\r\n iters = int(args.popleft())\r\n print('Running ' + str(iters) + ' iteration(s)')\r\n for i in range(iters):\r\n m.get_instance().update()\r\n\r\n def print_larva(self, args):\r\n larvae = m.get_instance().larvae\r\n for i in range(0,len(larvae)):\r\n print('Larva {0} {1}'.format(i + 1, larvae[i]))\r\n if len(larvae) == 0:\r\n print('Nothing to print.')\r\n\r\n def get_attached_view(self, view_type_str):\r\n \"\"\"Helper function that retreives an already attached view\r\n\r\n Throws an error if the view is not attached.\r\n \"\"\"\r\n view = self.all_views.get(view_type_str)\r\n if not view:\r\n raise Error('Not an attached view!')\r\n return view\r\n\r\n def attach_view(self, args):\r\n \"\"\"Attach a specified view to the Model\r\n\r\n Example:\r\n 'av ArenaView'\r\n \"\"\"\r\n view_type = args.popleft()\r\n if self.all_views.get(view_type):\r\n raise Error('View already attached!')\r\n view = view_factory(view_type)\r\n m.get_instance().attach(view)\r\n self.all_views[view_type] = view\r\n\r\n def draw_view(self, args):\r\n \"\"\"Draw a specific view (or all views)\r\n\r\n Example:\r\n 'd ArenaView'\r\n or\r\n 'd all'\r\n \"\"\"\r\n view_type = args.popleft()\r\n if view_type == 'all':\r\n # Draw all the views\r\n for v in self.all_views.values():\r\n v.draw()\r\n else:\r\n # Draw just the specified view\r\n view = self.get_attached_view(view_type)\r\n view.draw()\r\n\r\n def export_view(self, args):\r\n \"\"\"Export the specified view to a file\r\n\r\n Example:\r\n 'e TableView tableAsFile.txt'\r\n \"\"\"\r\n view_type = args.popleft()\r\n path = args.popleft()\r\n view = self.get_attached_view(view_type)\r\n view.export(path)\r\n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":7620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"278488077","text":"import numpy as np\nimport math\nimport pandas as pd\n\n\nclass Util:\n \"\"\"database column names\"\"\"\n # basic\n DT_DATE = 'dt_date'\n DT_DATETIME = 'dt_datetime'\n CODE_INSTRUMENT = 'code_instrument'\n ID_INSTRUMENT = 'id_instrument'\n ID_FUTURE = 'id_future'\n\n # option\n DT_MATURITY = 'dt_maturity'\n ID_UNDERLYING = 'id_underlying'\n CD_OPTION_TYPE = 'cd_option_type'\n NAME_CONTRACT_MONTH = 'name_contract_month'\n AMT_STRIKE = 'amt_strike'\n AMT_STRIKE_BEFORE_ADJ = 'amt_strike_before_adj'\n AMT_CLOSE = 'amt_close'\n AMT_OPEN = 'amt_open'\n AMT_HIGH = 'amt_high'\n AMT_LOW = 'amt_low'\n AMT_ADJ_OPTION_PRICE = 'amt_adj_option_price'\n AMT_OPTION_PRICE = 'amt_option_price'\n AMT_UNDERLYING_CLOSE = 'amt_underlying_close'\n AMT_UNDERLYING_OPEN_PRICE = 'amt_underlying_open_price'\n AMT_SETTLEMENT = 'amt_settlement'\n AMT_LAST_SETTLEMENT = 'amt_last_settlement'\n AMT_LAST_CLOSE = 'amt_last_close'\n NBR_MULTIPLIER = 'nbr_multiplier'\n NBR_MULTIPLIER_AFTER_ADJ = 'nbr_multiplier_after_adj'\n AMT_HOLDING_VOLUME = 'amt_holding_volume'\n AMT_TRADING_VOLUME = 'amt_trading_volume'\n AMT_TRADING_VOLUME_CALL = 'amtl_trading_volume_call'\n AMT_TRADING_VOLUME_PUT = 'amt_trading_volume_put'\n AMT_TRADING_VALUE = 'amt_trading_value'\n AMT_MORNING_OPEN_15MIN = 'amt_morning_open_15min'\n AMT_MORNING_CLOSE_15MIN = 'amt_morning_close_15min'\n AMT_AFTERNOON_OPEN_15MIN = 'amt_afternoon_open_15min'\n AMT_AFTERNOON_CLOSE_15MIN = 'amt_afternoon_close_15min'\n AMT_MORNING_AVG = 'amt_morning_avg'\n AMT_AFTERNOON_AVG = 'amt_afternoon_avg'\n AMT_DAILY_AVG = 'amt_daily_avg'\n AMT_NEAREST_STRIKE = 'amt_nearest_strike'\n PCT_IMPLIED_VOL = 'pct_implied_vol'\n PCT_IV_OTM_BY_HTBR = 'pct_iv_by_htbr'\n PCT_IV_CALL_BY_HTBR = 'pct_iv_call_by_htbr'\n PCT_IV_PUT_BY_HTBR = 'pct_iv_put_by_htbr'\n PCT_IV_CALL = 'pct_iv_call'\n PCT_IV_PUT = 'pct_iv_put'\n AMT_DELTA = 'amt_delta'\n AMT_THETA = 'amt_theta'\n AMT_VEGA = 'amt_vega'\n AMT_RHO = 'amt_rho'\n AMT_CARRY = 'amt_carry'\n AMT_IV_ROLL_DOWN = 'amt_iv_roll_down'\n NBR_INVEST_DAYS = 'nbr_invest_days'\n RISK_FREE_RATE = 'risk_free_rate'\n AMT_APPLICABLE_STRIKE = 'amt_applicable_strike'\n AMT_APPLICABLE_MULTIPLIER = 'amt_applicable_multiplier'\n AMT_YIELD = 'amt_yield'\n AMT_HISTVOL = 'amt_hist_vol'\n AMT_PARKINSON_NUMBER = 'amt_parkinson_number'\n AMT_GARMAN_KLASS = 'amt_garman_klass'\n AMT_HEDHE_UNIT = 'amt_hedge_unit'\n AMT_CALL_QUOTE = 'amt_call_quote'\n ID_CALL = 'id_call'\n ID_PUT = 'id_put'\n AMT_PUT_QUOTE = 'amt_put_quote'\n AMT_TTM = 'amt_ttm'\n AMT_HTB_RATE = 'amt_HTB_rate'\n AMT_CLOSE_VOLUME_WEIGHTED = 'amt_close_volume_weighted'\n CD_CLOSE = 'cd_close'\n CD_CLOSE_VOLUME_WEIGHTED = 'cd_close_volume_weighted'\n NAME_CODE = 'name_code'\n STR_CALL = 'call'\n STR_PUT = 'put'\n STR_50ETF = '50etf'\n STR_INDEX_50ETF = 'index_50etf'\n STR_INDEX_50SH = 'index_50sh'\n STR_INDEX_300SH = 'index_300sh'\n STR_INDEX_300SH_TOTAL_RETURN = 'index_300sh_total_return'\n STR_M = 'm'\n STR_IH = 'ih'\n STR_IF = 'iF'\n STR_SR = 'sr'\n STR_ALL = 'all'\n STR_CU = 'cu'\n STR_CF = 'cf'\n STR_C = 'c'\n STR_RU = 'ru'\n NAN_VALUE = -999.0\n NAME_CODE_159 = ['sr', 'm', 'ru']\n MAIN_CONTRACT_159 = [1, 5, 9, '01', '05', '09']\n NAME_CODE_1to12 = ['cu']\n # Trade\n LONG = 1\n SHORT = -1\n UUID = 'uuid'\n DT_TRADE = 'dt_trade'\n TRADE_TYPE = 'trade_type'\n TRADE_PRICE = 'trade_price'\n TRANSACTION_COST = 'transaction_cost'\n TRADE_UNIT = 'trade_unit' # 绝对值\n TIME_SIGNAL = 'time_signal'\n OPTION_PREMIIUM = 'option_premium'\n CASH = 'cash'\n TRADE_MARGIN_CAPITAL = 'trade_margin_capital'\n TRADE_MARKET_VALUE = 'trade_market_value' # 头寸市值\n TRADE_BOOK_VALUE = 'trade_book_value' # 头寸规模(含多空符号),例如,空一手豆粕(3000点,乘数10)得到头寸规模为-30000,而建仓时点头寸市值为0。\n ABS_TRADE_BOOK_VALUE = 'abs_trade_book_value'\n TRADE_LONG_SHORT = 'long_short'\n AVERAGE_POSITION_COST = 'average_position_cost' # 历史多次交易同一品种的平均成本(总头寸规模绝对值/unit)\n TRADE_REALIZED_PNL = 'realized_pnl'\n LAST_PRICE = 'last_price'\n POSITION_CURRENT_VALUE = 'position_current_value' # 用于计算杠杆率,保证金交易的current value为零\n PORTFOLIO_MARGIN_CAPITAL = 'portfolio_margin_capital'\n PORTFOLIO_MARGIN_TRADE_SCALE = 'portfolio_margin_trade_scale'\n PORTFOLIO_TOTAL_SCALE = 'portfolio_total_scale'\n PORTFOLIO_TRADES_VALUE = 'portfolio_trades_value'\n PORTFOLIO_VALUE = 'portfolio_value'\n PORTFOLIO_NPV = 'npv'\n PORTFOLIO_UNREALIZED_PNL = 'unrealized_pnl'\n PORTFOLIO_LEVERAGE = 'portfolio_leverage'\n PORTFOLIO_FUND_UTILIZATION = 'portfolio_fund_utilization'\n PORTFOLIO_SHORT_POSITION_SCALE = 'portfolio_short_position_scale'\n PORTFOLIO_LONG_POSITION_SCALE = 'portfolio_long_position_scale'\n MARGIN_UNREALIZED_PNL = 'margin_unrealized_pnl'\n NONMARGIN_UNREALIZED_PNL = 'nonmargin_unrealized_pnl'\n PORTFOLIO_DELTA = 'portfolio_delta'\n TURNOVER = 'turnover'\n DRAWDOWN = 'drawdown'\n DAILY_EXCECUTED_AMOUNT = 'daily_executed_amount' # abs value\n BILLION = 1000000000.0\n MILLION = 1000000.0\n TRADE_BOOK_COLUMN_LIST = [DT_DATE, TRADE_LONG_SHORT, TRADE_UNIT,\n LAST_PRICE, TRADE_MARGIN_CAPITAL,\n TRADE_BOOK_VALUE, AVERAGE_POSITION_COST,\n TRADE_REALIZED_PNL, NBR_MULTIPLIER,\n TRANSACTION_COST\n ] # ID_INSTRUMENR是index\n ACCOUNT_COLUMNS = [DT_DATE, PORTFOLIO_NPV, PORTFOLIO_VALUE, CASH, PORTFOLIO_MARGIN_CAPITAL, PORTFOLIO_TRADES_VALUE,\n PORTFOLIO_FUND_UTILIZATION, PORTFOLIO_DELTA, DAILY_EXCECUTED_AMOUNT\n ]\n DICT_FUTURE_MARGIN_RATE = { # 合约价值的百分比\n 'm': 0.05,\n 'sr': 0.05,\n 'cu': 0.05,\n 'if': 0.15,\n 'ih': 0.15,\n 'ic': 0.15,\n 'index': 0.15\n }\n DICT_TRANSACTION_FEE = { # 元/手\n 'm': 3.0,\n 'sr': 3.0,\n 'cu': 3.0,\n 'if': None,\n 'ih': None,\n 'ic': None,\n \"index\": 0\n }\n DICT_OPTION_TRANSACTION_FEE_RATE = { # 百分比\n \"50etf\": 0.0,\n \"m\": 0.0,\n \"sr\": 0.0,\n \"cu\": 0.0,\n }\n DICT_OPTION_TRANSACTION_FEE = { # 元/手\n \"50etf\": 5.0,\n \"m\": 5.0,\n \"sr\": 5.0,\n \"cu\": 5.0\n }\n DICT_TRANSACTION_FEE_RATE = { # 百分比\n 'm': None,\n 'sr': None,\n 'cu': None,\n 'if': 6.9 / 10000.0,\n 'ih': 6.9 / 10000.0,\n 'ic': 6.9 / 10000.0,\n \"index\": None\n }\n DICT_CONTRACT_MULTIPLIER = { # 合约乘数\n 'm': 10,\n 'sr': 10,\n 'cu': 5,\n 'if': 300,\n 'ih': 300,\n 'ic': 200,\n 'index': 1\n }\n DICT_OPTION_CONTRACT_MULTIPLIER = { # 合约乘数\n 'm': 10,\n 'sr': 10,\n STR_50ETF: 10000\n }\n DICT_FUTURE_CORE_CONTRACT = {\n 'm': [1, 5, 9],\n 'sr': [1, 5, 6],\n STR_50ETF: STR_ALL}\n\n DICT_TICK_SIZE = {\n \"50etf\": 0.0001,\n \"m\": 1,\n \"sr\": 0.5,\n 'if': 0.2,\n 'ih': 0.2,\n 'ic': 0.2,\n 'index': 0\n }\n\n\nclass HistoricalVolatility:\n\n @staticmethod\n def hist_vol_daily(closes, n=20):\n series = np.log(closes).diff()\n res_series = series.rolling(window=n).std()\n return res_series\n\n @staticmethod\n def hist_vol(closes, n=20):\n series = np.log(closes).diff()\n res_series = series.rolling(window=n).std() * math.sqrt(252)\n return res_series\n\n @staticmethod\n def parkinson_number(df, n=20):\n squred_log_h_l = df.apply(HistoricalVolatility.fun_squred_log_high_low, axis=1)\n sum_squred_log_h_l = squred_log_h_l.rolling(window=n).sum()\n res_series = sum_squred_log_h_l.apply(\n lambda x: math.sqrt(252 * x / (n * 4 * math.log(2))))\n return res_series\n\n @staticmethod\n def garman_klass(df, n=20):\n tmp = df.apply(HistoricalVolatility.fun_garman_klass, axis=1)\n sum_tmp = tmp.rolling(window=n).sum()\n res_resies = sum_tmp.apply(lambda x: math.sqrt(x * 252 / n))\n return res_resies\n\n @staticmethod\n def fun_squred_log_high_low(df: pd.Series) -> float:\n return (math.log(df[Util.AMT_HIGH] / df[Util.AMT_LOW])) ** 2\n\n @staticmethod\n def fun_squred_log_close_open(df: pd.Series) -> float:\n return (math.log(df[Util.AMT_CLOSE] / df[Util.AMT_OPEN])) ** 2\n\n @staticmethod\n def fun_garman_klass(df: pd.Series) -> float:\n return 0.5 * HistoricalVolatility.fun_squred_log_high_low(df) - (\n 2 * math.log(2) - 1) * HistoricalVolatility.fun_squred_log_close_open(df)\n\n\nclass FutureUtil:\n @staticmethod\n def get_futures_daily_c1(df):\n df = df.sort_values(by=[Util.DT_DATE, Util.AMT_TRADING_VOLUME], ascending=False)\n df_rs = df.drop_duplicates(subset=[Util.DT_DATE]).sort_values(by=Util.DT_DATE, ascending=True).reset_index(\n drop=True)\n return df_rs\n\n @staticmethod\n def get_futures_minute_c1(df):\n tmp = df.groupby([Util.DT_DATE, Util.ID_INSTRUMENT]).sum()[Util.AMT_TRADING_VOLUME].to_frame()\n tmp = tmp.reset_index(level=[Util.DT_DATE, Util.ID_INSTRUMENT]).sort_values(by=Util.AMT_TRADING_VOLUME,\n ascending=False)\n tmp = tmp.drop_duplicates(subset=[Util.DT_DATE]).sort_values(by=Util.DT_DATE, ascending=True)\n df0 = tmp[[Util.DT_DATE, Util.ID_INSTRUMENT]].rename(columns={Util.ID_INSTRUMENT: 'id_core'})\n df2 = pd.merge(df, df0, on=Util.DT_DATE, how='left')\n df2 = df2[df2[Util.ID_INSTRUMENT] == df2['id_core']].reset_index(drop=True)\n return df2\n\n # TODO\n @staticmethod\n def get_future_c1_by_option_mdt_minute(df, option_maturities):\n return\n","sub_path":"MachineLearning/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":10077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"24042458","text":"import json\nfrom collections import OrderedDict\nfrom django.template.loader import render_to_string\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom chartforge.registry import charts_registry\n\n\nclass DynamicChart:\n \"\"\"\n Abstract base class for charts. Subclasses are made automatically when used\n with the ``chartforge()` decorator.\n \"\"\"\n name = None\n verbose_name = None\n template_name = None\n template = None\n _wrapped_func = None\n\n def __call__(self, **kwargs):\n \"\"\"\n Simply calls ``get_template(**kwargs)``.\n\n :return: dict\n \"\"\"\n return self.get_template(**kwargs)\n\n def get_template(self, **kwargs):\n \"\"\"\n Override in subclasses to generate dynamic templates. By default, the\n ``template`` attribute is returned, otherwise the `template_name` is\n loaded.\n\n :return: dict\n \"\"\"\n both_defined = self.template is not None and self.template_name is not None\n assert not both_defined, 'Only set template or template_name, set the other to None'\n\n if self.template is not None:\n assert isinstance(self.template, dict), 'Static template must be JSON serializable dict'\n return self.template\n\n if self.template_name is not None:\n return self.render_template(**kwargs)\n\n raise ImproperlyConfigured('Charts must set template or template_name')\n\n def render_template(self, **kwargs):\n \"\"\"\n Simply renders the template file with the context from\n ``get_context_data()``. Chart templates can be more dynamic by using\n a chart template, but once a chart is created, the template is static.\n Use a custom ``get_data()`` method to add dynamic data sources.\n\n :return: dict\n \"\"\"\n context = self.get_context_data(**kwargs)\n result = render_to_string(self.template_name, context)\n return json.loads(result)\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Get context data for rendering a chart template. Useful for urls, dates,\n or any other dynamic data needed for a chart template.\n\n :param kwargs: Kwargs passed when creating this chart\n :return: dict\n \"\"\"\n return kwargs\n\n def get_editing_data(self, **kwargs):\n \"\"\"\n Get data that is used when editing this report. Set to something cached\n or static. Calls ``get_data()`` by default.\n\n :param kwargs:\n :return:\n \"\"\"\n return self.get_data(**kwargs)\n\n def get_data(self, **kwargs):\n \"\"\"\n Override to do any querying or processing needed to make the chart data\n dynamic.\n :param kwargs:\n :return: dict\n \"\"\"\n func = self._wrapped_func\n return func(**kwargs) if func is not None else kwargs\n\n def __str__(self):\n kwargs = OrderedDict([\n ('name', self.name),\n ('verbose_name', self.verbose_name)\n ])\n if self.template is not None:\n kwargs['template'] = self.template\n if self.template_name is not None:\n kwargs['template_name'] = self.template_name\n if self._wrapped_func is not None:\n kwargs['function'] = self._wrapped_func.__name__\n return '%s(%s)' % (\n self.name,\n ', '.join(map(lambda i: '%s=%s' % i, kwargs.items()))\n )\n\n\ndef dynamic_chart(name=None, template_name=None, template=None, verbose_name=None):\n \"\"\"\n A function or class decorator that registers a chart with the chartforge\n registry.\n\n Can be used on a function or class::\n\n from chartforge import dynamic_chart\n\n @dynamic_chart(\n name='MyCustomChart',\n template_name='example_chart.json',\n verbose_name='My Awesome Chart!')\n def my_chart(chart):\n # chart is an instance of DynamicChart\n return {} # example data...\n\n @dynamic_chart()\n def ChartClass:\n template_name = 'another_chart.json'\n\n def get_data(self):\n return {} # example data...\n\n :param name: The name of the chart, used with ``get_chart_class()``\n :param template_name: A name of a file to use for the template\n :param template: A dict to use as the template\n :param verbose_name: The name displayed to users in the admin\n :return:\n \"\"\"\n def wrapper(cls_or_func):\n _name = cls_or_func.__name__ if name is None else name\n app = cls_or_func.__module__\n\n bases = (cls_or_func, DynamicChart)\n wrapped_func = None\n if type(cls_or_func) is not type:\n bases = (DynamicChart,)\n wrapped_func = cls_or_func\n\n attrs = {\n 'name': _name,\n '_wrapped_func': wrapped_func,\n '__module__': app\n }\n if template_name is not None:\n attrs['template_name'] = template_name\n\n if template is not None:\n attrs['template'] = template\n\n if verbose_name is not None:\n attrs['verbose_name'] = verbose_name\n\n chart_class = type(_name, bases, attrs)\n chart_class.__doc__ = cls_or_func.__doc__\n charts_registry.register(app, _name, chart_class)\n\n return cls_or_func\n\n return wrapper\n","sub_path":"chartforge/dynamic.py","file_name":"dynamic.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"344720440","text":"#This script adds steps to an undeploy plan to get the ear back into a zipped format\n# it only uses one script wich goes into the apps directory and zip up the formerly expanded directory so that xld can then handle the undeploy\n\nfrom wlp.modules.utility import Paths\nfrom com.xebialabs.deployit.plugin.api.deployment.specification import Operation\nfrom com.xebialabs.deployit.plugin.api.deployment.planning import DefaultOrders\n\n\nif previousDeployed.unpackZipFile is True:\n\n fc = {'previousDeployed': previousDeployed,\n 'targetPath': \"%s/apps\" % (Paths.get_server_config_dir(previousDeployed.container))}\n\n context.addStepWithCheckpoint(steps.os_script(\n description=\"repacking earfile: %s \" % (previousDeployed.name) ,\n script=\"lmwlp/scripts/application/pack-ear\",\n freemarker_context=fc,\n order=DefaultOrders.UNDEPLOY_ARTIFACTS - 1 ,\n target_host = previousDeployed.container.host\n ), delta, Operation.DESTROY)\n","sub_path":"src/main/resources/lmwlp/scripts/application/plan-unpack-ear-destroy.py","file_name":"plan-unpack-ear-destroy.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"650670658","text":"import threading\nimport multiprocessing as mp\nimport time\nfrom random import randint\n\ninOut = {}\ndivideOut = {}\nchoiceOut = {}\n\ndef inputHandler(event):\n number = randint(1,50)\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":number}\n }\n\n return response\n\ndef incHandler(event):\n input = event['body']['number']\n output = input+1\n\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":output}\n }\n\n return response\n\ndef squareHandler(event):\n input = event['body']['number']\n output = input*input\n\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":output}\n }\n\n return response\n\ndef halfHandler(event):\n input = event['body']['number']\n output = int(input/2)\n\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":output}\n }\n\n return response\n\ndef doubleHandler(event):\n input = event['body']['number']\n output = 2*input\n\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":output}\n }\n\n return response\n\ndef divideby5Handler(event):\n input = event['body']['number']\n output = input%5\n\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":output}\n }\n\n return response\n\ndef divideby2Handler(event):\n input = event['body']['number']\n output = input%2\n\n response = {\n \"statusCode\": 200,\n \"body\": {\"number\":output}\n }\n\n return response\n\ndef inWorker(event):\n ######################################################\n ######################################################\n\n result = inputHandler(event)\n\n ######################################################\n global inOut\n inOut = result\n ######################################################\n\ndef divideby2Worker():\n ######################################################\n global inOut\n ######################################################\n\n result = divideby2Handler(inOut)\n\n ######################################################\n global divideOut\n divideOut = result\n ######################################################\n\ndef incWorker():\n ######################################################\n global divideOut\n ######################################################\n\n result = incHandler(divideOut)\n\n ######################################################\n global choiceOut\n choiceOut = result\n ######################################################\n\ndef doubleWorker():\n ######################################################\n global divideOut\n ######################################################\n\n result = doubleHandler(divideOut)\n\n ######################################################\n global choiceOut\n choiceOut = result\n ######################################################\n\ndef functionWorker(event):\n input = threading.Thread(target=inWorker, args = [event])\n divideby2 = threading.Thread(target=divideby2Worker)\n\n input.start()\n input.join()\n\n divideby2.start()\n divideby2.join()\n\n choices = {\n 0: incWorker,\n 1: doubleWorker\n }\n\n reminder = divideOut['body']['number']\n choiceWorker = choices.get(reminder)\n\n choice = threading.Thread(target=choiceWorker)\n\n choice.start()\n choice.join()\n\n return choiceOut\n\ndef processWrapper(activationId, event, responseQueue):\n response = functionWorker(event)\n\n ######################################################\n responseQueue.put({activationId:response})\n ######################################################\n\ndef main(events):\n processes = []\n responseQueue = mp.Queue()\n\n for activationId, event in events.items():\n processes.append(mp.Process(target=processWrapper, args=[activationId, event, responseQueue]))\n\n for idx, process in enumerate(processes):\n process.start()\n\n for idx, process in enumerate(processes):\n process.join()\n\n result = {}\n for x in range(len(events)):\n result.update(responseQueue.get())\n\n return(result)\n\n# if __name__ == '__main__':\n# out = main({'activation1':{},'activation3':{},'activation4':{}, 'activation2': {},\n# 'activation31':{},'activation33':{},'activation34':{}, 'activation32': {},\n# 'activation45':{},'activation46':{},'activation47':{}, 'activation48': {}})\n","sub_path":"microbenchmarks/native_batching/micro-choice-2fns.py","file_name":"micro-choice-2fns.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"209357549","text":"import os\nimport re\nimport sqlite3\nimport csv\nimport win32com.client\nimport xlrd\nimport fnmatch\n\ndef xlsx_to_arr(xlsx_file, worksheet=0, row_start=0, col_start=0, row_end=-1, col_end=-1):\n\tarr = []\n\twb = xlrd.open_workbook(xlsx_file)\n\tws = wb.sheet_by_index(worksheet)\n\n\trow_end = ws.nrows if row_end == -1 else row_end\n\tcol_end = ws.ncols if col_end == -1 else col_end\n\n\tarr = [ws.row_values(row, start_colx=col_start, end_colx=col_end) for row in range(row_start, row_end)]\n\theader = ','.join(x if x not in arr[0][:n] else x+str(n) for n, x in enumerate(arr[0]) )\n\n\treturn re.sub(r\"[\\*\\.#/\\$%\\\"\\(\\)& \\_]\", \"\", header), arr[1:]\n\ndef question_marks(st):\n\tquestion_marks = '?'\n\tfor i in range(0, len(st.split(','))-1):\n\t\tquestion_marks = question_marks + \",?\"\n\treturn question_marks\n\ndef db_cur(source = \":memory:\"):\n\tconn = sqlite3.connect(source, detect_types=sqlite3.PARSE_DECLTYPES)\n\tconn.row_factory = sqlite3.Row\n\tcur = conn.cursor()\n\n\treturn conn, cur\n\ndef create_tbl(cur, tbl_name, header, arr = None, index_arr = None):\n\tcur.execute(\"\"\"select count(*) FROM sqlite_master WHERE type='table' AND name = '%s' \"\"\" % (tbl_name))\n\ttbl_exists = cur.fetchone() \n\tif tbl_exists[0] == 0:\n\t\tcur.execute(\"CREATE TABLE \" + tbl_name + \" (\" + header.replace(\"id,\", \"id PRIMARY KEY,\") + \" );\")\n\t\tif index_arr is not None:\n\t\t\tfor index in index_arr:\n\t\t\t\tcur.execute(\"CREATE INDEX \" + tbl_name + \"_\" + index + \" ON \" + tbl_name + \" (\" + index + \");\")\n\t\t\n\tif arr is not None:\n\t\tcur.executemany(\"INSERT INTO \" + tbl_name + \" VALUES (\"+question_marks(header)+\")\", arr)\n\treturn \n\ndef files_lookup(tgt_dir, pattern, recur_list=False, sub_folder=False, most_recent=True):\n\tfilepath_arr = []\n\n\tfor fi in os.listdir(tgt_dir):\n\t\tfull_path = os.path.join(tgt_dir, fi)\n\t\tif sub_folder and os.path.isdir(full_path):\n\t\t\tfilepath_arr += files_lookup(full_path, pattern, recur_list, sub_folder, most_recent)\n\t\tif fnmatch.fnmatch(fi, pattern):\n\t\t\tfilepath_arr.append(full_path)\n\n\tfilepath_arr.sort(reverse=most_recent)\n\tif recur_list:\n\t\treturn filepath_arr\n\telse:\n\t\treturn filepath_arr[0]\n\ndef files_to_db(cur, path, filenames):\n\ttbls = {}\n\n\tfor key in filenames:\n\t\ttbls[key] = files_lookup(path, filenames[key])\n\t\tprint (tbls[key])\n\n\tfor key in tbls:\n\t\theader, arr = xlsx_to_arr(tbls[key], row_start=1)\n\t\tprint (header)\n\t\tcreate_tbl(cur, key, header, arr)\n\n\treturn \n\ndef cash_recon(cur):\n\tcash_header = \"Client Code,External Reference,Currency,Amount\"\n\t\n\tcur.execute(\"\"\"\n\t\tselect ClientCode, ExternalReference, Currency, sum(Amount) \n\t\tfrom cash\n\t\tgroup by ClientCode, Currency\"\"\")\n\n\tcash_arr = cur.fetchall()\n\n\treturn cash_header, cash_arr\n\ndef main():\n\tconn, cur = db_cur()\n\n\tpb_path = \"\\\\\\\\p7fs0003\\\\nd\\\\3033-Horizon-FA-Share\\\\PB_DeltaOne\\\\Daily_Data\\\\\"\n\n\tpb_filenames = {}\n\tpb_filenames[\"cash\"] = \"CashEntry_*.xlsx\"\n\tpb_filenames[\"trd\"] = \"TradeDetails_*.xlsx\"\n\tpb_filenames[\"sbl\"] = \"RepoSBLTrade_*.xlsx\"\n\tpb_filenames[\"clients\"] = \"ClientDetails_*.xlsx\"\n\n\tfiles_to_db(cur, pb_path, pb_filenames)\n\n\tcash_header, cash_arr = cash_recon(cur)\n\ttrd_header, trd_arr = trd_recon(cur)\n\n\tfor row in cash_arr:\n\t\tprint (row)\n\n\treturn\n\nmain()","sub_path":"deltaone/d1_cash_pool_balance.py","file_name":"d1_cash_pool_balance.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"219811159","text":"#! python3\n# Author simottar@gmail.com\n# companyNameExcel.py - Prints the name for an icelandic registered company from the command line.\n\nimport sys, json, requests, operator\n\n# class to keep track of the gas stations\nclass GasStation:\n 'Common base class for gas stations'\n\n def __init__(self, price, address, company):\n self.price = price\n self.address = address\n self.company = company \n\n def displayPrices(self): \n print('price: {}, company: {}, address: {}'.format(self.price, self.company, self.address))\n\n# Get the search criteria from command line arguments.\nif len(sys.argv) < 3:\n print('Usage: bensin95 or bensin95_discount or diesel or diesel_discount | max or min')\n sys.exit()\n\nsearchCrit = sys.argv[1]\nop_input = sys.argv[2]\n\n# check if the search criteria exists\nif not any(searchCrit in criteria for criteria in ['bensin95','bensin95_discount', 'diesel', 'diesel_discount']):\n print('use correct input: bensin95 or bensin95_discount or diesel or diesel_discount')\n sys.exit()\n\n# check if the comparision exists\nif not any(op_input in op for op in ['min','max']):\n print('use correct input: min for lowest price or max for highest price')\n sys.exit()\n\n\n# define the operators to use in comparison\nops = {\"min\": operator.gt, \"max\": operator.lt}\nop_func = ops[op_input]\n\n# return values \nprice = 9999\nif op_input == 'max':\n price = 0\n\ncompany = \"no result\"\naddress = \"no result\"\nstation = GasStation(price,company,address)\n\n# fetch the prices from apis.is\nurl = \"http://apis.is/petrol\"\n\n# bypass proxy!!!\nsession = requests.Session()\nsession.trust_env = False\n\nresponse = session.get(url)\nresponse.raise_for_status()\n\n#print(response.text)\n# Load JSON data into a Python variable.\njsonToPython = json.loads(response.text)\n\n\n\n# extract from results\nresult = jsonToPython['results']\n\nstationList = []\n# check for cheapest price\nfor i in range(0, len(result)):\n if result[i][searchCrit]: \n thisPrice = float(result[i][searchCrit])\n if op_func(station.price, thisPrice):\n stationList = []\n station.price = thisPrice\n station.company = result[i]['company']\n station.address = result[i]['name']\n stationList = [station] \n elif station.price == thisPrice:\n stationList.append(GasStation(thisPrice,result[i]['name'],result[i]['company'])) \n\nfor s in stationList:\n s.displayPrices()\n\n\n\n","sub_path":"gas.py","file_name":"gas.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"379363117","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport glob2 as gb\nfrom scipy.integrate import quad, trapz\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import curve_fit\n\nfNamesAc = gb.glob(\"/home/wesley/Documents/exoplanets/AC/AC *.log\")\nfor f in fNamesAc:\n AcData = np.loadtxt(f,skiprows=58)\n AcTime = AcData[:,0]\n AcIntensity = AcData[:,1]\n plt.plot(AcTime,AcIntensity,marker=\"o\",linestyle='--',markersize='2')\n plt.grid(which='major', linestyle='dashed')\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"Intensity\")\n plt.axis(ymin=0)\n plt.savefig(\"%s.pdf\" %f)\n plt.close()\n\nfNamesAc50 = gb.glob(\"/home/wesley/Documents/exoplanets/AC 50/AC *.log\")\nfor f in fNamesAc50:\n Ac50Data = np.loadtxt(f,skiprows=58)\n Ac50Time = Ac50Data[:,0]\n Ac50Intensity = Ac50Data[:,1]\n plt.plot(Ac50Time,Ac50Intensity,marker=\"o\",linestyle='--',markersize='2')\n plt.grid(which='major', linestyle='dashed')\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"Intensity\")\n plt.axis(ymin=0)\n plt.savefig(\"%s.pdf\" %f)\n plt.close()\n \nfNamesDc = gb.glob(\"/home/wesley/Documents/exoplanets/DC/DC *.log\")\nfor f in fNamesDc:\n DcData = np.loadtxt(f,skiprows=58)\n DcTime = DcData[:,0]\n DcIntensity = DcData[:,1]\n plt.plot(DcTime,DcIntensity,marker=\"o\",linestyle='--',markersize='2')\n plt.grid(which='major', linestyle='dashed')\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"Intensity\")\n plt.savefig(\"%s.pdf\" %f)\n plt.close()\n \nfNamesCassy = gb.glob(\"/home/wesley/Documents/exoplanets/CASSY/CASSY *.lab\")\nfor f in fNamesCassy:\n CassyData = np.genfromtxt(f,skip_header=24,skip_footer=17)\n CassyTime = CassyData[:,1]\n CassyIntensity = CassyData[:,2]\n plt.plot(CassyTime,CassyIntensity,marker=\"o\",linestyle='--',markersize='2')\n plt.grid(which='major', linestyle='dashed')\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"Intensity\")\n plt.axis(ymin=0)\n plt.savefig(\"%s.pdf\" %f)\n plt.close()\n \nfNamesFinal = gb.glob(\"/home/wesley/Documents/exoplanets/FINAL/FINAL *.txt\")\nfor f in fNamesFinal:\n FinalData = np.genfromtxt(f,skip_header=24)\n FinalTime = FinalData[:,0]\n FinalIntensity = FinalData[:,1]\n plt.plot(FinalTime,FinalIntensity,marker=\"o\",linestyle='--',markersize='2')\n plt.grid(which='major', linestyle='dashed')\n plt.xlabel(\"Time [s]\")\n plt.ylabel(\"Intensity\")\n plt.axis(ymin=0)\n plt.savefig(\"%s.pdf\" %f)\n plt.close()","sub_path":"Data Sorting.py","file_name":"Data Sorting.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"489189055","text":"# Copyright 2019-2021, the MIDOSS project contributors, The University of British Columbia,\n# and Dalhousie University.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"WWatch3-Cmd command plug-in for run sub-command.\n\nPrepare for, execute, and gather the results of a run of the WaveWatch III® model.\n\"\"\"\nimport argparse\nimport logging\nimport os\nfrom copy import deepcopy\nfrom pathlib import Path\nimport shlex\nimport shutil\nimport subprocess\nimport textwrap\n\nimport arrow\nimport arrow.parser\nimport cliff.command\nimport cookiecutter.main\nimport nemo_cmd.prepare\nimport yaml\n\nlogger = logging.getLogger(__name__)\n\n\nclass Run(cliff.command.Command):\n \"\"\"Prepare, execute, and gather results from a WaveWatch III® model run.\n \"\"\"\n\n def get_parser(self, prog_name):\n parser = super().get_parser(prog_name)\n parser.description = \"\"\"\n Prepare, execute, and gather the results from a WaveWatch III®\n run described in DESC_FILE.\n The results files from the run are gathered in RESULTS_DIR.\n\n If RESULTS_DIR does not exist it will be created.\n \"\"\"\n parser.add_argument(\n \"desc_file\",\n metavar=\"DESC_FILE\",\n type=Path,\n help=\"run description YAML file\",\n )\n parser.add_argument(\n \"walltime\",\n metavar=\"WALLTIME\",\n type=str,\n help=\"HPC batch job walltime for the run; formatted as HH:MM:SS\",\n )\n parser.add_argument(\n \"results_dir\",\n metavar=\"RESULTS_DIR\",\n type=Path,\n help=\"directory to store results into\",\n )\n parser.add_argument(\n \"--no-submit\",\n dest=\"no_submit\",\n action=\"store_true\",\n help=\"\"\"\n Prepare the temporary run directory, and the bash script to \n execute the WaveWatch III® run, but don't submit the run to the queue.\n This is useful during development runs when you want to hack on \n the bash script and/or use the same temporary run directory \n more than once.\n \"\"\",\n )\n parser.add_argument(\n \"-q\",\n \"--quiet\",\n action=\"store_true\",\n help=\"don't show the run directory path or job submission message\",\n )\n parser.add_argument(\n \"--start-date\",\n type=self._arrow_date,\n default=arrow.now().floor(\"day\"),\n help=f\"\"\"\n Date to start run execution on. Use YYYY-MM-DD format.\n Defaults to {arrow.now().floor('day').format('YYYY-MM-DD')}.\n \"\"\",\n )\n parser.add_argument(\n \"--n-days\",\n type=int,\n default=1,\n help=\"Number of days of runs to execute in the batch job. Defaults to 1.\",\n )\n return parser\n\n @staticmethod\n def _arrow_date(string):\n \"\"\"Convert a YYYY-MM-DD string to a UTC arrow object or raise\n :py:exc:`argparse.ArgumentTypeError`.\n\n The time part of the resulting arrow object is set to 00:00:00.\n\n :arg str string: YYYY-MM-DD string to convert.\n\n :returns: Date string converted to a UTC :py:class:`arrow.Arrow` object.\n\n :raises: :py:exc:`argparse.ArgumentTypeError`\n \"\"\"\n try:\n return arrow.get(string, \"YYYY-MM-DD\")\n except arrow.parser.ParserError:\n msg = f\"unrecognized date format: {string} - please use YYYY-MM-DD\"\n raise argparse.ArgumentTypeError(msg)\n\n def take_action(self, parsed_args):\n \"\"\"Execute the `wwatch3 run` sub-coomand.\n\n The message generated upon submission of the run to the queue\n manager is logged to the console.\n\n :param parsed_args: Arguments and options parsed from the command-line.\n :type parsed_args: :class:`argparse.Namespace` instance\n \"\"\"\n submit_job_msg = run(\n parsed_args.desc_file,\n parsed_args.results_dir,\n parsed_args.start_date,\n parsed_args.walltime,\n n_days=parsed_args.n_days,\n no_submit=parsed_args.no_submit,\n quiet=parsed_args.quiet,\n )\n if submit_job_msg and not parsed_args.quiet:\n logger.info(submit_job_msg)\n\n\ndef run(\n desc_file, results_dir, start_date, walltime, n_days=1, no_submit=False, quiet=False\n):\n \"\"\"Create and populate a temporary run directory, and a run script,\n and submit the run to the queue manager.\n\n The run script is stored in :file:`SoGWW3.sh` in the temporary run directory.\n That script is submitted to the queue manager in a subprocess.\n\n :param desc_file: File path/name of the YAML run description file.\n :type desc_file: :py:class:`pathlib.Path`\n\n :param results_dir: Path of the directory in which to store the run results;\n it will be created if it does not exist.\n :type results_dir: :py:class:`pathlib.Path`\n\n :param start_date: Date to start run execution on.\n :type :py:class:`arrow.Arrow`:\n\n :param str walltime: HPC batch job walltime to use for the run;\n formatted as :kbd:`HH:MM:SS`.\n\n :param int n_days: Number of days of runs to execute in the batch job.\n\n :param boolean no_submit: Prepare the temporary run directory,\n and the run script to execute the WaveWatch III® run,\n but don't submit the run to the queue.\n\n :param boolean quiet: Don't show the run directory path message;\n the default is to show the temporary run directory\n path.\n\n :returns: Message generated by queue manager upon submission of the\n run script.\n :rtype: str\n \"\"\"\n run_desc = nemo_cmd.prepare.load_run_desc(desc_file)\n run_id = nemo_cmd.prepare.get_run_desc_value(run_desc, (\"run_id\",))\n runs_dir = nemo_cmd.prepare.get_run_desc_value(\n run_desc, (\"paths\", \"runs directory\"), resolve_path=True\n )\n mod_def_ww3_path = nemo_cmd.prepare.get_run_desc_value(\n run_desc, (\"grid\", \"mod_def.ww3 file\"), resolve_path=True\n )\n current_forcing_dir = nemo_cmd.prepare.get_run_desc_value(\n run_desc, (\"forcing\", \"current\"), resolve_path=True\n )\n wind_forcing_dir = nemo_cmd.prepare.get_run_desc_value(\n run_desc, (\"forcing\", \"wind\"), resolve_path=True\n )\n days = list(arrow.Arrow.range(\"day\", start_date, limit=n_days))\n run_start_dates_yyyymmdd = (\n [start_date.format(\"YYYYMMDD\")]\n if n_days == 1\n else [day.format(\"YYYYMMDD\") for day in days]\n )\n results_dirs = (\n [_resolve_results_dir(results_dir)]\n if n_days == 1\n else [\n _resolve_results_dir(results_dir) / (day.format(\"DDMMMYY\").lower())\n for day in days\n ]\n )\n tmp_run_dir_timestamp = arrow.now().format(\"YYYY-MM-DDTHHmmss.SSSSSSZ\")\n tmp_run_dirs = (\n [runs_dir / f\"{run_id}_{tmp_run_dir_timestamp}\"]\n if n_days == 1\n else [\n runs_dir\n / f\"{run_id}_{day.format('DDMMMYY').lower()}_{tmp_run_dir_timestamp}\"\n for day in days\n ]\n )\n for day, day_results_dir, tmp_run_dir in zip(days, results_dirs, tmp_run_dirs):\n day_run_id = run_id\n try:\n restart_path = nemo_cmd.prepare.get_run_desc_value(\n run_desc, (\"restart\", \"restart.ww3\"), resolve_path=True, fatal=False\n )\n except KeyError:\n restart_path = \"\"\n cookiecutter_context = {\n \"tmp_run_dir\": tmp_run_dir,\n \"run_start_dates_yyyymmdd\": \"\\n \".join(run_start_dates_yyyymmdd),\n \"results_dirs\": \"\\n \".join(map(os.fspath, results_dirs)),\n \"work_dirs\": \"\\n \".join(map(os.fspath, tmp_run_dirs)),\n \"batch_directives\": _sbatch_directives(run_desc, day_results_dir, walltime),\n \"module_loads\": \"module load netcdf-fortran-mpi/4.4.4\",\n \"run_id\": run_id,\n \"runs_dir\": runs_dir,\n \"run_start_date_yyyymmdd\": start_date.format(\"YYYYMMDD\"),\n \"run_end_date_yyyymmdd\": start_date.shift(days=+1).format(\"YYYYMMDD\"),\n \"mod_def_ww3_path\": mod_def_ww3_path,\n \"current_forcing_dir\": current_forcing_dir,\n \"wind_forcing_dir\": wind_forcing_dir,\n \"restart_path\": restart_path,\n \"results_dir\": day_results_dir,\n }\n if n_days > 1:\n day_run_id = f\"{run_id}_{day.format('DDMMMYY').lower()}\"\n if restart_path:\n daym1_ddmmmyy = day.shift(days=-1).format(\"DDMMMYY\").lower()\n restart_path = (\n restart_path.parent.parent / daym1_ddmmmyy\n ) / restart_path.name\n else:\n logger.warning(\n \"You have requested a multi-day run with no restart file path. \"\n \"Each day of the run will start from calm wave fields. \"\n \"Is this really what you want?\"\n )\n cookiecutter_context.update(\n {\n \"run_id\": day_run_id,\n \"run_start_date_yyyymmdd\": day.format(\"YYYYMMDD\"),\n \"run_end_date_yyyymmdd\": day.shift(days=+1).format(\"YYYYMMDD\"),\n \"restart_path\": restart_path,\n }\n )\n cookiecutter.main.cookiecutter(\n os.fspath(Path(__file__).parent.parent / \"cookiecutter\"),\n no_input=True,\n output_dir=runs_dir,\n extra_context=cookiecutter_context,\n )\n day_run_desc = deepcopy(run_desc)\n day_run_desc.update(\n {\"run_id\": day_run_id, \"restart\": {\"restart.ww3\": os.fspath(restart_path)}}\n )\n _write_tmp_run_dir_run_desc(day_run_desc, tmp_run_dir, desc_file, n_days)\n if not quiet:\n logger.info(f\"Created temporary run directory {tmp_run_dir}\")\n day_results_dir.mkdir(parents=True, exist_ok=True)\n try:\n for tmp_run_dir in tmp_run_dirs[1:]:\n (tmp_run_dir / \"SoGWW3.sh\").unlink()\n except IndexError:\n # len(tmp_run_dirs) == 1 for n_days == 1\n pass\n run_script_file = tmp_run_dirs[0] / \"SoGWW3.sh\"\n if not quiet:\n logger.info(f\"Wrote job run script to {run_script_file}\")\n if no_submit:\n return\n sbatch_cmd = f\"sbatch {run_script_file}\"\n submit_job_msg = subprocess.run(\n shlex.split(sbatch_cmd),\n check=True,\n universal_newlines=True,\n stdout=subprocess.PIPE,\n ).stdout\n return submit_job_msg\n\n\ndef _write_tmp_run_dir_run_desc(run_desc, tmp_run_dir, desc_file, n_days):\n \"\"\"Write the run description to a YAML file in the temporary run directory\n so that it is preserved with the run results.\n\n Extracted into a separate function to improve testability of the run() function.\n\n :param dict run_desc: Contents of run description file parsed from YAML into a dict.\n\n :param tmp_run_dir: Temporary directory generated for the run.\n :type tmp_run_dir: :py:class:`pathlib.Path`\n\n :param desc_file: File path/name of the YAML run description file.\n :type desc_file: :py:class:`pathlib.Path`\n\n :param int n_days: Number of days of runs to execute in the batch job.\n \"\"\"\n if n_days == 1:\n shutil.copy2(desc_file, tmp_run_dir)\n return\n with (tmp_run_dir / desc_file.name).open(\"wt\") as f:\n yaml.safe_dump(run_desc, f, default_flow_style=False)\n\n\ndef _resolve_results_dir(results_dir):\n \"\"\"Expand environment variables and :file:`~` in :kbd:`results_dir`\n and resolve it to an absolute path.\n\n :param results_dir: Path of the directory in which to store the run results;\n it will be created if it does not exist.\n :type results_dir: :py:class:`pathlib.Path`\n\n :return: :py:class:`pathlib.Path`\n \"\"\"\n results_dir = Path(os.path.expandvars(results_dir)).expanduser().resolve()\n return results_dir\n\n\ndef _sbatch_directives(run_desc, results_dir, walltime):\n run_id = nemo_cmd.prepare.get_run_desc_value(run_desc, (\"run_id\",))\n sbatch_directives = textwrap.dedent(\n f\"\"\"\\\n #SBATCH --job-name={run_id}\n #SBATCH --mail-user={nemo_cmd.prepare.get_run_desc_value(run_desc, (\"email\",))}\n #SBATCH --mail-type=ALL\n #SBATCH --account={nemo_cmd.prepare.get_run_desc_value(run_desc, (\"account\",))}\n #SBATCH --constraint=skylake\n #SBATCH --nodes=1\n #SBATCH --ntasks-per-node=20\n #SBATCH --mem=0\n #SBATCH --time={walltime}\n # stdout and stderr file paths/names\n #SBATCH --output={results_dir/\"stdout\"}\n #SBATCH --error={results_dir/\"stderr\"}\n \"\"\"\n )\n return sbatch_directives\n","sub_path":"wwatch3_cmd/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":13387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"360489668","text":"#!/usr/bin/env python3\n\n\"\"\" File name: disease_simulation.py\n Author: Nathan Robinson, Miquel Ramirez, Enrico Scala\n Date: 2014, 2015, 2016, 2017\n Description: This is the main file for COMP3620 Assignment 0 Exercise 4.\n\n --- You do not need to modify this file ---\n\n python disease_simulation.py to get usage information.\n\"\"\"\n\nimport sys\nfrom io import StringIO\nimport copy\nimport importlib\nimport traceback\nimport os.path\nimport time\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n\nclass Capturing(list):\n \"\"\" A class to capture printed output. \"\"\"\n\n def __enter__(self):\n \"\"\" Allow us to use instances of Capturing with the 'with' keyword.\n Deal with entering the with block.\n \"\"\"\n self._stdout = sys.stdout\n sys.stdout = self._stringio = StringIO()\n return self\n\n def __exit__(self, *args):\n \"\"\" Allow us to use instances of Capturing with the 'with' keyword\n Deal with exiting the with block.\n \"\"\"\n self.extend(self._stringio.getvalue().splitlines())\n sys.stdout = self._stdout\n\n\nnon_existent_test = \"tests/non_existent_test.scn\"\ntest_files = [\"exercise4_maps/test1.scn\",\n \"exercise4_maps/test2.scn\", \"exercise4_maps/test3.scn\"]\ntest_params = [\n {\"threshold\": 0.5, \"growth\": 0.2, \"spread\": 0.1, \"locations\": [\"l1\", \"l2\"],\n \"location\": \"l1\",\n \"disease\": {\"l1\": 0, \"l2\": 0.8},\n \"conn\": {\"l1\": set([\"l2\"]), \"l2\": set([\"l1\"])},\n \"vloc\": \"l2\", \"iloc\": \"l3\",\n \"10it\": {'l2': 4.95338913792, 'l1': 0}},\n {\"threshold\": 1, \"growth\": 0.2, \"spread\": 0.1, \"locations\": [\"l1\", \"l2\", \"l3\", \"l4\"],\n \"location\": \"l1\",\n \"disease\": {\"l1\": 0, \"l2\": 1, \"l3\": 0, \"l4\": 0.1},\n \"conn\": {\"l1\": set([\"l2\", \"l3\"]), \"l2\": set([\"l1\", \"l3\"]), \"l3\": set([\"l1\", \"l2\", \"l4\"]),\n \"l4\": set([\"l3\"])},\n \"vloc\": \"l2\", \"iloc\": \"l4\",\n \"10it\": {'l4': 2.1405428582400003, 'l2': 7.713105638400002, 'l3': 5.520701214720001, 'l1': 0}},\n {\"threshold\": 1, \"growth\": 1, \"spread\": 1,\n \"locations\": [\"l0\", \"l1\", \"l2\", \"l3\", \"l4\", \"l5\", \"l6\", \"l7\", \"l8\", \"l9\"],\n \"location\": \"l9\",\n \"disease\": {\"l0\": 0.5, \"l1\": 0, \"l2\": 0, \"l3\": 0, \"l4\": 0, \"l5\": 0, \"l6\": 0,\n \"l7\": 0, \"l8\": 0, \"l9\": 0},\n \"conn\": {\"l0\": set([\"l1\", \"l5\"]), \"l1\": set([\"l0\", \"l2\"]), \"l2\": set([\"l1\", \"l3\"]),\n \"l3\": set([\"l2\", \"l4\"]), \"l4\": set([\"l3\", \"l9\"]), \"l5\": set([\"l0\", \"l6\"]),\n \"l6\": set([\"l5\", \"l7\"]), \"l7\": set([\"l6\", \"l8\"]), \"l8\": set([\"l7\", \"l9\"]),\n \"l9\": set([\"l4\", \"l8\"])},\n \"vloc\": \"l8\", \"iloc\": \"l2\",\n \"10it\": {'l6': 31806.0, 'l7': 18411.0, 'l4': 7752.0, 'l5': 43757.0, 'l2': 31806.0,\n 'l3': 18411.0, 'l0': 48620.0, 'l1': 43757.0, 'l8': 7752.0, 'l9': 0}\n }\n]\n\n\nclass TestingError(Exception):\n \"\"\" An error to be raised when testing fails. \"\"\"\n\n\ndef test_scenario_file(module):\n \"\"\" Test the given disease_scenario module.\n\n (module) -> None\n \"\"\"\n print(\"Testing implementation of disease_scenario.py\")\n print(\"--------------------------------------------------------------------\")\n\n print(\"Checking for DiseaseScenario class...\")\n print(\"-------------------------------------\")\n try:\n ds_class = module.DiseaseScenario\n if type(ds_class) != type:\n print(\"Failed. DiseaseScenario is not a class.\")\n\n class tc:\n pass\n if type(ds_class) == type(tc):\n print(\"You have forgotten to make DiseaseScenario subclass object.\")\n raise TestingError()\n ds = ds_class()\n except AttributeError:\n print(\"Failed. DiseaseScenario does not exist.\")\n raise TestingError()\n print(\"Success.\")\n\n print(\"Testing read_scenario_file method.\")\n print(\"-------------------------------------\")\n try:\n rsf = ds.read_scenario_file\n print(\"Testing on a non-existent file...\")\n try:\n if rsf(non_existent_test):\n print(\"Error: either to you failed to return False when an IOError was raised or\",\n \"you created a file called non_existent_test.scn (you should delete it).\")\n raise TestingError()\n except IOError:\n print(\"Error: you are supposed to catch IOErrors and return false.\")\n raise TestingError()\n except Exception:\n print(\"Unexpected error when running on a non-existent file:\")\n print(traceback.format_exc())\n raise TestingError()\n\n print(\"Success.\")\n\n test_ds = []\n for test, tparams in zip(test_files, test_params):\n print(\"Testing on file:\", test)\n ds_copy = copy.deepcopy(ds)\n try:\n if not ds_copy.read_scenario_file(test):\n print(\n \"Error:\", test, \" does not exist or you are returning False inadvertently.\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'threshold'):\n print(\"Error: you have made threshold a class variable!\")\n print(\"It should belong to the instance -- i.e. self.threshold = x\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'growth'):\n print(\"Error: you have made growth a class variable!\")\n print(\"It should belong to the instance -- i.e. self.growth = x\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'spread'):\n print(\"Error: you have made spread a class variable!\")\n print(\"It should belong to the instance -- i.e. self.spread = x\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'location'):\n print(\"Error: you have made location a class variable!\")\n print(\"It should belong to the instance -- i.e. self.location = x\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'locations'):\n print(\"Error: you have made locations a class variable!\")\n print(\n \"It should belong to the instance -- i.e. self.locations = []\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'disease'):\n print(\"Error: you have made disease a class variable!\")\n print(\"It should belong to the instance -- i.e. self.disease = {}\")\n raise TestingError()\n\n if hasattr(module.DiseaseScenario, 'conn'):\n print(\"Error: you have made conn a class variable!\")\n print(\"It should belong to the instance -- i.e. self.conn = {}\")\n raise TestingError()\n\n test_ds.append(ds_copy)\n except IOError:\n print(\"Error: you are supposed to catch IOErrors and return false.\")\n raise TestingError()\n except TestingError:\n raise TestingError()\n except Exception:\n print(\"Unexpected error:\")\n print(traceback.format_exc())\n raise TestingError()\n try:\n if not isinstance(ds_copy.threshold, float) and not isinstance(ds_copy.threshold, int):\n print(\"Error: threshold should be a float or int!\")\n raise TestingError()\n if abs(ds_copy.threshold - tparams[\"threshold\"]) > 0.001:\n print(\"Error: threshold has unexpected value: \", ds_copy.threshold,\n \"expected:\", tparams[\"threshold\"])\n raise TestingError()\n except AttributeError:\n print(\"Error: threshold variable is missing.\")\n raise TestingError()\n\n try:\n if not isinstance(ds_copy.growth, float) and not isinstance(ds_copy.growth, int):\n print(\"Error: growth should be a float or int!\")\n raise TestingError()\n\n if abs(ds_copy.growth - tparams[\"growth\"]) > 0.001:\n print(\"Error: growth has unexpected value:\", ds_copy.growth,\n \"expected:\", tparams[\"growth\"])\n raise TestingError()\n except AttributeError:\n print(\"Error: growth variable is missing.\")\n raise TestingError()\n\n try:\n if not isinstance(ds_copy.spread, float) and not isinstance(ds_copy.spread, int):\n print(\"Error: spread should be a float or int!\")\n raise TestingError()\n\n if abs(ds_copy.spread - tparams[\"spread\"]) > 0.001:\n print(\"Error: spread has unexpected value: \", ds_copy.spread,\n \"expected:\", tparams[\"spread\"])\n raise TestingError()\n except AttributeError:\n print(\"Error: spread variable is missing.\")\n raise TestingError()\n\n try:\n if ds_copy.location != tparams[\"location\"]:\n print(\"Error: location has unexpected value: \", ds_copy.location,\n \"expected:\", tparams[\"location\"])\n raise TestingError()\n except AttributeError:\n print(\"Error: location variable is missing.\")\n raise TestingError()\n\n try:\n if not isinstance(ds_copy.locations, list):\n print(\"Error: locations is not a list.\")\n raise TestingError()\n for loc in ds_copy.locations:\n if loc not in tparams[\"locations\"]:\n print(\"Unexpected location:\", loc)\n raise TestingError()\n for loc in tparams[\"locations\"]:\n if loc not in ds_copy.locations:\n print(\"Missing location:\", loc)\n raise TestingError()\n except AttributeError:\n print(\"Error: locations variable is missing.\")\n raise TestingError()\n\n try:\n if not isinstance(ds_copy.disease, dict):\n print(\"Error: disease is not a dictionary.\")\n raise TestingError()\n for loc, dis in ds_copy.disease.items():\n if loc not in tparams[\"disease\"]:\n print(\"Unexpected disease location:\", loc)\n raise TestingError()\n\n if not isinstance(dis, float) and not isinstance(dis, int):\n print(\"Error: the disease at location\",\n loc, \"should be a float or int!\")\n raise TestingError()\n\n if abs(tparams[\"disease\"][loc] - dis) > 0.001:\n print(\"Invalid disease at location:\", loc, \"expected:\",\n tparams[\"disease\"][loc])\n raise TestingError()\n for loc, dis in tparams[\"disease\"].items():\n if loc not in ds_copy.disease:\n print(\n \"Missing disease location (locations should have 0 disease by default):\", loc)\n raise TestingError()\n except AttributeError:\n print(\"Error: disease variable is missing.\")\n raise TestingError()\n\n try:\n if not isinstance(ds_copy.conn, dict):\n print(\"Error: conn is not a dictionary.\")\n raise TestingError()\n\n for loc, locs in ds_copy.conn.items():\n if loc not in tparams[\"conn\"]:\n print(\"Unexpected conn location:\", loc)\n raise TestingError()\n\n if not isinstance(locs, set):\n print(\"Error: location\", loc, \"should have a *set* of connected\",\n \"locations in the conn dictionary.\")\n raise TestingError()\n if locs != tparams[\"conn\"][loc]:\n print(\n \"There is an invalid set of connections at location:\", loc)\n print(\"We expected:\", tparams[\"conn\"][loc])\n print(\"We got:\", locs)\n raise TestingError()\n\n for loc, dis in tparams[\"conn\"].items():\n if loc not in ds_copy.conn:\n print(\"Missing location in conn dictionary:\", loc)\n raise TestingError()\n\n except AttributeError:\n print(\"Error: conn dictionary is missing.\")\n raise TestingError()\n except AttributeError:\n print(\"Failed. read_scenario_file does not exist.\")\n raise TestingError()\n print(\"Success.\")\n\n print(\"Testing valid_moves method.\")\n print(\"-------------------------------------\")\n try:\n vm = ds.valid_moves\n except AttributeError:\n print(\"Failed. valid_moves does not exist.\")\n raise TestingError()\n\n for tid, test_file in enumerate(test_files):\n tparams = test_params[tid]\n ds = test_ds[tid]\n\n try:\n correct_vm = tparams[\"conn\"][tparams[\"location\"]]\n correct_vm.add(tparams[\"location\"])\n valid_moves = ds.valid_moves()\n if not isinstance(valid_moves, list):\n print(\"Error: valid_moves is supposed to return a list.\")\n raise TestingError()\n if set(valid_moves) != correct_vm:\n print(\"Error: valid moves for test:\", test_file, \"loc:\", ds.location,\n \"is wrong. Did you remember that agents can move to their\",\n \"current locations?\")\n print(\"We expected:\", sorted(correct_vm))\n print(\"We got:\", sorted(valid_moves))\n\n raise TestingError()\n except Exception:\n print(\"Unexpected error when running valid_moves for test:\",\n test_file, \"location:\", ds.location)\n print(traceback.format_exc())\n raise TestingError()\n print(\"Success.\")\n\n print(\"Testing move method.\")\n print(\"-------------------------------------\")\n try:\n mm = ds.move\n except AttributeError:\n print(\"Failed. move does not exist.\")\n raise TestingError()\n\n for tid, test_file in enumerate(test_files):\n tparams = test_params[tid]\n ds = copy.deepcopy(test_ds[tid])\n\n # Invalid move first\n try:\n ds.move(tparams[\"iloc\"])\n raise TestingError()\n except ValueError:\n pass\n except Exception:\n print(\"Unexpected error when running move method with an invalid location:\",\n tparams[\"iloc\"], \"for test:\", test_file)\n print(traceback.format_exc())\n print(\"We Expected a ValueError to be raised when an invalid move was made.\")\n raise TestingError()\n\n # Valid move\n ds.disease[tparams[\"vloc\"]] = 100\n try:\n ds.move(tparams[\"vloc\"])\n except Exception:\n print(\"Unexpected error when running move to\", tparams[\"vloc\"],\n \"for test:\", test_file)\n print(traceback.format_exc())\n raise TestingError()\n if ds.disease[tparams[\"vloc\"]] != 0:\n print(\"Error: moving to\", tparams[\"vloc\"],\n \"did not clear disease there in test:\", test_file)\n raise TestingError()\n if ds.location != tparams[\"vloc\"]:\n print(\"Error: moving to\", tparams[\"vloc\"], \"failed to change the location\",\n \"in test:\", test_file)\n raise TestingError()\n print(\"Success.\")\n\n print(\"Testing spread_disease method.\")\n print(\"-------------------------------------\")\n try:\n sd = ds.spread_disease\n except AttributeError:\n print(\"Failed. spread_disease does not exist.\")\n raise TestingError()\n\n for tid, test_file in enumerate(test_files):\n tparams = test_params[tid]\n ds = test_ds[tid]\n try:\n for it in range(10):\n ds.spread_disease()\n except Exception:\n print(\"Unexpected error when running spread_disease for test:\", test_file)\n print(traceback.format_exc())\n raise TestingError()\n\n try:\n ed = tparams[\"10it\"]\n for loc in tparams[\"locations\"]:\n if loc == tparams[\"location\"]:\n if ds.disease[loc] != 0:\n print(\"Error: we expect there to always be zero disease\",\n \"at the current location:\", test_file, \"instead there is:\",\n ds.disease[loc])\n raise TestingError()\n else:\n if abs(ds.disease[loc] - ed[loc]) > 0.01:\n print(\"Error: after 10 iterations there is the wrong\",\n \"disease\", ds.disease[loc], \"expected\", ed[loc],\n \"(0.01 epsilon) at location:\", loc, \"test:\", test_file)\n raise TestingError()\n except AttributeError:\n print(\"Error: you must have deleted disease when running spread_disease\",\n \"for test:\", test_file)\n\n print(\"All tests passed. Good job!\")\n print(\"These tests are thorough, but not exhaustive.\")\n print(\"At the end of the day, the correctness of your code depends on you following instructions.\")\n print(\"Make sure you check your code again, comment your file appropriately,\",\n \"and then proceed to the next part of the exercise.\")\n\n\ndef print_summary(scenario):\n \"\"\" Print a summary of the disease spread and current location in the\n given scenario.\n\n (DiseaseScenario) -> None\n \"\"\"\n print(\"The locations have the following disease:\")\n total_disease = 0\n tokens = []\n for loc in scenario.locations:\n disease = scenario.disease[loc]\n total_disease += disease\n if disease >= scenario.threshold:\n status = \"(spreading)\"\n else:\n status = \"()\"\n tokens.append(' '.join([loc, str(disease), status]))\n print(','.join(tokens))\n print(\"Total disease:\", total_disease)\n return total_disease\n\n\ndef show_graph(graph):\n graph.graph = nx.Graph()\n for node, disease in graph.disease.items():\n graph.graph.add_node(node, label=node + \": \" + str(disease))\n\n for node in graph.conn.keys():\n graph.graph.add_edges_from([(node, neighbor) for neighbor in list(graph.conn[node])])\n plt.clf()\n nx.draw(graph.graph, pos=nx.circular_layout(graph.graph), with_labels=True, font_weight='bold',\n labels={k: \"{}\\n{:.2f}\".format(k, v) for k, v in graph.disease.items()},\n node_size=1300,\n node_color=[\"b\" if loc == graph.location else \"g\" if d <= 0 else \"r\" for loc, d in graph.disease.items()])\n plt.text(-1, 0.8,\n \"Spread: \" + str(graph.spread) +\n \"\\nGrowth: \" + str(graph.growth) +\n \"\\nThreshold: \" + str(graph.threshold))\n plt.draw()\n plt.pause(0.01) # Needed since GUI events happen while main code is sleeping\n input(\"Press [Enter] in the terminal to continue.\")\n\n\ndef on_keyboard(event):\n if event.key == 'right':\n plt.show(block=False)\n if event.key == 'escape':\n exit()\n\n\ndef parse_arguments():\n import argparse\n\n parser = argparse.ArgumentParser(\n description='Horseman No. 1 - an Australian epidemic simulator')\n parser.add_argument('-t', '--test', default=False, action='store_true',\n help='Activates TESTING mode (default: deactivated)')\n parser.add_argument('-s', '--scenario', default=None,\n type=str, help='Path to scenario (.scn) file')\n parser.add_argument('-a', '--agent', default='HealthAgent',\n type=str, help='Agent to be used (default: HealthAgent)')\n parser.add_argument('-H', '--horizon', default=100, type=int,\n help='Maximum number of steps in the simulation (default: 100)')\n parser.add_argument('-n', '--num_sims', default=1, type=int,\n help='Number of simulations to run (default: 1)')\n parser.add_argument('-v', '--viz', default=False, action='store_true',\n help='Draw a graph to visualise how diseases are spread. '\n 'When this is enabled, you need to press Enter in the terminal to move along the animation.')\n\n args = parser.parse_args()\n\n if args.scenario is None and not args.test:\n print(\"[Fatal]: Scenario file was not specified!\")\n parser.print_help()\n sys.exit(1)\n\n return args\n\n\ndef main():\n \"\"\" Run the simulation on the scenario file given in the command line.\n\n () -> None\n \"\"\"\n\n args = parse_arguments()\n\n try:\n with Capturing() as output:\n import disease_scenario\n except ImportError:\n print(\"Error disease_scenario.py does not exist.\")\n sys.exit()\n except Exception:\n print(\"Error: exception when importing disease_scenario:\")\n print(traceback.format_exc())\n sys.exit()\n\n if output:\n print(\"Error disease_scenario.py produced output when imported.\")\n sys.exit()\n\n if args.test:\n try:\n test_scenario_file(disease_scenario)\n except TestingError:\n pass\n else:\n try:\n ds = disease_scenario.DiseaseScenario()\n if not ds.read_scenario_file(args.scenario):\n print(\"Error: the supplied scenario file does not exist:\",\n args.scenario)\n sys.exit()\n except Exception:\n print(\n \"Unexpected error while loading the specified disease scenario:\", args.scenario)\n print(traceback.format_exc())\n print(\"Are you sure you tested disease_scenario correctly?\")\n sys.exit()\n\n agent_name = args.agent\n print(\"Trying to load agent:\", agent_name)\n try:\n agent_module = importlib.import_module(\"health_agents\")\n base_class = agent_module.HealthAgent\n except ImportError:\n print(\"Error loading agent from health_agents.py\")\n print(\"Make sure the file exists.\")\n sys.exit()\n except Exception:\n print(\"Unexpected error while trying to import health_agents.py:\")\n print(traceback.format_exc())\n print(\"What did you do in that file?\")\n sys.exit()\n\n if agent_name not in agent_module.__dict__:\n print(\"There is no such agent as\",\n agent_name, \"in health_agents.py\")\n sys.exit()\n\n agent_class = agent_module.__dict__[agent_name]\n if not issubclass(agent_class, base_class):\n print(\"Error:\", agent_name, \"is not an instance of a HealthAgent.\")\n sys.exit()\n\n try:\n agent = agent_class(list(ds.locations), copy.deepcopy(ds.conn))\n except Exception:\n print(\"Unknown error while trying to create a new:\", agent_name)\n print(traceback.format_exc())\n sys.exit()\n\n print(\"Agent loaded.\")\n\n try:\n iterations = args.horizon\n if iterations < 0:\n raise ValueError()\n except ValueError:\n print(\"Error: invalid number of iterations:\", sys.argv[3])\n sys.exit()\n\n simulations_data = {}\n simulations_data['runs'] = []\n simulations_data['average_score'] = 0.0\n print_summary(ds)\n print(\"Agent location:\", ds.location)\n if args.viz:\n plt.show()\n show_graph(ds)\n\n try:\n import random\n random.seed(938729021)\n start_time = time.clock()\n for j in range(0, args.num_sims):\n print(\"Starting simulation {} out of {}\".format(j+1, args.num_sims))\n ds = disease_scenario.DiseaseScenario()\n ds.read_scenario_file(args.scenario)\n\n for i in range(iterations):\n print(\"\\nSimulation Step:\", i)\n\n valid_moves = ds.valid_moves()\n move = agent.choose_move(ds.location, list(valid_moves),\n dict(ds.disease), ds.threshold, ds.growth, ds.spread)\n\n print(\"Selected move:\", move)\n\n ds.move(move)\n ds.spread_disease()\n total_disease = print_summary(ds)\n\n if args.viz:\n show_graph(ds)\n\n if total_disease < 0.001:\n print(\"You eradicated all disease! Good job.\")\n break\n if total_disease >= 100000:\n print(\"Total disease went over 100000.\")\n print(\n \"Everybody is dead, kangaroos, wallabies and wombats roam freely across the land.\")\n break\n sim_data = {}\n sim_data['last_step'] = i\n sim_data['final_disease'] = total_disease\n sim_data['score'] = 0.0\n if total_disease < 100000:\n if i < args.horizon - 1:\n sim_data['score'] = args.horizon - i\n else:\n sim_data['score'] = 1.0 - \\\n float(total_disease)/float(100000)\n simulations_data['runs'].append(sim_data)\n simulations_data['average_score'] += sim_data['score']\n end_time = time.clock()\n simulations_data['runtime'] = end_time - start_time\n simulations_data['average_score'] /= float(args.num_sims)\n\n import json\n print(simulations_data)\n with open('{}.results.json'.format(os.path.basename(args.scenario).replace('.scn', '')), 'w') as output:\n output.write(json.dumps(simulations_data,\n sort_keys=True, indent=4))\n print(\"Simulation finished in {}\".format(end_time - start_time))\n\n except Exception:\n print(\"Error: unexpected exception while running the simulation.\")\n print(traceback.format_exc())\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"assignment-0/disease_simulation.py","file_name":"disease_simulation.py","file_ext":"py","file_size_in_byte":26877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"559745314","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/2/19 9:14\n# @Author : LI Dongdong\n# @FileName: 求每层的节点数.py\n''''''\n'''\n题目分析\n1.要求:\n2.理解:\n3.类型:\n4.确认输入输出及边界条件:\n4.方法及方法分析:\ntime complexity order: \nspace complexity order: \n'''\n'''\n思路:BFS\n方法:\n while + width = len(queue) + for _ in range(queue)\ntime complex: \nspace complex: \n易错点:for之后进行popleft\n'''\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nfrom collections import deque\nclass Solution:\n def levelNodeNumb(self, root: TreeNode) -> int:\n if not root: # corner case\n return 0\n\n width = 0\n res = []\n queue = deque([root])\n\n while queue:\n width = len(queue)\n res.append(width)\n for _ in range(width): # traversal all same level node\n node = queue.popleft() # 易错点\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n return res\n\n'''\n思路:DFS\n方法:\n while + for\ntime complex: \nspace complex: \n易错点:用level标记层数,用dic记录\n'''\n\nclass Solution:\n def levelNodeNumb(self, root: TreeNode) -> int:\n if not root: # corner case\n return 0\n\n level = 0\n dic = {}\n\n self. width(root, level, dic)\n return dic\n\n def width(self, root, level, dic): # output: dic\n if not root: # corner case\n return {}\n\n if level not in dic:\n dic[level] = 1\n else:\n dic[level] += 1\n\n self.width(root.left, level + 1, dic)\n self.width(root.right, level + 1, dic)\n\nfrom collections import deque\ndef constructTree(nodeList): # input: list using bfs, output: root\n new_node = []\n for elem in nodeList: # transfer list val to tree node\n if elem:\n new_node.append(TreeNode(elem))\n else:\n new_node.append(None)\n\n queue = deque()\n queue.append(new_node[0])\n\n resHead = queue[0]\n i = 1\n\n while i <= len(new_node) - 1: # bfs method building\n head = queue.popleft()\n head.left = new_node[i] # build left and push\n queue.append(head.left)\n if i + 1 == len(new_node): # if no i + 1 in new_node\n break\n head.right = new_node[i + 1] # build right and push\n queue.append(head.right)\n i = i + 2\n return resHead\n\n\nroot = constructTree([1,2,3,4,None,5])\nx = Solution()\nprint(x.levelNodeNumb(root))","sub_path":"Binary tree/二叉树性质相关题目/求每层的节点数.py","file_name":"求每层的节点数.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"331689741","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport mltools as ml\n\nX = np.genfromtxt(\"data/X_train.txt\", delimiter = None)\nY = np.genfromtxt(\"data/Y_train.txt\", delimiter = None)\n#Xtest = np.genfromtxt(\"data/X_test.txt\", delimiter = None)\n\nX, Y = ml.shuffleData(X, Y)\nXtr, Ytr = X[: 10000, : ], Y[: 10000]\nXval, Yval = X[10000:20000], Y[10000:20000]\n\n#nBag = [1,3,5,7,10,13,16,20,22,25]\nnBag = range(1,41)\navgerrTrain, avgerrVal = [], []\nfor i in range(len(nBag)):\n\tdt = [None] * nBag[i]\n\tfor j in range(nBag[i]):\n\t\t#Xti, Yti = ml.bootstrapData(Xtr, Ytr, n_boot=np.size(Xtr, 1))\n\t\tXti, Yti = ml.bootstrapData(Xtr, Ytr)\n\t\t#dt[j] = ml.dtree.treeClassify(Xti, Yti, maxDepth=15, minLeaf=4, nFeatures=9)\n\t\tdt[j] = ml.dtree.treeClassify(Xti, Yti, maxDepth=6, nFeatures=7)\n\t\n\tmTest, mVal = Xtr.shape[0], Xval.shape[0]\n\tYhattr = np.zeros((mTest, nBag[i]))\n\tYhatval = np.zeros((mVal, nBag[i]))\n\tfor j in range(nBag[i]):\n\t\tYhattr[:,j] = dt[j].predict(Xtr)\n\t\tYhatval[:,j] = dt[j].predict(Xval)\n\n\tYhattr = np.mean(Yhattr, axis=1) > 0.5\n\tYhatval = np.mean(Yhatval, axis=1) > 0.5\n\terrTrain = np.mean(Yhattr != Ytr)\n\terrVal = np.mean(Yhatval != Yval)\n\t\n\t\n\tavgerrTrain.append(errTrain)\n\tavgerrVal.append(errVal)\n\nplt.plot(nBag, avgerrTrain, 'r', nBag, avgerrVal, 'g')\nplt.title('Error vs Ensemble size')\nplt.show()\n\n#Ypred = dt.predictSoft(Xtest)\n#np.savetxt('dtree_q2.txt', np.vstack((np.arange(len(Ypred)),\\\n#Ypred[:, 1])).T, '%d, %.2f', header='ID,Prob1',comments='',\\\n#delimiter=',')\n\n","sub_path":"hw4/2a.py","file_name":"2a.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"547330185","text":"## interaction3 / mfield / scripts / simulate_transmit_beamplot_with_corrected_folding_error.py\n\nimport numpy as np\nimport multiprocessing\nimport os\nimport sqlite3 as sql\nfrom itertools import repeat\nfrom contextlib import closing\nfrom tqdm import tqdm\nimport traceback\nimport sys\n\nfrom interaction3 import abstract, util\nfrom interaction3.mfield.solvers import TransmitBeamplot\n\n# register adapters for sqlite to convert numpy types\nsql.register_adapter(np.float64, float)\nsql.register_adapter(np.float32, float)\nsql.register_adapter(np.int64, int)\nsql.register_adapter(np.int32, int)\n\n# set default script parameters\ndefaults = {}\ndefaults['threads'] = multiprocessing.cpu_count()\ndefaults['transmit_focus'] = None\ndefaults['delay_quantization'] = 0\n\n\n## PROCESS FUNCTIONS ##\n\nPOSITIONS_PER_PROCESS = 1000\n\n\ndef init_process(_write_lock, _simulation, _arrays):\n\n global write_lock, simulation_base, arrays_base\n\n write_lock = _write_lock\n simulation_base = abstract.loads(_simulation)\n arrays_base = abstract.loads(_arrays)\n\n # important! avoid solver overriding current delays\n if 'transmit_focus' in simulation_base:\n simulation_base.pop('transmit_focus')\n if 'receive_focus' in simulation_base:\n simulation_base.pop('receive_focus')\n\n\ndef process(job):\n\n job_id, (file, field_pos, rotation_rule) = job\n\n rotation_rule = rotation_rule[0] # remove enclosing list\n arrays = arrays_base.copy()\n simulation = simulation_base.copy()\n\n # rotate arrays based on rotation rule\n for array_id, dir, angle in rotation_rule:\n for array in arrays:\n if array['id'] == array_id:\n abstract.rotate_array(array, dir, np.deg2rad(angle))\n\n # set focus delays while array is in rotated state\n focus = simulation['focus']\n if focus is not None:\n c = simulation['sound_speed']\n delay_quant = simulation['delay_quantization']\n for array in arrays:\n abstract.focus_array(array, focus, c, delay_quant, kind='both')\n\n arrays_plus = arrays.copy()\n arrays_minus = arrays.copy()\n\n # rotate arrays again based on plus and minus tolerance\n angle_tol = simulation['angle_tolerance']\n for array_id, dir, _ in rotation_rule:\n for array in arrays_plus:\n if array['id'] == array_id:\n abstract.rotate_array(array, dir, np.deg2rad(angle_tol))\n\n for array in arrays_minus:\n if array['id'] == array_id:\n abstract.rotate_array(array, dir, np.deg2rad(-angle_tol))\n\n # create and run simulation\n kwargs, meta = TransmitBeamplot.connector(simulation, *arrays_plus)\n solver_plus = TransmitBeamplot(**kwargs)\n solver_plus.solve(field_pos)\n\n # create and run simulation\n kwargs, meta = TransmitBeamplot.connector(simulation, *arrays_minus)\n solver_minus = TransmitBeamplot(**kwargs)\n solver_minus.solve(field_pos)\n\n # extract results and save\n angle = rotation_rule[0][2]\n\n with write_lock:\n with closing(sql.connect(file)) as con:\n\n rf_data = solver_plus.result['rf_data']\n p = np.max(util.envelope(rf_data, axis=1), axis=1)\n update_image_table(con, angle, angle_tol, 'plus', field_pos, p)\n\n rf_data = solver_minus.result['rf_data']\n p = np.max(util.envelope(rf_data, axis=1), axis=1)\n update_image_table(con, angle, angle_tol, 'minus', field_pos, p)\n\n util.update_progress(con, job_id)\n\n\ndef run_process(*args, **kwargs):\n\n try:\n return process(*args, **kwargs)\n except:\n raise Exception(\"\".join(traceback.format_exception(*sys.exc_info())))\n\n\n## ENTRY POINT ##\n\ndef main(**args):\n\n # get abstract objects from specification\n spec = args['spec']\n\n objects = TransmitBeamplot.get_objects_from_spec(*spec)\n simulation = objects[0]\n arrays = objects[1:]\n\n # set defaults with the following priority: command line arguments >> simulation object >> script defaults\n for k, v in simulation.items():\n args.setdefault(k, v)\n if args[k] is None:\n args[k] = v\n for k, v in defaults.items():\n args.setdefault(k, v)\n if args[k] is None:\n args[k] = v\n\n print('simulation parameters as key --> value:')\n for k, v in args.items():\n print(k, '-->', v)\n\n # get args needed in main\n file = args['file']\n threads = args['threads']\n mode = args['mesh_mode']\n mesh_vector1 = args['mesh_vector1']\n mesh_vector2 = args['mesh_vector2']\n mesh_vector3 = args['mesh_vector3']\n rotations = args['rotations']\n a_start, a_stop, a_step = args['angles']\n\n # create field positions\n field_pos = util.meshview(np.linspace(*mesh_vector1), np.linspace(*mesh_vector2), np.linspace(*mesh_vector3),\n mode=mode)\n\n # create angles\n angles = np.arange(a_start, a_stop + a_step, a_step)\n\n # create rotation rules which will be distributed by the pool\n array_ids = [id for id, _ in rotations]\n dirs = [dir for _, dir in rotations]\n zip_args = []\n for id, dir in zip(array_ids, dirs):\n zip_args.append(zip(repeat(id), repeat(dir), angles))\n rotation_rules = list(zip(*zip_args))\n\n # calculate job-related values\n is_complete = None\n njobs = int(np.ceil(len(field_pos) / POSITIONS_PER_PROCESS) * len(rotation_rules))\n ijob = 0\n\n # check for existing file\n if os.path.isfile(file):\n\n response = input('File ' + str(file) + ' already exists.\\n' +\n 'Continue (c), overwrite (o), or do nothing (any other key)?')\n\n if response.lower() in ['o', 'overwrite']: # if file exists, prompt for overwrite\n\n os.remove(file) # remove existing file\n create_database(file, args, njobs, field_pos) # create database\n\n elif response.lower() in ['c', 'continue']: # continue from current progress\n is_complete, ijob = util.get_progress(file)\n\n else:\n raise Exception('Database already exists')\n\n else:\n\n # Make directories if they do not exist\n file_dir = os.path.dirname(os.path.abspath(file))\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n\n # create database\n create_database(file, args, njobs, field_pos)\n\n try:\n\n # start multiprocessing pool and run process\n write_lock = multiprocessing.Lock()\n simulation = abstract.dumps(simulation)\n arrays = abstract.dumps(arrays)\n pool = multiprocessing.Pool(threads, initializer=init_process, initargs=(write_lock, simulation, arrays))\n\n jobs = util.create_jobs(file, (field_pos, POSITIONS_PER_PROCESS), (rotation_rules, 1), mode='product',\n is_complete=is_complete)\n result = pool.imap_unordered(run_process, jobs)\n\n for r in tqdm(result, desc='Simulating', total=njobs, initial=ijob):\n pass\n\n except Exception as e:\n print(e)\n\n finally:\n\n pool.terminate()\n pool.close()\n\n\n## DATABASE FUNCTIONS ##\n\ndef create_database(file, args, njobs, field_pos):\n\n with closing(sql.connect(file)) as con:\n # create database tables (metadata, progress, field_positions, pressures)\n util.create_metadata_table(con, **args)\n util.create_progress_table(con, njobs)\n create_field_positions_table(con, field_pos)\n create_image_table(con)\n\n\ndef create_field_positions_table(con, field_pos):\n\n x, y, z = np.atleast_2d(field_pos).T\n\n with con:\n # create table\n con.execute('CREATE TABLE field_positions (x float, y float, z float)')\n # create indexes\n con.execute('CREATE UNIQUE INDEX field_position_index ON field_positions (x, y, z)')\n # insert values into table\n con.executemany('INSERT INTO field_positions VALUES (?, ?, ?)', zip(x, y, z))\n\n\ndef create_image_table(con):\n\n with con:\n # create table\n query = '''\n CREATE TABLE image (\n id INTEGER PRIMARY KEY,\n angle float,\n angle_tolerance float,\n error_type string,\n x float,\n y float,\n z float,\n brightness float,\n FOREIGN KEY (x, y, z) REFERENCES field_positions (x, y, z)\n )\n '''\n con.execute(query)\n # create indexes\n con.execute('CREATE INDEX image_index ON image (angle, x, y, z)')\n\n\ndef update_image_table(con, angle, angle_tol, error_type, field_pos, brightness):\n\n x, y, z = np.array(field_pos).T\n\n with con:\n query = '''\n INSERT INTO image (angle, angle_tolerance, error_type, x, y, z, brightness)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n '''\n con.executemany(query, zip(repeat(angle), repeat(angle_tol), repeat(error_type), x, y, z, brightness.ravel()))\n\n\n## COMMAND LINE INTERFACE ##\n\ndef parse_rotation(string):\n try:\n return int(string)\n except ValueError:\n return string\n\n\nif __name__ == '__main__':\n\n import argparse\n\n # define and parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('file', nargs='?')\n parser.add_argument('-s', '--spec', nargs='+')\n parser.add_argument('-t', '--threads', type=int)\n # parser.add_argument('-r', '--rotations', nargs=2, action='append', type=parse_rotation)\n # parser.add_argument('-a', '--angles', nargs=3, type=float)\n\n args = vars(parser.parse_args())\n main(**args)\n\n","sub_path":"interaction3/mfield/scripts/simulate_transmit_beamplot_with_corrected_folding_error.py","file_name":"simulate_transmit_beamplot_with_corrected_folding_error.py","file_ext":"py","file_size_in_byte":9551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"336437468","text":"\ndef caesarCipher(s, k):\n alpha = set(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\")\n chars = list(s)\n cipher = []\n for c in chars:\n if c in alpha:\n cipher.append(fix(c, k))\n else:\n cipher.append(c)\n return ''.join(cipher)\n\ndef fix(c, k):\n for x in range(k):\n i = ord(c)\n if c == 'z':\n c = 'a'\n continue\n elif c == 'Z':\n c = 'A'\n continue\n i += 1 \n c = chr(i)\n return c\n\n\nprint(caesarCipher('abc', 2))\nprint(caesarCipher('middle-Outz', 2))\nprint(caesarCipher('Always-Look-on-the-Bright-Side-of-Life', 5))","sub_path":"ceasercipher.py","file_name":"ceasercipher.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"652403478","text":"#importing libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n#importing dataset\ndf = pd.read_csv('Mall.csv')\nx = df.iloc[:,[3,4]].values\n\n#choosing value for k\nfrom sklearn.cluster import KMeans\nwcss = []\nfor i in range(1,11):\n kmean = KMeans(n_clusters= i, init='k-means++',max_iter= 300, n_init=10,random_state = 0)\n kmean.fit(x)\n wcss.append(kmean.inertia_)\n \nplt.plot(range(1,11),wcss)\nplt.title('The Elbow Method')\nplt.xlabel('K value')\nplt.ylabel('WCSS')\nplt.show()\n\nkmean = KMeans(n_clusters=5,n_init=10,init = 'k-means++',max_iter=300,random_state = 0)\ny_means = kmean.fit_predict(x)\n\n\n\n#visualizing \nplt.scatter(x[y_means == 0,0],x[y_means == 0,1],s = 100,c = 'red', label = 'Cluster1')\nplt.scatter(x[y_means == 1,0],x[y_means == 1,1],s = 100,c = 'blue', label = 'Cluster2')\nplt.scatter(x[y_means == 2,0],x[y_means == 2,1],s = 100,c = 'orange', label = 'Cluster3')\nplt.scatter(x[y_means == 3,0],x[y_means == 3,1],s = 100,c = 'green', label = 'Cluster4')\nplt.scatter(x[y_means == 4,0],x[y_means == 4,1],s = 100,c = 'pink', label = 'Cluster5')\nplt.scatter(kmean.cluster_centers_[:,0],kmean.cluster_centers_[:,1],s = 300,c = 'yellow', label = 'Centroid')\nplt.title('K-Means Clustering')\nplt.xlabel('Annual income')\nplt.ylabel('Spending score')\nplt.legend()\nplt.show()\n","sub_path":"K-means Clustering/k_means_clustering.py","file_name":"k_means_clustering.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"286765888","text":"from construct import *\nfrom recipe import *\nfrom math import log\n\n\ndef _factory(fname, default_fields=None, idn=None, reformer=None):\n lst = None\n class _Adapter(Adapter):\n def _encode(self, obj, ctx):\n return obj._id\n\n def _decode(self, obj, ctx):\n nonlocal lst\n lst = lst or read_d2_file(fname, default_fields, idn, reformer)\n return lst[obj]\n return _Adapter\n\nD2Attribute = lambda name: _factory(\"txt\\\\exp\\\\ItemStatCost.txt\", (\"Stat\", \"ValShift\"), \"ID\")(ULInt8(name))\nD2Object = lambda name: _factory(\"txt\\\\exp\\\\objects.txt\", (\"Name\", \"description_-_not_loaded\"), \"Id\")(ULInt16(name))\nD2Skill = lambda name: _factory(\"txt\\\\exp\\\\skills.txt\", (\"skill\", \"charclass\"), \"Id\")(ULInt16(name))\nD2Monstat = lambda name: _factory(\"txt\\\\exp\\\\monstats.txt\", (\"namco\", \"Type\"), \"PopulateId\")(ULInt16(name))\n\ndef D2Montype_reformer(d):\n ifields = (\"BL_Dir\", \"S3_Dir\", \"GH_Dir\", \"WL_Dir\", \"A1_Dir\", \"DT_Dir\",\n \"S2_Dir\", \"A2_Dir\", \"SC_Dir\", \"RN_Dir\", \"S4_Dir\", \"NU_Dir\", \"S1_Dir\",\n \"SQ_Dir\", \"DD_Dir\", \"KB_Dir\"\n )\n rd = {}\n padding = 0\n for k, v in d.items():\n if k in ifields:\n padding = padding + int(log(int(v), 2))\n else:\n rd[k] = v\n rd[\"stats_length\"] = padding\n return rd\n\ndef D2Montype(class_code_name, name):\n f = _factory(\"txt\\\\exp\\\\MonType.txt\", None, None, D2Montype_reformer)\n return f(Value(name, lambda ctx: ctx[class_code_name][\"_id\"]))\n","sub_path":"list_d2_files.py","file_name":"list_d2_files.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"86065637","text":"import datetime\nfrom random import randint\n\nmonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nmax_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\ndef get_12_hour_time(hour, minute):\n if hour <= 12:\n am_pm = 'AM'\n else:\n hour -= 12\n am_pm = 'PM'\n\n if minute < 10:\n str_min = '0' + str(minute)\n else:\n str_min = str(minute)\n\n return f'{str(hour)}:{str_min} {am_pm}'\n\ndef gen_minute():\n return randint(1, 59)\n\ndef gen_hour():\n return randint(1, 24)\n\ndef gen_day(month, year):\n if month == 2:\n if year % 4 == 0:\n return randint(1, 29)\n else:\n return randint(1, 28)\n else:\n return randint(1, max_days[month - 1])\n\ndef gen_month():\n return randint(1, 12)\n\ndef gen_datetime(start_year):\n current_datetime = datetime.datetime.now()\n current_year = current_datetime.year\n current_month = current_datetime.month\n current_day = current_datetime.day\n current_hour = current_datetime.hour\n current_minute = current_datetime.minute\n year = randint(start_year, current_year)\n if year == current_year:\n month = randint(1, current_month)\n if month == current_month:\n day = randint(1, current_day)\n if day == current_day:\n hour = randint(1, current_hour)\n if hour == current_hour:\n minute = randint(1, current_minute)\n else:\n minute = gen_minute()\n else:\n hour = gen_hour()\n minute = gen_minute()\n else:\n day = gen_day(month, year)\n hour = gen_hour()\n minute = gen_minute()\n else:\n month = gen_month()\n day = gen_day(month, year)\n hour = gen_hour()\n minute = gen_minute()\n \n return f'{get_12_hour_time(hour, minute)} - {months[month - 1]} {day}, {year}'\n","sub_path":"randomdate.py","file_name":"randomdate.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"22295244","text":"from django.shortcuts import render, render_to_response\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.template import RequestContext\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\nimport random, string\nfrom base.views import getJsonResponse\n\n\ndef write_segment_file( view_id, segment_id, bitrate, segment_durations, base_url, instant_switch, write_header=False ):\n\n filename = \"%s-%sk.m3u8\" % ( view_id, bitrate )\n\n # get max segment_durations for ext-x-targetduration\n with open(settings.PLAYLISTS_DIR + '/' + filename, \"a\") as f:\n if write_header:\n f.write('#EXTM3U\\n#EXT-X-ALLOW-CACHE:NO\\n#EXT-X-PLAYLIST-TYPE:%s\\n#EXT-X-TARGETDURATION:10\\n' % ( ('VOD' if instant_switch else 'EVENT')) )\n\n for i in xrange( 1, len(segment_durations) + 1 ):\n f.write('#EXTINF:%s,\\n%s/%s-%sk-000%02d.ts\\n' % (segment_durations[i-1], base_url, segment_id, bitrate, i))\n\n if instant_switch:\n f.write('#EXT-X-ENDLIST')\n\n\ndef init_playlists( request, view_id, segment_id, bitrates, segment_durations, base_url, instant_switch ):\n\n data = render_to_string('hls_playlist.html', {'segment_id' : segment_id, 'view_id' : view_id, 'bitrates' : bitrates, 'instant_switch' : instant_switch }, context_instance=RequestContext(request))\n\n filename = '%s.m3u8' % (view_id)\n\n # write the master playlist file\n with open(settings.PLAYLISTS_DIR + '/' + filename, \"w\") as f:\n f.write(data)\n\n for bitrate in bitrates:\n write_segment_file( view_id, segment_id, bitrate, segment_durations, base_url, instant_switch, write_header=True )\n\n return 'static/playlists/' + filename\n\n\ndef hls_choose( request ):\n\n view_id = request.POST['view_id']\n segment_id = request.POST['segment_id']\n instant_switch = request.POST['instant_switch'] == '1'\n bitrates = request.POST['bitrates'].split(',')\n base_url = request.POST['base_url']\n segment_durations = request.POST['segment_durations'].split(',')\n\n if instant_switch == True:\n view_id = get_view_id() \n playlist = init_playlists( request, view_id, segment_id, bitrates, segment_durations, base_url, instant_switch )\n\n else:\n playlist = 'static/playlists/%s.m3u8' % ( view_id )\n for bitrate in bitrates:\n write_segment_file( view_id, segment_id, bitrate, segment_durations, base_url, instant_switch )\n\n return getJsonResponse( {'success' : 1, 'view_id' : view_id, 'playlist' : '/' + playlist} )\n\n\ndef get_view_id():\n return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(15))\n \n\ndef hls_create( request ):\n\n view_id = get_view_id();\n\n bitrates = request.GET['bitrates'].split(',')\n segment_id = request.GET['segment_id']\n segment_durations = request.GET['segment_durations'].split(',')\n base_url = request.GET['base_url']\n instant_switch = request.GET['instant_switch'] == '1'\n\n playlist = init_playlists( request, view_id, segment_id, bitrates, segment_durations, base_url, instant_switch )\n\n return getJsonResponse( {'success' : 1, 'playlist' : '/' + playlist, 'view_id' : view_id} )\n \n\n","sub_path":"web/base/hls.py","file_name":"hls.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"373047205","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport common.utils\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('account', '0002_account_owner'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('attach', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Candidate',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created_at', models.DateTimeField(auto_now_add=True, null=True)),\n ('modified_at', models.DateTimeField(auto_now=True, null=True)),\n ('name', models.CharField(max_length=255)),\n ('city', models.CharField(default=b'', max_length=255)),\n ('color', models.CharField(default=common.utils.generate_random_color, max_length=7)),\n ('account', models.ForeignKey(to='account.Account')),\n ('created_by', models.ForeignKey(related_name='created_candidate_candidate', to=settings.AUTH_USER_MODEL, null=True)),\n ('modified_by', models.ForeignKey(related_name='modified_candidate_candidate', to=settings.AUTH_USER_MODEL, null=True)),\n ('photo', models.ForeignKey(to='attach.AttachedImage', null=True)),\n ('resume', models.ForeignKey(to='attach.AttachedFile', null=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n","sub_path":"backend/rbapps/candidate/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"317430852","text":"#!/usr/bin/env python\n\"\"\"\ninfo about project here\n\"\"\"\n\n\n...\n\n__author__ = \"Johannes Coolen\"\n__email__ = \"johannes.coolen@student.kdg.be\"\n__status__ = \"development\"\n\n\ndef reverseword(woord):\n result = []\n for i in woord:\n result.insert(0, i)\n print(\"\".join(result))\n\n\ndef main():\n woord = list(input(\"geef een woord\"))\n reverseword(woord)\n\n\nif __name__ == '__main__': # code to execute if called from command-line\n main()\n","sub_path":"make/1.2.2/reverseword.py","file_name":"reverseword.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"57510858","text":"#Main file launching the GUI and calling the deeplearning algorithms\n\nimport os\nimport cv2\nimport numpy as np\nfrom PyQt5 import QtCore, QtGui, QtWidgets # uic\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QWidget, QLabel, QVBoxLayout, QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QGridLayout) # +++\n \nfrom PyQt5.QtGui import QPixmap, QFont\n\nimport datetime\n\nfrom pymongo import MongoClient\n\n#Name current file in analysis\nname =''\n\n##################################### Layout classes\n#Layout Readingdata\nclass ReadData(QWidget):\n def __init__(self, parent=None):\n super(ReadData, self).__init__(parent)\n \n client = MongoClient()\n db = client.DATABASE_malaria\n collection = db.data\n lista = list(collection.find({},{\"_id\":0}))\n n_saved = int(''.join(map(str,np.shape(lista))))\n self.tableWidget = QTableWidget()\n self.tableWidget.setRowCount(n_saved)\n self.tableWidget.setColumnCount(2)\n self.tableWidget.setHorizontalHeaderLabels([\"Patient ID\",\"N. plasmoids\"])\n\n\n #Loop iterating all saved data\n for x in range(n_saved):\n val = str(lista[x])\n self.tableWidget.setItem(x,0,QTableWidgetItem(val[15:-14])) #Name shortened\n self.tableWidget.setItem(x,1,QTableWidgetItem(\"0\")) #Name shortened\n self.tableWidget.setEditTriggers(QTableWidget.NoEditTriggers) #Set non editable\n self.tableWidget.resizeColumnsToContents()\n self.layout = QtWidgets.QHBoxLayout() \n \n self.labelImage = QLabel(self)\n self.pixmap = QPixmap( 'folders.png')\n self.smaller_pixmap =self.pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n self.labelImage.setPixmap( self.smaller_pixmap)\n self.labelImage.move(10, 10)\n self.back = QPushButton(\"Back\", self)\n self.layout.addWidget(self.back) \n self.back.resize(80, 50) \n self.back.setFont(QFont('Arial', 18))\n\n\n\n self.layout.addWidget(self.labelImage) \n\n self.layout.addWidget(self.tableWidget) \n self.setLayout(self.layout) \n \n# self.tableWidget.move(500,40)\n \n #self.show()\n\n #self.back.move(250, 750)\n \n self.tableWidget.doubleClicked.connect(self.on_click)\n self.show()\n #Personalize per image\n def on_click(self):\n for current in self.tableWidget.selectedItems():\n selected=current.row()\n client = MongoClient()\n db = client.DATABASE_malaria\n collection = db.data\n imm_select = list(collection.find({},{\"image_name\":1,\"_id\":0}))\n val_selected = str(imm_select[selected])\n val_selected = val_selected[16:-2]\n # val_selected = val_selected[:-]\n\n# print(val_selected[16:-2])\n path = r'data/' \n self.pixmap = QPixmap(os.path.join(path, 'res_' + val_selected))\n self.smaller_pixmap =self.pixmap.scaled(400, 400, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n self.labelImage.setPixmap( self.smaller_pixmap)\n \n self.show()\n\n\n#Layout Insertingdata\nclass SetData(QWidget):\n def __init__(self, parent=None):\n super(SetData, self).__init__(parent)\n\n path = r'data/' \n self.labelImage = QLabel(self)\n self.pixmap = QPixmap(os.path.join(path, 'res_' + name))\n self.smaller_pixmap =self.pixmap.scaled(450, 450, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n self.labelImage.setPixmap( self.smaller_pixmap)\n self.labelImage.move(50, 10)\n \n self.textlabel = QLabel(self)\n self.textlabel.setText(\"Insert ID patient\")\n self.textlabel.move(515, 40)\n self.textlabel.setFont(QFont('Arial', 18))\n\n self.textbox = QLineEdit(self)\n self.textbox.move(540, 65)\n self.textbox.resize(120,30)\n self.textlabel.setFont(QFont('Arial', 18))\n\n self.one = QPushButton(\"1\", self)\n self.one.move(530, 100)\n self.one.resize(40,40)\n self.one.setFont(QFont('Arial', 18))\n\n\n self.two = QPushButton(\"2\", self)\n self.two.move(585, 100)\n self.two.resize(40,40)\n self.two.setFont(QFont('Arial', 18))\n\n\n self.three = QPushButton(\"3\", self)\n self.three.move(640, 100)\n self.three.resize(40,40)\n self.three.setFont(QFont('Arial', 18))\n\n\n self.four = QPushButton(\"4\", self)\n self.four.move(530, 160)\n self.four.resize(40,40)\n self.four.setFont(QFont('Arial', 18))\n\n self.five = QPushButton(\"5\", self)\n self.five.move(585, 160)\n self.five.resize(40,40)\n self.five.setFont(QFont('Arial', 18))\n\n self.six = QPushButton(\"6\", self)\n self.six.move(640, 160)\n self.six.resize(40,40)\n self.six.setFont(QFont('Arial', 18))\n\n\n self.seven = QPushButton(\"7\", self)\n self.seven.move(530, 220)\n self.seven.resize(40,40)\n self.seven.setFont(QFont('Arial', 18))\n\n self.eight = QPushButton(\"8\", self)\n self.eight.move(585, 220)\n self.eight.resize(40,40)\n self.eight.setFont(QFont('Arial', 18))\n\n self.nine = QPushButton(\"9\", self)\n self.nine.move(640, 220)\n self.nine.resize(40,40)\n self.nine.setFont(QFont('Arial', 18))\n\n self.zero = QPushButton(\"0\", self)\n self.zero.move(530, 280)\n self.zero.resize(40,40)\n self.zero.setFont(QFont('Arial', 18))\n\n self.delete = QPushButton(\"delete\", self)\n self.delete.move(590, 280)\n self.delete.resize(90,40)\n self.delete.setFont(QFont('Arial', 18))\n\n\n '''\n self.layout = QGridLayout()\n self.layout.addWidget(QPushButton('Button (0, 0)'), 0, 0)\n self.layout.addWidget(QPushButton('Button (0, 1)'), 0, 1)\n self.layout.addWidget(QPushButton('Button (0, 2)'), 0, 2)\n self.layout.addWidget(QPushButton('Button (1, 0)'), 1, 0)\n self.layout.addWidget(QPushButton('Button (1, 1)'), 1, 1)\n self.layout.addWidget(QPushButton('Button (1, 2)'), 1, 2)\n self.layout.addWidget(QPushButton('Button (2, 0)'), 2, 0)\n self.layout.addWidget(QPushButton('Button (2, 1) + 2 Columns Span'), 2, 1, 1, 2)\n self.layout.setRowStretch(0, 6)\n self.layout.setRowStretch(1, 4)\n # self.setLayout(self.layout) \n \t\n #window.setLayout(layout)\n ''' \n self.Save = QPushButton(\"Save\", self)\n self.Save.move(190, 350)\n self.Save.setFont(QFont('Arial', 18))\n\n\n\n self.back = QPushButton(\"Back\", self)\n self.back.move(290, 450)\n self.back.setFont(QFont('Arial', 18))\n\n self.Save.setEnabled(False);\n self.textbox.textChanged.connect(self.disableButton)\n\n def disableButton(self):\n if len(self.textbox.text()) > 0:\n self.Save.setEnabled(True);\n\n\n\n#Layout 3 analysis\nclass Analysis(QWidget):\n def __init__(self, parent=None):\n super(Analysis, self).__init__(parent)\n\n #self.labelImage = QLabel(self)\n #self.pixmap = QPixmap(\"microscope.png\")\n #self.smaller_pixmap =self.pixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n #self.labelImage.setPixmap( self.smaller_pixmap)\n #self.labelImage.move(50, 100)\n\n self.thick = QPushButton(\"Thick smear\", self)\n self.thick.move(180, 350)\n self.thick.setFont(QFont('Arial', 18))\n\n\n self.labelImage = QLabel(self)\n self.pixmap = QPixmap(\"thinandthick.jpg\")\n #self.smaller_pixmap =self.pixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n self.labelImage.setPixmap( self.pixmap)\n\n self.labelImage.move(100, 100)\n\n self.thin = QPushButton(\"Thin smear\", self)\n self.thin.move(460, 350)\n self.thin.setFont(QFont('Arial', 18))\n\n\n self.back = QPushButton(\"Back\", self)\n self.back.move(330, 450)\n self.back.setFont(QFont('Arial', 18))\n\n\n#Layout 2 starting menu\nclass UIToolTab(QWidget):\n def __init__(self, parent=None):\n super(UIToolTab, self).__init__(parent)\n\n self.labelImage = QLabel(self)\n self.pixmap = QPixmap(\"microscope.png\")\n self.smaller_pixmap =self.pixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n self.labelImage.setPixmap( self.smaller_pixmap)\n self.labelImage.move(120, 100)\n self.CPSBTN = QPushButton(\"Acquire Data\", self)\n self.CPSBTN.move(160, 400) \n #self.CPSBTN.resize(130, 50) \n self.CPSBTN.setFont(QFont('Arial', 18))\n\n self.labelImage = QLabel(self)\n self.pixmap = QPixmap(\"folders.png\")\n self.smaller_pixmap =self.pixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)\n self.labelImage.setPixmap( self.smaller_pixmap)\n self.labelImage.move(435, 100)\n\n self.database = QPushButton(\"Look up database\", self)\n self.database.move(435, 400)\n #self.database.resize(200, 50) \n self.database.setFont(QFont('Arial', 18))\n\n \n\n \n\n#layout1 where images are captured\nclass Ui_Form(QWidget):\n def setupUi(self, Form):\n Form.setObjectName(\"Form\")\n #Form.resize(725, 586)\n self.horizontalLayout = QtWidgets.QHBoxLayout(Form)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setObjectName(\"verticalLayout\")\n\n self.image_label = QtWidgets.QLabel(Form,alignment=QtCore.Qt.AlignCenter)\n self.image_label.setText(\"\")\n self.image_label.setObjectName(\"image_label\")\n self.verticalLayout.addWidget(self.image_label)\n \n self.control_bt = QtWidgets.QPushButton(Form)\n self.control_bt.setObjectName(\"control_bt\")\n self.control_bt.setFont(QFont('Arial', 16))\n\n self.verticalLayout.addWidget(self.control_bt)\n\n self.capture = QtWidgets.QPushButton(Form)\n self.capture.setObjectName(\"capture\")\n self.capture.setFont(QFont('Arial', 16))\n\n self.verticalLayout.addWidget(self.capture)\n\n# self.thick = QtWidgets.QPushButton(Form)\n# self.thick.setObjectName(\"thick\")\n# self.verticalLayout.addWidget(self.thick)\n\n# self.thin = QtWidgets.QPushButton(Form)\n# self.thin.setObjectName(\"thin\")\n# self.verticalLayout.addWidget(self.thin)\n\n\n # self.statlabel = QtWidgets.QLabel(Form,alignment=QtCore.Qt.AlignCenter)\n # self.statlabel.setObjectName(\"statlabel\")\n # self.statlabel.resize(10, 40)\n # self.verticalLayout.addWidget(self.statlabel)\n # self.verticalLayout.setAlignment(self.statlabel, QtCore.Qt.AlignTop)\n\n self.back = QtWidgets.QPushButton(Form)\n self.back.setObjectName(\"back\")\n self.back.setFont(QFont('Arial', 16))\n\n self.verticalLayout.addWidget(self.back)\n \n self.horizontalLayout.addLayout(self.verticalLayout)\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n\n def retranslateUi(self, Form):\n _translate = QtCore.QCoreApplication.translate\n Form.setWindowTitle(_translate(\"Form\", \"Capturing\"))\n self.control_bt.setText(_translate(\"Form\", \"Start streaming\"))\n self.capture.setText(_translate(\"Form\", \"Capture\"))\n # self.thick.setText(_translate(\"Form\", \"Thick smear detection\"))\n # self.thin.setText(_translate(\"Form\", \"Thin smear detection\"))\n # self.statlabel.setText(_translate(\"Form\", \"Nothing is happening\"))\n self.back.setText(_translate(\"Form\", \"Back\"))\n######################################################################################\n\n####################### Windows classes ##############################################\n \nclass StartWindow(QMainWindow):\n def __init__(self, parent=None):\n super(StartWindow, self).__init__(parent)\n self.setGeometry(50, 50, 640, 480)\n #self.showFullScreen()\n #self.setFixedSize(400, 450)\n self.startUIToolTab()\n\n def startUIToolTab(self):\n self.ToolTab = UIToolTab(self)\n self.setWindowTitle(\"StartWindow\")\n self.setCentralWidget(self.ToolTab)\n self.ToolTab.CPSBTN.clicked.connect(self.startUIWindow)\n self.ToolTab.database.clicked.connect(self.startUIWindow2)\n self.show()\n \n def startUIWindow(self):\n self.Window = Video(self)\n self.setWindowTitle(\"UIWindow\")\n #self.setCentralWidget(self.Window)f\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n\n self.hide()\n self.Window.show()\n\n def startUIWindow2(self):\n self.Window = ReadDataWindow(self)\n self.setWindowTitle(\"Readata\")\n #self.setCentralWidget(self.Window)f\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n\n self.hide()\n self.Window.show()\n\nclass ReadDataWindow(QMainWindow):\n def __init__(self, parent=None):\n super(ReadDataWindow, self).__init__(parent)\n self.setGeometry(50, 50, 640, 480)\n self.showFullScreen()\n #self.setFixedSize(400, 450)\n self.startUIToolTab()\n\n def startUIToolTab(self):\n self.ToolTab = ReadData(self)\n self.setWindowTitle(\"ReadData\")\n self.setCentralWidget(self.ToolTab)\n self.ToolTab.back.clicked.connect(self.startUIWindow)\n\n \n def startUIWindow(self):\n self.Window = StartWindow(self)\n self.setWindowTitle(\"Analysis\")\n #self.setCentralWidget(self.Window)f\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n self.hide()\n self.Window.show()\n \n\n\nclass AnalysisWindow(QMainWindow):\n def __init__(self, parent=None):\n super(AnalysisWindow, self).__init__(parent)\n self.setGeometry(50, 50, 640, 480)\n self.showFullScreen()\n #self.setFixedSize(400, 450)\n self.startUIToolTab()\n\n def startUIToolTab(self):\n self.ToolTab = Analysis(self)\n self.setWindowTitle(\"Analysis\")\n self.setCentralWidget(self.ToolTab)\n self.ToolTab.back.clicked.connect(self.startUIWindow)\n self.ToolTab.thick.clicked.connect(self.PerformThickAnalysis)\n self.ToolTab.thin.clicked.connect(self.PerformThinAnalysis)\n\n self.show()\n \n def startUIWindow(self):\n self.Window = Video(self) #???????\n self.setWindowTitle(\"Analysis\")\n #self.setCentralWidget(self.Window)\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n self.hide()\n self.Window.show()\n\n\n def PerformThickAnalysis(self):\n\n #Load data\n path = r'data/' \n #original = cv2.imwrite(os.path.join(path, name), frame)\n img = cv2.imread(os.path.join(path, name),1)\n print('done')\n #perform Deeplearning classification\n\n cv2.imwrite(os.path.join(path, 'res_' + name), img)\n \n self.Window = SetDatasWindow(self)\n self.setWindowTitle(\"SetData\")\n #self.setCentralWidget(self.Window)\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n\n self.hide()\n self.Window.show()\n\n def PerformThinAnalysis(self):\n\n\n #Load data\n path = r'data/' \n #original = cv2.imwrite(os.path.join(path, name), frame)\n img = cv2.imread(os.path.join(path, name),1)\n print('done')\n #perform Deeplearning classification\n\n cv2.imwrite(os.path.join(path, 'res_' + name), img)\n \n self.Window = SetDatasWindow(self)\n self.setWindowTitle(\"SetData\")\n #self.setCentralWidget(self.Window)\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n\n self.hide()\n self.Window.show()\n\n\n\nclass SetDatasWindow(QMainWindow):\n def __init__(self, parent=None):\n super(SetDatasWindow, self).__init__(parent)\n self.setGeometry(50, 50, 640, 480)\n self.showFullScreen()\n #self.setFixedSize(400, 450)\n self.startUIToolTab()\n\n def startUIToolTab(self):\n self.ToolTab = SetData(self)\n self.setWindowTitle(\"SetData\")\n self.setCentralWidget(self.ToolTab)\n self.ToolTab.back.clicked.connect(self.startUIWindow)\n self.ToolTab.Save.clicked.connect(self.saveData)\n self.ToolTab.one.clicked.connect(self.addOne)\n self.ToolTab.two.clicked.connect(self.addTwo)\n self.ToolTab.three.clicked.connect(self.addThree)\n self.ToolTab.four.clicked.connect(self.addFour)\n self.ToolTab.five.clicked.connect(self.addFive)\n self.ToolTab.six.clicked.connect(self.addSix)\n self.ToolTab.seven.clicked.connect(self.addSeven)\n self.ToolTab.eight.clicked.connect(self.addEight)\n self.ToolTab.nine.clicked.connect(self.addNine)\n self.ToolTab.zero.clicked.connect(self.addZero)\n self.ToolTab.delete.clicked.connect(self.delete)\n\n self.show()\n \n def startUIWindow(self):\n self.Window = AnalysisWindow(self)\n self.setWindowTitle(\"Analysis\")\n #self.setCentralWidget(self.Window)f\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n self.hide()\n self.Window.show()\n\n def saveData(self):\n client = MongoClient()\n db = client.DATABASE_malaria\n collection = db.data\n new_id = self.ToolTab.textbox.text()\n post_id = collection.insert_one({\"patient_id\":new_id,\"image_name\":name,\"count\":\"0\"}).inserted_id\n QMessageBox.about(self, \"Database ok\", \"Data have been saved, you can proceed with another task\")\n\n def addOne(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'1')\n\n def addTwo(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'2')\n\n def addThree(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'3')\n\n def addFour(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'4')\n\n def addFive(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'5')\n\n def addSix(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'6')\n\n def addSeven(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'7')\n\n def addEight(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'8')\n\n def addNine(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'9')\n\n def addZero(self):\n self.ToolTab.textbox.setText( self.ToolTab.textbox.text()+'0')\n\n def delete(self):\n val = self.ToolTab.textbox.text()\n self.ToolTab.textbox.setText( val[:-1] )\n\nclass Video (QtWidgets.QDialog, Ui_Form):\n def __init__(self, parent=None):\t\n super().__init__() \n self.setGeometry(50, 50, 640, 480)\n# uic.loadUi('test2.ui',self) # ---\n self.setupUi(self) # +++\n self.showFullScreen()\n self.control_bt.clicked.connect(self.start_webcam)\n self.capture.clicked.connect(self.capture_image)\n self.back.clicked.connect(self.startUIWindow)\n \n # self.capture.clicked.connect(self.startUIWindow) # - ()\n\n # self.image_label.setScaledContents(True)\n self.cap = None # -capture <-> +cap\n self.streaming()\n\n\n def startUIToolTab(self):\n self.ToolTab = UIToolTab(self)\n self.setWindowTitle(\"Video\")\n #self.setCentralWidget(self.ToolTab)\n self.ToolTab.CPSBTN.clicked.connect(self.startUIWindow)\n self.show()\n \n\n def streaming(self):\n self.timer = QtCore.QTimer(self, interval=5)\n self.timer.timeout.connect(self.update_frame)\n self._image_counter = 0\n\n @QtCore.pyqtSlot()\n def start_webcam(self):\n if self.cap is None:\n self.cap = cv2.VideoCapture(0) #default is 0\n self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n # self.statlabel.setText(\"Streaming\")\n self.timer.start()\n self.flag = 1\n self.streaming()\n\n @QtCore.pyqtSlot()\n def update_frame(self):\n if (self.flag):\n ret, image = self.cap.read()\n simage = cv2.flip(image, 1)\n self.displayImage(image, True)\n\n @QtCore.pyqtSlot()\n def capture_image(self):\n flag, frame = self.cap.read()\n path = r'data/' # \n if flag:\n # QtWidgets.QApplication.beep()\n global name\n datetime_object = datetime.datetime.now() \n print(datetime_object.strftime(\"%d_%m_%Y_%H:%M:%S\"))\n name = datetime_object.strftime(\"%d_%m_%Y_%H:%M:%S\") + \".jpg\"\n cv2.imwrite(os.path.join(path, name), frame)\n # self.statlabel.setText(\"Image Captured\")\n self._image_counter += 1\n self.cap.release()\n self.cap = None \n self.flag = 0\n# self.startUIWindow()\n self.startAnalysis()\n\n def displayImage(self, img, window=True):\n qformat = QtGui.QImage.Format_Indexed8\n if len(img.shape)==3 :\n if img.shape[2]==4:\n qformat = QtGui.QImage.Format_RGBA8888\n else:\n qformat = QtGui.QImage.Format_RGB888\n outImage = QtGui.QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat)\n outImage = outImage.rgbSwapped()\n if window:\n self.image_label.setPixmap(QtGui.QPixmap.fromImage(outImage))\n\n # def startUIWindow(self):\n # self.Window = UIWindow() # - self\n # self.setWindowTitle(\"DeepMalaria\")\n\n# self.setCentralWidget(self.Window)\n# self.show()\n### +++ vvv\n # self.Window.ToolsBTN.clicked.connect(self.goWindow1)\n \n def startUIWindow(self):\n self.Window = StartWindow(self)\n self.setWindowTitle(\"UIWindow\")\n #self.setCentralWidget(self.Window)f\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n\n self.hide()\n self.Window.show()\n\n\n\n def startAnalysis(self):\n self.Window = AnalysisWindow(self)\n self.setWindowTitle(\"Analysis\")\n #self.setCentralWidget(self.Window)f\n #self.Window.capture.clicked.connect(self.startUIToolTab)\n self.show()\n\n self.hide()\n self.Window.show()\n\n def goWindow1(self):\n self.show()\n self.Window.hide()\n \n\nif __name__=='__main__':\n import sys\n app = QtWidgets.QApplication(sys.argv)\n window = StartWindow()\n window.setWindowTitle('main code')\n window.show()\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":22904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"48203144","text":"import db\nimport logic\nimport numpy as np\nimport pandas as pd\n\n#分析用処理\n\n#DB接続\ndef connect_db():\n return db.dbconnection.getConnection()\n\n#DBclose\ndef close(cur,conn):\n db.dbconnection.close(cur,conn)\n\n#ジャンルの種類を取得\ndef get_genre_type(result,cl_num):\n rows = np.array(result)\n num = rows.shape[0]\n genre_list = np.empty(num,dtype=object)\n for count,row in enumerate(rows):\n genre_list[count] =row[cl_num]\n return np.unique(genre_list)\n\n#ジャンル別カウントのグラフ作成\ndef get_genre(period):\n #DBからデータ取得\n conn = connect_db()\n cur = conn.cursor()\n if period == \"all\":\n sql = db.lending_status_sql.count_genre_all\n title = \"貸出総数(ジャンル別)\"\n elif period == \"month\":\n sql = db.lending_status_sql.count_genre_month\n title = \"今月の貸出数(ジャンル別)\"\n elif period == \"year\":\n sql = db.lending_status_sql.count_genre_year\n title = \"今日から1年前までの貸出数(ジャンル別)\"\n cur.execute(sql)\n result = cur.fetchall()\n close(cur,conn)\n\n #グラフ作成\n if not result:\n data = False\n else:\n data = logic.create_graph.make_bar(result,title)\n return data\n\n#長期間の貸し出しがない書籍\ndef not_borrow_long_period():\n #DBからデータ取得\n conn = connect_db()\n df = pd.read_sql(db.lending_status_sql.not_borrowed,conn)\n cur = conn.cursor()\n close(cur,conn)\n \n #ジャンルの種類を取得\n genre_list = df[\"genre\"].unique()\n\n if genre_list.size == 0:\n data = False\n else:\n title = \"1年以上貸し出しがない書籍\"\n data = logic.create_graph.make_scatter(df,genre_list,title)\n return data\n\n#ジャンル別各月総数\ndef create_monthly_genre_count(specified_year):\n #ジャンルの種類を取得\n conn = connect_db()\n cur = conn.cursor()\n sql1 = db.lending_status_sql.get_specified_year\n cur.execute(sql1,(specified_year+'%',))\n result1 = cur.fetchall()\n genre_list = get_genre_type(result1,1)\n if genre_list.size == 0:\n #genre_listが空の場合、グラフ作成するためのデータがないと判定し、Falseを返す\n data = False\n else:\n #1年間のデータをジャンル毎に取得\n sql2 = db.lending_status_sql.borrowing_number_genre\n result2 = np.empty(len(genre_list),dtype=object)\n for count,genre in enumerate(genre_list):\n month_list = np.empty(12,dtype=object)\n for i in range(1,13):\n if i < 10:\n month = specified_year + \"-0\" +str(i)\n else:\n month = specified_year +\"-\"+str(i)\n values = (month,genre,month+'%',genre)\n cur.execute(sql2,values)\n month_list[i-1] = cur.fetchone()\n result2[count] = month_list\n \n #グラフ作成\n title = specified_year + \"年の月別貸出数(ジャンル別)\"\n data = logic.create_graph.make_plot(result2,genre_list,title)\n \n close(cur,conn)\n \n return data\n","sub_path":"デスクトップ/python/BLMS_20210127/app/logic/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"308948427","text":"#!/usr/bin/env python3\n\ndef parse_cdp_neighbors(input_txt):\n\tf=open(input_txt)\n\tdevname=f.readline().split('>')[0]\n\tf1=f.readlines()[4:]\n\tdict_neighbors={}\n\tfor line in f1:\n\t\tdevid=line.replace('Eth ','Eth').replace(' S ','S').split()[0]\n\t\tlocint=line.replace('Eth ','Eth').replace(' S ','S').split()[1]\n\t\tportid=line.replace('Eth ','Eth').replace(' S ','S').split()[5]\n\t\tdict_neighbors.setdefault(tuple([devname,locint]))\n\t\tdict_neighbors[tuple([devname,locint])]=tuple([devid,portid])\n\treturn dict_neighbors\n\tprint(dict_neighbors)\n\t\t\n\t\t\n\n\t\t\n#parse_cdp_neighbors('sw1_sh_cdp_neighbors.txt')\t\n\t\t\n\t\t\n\n'''{('R4', 'Fa0/1'): ('R5', 'Fa0/1'),\n('R4', 'Fa0/2'): ('R6', 'Fa0/0')}'''\n","sub_path":"11/parse_cdp_neighbors.py","file_name":"parse_cdp_neighbors.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"178279775","text":"import numpy as np #import numpy package\r\nimport matplotlib.pyplot as plt #plotting package\r\nimport scipy # 使用sklrean所需安裝的套件\r\nimport sklearn.datasets # 引入mnist資料庫,之後可匯入數字...等圖檔\r\nimport sklearn.svm # 作為classifier 用的 support vectorm machine\r\nimport sklearn.metrics # 為了之後取得confusion matrix用\r\n\r\n\r\n#### A. downloading the dataset\r\ndatabase = sklearn.datasets.load_digits() # 從MNIST database 中匯入數字的資料庫\r\n\r\n#### B. preprocessing character images\r\ntotal = len(database.images) # 紀錄樣本數量, 之後要將dataset分成前後兩半\r\ndata = database.images.reshape( (total, -1) ) # reshape 1-D\r\n\r\n#### C. reducing the dimension & choosing a classifier and training it\r\nclassifier = sklearn.svm.SVC( gamma = 0.001) # 使用SVM作為classifier\r\nclassifier.fit(data[:total // 2], database.target[:total // 2]) # 將前半部的dataset送入SVC進行訓練\r\n\r\n#### D. evaluating the performance of the classifier.\r\nexpected = database.target[total // 2:] # 預期得到的結果\r\npredicted = classifier.predict(data[total // 2:]) # 訓練完後預測的結果\r\n\r\n# 將正確樣本數字顯示在上排以供參考對照\r\nimg_sample = list( zip(database.images, database.target) ) # 讀取數字圖像資料\r\nfor start, (image, label) in enumerate(img_sample[:8]):\r\n plt.subplot(2, 8, start + 1)\r\n plt.imshow(image, cmap = plt.cm.gray_r, interpolation = 'none')\r\n plt.title('digit:%i' % label)\r\n# 將訓練完後的機器之預測結果顯示在下排\r\nimg_predict = list(zip(database.images[total // 2:], predicted))\r\nfor start, (image, prediction) in enumerate(img_predict[:8]):\r\n plt.subplot(2, 8, start + 9)\r\n plt.imshow(image, cmap = plt.cm.gray_r, interpolation = 'none')\r\n plt.title('predict:%i' % prediction)\r\n\r\nplt.show()\r\n\r\n# 完工,print出預測結果\r\nprint( \"Report for classifier %s\\n\" % (sklearn.metrics.classification_report(expected, predicted)) )\r\nprint(\"Confusion matrix:\\n%s\" % sklearn.metrics.confusion_matrix(expected, predicted))\r\n\r\n\r\n\r\n","sub_path":"ML2018_410336012_HW2/scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"385433198","text":"from datetime import date, timedelta\n\ndef meetup_day(year, month, weekday, ordinal):\n \"\"\"Calculate the date of meetups.\n\n >>> meetup_day(2013, 5, 'Monday', 'teenth')\n datetime.date(2013, 5, 13)\n \"\"\"\n num_week_days = 7\n week_days = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\", \"Sunday\"]\n idx = [\"1st\", \"2nd\", \"3rd\", \"4th\", \"5th\"]\n\n # initialize day as the first day of a month\n day = 1\n\n # date of the first day of a month\n dt = date(year, month, day)\n\n # determine the difference between weekday\n diff = week_days.index(weekday) - dt.weekday()\n diff = diff if diff >= 0 else num_week_days + diff\n\n # update day to the 1st weekday\n day += diff\n\n # update day to the ordinal weekday\n if ordinal in idx:\n day += num_week_days * idx.index(ordinal)\n\n if ordinal == \"teenth\":\n while day < 13:\n day += num_week_days\n\n if ordinal == \"last\":\n num_month_days = (dt.replace(month = dt.month % 12 + 1, day = 1) \\\n - timedelta(days=1)).day\n while day + num_week_days <= num_month_days:\n day += num_week_days\n\n return date(year, month, day)\n\n","sub_path":"meetup/meetup.py","file_name":"meetup.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"496663053","text":"\"\"\"\nThis module provides several classes and LinkCollection classes to\nassist in linking data.\n\nThe :class:`LinkCollection` class and its sublcasses are factories to create\nmultiple ComponentLinks easily. They are meant to be passed to\n:meth:`~glue.core.data_collection.DataCollection.add_link()`\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom glue.config import link_function\nfrom glue.external import six\nfrom glue.core.data import ComponentID\nfrom glue.core.component_link import ComponentLink\n\n\n__all__ = ['LinkCollection', 'LinkSame', 'LinkTwoWay', 'MultiLink',\n 'LinkAligned']\n\n\n@link_function(\"Link conceptually identical components\",\n output_labels=['y'])\ndef identity(x):\n return x\n\n\n@link_function(\"Convert between linear measurements and volume\",\n output_labels=['volume'])\ndef lengths_to_volume(width, height, depth):\n return width * height * depth\n\n\nclass PartialResult(object):\n\n def __init__(self, func, index, name_prefix=\"\"):\n self.func = func\n self.index = index\n self.__name__ = '%s%s_%i' % (name_prefix, func.__name__, index + 1)\n\n def __call__(self, *args, **kwargs):\n return self.func(*args, **kwargs)[self.index]\n\n def __gluestate__(self, context):\n return dict(func=context.do(self.func), index=self.index)\n\n @classmethod\n def __setgluestate__(cls, rec, context):\n return cls(context.object(rec['func']), rec['index'])\n\n\ndef _toid(arg):\n \"\"\"Coerce the input to a ComponentID, if possible\"\"\"\n if isinstance(arg, ComponentID):\n return arg\n elif isinstance(arg, six.string_types):\n return ComponentID(arg)\n else:\n raise TypeError('Cannot be cast to a ComponentID: %s' % arg)\n\n\nclass LinkCollection(list):\n pass\n\n\nclass LinkSame(LinkCollection):\n\n \"\"\"\n Return ComponentLinks to represent that two componentIDs\n describe the same piece of information\n \"\"\"\n\n def __init__(self, cid1, cid2):\n self.append(ComponentLink([_toid(cid1)], _toid(cid2)))\n\n\nclass LinkTwoWay(LinkCollection):\n\n def __init__(self, cid1, cid2, forwards, backwards):\n \"\"\" Return 2 links that connect input ComponentIDs in both directions\n\n :param cid1: First ComponentID to link\n :param cid2: Second ComponentID to link\n :param forwards: Function which maps cid1 to cid2 (e.g. cid2=f(cid1))\n :param backwards: Function which maps cid2 to cid1 (e.g. cid1=f(cid2))\n\n :returns: Two :class:`~glue.core.component_link.ComponentLink`\n instances, specifying the link in each direction\n \"\"\"\n self.append(ComponentLink([_toid(cid1)], _toid(cid2), forwards))\n self.append(ComponentLink([_toid(cid2)], _toid(cid1), backwards))\n\n\nclass MultiLink(LinkCollection):\n \"\"\"\n Compute all the ComponentLinks to link groups of ComponentIDs\n\n :param cids_left: first collection of ComponentIDs\n :param cids_right: second collection of ComponentIDs\n :param forwards:\n Function that maps ``cids_left -> cids_right``. Assumed to have\n signature ``cids_right = forwards(*cids_left)``, and assumed\n to return a tuple. If not provided, the relevant ComponentIDs\n will not be generated\n :param backwards:\n The inverse function to forwards. If not provided, the relevant\n ComponentIDs will not be generated\n\n :returns: a collection of :class:`~glue.core.component_link.ComponentLink`\n objects.\n \"\"\"\n\n cids = None\n\n def __init__(self, *args):\n self.cids = args\n\n def create_links(self, cids_left, cids_right, forwards=None, backwards=None):\n\n if self.cids is None:\n raise Exception(\"MultiLink.__init__ was not called before creating links\")\n\n if forwards is None and backwards is None:\n raise TypeError(\"Must supply either forwards or backwards\")\n\n if forwards is not None:\n for i, r in enumerate(cids_right):\n func = PartialResult(forwards, i, name_prefix=self.__class__.__name__ + \".\")\n self.append(ComponentLink(cids_left, r, func))\n\n if backwards is not None:\n for i, l in enumerate(cids_left):\n func = PartialResult(backwards, i, name_prefix=self.__class__.__name__ + \".\")\n self.append(ComponentLink(cids_right, l, func))\n\n def __gluestate__(self, context):\n return {'cids': [context.id(cid) for cid in self.cids]}\n\n @classmethod\n def __setgluestate__(cls, rec, context):\n return cls(*[context.object(cid) for cid in rec['cids']])\n\n\ndef multi_link(cids_left, cids_right, forwards=None, backwards=None):\n ml = MultiLink(cids_left + cids_right)\n ml.create_links(cids_left, cids_right, forwards=forwards, backwards=backwards)\n return ml\n\n\nclass LinkAligned(LinkCollection):\n\n \"\"\"Compute all the links to specify that the input data are pixel-aligned.\n\n :param data: An iterable of :class:`~glue.core.data.Data` instances\n that are aligned at the pixel level. They must be the\n same shape.\n \"\"\"\n\n def __init__(self, data):\n shape = data[0].shape\n ndim = data[0].ndim\n for i, d in enumerate(data[1:]):\n if d.shape != shape:\n raise TypeError(\"Input data do not have the same shape\")\n for j in range(ndim):\n self.extend(LinkSame(data[0].get_pixel_component_id(j),\n data[i + 1].get_pixel_component_id(j)))\n","sub_path":"glue/core/link_helpers.py","file_name":"link_helpers.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"123585310","text":"from __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport operator\nimport math\nfrom scipy import sparse\nfrom scipy.sparse import csr_matrix, save_npz, load_npz\n\n\nnum_newsgroups = 20\nnum_training = 12000\nnum_tests = 6774\n#num_tests = 10\n#num_training = 50\nvocab_size = 61188\nlamda=0.001\ndef get_parsed_matrix(csv_file, matrix_file):\n \"\"\"Parses the data out of the data file and into a format used by naive bayes.\n\n :rtype: ndarray\n :returns: A matrix read from the csv file\n \"\"\"\n matrix = None\n\n # Check to see if we have a saved npz file first\n if os.path.isfile(matrix_file):\n sparse_matrix = load_npz(matrix_file)\n matrix = sparse_matrix.todense()\n else:\n # initialize the matrix with 0's. This will help speed up the time to parse the data file\n if 'testing' in csv_file.name:\n matrix = np.zeros((num_tests, vocab_size+1), dtype=np.float64)\n \n else:\n matrix = np.zeros((num_training, vocab_size+2), dtype=np.float64)\n row = 0\n for line in csv_file.readlines():\n matrix[row, :]= list(map(int,line.split(',')))\n row += 1\n \n # Gets rid of the first column of ids. We don't need this\n # since that information is based on the row. i.e. row 0 is ID 1.\n #matrix = matrix[:, 1:]\n matrix[:,0]=1\n # save a sparse version of the matrix to reduce size and speed up reading time\n sparse_matrix = csr_matrix(matrix)\n save_npz(matrix_file, sparse_matrix)\n \n # returns a normal matrix. Sparse matrices don't have the same indexing power\n # as normal matrices, so we will be using normal matrices in the other functions.\n \n return matrix\n\ndef initialize_betas(dim):\n w = np.random.rand(dim)\n return w\n\ndef cost_func(weights, X, Y):\n \"\"\"Logistic loss, numerically stable implementation.\n \n Parameters\n ----------\n x: array-like, shape (n_features,)\n Coefficients\n\n A: array-like, shape (n_samples, n_features)\n Data matrix\n\n b: array-like, shape (n_samples,)\n Labels\n\n Returns\n -------\n loss: float\n \"\"\"\n z = np.matmul(X,weights)\n z=np.asarray(z).reshape(-1)\n Y = np.asarray(Y).reshape(-1)\n return np.mean((1 - Y) * z - logsig(z))\n\ndef logsig(x):\n \"\"\"Compute the log-sigmoid function component-wise.\"\"\"\n out = np.zeros_like(x)\n idx0 = x < -33\n out[idx0] = x[idx0]\n idx1 = (x >= -33) & (x < -18)\n out[idx1] = x[idx1] - np.exp(x[idx1])\n idx2 = (x >= -18) & (x < 37)\n out[idx2] = -np.log1p(np.exp(-x[idx2]))\n idx3 = x >= 37\n out[idx3] = -np.exp(-x[idx3])\n return out\n\n\n\ndef train(X_features, Y_labels, weights, lr, iters):\n cost_history = []\n a=[]\n cost=0\n i=0\n #for i in range(1000):\n #a.append(i)\n for i in range(iters):\n weights = update_weights(X_features, Y_labels, weights, lr)\n \n #Calculate error for auditing purposes\n #cost = cost_func(weights,X_features, Y_labels)\n #cost_history.append(cost)\n\n # Log Progress\n #if i % 2 == 0:\n #print (\"iter: \" +str(i) + \" cost: \"+str(cost))\n #plt.plot(a,cost_history)\n #plt.show()\n #print(weights)\n return weights, cost_history\n\ndef getbeta_forclasses(features,labels,weights):\n classlabel=1\n num=vocab_size+1\n #initial_weight=initialize_betas(X.shape[1])\n result_beta_matrix=np.zeros([num,1])\n for classlabel in range (1,21):\n y_new=np.where(labels==classlabel,1,0)\n weights,cost=train(features,y_new,weights,0.01,5000)\n #weights=weights.reshape(-1,1)\n result_beta_matrix=np.concatenate((result_beta_matrix,weights),axis=1)\n result_beta_matrix=np.delete(result_beta_matrix,0,1)\n \n return result_beta_matrix\n\n\n \ndef get_classification(X,result_beta_matrix):\n result_matrix=np.matmul(X,result_beta_matrix)\n #print(result_matrix)\n return np.argmax(result_matrix,axis=1)\n\ndef classify_data(result_array):\n \"\"\"Find the classification for the given testing data.\n\n :type data: list\n :param data: Parsed testing data to classify.\n\n :rtype: list\n :returns: A classification for each data item in the testing data set.\n \"\"\"\n classification = []\n i=12001\n result_array=np.asarray(result_array).reshape(-1)\n for item in result_array:\n \n \n \n classification.append({'id': i,\n 'class': 1+result_array[i-12001]})\n i=i+1\n return classification\n\ndef save_result_File(classification, result_file):\n \"\"\"Saves the classification from the ID3 algorithm to a file.\n\n :type classification: list\n :param classification: The classification output from the ID3 algorithm for the testing data.\n\n :type classification_file: File Object\n :param classification_file: File to write the classification to.\n \"\"\"\n print('id', 'class', file=result_file, sep=',')\n for item in classification:\n idx, cls = item.values()\n print(idx, cls, file=result_file, sep=',')\n return\n\n\n\n\n\n\ndef expit_b(x, b):\n \"\"\"Compute sigmoid(x) - b component-wise.\"\"\"\n idx = x < 0\n out = np.zeros_like(x,dtype=np.float64)\n exp_x = np.exp(x[idx])\n b_idx = b[idx]\n out[idx] = ((1 - b_idx) * exp_x - b_idx) / (1 + exp_x)\n exp_nx = np.exp(-x[~idx])\n b_nidx = b[~idx]\n out[~idx] = ((1 - b_nidx) - b_nidx * exp_nx) / (1 + exp_nx)\n return out\n\n\ndef f_gradient(weights, training_features, training_labels):\n \"\"\"Computes the gradient of the logistic loss.\n \n Parameters\n ----------\n x: array-like, shape (n_features,)\n Coefficients\n\n A: array-like, shape (n_samples, n_features)\n Data matrix\n\n b: array-like, shape (n_samples,)\n Labels\n\n Returns\n -------\n grad: array-like, shape (n_features,) \n \"\"\"\n \n #straining_features=sparse.csr_matrix(training_features)\n #straining_labels = sparse.csr_matrix(training_labels)\n #Z=straining_features*(sparse.csr_matrix(weights))\n #z=Z.todense()\n #z = A.dot(x)\n #z = np.asarray(z)\n c=np.matmul(training_features,weights)\n c=np.squeeze(c)\n slabels=np.squeeze(training_labels)\n s=expit_b(c,slabels)\n s=np.array(s).reshape(-1,1)\n t_features=training_features.transpose()\n result=np.matmul(t_features,s)\n #training_labels= np.asarray(training_labels)\n #s = expit_b(z,training_labels)\n #print('sshape is')\n #print(s.shape)\n #number=training_features.shape[0]\n #result=straining_features.transpose()*(sparse.csr_matrix(s))\n return result \n\ndef update_weights(features, labels, weights, lr):\n #N = len(features)\n\n \n \n\n #2 Transpose features from (200, 3) to (3, 200)\n # So we can multiply w the (200,1) cost matrix.\n # Returns a (3,1) matrix holding 3 partial derivatives --\n # one for each feature -- representing the aggregate\n # slope of the cost function across all observations\n gradient = f_gradient(weights,features,labels)\n\n #3 Take the average cost derivative for each feature\n #gradient /= N\n\n #4 - Multiply the gradient by our learning rate\n gradient *= lr\n small_weights=lr*lamda*weights\n #5 - Subtract from our weights to minimize cost\n #weights=np.array(weights).reshape(-1,1)\n #weights -= gradient\n weights=weights-gradient-small_weights\n return weights\n\ndef split(X_total):\n \n X = np.delete(X_total, -1, axis=1)\n Y=np.array(X_total[:,-1])\n X_total\n X[:,0]=1\n X = np.array(X)\n Y=np.array(Y).reshape(-1,1)\n return X,Y\n\n\nresultfile=open('training.csv','r')\n#matrixfile=open('matrix','w')\ntestingfile=open('testing.csv','r')\n\nX_total=get_parsed_matrix(resultfile,'training-matrix-total.npz')\nX_test=get_parsed_matrix(testingfile,'testing-matrix-total.npz')\nX_test[:,0]=1\nX_test = np.array(X_test)\nfeatures,labels=split(X_total)\nweights_initial=initialize_betas(61189)\nweights_initial=np.array(weights_initial).reshape(-1,1)\n\nbeta=getbeta_forclasses(features,labels,weights_initial)\n\nresult_array=get_classification(X_test,beta)\n\nclassification=classify_data(result_array)\nresultfile1=open('0320-test6.csv','w')\nsave_result_File(classification, resultfile1)\nresultfile.close()\nresultfile1.close()\n","sub_path":"test-0320/0320-test6.py","file_name":"0320-test6.py","file_ext":"py","file_size_in_byte":8427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"6091733","text":"import wikiquote\nimport unittest\n\n\nclass SearchTest(unittest.TestCase):\n \"\"\"\n Test wikiquote.search()\n \"\"\"\n\n def test_search(self):\n for lang in wikiquote.supported_languages():\n results = wikiquote.search(\"Matrix\", lang=lang)\n self.assertTrue(len(results) > 0)\n\n def test_unsupported_lang(self):\n with self.assertRaisesRegex(\n wikiquote.UnsupportedLanguageException, \"Unsupported language: foobar\"\n ):\n wikiquote.search(\"test\", lang=\"foobar\")\n\n def test_empty_search(self):\n results = wikiquote.search(\"\")\n self.assertEqual(results, [])\n","sub_path":"tests/test_search.py","file_name":"test_search.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"603389071","text":"'''\nTrains a simple deep NN on the MNIST dataset and one extra class.\n'''\n\nfrom __future__ import print_function\n\nimport os\nimport os.path as path\n\nimport keras\nfrom keras.preprocessing.image import img_to_array\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.optimizers import RMSprop\nfrom keras import backend as K\n\nimport tensorflow as tf\nfrom tensorflow.python.tools import freeze_graph\nfrom tensorflow.python.tools import optimize_for_inference_lib\n\nfrom PIL import Image\n\nimport glob\nimport numpy as np\n\n\n#\n# Configuration\n#\nMODEL_NAME = 'mnist_convnet'\nBATCH_SIZE = 128\nNUM_CLASSES = 11\nEPOCHS = 20\n\n\n#\n# Prepare custom class extention: 75:25\n#\ndef load_data():\n image_list = []\n for filename in glob.glob('teach-data/A/*.png'):\n im=Image.open(filename)\n image_list.append(img_to_array(im))\n\n x_train2 = np.array(image_list)\n x_train2 = x_train2[:1350]\n x_train2 = x_train2.reshape(1350, 784)\n\n x_test2 = np.array(image_list)\n x_test2 = x_test2[1350:1800]\n x_test2 = x_test2.reshape(450, 784)\n\n y_train2 = [10] * 1350\n y_test2 = [10] * 450\n\n #\n # Prepare train and test sets\n #\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n x_train = x_train.astype('float32')\n x_train = x_train.reshape(60000, 784)\n x_test = x_test.reshape(10000, 784)\n\n x_train = np.concatenate((x_train, x_train2))\n x_test = np.concatenate((x_test, x_test2 ))\n y_train = np.concatenate((y_train, y_train2))\n y_test = np.concatenate((y_test, y_test2 ))\n\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n x_train /= 255\n x_test /= 255\n\n # Convert class vectors to binary class matrices\n y_train = keras.utils.to_categorical(y_train, NUM_CLASSES)\n y_test = keras.utils.to_categorical(y_test, NUM_CLASSES)\n return x_train, y_train, x_test, y_test\n\n#\n# Construct the neural network\n#\ndef build_model():\n model = Sequential()\n model.add(Dense(512, activation='relu', input_shape=(784,))) # 512 - output vector dimension\n # model.add(Dropout(0.2))\n model.add(Dense(512, activation='relu'))\n # model.add(Dropout(0.2))\n model.add(Dense(NUM_CLASSES, activation='softmax'))\n model.summary()\n return model\n\n\ndef train(model, x_train, y_train, x_test, y_test):\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSprop(),\n metrics=['accuracy'])\n\n tbCallBack = keras.callbacks.TensorBoard(log_dir='tensor-boards', histogram_freq=0, batch_size=BATCH_SIZE,\n write_graph=True, write_grads=False, write_images=False, embeddings_freq=0,\n embeddings_layer_names=None, embeddings_metadata=None)\n\n model.fit(x_train, y_train,\n batch_size=BATCH_SIZE, #how many examples at once\n epochs=EPOCHS,\n verbose=1,\n validation_data=(x_test, y_test),\n callbacks=[tbCallBack])\n score = model.evaluate(x_test, y_test, verbose=0)\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])\n\n#\n# Real data recognition\n#\ndef test_real_data(model):\n img = Image.open('real-data/final_A.png')\n img.load()\n data = np.asarray(img, dtype=\"float32\")\n data /= 255\n data = data.reshape(1, 784)\n\n pred = model.predict_classes(data)\n predVerbose = model.predict(data, batch_size=None, verbose=1)\n\n print('Prediction: ', pred)\n print('Prediction scores: \\n', predVerbose)\n\n\ndef export_model(saver, model, input_node_names, output_node_name):\n tf.train.write_graph(K.get_session().graph_def, 'out', \\\n MODEL_NAME + '_graph.pbtxt')\n\n saver.save(K.get_session(), 'out/' + MODEL_NAME + '.chkp')\n\n freeze_graph.freeze_graph('out/' + MODEL_NAME + '_graph.pbtxt', None, \\\n False, 'out/' + MODEL_NAME + '.chkp', output_node_name, \\\n \"save/restore_all\", \"save/Const:0\", \\\n 'out/frozen_' + MODEL_NAME + '.pb', True, \"\")\n\n input_graph_def = tf.GraphDef()\n with tf.gfile.Open('out/frozen_' + MODEL_NAME + '.pb', \"rb\") as f:\n input_graph_def.ParseFromString(f.read())\n\n output_graph_def = optimize_for_inference_lib.optimize_for_inference(\n input_graph_def, input_node_names, [output_node_name],\n tf.float32.as_datatype_enum)\n\n with tf.gfile.FastGFile('out/opt_' + MODEL_NAME + '.pb', \"wb\") as f:\n f.write(output_graph_def.SerializeToString())\n\n print(\"graph saved!\")\n\n\ndef main():\n if not path.exists('out'):\n os.mkdir('out')\n\n x_train, y_train, x_test, y_test = load_data()\n\n model = build_model()\n\n train(model, x_train, y_train, x_test, y_test)\n\n export_model(tf.train.Saver(), model, [\"dense_1_input\"], \"dense_3/Softmax\")\n test_real_data(model)\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/mnist_mlp.py","file_name":"mnist_mlp.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"63363537","text":"from database.authenticate import Login\nfrom database.signup import Signup\nfrom database.logger import ConfigureLogs\n\nclass MainUi():\n\n def ask_user(self):\n print(\"Enter 0 to Login\\nEnter 1 to SignUp\")\n option = input(\"your option: \")\n if option == '0':\n #redirect to login\n logger = ConfigureLogs().configure_log(\"Eventlogs\",\"Event\")\n Login().user_login(logger)\n elif option == '1':\n #redirect to signup\n logger = ConfigureLogs().configure_log(\"Eventlogs\",\"Event\")\n Signup().signup_user(logger)\n self.ask_user()\n else:\n print('enter correct option')\n\nif __name__==\"__main__\":\n MainUi().ask_user()\n","sub_path":"database/mainUI.py","file_name":"mainUI.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"328543217","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n#--Constants--\nM = 20 # Jmax\nN = 1000 # Number of J values\nT = 50 # Actually T/theta_r\n\nJ1 = np.linspace(0,M,N)\nJ2 = np.linspace(0,M,M+1)\n\n#--Calculate z--\ndef z(J):\n return(2*J+1)*np.exp(-J*(J+1)/T)\n\n#--Plot--\nwidth = .9 #Width of columns\nplt.bar(J2-0.5*width, z(J2), width=width) #Plotting histogram\nplt.plot(J1,z(J1),'-r', linewidth=2)\n\nSZ={'size':'16'}\nplt.title('Different terms $z(j)$ plotted as function of $j$',**SZ)\nplt.xlabel('$j$',**SZ)\nplt.ylabel('$z(j)$',**SZ)\nplt.legend(['Exact','Integral approx'])\nplt.grid()\nplt.show()\n","sub_path":"FYS2160/Oblig2/oblig02_f.py","file_name":"oblig02_f.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"100623959","text":"import logging\nimport math\n\nfrom .matrix4x4 import Matrix4x4\n\n\nclass Euler(list):\n\n def __init__(self, angles=(0.0,0.0,0.0)):\n\n list.__init__(self, angles)\n\n\n @property\n def x(self):\n \"\"\" Get X value \"\"\"\n\n return self[0]\n\n\n @x.setter\n def x(self, value):\n \"\"\" Set X value \"\"\"\n\n self[0] = value\n\n\n @property\n def y(self):\n \"\"\" Get Y value \"\"\"\n\n return self[1]\n\n\n @y.setter\n def y(self, value):\n \"\"\" Set Y value \"\"\"\n\n self[1] = value\n\n\n @property\n def z(self):\n \"\"\" Get Z value \"\"\"\n\n return self[2]\n\n\n @z.setter\n def z(self, value):\n \"\"\" Set Z value \"\"\"\n\n self[2] = value\n\n\n def to_matrix4x4(self):\n\n # From stackflow -> PDF:\n # http://stackoverflow.com/questions/18433801/converting-a-3x3-matrix-to-euler-tait-bryan-angles-pitch-yaw-roll\n\n m = Matrix4x4.init_identity()\n\n cosX = math.cos(self[0])\n sinX = math.sin(self[0])\n\n cosY = math.cos(self[1])\n sinY = math.sin(self[1])\n\n cosZ = math.cos(self[2])\n sinZ = math.sin(self[2])\n\n m[0][0] = cosY * cosZ\n m[0][1] = sinX*sinY*cosZ - cosX*sinZ\n m[0][2] = cosX*sinY*cosZ + sinX*sinZ\n\n m[1][0] = cosY * sinZ\n m[1][1] = sinX*sinY*sinZ + cosX*cosZ\n m[1][2] = cosX*sinY*sinZ - sinX*cosZ\n\n m[2][0] = -sinY\n m[2][1] = sinX*cosY\n m[2][2] = cosX*cosY\n\n m.transpose()\n\n return m\n\n \"\"\"\n mX = Matrix4x4.init_identity()\n mX[0][0] = 1.0\n mX[0][1] = 0.0\n mX[0][2] = 0.0\n\n mX[1][0] = 0.0\n mX[1][1] = math.cos(self[0])\n mX[1][2] = -math.sin(self[0])\n\n mX[2][0] = 0.0\n mX[2][1] = math.sin(self[0])\n mX[2][2] = math.cos(self[0])\n\n mY = Matrix4x4.init_identity()\n mY[0][0] = math.cos(self[1])\n mY[0][1] = 0.0\n mY[0][2] = math.sin(self[1])\n\n mY[1][0] = 0.0\n mY[1][1] = 1.0\n mY[1][2] = 0.0\n\n mY[2][0] = -math.sin(self[1])\n mY[2][1] = 0.0\n mY[2][2] = math.cos(self[1])\n\n mZ = Matrix4x4.init_identity()\n mZ[0][0] = math.cos(self[2])\n mZ[0][1] = -math.sin(self[2])\n mZ[0][2] = 0.0\n\n mZ[1][0] = math.sin(self[2])\n mZ[1][1] = math.cos(self[2])\n mZ[1][2] = 0.0\n\n mZ[2][0] = 0.0\n mZ[2][1] = 0.0\n mZ[2][2] = 1.0\n\n # Row order\n m = mX * mY * mZ\n\n # Convert to column order\n m.transpose()\n\n return m\n \"\"\"\n\n\n def to_quaternion(self):\n\n \"\"\"\n Quaternion QuatAroundX = Quaternion( Vector3(1.0,0.0,0.0), EulerAngle.x );\n Quaternion QuatAroundY = Quaternion( Vector3(0.0,1.0,0.0), EulerAngle.y );\n Quaternion QuatAroundZ = Quaternion( Vector3(0.0,0.0,1.0), EulerAngle.z );\n Quaternion finalOrientation = QuatAroundX * QuatAroundY * QuatAroundZ;\n \"\"\"\n\n # From euclideanspace.com\n \"\"\"\n c1 = math.cos(self[1] / 2)\n c2 = math.cos(self[2] / 2)\n c3 = math.cos(self[0] / 2)\n\n s1 = math.sin(self[1] / 2)\n s2 = math.sin(self[2] / 2)\n s3 = math.sin(self[0] / 2)\n\n \"\"\"\n c1 = math.cos(self[1] / 2)\n s1 = math.sin(self[1] / 2)\n\n c2 = math.cos(self[2] / 2)\n s2 = math.sin(self[2] / 2)\n\n c3 = math.cos(self[0] / 2)\n s3 = math.sin(self[0] / 2)\n\n\n w = (c1 * c2 * c3) - (s1 * s2 * s3)\n x = (s1 * s2 * c3) + (c1 * c2 * s3)\n y = (s1 * c2 * c3) + (c1 * s2 * s3)\n z = (c1 * s2 * c3) - (s1 * c2 * s3)\n\n from .quaternion import Quaternion\n return Quaternion((w,x,y,z))\n","sub_path":"glmath/euler.py","file_name":"euler.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"223797250","text":"import database as db\nimport unseen_scrapper as scrapper\n\nimport telegram\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler\nfrom telegram.ext import Filters\nimport configparser\nimport logging\nimport requests\nimport traceback\nimport datetime\n\n# Controller\n#########################################\n\nCOMMAND_ADD_URL = 'addurl'\nCOMMAND_GET_URLS = 'geturls'\nCOMMAND_DELETE_URL = 'deleteurl'\n\nSTART_TEXT = \"\"\"\n Hello from **propfinder bot** developed by @rodri_st\n\n 1 - Make a prop search in one of the available domains (www.zonaprop.com.ar, www.argenprop.com, inmuebles.mercadolibre.com.ar)\n 2 - Order the results by 'most recent'\n 3 - Copy url and pass it to the bot (/addurl )\n 4 - Use /updateunseen to get unseen prop ads\n\n We recommend you delete the prop ads you are not interested in to keep the conversation clean\n\n Available commands:\n /help - How it works\n /geturls - Get current urls\n /addurl - Add new url\n /deleteurl - Delete url (if does not exists, nothing happens)\n /updateunseen - Fetches all prop ads from your urls and returns those you haven't seen\n /vippify - Subscribe to receive updates each 20 minutes\n /unvippify - Unsubscribe\n\"\"\"\n\n\ndef start(bot, update):\n chat_id = update.message.chat_id\n\n try:\n send_message(bot, chat_id, START_TEXT)\n\n username = get_username(update.message.chat)\n db.create_user(chat_id, username)\n\n except Exception as e:\n print('Error with chat_id: {}'.format(chat_id))\n print(traceback.format_exc())\n send_message(bot, chat_id, 'There was a server error')\n\n\ndef create_user(bot, update):\n chat_id = update.message.chat_id\n\n try:\n send_message(bot, chat_id, 'Creating your user, wait for a confirmation message')\n db.create_user(chat_id)\n send_message(bot, chat_id, 'User successfully created!')\n except Exception as e:\n print('Error with chat_id: {}'.format(chat_id))\n print(traceback.format_exc())\n send_message(bot, chat_id, 'There was an error while creating your user')\n\n\ndef add_url(bot, update):\n chat_id = update.message.chat_id\n\n try:\n url = get_text_from_command(update.message.text, COMMAND_ADD_URL)\n\n if not scrapper.is_valid_url(url):\n send_message(bot, chat_id, 'Not a valid url. Use /help to see valid domains. Remember to add http or https')\n return\n\n if len(url) == 0:\n send_message(bot, chat_id, 'Cannot add empty url :(')\n return\n\n username = get_username(update.message.chat)\n db.add_url(chat_id, username, url)\n\n send_message(bot, chat_id, 'Successfully added new url!')\n except Exception as e:\n print('Error with chat_id: {}'.format(chat_id))\n print(traceback.format_exc())\n send_message(bot, chat_id, 'There was an error adding the url: ' + url)\n\n\ndef get_urls(bot, update):\n chat_id = update.message.chat_id\n\n try:\n urls = db.get_urls(chat_id)\n \n if len(urls) == 0:\n send_message(bot, chat_id, 'There are no registered urls')\n return\n\n for url in urls:\n send_message(bot, chat_id, url)\n\n except Exception as e:\n print('Error with chat_id: {}'.format(chat_id))\n print(traceback.format_exc())\n send_message(bot, chat_id, 'There was an error getting the urls')\n\n\ndef delete_url(bot, update):\n chat_id = update.message.chat_id\n\n try:\n url = get_text_from_command(update.message.text, COMMAND_DELETE_URL)\n\n username = get_username(update.message.chat)\n db.delete_url(chat_id, username, url)\n\n send_message(bot, chat_id, 'Successfully deleted url')\n except Exception as e:\n send_message(bot, chat_id, 'There was an error deleting the url: ' + url)\n\n\ndef update_unseen(bot, update):\n chat_id = update.message.chat_id\n\n try:\n urls = db.get_urls(chat_id)\n history = list(map(lambda ad: ad['id'], db.get_history(chat_id)))\n\n if len(urls) == 0:\n send_message(bot, chat_id, 'There are no registered urls')\n return\n\n process_unseen(bot, chat_id, urls, history)\n\n except Exception as e:\n print('Error with chat_id: {}'.format(chat_id))\n print(traceback.format_exc())\n send_message(bot, chat_id, 'There was an error updating unseen')\n\n\ndef vippify(bot, update):\n chat_id = update.message.chat_id\n\n try:\n db.add_vip(chat_id)\n\n send_message(bot, chat_id, 'Successfully vippified')\n except Exception as e:\n send_message(bot, chat_id, 'There was an error vippifying')\n\n\ndef unvippify(bot, update):\n chat_id = update.message.chat_id\n\n try:\n db.remove_vip(chat_id)\n\n send_message(bot, chat_id, 'Successfully unvippified')\n except Exception as e:\n send_message(bot, chat_id, 'There was an error unvippifying')\n\n\ndef health_check(bot, update):\n chat_id = update.message.chat_id\n send_message(bot, chat_id, 'OK')\n\n\ndef error(bot, update, error):\n # logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n print('Update \"%s\" caused error \"%s\"', update, error)\n\n\ndef get_username(chat):\n chat_type = chat.type\n if chat_type == 'private':\n username = chat.username\n elif chat_type == 'group':\n username = chat.title\n else:\n username = ''\n\n return username\n\n\ndef get_text_from_command(original_text, command):\n return original_text.replace('/'+command, '', 1).strip()\n\n\ndef send_message(bot, chat_id, text):\n bot.send_message(chat_id=chat_id, text=text)\n\n\ndef send_message_2(bot, chat_id, text):\n url = \"https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}\".format(bot, chat_id, text)\n try:\n r = requests.get(url)\n print(r)\n except:\n print('Error in request')\n\n\ndef process_unseen(bot, chat_id, urls, history):\n seen, unseen = scrapper.scrap_for_unseen(urls, history)\n\n send_message(bot, chat_id, 'You have already seen {} ads of your current urls and {} in total'.format(len(seen), len(history)))\n\n if len(unseen) == 0:\n send_message(bot, chat_id, 'There are no new ads for you')\n return\n\n for ad in unseen:\n send_message(bot, chat_id, ad['url'])\n\n mark_as_seen(chat_id, unseen)\n\n\ndef mark_as_seen(chat_id, unseen):\n db.add_seen(chat_id, unseen)\n\n\ndef log_ip():\n ip = requests.get('https://api.ipify.org').text\n print('My public IP address is:', ip)\n #db.record_deploy(ip, datetime.datetime.utcnow())\n\n\ndef main():\n log_ip()\n\n config = configparser.ConfigParser()\n config.read('sensitive.conf')\n bot_id = config['telegram.com']['bot-id']\n\n updater = Updater(bot_id)\n\n dp = updater.dispatcher\n\n dp.add_handler(CommandHandler('start', start))\n dp.add_handler(CommandHandler('help', start))\n dp.add_handler(CommandHandler(COMMAND_ADD_URL, add_url))\n dp.add_handler(CommandHandler(COMMAND_GET_URLS, get_urls))\n dp.add_handler(CommandHandler(COMMAND_DELETE_URL, delete_url))\n dp.add_handler(CommandHandler('updateunseen', update_unseen))\n dp.add_handler(CommandHandler('vippify', vippify))\n dp.add_handler(CommandHandler('unvippify', unvippify))\n dp.add_handler(CommandHandler('healthcheck', health_check))\n dp.add_error_handler(error)\n\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"propfinder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"130058906","text":"import cv2 as cv\nimport os\nimport glob\nimport numpy as np\n\n\ndef makeDataSet(path, label):\n images = []\n labels = []\n path = path + '/*.png'\n for file in glob.glob(path):\n img = cv.imread(file, cv.IMREAD_GRAYSCALE)\n images.append(img)\n labels.append(label)\n return np.array(images, dtype = 'uint8'), np.array(labels, dtype = 'int64')\n\ndef createDataSet():\n '''\n Random shuffle data and split training and validation set\n '''\n\n anger_path = os.path.join(dir, 'anger')\n disgust_path = os.path.join(dir, 'disgust')\n fear_path = os.path.join(dir, 'fear')\n happy_path = os.path.join(dir, 'happy')\n sadness_path = os.path.join(dir, 'sadness')\n surprise_path = os.path.join(dir, 'surprise')\n contempt_path = os.path.join(dir, 'contempt')\n\n anger_imgs, anger_labels = makeDataSet(anger_path, 0)\n comtempt_imgs, comtempt_labels = makeDataSet(contempt_path, 1)\n disgust_imgs, disgust_labels = makeDataSet(disgust_path, 2)\n fear_imgs, fear_labels = makeDataSet(fear_path, 3)\n happy_imgs, happy_labels = makeDataSet(happy_path, 4)\n sad_imgs, sad_labels = makeDataSet(sadness_path, 5)\n surprise_imgs, surprise_labels = makeDataSet(surprise_path, 6)\n\n imgs_data = np.vstack((anger_imgs, comtempt_imgs, disgust_imgs,\n fear_imgs, happy_imgs, sad_imgs, surprise_imgs))\n labels_data = np.hstack((anger_labels, comtempt_labels, disgust_labels, fear_labels, happy_labels, sad_labels,\n surprise_labels))\n imgs_data, labels_data = shuffleData(imgs_data, labels_data)\n\n train_imgs_data, train_labels_data, val_imgs_data, val_labels_data = splitTraingTest(imgs_data, labels_data, 60)\n return train_imgs_data, train_labels_data, val_imgs_data, val_labels_data\n\ndef shuffleData(imgs_data, labels_data):\n '''\n shuffle data in groups of 3\n :param imgs_data:\n :param labels_data:\n :return: shuffled data\n '''\n indices_tmp = np.arange(imgs_data.shape[0], step=3)\n np.random.shuffle(indices_tmp)\n indices = []\n for index in indices_tmp:\n indices.extend([index, index+1, index+2])\n indices = np.array(indices)\n output_imgs_data = imgs_data[indices].copy()\n output_labels_data = labels_data[indices].copy()\n return output_imgs_data, output_labels_data\n\n\ndef splitTraingTest(imgs_data, labels_data, split_indices):\n val_split = split_indices\n train_imgs_data = imgs_data[val_split:, :]\n val_imgs_data = imgs_data[:val_split, :]\n\n train_labels_data = labels_data[val_split:]\n val_labels_data = labels_data[:val_split]\n\n return train_imgs_data, train_labels_data, val_imgs_data, val_labels_data\n\n\n\ndef saveNumpys(train_imgs_data, train_labels_data, val_imgs_data, val_labels_data):\n if not os.path.exists('./numpy_data'):\n os.makedirs('./numpy_data')\n\n np.save('./numpy_data/train_imgs_data.npy', train_imgs_data)\n np.save('./numpy_data/train_labels_data.npy', train_labels_data)\n np.save('./numpy_data/val_imgs_data.npy', val_imgs_data)\n np.save('./numpy_data/val_labels_data.npy', val_labels_data)\n\n\ndef readNumpys():\n train_imgs_data = np.load('./numpy_data/train_imgs_data.npy')\n train_labels_data = np.load('./numpy_data/train_labels_data.npy')\n val_imgs_data = np.load('./numpy_data/val_imgs_data.npy')\n val_labels_data = np.load('./numpy_data/val_labels_data.npy')\n return train_imgs_data, train_labels_data, val_imgs_data, val_labels_data\n\nif __name__ == '__main__':\n\n dir = \"CK+\"\n train_imgs_data, train_labels_data, val_imgs_data, val_labels_data = createDataSet()\n saveNumpys(train_imgs_data, train_labels_data, val_imgs_data, val_labels_data)\n\n train_imgs_data, train_labels_data, val_imgs_data, val_labels_data = readNumpys()\n\n print(train_imgs_data.shape)\n print(train_labels_data.shape)\n print(val_imgs_data.shape)\n print(val_labels_data.shape)\n\n","sub_path":"preprocess_ck.py","file_name":"preprocess_ck.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"297952721","text":"# Code 5.py\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nprint(\"Socked created!\")\n\nhost = 'www.google.com'\nport = 80\n\nremote_ip = socket.gethostbyname(host)\n\nprint(\"IP Address of \" + host + \" is \" + remote_ip)\n\ns.connect((remote_ip, port))\n\nprint(\"Socket connected to \" + host + \" on ip \" + remote_ip)\n\nmessage = b\"GET / HTTP/1.1\\r\\n\\r\\n\"\ns.sendall(message)\n\nreply = s.recv(4096)\n\nprint(reply)\n","sub_path":"codes/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"583883612","text":"from collections import Counter, defaultdict, OrderedDict, deque\nfrom bisect import bisect_left, bisect_right \nfrom functools import reduce, lru_cache \nimport itertools \nimport math \nimport string\ntrue = True\nfalse = False\nMIN, MAX = -0x3f3f3f3f, 0x3f3f3f3f\n#\n# @lc app=leetcode id=535 lang=python3\n#\n# [535] Encode and Decode TinyURL\n#\n# https://leetcode.com/problems/encode-and-decode-tinyurl/description/\n#\n# algorithms\n# Medium (78.89%)\n# Total Accepted: 98.1K\n# Total Submissions: 124.3K\n# Testcase Example: '\"https://leetcode.com/problems/design-tinyurl\"'\n#\n# Note: This is a companion problem to the System Design problem: Design\n# TinyURL.\n# \n# TinyURL is a URL shortening service where you enter a URL such as\n# https://leetcode.com/problems/design-tinyurl and it returns a short URL such\n# as http://tinyurl.com/4e9iAk.\n# \n# Design the encode and decode methods for the TinyURL service. There is no\n# restriction on how your encode/decode algorithm should work. You just need to\n# ensure that a URL can be encoded to a tiny URL and the tiny URL can be\n# decoded to the original URL.\n# \n#\nclass Codec:\n def __init__(self):\n self.db = [] \n\n def encode(self, longUrl: str) -> str:\n \"\"\"Encodes a URL to a shortened URL.\n \"\"\"\n self.db.append(longUrl)\n return 'https://tinyurl.com/' + str(len(self.db))\n \n\n def decode(self, shortUrl: str) -> str:\n \"\"\"Decodes a shortened URL to its original URL.\n \"\"\"\n l = int(shortUrl.split('/')[-1])\n return self.db[l-1]\n \n\n# Your Codec object will be instantiated and called as such:\ncodec = Codec()\nurl = \"https://www.google.com\"\nprint(codec.decode(codec.encode(url)))\n\n\n\n\n","sub_path":"python_solutions/535.encode-and-decode-tinyurl.py","file_name":"535.encode-and-decode-tinyurl.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"469517249","text":"import tensorflow as tf\nimport numpy as np\n\n\ndef calculate_euclidean_distance(training_data, test_data):\n # computing (x-y)^2 = x^2 + y^2 - 2xy\n first_term = tf.reduce_sum(training_data**2, axis=1)\n second_term = tf.expand_dims(tf.reduce_sum(test_data**2, axis=1), axis=1)\n xy = tf.matmul(test_data, tf.transpose(training_data))\n third_term = tf.scalar_mul(-2, xy)\n dist = first_term + second_term + third_term\n\n # shape1 = tf.shape(first_term)\n # shape2 = tf.shape(second_term)\n # shape3 = tf.shape(third_term)\n # sess = tf.InteractiveSession()\n # print(sess.run([dist], feed_dict={X: trainData, Z: testData}))\n # print(sess.run([shape1, shape2, shape3], feed_dict={X: trainData, Z: testData}))\n return dist\n\n\ndef main():\n # np.random.seed(521)\n # Data = np.linspace(1.0, 10.0, num =100)[:, np. newaxis]\n # Target = np.sin(Data) + 0.1 * np.power(Data, 2) + 0.5 * np.random.randn(100, 1)\n # randIdx = np.arange(100)\n # np.random.shuffle(randIdx)\n # trainData, trainTarget = Data[randIdx[:80]], Target[randIdx[:80]]\n # validData, validTarget = Data[randIdx[80:90]], Target[randIdx[80:90]]\n # testData, testTarget = Data[randIdx[90:100]], Target[randIdx[90:100]]\n\n X = tf.placeholder(tf.float32, name = 'input_x')\n Z = tf.placeholder(tf.float32, name = 'input_z')\n dist = calculate_euclidean_distance(X, Z)\n\n trainData = [[1, 2, 3], [2, 3, 4]]\n testData = [[2, 3, 4]]\n sess = tf.InteractiveSession()\n print(sess.run([dist], feed_dict={X: trainData, Z: testData}))\n print(sess.run(dist, feed_dict={X: trainData, Z: testData}).shape)\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"ECE521_Inference_Algorithms_and_Machine_Learning/assignment1/a1_1.py","file_name":"a1_1.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"334030798","text":"from Ensamblador.f06Evaluar_Direccionamientos import validar_operando_inmediato, validar_operando_directo_o_extendido, identificar_indizado\nfrom Ensamblador.f03_Ensamblador import evaluar_etiqueta\n\ndef direccionamiento_correspondiente(lista_direccionamientos, operando, CONTLOC):\n print()\n resultado_evaluacion = ''\n totalBytes = ''\n # Se le quita el espacio en blanco al operando\n auxiliar = ''\n for caracter in operando:\n if(caracter != ' '):\n auxiliar += caracter\n operando = auxiliar\n \n # Nombre de los direccionamientos disponibles\n direccionamientos_disponibles = []\n for direccionamiento in lista_direccionamientos:\n direccionamientos_disponibles.append(direccionamiento[0])\n \n #-----------------------------------------------------------------------\n # INHERENTE\n #-----------------------------------------------------------------------\n\n if('INH' in direccionamientos_disponibles):\n if(operando == 'null' or operando == 'NULL'):\n informacion = lista_direccionamientos.pop()\n totalBytes = informacion[4]\n print('\\t\\t Modo Inherente de %s bytes' %totalBytes)\n resultado_evaluacion = 'Inherente, %s bytes' %totalBytes\n #-----------------------------------------------------------------------\n # INMEDIATO\n #-----------------------------------------------------------------------\n elif(operando[0] == '#'):\n if('INM' in direccionamientos_disponibles):\n informacion = lista_direccionamientos[0]\n lista = validar_operando_inmediato(operando, informacion[3], informacion[4])\n esValido = lista[0]\n resultado_evaluacion = lista[1]\n \n if(esValido): \n totalBytes = informacion[4]\n else:\n print('\\t\\t ERROR DE CODIGO DE OPERACION: Este Codigo de Operacion no soporta el Modo Inmediato')\n #-----------------------------------------------------------------------\n # INDIZADOS\n #-----------------------------------------------------------------------\n elif(',' in operando or '[' in operando or ']' in operando ):\n if('IDX' in direccionamientos_disponibles or 'IDX1' in direccionamientos_disponibles or 'IDX2' in direccionamientos_disponibles \n or '[IDX2]' in direccionamientos_disponibles or '[D,IDX]' in direccionamientos_disponibles):\n lista = identificar_indizado(operando, lista_direccionamientos)\n \n totalBytes = lista[0]\n resultado_evaluacion = lista[1]\n #-----------------------------------------------------------------------\n # (2)RELATIVO\n #-----------------------------------------------------------------------\n elif('REL' in direccionamientos_disponibles):\n esValido = evaluar_etiqueta(operando)\n else:\n #-----------------------------------------------------------------------\n # DIRECTO & EXTENDIDO\n #-----------------------------------------------------------------------\n if(operando[0] == '$' or operando[0] == '%' or operando[0] == '@' or (operando[0] >= '0' and operando[0] <= '9') or operando[0] == '-'):\n rango = validar_operando_directo_o_extendido(operando)\n if('DIR' in direccionamientos_disponibles and (rango >= 0 and rango <= 255)):\n informacion = lista_direccionamientos[1]\n totalBytes = informacion[4]\n print('\\t\\t Modo Directo, %s bytes' %totalBytes) \n resultado_evaluacion = 'Directo, %s bytes' %totalBytes\n elif('EXT' in direccionamientos_disponibles and rango >= 256 and rango <= 65535):\n informacion = lista_direccionamientos[2]\n totalBytes = informacion[4]\n print('\\t\\t Modo Extendido, %s bytes' %totalBytes) \n resultado_evaluacion = 'Extendido, %s bytes' %totalBytes\n elif(rango > 65535):\n print('\\t\\t ERROR: El valor del operando esta fuera del rango de Modo Extendido (%d > 65535)' %rango)\n elif(rango < 0):\n print('\\t\\t ERROR: El valor del operando esta fuera del rango de Modo Directo (0 > %d)' %rango)\n \n #-----------------------------------------------------------------------\n # RELATIVO & EXTENDIDO\n #-----------------------------------------------------------------------\n else:\n esValido = evaluar_etiqueta(operando)\n if(esValido):\n if('REL' in direccionamientos_disponibles):\n informacion = lista_direccionamientos[0]\n totalBytes = informacion[4]\n \n if(informacion[3] == '1'):\n print('\\t\\t Modo Relativo de 8 bits, %s bytes' %totalBytes)\n resultado_evaluacion = 'Relativo de 8 bits, %s bytes' %totalBytes\n elif(informacion[3] == '2'):\n print('\\t\\t Modo Relativo de 16 bits, %s bytes' %totalBytes)\n resultado_evaluacion = 'Relativo de 16 bits, %s bytes' %totalBytes\n elif('EXT' in direccionamientos_disponibles):\n informacion = lista_direccionamientos[2]\n totalBytes = informacion[4]\n print('\\t\\t Extendido, %s bytes' %totalBytes)\n resultado_evaluacion = 'Extendido, %s bytes' %totalBytes\n \n print()\n return totalBytes, resultado_evaluacion\n\ndef busca_etiqueta_tabop(etiqueta):\n valor = 0\n LECTURA = 'r'\n try:\n with open(\"tabsim.txt\", LECTURA) as archivo:\n for linea in archivo:\n if(len(linea) > 1):\n print(linea)\n lista = linea.split('|')\n if(etiqueta == lista[1]):\n valor = lista[2]\n except:\n print('%s (El sistema no puede encontrar el archivo especificado)' %nombre_archivo)\n return valor","sub_path":"[CC207] ~ Practica05/Ensamblador/f05_Direccionamientos.py","file_name":"f05_Direccionamientos.py","file_ext":"py","file_size_in_byte":6205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"322122908","text":"#!/usr/bin/python3\n\n# Pre-requisite: pyserial, install via 'python -m pip install pyserial'\n# plug in the GR sensor into the shuttle\n# This script is used during 'dry' printing to read data from a GR sensor via serial port\n# and display it to the user and logs it to a log file\n# assumes that GR sensor is plugged into /dev/ttyUSB2\n\nimport serial, sys, os, datetime\n\ndef gr_log(outputfile):\n gr = serial.Serial(\"/dev/ttyUSB2\", 115200, parity=serial.PARITY_NONE)\n \n #read line by line from the serial port with infinite timeout\n #print to user after every line read, and write to file after\n #string 'Final Values' encountered\n layer = 1\n print(\"Logging\")\n while True:\n read = gr.readline()\n if 'Final Values' in read.decode():\n final = gr.readline()\n cur_dt = datetime.datetime.now()\n s = cur_dt.strftime(\"%d %b %Y %H:%M:%S.%f\")\n trunc = s[:len(s) - 3] # remove last 3 trailing zeroes\n (average, peak, dosage, exptime) = final.decode().split()\n s = str(trunc) + ',' + str(layer) + ',' + average + ',' + peak + ',' + dosage + ',' + exptime + '\\n'\n print(s, end = '')\n try:\n ofile = open(outputfile, \"a+\")\n ofile.write(s)\n ofile.close()\n except Exception as e:\n print(layer, type(e), str(e))\n layer = layer + 1\n return\n\ndef main():\n if (len(sys.argv) < 2):\n print(\"Usage is ./gr.py \")\n sys.exit(1)\n gr_log(sys.argv[1])\n\nif __name__ == '__main__':\n main()\n","sub_path":"dtf/gr.py","file_name":"gr.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"631542650","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\nimport sys\nimport urllib\nfrom bs4 import BeautifulSoup\nreload(sys)\nsys.setdefaultencoding('utf-8')\ndef get_html(url): #通过url获取网页内容\n result = urllib.urlopen(url)\n return result.read()\n # save_file(result.read(), 'thefile.txt')\ndef get_movie_all(html): #通过soup提取到每个电影的全部信息,以list返回\n soup = BeautifulSoup(html,\"html.parser\")\n movie_1 = soup.find_all('table', class_=\"table\")\n movie_str=str(movie_1[0])\n movie=[movie_str]\n return movie\ndef get_movie_one(movie):\n result = [] # 用于存储提取出来的电影信息\n soup_all = BeautifulSoup(str(movie),\"html.parser\")\n result_str=\"\"\n movie=soup_all.find_all('a')\n for it_movie in movie:\n soup_movie=BeautifulSoup(str(it_movie),\"html.parser\")\n for line in soup_movie.stripped_strings:\n result_str=result_str+line+'\\n'\n\n result.append(result_str)\n\n return result #返回获取到的结果\ndef save_file(text, filename): #保存网页到文件\n f= open(filename,'ab')\n f.write(bytes(text))\n f.close()\ndef read_file(filename): #读取文件\n f = open(filename,'r')\n text = f.read()\n f.close()\n return text\ndef work():\n\n url = 'https://www.rottentomatoes.com/top/bestofrt/?year=2017'\n html = get_html(url)\n movie_list = get_movie_all(html)\n for movie in movie_list: # 将每一页中的每个电影信息放入函数中提取\n result = get_movie_one(movie)\n text = ''+str(result[0])+'\\t'\n save_file(text, 'RottenTomatoes_by_toplist.txt')\n\n\nif __name__=='__main__':\n work()","sub_path":"Catcher/RottenTomatoes_by_toplist.py","file_name":"RottenTomatoes_by_toplist.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"51014061","text":"import unittest\nfrom xml.etree import cElementTree as ET\nfrom sleekxmpp.xmlstream.matcher.stanzapath import StanzaPath\n\nclass testpubsubstanzas(unittest.TestCase):\n\n\tdef setUp(self):\n\t\timport sleekxmpp.plugins.stanza_pubsub as ps\n\t\tself.ps = ps\n\n\tdef testAffiliations(self):\n\t\t\"Testing iq/pubsub/affiliations/affiliation stanzas\"\n\t\tiq = self.ps.Iq()\n\t\taff1 = self.ps.Affiliation()\n\t\taff1['node'] = 'testnode'\n\t\taff1['affiliation'] = 'owner'\n\t\taff2 = self.ps.Affiliation()\n\t\taff2['node'] = 'testnode2'\n\t\taff2['affiliation'] = 'publisher'\n\t\tiq['pubsub']['affiliations'].append(aff1)\n\t\tiq['pubsub']['affiliations'].append(aff2)\n\t\txmlstring = \"\"\"\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3), \"3 methods for creating stanza don't match\")\n\t\tself.failUnless(iq.match('iq@id=0/pubsub/affiliations/affiliation@node=testnode2@affiliation=publisher'), 'Match path failed')\n\t\n\tdef testSubscriptions(self):\n\t\t\"Testing iq/pubsub/subscriptions/subscription stanzas\"\n\t\tiq = self.ps.Iq()\n\t\tsub1 = self.ps.Subscription()\n\t\tsub1['node'] = 'testnode'\n\t\tsub1['jid'] = 'steve@myserver.tld/someresource'\n\t\tsub2 = self.ps.Subscription()\n\t\tsub2['node'] = 'testnode2'\n\t\tsub2['jid'] = 'boogers@bork.top/bill'\n\t\tsub2['subscription'] = 'subscribed'\n\t\tiq['pubsub']['subscriptions'].append(sub1)\n\t\tiq['pubsub']['subscriptions'].append(sub2)\n\t\txmlstring = \"\"\"\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\t\n\tdef testOptionalSettings(self):\n\t\t\"Testing iq/pubsub/subscription/subscribe-options stanzas\"\n\t\tiq = self.ps.Iq()\n\t\tiq['pubsub']['subscription']['suboptions']['required'] = True\n\t\tiq['pubsub']['subscription']['node'] = 'testnode alsdkjfas'\n\t\tiq['pubsub']['subscription']['jid'] = \"fritzy@netflint.net/sleekxmpp\"\n\t\tiq['pubsub']['subscription']['subscription'] = 'unconfigured'\n\t\txmlstring = \"\"\"\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\t\n\tdef testItems(self):\n\t\tiq = self.ps.Iq()\n\t\tiq['pubsub']['items']\n\t\tpayload = ET.fromstring(\"\"\"\"\"\")\n\t\tpayload2 = ET.fromstring(\"\"\"\"\"\")\n\t\titem = self.ps.Item()\n\t\titem['id'] = 'asdf'\n\t\titem['payload'] = payload\n\t\titem2 = self.ps.Item()\n\t\titem2['id'] = 'asdf2'\n\t\titem2['payload'] = payload2\n\t\tiq['pubsub']['items'].append(item)\n\t\tiq['pubsub']['items'].append(item2)\n\t\txmlstring = \"\"\"\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\t\t\n\tdef testCreate(self):\n\t\tfrom sleekxmpp.plugins import xep_0004\n\t\tiq = self.ps.Iq()\n\t\tiq['pubsub']['create']['configure']\n\t\tiq['pubsub']['create']['node'] = 'mynode'\n\t\tform = xep_0004.Form()\n\t\tform.addField('pubsub#title', ftype='text-single', value='This thing is awesome')\n\t\tiq['pubsub']['create']['configure']['config'] = form\n\t\txmlstring = \"\"\"This thing is awesome\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\t\n\tdef testDefault(self):\n\t\tfrom sleekxmpp.plugins import xep_0004\n\t\tiq = self.ps.Iq()\n\t\tiq['pubsub']['default']\n\t\tiq['pubsub']['default']['node'] = 'mynode'\n\t\tform = xep_0004.Form()\n\t\tform.addField('pubsub#title', ftype='text-single', value='This thing is awesome')\n\t\tiq['pubsub']['default']['config'] = form\n\t\txmlstring = \"\"\"This thing is awesome\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\t\n\tdef testSubscribe(self):\n\t\tfrom sleekxmpp.plugins import xep_0004\n\t\tiq = self.ps.Iq()\n\t\tiq['pubsub']['subscribe']['options']\n\t\tiq['pubsub']['subscribe']['node'] = 'cheese'\n\t\tiq['pubsub']['subscribe']['jid'] = 'fritzy@netflint.net/sleekxmpp'\n\t\tiq['pubsub']['subscribe']['options']['node'] = 'cheese'\n\t\tiq['pubsub']['subscribe']['options']['jid'] = 'fritzy@netflint.net/sleekxmpp'\n\t\tform = xep_0004.Form()\n\t\tform.addField('pubsub#title', ftype='text-single', value='This thing is awesome')\n\t\tiq['pubsub']['subscribe']['options']['options'] = form\n\t\txmlstring = \"\"\"This thing is awesome\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\t\n\tdef testPublish(self):\n\t\tiq = self.ps.Iq()\n\t\tiq['pubsub']['publish']['node'] = 'thingers'\n\t\tpayload = ET.fromstring(\"\"\"\"\"\")\n\t\tpayload2 = ET.fromstring(\"\"\"\"\"\")\n\t\titem = self.ps.Item()\n\t\titem['id'] = 'asdf'\n\t\titem['payload'] = payload\n\t\titem2 = self.ps.Item()\n\t\titem2['id'] = 'asdf2'\n\t\titem2['payload'] = payload2\n\t\tiq['pubsub']['publish'].append(item)\n\t\tiq['pubsub']['publish'].append(item2)\n\t\txmlstring = \"\"\"\"\"\"\n\t\tiq2 = self.ps.Iq(None, self.ps.ET.fromstring(xmlstring))\n\t\tiq3 = self.ps.Iq()\n\t\tvalues = iq2.getValues()\n\t\tiq3.setValues(values)\n\t\t#print()\n\t\t#print(xmlstring)\n\t\t#print(iq)\n\t\t#print(iq2)\n\t\t#print(iq3)\n\t\tself.failUnless(xmlstring == str(iq) == str(iq2) == str(iq3))\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(testpubsubstanzas)\n","sub_path":"tests/test_pubsubstanzas.py","file_name":"test_pubsubstanzas.py","file_ext":"py","file_size_in_byte":8316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"416303299","text":"import argparse\nimport os\nimport sys\nimport textwrap\nimport traceback\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Set, Union\n\nfrom packaging.specifiers import SpecifierSet\n\nimport cibuildwheel\nimport cibuildwheel.linux\nimport cibuildwheel.macos\nimport cibuildwheel.util\nimport cibuildwheel.windows\nfrom cibuildwheel.architecture import Architecture, allowed_architectures_check\nfrom cibuildwheel.environment import EnvironmentParseError, parse_environment\nfrom cibuildwheel.options import ConfigOptions\nfrom cibuildwheel.projectfiles import get_requires_python_str\nfrom cibuildwheel.typing import PLATFORMS, PlatformName, assert_never\nfrom cibuildwheel.util import (\n BuildFrontend,\n BuildOptions,\n BuildSelector,\n DependencyConstraints,\n TestSelector,\n Unbuffered,\n detect_ci_provider,\n resources_dir,\n)\n\nMANYLINUX_ARCHS = (\n \"x86_64\",\n \"i686\",\n \"pypy_x86_64\",\n \"aarch64\",\n \"ppc64le\",\n \"s390x\",\n \"pypy_aarch64\",\n \"pypy_i686\",\n)\n\n\ndef main() -> None:\n platform: PlatformName\n\n parser = argparse.ArgumentParser(\n description=\"Build wheels for all the platforms.\",\n epilog=\"\"\"\n Most options are supplied via environment variables or in\n --config-file (pyproject.toml usually). See\n https://github.com/pypa/cibuildwheel#options for info.\n \"\"\",\n )\n\n parser.add_argument(\n \"--platform\",\n choices=[\"auto\", \"linux\", \"macos\", \"windows\"],\n default=os.environ.get(\"CIBW_PLATFORM\", \"auto\"),\n help=\"\"\"\n Platform to build for. For \"linux\" you need docker running, on Mac\n or Linux. For \"macos\", you need a Mac machine, and note that this\n script is going to automatically install MacPython on your system,\n so don't run on your development machine. For \"windows\", you need to\n run in Windows, and it will build and test for all versions of\n Python. Default: auto.\n \"\"\",\n )\n\n arch_list_str = \", \".join(a.name for a in Architecture)\n parser.add_argument(\n \"--archs\",\n default=None,\n help=f\"\"\"\n Comma-separated list of CPU architectures to build for.\n When set to 'auto', builds the architectures natively supported\n on this machine. Set this option to build an architecture\n via emulation, for example, using binfmt_misc and QEMU.\n Default: auto.\n Choices: auto, auto64, auto32, native, all, {arch_list_str}\n \"\"\",\n )\n\n parser.add_argument(\n \"--output-dir\",\n help=\"Destination folder for the wheels.\",\n )\n\n parser.add_argument(\n \"--config-file\",\n help=\"\"\"\n TOML config file for cibuildwheel. Defaults to pyproject.toml, but\n can be overridden with this option.\n \"\"\",\n )\n\n parser.add_argument(\n \"package_dir\",\n default=\".\",\n nargs=\"?\",\n help=\"\"\"\n Path to the package that you want wheels for. Must be a subdirectory of\n the working directory. When set, the working directory is still\n considered the 'project' and is copied into the Docker container on\n Linux. Default: the working directory.\n \"\"\",\n )\n\n parser.add_argument(\n \"--print-build-identifiers\",\n action=\"store_true\",\n help=\"Print the build identifiers matched by the current invocation and exit.\",\n )\n\n parser.add_argument(\n \"--allow-empty\",\n action=\"store_true\",\n help=\"Do not report an error code if the build does not match any wheels.\",\n )\n\n parser.add_argument(\n \"--prerelease-pythons\",\n action=\"store_true\",\n help=\"Enable pre-release Python versions if available.\",\n )\n\n args = parser.parse_args()\n\n if args.platform != \"auto\":\n platform = args.platform\n else:\n ci_provider = detect_ci_provider()\n if ci_provider is None:\n print(\n textwrap.dedent(\n \"\"\"\n cibuildwheel: Unable to detect platform. cibuildwheel should run on your CI server;\n Travis CI, AppVeyor, Azure Pipelines, GitHub Actions, CircleCI, and Gitlab are\n supported. You can run on your development machine or other CI providers using the\n --platform argument. Check --help output for more information.\n \"\"\"\n ),\n file=sys.stderr,\n )\n sys.exit(2)\n if sys.platform.startswith(\"linux\"):\n platform = \"linux\"\n elif sys.platform == \"darwin\":\n platform = \"macos\"\n elif sys.platform == \"win32\":\n platform = \"windows\"\n else:\n print(\n 'cibuildwheel: Unable to detect platform from \"sys.platform\" in a CI environment. You can run '\n \"cibuildwheel using the --platform argument. Check --help output for more information.\",\n file=sys.stderr,\n )\n sys.exit(2)\n\n if platform not in PLATFORMS:\n print(f\"cibuildwheel: Unsupported platform: {platform}\", file=sys.stderr)\n sys.exit(2)\n\n package_dir = Path(args.package_dir)\n\n manylinux_identifiers = {\n f\"manylinux-{build_platform}-image\" for build_platform in MANYLINUX_ARCHS\n }\n disallow = {\n \"linux\": {\"dependency-versions\"},\n \"macos\": manylinux_identifiers,\n \"windows\": manylinux_identifiers,\n }\n options = ConfigOptions(package_dir, args.config_file, platform=platform, disallow=disallow)\n output_dir = Path(\n args.output_dir\n if args.output_dir is not None\n else os.environ.get(\"CIBW_OUTPUT_DIR\", \"wheelhouse\")\n )\n\n build_config = options(\"build\", env_plat=False, sep=\" \") or \"*\"\n skip_config = options(\"skip\", env_plat=False, sep=\" \")\n test_skip = options(\"test-skip\", env_plat=False, sep=\" \")\n\n archs_config_str = args.archs or options(\"archs\", sep=\" \")\n\n build_frontend_str = options(\"build-frontend\", env_plat=False)\n environment_config = options(\"environment\", table={\"item\": '{k}=\"{v}\"', \"sep\": \" \"})\n before_all = options(\"before-all\", sep=\" && \")\n before_build = options(\"before-build\", sep=\" && \")\n repair_command = options(\"repair-wheel-command\", sep=\" && \")\n\n dependency_versions = options(\"dependency-versions\")\n test_command = options(\"test-command\", sep=\" && \")\n before_test = options(\"before-test\", sep=\" && \")\n test_requires = options(\"test-requires\", sep=\" \").split()\n test_extras = options(\"test-extras\", sep=\",\")\n build_verbosity_str = options(\"build-verbosity\")\n\n prerelease_pythons = args.prerelease_pythons or cibuildwheel.util.strtobool(\n os.environ.get(\"CIBW_PRERELEASE_PYTHONS\", \"0\")\n )\n\n build_frontend: BuildFrontend\n if build_frontend_str == \"build\":\n build_frontend = \"build\"\n elif build_frontend_str == \"pip\":\n build_frontend = \"pip\"\n else:\n msg = f\"cibuildwheel: Unrecognised build frontend '{build_frontend}', only 'pip' and 'build' are supported\"\n print(msg, file=sys.stderr)\n sys.exit(2)\n\n package_files = {\"setup.py\", \"setup.cfg\", \"pyproject.toml\"}\n\n if not any(package_dir.joinpath(name).exists() for name in package_files):\n names = \", \".join(sorted(package_files, reverse=True))\n msg = f\"cibuildwheel: Could not find any of {{{names}}} at root of package\"\n print(msg, file=sys.stderr)\n sys.exit(2)\n\n # This is not supported in tool.cibuildwheel, as it comes from a standard location.\n # Passing this in as an environment variable will override pyproject.toml, setup.cfg, or setup.py\n requires_python_str: Optional[str] = os.environ.get(\n \"CIBW_PROJECT_REQUIRES_PYTHON\"\n ) or get_requires_python_str(package_dir)\n requires_python = None if requires_python_str is None else SpecifierSet(requires_python_str)\n\n deprecated_selectors(\"CIBW_BUILD\", build_config, error=True)\n deprecated_selectors(\"CIBW_SKIP\", skip_config)\n deprecated_selectors(\"CIBW_TEST_SKIP\", test_skip)\n\n build_selector = BuildSelector(\n build_config=build_config,\n skip_config=skip_config,\n requires_python=requires_python,\n prerelease_pythons=prerelease_pythons,\n )\n test_selector = TestSelector(skip_config=test_skip)\n\n try:\n environment = parse_environment(environment_config)\n except (EnvironmentParseError, ValueError):\n print(f'cibuildwheel: Malformed environment option \"{environment_config}\"', file=sys.stderr)\n traceback.print_exc(None, sys.stderr)\n sys.exit(2)\n\n if dependency_versions == \"pinned\":\n dependency_constraints: Optional[\n DependencyConstraints\n ] = DependencyConstraints.with_defaults()\n elif dependency_versions == \"latest\":\n dependency_constraints = None\n else:\n dependency_versions_path = Path(dependency_versions)\n dependency_constraints = DependencyConstraints(dependency_versions_path)\n\n if test_extras:\n test_extras = f\"[{test_extras}]\"\n\n try:\n build_verbosity = min(3, max(-3, int(build_verbosity_str)))\n except ValueError:\n build_verbosity = 0\n\n # Add CIBUILDWHEEL environment variable\n # This needs to be passed on to the docker container in linux.py\n os.environ[\"CIBUILDWHEEL\"] = \"1\"\n\n archs = Architecture.parse_config(archs_config_str, platform=platform)\n\n identifiers = get_build_identifiers(platform, build_selector, archs)\n\n if args.print_build_identifiers:\n for identifier in identifiers:\n print(identifier)\n sys.exit(0)\n\n manylinux_images: Dict[str, str] = {}\n if platform == \"linux\":\n pinned_docker_images_file = resources_dir / \"pinned_docker_images.cfg\"\n all_pinned_docker_images = ConfigParser()\n all_pinned_docker_images.read(pinned_docker_images_file)\n # all_pinned_docker_images looks like a dict of dicts, e.g.\n # { 'x86_64': {'manylinux1': '...', 'manylinux2010': '...', 'manylinux2014': '...'},\n # 'i686': {'manylinux1': '...', 'manylinux2010': '...', 'manylinux2014': '...'},\n # 'pypy_x86_64': {'manylinux2010': '...' }\n # ... }\n\n for build_platform in MANYLINUX_ARCHS:\n pinned_images = all_pinned_docker_images[build_platform]\n\n config_value = options(f\"manylinux-{build_platform}-image\", ignore_empty=True)\n\n if not config_value:\n # default to manylinux2010 if it's available, otherwise manylinux2014\n image = pinned_images.get(\"manylinux2010\") or pinned_images.get(\"manylinux2014\")\n elif config_value in pinned_images:\n image = pinned_images[config_value]\n else:\n image = config_value\n\n manylinux_images[build_platform] = image\n\n build_options = BuildOptions(\n architectures=archs,\n package_dir=package_dir,\n output_dir=output_dir,\n test_command=test_command,\n test_requires=test_requires,\n test_extras=test_extras,\n before_test=before_test,\n before_build=before_build,\n before_all=before_all,\n build_verbosity=build_verbosity,\n build_selector=build_selector,\n test_selector=test_selector,\n repair_command=repair_command,\n environment=environment,\n dependency_constraints=dependency_constraints,\n manylinux_images=manylinux_images or None,\n build_frontend=build_frontend,\n )\n\n # Python is buffering by default when running on the CI platforms, giving problems interleaving subprocess call output with unflushed calls to 'print'\n sys.stdout = Unbuffered(sys.stdout) # type: ignore\n\n print_preamble(platform, build_options)\n\n try:\n allowed_architectures_check(platform, build_options.architectures)\n except ValueError as err:\n print(\"cibuildwheel:\", *err.args, file=sys.stderr)\n sys.exit(4)\n\n if not identifiers:\n print(f\"cibuildwheel: No build identifiers selected: {build_selector}\", file=sys.stderr)\n if not args.allow_empty:\n sys.exit(3)\n\n if not output_dir.exists():\n output_dir.mkdir(parents=True)\n\n with cibuildwheel.util.print_new_wheels(\n \"\\n{n} wheels produced in {m:.0f} minutes:\", output_dir\n ):\n if platform == \"linux\":\n cibuildwheel.linux.build(build_options)\n elif platform == \"windows\":\n cibuildwheel.windows.build(build_options)\n elif platform == \"macos\":\n cibuildwheel.macos.build(build_options)\n else:\n assert_never(platform)\n\n\ndef deprecated_selectors(name: str, selector: str, *, error: bool = False) -> None:\n if \"p2\" in selector or \"p35\" in selector:\n msg = f\"cibuildwheel 2.x no longer supports Python < 3.6. Please use the 1.x series or update {name}\"\n print(msg, file=sys.stderr)\n if error:\n sys.exit(4)\n\n\ndef print_preamble(platform: str, build_options: BuildOptions) -> None:\n print(\n textwrap.dedent(\n \"\"\"\n _ _ _ _ _ _ _\n ___|_| |_ _ _|_| |_| |_ _ _| |_ ___ ___| |\n | _| | . | | | | | . | | | | | -_| -_| |\n |___|_|___|___|_|_|___|_____|_|_|___|___|_|\n \"\"\"\n )\n )\n\n print(f\"cibuildwheel version {cibuildwheel.__version__}\\n\")\n\n print(\"Build options:\")\n print(f\" platform: {platform!r}\")\n for option, value in sorted(build_options._asdict().items()):\n print(f\" {option}: {value!r}\")\n\n warnings = detect_warnings(platform, build_options)\n if warnings:\n print(\"\\nWarnings:\")\n for warning in warnings:\n print(\" \" + warning)\n\n print(\"\\nHere we go!\\n\")\n\n\ndef get_build_identifiers(\n platform: PlatformName, build_selector: BuildSelector, architectures: Set[Architecture]\n) -> List[str]:\n python_configurations: Union[\n List[cibuildwheel.linux.PythonConfiguration],\n List[cibuildwheel.windows.PythonConfiguration],\n List[cibuildwheel.macos.PythonConfiguration],\n ]\n\n if platform == \"linux\":\n python_configurations = cibuildwheel.linux.get_python_configurations(\n build_selector, architectures\n )\n elif platform == \"windows\":\n python_configurations = cibuildwheel.windows.get_python_configurations(\n build_selector, architectures\n )\n elif platform == \"macos\":\n python_configurations = cibuildwheel.macos.get_python_configurations(\n build_selector, architectures\n )\n else:\n assert_never(platform)\n\n return [config.identifier for config in python_configurations]\n\n\ndef detect_warnings(platform: str, build_options: BuildOptions) -> List[str]:\n warnings = []\n\n # warn about deprecated {python} and {pip}\n for option_name in [\"test_command\", \"before_build\"]:\n option_value = getattr(build_options, option_name)\n\n if option_value and (\"{python}\" in option_value or \"{pip}\" in option_value):\n # Reminder: in an f-string, double braces means literal single brace\n msg = (\n f\"{option_name}: '{{python}}' and '{{pip}}' are no longer needed, \"\n \"and will be removed in a future release. Simply use 'python' or 'pip' instead.\"\n )\n warnings.append(msg)\n\n return warnings\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"cibuildwheel/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":15583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"318527835","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/1/8 10:54\n# @Author : A yang7\nimport numpy as np\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport logging\nlogger = logging.getLogger(__name__)\n\nnp.set_printoptions(threshold=np.nan)\n\n\n__all__ = ['VectorizerWrapper', 'Transform2WordVectors']\n\n\ndef log_trace(message, args):\n logger.info('In {}. #args:{}'.format(message, len(args)))\n for arg in args:\n logger.info(\"\\t{}\".format(type(arg)))\n\n\nclass VectorizerWrapper (TransformerMixin, BaseEstimator):\n def __init__(self, model):\n self.model = model\n\n def fit(self, *args):\n log_trace(\"VectorizerWrapper: fit.\", args)\n self.model.fit(args[0], args[1])\n return self\n\n def transform(self, *args):\n log_trace(\"VectorizerWrapper: transform.\", args)\n return {'sparseX': self.model.transform(args[0]), 'vocab': self.model.vocabulary_}\n\n\nclass Transform2WordVectors (BaseEstimator, TransformerMixin):\n\n wv_obj = None\n\n def __init__(self, wv_obj=None):\n Transform2WordVectors.wv_obj = wv_obj\n\n def fit(self, *args):\n log_trace('Transform2WordVectors: fit.', args)\n return self\n\n def transform(self, *args):\n log_trace(\"Transform2WordVectors: transform.\", args)\n sparse_x = args[0]['sparseX']\n if(not Transform2WordVectors.wv_obj):\n return sparse_x\n else:\n vocab = args[0]['vocab']\n sorted_words = sorted(vocab, key=vocab.get)\n logger.info('sortedWords. type:{}, size:{}'.format(type(sorted_words), len(sorted_words)))\n word_vec = Transform2WordVectors.wv_obj.get_vectors(sorted_words)\n logger.info('wordVectors. type:{}, shape:{}'.format(type(word_vec), word_vec.shape))\n\n reduce_matrix = self.sparse_multiply(sparse_x, word_vec)\n logger.info(\"reduce_matrix. type:{}, shape:{}\".format(type(reduce_matrix), reduce_matrix.shape))\n\n return reduce_matrix\n\n @staticmethod\n def sparse_multiply(sparse_x, word_vectors):\n wv_length = len(word_vectors[0])\n reduce_matrix = []\n\n for row in sparse_x:\n new_row = np.zeros(wv_length)\n for non_zero_location, value in list(zip(row.indices, row.data)):\n new_row = new_row + value * word_vectors[non_zero_location]\n reduce_matrix.append(new_row)\n reduce_matrix = np.array([np.array(xi) for xi in reduce_matrix])\n return reduce_matrix\n\n","sub_path":"Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"135506200","text":"import subprocess as sub\nimport numpy as np\n\nclass validator:\n\n # Set up the pipes to the agwsvalid executable\n # mode should be 'dgnf', 'm3', or 'dgwf'\n def __init__(self, mode, silent=False):\n if silent: \n self.pipes = sub.Popen(['agwsvalid', '--'+mode, '--boolonly'], stdin=sub.PIPE, stdout=sub.PIPE)\n else:\n self.pipes = sub.Popen(['agwsvalid', '--'+mode, '--bool'], stdin=sub.PIPE, stdout=sub.PIPE)\n\n def close(self):\n self.pipes.stdin.close()\n self.pipes.stdout.close()\n \n def check(self, probeax, probeay, probebx, probeby, probecx, probecy, probedx, probedy,**kwargs):\n probestr = \"%f %f %f %f %f %f %f %f\" % (probeax, probeay, probebx, probeby, probecx, probecy, probedx, probedy) + '\\n'\n try:\n self.pipes.stdin.write(bytes(probestr, 'UTF-8'))\n self.pipes.stdin.flush()\n r = self.pipes.stdout.readline().decode('UTF-8').strip().split()\n except:\n return False\n \n self.shadowfrac = float(r[1])\n\n if (str(r[0]) == \"1\"):\n return True\n else:\n return False\n\ndef test():\n \n dgwf = validator('dgwf',silent=True)\n gsloc = np.array([[0,0.159],[-0.159,0],[0,-0.159],[0.159,0]])*0.9\n t = np.ndarray.flatten(gsloc)\n check = dgwf.check(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7])\n print(check)\n print(dgwf.shadowfrac)\n \n dgnf = validator('dgnf',silent=True)\n gsloc = np.array([[0,0.159],[-0.159,0],[0,-0.159],[0.159,0]])*0.9\n t = np.ndarray.flatten(gsloc)\n check = dgnf.check(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7])\n print(check)\n\n dgnf = validator('gmacs',silent=True)\n gsloc = np.array([[0, 9.2/2], [10.7/2,0], [0, -9.2/2], [-10.7/2, 0] ])/60 #in degree\n t = np.ndarray.flatten(gsloc)\n check = dgnf.check(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7])\n print(check)\n","sub_path":"agwsvalid.py","file_name":"agwsvalid.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"240634766","text":"import json\n\ndef choice (data):\n d = json.load(data)\n health = d[\"snakes\"][\"data\"][0][\"health\"]\n \n if health > 45: # chase your own tail\n direction = \"down\" # make this it's astar tail\n else: # locate food\n direction = \"down\" # make the direction right\n\n return direction\n\n# this is all for testing\nif __name__==\"__main__\":\n with open('move.json') as json_data:\n d = json.load(json_data)\n choice(d)\n","sub_path":"app/snakechoice.py","file_name":"snakechoice.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"332585201","text":"# 给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。\r\n#\r\n# 解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。\r\n#\r\n#\r\n#\r\n# 示例 1:\r\n#\r\n#\r\n# 输入:nums = [1,2,3]\r\n# 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n#\r\n# 输入:nums = [0]\r\n# 输出:[[],[0]]\r\n#\r\n#\r\n#\r\n#\r\n# 提示:\r\n#\r\n#\r\n# 1 <= nums.length <= 10\r\n# -10 <= nums[i] <= 10\r\n# nums 中的所有元素 互不相同\r\n#\r\n# Related Topics 位运算 数组 回溯算法\r\n# 👍 1226 👎 0\r\n\r\nfrom typing import List\r\n# leetcode submit region begin(Prohibit modification and deletion)\r\nclass Solution:\r\n def subsets(self, nums: List[int]) -> List[List[int]]:\r\n self.res = []\r\n self.backtrack(0, nums, [])\r\n return self.res\r\n\r\n def backtrack(self, index, nums, track): #回溯算法\r\n if index == len(nums): #结束条件\r\n self.res.append(track[:]) #注意,添加时要用[:]\r\n return\r\n track.append(nums[index]) #将nums[index]加入track\r\n self.backtrack(index+1, nums, track) #进行回溯\r\n track.pop() #撤销nums[index]\r\n self.backtrack(index+1, nums, track) # track不添加nums[index],进行回溯\r\n\r\n# leetcode submit region end(Prohibit modification and deletion)\r\n\r\n\r\nsolution = Solution()\r\nprint(solution.subsets([1,2,3]))\r\nprint(solution.subsets([0]))\r\n","sub_path":"[78]子集.pyi","file_name":"[78]子集.pyi","file_ext":"pyi","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"624715920","text":"\"\"\" original contribution from Andrew Dalke \"\"\"\nimport sys\nfrom rdkit import Chem\nfrom rdkit.Chem import AllChem\nimport pdb\n\nwriter = Chem.SDWriter(\"decane_rdk_optim.sdf\")\n\n# This function is called in the subprocess.\n# The parameters (molecule and number of conformers) are passed via a Python\ndef generateconformations(m, n):\n m = Chem.AddHs(m)\n ids=AllChem.EmbedMultipleConfs(m, numConfs=n, params=AllChem.ETKDG())\n # EmbedMultipleConfs returns a Boost-wrapped type which\n # cannot be pickled. Convert it to a Python list, which can.\n return m, list(ids)\n\n# m = Chem.MolFromSmiles('CC1=C(C(CCC1)(C)C)C=CC(=CC=CC(=CCO)C)C') #retinol\n# m = Chem.MolFromSmiles('CCC(=O)N(C1CCN(CCC2=CC=CC=C2)CC1)C1=CC=CC=C1') #fentanyl\nm = Chem.MolFromSmiles('CCCCCCCCCC') #decane\n# m = Chem.MolFromSmiles('CC(CC1=CC=CC=C1)NC') #meth\nn = 8\n\nmol, ids = generateconformations(m, n)\ncopy_mol, copy_ids = mol, ids\nres = AllChem.MMFFOptimizeMoleculeConfs(mol, numThreads=0, maxIters=600)\nprint(res)\n\n# pdb.set_trace()\nfor id in ids:\n\twriter.write(mol, confId=id)\n","sub_path":"conformation_generator.py","file_name":"conformation_generator.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"347996334","text":"def factorial(nums):\r\n while nums > 1:\r\n fact = nums\r\n fact = fact*(nums-1)\r\n nums -= 1\r\n return fact\r\n\r\n\r\nnumber = int(input('enter the number you wish to calculate the factorial of\\n='))\r\nresult = factorial(number)\r\nprint(f'the factorial of the number is {result}')\r\n","sub_path":"functions_mul.py","file_name":"functions_mul.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"111175459","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2018年3月6日\n\n@author: zwp\n'''\n\n'''\n单分类问题的例子\n包括模型,训练,评价\n模型持久化\n\n'''\n\nimport tensorflow as tf;\nimport numpy as np;\nfrom LAMOST import DataSource, DataSetProcess\nimport time;\n########################## 参数 ##########################\n\n\ndef act_func(X):\n return tf.nn.relu(X);\n\n# 特征数,输入张量的shape\nfeature_size = 2600;\n# 标签数,输出张量的shape\nlabel_size = 4;\n# 隐层数和各个层节点数\nhiddens = [300,80];\n\nsteps = 8000;\nbatch_size = 30;\nlearn_rate = 0.001;\nlearn_rate_decy = 0.96;\n\nneed_regular=True;\nregular_lambda = 0.01;\n\nneed_val_avage=False;\nmove_avage_rate = 0.9999;\n\nmodel_save_path = 'value_cache/model_uk_type.ckpt'\n\nload_value = False;\nneed_train=True;\nneed_result_out=False;\n########################## 模型部分 #######################\n\ndef get_weight_variable(shape,regularizer=None):\n '''\n 获取权重函数,如果regularizer不是None\n 则在损失函数中添加正则化\n '''\n weights = tf.get_variable('weights',\n shape,\n initializer=tf.truncated_normal_initializer( stddev=0.05));\n if regularizer != None:\n tf.add_to_collection('losses', regularizer(weights));\n return weights;\n\n# 定义模型函数,\ndef get_inference(X,act_func,regularizer):\n '''\n 定义模型函数\n '''\n lay_cot = len(hiddens);\n with tf.variable_scope('hidden_layer1',reuse=tf.AUTO_REUSE):\n weights = get_weight_variable([feature_size,hiddens[0]],regularizer);\n biase = tf.get_variable('biase1',\n [hiddens[0]],\n initializer=tf.truncated_normal_initializer( stddev=0.05));\n layer = act_func(tf.matmul(X,weights)+biase);\n for lay_num in range(1,lay_cot):\n var_name = 'hidden_layer%d'%(lay_num+1);\n with tf.variable_scope(var_name,reuse=tf.AUTO_REUSE):\n weights = get_weight_variable([hiddens[lay_num-1],hiddens[lay_num]],regularizer);\n biase = tf.get_variable('biase%d'%(lay_num+1),\n [hiddens[lay_num]],\n initializer=tf.truncated_normal_initializer( stddev=0.05));\n layer = act_func(tf.matmul(layer,weights)+biase);\n \n # 输出层设计\n with tf.variable_scope('out_layer',reuse=tf.AUTO_REUSE):\n weights = get_weight_variable([hiddens[lay_cot-1],label_size],regularizer);\n biase = tf.get_variable('biase_out',\n [label_size],\n initializer=tf.truncated_normal_initializer( stddev=0.05));\n layer = tf.matmul(layer,weights)+biase; \n \n return layer\n\n\n\n########################## 训练部分 #######################\n\n\ndef train(datasource):\n X = tf.placeholder(tf.float32, [None,feature_size], 'X');\n Y = tf.placeholder(tf.float32, [None,label_size], 'Y');\n \n \n global_step = tf.Variable(0,trainable=False,name='gs');\n data_size = datasource.data_size();\n \n # 正则处理\n if need_regular: \n regularizer = tf.contrib.layers.l2_regularizer(regular_lambda);\n py = get_inference(X, act_func, regularizer);\n else:\n py = get_inference(X, act_func, None);\n \n\n \n # 滑动平均\n if need_regular:\n variable_avage = tf.train.ExponentialMovingAverage(move_avage_rate,global_step);\n variable_avage_op = variable_avage.apply(tf.trainable_variables());\n \n # 损失函数\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y, logits=py));\n regloss = tf.get_collection('losses');\n if len(regloss)!=0:\n loss = loss + tf.add_n(regloss);\n # 递减学习率\n lr = tf.train.exponential_decay(learn_rate, global_step,\n data_size/batch_size,\n #200,\n learn_rate_decy,\n staircase=True);\n \n # 优化训练过程\n train_step = tf.train.AdamOptimizer(lr).minimize(loss,global_step=global_step);\n if need_regular:\n train_op = tf.group(train_step,variable_avage_op);\n else:\n train_op = train_step;\n \n saver = tf.train.Saver();\n with tf.Session() as sess:\n if load_value:\n saver.restore(sess, model_save_path);\n else:\n sess.run(tf.global_variables_initializer());\n now = time.time();\n for i in range(steps):\n start = (i*batch_size) % data_size;\n end = min(start+batch_size,data_size);\n xs,ys = datasource.getDataXY(start,end);\n _,lossv,pyv,yv,step = sess.run([train_op,loss,py,Y,global_step],{X:xs,Y:ys});\n if step%20==0:\n print('step=%d loss=%.5f time=%.2f'%(step,lossv,time.time()-now));\n now = time.time();\n saver.save(sess,model_save_path);\n print('finished!'); \n\n\n \n########################## 测评部分 #######################\n \ndef evel(datasource):\n X = tf.placeholder(tf.float32, [None,feature_size]);\n py = get_inference(X, act_func,None);\n py = tf.nn.softmax(py, axis=1);\n saver = tf.train.Saver();\n with tf.Session() as sess:\n saver.restore(sess, model_save_path);\n xs,ys = datasource.getAllData();\n py = sess.run(py,{X:xs});\n \n data_size = datasource.data_size();\n y = np.array(ys);\n py = np.array(py);\n \n mxpy=np.reshape(np.max(py,axis=1),(-1,1));\n py =(py/mxpy).astype(int);\n \n y_sum_types = np.sum(y,axis=0);\n py_sum_types= np.sum(py,axis=0);\n \n py_indexes = np.reshape(np.argmax(py, axis=1),(-1,1));\n y_indexes = np.reshape(np.argmax(y, axis=1),(-1,1));\n \n err=0;\n err_type=np.array([0,0,0,0],dtype=float);\n \n for i in range(data_size):\n yi = y_indexes[i];\n pyi = py_indexes[i];\n if yi != pyi:\n err+=1;\n err_type[yi]+=1;\n print('y=\\t',y_sum_types);\n print('py=\\t',py_sum_types);\n print('err=\\t',err_type);\n tp = (y_sum_types-err_type);\n recall = np.divide(tp, y_sum_types, out=np.zeros_like(tp), where=y_sum_types!=0);\n prec = np.divide(tp, py_sum_types, out=np.zeros_like(tp), where=py_sum_types!=0);\n \n print('recall\\t',recall);\n print('prec\\t',prec);\n tmp1 = 2*recall*prec;\n tmp2 = recall+prec;\n macro_f1 = np.mean(np.divide(tmp1,tmp2,out=np.zeros_like(tmp1),where=tmp2!=0));\n print('all=%d true=%d err=%d pr=%.2f%%,macro_f1=%.3f'%(data_size,data_size-err,err,err*100.0/data_size,macro_f1));\n return py; \n\n########################## 计算部分 #######################\n\ndef calculate(datasource):\n X = tf.placeholder(tf.float32, [None,feature_size]);\n py = get_inference(X, act_func,None);\n py = tf.nn.softmax(py, axis=1);\n saver = tf.train.Saver();\n with tf.Session() as sess:\n saver.restore(sess, model_save_path);\n xs = datasource.getAllDataX();\n py = sess.run(py,{X:xs});\n return py;\n\n\n\n\nbase_path=r'/home/zwp/work/Dataset/tianci/LAMOST';\ntrain_data_index = base_path+r'/index_train_uk.csv';\ntrain_data_zip = base_path+r'/first_train_data_20180131.zip';\n\ntest_data_index = base_path+r'/index_test_uk.csv';\ntest_data_zip = base_path+r'/first_train_data_20180131.zip';\n\n\nresult_test_index=base_path+r'/first_test_index_20180131.csv';\nresult_test_data_zip=base_path+r'/first_test_data_20180131.zip';\nresult_test_out_path=base_path+r'/test_result.csv';\n\n\ndef run():\n\n print('\\n加载训练数据')\n train_ds = DataSource.DataSource(train_data_index,train_data_zip);\n if need_train:\n print('\\n开始训练')\n train(train_ds,);\n print('\\n开始测试')\n train_ds.reload_index(test_data_index);\n print('开始测评')\n evel(train_ds);\n \n if need_result_out:\n print('\\n开始加载比赛数据集')\n result_ds=DataSource.DataSource(result_test_index,result_test_data_zip);\n indexids=result_ds.getAllIndexID();\n print('计算比赛数据')\n py=calculate(result_ds);\n print('创建比赛文件')\n DataSetProcess.create_result_csv(indexids, py, result_test_out_path);\n \n \n pass;\n\n\n\nif __name__ == '__main__':\n run();\n pass","sub_path":"TianChiMatch/src/LAMOST/BPModel_uk_type.py","file_name":"BPModel_uk_type.py","file_ext":"py","file_size_in_byte":8361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"232183163","text":"from django.conf.urls import url\nfrom account import views\n\nurlpatterns = [\n url(r'^$', views.account, name='goats-account'),\n url(r'^login', views.login, name='goats-login'),\n url(r'^auth', views.auth_view, name='goats-auth'),\n url(r'^logout', views.logout, name='goats-logout'),\n url(r'^loggedin', views.loggedin, name='goats-loggedin'), \n url(r'^invalid', views.invalid_login, name='goats-invalid'),\n url(r'^register', views.register, name='goats-register'),\n url(r'^register_user', views.register_user, name='goats-register'),\n url(r'^register_success', views.register_success, name='goats-register-success'),\n # url(r'^profile', views.profile, name='goats-profile'),\n # url(r'^teams', views.teams, name='goats-teams'),\n\n]","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"272617288","text":"import pymongo\n\nzd_host = '127.0.0.1'\nzd_port = 27017\nzd_client = pymongo.MongoClient(host=zd_host, port=zd_port)\nzd_db = zd_client['TaobaoInsurance']\n\ndoc_productInfo = zd_db['product_info']\n\nlist_seller = doc_productInfo.find({}, {'seller_id': 1})\n\nprint(list_seller)\n\nfor each_seller in list_seller:\n\n # del each_seller['_id']\n print(each_seller)","sub_path":"Playground/Python/Basic/PyMongo_find.py","file_name":"PyMongo_find.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"295447556","text":"from collections import KeysView\n\nfrom Corpus.Corpus import Corpus\nfrom Corpus.Sentence import Sentence\nfrom DataStructure.CounterHashMap import CounterHashMap\n\nfrom PosTagger.PosTaggedWord import PosTaggedWord\nimport re\n\n\nclass PosTaggedCorpus(Corpus):\n\n __tagList: CounterHashMap\n\n def __init__(self, fileName:str = None):\n \"\"\"\n A constructor of PosTaggedCorpus which initializes the sentences of the corpus, the word list of\n the corpus, and all possible tags.\n\n PARAMETERS\n ----------\n fileName : str\n Name of the corpus file.\n \"\"\"\n self.sentences = []\n self.wordList = CounterHashMap()\n self.__tagList = CounterHashMap()\n newSentence = Sentence()\n if fileName is not None:\n inputFile = open(fileName, \"r\", encoding=\"utf8\")\n lines = inputFile.readlines()\n for line in lines:\n words = re.split(\"[\\t\\n ]\", line)\n for word in words:\n if len(word) > 0 and \"/\" in word:\n name = word[:word.rindex(\"/\")]\n tag = word[word.rindex(\"/\") + 1:]\n if \"+\" in tag:\n shortTag = tag[:tag.index(\"+\")]\n elif \"-\" in tag:\n shortTag = tag[:tag.index(\"-\")]\n else:\n shortTag = tag\n self.__tagList.put(shortTag)\n newSentence.addWord(PosTaggedWord(name, shortTag))\n if tag == '.':\n self.addSentence(newSentence)\n newSentence = Sentence()\n if newSentence.wordCount() > 0:\n self.addSentence(newSentence)\n\n def getTagList(self) -> KeysView:\n \"\"\"\n getTagList returns all possible tags as a set.\n\n RETURNS\n -------\n set\n Set of all possible tags.\n \"\"\"\n return self.__tagList.keys()\n","sub_path":"PosTagger/PosTaggedCorpus.py","file_name":"PosTaggedCorpus.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"280383971","text":"import cv2\nfrom typing import List, Dict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef crop_image(image: np.ndarray, height: int, width: int, stride:int = 1) -> List[np.ndarray]:\n \"\"\"\n Retorna os pedaços da imagem com dimensão height X width.\n \"\"\"\n w, h = image.shape\n \n patches = []\n\n for row in range(0, w - width + 1, stride):\n for col in range(0, h - height + 1, stride):\n patches.append(image[row:row + width, col: col + height])\n \n patches = np.array(patches)\n\n return patches\n\ndef show(img):\n assert len(img.shape) == 2, 'A imagem deve ter apenas 2 dimensões.'\n\n plt.figure(figsize=(12,8))\n plt.imshow(img, cmap='gray', interpolation='nearest')\n\ndef mostrar_lado_a_lado(imagens: List[np.ndarray], titulos: List[str], figsize: Dict[int, int] = (12,8)):\n \"\"\"\n Imprime as imagens que estiverem na lista com os títulos apresentados.\n \"\"\"\n \n assert len(imagens) == len(titulos), 'imagens e titulos devem ter o mesmo tamanho.'\n assert len(imagens[0].shape) == 2, 'As imagens deve ter apenas 2 dimensões.'\n \n quantidade = len(imagens)\n \n fig, ax = plt.subplots(1, quantidade, figsize=figsize)\n \n for i in range(quantidade):\n ax[i].axis('off')\n ax[i].set_title(titulos[i])\n ax[i].imshow(imagens[i], cmap='gray', interpolation='nearest')\n\ndef adiciona_a_dimensao_das_cores(array:np.ndarray) -> np.ndarray:\n \"\"\"\n Adiciona a dimensão das cores no array numpy, considerando a imagem sendo escala de cinza.\n \"\"\"\n return array.reshape( array.shape + (1,) )\n\ndef histograma_colorido(imagem, intervalo=(0, 256)):\n \"\"\" \n Histograma para imagem colorida (RGB).\n \"\"\"\n \n color = ('b','g','r')\n \n fig, ax = plt.subplots(3,1, figsize=(12,8))\n \n for i,col in enumerate(color):\n histr = cv2.calcHist([imagem],[i],None,[intervalo[1]],[intervalo[0],intervalo[1]])\n ax[i].plot(histr, color = col)\n ax[i].set_xlim([intervalo[0],intervalo[1]])\n# plt.plot(histr,color = col)\n# plt.xlim([intervalo[0],intervalo[1]])\n plt.show()\n\ndef histograma(imagem, intervalo=(0, 256)):\n plt.figure(figsize=(12,8))\n \n histr = cv2.calcHist([imagem],[0],None,[intervalo[1]],[intervalo[0],intervalo[1]])\n plt.plot(histr, color = 'b')\n plt.xlim([intervalo[0],intervalo[1]])\n plt.show()\n\nif __name__ == '__main__':\n a = np.arange(180*180).reshape(180, 180)\n print(a.shape)\n\n patches = crop_image(a, height=40, width=40, stride=40)\n print(patches.shape)\n\n print(patches[0].shape)\n print(patches)\n import matplotlib.pyplot as plt\n\n plt.imshow(patches[0], cmap='gray', interpolation='nearest')\n plt.show()\n","sub_path":"images/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"423289059","text":"from abc import ABC, abstractmethod\n\nimport pandas as pd\nfrom typing import Optional, Union, Dict, List\n\nfrom arize import public_pb2 as public__pb2\nfrom arize.utils.types import ModelTypes\nfrom arize.utils.utils import (\n validate_prediction_timestamps,\n bundle_records,\n convert_element,\n get_value_object,\n get_timestamp,\n infer_model_type,\n get_bulk_records,\n)\n\n# TODO this class hierarchy will go away\n\n\nclass BaseRecord(ABC):\n def __init__(\n self,\n organization_key: str,\n model_id: str,\n model_type: Optional[ModelTypes] = None,\n ):\n self.organization_key = organization_key\n self.model_id = model_id\n self.model_type = model_type\n\n @abstractmethod\n def validate_inputs(self):\n pass\n\n @abstractmethod\n def build_proto(self):\n pass\n\n def _base_validation(self):\n if not isinstance(self.organization_key, str):\n raise TypeError(\n f\"organization_key {self.organization_key} is type {type(self.organization_key)}, but must be a str\"\n )\n if not isinstance(self.model_id, str):\n raise TypeError(\n f\"model_id {self.model_id} is type {type(self.model_id)}, but must be a str\"\n )\n\n def _label_validation(self, label):\n if self.model_type == ModelTypes.BINARY:\n if not (isinstance(label, bool) or label == 0 or label == 1):\n raise TypeError(\n f\"label {label} has type {type(label)}, but must be one a bool, 0 or 1 for ModelTypes.BINARY\"\n )\n elif self.model_type == ModelTypes.NUMERIC:\n if not isinstance(label, (float, int)):\n raise TypeError(\n f\"label {label} has type {type(label)}, but must be either float or int for ModelTypes.NUMERIC\"\n )\n elif self.model_type == ModelTypes.CATEGORICAL:\n if not isinstance(label, str):\n raise TypeError(\n f\"label {label} has type {type(label)}, but must be str for ModelTypes.CATEGORICAL\"\n )\n elif self.model_type == ModelTypes.SCORE_CATEGORICAL:\n if not isinstance(label, str):\n raise TypeError(\n f\"label {label} has type {type(label)}, but must be str for ModelTypes.SCORE_CATEGORICAL\"\n )\n\n def _get_label(\n self, name: str, value, score: Optional[float] = None\n ) -> public__pb2.Label:\n if isinstance(value, public__pb2.Label):\n return value\n val = convert_element(value)\n if self.model_type == ModelTypes.SCORE_CATEGORICAL:\n return public__pb2.Label(\n score_categorical=public__pb2.ScoreCategorical(\n categorical=val, score=convert_element(score)\n )\n )\n elif self.model_type == ModelTypes.BINARY:\n return public__pb2.Label(binary=val)\n elif self.model_type == ModelTypes.NUMERIC:\n return public__pb2.Label(numeric=val)\n elif self.model_type == ModelTypes.CATEGORICAL:\n return public__pb2.Label(categorical=val)\n raise TypeError(\n f\"{name}_label = {value} of type {type(value)}. Must be one of str, bool, float, or int\"\n )\n\n\nclass PreProductionRecords(BaseRecord, ABC):\n def __init__(\n self,\n organization_key: str,\n model_id: str,\n model_version: str,\n prediction_labels: Union[pd.DataFrame, pd.Series],\n actual_labels: Union[pd.DataFrame, pd.Series],\n features: Optional[pd.DataFrame] = None,\n model_type: Optional[ModelTypes] = None,\n prediction_scores: Optional[Union[pd.DataFrame, pd.Series]] = None,\n prediction_ids: Optional[Union[pd.DataFrame, pd.Series]] = None,\n ):\n if model_type is None:\n if prediction_scores is None:\n model_type = (\n infer_model_type(prediction_labels[0])\n if model_type is None\n else model_type\n )\n else:\n model_type = ModelTypes.SCORE_CATEGORICAL\n super().__init__(\n organization_key=organization_key, model_id=model_id, model_type=model_type\n )\n self.model_version = model_version\n self.features = features\n self.prediction_labels = prediction_labels\n self.prediction_scores = prediction_scores\n self.actual_labels = actual_labels\n self.prediction_ids = prediction_ids\n\n def _validate_preprod_inputs(self):\n self._base_validation()\n if not isinstance(self.model_version, str):\n raise TypeError(\n f\"model_version {self.model_version} is type {type(self.model_version)}, but must be a str\"\n )\n if not isinstance(self.prediction_labels, (pd.DataFrame, pd.Series)):\n raise TypeError(\n f\"prediction_labels is type {type(self.prediction_labels)}, but expects one of: pd.DataFrame, pd.Series\"\n )\n if self.prediction_labels.shape[0] != self.actual_labels.shape[0]:\n raise ValueError(\n f\"prediction_labels contains {self.prediction_labels.shape[0]} elements, but must have the same as \"\n f\"actual_labels: {self.actual_labels.shape[0]}. \"\n )\n if self.model_type == ModelTypes.SCORE_CATEGORICAL:\n if not isinstance(self.prediction_scores, (pd.DataFrame, pd.Series)):\n raise TypeError(\n f\"prediction_scores is type {type(self.prediction_scores)}, but expects one of: pd.DataFrame, pd.Series\"\n )\n if self.prediction_scores.shape[0] != self.prediction_labels.shape[0]:\n raise ValueError(\n f\"prediction_scores contains {self.prediction_scores.shape[0]} elements, but must have the same as \"\n f\"prediction_labels: {self.prediction_scores.shape[0]}.\"\n )\n\n if self.prediction_ids is not None:\n if not isinstance(self.prediction_labels, (pd.DataFrame, pd.Series)):\n raise TypeError(\n f\"prediction_ids is type {type(self.prediction_ids)}, but expects one of: pd.DataFrame, pd.Series\"\n )\n if self.prediction_labels.shape[0] != self.prediction_ids.shape[0]:\n raise ValueError(\n f\"prediction_ids contains {self.prediction_ids.shape[0]} elements, but must have the same as \"\n f\"prediction_labels: {self.prediction_labels.shape[0]}. \"\n )\n\n if self.features is None:\n return\n if not isinstance(self.features, pd.DataFrame):\n raise TypeError(\n f\"features is type {type(self.features)}, but expect type pd.DataFrame.\"\n )\n if self.features.shape[0] != self.prediction_labels.shape[0]:\n raise ValueError(\n f\"features has {self.features.shape[0]} sets of features, but must match size of prediction_labels: \"\n f\"{self.prediction_labels.shape[0]}. \"\n )\n for name in self.features.columns:\n if not isinstance(name, str):\n raise TypeError(\n f\"features.column {name} is type {type(name)}, but expect str\"\n )\n\n def _normalize_inputs(self):\n \"\"\"Converts inputs from DataFrames, Series, lists to numpy arrays or lists for consistent iterations\n downstream.\"\"\"\n if isinstance(self.prediction_labels, (pd.DataFrame, pd.Series)):\n self.prediction_labels = self.prediction_labels.to_numpy()\n if isinstance(self.prediction_ids, (pd.DataFrame, pd.Series)):\n self.prediction_ids = self.prediction_ids.to_numpy()\n if isinstance(self.actual_labels, (pd.DataFrame, pd.Series)):\n self.actual_labels = self.actual_labels.to_numpy()\n if isinstance(self.prediction_scores, (pd.DataFrame, pd.Series)):\n self.prediction_scores = self.prediction_scores.to_numpy()\n if isinstance(self.features, pd.DataFrame):\n self.feature_names = self.features.columns\n self.features = self.features.to_numpy()\n\n\nclass TrainingRecords(PreProductionRecords):\n def __init__(\n self,\n organization_key: str,\n model_id: str,\n model_version: str,\n prediction_labels: Union[pd.DataFrame, pd.Series],\n actual_labels: Union[pd.DataFrame, pd.Series],\n features: Optional[pd.DataFrame] = None,\n model_type: Optional[ModelTypes] = None,\n prediction_scores: Optional[Union[pd.DataFrame, pd.Series]] = None,\n ):\n super().__init__(\n organization_key=organization_key,\n model_id=model_id,\n model_type=model_type,\n model_version=model_version,\n features=features,\n prediction_labels=prediction_labels,\n prediction_scores=prediction_scores,\n actual_labels=actual_labels,\n )\n\n def validate_inputs(self):\n self._validate_preprod_inputs()\n\n def build_proto(self):\n records = []\n self._normalize_inputs()\n for row, v in enumerate(self.prediction_labels):\n a = public__pb2.Actual(\n label=self._get_label(value=self.actual_labels[row], name=\"actual\")\n )\n score = (\n None\n if self.model_type != ModelTypes.SCORE_CATEGORICAL\n else self.prediction_scores[row]\n )\n p = public__pb2.Prediction(\n label=self._get_label(value=v, name=\"prediction\", score=score),\n model_version=self.model_version,\n )\n\n if self.features is not None:\n converted_feats = {}\n for column, name in enumerate(self.feature_names):\n val = get_value_object(value=self.features[row][column], name=name)\n if val is not None:\n converted_feats[name] = val\n feats = public__pb2.Prediction(features=converted_feats)\n p.MergeFrom(feats)\n\n panda = public__pb2.PredictionAndActual(\n prediction=p,\n actual=a,\n )\n r = public__pb2.Record(\n organization_key=self.organization_key,\n model_id=self.model_id,\n prediction_and_actual=panda,\n )\n\n t = public__pb2.PreProductionRecord(\n training_record=public__pb2.PreProductionRecord.TrainingRecord(record=r)\n )\n records.append(t)\n return bundle_records(records)\n\n\nclass ValidationRecords(PreProductionRecords):\n def __init__(\n self,\n organization_key: str,\n model_id: str,\n model_version: str,\n batch_id: str,\n prediction_labels: Union[pd.DataFrame, pd.Series],\n actual_labels: Union[pd.DataFrame, pd.Series],\n features: Optional[pd.DataFrame] = None,\n model_type: Optional[ModelTypes] = None,\n prediction_scores: Optional[Union[pd.DataFrame, pd.Series]] = None,\n prediction_ids: Optional[Union[pd.DataFrame, pd.Series]] = None,\n prediction_timestamps: Optional[Union[List[int], pd.Series]] = None,\n ):\n super().__init__(\n organization_key=organization_key,\n model_id=model_id,\n model_type=model_type,\n model_version=model_version,\n features=features,\n prediction_labels=prediction_labels,\n prediction_scores=prediction_scores,\n actual_labels=actual_labels,\n prediction_ids=prediction_ids,\n )\n self.batch_id = batch_id\n self.prediction_timestamps = prediction_timestamps\n\n def validate_inputs(self):\n self._validate_preprod_inputs()\n if not isinstance(self.batch_id, str):\n raise TypeError(\n f\"batch_id {self.batch_id} is type {type(self.batch_id)}, but must be a str\"\n )\n validate_prediction_timestamps(self.prediction_ids, self.prediction_timestamps)\n\n def build_proto(self):\n records = []\n self._normalize_inputs()\n prediction_timestamps = (\n self.prediction_timestamps.tolist()\n if isinstance(self.prediction_timestamps, pd.Series)\n else self.prediction_timestamps\n )\n for row, v in enumerate(self.prediction_labels):\n a = public__pb2.Actual(\n label=self._get_label(value=self.actual_labels[row], name=\"actual\")\n )\n score = (\n None\n if self.model_type != ModelTypes.SCORE_CATEGORICAL\n else self.prediction_scores[row]\n )\n p = public__pb2.Prediction(\n label=self._get_label(value=v, name=\"prediction\", score=score),\n model_version=self.model_version,\n )\n\n if prediction_timestamps is not None:\n p.timestamp.MergeFrom(get_timestamp(prediction_timestamps[row]))\n\n prediction_id = None\n if self.prediction_ids is not None:\n v = self.prediction_ids[row]\n prediction_id = v if isinstance(v, str) else v[0]\n if not isinstance(prediction_id, str):\n raise TypeError(\n f\"prediction_id={prediction_id} of type {type(prediction_id)}. Must be str type.\"\n )\n\n if self.features is not None:\n converted_feats = {}\n for column, name in enumerate(self.feature_names):\n val = get_value_object(value=self.features[row][column], name=name)\n if val is not None:\n converted_feats[name] = val\n feats = public__pb2.Prediction(features=converted_feats)\n p.MergeFrom(feats)\n\n panda = public__pb2.PredictionAndActual(\n prediction=p,\n actual=a,\n )\n r = public__pb2.Record(\n prediction_id=prediction_id,\n organization_key=self.organization_key,\n model_id=self.model_id,\n prediction_and_actual=panda,\n )\n v = public__pb2.PreProductionRecord(\n validation_record=public__pb2.PreProductionRecord.ValidationRecord(\n batch_id=self.batch_id, record=r\n ),\n )\n records.append(v)\n return bundle_records(records)\n","sub_path":"arize/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"34992434","text":"import matplotlib\nimport matplotlib.cm as cmx\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib as mpl\nimport numpy as np\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\nimport random\n\n\nimport os\ndef printPath(pathtemp):\n path=pathtemp\n # 所有文件夹,第一个字段是次目录的级别\n dirList = []\n # 所有文件\n fileList = []\n # 返回一个列表,其中包含在目录条目的名称\n files = os.listdir(path)\n #print(files)\n # 先添加目录级别\n for f in files:\n if (os.path.isdir(path + '/' + f)):\n # 排除隐藏文件夹。因为隐藏文件夹过多\n if (f[0] == '.'):\n pass\n else:\n # 添加非隐藏文件夹\n dirList.append(f)\n if (os.path.isfile(path + '/' + f)):\n # 添加文件\n fileList.append(f)\n i=1\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n for fl in fileList:\n x=[]\n y=[]\n\n # 打印文件\n #print(fl)\n f = open(path + fl) # 读取完txt再读txt里面的类容\n alllines = f.readlines()\n for eachLine in alllines:\n eachdata = eachLine.split()\n x.append(float(eachdata[0]))\n y.append(float(eachdata[1]))\n z=np.linspace(i*0.01,i*0.01,len(x))\n i+=1\n z=z.tolist()\n # print(z)\n # print(x)\n # print(y)\n #ax.plot(x,y,z,label=fl)\n # plt.plot(x,y,label=fl)\n color = plt.cm.Set2(random.choice(range(plt.cm.Set2.N)))\n #dz = hist.flatten()\n ax.bar(x,y,zs=z, zdir='y',alpha=1,label=fl)\n\n ax.set_title(\"3D\")\n ax.set_xlabel(\"time/ms\")\n ax.set_ylabel(\"cps\")\n ax.set_zlabel(\"曲线编号\")\n # plt.legend()\n plt.show()\n# printPath(\"C:/Users/ENERGY/Desktop/finall2/处理后的原始数据/\")\nprintPath(\"C:/Users/ENERGY/Desktop/新建文件夹 (2)/处理后的原始数据/\")\n\n","sub_path":"AcqBiophoton_Plot/ccc.py","file_name":"ccc.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"648130900","text":"##########################################################\n# Contains variables shared across iperf3 tool components\n##########################################################\n\n# Default test time\nDEFAULT_DURATION = 10\n\n# Default extra time to add on to test to wait for control packets, etc.\n## BWCTL needs a lot becuause it takes time to schedule test\nDEFAULT_FUDGE_FACTOR = 60\n\n# Default number of seconds before client will start to allow server time to boot\nDEFAULT_WAIT_SLEEP = 1\n\n# The default iperf3 control port\nDEFAULT_SERVER_PORT = 5201\n","sub_path":"pscheduler-tool-bwctliperf3/bwctliperf3/iperf3_defaults.py","file_name":"iperf3_defaults.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"554053455","text":"import re\nfrom urllib import request\nimport requests\nfrom bs4 import BeautifulSoup\nfrom fake_useragent import UserAgent\n\nurl = 'http://quote.stockstar.com/fund/stock_3_1_2.html'\n\nua = UserAgent()\nheaders = {\n 'User-Agent':ua.chrome\n}\n\n\nproxy_get = requests.get('http://107.148.246.41:5010/get/').text\n\nproxy = {\n 'http':'http://'+proxy_get\n}\n# html = requests.get(url=url, headers=headers, proxies=proxy)\nreq = request.Request(url, headers=headers)\nres = request.urlopen(req)\n\nsoup = BeautifulSoup(res.read().decode('gb2312'),'lxml')\n\ndata_list = soup.select('#datalist')[0] #取到id是datalist的元素\n\ntr_list = data_list.select('tr')\nfor each_line in tr_list:\n code = each_line.select('a')[0].text\n name = each_line.select('a')[1].text\n print(name+\":\"+code)","sub_path":"day03_spider&beautifulsoup/05_stock-start.py","file_name":"05_stock-start.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"81250791","text":"import math\r\nimport keyboard\r\nimport pyautogui\r\nimport cv2\r\nimport mediapipe as mp\r\nimport pygetwindow as gw\r\nimport time\r\n\r\nmp_drawing = mp.solutions.drawing_utils\r\nmp_face_mesh = mp.solutions.face_mesh\r\nmp_hands = mp.solutions.hands\r\n\r\npyautogui.PAUSE = 0\r\ne_time = 0\r\nright_click_time = 0\r\n\r\n\r\ndef is_hand_thumb_up(landmarks):\r\n for landmark in landmarks:\r\n if landmark.y < landmarks[4].y: # y 0 is at top\r\n return False\r\n return True\r\n\r\n\r\ndef get_thumbs_up(data):\r\n landmarks = []\r\n for data_landmarks in data.multi_hand_landmarks:\r\n for idx, landmark in enumerate(data_landmarks.landmark):\r\n landmarks.append(landmark)\r\n\r\n if len(landmarks) == 0:\r\n return False, False\r\n elif len(landmarks) == 21:\r\n return (is_hand_thumb_up(landmarks), False) if landmarks[4].x <= .5 else (False, is_hand_thumb_up(landmarks))\r\n else:\r\n return (is_hand_thumb_up(landmarks[:21]), is_hand_thumb_up(landmarks[21:])) if landmarks[4].x <= 0.5 else (is_hand_thumb_up(landmarks[21:]), is_hand_thumb_up(landmarks[:21]))\r\n\r\n\r\ndef is_fist_clenched(landmarks):\r\n distance_sum = 0.0\r\n for i in range(0, len(landmarks)):\r\n for j in range(0, len(landmarks)):\r\n distance_sum += math.sqrt(math.pow(landmarks[i].x - landmarks[j].x, 2) + math.pow(landmarks[i].y - landmarks[j].y, 2) + math.pow(landmarks[i].z - landmarks[j].z, 2))\r\n avg_distance = distance_sum / len(landmarks) / len(landmarks)\r\n return avg_distance < .1\r\n\r\n\r\ndef get_hands_shown(data): # 0 is base of hand, 4 is end of thumb\r\n landmarks = []\r\n for data_landmarks in data.multi_hand_landmarks:\r\n for idx, landmark in enumerate(data_landmarks.landmark):\r\n landmarks.append(landmark)\r\n\r\n if len(landmarks) == 0:\r\n return 'gone', 'gone'\r\n if len(landmarks) == 42:\r\n return 'clenched' if is_fist_clenched(landmarks[:21]) else 'shown', 'clenched' if is_fist_clenched(landmarks[21:]) else 'shown' # TODO may be wrong\r\n elif landmarks[4].x > landmarks[0].x: # thumb is to the right of hand base (assumes palm is facing camera)\r\n return 'clenched' if is_fist_clenched(landmarks) else 'shown', 'gone'\r\n else:\r\n return 'gone', 'clenched' if is_fist_clenched(landmarks) else 'shown'\r\n\r\n\r\ndef is_mouth_open(data): # 13 is top lip, 14 is bottom lip\r\n landmarks = []\r\n for data_landmarks in data.multi_face_landmarks:\r\n for idx, landmark in enumerate(data_landmarks.landmark):\r\n landmarks.append(landmark)\r\n\r\n distance = math.sqrt(math.pow(landmarks[14].x - landmarks[13].x, 2) + math.pow(landmarks[14].y - landmarks[13].y, 2) + math.pow(landmarks[14].z - landmarks[13].z, 2))\r\n if distance > .01:\r\n if distance > .05:\r\n return 'run'\r\n else:\r\n return 'walk'\r\n else:\r\n return 'stay'\r\n\r\n\r\ndef are_eyebrows_raised(data): # 65 is bottom of left eyebrow, 133 is the rightmost point of the left eye\r\n landmarks = []\r\n for data_landmarks in data.multi_face_landmarks:\r\n for idx, landmark in enumerate(data_landmarks.landmark):\r\n landmarks.append(landmark)\r\n\r\n eye_eyebrow_distance = math.sqrt(math.pow(landmarks[65].x - landmarks[133].x, 2) + math.pow(landmarks[65].y - landmarks[133].y, 2) + math.pow(landmarks[65].z - landmarks[133].z, 2))\r\n return eye_eyebrow_distance > .06\r\n\r\n\r\ndef get_face_rotation(data): # 93 is left, 323 is right, 109 is top, 148 is bottom\r\n landmarks = []\r\n for data_landmarks in data.multi_face_landmarks:\r\n for idx, landmark in enumerate(data_landmarks.landmark):\r\n landmarks.append(landmark)\r\n\r\n left_right_delta_z = landmarks[93].z - landmarks[323].z\r\n top_bottom_delta_z = landmarks[109].z - landmarks[148].z\r\n final_delta_y = landmarks[109].y - landmarks[148].y\r\n\r\n left_right_axis = 'none'\r\n if left_right_delta_z > 0.1:\r\n left_right_axis = 'left'\r\n elif left_right_delta_z < -0.1:\r\n left_right_axis = 'right'\r\n top_bottom_axis = 'none'\r\n if top_bottom_delta_z > 0.1:\r\n top_bottom_axis = 'up'\r\n elif top_bottom_delta_z < -0.05:\r\n top_bottom_axis = 'down'\r\n final_axis = 'none'\r\n if abs(final_delta_y) < 0.25:\r\n if landmarks[109].x < landmarks[148].x:\r\n final_axis = 'left'\r\n else:\r\n final_axis = 'right'\r\n\r\n return left_right_axis, top_bottom_axis, final_axis, left_right_delta_z, top_bottom_delta_z, final_delta_y\r\n\r\n\r\n# For webcam input:\r\ndrawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)\r\ncap = cv2.VideoCapture(0)\r\nwith mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) as face_mesh:\r\n with mp_hands.Hands(min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands:\r\n while cap.isOpened():\r\n success, image = cap.read()\r\n if not success:\r\n print(\"Ignoring empty camera frame.\")\r\n continue\r\n\r\n # Flip the image horizontally for a later selfie-view display, and convert\r\n # the BGR image to RGB.\r\n image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)\r\n # To improve performance, optionally mark the image as not writeable to\r\n # pass by reference.\r\n image.flags.writeable = False\r\n results_face_mesh = face_mesh.process(image)\r\n results_hands = hands.process(image)\r\n\r\n image.flags.writeable = True\r\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\r\n\r\n # Draw the face mesh annotations on the image.\r\n if results_face_mesh.multi_face_landmarks:\r\n for face_landmarks in results_face_mesh.multi_face_landmarks:\r\n mp_drawing.draw_landmarks(image=image, landmark_list=face_landmarks,\r\n connections=mp_face_mesh.FACE_CONNECTIONS,\r\n landmark_drawing_spec=drawing_spec, connection_drawing_spec=drawing_spec)\r\n\r\n # Draw the hand annotations on the image.\r\n if results_hands.multi_hand_landmarks:\r\n for hand_landmarks in results_hands.multi_hand_landmarks:\r\n mp_drawing.draw_landmarks(image, hand_landmarks, mp_hands.HAND_CONNECTIONS)\r\n\r\n cv2.imshow('MediaPipe Face Mesh and Hands', image)\r\n\r\n # Post-processing and input\r\n if results_hands.multi_hand_landmarks is not None:\r\n print(get_thumbs_up(results_hands))\r\n active_window = gw.getActiveWindow()\r\n if active_window is not None and 'Minecraft' in active_window.title:\r\n if results_face_mesh.multi_face_landmarks:\r\n if is_mouth_open(results_face_mesh) == 'walk' or is_mouth_open(results_face_mesh) == 'run':\r\n keyboard.press('w')\r\n else:\r\n keyboard.release('w')\r\n if is_mouth_open(results_face_mesh) == 'run':\r\n keyboard.press('z')\r\n else:\r\n keyboard.release('z')\r\n if are_eyebrows_raised(results_face_mesh):\r\n keyboard.press('space')\r\n else:\r\n keyboard.release('space')\r\n\r\n rotation = get_face_rotation(results_face_mesh)\r\n delta_x = 0\r\n delta_y = 0\r\n if rotation[0] == 'left':\r\n delta_x = -25\r\n elif rotation[0] == 'right':\r\n delta_x = 25\r\n if rotation[1] == 'up':\r\n delta_y = -10\r\n elif rotation[1] == 'down':\r\n delta_y = 10\r\n if rotation[2] == 'left' and time.time() - e_time >= 1:\r\n keyboard.press_and_release('e')\r\n e_time = time.time()\r\n elif rotation[2] == 'right':\r\n pyautogui.scroll(-10)\r\n\r\n delta_x = rotation[3] * -200\r\n delta_y = rotation[4] * -200\r\n\r\n pyautogui.moveRel(delta_x, delta_y)\r\n\r\n if results_hands.multi_hand_landmarks is not None:\r\n hands_shown = get_hands_shown(results_hands)\r\n else:\r\n hands_shown = 'gone', 'gone'\r\n\r\n if hands_shown[0] == 'shown' or hands_shown[0] == 'clenched':\r\n pyautogui.mouseDown(button='left')\r\n else:\r\n pyautogui.mouseUp(button='left')\r\n if (hands_shown[1] == 'shown' or hands_shown[1] == 'clenched') and time.time() - right_click_time >= 1:\r\n pyautogui.click(button='right')\r\n right_click_time = time.time()\r\n\r\n if hands_shown[0] == 'clenched' or hands_shown[1] == 'clenched':\r\n keyboard.press('left_shift')\r\n else:\r\n keyboard.release('left_shift')\r\n\r\n if results_hands.multi_hand_landmarks is not None:\r\n thumbs = get_thumbs_up(results_hands)\r\n else:\r\n thumbs = False, False\r\n\r\n if thumbs[0]:\r\n keyboard.press('s')\r\n else:\r\n keyboard.release('s')\r\n if thumbs[1]:\r\n pyautogui.mouseDown(button='right')\r\n else:\r\n pyautogui.mouseUp(button='right')\r\n\r\n # Exit\r\n if cv2.waitKey(5) & 0xFF == 27:\r\n break\r\ncap.release()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"314699628","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup\n\nwith open('requirements.txt') as fp:\n install_requires = fp.read()\n\nsetup(\n name='compare-jenkins',\n version='0.1',\n url='https://github.com/evilkost/compare_jenkins',\n author='Valentin Gologuzov',\n description='Simple script to compare test results in jenkins.',\n install_requires=install_requires,\n entry_points={\n 'console_scripts': [\n 'jen_compare=jen_compare:main',\n ],\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"141295120","text":"import random\nfrom modules.agent import Agent\nimport matplotlib.pyplot as plt\n\ndef qLearning(\n learning_rate, discount_factor, epsilon, reward_map, state_grid, max_steps, epochs\n):\n\n agent = Agent(learning_rate, discount_factor, reward_map, state_grid, max_steps)\n\n stateDic = {}\n # all_epochs = []\n # epoch_rewards = []\n # every_5 = []\n # mean_every_5 = []\n # epochs_mean = []\n\n for e in range(epochs):\n\n current_state = Agent.choose_start(reward_map, state_grid, max_steps)\n\n # epoch_reward = 0\n # all_epochs.append(e)\n # current_epoch_rewards = []\n\n for _ in range(0, len(reward_map) * len(reward_map[0]) * 2):\n\n action = Agent.epsilon_greedy_policy(epsilon, current_state)\n\n next_state, reward = agent.take_action(current_state, action, stateDic)\n\n # update\n current_state.update_qvalue(\n learning_rate, reward, discount_factor, next_state, action\n )\n\n stateDic[(current_state.posX, current_state.posY, current_state.steps)] = current_state\n\n # epoch_reward += reward\n # current_epoch_rewards.append(reward)\n\n if next_state.is_terminal:\n # epoch_rewards.append(epoch_reward)\n # every_5.append(epoch_reward)\n break\n\n current_state = next_state\n \n # epochs_mean.append(sum(current_epoch_rewards) / len(current_epoch_rewards))\n\n # if(e % 5 == 0):\n # mean_every_5.append(sum(every_5) / len(every_5))\n # every_5 = [] \n\n # plt.style.use(['dark_background']) \n # plt.figure(figsize=(18,12))\n # plt.plot(epochs_mean)\n # plt.xlabel(\"Episodios\")\n # plt.ylabel(\"Reward médio por episodio\", size=10)\n # plt.title(\"Reward médio por episodio 0.9 Lambda\")\n # plt.savefig('epochs_mean.png')\n # plt.show()\n\n\n # plt.style.use(['dark_background'])\n # plt.figure(figsize=(20,10))\n # plt.plot(epoch_rewards)\n # plt.xlabel(\"Episodios\")\n # plt.ylabel(\"Reward axumulativa\", size=10)\n # plt.title(\"Reward acumulativa por episodio\")\n # plt.savefig('reward_cumulative.png')\n # plt.show()\n\n # plt.figure(figsize=(20,10))\n # plt.plot(mean_every_5)\n # plt.xlabel(\"Episodios\")\n # plt.ylabel(\"Média Móvel a cada 5 episodios\", size=10)\n # plt.title(\"Média Móvel\")\n # plt.savefig('mean_every5.png')\n # plt.show()\n\n # plt.figure(figsize=(20,10))\n # plt.plot(epochs_mean)\n # plt.xlabel(\"Episodios\")\n # plt.ylabel(\"Reward médio por episodio\", size=10)\n # plt.title(\"Reward médio por episodio\")\n # plt.savefig('epochs_mean.png')\n # plt.show()\n \n return stateDic\n","sub_path":"modules/qlearning.py","file_name":"qlearning.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"474725560","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\nimport socket\n\nif __name__ == '__main__':\n s = socket.socket()\n host = socket.gethostname()\n port = 12345\n s.connect((host, port))\n print('Linked')\n info = ''\n while info != 'exit':\n print('SCIENCE:' + info)\n send_mes = input()\n s.send(send_mes.encode())\n if send_mes == 'exit':\n break\n info = s.recv(1024).decode()\n s.close()\n","sub_path":"language/python/modules/System/socket/socket_chat/socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"460503888","text":"__author__ = 'nikolai'\n\nimport threading\nimport requests\nimport socket\nimport random\nimport bs4\nfrom cssselect import HTMLTranslator, SelectorError\nfrom bs4 import UnicodeDammit\nimport lxml.html\nfrom urllib.parse import urlparse\n\n\nclass TestThread(threading.Thread):\n def __init__(self, url='http://httpbin.org/get', uparam=None, gsearch={}):\n super().__init__()\n self.url = url\n if not uparam:\n self.uparam = {'uparam': random.randint(0, 100000)}\n else:\n self.uparam = {'uparam': uparam}\n\n self.gsearch = gsearch\n\n def run(self):\n self.google_search()\n\n def google_search(self):\n params = {\n 'q': self.gsearch['query'], # the search term\n 'num': self.gsearch['n_res_page'], # the number of results per page\n 'start': self.gsearch['n_res_page']*self.gsearch['n_page'], # the offset to the search results. page number = (start / num) + 1\n 'pws': '0' # personalization turned off by default\n }\n headers = {\n 'User-Agent': 'Mozilla/5.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Connection': 'close',\n 'DNT': '1'\n }\n print(\"Initiating search with params={}\".format(params))\n r = requests.get('http://www.google.com/search', params=params, headers=headers)\n html = r.text\n # Try to parse the google HTML llresult using lxml\n try:\n doc = UnicodeDammit(html, is_html=True)\n parser = lxml.html.HTMLParser(encoding=doc.declared_html_encoding)\n dom = lxml.html.document_fromstring(html, parser=parser)\n dom.resolve_base_href()\n except Exception as e:\n print('Some error occurred while lxml tried to parse: {}'.format(e.msg))\n return False\n\n try:\n res = dom.xpath(HTMLTranslator().css_to_xpath('div#resultStats'))[0].text_content()\n print(\"Got number of results: `{}` for query {}\".format(res, self.gsearch['query']))\n except Exception as e:\n print(e.msg)\n\n\ndef with_requests(self):\n r = requests.get(self.url, params=self.uparam)\n print(r.text)\n\n\ndef with_socket(self):\n host, path = urlparse(self.url).netloc, urlparse(self.url).path\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n s.connect((host, 80))\n payload = 'GET {}?uparam={} HTTP/1.1\\r\\nHost: {}\\r\\nConnection: close\\r\\n\\r\\n'.format(path, self.uparam.get(\n 'uparam'), host)\n #print(\"Sending: {}\".format(payload))\n s.send(payload.encode())\n except socket.error as se:\n print(se.args)\n\n response = s.recv(4096)\n print(response)\n\n\nif __name__ == '__main__':\n searches = ['casablance', 'travel']\n configs = [{'query': query, 'n_res_page': 10, 'n_page': 2} for query in searches]\n threads = [TestThread(gsearch=config) for config in configs]\n for t in threads:\n t.start()\n\n for t in threads:\n t.join()\n","sub_path":"tests/threadtests.py","file_name":"threadtests.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"222781671","text":"from django.conf.urls import url\nfrom .views import index, upload, options, results, join_data\n\napp_name = 'combiner'\n\nurlpatterns = [\n url(r'^$', index, name='index'),\n url(r'^upload/$', upload, name='upload'),\n url(r'^options/$', options, name='options'),\n url(r'^results/$', results, name='results'),\n url(r'^join/$', join_data, name='join')\n]\n","sub_path":"combiner/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"498656504","text":"import pandas as pd\n\n################################################\n\n# Merging\n\n##############################################\n\n\n#appending\n\nfermions = pd.read_csv('~/data/fermions.csv')\nbosons = pd.read_csv('~/data/bosons.csv')\n# print(fermions.append(bosons))\n\n\n#############################################\n\n\n# Concat\n\n# buckets = [fermions, bosons]\n# # print(pd.concat(buckets, axis='columns'))\n#\n# # Concatenate dataframes\n# bucket = pd.concat(buckets,\n# keys=['fermions','bosons'], axis=0)\n#\n# print(bucket)\n#\n# # # Print bucket.info()\n# print(bucket.info())\n\n\n###########################################\n\n\n# Joins\n\njoinedBucket = [fermions,bosons]\n\ninnerjoinedBucket = pd.concat(joinedBucket,\n keys=['type', 'charge'],axis=1, join='outer')\nouterjoinedBucket = pd.concat(joinedBucket,\n keys=['type', 'charge'],axis=1, join='outer')\n\n\n# print(innerjoinedBucket)\n# print(outerjoinedBucket)\n\n###############################################\n\n\nmergedBucket = pd.merge(fermions, bosons, on='type')\nprint(mergedBucket)","sub_path":"blocks/dataSci/dataframes/mushing.py","file_name":"mushing.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"1811544","text":"import pandas as pd\nimport os\nimport sys\nimport numpy as np\nimport gzip\nimport flatdict\nimport json\nimport operator\nfrom itertools import product\nfrom fbprophet import Prophet\nfrom functools import reduce\n\nfrom Utilities import sys_utils as su\nfrom Utilities import time_utils as tu\n# from capacity_planning.utilities import TempUtils\n\n\ndef _get_bin_vals(df, t_col, bin_cnt, fbin, qfunc):\n \"\"\"\n returns a DF with bin values based on the t_col bins, i.e t_col defines the aggregation bins for the other columns\n supports duplicated values\n :param df: input DF\n :param t_col: column to build the initial bin breakdown from\n :param bin_cnt: number of bins to generate\n :param fbin: binning method: count(qcut) or size(cut)\n :param qfunc: function to use to compute the bin value: np.median, np.mean, ... in numerical columns. In discrete columns, the mean is always used.\n :return: DF with same numerical cols as df and bin_cnt rows. The non-numerical cols are split into dummy cols.\n \"\"\"\n def nbin_agg(zf, n_func, cols):\n fo = zf[cols].apply(n_func, axis=0)\n fo['_bin_prob'] = len(zf) # normalized later\n return fo\n\n if len(df) == 0 or df is None:\n return None\n\n qidx = '_' + t_col + '_idx' # column with the t_col bin number\n q_df = None\n s_df = df.copy()\n dropped_df = list()\n while q_df is None and bin_cnt >= 2:\n try:\n q_df = pd.concat([s_df, fbin(s_df[t_col], int(bin_cnt), labels=range(int(bin_cnt)))], axis=1, sort=True) # add bin number column\n except ValueError: # repeat values: fix and try again\n vc = s_df[t_col].value_counts()\n cm_val, cm_cnt = vc.idxmax(), vc.max() # most common repeat value and repeat count\n if cm_cnt <= 1: # this should not happen!\n su.my_su.my_print('invalid max count for ' + t_col + '. Should be > 1')\n su.my_su.my_print(vc.head())\n return None\n mask = s_df[t_col] == cm_val\n if cm_cnt >= len(s_df) / bin_cnt: # repeat value spans more than one bin\n bin_cnt *= float(len(s_df) - cm_cnt) / len(s_df) # adjust qtile to keep proportions\n dropped_df.append(s_df[mask].copy()) # save the portion dropped from s_df to bin later\n s_df = s_df[~mask].copy() # new DF for fbin\n else: # add noise to the repeat value to drop repeats\n idx = np.argmin(np.abs(s_df[t_col][~mask].values - cm_val)) # closest value to cm_val, not equal to cm_val\n z = s_df[t_col][~mask].values[idx]\n std = min(np.abs(cm_val - z), np.abs(cm_val)) / 1000.0\n v_noise = np.where(mask, np.random.normal(0, std, len(s_df)), np.zeros(len(s_df)))\n s_df[t_col] += v_noise # t_col with noise on most common value to remove repeats\n if q_df is not None and len(s_df) >= bin_cnt:\n break\n\n if q_df is not None and len(s_df) >= bin_cnt:\n q_df.columns = list(s_df.columns) + [qidx]\n if len(dropped_df) > 0: # bin repeated values\n su.my_print('_get_bin_vals:: ' + t_col + ' has duplicated values')\n bin_val = q_df[qidx].max() # highest bin created\n for idx in range(len(dropped_df)): # add bin number value to the dropped repeat values\n dropped_df[idx][qidx] = bin_val + 1 + idx\n dropped_df.append(q_df) # add DF with bins\n q_df = pd.concat(dropped_df, axis=0, sort=True) # DF with all bins, including repeated values\n\n # compute the value for each bin\n q_df[qidx] = q_df[qidx].astype(np.int64) # not a category\n n_cols = [c for c in q_df.columns if not(str(q_df.dtypes[c]) in ['object', 'category'])] # only numerical cols\n n_df = q_df.groupby(qidx).apply(nbin_agg, n_func=qfunc, cols=n_cols).reset_index(drop=True) # values in each bin for numerical cols\n n_df['_bin_prob'] /= n_df['_bin_prob'].sum() # fraction of samples (rows) in each bin\n d_cols = list(set(q_df.columns) - set(n_cols)) # discrete columns\n d_df_list = [pd.get_dummies(q_df[d], prefix=d, prefix_sep='::') for d in d_cols] # list of dummy DFs\n if len(d_df_list) > 0: # compute value for discrete column: always use mean\n d_df = pd.concat(d_df_list, axis=1, sort=True)\n d_df[qidx] = q_df[qidx]\n c_df = d_df.groupby(qidx).apply(lambda z_df: z_df.apply(np.mean, axis=0)).reset_index(drop=True) # value in each bin for non-numerical cols (prob)\n m_df = n_df.merge(c_df, on=qidx, how='outer')\n else:\n m_df = n_df.drop(qidx, axis=1)\n return m_df\n else:\n su.my_print('_get_bin_vals failed')\n return None\n\n\ndef _thres_bins(bin_df, thres):\n \"\"\"\n non-numerical cols contain the prob that the cat happens in a bin\n this function allows to remove non-numerical cols from a bin DF with very low prob to get rid of categories with low probabilities\n :param bin_df: output of _get_bin_vals\n :param thres: removal threshold: cols with max less than thres get dropped\n :return: DF with bin values for numerical and (thresholded) non-numerical cols\n \"\"\"\n if bin_df is None:\n return None\n c_cols = [c for c in bin_df.columns if '::' in c] # non-numerical columns\n n_cols = [c for c in bin_df.columns if not('::' in c)] # numerical columns\n c_w = bin_df[c_cols].copy()\n n_w = bin_df[n_cols].copy()\n y = c_w.apply(lambda x: x if x.max() > thres else [np.nan] * len(x), axis=0) # remove cat cols with very low values\n y.dropna(inplace=True, axis=1)\n col_dict = dict()\n for col in y.columns:\n n = col.split('::')[0]\n if n not in col_dict.keys():\n col_dict[n] = list()\n col_dict[n].append(col)\n for c, c_list in col_dict.items():\n y[c + '::other'] = 1.0 - c_w[c_list].sum(axis=1) # lump all low prob cats into the 'other' cat\n return pd.concat([n_w, y], axis=1, sort=True)\n\n\ndef get_sz_bins(df, t_col, bin_cnt, qfunc=np.nanmedian, thres=None):\n \"\"\"\n returns a DF with bin_cnt bins of equal size based on t_col, i.e t_col defines the aggregation bins for the other columns\n supports with duplicated values\n all bins are the same size in t_col\n for discrete columns, return the avg number of 1's in the bin\n :param df: input DF\n :param t_col: column to build the initial bin breakdown from\n :param bin_cnt: number of hist bins to generate\n :param qfunc: function to use to compute the bin value: np.median, np.mean, ...\n :param thres: thres to drop non-numerical cols, None or between 0 and 1.\n :return: DF with same numerical cols as df and bin_cnt rows\n \"\"\"\n b_df = _get_bin_vals(df, t_col, bin_cnt, pd.cut, qfunc)\n if thres is None:\n return b_df\n else:\n return _thres_bins(b_df, thres)\n\n\ndef get_cnt_bins(df, t_col, bin_cnt, qfunc=np.nanmedian, thres=None):\n \"\"\"\n returns a DF with bins based on the t_col quantiles, i.e t_col defines the aggregation bins for the other columns\n supports with duplicated values\n all bins have the same number of points\n for discrete columns, return the avg number of 1's in the bin\n :param df: input DF\n :param t_col: column to build the initial bin breakdown from\n :param bin_cnt: number of bins to generate\n :param qfunc: function to use to compute the bin value: np.median, np.mean, ...\n :param thres: thres to drop non-numerical cols, None or between 0 and 1.\n :return: DF with same numerical cols as df and bin_cnt rows\n \"\"\"\n b_df = _get_bin_vals(df, t_col, bin_cnt, pd.qcut, qfunc)\n if thres is None:\n return b_df\n else:\n return _thres_bins(b_df, thres)\n\n\ndef df2json(df, f_out):\n \"\"\"\n NOTE: only works if columns contain json-like elements: numbers, strings, lists, dict. Does not work for sets.\n write a df into a by-line json file\n df: input DF\n f_out: output file\n \"\"\"\n f = gzip.open(f_out, 'wb') if f_out[-3:] == '.gz' else open(f_out, 'wb')\n f.write('\\n'.join(r[1].to_json(orient='index') for r in df.iterrows()))\n f.close()\n\n\ndef df2json_gen(df, f_out):\n \"\"\"\n NOTE: only works if columns contain json-like elements: numbers, strings, lists, dict. Does not work for sets.\n Generator version: slower but scales to larger DF's\n write a df into a by-line json file\n df: input DF\n f_out: output file\n \"\"\"\n f = gzip.open(f_out, 'wb') if f_out[-3:] == '.gz' else open(f_out, 'wb')\n f.writelines((r[1].to_json(orient='index') + '\\n' for r in df.iterrows()))\n f.close()\n\n\ndef df_to_json_lines(df, f_out):\n return df2json(df, f_out)\n\n\ndef json_line_to_df(fname):\n \"\"\"\n reads json line file and returns DF\n :param fname: file in json line format\n :return: df\n \"\"\"\n f = gzip.open(fname, 'r') if fname[-3:] == '.gz' else open(fname, 'r')\n lines = f.read().splitlines()\n f.close()\n data_list = [json.loads(line) for line in lines]\n return pd.DataFrame(data_list)\n\n\ndef df_inspect(df, df_name, rows=5, pid=False):\n \"\"\"\n Inspect a dataframe\n pid su.my_prints the pid running\n \"\"\"\n rows = max(rows, len(df.columns))\n pd.set_option('display.max_rows', rows)\n pd.set_option('display.max_columns', 2 + len(df.columns))\n w = max(20 * len(df.columns), 250)\n pd.set_option('display.width', w)\n su.my_print('------------ ' + df_name + ' ------------')\n if pid == True:\n su.my_print('pid: ' + str(os.getpid()))\n su.my_print('length: ' + str(len(df)))\n su.my_print('size: ' + str(df_sz_MBs(df)) + 'MB')\n su.my_print(df.head(rows))\n su.my_print(df.tail(rows))\n t_df = df.dtypes.reset_index()\n t_df.columns = ['cols', 'type']\n v = {}\n for i in t_df.index:\n c = t_df.iloc[i, 'cols']\n t = t_df.iloc[i, 'type']\n v[c] = [len(df[c].unique())] if t == np.object else [np.nan]\n v_df = pd.DataFrame(v).transpose()\n desc = df.describe().transpose()\n smry = pd.concat([df.isnull().sum(), df.dtypes, v_df, desc], axis=1, sort=True)\n smry.columns = ['nulls', 'dtypes', 'uniques'] + list(desc.columns)\n pd.set_option('display.max_columns', 2 + len(smry.columns))\n su.my_print(smry)\n su.my_print('------------------------------------')\n\n\ndef df_sz_MBs(df):\n return int((df.values.nbytes + df.index.nbytes + df.columns.nbytes) / 1048576.0)\n\n\ndef drop_cols(df):\n \"\"\"\n drop single valued columns in a df or cols with NAs and a single value\n :param df: pd data frame\n :return: df with single value cols dropped\n unique() includes NA's\n value_counts().sum() excludes NAs\n len() - value_counts().sum() = number of NAs\n \"\"\"\n z = df.dropna(axis=1, how='all')\n drop_list = []\n z_len = len(z)\n for c in z.columns:\n if len(z[c].unique()) == 1:\n drop_list.append(c)\n elif len(z[c].unique()) == 2 and z_len - z[c].value_counts().sum() > 0: # NAs and one on-NA value\n drop_list.append(c)\n else:\n pass\n if len(drop_list) > 0:\n return z.drop(drop_list, axis=1)\n else:\n return z\n\n\ndef list_gb(df, gb_cols, from_col):\n \"\"\"\n Take df and groupby gb_cols\n then list all the elements in column from_col in the column new_col as a list\n :return: Series indexed by gb_cols with lists\n \"\"\"\n return df.groupby(gb_cols)[from_col].apply(lambda x: x.tolist())\n\n\ndef col_list_gb(df, gb_cols, col_list):\n \"\"\"\n a wrapper for list_gb\n col_list: a list of columns\n :return: a DF indexed by gb_cols with the values in each col in col list turned into a list\n \"\"\"\n df_list = [list_gb(df, gb_cols, c) for c in col_list]\n return pd.concat(df_list, axis=1, sort=True)\n\n\ndef nested_dict_to_df(a_dict, col_names, key_depth=None):\n \"\"\"\n builds a df from a nested dict. Requires that all key paths be equally deep\n use pandas to_dict when 3 columns (keys levels) are left. otherwise, go recursive\n :param a_dict: dict to turn to a DF\n :param col_names: col names for the output DF\n :param key_depth: key depth entries to return. If None take the most common. Other entries are su.my_printed and dropped.\n :return: a DF with columns given by col_names and rows given by either the keys or the values in the input dict\n Example\n big_dict = {'a': {\n 'p1': {'d1': {'00': 1, '01': 2}, 'd2': {'00': 2, '02': 3}},\n 'p2': {'d2': {'04': 4, '01': 2}, 'd3': {'00': 2, '01': 3}}\n },\n 'b': {\n 'p1': {'d1': {'00': 1, '01': 2}, 'd2': {'00': 2, '02': 3}},\n 'p3': {'d4': {'00': 1, '01': 2}, 'd3': {'00': 2, '01': 3}},\n 'p2': {'d1': {'00': 2, '01': 2}},\n 'p3': {'d1': {'05': None}}\n },\n 'c': {\n 'p1': {'d3': 2, 'd2': {'01': 5}},\n 'p2': 4,\n 'p4': 'd1'\n }\n }\n Example:\n nested_dict_to_df(big_dict, ['col', 'pod', 'date', 'hr', 'val'])\n su.my_prints:\n the following entries are incomplete and will be dropped from the output\n c:p4:d1\n c:p1:d3:2\n c:p2:4\n and returns:\n col date hr pod val\n 0 b d2 00 p1 2.0\n 1 a d3 00 p2 2.0\n 2 a d3 01 p2 3.0\n 3 b d1 00 p1 1.0\n 4 b d1 01 p2 2.0\n 5 b d2 02 p1 3.0\n 6 a d2 00 p1 2.0\n 7 a d2 02 p1 3.0\n 8 c d2 01 p1 5.0\n 9 b d1 05 p3 NaN\n 10 a d2 04 p2 4.0\n 11 a d2 01 p2 2.0\n 12 b d1 00 p2 2.0\n 13 a d1 01 p1 2.0\n 14 a d1 00 p1 1.0\n 15 b d1 01 p1 2.0\n \"\"\"\n delim = '>>@:::#-->' # use an odd delimiter to avoid split problems\n flat_dict = flatdict.FlatDict(a_dict, delimiter=delim)\n\n if key_depth is None: # find the most common key depth\n k_lists = [k.split(delim) for k in flat_dict.keys()]\n d_lens = dict() # {key_len: count}\n for l in k_lists:\n k_len = len(l)\n if k_len not in d_lens:\n d_lens[k_len] = 0\n d_lens[k_len] += 1\n max_k_len = max(d_lens.iteritems(), key=operator.itemgetter(1))[0]\n else:\n max_k_len = key_depth # key depth to output\n\n # check that col_names length match key depth, otherwise error because we cannot name all the DF columns we need or have too many columns\n if len(col_names) != 1 + max_k_len:\n su.my_print('invalid col_names: ' + str(col_names) + '. There should be ' + str(max_k_len) + ' columns')\n raise RuntimeError('failure')\n\n # keep only the path depth we want and drop the others\n # su.my_print what is dropped\n flat_drop = {k: v for k, v in flat_dict.iteritems() if len(k.split(delim)) != max_k_len}\n if len(flat_drop) != 0:\n su.my_print('the following entries are incomplete and will be dropped from the output')\n for k, v in flat_drop.iteritems():\n k_col = k.replace(delim, ':')\n su.my_print('\\t' + str(k_col) + ':' + str(v))\n\n # recover the dict to make into a DF\n flat_keep = {k: v for k, v in flat_dict.iteritems() if len(k.split(delim)) == max_k_len}\n t_list = [tuple(k.split(delim) + [v]) for k, v in flat_keep.iteritems()]\n dict_list = [dict(zip(col_names, row)) for row in t_list]\n return pd.DataFrame.from_dict(dict_list)\n\n\ndef nested_update(a_dict, old_val, new_val):\n \"\"\"\n update all instances of old_val by new_val at any nesting level\n :param a_dict: \n :param old_val: \n :param new_val: \n :return: \n \"\"\"\n def is_mutable(val): # true if val is mutable\n if val is None:\n return False\n\n immutables = [str, int, bool, float, tuple]\n for t in immutables:\n if isinstance(val, t):\n return False\n return True\n\n if is_mutable(old_val):\n su.my_print('nested update: cannot update mutable value: ' + str(old_val))\n return\n\n for k, v in a_dict.iteritems():\n if isinstance(v, dict):\n nested_update(v, old_val, new_val)\n else:\n if old_val is None:\n if a_dict[k] is None:\n a_dict[k] = new_val\n else:\n if a_dict[k] == old_val:\n a_dict[k] = new_val\n\n\ndef w_mean(df, m_col, w_col):\n \"\"\"\n weighted average of m_col using w_col as weights\n :param df:\n :param m_col:\n :param w_col:\n :return: the weighted average\n \"\"\"\n return np.average(df[m_col].values, weights=df[w_col].values)\n\n\ndef trim_df(a_df, rge=1.5, qtiles=[0.25, 0.75], cols=None, upr=True, lwr=True, msg=None):\n \"\"\"\n basic outlier IQR trim of a DF.\n Drop any row with any of its col in cols outside the interval [q1 - rge * iqr, q3 + rge * iqr]\n :param a_df: DF to trim\n :param cols: list of cols or str (single col) to use in the trimming. If None use all columns\n :param rge: iqr factor\n :param upr: if True drop upper (right) outliers\n :param lwr: if True drop lower (left) outliers\n :param qtiles: quantiles for the iqr range\n :param msg: report on data dropped with msg (eg cols, df, context) if not None\n :return: returns trimmed DF\n \"\"\"\n if len(a_df) > 0:\n if isinstance(a_df, type(pd.DataFrame())):\n if isinstance(cols, str):\n cols = [cols]\n a_df_cols = list(a_df.columns)\n else: # series\n cols, a_df_cols = None, None\n t_df = a_df.copy() if cols is None else a_df[cols].copy()\n q_df = t_df.quantile(qtiles)\n q_lwr, q_upr = qtiles\n if q_lwr > q_upr:\n q_upr, q_lwr = q_lwr, q_upr\n iqr = q_df.diff(1).dropna().reset_index(drop=True)\n if len(q_df) == 2 and len(iqr) == 1:\n lwr_thres = q_df.loc[q_lwr] - rge * iqr.iloc[0]\n upr_thres = q_df.loc[q_upr] + rge * iqr.iloc[0]\n\n # if bool_df == True, drop the row\n if upr == True and lwr == True:\n bool_df = (t_df < lwr_thres) | (t_df > upr_thres)\n elif upr == True and lwr == False:\n bool_df = (t_df > upr_thres)\n elif upr == False and lwr == True:\n bool_df = (t_df < lwr_thres)\n else: # ignore the trim\n bool_df = pd.DataFrame([False] * len(a_df))\n\n if isinstance(a_df, type(pd.DataFrame())):\n z_bool = bool_df.apply(lambda x: any(x), axis=1) # true if any row value are outside the interval [q1-rge * iqr, q3 + rge * iqr]\n z_out = a_df[~z_bool][a_df_cols].copy()\n else: # series\n z_out = a_df[~bool_df].copy()\n\n if msg is not None:\n diff = len(a_df) - len(z_out)\n if diff != 0:\n su.my_print(str(msg) + ':: dropped ' + str(diff) + ' outliers out of ' + str(len(a_df)) + ' points')\n return z_out\n else:\n return None\n else:\n return None\n\n\ndef iqr_filter(r_df, coef=3.0, q_lwr=0.25, q_upr=0.75):\n q_upr = r_df.quantile(q_upr)\n q_lwr = r_df.quantile(q_lwr)\n iqr = q_upr - q_lwr\n return q_upr + coef * iqr, q_lwr - coef * iqr #\n\n\ndef median_filter(r_df, coef=3.0):\n m, stdev = r_df.median(), r_df.std()\n return m + coef * stdev, m - coef * stdev #\n\n\ndef ts_outliers(y_df, t_col, y_col, coef=3.0, verbose=False, replace=False, ignore_dates=None, lbl_dict=None, r_val=1.0): # set outliers to NaN\n \"\"\"\n Find outliers in y_col which is a time series using IQR method or median filter.\n Assumes y_col >= 0\n :param df: DF with y_col (data) and t_col\n :param t_col: time column name.\n :param y_col: data column\n :param coef: IQR coefficient\n :param verbose: verbose\n :param lbl_dict: into dict (context)\n :param r_val: r_val = 1 replaces by the yhat_upr/yhat_lwr value, r_val=0 replaces by yhat. In between, a weighted avg\n :param replace: if True replace the outlier value(s) by the Prophet in-sample forecast. If false, set outlier to nan\n :param ignore_dates: do not replace outliers for dates in this list\n :return: DF with either nan in outliers or fit outliers\n \"\"\"\n if len(y_df) <= 10:\n su.my_print(str(os.getpid()) + ' WARNING: not enough points for outlier detection: ' + str(len(y_df)))\n return y_df, np.nan, None\n\n # look for outliers\n _y_df = y_df.copy()\n _y_df.rename(columns={t_col: 'ds', y_col: 'y'}, inplace=True)\n _y_df.reset_index(inplace=True, drop=True)\n try:\n if verbose:\n m = Prophet(changepoint_range=0.9)\n m.fit(_y_df[['ds', 'y']])\n else:\n with su.suppress_stdout_stderr():\n m = Prophet(changepoint_range=0.9)\n m.fit(_y_df[['ds', 'y']])\n except ValueError:\n su.my_print(str(os.getpid()) + ' ERROR: prophet err: returning original DF. Data len: ' + str(len(_y_df)) + ' Saving to ' + '~/my_tmp/_prophet_df.par')\n _y_df.rename(columns={'ds': t_col, 'y': y_col}, inplace=True)\n save_df(_y_df, '~/my_tmp/_y_df')\n return None, np.nan, None\n\n future = m.make_future_dataframe(periods=0)\n forecast = m.predict(future)\n y_vals = _y_df['y'].copy() # they will be filtered later\n _y_df['yhat'] = forecast['yhat']\n _y_df['resi'] = _y_df['y'] - _y_df['yhat']\n\n # use iqr or median filter\n # using Prophet's interval_width does not work as it is a quantile,\n # and about the same number of outliers is always found on avg ~ len * (1 - interval_width)\n upr, lwr = iqr_filter(_y_df['resi'], coef=coef, q_lwr=0.25, q_upr=0.75) # iqr\n # upr, lwr = median_filter(_y_df['resi'], coef=coef) # median filter\n\n _y_df['yhat_upr'] = forecast['yhat'] + upr\n _y_df['yhat_lwr'] = forecast['yhat'] + lwr\n _y_df.rename(columns={'ds': t_col, 'y': y_col}, inplace=True)\n\n # no outlier if yhat_lwr <= y <= yhat_upr\n _y_df['is_outlier'] = (y_vals > _y_df['yhat_upr']) | (y_vals < _y_df['yhat_lwr'])\n n_outliers = _y_df['is_outlier'].sum()\n err = np.round(100 * n_outliers / len(_y_df), 0)\n if ignore_dates is None:\n ignore_dates = list()\n\n off = None\n if n_outliers > 0:\n if verbose is True:\n save_df(_y_df, '~/my_tmp/outliers_DF_' + str(y_col) + '_' + str(lbl_dict)) # no outlier processing yet\n su.my_print(str(os.getpid()) + ' WARNING::column ' + y_col + ' has ' + str(len(_y_df)) +\n ' rows and ' + str(n_outliers) + ' outliers (' + str(err) + '%) for context ' + str(lbl_dict))\n b_dates = ~_y_df[t_col].isin(ignore_dates) # boolean dates adjuster: when true, an outlier on that date can be adjusted\n b_adj = _y_df['is_outlier'] & b_dates # boolean outlier adjuster: if true it is an outlier we can adjust\n if replace is False:\n _y_df[y_col] = y_vals * (1 - b_adj) + np.nan * b_adj\n else:\n _y_df[y_col] = y_vals * (1 - b_adj) + \\\n (r_val * _y_df['yhat_upr'] + (1.0 - r_val) * _y_df['yhat']) * ((y_vals > _y_df['yhat_upr']) & b_dates) + \\\n (r_val * _y_df['yhat_lwr'] + (1.0 - r_val) * _y_df['yhat']) * ((y_vals < _y_df['yhat_lwr']) & b_dates)\n\n if verbose is True: # print outlier info: note that actuals are already filtered wheras the original value is in the outlier column\n off = _y_df[b_adj].copy()\n su.my_print('*************** outlier detail ************')\n print(off)\n _y_df.drop(['resi', 'yhat', 'yhat_upr', 'yhat_lwr', 'is_outlier'], axis=1, inplace=True)\n return _y_df, err, off\n\n\ndef df_hist(in_df, v_col, w_col, g_col=None, v_col_vals=None):\n \"\"\"\n get the v_col histogram of the DF with weights in w_col, ie p(v_col=v) = sum(x[r_col]: x[vcol]=v)/sum(x[r_col])\n assumes w_col is numeric and v_col has a finite number of values\n :param in_df: input DF\n :param w_col: col of float values (weights)\n :param v_col: col with the values to get the histogram of\n :param g_col: pre-pivot grouping columns wrt v_col to group duplicates in v_vol\n :param v_col_vals: subset of the v_col values\n :return: a DF with cols in the values of v_col and a totals columns for the total weight\n \"\"\"\n b_df = in_df.copy() if v_col_vals is None else in_df[in_df[v_col].isin(v_col_vals)].copy()\n p_df = b_df if g_col is None else b_df.groupby([g_col, v_col]).agg({w_col: np.sum}).reset_index() # aggregate duplicates before pivot\n cnts_df = p_df.pivot(index=g_col, columns=v_col, values=w_col)\n cnts_df.fillna(0, inplace=True)\n cnts_df.columns = [v_col + ':' + c for c in cnts_df.columns]\n s = cnts_df.sum(axis=1)\n hist_df = cnts_df.div(s, axis=0)\n hist_df[w_col] = s\n hist_df.reset_index(inplace=True)\n return hist_df\n\n\n# def multi_merge(df_list, on, how):\n# \"\"\"\n# merge the list of DFs according to m_cols (\n# :param df_list: list of DFs\n# :param on: list of columns. Must be in all DFs\n# :param how: inner, outer. Note with left and right, the order of df1 and df2 makes a difference in the lambda below\n# :return:\n# \"\"\"\n# df_list_ = [f for f in df_list if f is not None]\n# return ft.reduce(lambda df1, df2: df1.merge(df2, on=on, how=how), df_list_) if len(df_list_) > 0 else None\n\n\ndef get_data(fpath, usecols=None, date_format=None, date_cols=list(), str_cols=list(), num_cols=list(), b_cols=list(), cat_cols=list(), other_cols=list()):\n # reads from csv files\n # manages NaN (NA vs. North America)\n # formats cols (time, str, float)\n def to_bool(pd_series):\n # only handles NaNs and values 0/1 or True/False\n is_null = pd_series.isnull()\n yn = pd_series[is_null]\n nn = pd_series[~is_null]\n d = {'False': False, 'True': True, '0': False, '1': True, 0: False, 1: False, True: True, False: False}\n for v in nn.unique():\n if v not in list(d.keys()):\n su.my_print(str(v) + ' :::::::WARNING:::::: to_bool: invalid values for ' + str(pd_series.name) + ': ' + str(nn.unique()))\n return pd_series\n s = pd.concat([yn, nn.map(d)], axis=0, sort=True)\n return s.sort_index()\n\n df = pd.read_csv(fpath,\n usecols=usecols,\n dtype=str,\n keep_default_na=False,\n na_values=['', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',\n '#1.#IND', '1.#QNAN', 'N/A', 'NULL', 'NaN', 'n/a', 'nan', 'null', 'undefined', 'unknown'])\n # date cols\n if date_format is not None:\n date_list = [pd.DataFrame(pd.to_datetime(df[c].values, format=date_format), columns=[c]) for c in date_cols]\n else:\n try:\n date_list = [pd.DataFrame(pd.to_datetime(df[c].values, unit='s'), columns=[c]) for c in date_cols]\n except ValueError:\n date_list = [pd.DataFrame(pd.to_datetime(df[c].values, infer_datetime_format=True, errors='coerce'), columns=[c]) for c in date_cols]\n date_df = pd.concat(date_list, axis=1, sort=True) if len(date_list) > 0 else pd.DataFrame()\n for c in date_cols:\n n_len = len(date_df[date_df[c].isnull()])\n if n_len > 0:\n su.my_print('WARNING: invalid dates in ' + str(c) + ': ' + str(n_len))\n\n # str cols\n sdf = df[str_cols].fillna('nan')\n str_df = sdf[str_cols].astype(str) if len(str_cols) > 0 else pd.DataFrame()\n\n # cat cols\n cdf = df[cat_cols].fillna('nan')\n cat_df = cdf[cat_cols].astype(str) if len(cat_cols) > 0 else pd.DataFrame()\n\n # bool cols\n b_list = [pd.DataFrame(to_bool(df[c])) for c in b_cols]\n bool_df = pd.concat(b_list, axis=1, sort=True) if len(b_list) > 0 else pd.DataFrame()\n\n # num cols\n n_list = [pd.DataFrame(pd.to_numeric(df[c].values, errors='coerce'), columns=[c]) for c in num_cols]\n num_df = pd.concat(n_list, axis=1, sort=True) if len(n_list) > 0 else pd.DataFrame()\n if other_cols is None: # keep all the other cols\n other_cols = list(set(df.columns) - set(date_cols) - set(str_cols) - set(cat_cols) - set(num_cols) - set(b_cols))\n return pd.concat([df[other_cols], date_df, str_df, cat_df, num_df, bool_df], axis=1, sort=True)\n\n\ndef clean_cols(df, col_list, c_vals_path, check_new=True, do_nan=False, rename=False):\n # clean categorical cols\n # col_list: cols to fix\n # cat_cols: cols to check for new\n # c_vals contains translation dicts\n # from capacity_planning.utilities import col_values as c_vals\n\n def flip_dict(d, cols, c_map):\n # d[col] = {'good_val': [...bad_vals...], ...}\n new_dict = dict()\n for c in cols:\n nc = c_map.get(c, c) # mapped col name\n new_dict[c] = {kv: kk for kk, vv in d[nc].items() for kv in vv}\n return new_dict\n\n # find new invalid values and replace bad values with good ones\n # with open(os.path.expanduser(c_vals_path), 'r') as fp:\n su.my_print('pid: ' + str(os.getpid()) + ' p_ut:clean_cols: values check for cols ' + str(col_list))\n with open(os.path.expanduser(c_vals_path), 'r') as fp:\n c_vals = json.load(fp)\n\n v_dict = c_vals['col_values']\n m_dict = c_vals['col_maps']\n\n if rename:\n r_dict = dict()\n c_cols = dict()\n for c in col_list:\n c_cols[c] = [k for k, v in m_dict.items() if v == c and k in df.columns] if c in m_dict.values() else list()\n if len(c_cols[c]) == 0:\n su.my_print('ERROR: column ' + str(c) + ' has no mapping in m_dict: ' + str(m_dict) + ' and DF has columns ' + str(df.columns))\n sys.exit()\n elif len(c_cols[c]) > 1:\n su.my_print('ERROR: column ' + str(c) + ' has too many matches in m_dict: ' + str(m_dict) + ' and DF has columns ' + str(df.columns))\n sys.exit()\n else:\n r_dict[c_cols[c][0]] = c\n df.rename(columns=r_dict, inplace=True)\n\n my_cols = list()\n for c in col_list:\n if c in m_dict.keys():\n my_cols.append(c)\n else:\n su.my_print('pid: ' + str(os.getpid()) + ' WARNING: clean_cols:: no mapping for column ' + str(c))\n f_dict = flip_dict(v_dict, my_cols, m_dict)\n _ = [df[c].update(df[c].map(f_dict[c])) for c in my_cols] # in place replacement\n if do_nan is True:\n df.replace(['_drop', 'nan', 'other'], np.nan, inplace=True)\n\n # find new invalid values in cat cols\n new_ones = dict()\n if check_new is True:\n su.my_print('pid: ' + str(os.getpid()) + ' p_ut:clean_cols: starting new invalid values check for cols ' + str(my_cols))\n for c in my_cols:\n uniques = df[c].unique()\n new_vals = list(set(uniques) - set(v_dict[m_dict.get(c, c)]))\n if len(new_vals) > 0:\n new_ones[c] = new_vals\n # su.my_print('pid: ' + str(os.getpid()) + ' p_ut:clean_cols::col: ' + str(c) + ' has new invalid values: ' + str(new_vals))\n return new_ones\n\n\ndef plot_by_year(df_in, cols, tcol, base_year=None, time_scale='W'):\n # cols: columns to plot\n # tcol: time column\n # returns a DF based on df_in ready to plot cols aligned by weekday and week for each year\n # the values are aligned by week and day of the week using the iso calendar\n # base year is used to index the resulting data. If None is given, take the largest or the one with a whole year of data.\n # If there is no complete year, sets values to 0\n # base year is only for plotting purposes. The dates and values in base year may not match the exact date of the year.\n # since 365 and 366 are not multiples of 7, there will be some NAs ate the beginning or end of some years.\n\n df = df_in[[tcol] + cols].copy()\n df.set_index(tcol, inplace=True)\n i_name = df.index.name\n s = pd.Series(df.index)\n iso = s.apply(lambda x: x.isocalendar())\n df['iso_nbr'] = iso.apply(lambda x: x[1]).values if time_scale == 'W' else iso.apply(lambda x: x[2]).values\n\n if len(df) != len(df.index.unique()):\n su.my_print('plot by year has duplicated dates')\n return None\n\n # set base year and check that data is daily (at least during the base year)\n years = list(df.index.year.unique())\n if base_year is None:\n base_year = min(years)\n\n # collect cols to plot by year\n g_list = list()\n for y in years:\n g = df[df.index.year == y].copy()\n g.index.name = y\n g.columns = [str(y) + '_' + c if c in cols else c for c in df.columns]\n g.reset_index(inplace=True)\n g.drop(y, axis=1, inplace=True)\n g_list.append(g)\n mf = reduce(lambda x, y: x.merge(y, on='iso_nbr', how='outer'), g_list) if len(g_list) > 0 else None\n\n # build index DF\n base_idx = df.index[df.index.year == base_year]\n i_df = pd.DataFrame(index=base_idx)\n s = pd.Series(base_idx)\n iso = s.apply(lambda x: x.isocalendar())\n i_df['iso_nbr'] = iso.apply(lambda x: x[1]).values if time_scale == 'W' else iso.apply(lambda x: x[2]).values\n i_df.reset_index(inplace=True)\n\n a_df = i_df.merge(mf, on='iso_nbr', how='left')\n a_df.drop('iso_nbr', axis=1, inplace=True)\n a_df.set_index(i_name, inplace=True)\n return a_df # will have NaN entries\n\n\ndef plot_regression(df, xcol, ycol, xreg_col, yreg_col, title='Title', legend=None, pad=3.5, orientation=90):\n \"\"\"\n plots scatter for original data and the regression line\n :param df: data DF\n :param xcol: x axis values for train/test data or time\n :param ycol: y axis values for train/test data\n :param xreg_col: x axis values for regression data. If None use xcol values\n :param yreg_col: y values from the regression model\n :param title: plot title\n :param pad: padding to avoid cutting values\n :param orientation: xaxis labels/values orientation\n :return: None\n \"\"\"\n import matplotlib.pyplot as plt\n\n if xreg_col is None:\n xreg_col = xcol\n\n if xcol in df.select_dtypes(include=[np.datetime64]).columns: # xcol is datetime\n xvals = np.arange(len(df))\n xreg_vals = np.arange(len(df))\n else:\n xvals = df[xcol].values\n xreg_vals = df[xreg_col].values\n\n plt.scatter(xvals, df[ycol].values, color='black', label=ycol)\n\n plt.title(title)\n plt.xlabel(xcol)\n plt.ylabel(ycol)\n plt.tight_layout(pad=pad)\n plt.grid(True)\n plt.plot(xreg_vals, df[yreg_col], color='red', linewidth=3, label=yreg_col)\n plt.legend(loc='upper left')\n if xcol in df.select_dtypes(include=[np.datetime64]).columns: # xcol is datetime\n plt.xticks(xvals, df[xcol].astype(str).values, rotation=orientation) # 90 = vertical\n\n\ndef to_parquet(df, f_path, str_cols=None, reset_and_drop=True):\n # save DF to a parquet file\n # json dumps to str the cols in str_cols. This way we deal with dict, nested lists, ... that json can handle\n def serial(x):\n # this function is to convert objects to json-serializable objects\n if isinstance(x, np.ndarray):\n return x.tolist()\n else:\n return x\n\n if str_cols is None:\n str_cols = list()\n\n # look for numeric columns with np.nan. They do not load so well to hive tables\n df_c = df.copy()\n for c in df_c.columns:\n if df_c[c].dtype == float or df_c[c].dtype[c] == int:\n if df_c[c].isnull().sum() > 0:\n df_c[c].fillna(np.nan, inplace=True)\n df_c[c] = df_c[c].apply(json.dumps)\n su.my_print('WARNING:: numeric column ' + c + ' has nulls. Converted to json string')\n\n # _path = os.path.expanduser(f_path)\n if os.path.exists(os.path.dirname(f_path)):\n for c in str_cols:\n df_c[c] = df_c[c].apply(lambda x: json.dumps(serial(x)))\n if reset_and_drop is True:\n df_c.reset_index(inplace=True, drop=True)\n if '.gz' in f_path:\n df_c.to_parquet(f_path, compression='gzip')\n else:\n df_c.to_parquet(f_path)\n else:\n su.my_print('to_parquet:: directory ' + str(os.path.dirname(f_path)) + ' does not exit for file ' + str(f_path))\n raise RuntimeError('failure')\n\n\ndef from_parquet(f_path, str_cols=None):\n # read the DF from a parquet file\n # converts str cols into dict or other json dumped structures\n if str_cols is None:\n str_cols = list()\n # _path = os.path.expanduser(f_path)\n if os.path.isfile(f_path):\n df_out = pd.read_parquet(f_path)\n for c in str_cols:\n if c in df_out.columns:\n df_out[c] = df_out[c].apply(json.loads)\n else:\n su.my_print('from_parquet:: ' + c + ' is not a column')\n return df_out\n else:\n su.my_print('from_parquet:: file ' + f_path + ' does not exit')\n raise RuntimeError('failure')\n\n\ndef set_date_range(init_date, final_date, freq, w_start='MON'):\n # generate a pairs of start end end dates spaced by freq with start dates centered on Mondays by default\n wday = '-' + w_start if 'W' in freq else ''\n if isinstance(init_date, str):\n init_date = pd.to_datetime(init_date)\n if isinstance(final_date, str):\n final_date = pd.to_datetime(final_date)\n dr = list(pd.date_range(init_date, end=final_date, freq=freq + wday))\n if len(dr) > 0:\n if dr[0] > init_date:\n dr.insert(0, init_date)\n else:\n dr = [init_date, final_date]\n dr.sort()\n pairs = [(dr[i], dr[i + 1]) for i in range(len(dr) - 1)] # start_d, end_d window\n if dr[-1] < final_date:\n pairs.append((dr[-1], final_date))\n return pairs\n\n\ndef save_df(a_df, os_path, sep=',', msg_hdr=None, msg_tail=None, verbose=True, index=False):\n hdr = '' if msg_hdr is None else msg_hdr\n tail = '' if msg_tail is None else msg_tail\n if os.path.dirname(os_path): # dir exists\n try:\n a_df.to_parquet(os_path + '.par')\n if verbose:\n su.my_print(hdr + 'pid: ' + str(os.getpid()) + ' save_df::Saving to ' + os_path + '.par' + tail)\n return os_path + '.par'\n except:\n su.my_print(hdr + 'pid: ' + str(os.getpid()) + ' save_df::Failed for ' + os_path + '.par' + tail)\n try:\n a_df.to_csv(os_path + '.csv.gz', sep=sep, compression='gzip', index=index)\n if verbose:\n su.my_print(hdr + 'pid: ' + str(os.getpid()) + ' save_df::Saving to ' + os_path + '.csv.gz' + tail)\n return os_path + '.csv.gz'\n except FileNotFoundError:\n su.my_print('ERROR: could not save: ' + os_path + ' not found')\n return None\n else:\n return None\n\n\ndef read_df(f_name, sep=None):\n fn = os.path.expanduser(f_name)\n root, ext = os.path.splitext(fn)\n if ext == '' or ext == '.':\n for ext in ['.par', '.csv', '.tsv', '.csv.gz', '.tsv.gz']:\n sep = '\\t' if 'tsv' in ext else ','\n f = read_df(fn + ext, sep=sep)\n if f is not None:\n return f\n return None\n else:\n if os.path.isfile(fn):\n su.my_print('read_df file: ' + str(fn))\n root, ext = os.path.splitext(fn)\n if 'gz' in ext or 'csv' in ext:\n try:\n return pd.read_csv(fn, sep=sep)\n except:\n su.my_print('read_csv failed for file ' + str(fn))\n return None\n elif 'par' in ext:\n try:\n return pd.read_parquet(fn)\n except:\n su.my_print('read_parquet failed for file ' + str(fn))\n return None\n else:\n su.my_print(fn + ' does not exist')\n return None\n\n# ############# DF dedup by close values ###########\ndef num_dedup(df, idx_cols, ycol, tol):\n # finds if there are entries with ycol values different by more than tol in the data when grouping by idx_cols\n # returns a dups DF with dup vals (same idx_col values and y values off by more than tol) and a dedups DF with unique idx_col and averaged ycol (all values were within tol)\n def y_avg(xf, ycol_):\n xf[ycol_] = xf[ycol_].mean()\n return xf\n\n def num_unique(x, ycol, tol):\n def _err(x1, x2):\n return np.abs(x1 - x2) / (2 * np.abs(x1 + x2))\n vals = [list(x[ycol].values), list(x[ycol].values)]\n arr = np.array([_err(*p) for p in product(*vals) if p[0] > p[1]])\n return len(arr[arr > tol]) # number of different values\n\n df_cols = df.columns\n g = df.groupby(idx_cols)\n gu = pd.DataFrame(g.apply(lambda x: num_unique(x, ycol, tol)))\n gu.columns = ['_uy']\n gu.reset_index(inplace=True)\n zf = df.merge(gu, on=idx_cols, how='left')\n dups = zf[zf['_uy'] >= 1].copy() # diff y's and same idx cols\n dups.sort_values(by=idx_cols, inplace=True)\n dedups = zf[zf['_uy'] == 0].groupby(idx_cols).apply(y_avg, ycol_=ycol).reset_index() # values within tol or no idx_col repeats\n dedups.drop_duplicates(subset=idx_cols + [ycol], inplace=True)\n return dups[df_cols], dedups[df_cols]\n\n\ndef to_df(data_list, a_lbl, sep='\\t', cols=None, debug=False):\n q_data = data_list[0] if len(data_list) == 1 else data_list\n if q_data is None or len(q_data) <= 1:\n return None\n\n # each row in q_data is a tab separated string\n if cols is None: # infer?\n cols = ['.'.join(c.split('.')[1:]) for c in q_data[0].split(sep)] if '.' in q_data[0] else q_data[0].split(sep) # col names of the form .: drop table name\n rows = [r.split(sep) for r in q_data[1:]]\n else:\n rows = [r.split(sep) for r in q_data]\n su.my_print('pid: ' + str(os.getpid()) + ' to_df: collected for ' + a_lbl + ':: rows: ' + str(len(rows)) + ' columns: ' + str(cols))\n ncols = len(cols)\n rcols = [r for r in rows if len(r) == ncols]\n if len(rows) - len(rcols) > 0:\n su.my_print('pid: ' + str(os.getpid()) + ' WARNING: ' + str(len(rows) - len(rcols)) + ' dropped for ' + a_lbl)\n if len(rcols) > 0:\n _df = pd.DataFrame(rcols, columns=cols)\n if list(_df.columns) == list(_df.loc[0,].values):\n _df.drop(0, axis=0, inplace=True)\n if debug:\n save_df(_df, TempUtils.tmpfile(a_lbl + '_get_data_df'))\n return _df\n else:\n su.my_print('pid: ' + str(os.getpid()) + ' WARNING: no valid data returned for ' + a_lbl)\n return None\n\n\ndef set_week_start(adf, tcol='ds'):\n tu.set_week_start(adf, tcol=tcol)\n","sub_path":"pandas_utils.py","file_name":"pandas_utils.py","file_ext":"py","file_size_in_byte":43344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"105968053","text":"#Desafio045 - Jokenpô (pedra, papel e tesoura)\nimport time\nplacar = {'Ganhou':0,'Perdeu':0}\n\nfrom random import choice, randint\nimport os\n\ndef limpar():\n if os.name == 'nt':\n return os.system('cls')\n else:\n return os.system('clear')\n \nlimpar()\n\nlista = ['Pedra','Papel','Tesoura']\nopcoes = {'Pedra':9994,'Papel':9995,'Tesoura':9996}\nescolha = 0\n\nwhile escolha != 4:\n print('\\n\\033[7;35;47m','-'*10,'JOKENPÔ','-'*10,'\\033[m\\n',end='')\n \n print('\\nVoce \\033[1;33m{} x {}\\033[m PC'.format(placar.get('Ganhou'),placar.get('Perdeu')))\n \n print('\\n1- {}Pedra\\n2- {}Papel\\n3- {}Tesoura\\n4- SAIR'.format(chr(9994),chr(9995),chr(9996)))\n \n try:\n escolha=int(input('Opcao: '))\n except:\n print('\\nOpcao inválida!\\nUma opcao aleatoria\\nserá escolhida para você ')\n escolha = randint(1,3)\n \n pc = opcoes.get(choice(lista))\n jogador = None\n\n if escolha == 1:\n jogador = 9994\n elif escolha == 2:\n jogador = 9995\n elif escolha == 3:\n jogador = 9996\n elif escolha == 4:\n print('Saindo....')\n break\n else:\n print('\\nOpção inválida!\\nUma opcao aleatoria será\\nescolhida para você')\n jogador = randint(9994,9996)\n print()\n\n if jogador == pc:\n print(chr(jogador),'x',chr(pc))\n print('Empate\\n')\n #placar['Perdeu'] = placar.get('Perdeu')+1\n #placar['Ganhou'] = placar.get('Ganhou')+1\n elif (jogador == 9994 and pc == 9996) or (jogador == 9995 and pc == 9994) or (jogador == 9996 and pc == 9995):\n print(chr(jogador),'x',chr(pc))\n print('Voce ganhou\\n')\n placar['Ganhou'] = placar.get('Ganhou')+1\n else:\n print(chr(jogador),'x',chr(pc))\n print('Voce perdeu\\n')\n placar['Perdeu'] = placar.get('Perdeu')+1\n \n time.sleep(2)\n limpar()\n\n","sub_path":"Desafio045(1).py","file_name":"Desafio045(1).py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"392607464","text":"# Copyright 2018-2021 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"This module contains utilities for defining custom gradient transforms,\r\nincluding a decorator for specifying gradient expansions.\"\"\"\r\n# pylint: disable=too-few-public-methods\r\nimport pennylane as qml\r\n\r\n\r\nunsupported_op = lambda op: op.grad_method is None\r\nsupported_op = lambda op: op.grad_method is not None\r\ntrainable_op = lambda op: any(qml.math.requires_grad(p) for p in op.parameters)\r\n\r\n\r\ndef gradient_expand(tape, depth=10):\r\n \"\"\"Expand out a tape so that it supports differentiation\r\n of requested operations.\r\n\r\n This is achieved by decomposing all trainable operations that have\r\n ``Operation.grad_method=None`` until all resulting operations\r\n have a defined gradient method, up to maximum depth ``depth``. Note that this\r\n might not be possible, in which case the gradient rule will fail to apply.\r\n\r\n Args:\r\n tape (.QuantumTape): the input tape to expand\r\n depth (int) : the maximum expansion depth\r\n\r\n Returns:\r\n .QuantumTape: the expanded tape\r\n \"\"\"\r\n\r\n # check if the tape contains unsupported trainable operations\r\n if any(unsupported_op(op) and trainable_op(op) for op in tape.operations):\r\n\r\n # Define the stopping condition for the expansion\r\n stop_cond = lambda obj: (\r\n not isinstance(obj, qml.measure.MeasurementProcess)\r\n and ((supported_op(obj) and trainable_op(obj)) or not trainable_op(obj))\r\n )\r\n\r\n new_tape = tape.expand(depth=depth, stop_at=stop_cond)\r\n params = new_tape.get_parameters(trainable_only=False)\r\n new_tape.trainable_params = qml.math.get_trainable_indices(params)\r\n return new_tape\r\n\r\n return tape\r\n\r\n\r\nclass gradient_transform(qml.batch_transform):\r\n \"\"\"Decorator for defining quantum gradient transforms.\r\n\r\n Quantum gradient transforms are a specific case of :class:`~.batch_transform`.\r\n All quantum gradient transforms accept a tape, and output\r\n a batch of tapes to be independently executed on a quantum device, alongside\r\n a post-processing function that returns the result.\r\n\r\n Args:\r\n expand_fn (function): An expansion function (if required) to be applied to the\r\n input tape before the gradient computation takes place. If not provided,\r\n the default expansion function simply expands all operations that\r\n have ``Operation.grad_method=None`` until all resulting operations\r\n have a defined gradient method.\r\n differentiable (bool): Specifies whether the gradient transform is differentiable or\r\n not. A transform may be non-differentiable if it does not use an\r\n autodiff framework for its tensor manipulations. In such a case, setting\r\n ``differentiable=False`` instructs the decorator\r\n to mark the output as 'constant', reducing potential overhead.\r\n hybrid (bool): Specifies whether classical processing inside a QNode\r\n should be taken into account when transforming a QNode.\r\n\r\n - If ``True``, and classical processing is detected and this\r\n option is set to ``True``, the Jacobian of the classical\r\n processing will be computed and included. When evaluated, the\r\n returned Jacobian will be with respect to the QNode arguments.\r\n\r\n - If ``False``, any internal QNode classical processing will be\r\n **ignored**. When evaluated, the returned Jacobian will be with\r\n respect to the **gate** arguments, and not the QNode arguments.\r\n\r\n Supported gradient transforms must be of the following form:\r\n\r\n .. code-block:: python\r\n\r\n @gradient_transform\r\n def my_custom_gradient(tape, argnum=None, **kwargs):\r\n ...\r\n return gradient_tapes, processing_fn\r\n\r\n where:\r\n\r\n - ``tape`` (*QuantumTape*): the input quantum tape to compute the gradient of\r\n\r\n - ``argnum`` (*int* or *list[int]* or *None*): Which trainable parameters of the tape\r\n to differentiate with respect to. If not provided, the derivatives with respect to all\r\n trainable inputs of the tape should be returned (``tape.trainable_params``).\r\n\r\n - ``gradient_tapes`` (*List[QuantumTape]*): is a list of output tapes to be evaluated.\r\n If this list is empty, no quantum evaluations will be made.\r\n\r\n - ``processing_fn`` is a processing function to be applied to the output of the evaluated\r\n ``gradient_tapes``. It should accept a list of numeric results with length ``len(gradient_tapes)``,\r\n and return the Jacobian matrix.\r\n\r\n Once defined, the quantum gradient transform can be used as follows:\r\n\r\n >>> gradient_tapes, processing_fn = my_custom_gradient(tape, *gradient_kwargs)\r\n >>> res = execute(tapes, dev, interface=\"autograd\", gradient_fn=qml.gradients.param_shift)\r\n >>> jacobian = processing_fn(res)\r\n\r\n Alternatively, gradient transforms can be applied directly to QNodes,\r\n in which case the execution is implicit:\r\n\r\n >>> fn = my_custom_gradient(qnode, *gradient_kwargs)\r\n >>> fn(weights) # transformed function takes the same arguments as the QNode\r\n 1.2629730888100839\r\n\r\n .. note::\r\n\r\n The input tape might have parameters of various types, including\r\n NumPy arrays, JAX DeviceArrays, and TensorFlow and PyTorch tensors.\r\n\r\n If the gradient transform is written in a autodiff-compatible manner, either by\r\n using a framework such as Autograd or TensorFlow, or by using ``qml.math`` for\r\n tensor manipulation, then higher-order derivatives will also be supported.\r\n\r\n Alternatively, you may use the ``tape.unwrap()`` context manager to temporarily\r\n convert all tape parameters to NumPy arrays and floats:\r\n\r\n >>> with tape.unwrap():\r\n ... params = tape.get_parameters() # list of floats\r\n \"\"\"\r\n\r\n def __init__(self, transform_fn, expand_fn=gradient_expand, differentiable=True, hybrid=True):\r\n self.hybrid = hybrid\r\n super().__init__(transform_fn, expand_fn=expand_fn, differentiable=differentiable)\r\n\r\n def default_qnode_wrapper(self, qnode, targs, tkwargs):\r\n # Here, we overwrite the QNode execution wrapper in order\r\n # to take into account that classical processing may be present\r\n # inside the QNode.\r\n hybrid = tkwargs.pop(\"hybrid\", self.hybrid)\r\n _wrapper = super().default_qnode_wrapper(qnode, targs, tkwargs)\r\n cjac_fn = qml.transforms.classical_jacobian(qnode)\r\n\r\n def jacobian_wrapper(*args, **kwargs):\r\n qjac = _wrapper(*args, **kwargs)\r\n\r\n if any(m.return_type is qml.operation.Probability for m in qnode.qtape.measurements):\r\n qjac = qml.math.squeeze(qjac)\r\n\r\n if not hybrid:\r\n return qjac\r\n\r\n cjac = cjac_fn(*args, **kwargs)\r\n\r\n if isinstance(cjac, tuple):\r\n # Classical processing of multiple arguments is present. Return qjac @ cjac.\r\n jacs = [\r\n qml.math.squeeze(qml.math.tensordot(c, qjac, [[0], [-1]]))\r\n for c in cjac\r\n if c is not None\r\n ]\r\n return jacs\r\n\r\n is_square = cjac.shape == (1,) or (cjac.ndim == 2 and cjac.shape[0] == cjac.shape[1])\r\n\r\n if is_square and qml.math.allclose(cjac, qml.numpy.eye(cjac.shape[0])):\r\n # Classical Jacobian is the identity. No classical processing\r\n # is present inside the QNode.\r\n return qjac\r\n\r\n # Classical processing of a single argument is present. Return qjac @ cjac.\r\n jac = qml.math.squeeze(qml.math.tensordot(qml.math.T(cjac), qjac, [[-1], [-1]]))\r\n return qml.math.T(jac)\r\n\r\n return jacobian_wrapper\r\n","sub_path":"pennylane/gradients/gradient_transform.py","file_name":"gradient_transform.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"94112177","text":"import math\n\nnum = int(input(\"Enter a int number: \"))\nend = int(math.sqrt(num))\n\nrecord = 0\nfor x in range(2, end+1):\n if num% x == 0:\n record = 1\n print(\"%d is NOT prime number\" % num)\n break\n\nif record == 0:\n print(\"%d is prime number\" % num)","sub_path":"Day01-15/Day04/my_code/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"571119835","text":"\"\"\"\nReinforcement Learning agent that trains on MineRLTreechop environment. It is then evaluated on MineRLObtainDiamond by\nrunning it for a certain number of ticks and then switching to the scripted part that crafts a wooden_pickaxe and digs\ndown to get some cobblestone.\nWith default parameters it trains in about 8 hours on a machine with a GeForce RTX 2080 Ti GPU.\nIt uses less than 8GB RAM and achieves an average reward of 8.3.\n\"\"\"\n\nimport gym\nimport time\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.vec_env import DummyVecEnv\nimport minerl # it's important to import minerl after SB3, otherwise model.save doesn't work...\n\n\n# Parameters:\nTRAIN_TIMESTEPS = 2000000 # number of steps to train the agent for. At 70 FPS 2m steps take about 8 hours.\nTRAIN_ENV = 'MineRLTreechop-v0' # training environment for the RL agent. Could use MineRLObtainDiamondDense-v0 here.\nTRAIN_MODEL_NAME = 'potato' # name to use when saving the trained agent.\nTEST_MODEL_NAME = 'potato' # name to use when loading the trained agent.\n\nTEST_EPISODES = 10 # number of episodes to test the agent for.\nMAX_TEST_EPISODE_LEN = 18000 # 18k is the default for MineRLObtainDiamond.\nTREECHOP_STEPS = 2000 # number of steps to run RL lumberjack for in evaluations.\n\nexperiment_name = f\"ppo_{int(time.time())}\"\n\n\ndef make_env(idx):\n def thunk():\n env = gym.make(TRAIN_ENV)\n env = PovOnlyObservation(env)\n env = ActionShaping(env, always_attack=True)\n if idx == 0:\n env = gym.wrappers.Monitor(env, f\"videos/{experiment_name}\")\n return env\n return thunk\n\n\nclass PovOnlyObservation(gym.ObservationWrapper):\n \"\"\"\n Turns the observation space into POV only, ignoring the inventory. This is needed for stable_baselines3 RL agents,\n as they don't yet support dict observations. The support should be coming soon (as of April 2021).\n See following PR for details:\n https://github.com/DLR-RM/stable-baselines3/pull/243\n \"\"\"\n def __init__(self, env):\n super().__init__(env)\n self.observation_space = self.env.observation_space['pov']\n\n def observation(self, observation):\n return observation['pov']\n\n\nclass ActionShaping(gym.ActionWrapper):\n \"\"\"\n The default MineRL action space is the following dict:\n\n Dict(attack:Discrete(2),\n back:Discrete(2),\n camera:Box(low=-180.0, high=180.0, shape=(2,)),\n craft:Enum(crafting_table,none,planks,stick,torch),\n equip:Enum(air,iron_axe,iron_pickaxe,none,stone_axe,stone_pickaxe,wooden_axe,wooden_pickaxe),\n forward:Discrete(2),\n jump:Discrete(2),\n left:Discrete(2),\n nearbyCraft:Enum(furnace,iron_axe,iron_pickaxe,none,stone_axe,stone_pickaxe,wooden_axe,wooden_pickaxe),\n nearbySmelt:Enum(coal,iron_ingot,none),\n place:Enum(cobblestone,crafting_table,dirt,furnace,none,stone,torch),\n right:Discrete(2),\n sneak:Discrete(2),\n sprint:Discrete(2))\n\n It can be viewed as:\n - buttons, like attack, back, forward, sprint that are either pressed or not.\n - mouse, i.e. the continuous camera action in degrees. The two values are pitch (up/down), where up is\n negative, down is positive, and yaw (left/right), where left is negative, right is positive.\n - craft/equip/place actions for items specified above.\n So an example action could be sprint + forward + jump + attack + turn camera, all in one action.\n\n This wrapper makes the action space much smaller by selecting a few common actions and making the camera actions\n discrete. You can change these actions by changing self._actions below. That should just work with the RL agent,\n but would require some further tinkering below with the BC one.\n \"\"\"\n def __init__(self, env, camera_angle=10, always_attack=False):\n super().__init__(env)\n\n self.camera_angle = camera_angle\n self.always_attack = always_attack\n self._actions = [\n [('attack', 1)],\n [('forward', 1)],\n # [('back', 1)],\n # [('left', 1)],\n # [('right', 1)],\n # [('jump', 1)],\n # [('forward', 1), ('attack', 1)],\n # [('craft', 'planks')],\n [('forward', 1), ('jump', 1)],\n [('camera', [-self.camera_angle, 0])],\n [('camera', [self.camera_angle, 0])],\n [('camera', [0, self.camera_angle])],\n [('camera', [0, -self.camera_angle])],\n ]\n\n self.actions = []\n for actions in self._actions:\n act = self.env.action_space.noop()\n for a, v in actions:\n act[a] = v\n if self.always_attack:\n act['attack'] = 1\n self.actions.append(act)\n\n self.action_space = gym.spaces.Discrete(len(self.actions))\n\n def action(self, action):\n return self.actions[action]\n\n\ndef train(wandb_project_name=None):\n if wandb_project_name:\n import wandb\n wandb.init(\n project=wandb_project_name,\n sync_tensorboard=True,\n name=experiment_name,\n monitor_gym=True,\n save_code=True,\n )\n\n env = DummyVecEnv([make_env(i) for i in range(1)])\n # For all the PPO hyperparameters you could tune see this:\n # https://github.com/DLR-RM/stable-baselines3/blob/6f822b9ed7d6e8f57e5a58059923a5b24e8db283/stable_baselines3/ppo/ppo.py#L16\n model = PPO('CnnPolicy', env, verbose=1, tensorboard_log=f\"runs/{experiment_name}\")\n model.learn(total_timesteps=TRAIN_TIMESTEPS) # 2m steps is about 8h at 70 FPS\n model.save(TRAIN_MODEL_NAME)\n\n env.close()\n\n\ndef str_to_act(env, actions):\n \"\"\"\n Simplifies specifying actions for the scripted part of the agent.\n Some examples for a string with a single action:\n 'craft:planks'\n 'camera:[10,0]'\n 'attack'\n 'jump'\n ''\n There should be no spaces in single actions, as we use spaces to separate actions with multiple \"buttons\" pressed:\n 'attack sprint forward'\n 'forward camera:[0,10]'\n\n :param env: base MineRL environment.\n :param actions: string of actions.\n :return: dict action, compatible with the base MineRL environment.\n \"\"\"\n act = env.action_space.noop()\n for action in actions.split():\n if \":\" in action:\n k, v = action.split(':')\n if k == 'camera':\n act[k] = eval(v)\n else:\n act[k] = v\n else:\n act[action] = 1\n return act\n\n\ndef get_action_sequence():\n \"\"\"\n Specify the action sequence for the scripted part of the agent.\n \"\"\"\n # make planks, sticks, crafting table and wooden pickaxe:\n action_sequence = []\n action_sequence += [''] * 100\n action_sequence += ['craft:planks'] * 4\n action_sequence += ['craft:stick'] * 2\n action_sequence += ['craft:crafting_table']\n action_sequence += ['camera:[10,0]'] * 18\n action_sequence += ['attack'] * 20\n action_sequence += [''] * 10\n action_sequence += ['jump']\n action_sequence += [''] * 5\n action_sequence += ['place:crafting_table']\n action_sequence += [''] * 10\n\n # bug: looking straight down at a crafting table doesn't let you craft. So we look up a bit before crafting.\n action_sequence += ['camera:[-1,0]']\n action_sequence += ['nearbyCraft:wooden_pickaxe']\n action_sequence += ['camera:[1,0]']\n action_sequence += [''] * 10\n action_sequence += ['equip:wooden_pickaxe']\n action_sequence += [''] * 10\n\n # dig down:\n action_sequence += ['attack'] * 600\n action_sequence += [''] * 10\n\n return action_sequence\n\n\ndef test():\n env = gym.make('MineRLObtainDiamond-v0')\n\n # optional interactive mode, where you can connect to your agent and play together (see link for details):\n # https://minerl.io/docs/tutorials/minerl_tools.html#interactive-mode-minerl-interactor\n # env.make_interactive(port=6666, realtime=True)\n\n env = PovOnlyObservation(env)\n env = ActionShaping(env, always_attack=True)\n env1 = env.unwrapped\n\n model = PPO.load(TEST_MODEL_NAME, verbose=1)\n model.set_env(env)\n\n action_sequence = get_action_sequence()\n\n for episode in range(TEST_EPISODES):\n obs = env.reset()\n done = False\n total_reward = 0\n steps = 0\n\n # RL part to get some logs:\n for i in range(TREECHOP_STEPS):\n action = model.predict(obs)\n obs, reward, done, _ = env.step(action[0])\n total_reward += reward\n steps += 1\n if done:\n break\n\n # scripted part to use the logs:\n if not done:\n for i, action in enumerate(action_sequence[:MAX_TEST_EPISODE_LEN - TREECHOP_STEPS]):\n obs, reward, done, _ = env1.step(str_to_act(env1, action))\n total_reward += reward\n steps += 1\n if done:\n break\n\n print(f'Episode #{episode + 1} reward: {total_reward}\\t\\t episode length: {steps}')\n\n env.close()\n\n\ndef main():\n # uncomment either one of the following lines to train\n # if `wandb_project_name` is set, the training logs and videos\n # will be uploaded to Weights and Biases\n # train()\n # train(wandb_project_name=\"minerl\")\n test()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"standalone/RL_plus_script.py","file_name":"RL_plus_script.py","file_ext":"py","file_size_in_byte":9379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"139427454","text":"from datetime import datetime, timezone\nfrom flask import Flask, request, Response\nimport logging\nimport platform\nimport socket\n\napp = Flask(__name__)\n\nlogging.basicConfig(level=logging.INFO)\n\n\n@app.route('/ping')\ndef hello_world():\n currentDateTime = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()\n responseText = 'At the pong it is {} on {} (running {}/{})'.format(currentDateTime, socket.gethostname(), platform.system(), platform.machine())\n\n app.logger.info('{} request from {}'.format(\n currentDateTime, request.remote_addr))\n return Response(responseText, mimetype=\"text/plain\")\n\n\n@app.route('/health')\ndef health():\n return {\n \"status\": \"UP\"\n }\n\n\nif __name__ == '__main__':\n app.run(port = 8080)\n","sub_path":"flask/ping_pong.py","file_name":"ping_pong.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"181206337","text":"# Program for circuler pattern\n'''\n Author : Samadhan Gaikwad.\n Software Developer\n Location: Pune.\n'''\n\nimport turtle\n# s = turtle.getscreen()\nt = turtle.Turtle()\nturtle.bgcolor(\"black\")\nt.pensize(3)\n# t.speed(5)\n# t.goto(-300, 0)\nfor i in range(6):\n for j in [\"magenta\", \"red\", \"blue\", \"green\", \"cyan\", \"yellow\", \"white\", \"purple\"]:\n t.color(j)\n t.circle(100)\n t.left(10)\n # t.pensize(3)\n # t.circle(150)\n # t.forward(20)\n t.speed(11)\nt.hideturtle()\nturtle.done()\n","sub_path":"Logical Program/Turtle.py","file_name":"Turtle.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"43026841","text":"from setup import *\n\n\ndef handle_message(soc, message):\n global version, nodes, sync, expec_blocks, my_addr, con_sent\n command = bytes.fromhex(message[:24].lstrip(\"0\")).decode(\"utf-8\")\n payload = message[32:]\n logging.debug(f\"{soc.getpeername()}: {command}\")\n if command == \"version\":\n if nodes[soc.getpeername()].expecting == \"version\":\n node_version = payload[:8]\n if node_version != version:\n return\n if int(node_version, 16) > int(version, 16):\n logging.debug(\"old version\")\n ui_in.put([\"warning\", \"Vyzerá to že máš zastaralú verziu\"])\n best_height = int(payload[-20:-12], 16)\n nodes[soc.getpeername()].best_height = best_height\n my_addr = decode_ip(payload[-12:-4])\n logging.debug(f\"my_addr: {my_addr}\")\n tr_port = int(payload[-4:], 16)\n nodes[soc.getpeername()].port = tr_port\n logging.debug(f\"node property: {tr_port}\")\n timestamp = int(payload[8:24], 16)\n time_difference = int(int(time()) - timestamp)\n if -300 < time_difference > 300:\n return\n if nodes[soc.getpeername()].inbound:\n send_message(\"version\", nodes[soc.getpeername()].socket)\n nodes[soc.getpeername()].expecting = \"verack\"\n else:\n send_message(\"only\", soc=nodes[soc.getpeername()].socket, cargo=\"verack\")\n nodes[soc.getpeername()].authorized = True\n nodes[soc.getpeername()].expecting = \"\"\n send_message(\"addr\", soc=nodes[soc.getpeername()].socket, cargo=\"init\")\n send_message(\"only\", soc=list(nodes.values())[0].socket, cargo=\"getaddr\")\n if soc.getpeername() not in hardcoded_nodes:\n send_message(\"sync\", soc=soc)\n peer = nodes[soc.getpeername()]\n c.execute(\"UPDATE nodes SET timestamp = (?) WHERE addr = (?) AND port = (?);\", (peer.lastrecv, peer.address[0], peer.port))\n con_sent = False\n elif command == \"verack\":\n if nodes[soc.getpeername()].expecting == \"verack\":\n nodes[soc.getpeername()].authorized = True\n nodes[soc.getpeername()].expecting = \"\"\n else:\n ban_check(soc.getpeername())\n elif command == \"transaction\":\n if nodes[soc.getpeername()].authorized == True:\n result = blockchain.verify_tx(payload)\n if result == True:\n #mal by som to spreavit tak aby sa checkovalo len raz ci je tx v mempool\n #vymazava sa z mempoolu?\n logging.debug(payload)\n blockchain.valid_tx.append(payload)\n blockchain.mempool.append(payload)\n blockchain.tx_content(payload)\n send_message(\"broadcast\", soc=soc.getpeername(), cargo=[payload, \"transaction\"])\n elif result == \"already\":\n pass\n else:\n ban_check(soc.getpeername())\n else:\n ban_check(soc.getpeername())\n elif command == \"headers\":\n logging.debug(f\"headers msg: {payload}\")\n logging.debug(f\"headers sync: {sync}\")\n if payload == \"00\":\n sync = [True, 0, 0]\n ui_in.put([\"sync_t\", \"\"])\n return\n if not sync[0] and sync[2] == soc.getpeername():\n sync[1] = 0\n num_headers = int(payload[:2],16)\n num_hashes = 0\n index = 2\n getblocks = \"\"\n for i in range(num_headers):\n header_hash = payload[index:index+64]\n blockchain.c.execute(\"SELECT * FROM blockchain WHERE hash = (?);\", (header_hash,))\n result = blockchain.c.fetchone()\n if result == None:\n logging.debug(f\"requested: {header_hash}\")\n getblocks += header_hash\n expec_blocks += 1\n num_hashes += 1\n index += 64\n new_message = blockchain.fill(hex(num_hashes)[2:], 2) + getblocks\n send_message(\"universal\", soc=soc, cargo=(new_message, \"getblocks\"))\n elif command == \"getblocks\":#toto by mohol poslat hocikto to by som mal riesit\n num_headers = int(payload[:2],16)\n index = 2\n for i in range(num_headers):\n header_hash = payload[index:index+64]\n logging.debug(f\"getblocks hash: {header_hash}\")\n blockchain.c.execute(\"SELECT * FROM blockchain WHERE hash = (?);\", (header_hash,))\n result = blockchain.c.fetchone()\n if result:\n block = result[1]\n send_message(\"universal\", soc=soc, cargo=(block, \"block\"))\n else:\n logging.debug(\"dojebana picovina\")\n index += 64\n elif command == \"block\":\n logging.debug(f\"new block: {payload}\")\n block_hash = blockchain.hash(payload[:216])\n expec_blocks -= 1\n logging.debug(f\"expec_blocks: {expec_blocks}\")\n if blockchain.verify_block(payload):\n appended = blockchain.append(payload, sync[0])\n logging.debug(f\"block appended: {appended}\")\n if appended == \"orphan\":\n if sync[0] == False and expec_blocks == 0 and sync[1] == 0:\n logging.debug(\"block posielam sync\")\n send_message(\"sync\", soc=soc)\n return\n if sync[0]:\n new_message = \"01\" + payload[8:72]\n send_message(\"universal\", soc=soc, cargo=[new_message, \"getblocks\"])\n expec_blocks += 1\n return\n elif appended == \"alrdgot\":\n if sync[0] == False and expec_blocks == 0 and sync[1] == 0:\n logging.debug(\"block posielam sync\")\n send_message(\"sync\", soc=soc)\n return\n elif appended == \"appended\":\n if sync[0]:\n new_message = \"01\" + block_hash\n send_message(\"broadcast\", soc=soc.getpeername(), cargo=[new_message, \"headers\"])\n if sync[0] == False and expec_blocks == 0:\n logging.debug(\"block posielam sync\")\n send_message(\"append sync\", soc=soc, cargo=block_hash)\n blockchain.check_orphans(block_hash)\n return\n elif appended == True:\n orphans = blockchain.check_orphans(\"main\")\n else:\n ban_check(soc.getpeername())\n return\n else:\n ban_check(soc.getpeername())\n return\n logging.debug(f\"sync: {sync}\")\n if sync[0] == False and expec_blocks == 0:\n logging.debug(\"block posielam sync\")\n send_message(\"sync\", soc=soc)\n return\n if not sync[0]:\n return\n if mining:\n logging.debug(\"stopping mining\")\n to_mine.put(\"stop\")\n start_mining()\n num_headers = 1\n headers = block_hash\n if 'orphans' in locals():\n for i in orphans:\n headers += i\n num_headers += 1\n num_headers = blockchain.fill(hex(num_headers)[2:], 2)\n new_message = num_headers + headers\n send_message(\"broadcast\", soc=soc.getpeername(), cargo=[new_message, \"headers\"])\n elif command == \"getheaders\":\n logging.debug(f\"getheaders sync: {sync}\")\n if not sync[0] and sync[2] != soc.getpeername():\n return\n if not sync[0] and sync[2] == soc.getpeername():\n sync = [True, 0, 0]\n ui_in.put([\"sync_t\", \"\"])\n chainwork = int(payload[:64], 16)\n if blockchain.chainwork < chainwork:#tu by sa potom dal dat ze expect sync ak to budem chciet robit cez\n logging.debug(\"node ma vacsi chainwork\")\n send_message(\"sync\", soc=soc)\n return\n num_hash = int(payload[64:66])\n size = 64 + 2 + ((num_hash + 1) * 64)\n if len(payload) == size:\n stop_hash = payload[-64:]\n start_hash = payload[66:130]\n index = 130\n for i in range(num_hash):\n blockchain.c.execute(\"SELECT rowid FROM blockchain WHERE hash = (?);\", (start_hash,))\n rowid = blockchain.c.fetchone()\n if rowid != None:\n break\n index += 64\n start_hash = payload[index:index+64]\n if rowid == None:\n logging.debug(\"getheaders none\")\n rowid = 1\n else:\n rowid = rowid[0]\n blockchain.c.execute(\"SELECT rowid FROM blockchain WHERE rowid = (SELECT MAX(rowid) FROM blockchain);\")\n max_rowid = blockchain.c.fetchone()[0]\n logging.debug(f\"rowid: {rowid}\")\n logging.debug(f\"maxrowid: {max_rowid}\")\n if rowid and rowid != max_rowid:\n new_message = \"\"\n num_headers = 0\n for i in range(255):#toto bude este treba fixnut ked to bude nad 255\n blockchain.c.execute(\"SELECT * FROM blockchain WHERE rowid = (?);\", (rowid,))\n block = blockchain.c.fetchone()\n if block:\n new_message += block[0]\n num_headers += 1\n if block[0] == stop_hash:\n num_headers = hex(num_headers)[2:]\n num_headers = blockchain.fill(num_headers, 2)\n new_message = num_headers + new_message\n send_message(\"universal\", soc=soc, cargo=[new_message, \"headers\"])\n return\n else:\n break\n rowid += 1\n num_headers = hex(num_headers)[2:]\n num_headers = blockchain.fill(num_headers, 2)\n new_message = num_headers + new_message\n send_message(\"universal\", soc=soc, cargo=[new_message, \"headers\"])\n elif rowid == max_rowid:\n send_message(\"universal\",soc=soc, cargo=[\"00\", \"headers\"])\n else:\n ban_check(soc.getpeername())\n elif command == \"getaddr\":\n send_message(\"addr\", soc=soc)\n elif command == \"addr\":\n logging.debug(f\"addr payload: {payload}\")\n num_addr = int(payload[:4], 16)\n if num_addr > 1000:\n ban_check(soc.getpeername())\n return\n index = 4\n logging.debug(f\"my addr:{my_addr}, {port}\")\n for i in range(num_addr):\n node_ip = decode_ip(payload[index:index+8])\n node_port = int(payload[index+8:index+12], 16)\n node_timestamp = int(payload[index+12:index+20], 16)\n logging.debug(f\"node: {node_ip}, {node_port}, {node_timestamp}\")\n if (node_ip, node_port) in hardcoded_nodes:\n continue\n if node_ip == \"127.0.0.1\" or node_ip == \"0.0.0.0\":\n return\n index += 20\n c.execute(\"SELECT * FROM nodes WHERE addr = (?) AND port = (?);\", (node_ip, node_port))\n query = c.fetchone()\n logging.debug(f\"query {query}\")\n if (node_ip != my_addr or node_port != port) and query == None:\n c.execute(\"INSERT INTO nodes VALUES (?,?,?);\", (node_ip, node_port, node_timestamp))\n elif (node_ip != my_addr or node_port != port) and query != None:\n if query[2] < node_timestamp:\n c.execute(\"UPDATE nodes SET timestamp = (?) WHERE addr = (?) AND port = (?);\", (node_timestamp, node_ip, node_port))\n if num_addr == 1 and int(time()) - node_timestamp < 600 and (node_ip != my_addr or node_port != port) and routable(node_ip):\n address = soc.getpeername()\n if query != None:\n if query[0] == node_ip and query[1] == node_port and query[2] == node_timestamp:\n break\n if len(nodes) <= 1:\n break\n elif len(nodes) == 2:\n for i in list(nodes.values()):\n if i.address != address:\n send_message(\"addr\", soc=i.socket, cargo=payload)\n break\n while True:\n logging.debug(\"loop addr preposielanie\")\n first = randint(0, len(nodes)-1)\n second = randint(0, len(nodes)-1)\n if first != second and address != list(nodes.values())[first].address and address != list(nodes.values())[second].address:\n send_message(\"addr\", soc=list(nodes.values())[first].socket, cargo=payload)\n send_message(\"addr\", soc=list(nodes.values())[second].socket, cargo=payload)\n break\n conn.commit()\n elif command == \"active\":\n pass\n else:\n ban_check(soc.getpeername())\n\n\ndef send_message(command, soc = None, cargo = None):\n global version, nodes, port, sync\n if command == \"version\" or command == \"version1\":\n timestamp = hex(int(time()))[2:]\n best_height = hex(blockchain.height)[2:]\n best_height = blockchain.fill(best_height, 8)\n if command == \"version1\":\n addr_recv = cargo\n else:\n addr_recv = soc.getpeername()[0]\n addr_recv = encode_ip(addr_recv)\n tr_port = blockchain.fill(hex(port)[2:], 4)\n payload = bytes.fromhex(version + timestamp + best_height + addr_recv + tr_port)\n payload_lenght = hex(len(payload))[2:]\n header = create_header(\"version\", payload_lenght)\n if command == \"version1\":\n return header + payload\n outbound.put([\"send\", [soc, header + payload]])\n elif command == \"send\":\n msg, pub_key, msg_type = cargo\n payload = blockchain.create_tx(msg_type ,msg, pub_key)\n blockchain.mempool.append(payload.hex())\n payload_lenght = hex(len(payload))[2:]\n logging.debug(\"idem sendovat\")\n header = create_header(\"transaction\", payload_lenght)\n outbound.put([\"broadcast\", [soc, header + payload]])\n elif command == \"broadcast\":\n payload, type = cargo\n payload = bytes.fromhex(payload)\n payload_lenght = hex(len(payload))[2:]\n header = create_header(type, payload_lenght)\n outbound.put([\"broadcast\", [soc, header + payload]])\n elif command == \"universal\":\n cargo, type = cargo\n payload = bytes.fromhex(cargo)\n payload_lenght = hex(len(payload))[2:]\n header = create_header(type, payload_lenght)\n outbound.put([\"send\", [soc, header + payload]])\n elif command == \"sync\":\n sync = [False, int(time()), soc.getpeername()]\n ui_in.put([\"sync_f\", \"\"])\n num_headers = 0\n blockchain.c.execute(\"SELECT rowid FROM blockchain WHERE rowid = (SELECT MAX(rowid) FROM blockchain);\")\n rowid = blockchain.c.fetchone()[0]\n if rowid < 50:\n blockchain.c.execute(\"SELECT hash FROM blockchain WHERE rowid = (SELECT MAX(rowid) FROM blockchain);\")\n block_headers = blockchain.c.fetchone()[0]\n num_headers = 1\n else:\n change = int(rowid / 10)\n block_headers = \"\"\n for i in range(9):\n blockchain.c.execute(\"SELECT hash FROM blockchain WHERE rowid = (?);\", (rowid,))\n block_headers += blockchain.c.fetchone()[0]\n rowid -= change\n num_headers += 1\n payload = bytes.fromhex(blockchain.fill(hex(blockchain.chainwork)[2:], 64) + blockchain.fill(hex(num_headers)[2:], 2) + block_headers + \"0\"*64)\n payload_lenght = hex(len(payload))[2:]\n header = create_header(\"getheaders\", payload_lenght)\n outbound.put([\"send\", [soc, header + payload]])\n elif command == \"append sync\":\n payload = bytes.fromhex(blockchain.fill(hex(blockchain.chainwork)[2:], 64) + \"01\" + cargo + \"0\"*64)\n payload_lenght = hex(len(payload))[2:]\n header = create_header(\"getheaders\", payload_lenght)\n outbound.put([\"send\", [soc, header + payload]])\n elif command == \"addr\":\n if cargo == \"init\":\n payload = bytes.fromhex(\"0001\" + encode_ip(my_addr) + blockchain.fill(hex(port)[2:], 4) + hex(int(time()))[2:])\n elif cargo != None and cargo != \"broadcast\":\n payload = bytes.fromhex(cargo)\n else:\n timestamp = int(time()) - 18000\n c.execute(\"SELECT * FROM nodes WHERE timestamp > ?;\", (timestamp,))\n ls_nodes = c.fetchall()\n logging.debug(f\"ls_nodes addr: {ls_nodes}\")\n if ls_nodes == []:\n return\n num_addr = 0\n payload = \"\"\n for node in ls_nodes:\n peer = soc.getpeername()\n if node[0] != peer[0] and node[1] != peer[1]:\n num_addr += 1\n payload = payload + encode_ip(node[0]) + blockchain.fill(hex(node[1])[2:], 4) + hex(node[2])[2:]\n elif len(ls_nodes) == 1:\n return\n if num_addr == 1000:\n break\n payload = bytes.fromhex(blockchain.fill(hex(num_addr)[2:], 4) + payload)\n payload_lenght = hex(len(payload))[2:]\n header = create_header(\"addr\", payload_lenght)\n if cargo == \"broadcast\":\n outbound.put([\"broadcast\", [soc, header + payload]])\n else:\n outbound.put([\"send\", [soc, header + payload]])\n elif command == \"only\":\n header = create_header(cargo, \"0\")\n outbound.put([\"send\", [soc, header]])\n\n\ndef create_header(command, payload_lenght):\n return bytes.fromhex(blockchain.fill(command.encode(\"utf-8\").hex(), 24) + blockchain.fill(payload_lenght, 8))\n\n\ndef encode_ip(ip):\n ip = ip.split(\".\")\n addr = \"\"\n for i in ip:\n if 0 > int(i) > 255:\n print(\"neplatna adresa\")\n return\n temp = hex(int(i))[2:]\n addr += blockchain.fill(temp, 2)\n return addr\n\n\ndef decode_ip(ip):\n previ = -1\n addr = \"\"\n for i in range(2, 10, 2):\n if i == 2:\n addr = str(int(ip[-i:], 16)) + \".\" + addr\n else:\n addr = str(int(ip[-i:previ], 16)) + \".\" + addr\n previ = -i\n return addr[:-1]\n\n\ndef ban_check(address):\n logging.debug(\"bancheck\")\n try:\n logging.debug(f\"ban nodes: {nodes}\")\n logging.debug(f\"ban addr: {address}\")\n nodes[address].banscore += 1\n if nodes[address].banscore >= 10:\n c.execute(\"DELETE FROM nodes WHERE addr=(?) AND port=(?)\", (address[0], address[1]))\n outbound.put([\"close\", address])\n ban_list.append(address)\n except KeyError:\n logging.debug(\"ban_check key error\")\n pass\n\n\ndef routable(ip):\n if ip == \"0.0.0.0\":\n return False\n elif ip == \"127.0.0.1\":\n return False\n ip_split = [int(i) for i in ip.split(\".\")]\n if ip_split[0] == 10:\n return False\n elif ip_split[0] == 192 and ip_split[1] == 168:\n return False\n elif ip_split[0] == 176 and 16 <= ip_split[1] <= 31:\n return False\n return True\n\n\ndef connect():\n global nodes, con_sent, c\n #aby som sa nepokusal pripojit na node na ktory uz som na jednom porte moze pocuvat len jeden node takze ak by bol tam aj druhy tak on moze robit len outbound\n node_list = [(i.address[0], i.port) for i in list(nodes.values())]\n c.execute(\"SELECT * FROM nodes ORDER BY RANDOM() LIMIT 1\")\n query = c.fetchone()#bude cakat kym dostanem addr od con aby som dostal nove adresy!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n if query == None:\n return\n line = (query[0], query[1])\n if line not in node_list and line not in ban_list:\n logging.debug(f\"connectujem: {line}\")\n outbound.put([\"connect\", [line[0], line[1], send_message(\"version1\", cargo=line[0])]])\n con_sent = True\n\ndef start_mining():\n block_header, txs = blockchain.build_block()\n to_mine.put([block_header, txs])\n\n\ndef main():\n global sync, mining, con_sent, blockchain, stime, prev_time, num_time\n blockchain = Blockchain(version, send_message, sync, ui_in, logging)\n local_node = threading.Thread(target=p2p.start_node, args=(port, nodes, inbound, outbound, ban_list, logging))\n tui = threading.Thread(target=ui.main, args=(blockchain.pub_keys, ui_in, ui_out, blockchain.public_key_hex, nodes, sync))\n local_node.start()\n tui.start()\n\n c.execute(\"SELECT count(name) FROM sqlite_master WHERE type='table' AND name='nodes'\")\n if c.fetchone()[0] != 1:\n c.execute(\"\"\"CREATE TABLE nodes (\n addr TEXT,\n port INTEGER,\n timestamp INTEGER)\n \"\"\")\n\n print(\"finding nodes...\")\n c.execute(\"SELECT * FROM nodes;\")\n if c.fetchall() == []:\n for i in hardcoded_nodes:\n sent = None\n outbound.put([\"connect\", [i[0], i[1], send_message(\"version1\", cargo=i[0])]])\n started = int(time())\n while True:\n if not inbound.empty():\n soc, message = inbound.get()\n if message == \"error\":\n logging.debug(\"error\")\n break\n handle_message(soc, message)\n if message[:24] == \"000000000000000061646472\":\n logging.debug(\"msg je addr\")\n break\n if int(time()) - started > 10:\n logging.debug(\"prekroceny cas\")\n break\n if len(nodes) != 0:\n outbound.put([\"close\", list(nodes.values())[0].address])\n c.execute(\"SELECT * FROM nodes;\")\n if len(c.fetchall()) >= 8:\n outbound.put([\"close\", list(nodes.values())[0].address])\n break#treba zatvorit conection\n\n try:\n while True:\n if len(nodes) < opt_nodes:\n if len(nodes) == 0 and int(time()) % 5 == 0 and int(time()) != prev_time:\n prev_time = int(time())\n c.execute(\"SELECT * FROM nodes;\")\n logging.debug(f\"con_sent: {con_sent}\")\n logging.debug(c.fetchall())\n if not con_sent:\n connect()#mozno by bolo lepsie spravit init connect v loope pred tymto\n if not inbound.empty():\n soc, message = inbound.get()\n if message == \"error\":\n c.execute(\"DELETE FROM nodes WHERE addr=(?) AND port=(?)\", (soc[0], soc[1]))\n conn.commit()\n con_sent = False\n else:\n handle_message(soc, message)\n if not mined.empty():\n new_block = mined.get()\n logging.debug(f\"new block mined: {new_block}\")\n new_block_hash = blockchain.hash(new_block[:216])\n if blockchain.append(new_block, sync[0]) == True:\n message = \"01\" + new_block_hash\n send_message(\"broadcast\", cargo=[message, \"headers\"])\n ui_in.put([\"mined\", int(time())])\n else:\n logging.debug(\"block neappendnuty\")\n start_mining()\n if int(time()) - stime > 1800:\n print(\"time ta pecka\")\n num_time += 1\n current_time = int(time())\n for tx in blockchain.valid_tx:\n if not -1800 <= current_time - int(tx[-264:-256], 16) <= 1800:\n blockchain.valid_tx.remove(tx)\n for i in list(nodes.values()):\n c.execute(\"UPDATE nodes SET timestamp = (?) WHERE addr = (?) AND port = (?);\", (i.lastrecv, i.address[0], i.port))\n if current_time - i.lastrecv > 5400:\n outbound.put([\"close\", i.address])\n elif current_time - i.lastsend > 1800:\n print(\"time active\")\n send_message(\"only\", soc=nodes[i.socket.getpeername()].socket, cargo=\"active\")\n if num_time == 48:\n send_message(\"addr\", cargo=\"broadcast\")\n c.execute(\"SELECT MAX(rowid) FROM nodes;\")\n rowid = c.fetchone()[0]\n if len(nodes) >= 3 and rowid > 1000:\n c.execute(\"DELETE FROM nodes WHERE timestamp<(?)\", (stime, ))\n num_time = 0\n stime = int(time())\n conn.commit()\n if not sync[0]:\n if sync[1] != 0 and int(time()) - sync[1] > 30:\n ban_check(sync[2])\n sync = [True, 0, 0]\n ui_in.put([\"sync_t\", \"\"])\n if not tui.is_alive():\n print(\"dead\")\n outbound.put([\"end\", []])\n local_node.join()\n ui_in.put([\"end\", \"\"])\n tui.join()\n if mining:\n mining.terminate()\n break\n if not ui_out.empty():\n a, b = ui_out.get()\n logging.debug(f\"cli a: {a}\")\n logging.debug(f\"cli b: {b}\")\n if a == \"con\":\n b, d = b\n outbound.put([\"connect\", [b, d, send_message(\"version1\", cargo=b)]])\n elif a == \"send\":\n receiver_key, msg, msg_type = b\n if msg_type:\n msg_type = \"01\"\n else:\n msg_type = \"02\"\n cargo = [msg, receiver_key, msg_type]\n send_message(\"send\", cargo=cargo)\n elif a == \"import\":\n b, d = b\n blockchain.save_key(b, d)\n cargo = [\"\", b, \"00\"]\n send_message(\"send\", cargo=cargo)\n elif a == \"edit\":\n pub_key, new_name = b\n blockchain.edit_key_file(pub_key, new_name, 1)\n elif a == \"lsnodes\":\n display.put(list(nodes.values()))\n elif a == \"start mining\":\n if not sync[0]:\n ui_in.put([\"warning\", \"Ešte niesi synchronizovaný zo sieťou\"])\n continue\n ui_in.put([\"warning\", \"Začal si ťažiť\"])\n start_mining()\n mining = Process(target=mine, args=(mined, to_mine))\n mining.start()\n elif a == \"stop mining\":\n if mining:\n mining.terminate()\n mining = None\n elif a == \"nodesdb\":\n current_time = int(time())\n c.execute(\"SELECT * FROM nodes\")\n nod = c.fetchall()\n for i in nod:\n print(f\"address: {i[0]}, port: {i[1]}, from last time: {current_time-i[2]}\")\n elif a == \"highest\":\n blockchain.c.execute(\"SELECT rowid,* FROM blockchain WHERE rowid = (SELECT MAX(rowid) FROM blockchain);\")\n row = blockchain.c.fetchone()\n print(f\"height: {row[0]}\")\n print(f\"block hash: {row[1]}\")\n print(f\"block: {row[2]}\")\n elif a == \"end\":\n outbound.put([\"end\", []])\n local_node.join()\n ui_in.put([\"end\", \"\"])\n tui.join()\n if mining:\n mining.terminate()\n break\n\n except:\n logging.error(traceback.format_exc())\n if mining:\n mining.terminate()\n print(\"crash daco sa pokazilo!!!!!!!!!!!!!!!!!!!!!!!!\")\n outbound.put([\"end\", []])\n local_node.join()\n ui_in.put([\"end\", \"\"])\n tui.join()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":28183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"311194786","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom rest_framework.exceptions import PermissionDenied\n\nfrom enreda_app.forms.contrato import ContratoCreateForm, ContratoEditForm\nfrom enreda_app.models import Licitacion, Contrato\n\n\n@login_required\ndef create(request):\n if request.method == \"GET\":\n return render(request, 'contrato/create.html', {'form': ContratoCreateForm()})\n elif request.method == \"POST\":\n form = ContratoCreateForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/')\n else:\n return render(request, 'contrato/create.html', {'form': form})\n else:\n # Another request method\n raise PermissionDenied\n\n\n@login_required\ndef edit(request, pk):\n contrato = get_object_or_404(Contrato, pk=pk)\n\n data = {'nombre': contrato.nombre,\n 'fecha': contrato.fecha,\n 'licitacion': contrato.licitacion, }\n\n if request.method == \"GET\":\n form = ContratoEditForm(initial=data)\n return render(request, 'contrato/edit.html', {'form': form})\n elif request.method == \"POST\":\n form = ContratoEditForm(request.POST, initial=data)\n if form.is_valid():\n contrato.nombre = form.cleaned_data[\"nombre\"]\n licitacion = get_object_or_404(Licitacion, id=form.cleaned_data[\"licitacion\"])\n contrato.licitacion = licitacion\n contrato.save()\n return HttpResponseRedirect('/')\n else:\n return render(request, 'contrato/edit.html', {'form': form})\n else:\n raise PermissionDenied\n\n\n@login_required\ndef delete(request, pk):\n contrato = get_object_or_404(Contrato, pk=pk)\n contrato.delete()\n contratos = Contrato.objects.all()\n return render(request, 'contrato/list.html', {'contratos': contratos})\n\n\n@login_required\ndef view(request, pk):\n contrato = get_object_or_404(Contrato, pk=pk)\n return render(request, 'contrato/view.html', {'contrato': contrato})\n\n\n@login_required\ndef list(request):\n contratos = Contrato.objects.all()\n return render(request, 'contrato/list.html', {'contratos': contratos})\n","sub_path":"enreda_project/enreda_app/controllers/contrato.py","file_name":"contrato.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"42220226","text":"#coding=utf-8\nimport shutil\nimport os\nimport sys\nimport re\n# import logging\nimport subprocess\nimport plistlib\nimport pprint\nimport time\nimport json\nimport tempfile\nimport rtool.utils as utils\n\n# def create_logger(name):\n# # create logger with 'spam_application'\n# logger = logging.getLogger(name)\n# logger.setLevel(logging.DEBUG)\n# # create file handler which logs even debug messages\n# fh = logging.FileHandler(name+'.log')\n# fh.setLevel(logging.DEBUG)\n# # create console handler with a higher log level\n# ch = logging.StreamHandler()\n# ch.setLevel(logging.DEBUG)\n# # create formatter and add it to the handlers\n# formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n# fh.setFormatter(formatter)\n# ch.setFormatter(formatter)\n# # add the handlers to the logger\n# logger.addHandler(fh)\n# logger.addHandler(ch)\n# return logger\n\nclass JobInterface(object):\n \"\"\"定义一个可执行的任务\"\"\"\n\n def __init__(self):\n self.finished = False\n self.started = False\n\n def start(self):\n \"\"\"启动任务\"\"\"\n raise NotImplementedError( \"Should have implemented this\")\n\n def isFinished(self):\n \"\"\"检查任务是否结束\"\"\"\n raise NotImplementedError( \"Should have implemented this\")\n\n def isSucceeded(self):\n \"\"\"当任务结束后,检查任务是否执行成功\"\"\"\n raise NotImplementedError( \"Should have implemented this\")\n\n def getOutput(self):\n \"\"\"当任务结束后,返回任务的输出\"\"\"\n raise NotImplementedError( \"Should have implemented this\")\n\n def __str__(self):\n raise NotImplementedError( \"Should have implemented this\")\n\nclass RunnableShellCommandJob(JobInterface):\n def __init__(self,args):\n JobInterface.__init__(self)\n self.args = args\n self.stdout = None\n self.process = None\n self.returncode = None\n self.output = None\n\n def start(self):\n self.stdout = f = tempfile.TemporaryFile()\n self.process = subprocess.Popen(self.args,stdout=f, stderr=f, stdin=subprocess.PIPE)\n self.started = True\n\n def isFinished(self):\n if not self.started:\n return False\n if not self.finished:\n self.returncode = self.process.poll()\n if self.returncode == None:\n return False\n\n self.finished = True\n self.stdout.seek(0)\n self.output = self.stdout.read()\n self.stdout.close()\n\n return True\n\n def isSucceeded(self):\n return self.returncode == 0\n\n def getOutput(self):\n return self.output\n\n def __str__(self):\n return ' '.join(self.args)\n\n\nclass MultiProcessRunner():\n \"\"\"用多进程执行任务的类\n\n Usage:\n\n mpr = MultiProcessRunner(process_count=8)\n jobs = [RunnableShellCommandJob(['ls','/']),RunnableShellCommandJob(['ls','/Users'])]\n failed_jobs = mpr.run_jobs(jobs)\n for job in failed_jobs:\n print job.getOutput()\n \"\"\"\n\n def __init__(self,process_count=8):\n \"\"\"初始化,通过process_count 参数指定最多使用的进程数量\"\"\"\n self.process_count = process_count\n self.disable_print = os.environ.get('disable_print','0')\n self.process_info = {}\n #self.logger = create_logger('MultiProcessRunner')\n self.logger = utils.getLogger('RES')\n\n def check_jobs(self,process_arr):\n \"\"\"检查正在执行的jobs,找出未执行完毕的jobs和执行失败的jobs\"\"\"\n unfinished_process_arr = []\n failed_process_arr = []\n for job in process_arr:\n if job.isFinished():\n if not job.isSucceeded():\n failed_process_arr.append(job)\n else:\n unfinished_process_arr.append(job)\n return unfinished_process_arr,failed_process_arr\n\n\n def run_jobs(self,jobs):\n \"\"\"执行 jobs(JobInterface类),返回 执行失败的jobs数组\"\"\"\n # self.logger.info('start tp jobs')\n process_arr = []\n all_failed_process_arr = []\n job_total_count = len(jobs)\n while len(jobs) > 0 or len(process_arr) > 0:\n job_remain_count = len(jobs)\n job_running_count = len(process_arr)\n job_failed_count = len(all_failed_process_arr)\n if job_remain_count > 0 and job_running_count < self.process_count:\n job = jobs.pop()\n if self.disable_print != '1':\n self.logger.debug('total jobs %d , %d jobs remain, %d running, %d failed'%(job_total_count,job_remain_count,job_running_count,job_failed_count))\n self.logger.debug('start job %s'%(job))\n job.start()\n process_arr.append(job)\n\n unfinished_process_arr,failed_process_arr = self.check_jobs(process_arr)\n all_failed_process_arr.extend(failed_process_arr)\n process_arr = unfinished_process_arr\n #pprint.pprint(process_arr)\n time.sleep(0.05)\n\n self.logger.info('finish tp jobs')\n return all_failed_process_arr\n\n\nclass JobList(list):\n def __init__(self):\n list.__init__(self)\n\n def show(self):\n for i in self:\n print(i)\n\n def run(self,process_count = None):\n if process_count == None:\n import multiprocessing\n process_count = multiprocessing.cpu_count()\n mpr = MultiProcessRunner(process_count=process_count)\n failed_jobs = mpr.run_jobs(self)\n return failed_jobs\n","sub_path":"rtool/taskplugin/plugin/MultiProcessRunner.py","file_name":"MultiProcessRunner.py","file_ext":"py","file_size_in_byte":5639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"598694355","text":"###########################################################\n##### Managing Static and External Pages Microservices ####\n###########################################################\n\nimport settings\nfrom controller.healthservicehandler import HandleService\n\n# Microservice URL\nservice_url = settings.pages_server_name\n\nclass ManagePageService(HandleService):\n\n def __init__(self):\n self.create_service_url\n \n # List services\n services = [\n 'add_page',\n 'retrieve_page_html',\n 'set_page_markdown',\n 'list_pages'\n ]\n\n \n def create_service_url(self):\n count = 0\n total_service_list = len(self.services)\n while count < total_service_list:\n self.services[count] = service_url + self.services[count]\n count += 1\n return self.services","sub_path":"healthchecks/services/manage_pages.py","file_name":"manage_pages.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"518970040","text":"import numpy as np\nimport pandas as pd\nimport math\nimport time\nimport matplotlib.pyplot as plt\n\ndef RunningMedian(mouseframe, h):\n\tDistance = mouseframe[\"Distance moved\"]\n\tTime = mouseframe[\"Time\"]\n\tXold = mouseframe[\"X\"]\n\tYold = mouseframe[\"Y\"]\n\tXnew = np.zeros(len(mouseframe))\n\tYnew = np.zeros(len(mouseframe))\n\tsegmenttype = np.full(len(mouseframe), \"Moving\")\n\tfor i in range(0, len(mouseframe)):\n\t\tif (i < h):\n\t\t\tXnew[i] = np.nan\n\t\t\tYnew[i] = np.nan\n\t\t\tsegmenttype[i] = np.nan\n\t\tif (i >= h):\n\t\t\tXnew[i] = mouseframe[\"X\"][(i-h):(i+h)].median()\n\t\t\tYnew[i] = mouseframe[\"Y\"][(i-h):(i+h)].median()\n\t\t\tif (((Xnew[i] == Xnew[i-1]) & (Ynew[i] == Ynew[i-1])) == True):\n\t\t\t\tsegmenttype[i] = \"Arrest\"\n\t\t\tif (((Xnew[i] == Xnew[i-1]) & (Ynew[i] == Ynew[i-1])) == False):\n\t\t\t\tsegmenttype[i] = \"Moving\"\n\t\tif (i > (len(mouseframe)-h)):\n\t\t\tXnew[i] = np.nan\n\t\t\tYnew[i] = np.nan\n\t\t\tsegmenttype[i] = np.nan\n\tXnew = pd.DataFrame(Xnew)\n\tYnew = pd.DataFrame(Ynew)\n\tsegmenttype = pd.DataFrame(segmenttype)\n\tmouseRM = pd.concat([Time, Xold, Yold, Xnew, Ynew, segmenttype, Distance], axis=1)\n\tmouseRM.columns = [\"Time\", \"Xold\", \"Yold\", \"X\", \"Y\", \"Segment Type\", \"Distance moved\"]\n\treturn mouseRM\n\t\ndef Activity(mouseframe2, number):\n\tdistancemoved = np.zeros(number)\n\ttimespentmoving = np.zeros(number)\n\ttimepoints = np.zeros(number)\n\tp = 0\n\tq = 0\n\tcounter = 0\n\tvalue = 0\n\tfor i in range(0, number):\n\t\tif (i == 0):\n\t\t\tif (mouseframe2[\"Segment Type\"][i] == \"Moving\"):\t\n\t\t\t\tdistancemoved[p] = distancemoved[p] + mouseframe2[\"Distance moved\"][i]\n\t\tif (i > 0):\n\t\t\tif (mouseframe2[\"Segment Type\"][i] == \"Moving\"):\t\n\t\t\t\tdistancemoved[p] = distancemoved[p] + mouseframe2[\"Distance moved\"][i]\n\t\t\tif ((mouseframe2[\"Segment Type\"][i] == \"Moving\") & (value == 0)):\t\n\t\t\t\ttimestart = mouseframe2[\"Time\"][i]\n\t\t\t\ttimepoints[p] = timestart\n\t\t\t\tvalue = 1\n\t\t\tif ((mouseframe2[\"Segment Type\"][i] != \"Moving\") & (mouseframe2[\"Segment Type\"][i-1] == \"Moving\")):\n\t\t\t\ttimeend = mouseframe2[\"Time\"][i]\n\t\t\t\ttimespentmoving[p] = timeend - timestart\n\t\t\t\tp = p+1\n\t\t\t\tcounter = counter + 1\n\t\t\t\tvalue = 0\n\tdistancemoved = distancemoved[0:counter]\n\tdistancemoved = pd.DataFrame(distancemoved)\n\ttimespentmoving = timespentmoving[0:counter]\n\ttimespentmoving = pd.DataFrame(timespentmoving)\n\ttimepoints = timepoints[0:counter]\n\ttimepoints = pd.DataFrame(timepoints)\n\tActivityBouts = pd.concat([timepoints, timespentmoving, distancemoved], axis=1)\n\tActivityBouts.columns = [\"SecondsAfterStart\", \"Time moving\", \"Distance moved\"]\n\tActivityBouts[\"SecondsAfterStart\"] = ActivityBouts[\"SecondsAfterStart\"] / 3600\n\tActivityBouts.columns = [\"HoursAfterStart\", \"Time moving\", \"Distance moved\"]\n\treturn ActivityBouts\n\t\t\ndef Frequency2(inputframe):\n\tminimum = -10\n\tminimum = round(minimum)-1\n\tmaximum = inputframe[\"Distance moved\"].max()\t\n\tmaximum = 12\n\tinterval = 0.1;\n\tdivider = int(1/interval)\n\tvaluesrange = int((maximum-minimum+1)*divider)\n\tx = np.zeros(int((maximum-minimum+1)*divider))\n\ty = np.zeros(int((maximum-minimum+1)*divider))\n\trangeStart = minimum-interval;\n\trangeEnd = minimum;\n\tfor i in range(0, (valuesrange)):\n\t\ttemp = np.array(inputframe[\"Distance moved\"][(inputframe[\"Distance moved\"] > rangeStart) & (inputframe[\"Distance moved\"] < rangeEnd)])\n\t\tnumber = int(len(temp))\n\t\ty[i] = number\n\t\tx[i] = rangeEnd\n\t\trangeStart = rangeStart+interval;\n\t\trangeEnd = rangeEnd+interval\n\n\tx = pd.DataFrame(x)\n\ty = pd.DataFrame(y)\n\tFrequencyDistribution = pd.concat([x, y], axis=1)\n\tFrequencyDistribution.columns = [\"Distance\", \"Frequency\"]\t\n\treturn FrequencyDistribution\n\t\nAnimalID = \"PH00313\"\nTreatment = \"6 month\"\t\n\nmouse = pd.read_csv(\"G:/Inputs/6 month/\" + AnimalID + \".txt\", sep=\";\", header=36, na_values=[\"-\", \"s\", \"s?\", \"cm\", \"cm?\", \"cm/s\", \"cm/s?\"])\nmouseAcc = mouse[[\"Recording time\", \"X center\", \"Y center\", \"Distance moved\"]]\nmouseAcc.columns = [\"Time\", \"X\", \"Y\", \"Distance moved\"]\nmouseAcc = mouseAcc.drop(mouseAcc.index[0])\nmouseAcc = mouseAcc.reset_index()\ndel mouseAcc[\"index\"]\ndel mouse\n\n\nstart = time.time()\nmouseAccI = RunningMedian(mouseAcc, 450)\nend = time.time()\nelapsed = (end-start) / 60\nprint(elapsed)\ndel mouseAcc\nmouseAccI.to_csv(\"E:/RMreportindexmethodv450.csv\")\nAccrownumbers = int(len(mouseAccI))\nmouseSeg = Activity(mouseAccI, Accrownumbers)\nmouseSeg.to_csv(\"E:/MouseSegAfterRMv450.csv\")\n\nmouse = mouseSeg\nmouse[\"Distance moved\"] = np.log2(mouse[\"Distance moved\"])\ndel mouseSeg\nNewFreq = Frequency2(mouse)\nNewFreq = NewFreq.sort_values([\"Distance\"], ascending=True)\nNewFreq = NewFreq.reset_index()\ndel NewFreq[\"index\"]\nNewFreq.to_csv(\"E:/\" + AnimalID + \"FreqAfterRMvaluesv450.csv\")\n\nplt.figure(figsize=(12, 6))\nplt.plot(NewFreq[\"Distance\"], NewFreq[\"Frequency\"])\nplt.title(AnimalID + \" - C57 (\" + Treatment + \") - Frequency Distribution of ActivityBoutsv1 (log2 intervals of 0.1) 30seconds\")\nplt.xlabel(\"Log2 of Distance (cm)\", fontsize=18)\nplt.xticks([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])\nplt.yticks([0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000])\nplt.ylabel(\"Frequency\", fontsize=18)\nplt.savefig(\"E:/\" + AnimalID + \"FreqDist30seconds.png\")\nplt.clf()\ndel mouse, NewFreq, Accrownumbers\n\n\nmouseAccI = RunningMedian(mouseAccI, 300)\nmouseAccI.to_csv(\"E:/RMreportindexmethodv300.csv\")\n\nAccrownumbers = int(len(mouseAccI))\nmouseSeg = Activity(mouseAccI, Accrownumbers)\nmouseSeg.to_csv(\"E:/MouseSegAfterRMv300.csv\")\nmouse = mouseSeg\nmouse[\"Distance moved\"] = np.log2(mouse[\"Distance moved\"])\ndel mouseSeg\nNewFreq = Frequency2(mouse)\nNewFreq = NewFreq.sort_values([\"Distance\"], ascending=True)\nNewFreq = NewFreq.reset_index()\ndel NewFreq[\"index\"]\nNewFreq.to_csv(\"E:/\" + AnimalID + \"FreqAfterRMvaluesv300.csv\")\n\nplt.figure(figsize=(12, 6))\nplt.plot(NewFreq[\"Distance\"], NewFreq[\"Frequency\"])\nplt.title(AnimalID + \" - C57 (\" + Treatment + \") - Frequency Distribution of ActivityBoutsv2 (log2 intervals of 0.1) 20seconds\")\nplt.xlabel(\"Log2 of Distance (cm)\", fontsize=18)\nplt.xticks([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])\nplt.yticks([0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000])\nplt.ylabel(\"Frequency\", fontsize=18)\nplt.savefig(\"E:/\" + AnimalID + \"FreqDist20seconds.png\")\nplt.clf()\ndel mouse, NewFreq, Accrownumbers\n\nmouseAccI = RunningMedian(mouseAccI, 150)\nmouseAccI.to_csv(\"E:/RMreportindexmethod150.csv\")\n\nAccrownumbers = int(len(mouseAccI))\nmouseSeg = Activity(mouseAccI, Accrownumbers)\nmouseSeg.to_csv(\"E:/MouseSegAfterRMv150.csv\")\nmouse = mouseSeg\nmouse[\"Distance moved\"] = np.log2(mouse[\"Distance moved\"])\ndel mouseSeg\nNewFreq = Frequency2(mouse)\nNewFreq = NewFreq.sort_values([\"Distance\"], ascending=True)\nNewFreq = NewFreq.reset_index()\ndel NewFreq[\"index\"]\nNewFreq.to_csv(\"E:/\" + AnimalID + \"FreqAfterRMvalues150.csv\")\n\nplt.figure(figsize=(12, 6))\nplt.plot(NewFreq[\"Distance\"], NewFreq[\"Frequency\"])\nplt.title(AnimalID + \" - C57 (\" + Treatment + \") - Frequency Distribution of ActivityBoutsv3 (log2 intervals of 0.1) 10seconds\")\nplt.xlabel(\"Log2 of Distance (cm)\", fontsize=18)\nplt.xticks([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])\nplt.yticks([0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000])\nplt.ylabel(\"Frequency\", fontsize=18)\nplt.savefig(\"E:/\" + AnimalID + \"FreqDist10seconds.png\")\nplt.clf()\ndel mouse, NewFreq, Accrownumbers\n\nmouseAccI = RunningMedian(mouseAccI, 150)\nmouseAccI.to_csv(\"E:/RMreportindexmethodv10secondsv2.csv\")\n\nAccrownumbers = int(len(mouseAccI))\nmouseSeg = Activity(mouseAccI, Accrownumbers)\nmouseSeg.to_csv(\"E:/MouseSegAfterRMv150v2.csv\")\nmouse = mouseSeg\nmouse[\"Distance moved\"] = np.log2(mouse[\"Distance moved\"])\ndel mouseSeg\nNewFreq = Frequency2(mouse)\nNewFreq = NewFreq.sort_values([\"Distance\"], ascending=True)\nNewFreq = NewFreq.reset_index()\ndel NewFreq[\"index\"]\nNewFreq.to_csv(\"E:/\" + AnimalID + \"FreqAfterRMvaluesv150v2.csv\")\n\nplt.figure(figsize=(12, 6))\nplt.plot(NewFreq[\"Distance\"], NewFreq[\"Frequency\"])\nplt.title(AnimalID + \" - C57 (\" + Treatment + \") - Frequency Distribution of ActivityBoutsv4 (log2 intervals of 0.1) 10secondsv2\")\nplt.xlabel(\"Log2 of Distance (cm)\", fontsize=18)\nplt.xticks([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])\nplt.yticks([0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000])\nplt.ylabel(\"Frequency\", fontsize=18)\nplt.savefig(\"E:/\" + AnimalID + \"FreqDist10secondsv2.png\")\nplt.clf()\ndel mouse, NewFreq, Accrownumbers","sub_path":"RMsylics.py","file_name":"RMsylics.py","file_ext":"py","file_size_in_byte":8563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"248263823","text":"def search(nums,left,right,target):\n if(left==right):\n if(nums[left]==target):\n return left\n else:\n return -1\n else:\n mid=(left+right)//2+1\n if(nums[mid]target):\n return search(nums,left,mid,target)\n else:\n return mid\n \nstr=input()\ntarget=eval(input())\nnums=eval(str)\nprint(search(nums,0,len(nums),target))","sub_path":"Code/CodeRecords/2606/60778/243453.py","file_name":"243453.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"249983997","text":"from flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileAllowed, FileRequired\nfrom flask_login import current_user\nfrom wtforms import DecimalField, StringField, PasswordField, SubmitField, BooleanField, TextAreaField, IntegerField, DateField, SelectField, HiddenField, DecimalField, SelectMultipleField\nfrom wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Regexp, InputRequired\nfrom wtforms.ext.sqlalchemy.fields import QuerySelectField\nfrom flaskDemo import db\nfrom flaskDemo.models import Algorithm, Gene, Job, KNN_Model, Population, Pred_Result, RF_Model, SVR_Model, User\nfrom wtforms.fields.html5 import DateField\nfrom wtforms.fields import Field\nimport sys\n\ngene_names = Gene.query.with_entities(Gene.gene_name).distinct()\ngene_name_choices = [(row[0], row[0]) for row in gene_names]\n\npop_id = Population.query.with_entities(Population.population_id).distinct()\npop = [(row[0], row[0]) for row in pop_id]\n\nclass Add_Gene_Model(FlaskForm):\n genename = SelectField(\"Gene Name\", choices=gene_name_choices,\n validators=[InputRequired()]) #I used gene name to make it easier for\n #users to be able to search genes. Then with gene name, I can get the gene_id and add that to\n #the model table\n pop_id = SelectField(\"Population ID\", choices=pop,\n validators=[InputRequired()])\n cross_val = DecimalField(\"Cross Validation Value\",\n validators=[InputRequired()])\n\nclass KNN(Add_Gene_Model):\n neigbor = IntegerField(\"Neigbour\", validators=[DataRequired()])\n weight = StringField(\"Weight\", validators=[DataRequired(), Length(min=5, max=20)])\n p = IntegerField(\"P\", validators=[DataRequired()])\n submit = SubmitField(\"Add Gene Model\")\n\n def validate_genename(self, genename):\n gene = Gene.query.filter_by(gene_name=genename.data).first()\n knndb = KNN_Model.query.filter_by(gene_id=gene.gene_id).first()\n if knndb and (str(knndb.population_id) == str(self.pop_id.data)):\n raise ValidationError(\"There is a model for that gene and population\")\n\nclass RF(Add_Gene_Model):\n tree = IntegerField(\"Tree\", validators=[DataRequired()])\n submit = SubmitField(\"Add Gene Model\")\n \n def validate_genename(self, genename):\n gene = Gene.query.filter_by(gene_name=genename.data).first()\n rfdb = RF_Model.query.filter_by(gene_id=gene.gene_id).first()\n if rfdb and (str(rfdb.population_id) == str(self.pop_id.data)):\n raise ValidationError(\"There is a model for that gene and population\")\n\n\nclass SVR(Add_Gene_Model):\n kernel = StringField(\"Kernel\", validators=[DataRequired(), Length(min=1, max=20)])\n degree = IntegerField(\"Degree\", validators=[DataRequired()])\n c = DecimalField(\"C\", validators=[DataRequired()])\n submit = SubmitField(\"Add Gene Model\")\n\n def validate_genename(self, genename):\n gene = Gene.query.filter_by(gene_name=genename.data).first()\n svrdb = SVR_Model.query.filter_by(gene_id=gene.gene_id).first()\n if svrdb and (str(svrdb.population_id) == str(self.pop_id.data)):\n raise ValidationError(\"There is a model for that gene and population\")\n\nclass RegistrationForm(FlaskForm):\n firstname = StringField('First Name',\n validators=[DataRequired(), Length(min=2, max=20)])\n lastname = StringField('Last Name',\n validators=[DataRequired(), Length(min=2, max=20)])\n email = StringField('Email',\n validators=[DataRequired(), Email()])\n user_type = SelectField('Choose User Type',\n choices=[('Admin', 'Admin'),('Regular','Regular')],\n validators=[DataRequired()])\n password = PasswordField('Password', validators=[DataRequired()])\n confirm_password = PasswordField('Confirm Password',\n validators=[DataRequired(), EqualTo('password')])\n submit = SubmitField('Sign Up')\n\n def validate_email(self, email):\n user = User.query.filter_by(email=email.data).first()\n if user:\n raise ValidationError('That email is taken. Please choose a different one.')\n\n\nclass LoginForm(FlaskForm):\n email = StringField('Email',\n validators=[DataRequired(), Email()])\n password = PasswordField('Password', validators=[DataRequired()])\n remember = BooleanField('Remember Me')\n submit = SubmitField('Login')\n\n \nclass GeneModelForm(FlaskForm):\n genes = Gene.query.with_entities(Gene.gene_id, Gene.chromosome_no, Gene.gene_name, Gene.gene_type).order_by(Gene.gene_name)\n algorithms = Algorithm.query.with_entities(Algorithm.algorithm_id, Algorithm.algorithm_description).order_by(Algorithm.algorithm_description)\n populations = Population.query.with_entities(Population.population_id, Population.population_description).order_by(Population.population_description)\n\n genechoices = [(row[0], row[2]) for row in genes]\n algochoices = [(row[0],row[1]) for row in algorithms]\n popchoices = [(row[0],row[1]) for row in populations]\n\n gene = SelectMultipleField(\"Gene\", choices=genechoices, validators=[InputRequired()])\n algo = SelectField(\"Algorithm\", choices=algochoices, validators=[InputRequired()])\n pop = SelectMultipleField(\"Population\", choices=popchoices, validators=[InputRequired()])\n submit = SubmitField(\"Get Results\")\n\nclass GeneForm(FlaskForm):\n genes = Gene.query.with_entities(Gene.gene_id, Gene.chromosome_no, Gene.gene_name, Gene.gene_type).order_by(Gene.gene_name)\n genechoices = [(row[0], row[2]) for row in genes]\n gene = SelectField(\"Gene\", choices=genechoices, validators=[InputRequired()])\n submit = SubmitField(\"Submit\")\n\nclass UserDeleteForm(FlaskForm):\n users = User.query.with_entities(User.user_id, User.first_name, User.last_name, User.user_type).order_by(User.last_name)\n userchoices = [(row[0], row[2] + \", \" + row[1]) for row in users if row[3] == \"Regular\"]\n user = SelectField(\"Users\", choices=userchoices, coerce=int, validators=[InputRequired()])\n submit = SubmitField(\"Submit\")\n\n @classmethod\n def new(cls):\n # Instantiate the form\n form = cls()\n\n # Update the choices for the agency field\n users = User.query.with_entities(User.user_id, User.first_name, User.last_name, User.user_type).order_by(User.last_name)\n userchoices = [(row[0], row[2] + \", \" + row[1]) for row in users if row[3] == \"Regular\"]\n form.user.choices = userchoices\n return form\n\nclass UploadGene(FlaskForm):\n file = FileField(\"Upload Gene Model File\",\n validators=[FileRequired(),\n FileAllowed(['txt','gz'],\n 'Upload only text file or zipped text file')])\n submit = SubmitField(\"Upload\")\n\n\nknn_gene_id = KNN_Model.query.with_entities(KNN_Model.gene_id).distinct()\nknn_gene_choices = [(row[0], row[0]) for row in knn_gene_id]\n\n\nclass KNNDelete(FlaskForm):\n gene_id = SelectField(\"Gene\", choices=knn_gene_choices,\n validators=[DataRequired()])\n pop_id = SelectField(\"Population\", choices=pop, validators=[DataRequired()])\n submit = SubmitField(\"Delete\")\n\n\n\nrf_gene_id = RF_Model.query.with_entities(RF_Model.gene_id).distinct()\nrf_gene_choices = [(row[0], row[0]) for row in rf_gene_id]\n\n\nclass RFDelete(FlaskForm):\n gene_id = SelectField(\"Gene\", choices=rf_gene_choices,\n validators=[DataRequired()])\n pop_id = SelectField(\"Population\", choices=pop, validators=[DataRequired()])\n submit = SubmitField(\"Delete\")\n\n\nsvr_gene_id = SVR_Model.query.with_entities(SVR_Model.gene_id).distinct()\nsvr_gene_choices = [(row[0], row[0]) for row in svr_gene_id]\n\n\nclass SVRDelete(FlaskForm):\n gene_id = SelectField(\"Gene\", choices=svr_gene_choices,\n validators=[DataRequired()])\n pop_id = SelectField(\"Population\", choices=pop, validators=[DataRequired()])\n submit = SubmitField(\"Delete\")\n","sub_path":"FINAL-code/flaskDemo/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":8086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"608687287","text":"\n\n#calss header\nclass _CONFLAGRATION():\n\tdef __init__(self,): \n\t\tself.name = \"CONFLAGRATION\"\n\t\tself.definitions = [u'a large fire that causes a lot of damage', u'a large and violent event, such as a war, involving a lot of people: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_conflagration.py","file_name":"_conflagration.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"220916772","text":"from django.db import models\nfrom django.utils import timezone\nfrom django.template.defaultfilters import slugify\nfrom django.utils.text import slugify\nimport tweepy\nfrom tweepy.auth import AppAuthHandler\nfrom .secrets import TWITTER_API_KEY, TWITTER_API_SECRET\n\nclass Tweeprint(models.Model):\n\n class Meta:\n db_table = \"tweeprints\"\n ordering = [\"-date_added\"]\n \n CHOICES = [\n ('Animal Behavior and Cognition', 'Animal Behavior and Cognition'),\n ('Behavioural Neuroscience', 'Behavioural Neuroscience'),\n ('Biochemistry', 'Biochemistry'),\n ('Bioengineering', 'Bioengineering'),\n ('Bioinformatics', 'Bioinformatics'),\n ('Biophysics', 'Biophysics'),\n ('Cancer Biology', 'Cancer Biology'),\n ('Cell Biology', 'Cell Biology'),\n ('Cognitive Science', 'Cognitive Science'),\n ('Developmental Biology', 'Developmental Biology'),\n ('Ecology', 'Ecology'),\n ('Evolutionary Biology', 'Evolutionary Biology'),\n ('Genetics', 'Genetics'),\n ('Genomics', 'Genomics'),\n ('Immunology', 'Immunology'),\n ('Microbiology', 'Microbiology'),\n ('Molecular Biology', 'Molecular Biology'),\n ('Molecular Neuroscience', 'Molecular Neuroscience'),\n ('Motor Neuroscience', 'Motor Neuroscience'),\n ('Neuroscience', 'Neuroscience'),\n ('Paleontology', 'Paleontology'),\n ('Pathology', 'Pathology'),\n ('Pharmacology and Toxicology', 'Pharmacology and Toxicology'),\n ('Physiology', 'Physiology'),\n ('Plant Biology', 'Plant Biology'),\n ('Psychology', 'Psychology'),\n ('Psychophysics', 'Psychophysics'),\n ('Scientific Communication and Education', 'Scientific Communication and Education'),\n ('Synthetic Biology', 'Synthetic Biology'),\n ('Structural Biology', 'Structural Biology'),\n ('Systems Biology', 'Systems Biology'),\n ('Systems Neuroscience', 'Systems Neuroscience'),\n ('Zoology', 'Zoology'),\n\n ]\n\n name = models.CharField(max_length=300, blank=True)\n date_added = models.DateTimeField(default=timezone.now)\n link = models.URLField(unique=True)\n tweet_id = models.CharField(max_length=300, blank=True, null=True)\n tweet_text = models.CharField(max_length=1000, blank=True, null=True)\n tweet_json = models.JSONField(null=True, blank=True)\n category = models.CharField(max_length=300, choices=CHOICES)\n category_slug = models.SlugField(max_length=300, default=\"\", blank=True, null=True)\n score = models.IntegerField(default=0)\n url_ref = models.SlugField(blank=True, null=True, max_length=255)\n\n def __str__(self):\n return (f'{self.link} <{self.category}>')\n\n def get_tweet(self):\n auth = AppAuthHandler(TWITTER_API_KEY, TWITTER_API_SECRET)\n api = tweepy.API(auth)\n tweet = api.get_status(self.tweet_id, tweet_mode=\"extended\")\n try:\n self.tweet_text = tweet.retweeted_status.full_text\n except AttributeError:\n self.tweet_text = tweet.full_text\n self.tweet_json = tweet._json\n return tweet\n \n def update_tweet_json(self):\n self.save()\n \n\n def save(self, *args, **kwargs):\n if not self.date_added:\n self.date_added = timezone.now\n if not self.url_ref:\n if self.name:\n self.url_ref = slugify(self.name)\n self.tweet_id = self.link.split('/')[-1].split('?')[0]\n self.category_slug = slugify(self.category)\n self.get_tweet()\n super(Tweeprint, self).save(*args, **kwargs)\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"407110433","text":"#https://practice.geeksforgeeks.org/problems/minimum-spanning-tree/1\ndef minWt(wt,vis,V):\n mi = float(\"inf\")\n for node in range(V):\n if wt[node]graph[min_node][nbr]:\n weight[nbr] = graph[min_node][nbr]\n parent[nbr] = min_node\n return (sum(weight)) \n","sub_path":"Graph/minimum-spanning-tree.py","file_name":"minimum-spanning-tree.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"23574305","text":"\n# implementation of card game - Memory\n\n# http://www.codeskulptor.org/#user40_Z6pXyM646VxoniY.py\n\n\nimport simplegui\nimport random\n\n\n#===============================================================================\n# helper functions\n#===============================================================================\n\n\ndef create_memory_deck():\n l=list(range(0,8))\n l.extend(range(0,8))\n #return l.copy() #python3\n return l[:]\n \n\n#===============================================================================\n# Init globals\n#===============================================================================\n\n# constants\n_DECK_SIZE = 16\n_CANVAS_WIDTH = 800\n_CANVAS_HEIGHT = 100\n_CARD_FONT_SIZE = _CANVAS_HEIGHT/3\n_CARD_FONT_COLOR = \"White\"\n_CANVAS_WIDTH_STEP = _CANVAS_WIDTH / _DECK_SIZE\n_IS_GAME_OVER = 0\n\n# variables\n\n#\\param the_state\n# 0 : init game\n# 1 : 1 unexposed card\n# 2 : a pair of cards has been exposed\nthe_state = 0\n\n#\\param the_first_card_index\n# index of the first exposed card of the pair to guess on each turn\nthe_first_card_index = 0\nthe_second_card_index = 0\n\nturns = 0\nthe_deck = create_memory_deck()\nthe_exposed_deck = [False]*len(the_deck)\nassert(len(the_deck)==_DECK_SIZE)\nassert(len(the_exposed_deck)==_DECK_SIZE)\n\n\ngame_over = _DECK_SIZE # _IS_GAME_OVER if all the cards has been paired.\n\n\n#===============================================================================\n# more helper functions\n#===============================================================================\n\ndef new_game():\n global the_deck, the_exposed_deck, turns, the_state, game_over\n global the_first_card_index, the_second_card_index\n \n game_over = _DECK_SIZE\n the_state = 0\n turns = 0\n the_first_card_index = 0\n the_second_card_index = 0\n random.shuffle(the_deck)\n the_exposed_deck = [False]*len(the_deck)\n assert(len(the_exposed_deck)==_DECK_SIZE)\n\n#-------------------------------------------------------------------------------\n\n\n#===============================================================================\n# define event handlers\n#===============================================================================\n \n\ndef set_state():\n if the_state == 0:\n return 1\n elif the_state == 1:\n return 2\n else:\n return 1 \n\n#-------------------------------------------------------------------------------\n\ndef apply_game_rules(pos):\n \n global the_state, turns, game_over\n global the_exposed_deck\n global the_first_card_index, the_second_card_index\n\n index = pos[0] // _CANVAS_WIDTH_STEP\n\n if the_state == 1:\n # handle case: cards not paired in the previous turn\n if turns>0:\n if (the_deck[the_first_card_index] != \\\n the_deck[the_second_card_index]):\n the_exposed_deck[the_second_card_index] = False\n the_exposed_deck[the_first_card_index] = False\n #handle current turn\n turns+=1\n the_first_card_index = index\n the_exposed_deck[index] = True\n\n elif the_state == 2:\n the_second_card_index = index\n the_exposed_deck[index] = True\n # pair found\n if (the_deck[the_first_card_index] == the_deck[the_second_card_index]):\n game_over-=2\n \n#-------------------------------------------------------------------------------\n\ndef mouseclick(pos):\n\n global the_state\n\n # reset required after game over\n if game_over == _IS_GAME_OVER:\n return\n\n # ignore already exposed cards\n index = pos[0] // _CANVAS_WIDTH_STEP\n if the_exposed_deck[index] == True:\n return\n \n # setting the_state\n the_state = set_state()\n\n # actions per the_state\n apply_game_rules(pos)\n \n#-------------------------------------------------------------------------------\n \n# cards are logically 50x100 pixels in size \ndef draw(canvas):\n xcoord = _CANVAS_WIDTH_STEP / 2\n ycoord = _CANVAS_HEIGHT - _CARD_FONT_SIZE\n FILL_COLOR = \"Green\"\n LINE_COLOR = \"Black\"\n for index in xrange(0, len(the_deck)):\n assert(xcoord <= _CANVAS_WIDTH)\n if(the_exposed_deck[index]):\n canvas.draw_text(str(the_deck[index]), (xcoord, ycoord), \\\n _CARD_FONT_SIZE, _CARD_FONT_COLOR)\n else:\n canvas.draw_polygon([(xcoord, _CANVAS_HEIGHT), (xcoord, 0)], \n _CANVAS_WIDTH_STEP-2, \n FILL_COLOR, \n LINE_COLOR)\n xcoord += _CANVAS_WIDTH_STEP\n\n label.set_text(str(turns))\n\n\n#-------------------------------------------------------------------------------\n\n\n#===============================================================================\n# create frame & register event handlers\n#===============================================================================\n\n# create frame and add a button and labels\nframe = simplegui.create_frame(\"Memory\", _CANVAS_WIDTH, _CANVAS_HEIGHT)\n\nframe.add_button(\"Reset\", new_game)\nlabel = frame.add_label(\"Turns = 0\")\n# label = frame.add_label(\"Turns = \" + str(turns))\n\n# register event handlers\nframe.set_mouseclick_handler(mouseclick)\nframe.set_draw_handler(draw)\n\n#===============================================================================\n# main loop\n#===============================================================================\n\nnew_game()\nframe.start()\n\n# Always remember to review the grading rubric\n","sub_path":"language/courses/interactive_programming_with_python/projects/5.memory/memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":5485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"625327465","text":"#-*- coding: utf-8 -*-\r\nimport threading, time\r\nimport connect_db\r\nimport ko_gtts_test\r\nimport led_sensor\r\nimport light_sensor\r\n\r\n\r\n#드론의 on/off 상태 체크하는 쓰레드\r\ndef CheckOnOff(dr):\r\n try:\r\n global dr_status\r\n while(1):\r\n lock.acquire() #Lock 실행\r\n\r\n dr.ConnetDB('SELECT STATUS FROM DRONE_ON_OFF WHERE NAME=\"MI DRONE\"')\r\n result = dr.getOne()\r\n\r\n if result is not None:\r\n dr_status = result[0]\r\n print(dr_status)\r\n else:\r\n lock.release()\r\n break\r\n\r\n dr.DisconnetDB()\r\n\r\n lock.release() #Lock 해제\r\n time.sleep(5)\r\n\r\n except Exception as e:\r\n print(\"e: \", e)\r\n\r\n finally:\r\n dr_status = None\r\n dr.DisconnetDB()\r\n print(\"dr_status db를 종료합니다.\")\r\n return\r\n\r\n###############################################################################################\r\n\r\n#조도 센서 및 LED 관리하는 쓰레드\r\ndef SensorAndLED(light, led):\r\n try:\r\n global dr_status\r\n while(1):\r\n lock.acquire() #드론의 상태를 체크하기전 Lock 실행\r\n\r\n if dr_status == \"ON\":\r\n result = light.rc_time()\r\n print(result)\r\n if result > 5000: #조도가 5000이상으로 어둡다면, LED On\r\n print(\"LED On\")\r\n led.LEDOn()\r\n else:\r\n print(\"LED Off\") #조도가 밝으면, LED Off\r\n led.LEDOff()\r\n\r\n elif dr_status == \"OFF\": #드론이 꺼져있으면, 강제 LED off\r\n led.LEDOff()\r\n elif dr_status == None: #Thread1이 종료된 상태라면(데이터베이스에 더이상 값이 없다면), Thread2 종료\r\n lock.release() # Lock 해제\r\n break\r\n\r\n lock.release() #Lock 해제\r\n\r\n except Exception as e:\r\n print(\"e: \", e)\r\n\r\n finally:\r\n light.CleanLight()\r\n led.CleanLED()\r\n return\r\n\r\n#################################################################################################\r\n\r\n#DB에 입력된 문장을 스피커로 출력하는 쓰레드\r\ndef DroneSpeaker(sp):\r\n try:\r\n global dr_status\r\n before = None\r\n while(1):\r\n sp.ConnetDB('SELECT Broadcast FROM DRONE_SPEAK WHERE Name=\"MI DRONE\"')\r\n lock.acquire() # 드론의 상태를 체크하기전 Lock 실행\r\n\r\n if dr_status == \"ON\": #드론이 작동중이면,\r\n lock.release() # Lock 해제\r\n result = sp.getOne() #출력할 문장 읽어오기\r\n if result is not None:\r\n if result[0] != before:\r\n #출력하기\r\n before = result[0]\r\n ko_gtts_test.TexttoSpeech_KO(result[0])\r\n\r\n elif dr_status != \"ON\": #Thread3 종료\r\n lock.release() # Lock 해제\r\n break\r\n\r\n\r\n\r\n except Exception as e:\r\n print(\"e: \", e)\r\n\r\n finally:\r\n sp.DisconnetDB()\r\n print(\"dr_speak db를 종료합니다.\")\r\n return\r\n\r\n#################################################################################################\r\n\r\n#인코딩 설정 실행\r\nko_gtts_test.init()\r\n\r\n#Lock 객체 선언\r\nlock = threading.Lock()\r\n\r\n#객체 및 변수 생성\r\ndr_status = False #드론의 상태를 체크하는 변수, glrobal 변수로 사용한다.\r\n#dr_status = \"ON\"\r\ndb_status = connect_db.DroneSQL()\r\nled = led_sensor.myLED(11) #LED 클래스 생성\r\nlight = light_sensor.myLight(7) #조도센서 클래스 생성\r\ndb_speak = connect_db.DroneSQL()\r\n\r\n# 메인 함수 실행하기############################################################################\r\nif __name__ == \"__main__\":\r\n #데이터베이스에서 드론의 상태를 주기적으로 받아오는 쓰레드\r\n th1 = threading.Thread(target=CheckOnOff, args=(db_status, ))\r\n #드론의 상태에 따라 조도센서와 LED 센서 동작하는 쓰레드\r\n th2 = threading.Thread(target=SensorAndLED, args=(light, led, ))\r\n #드론 스피커 출력하기\r\n th3 = threading.Thread(target=DroneSpeaker, args=(db_speak,))\r\n\r\n #쓰레드 실행\r\n th1.start()\r\n th2.start()\r\n th3.start()\r\n\r\n th1.join()\r\n th2.join()\r\n th3.join()\r\n\r\n\r\n print(\"all the program is finished\")\r\n\r\n\r\n\r\n","sub_path":"thread_test.py","file_name":"thread_test.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"41987687","text":"\"\"\" src.mixins.record \"\"\"\nfrom collections import OrderedDict\n\n\nclass Record:\n \"\"\"Record\"\"\"\n\n __repr_hide = [\"auth\", \"tokens_valid_after_timestamp\", \"password\"]\n __insert_hide = []\n\n @property\n def _repr_hide(self):\n return self.__repr_hide\n\n @_repr_hide.setter\n def _repr_hide(self, k):\n self.__repr_hide.append(k)\n\n @property\n def _insert_hide(self):\n return self.__insert_hide\n\n @_insert_hide.setter\n def _insert_hide(self, k):\n self.__insert_hide.append(k)\n\n def serialize(self, obj):\n \"\"\"serialize\"\"\"\n for k, v in obj.items():\n if k in self.__repr_hide:\n continue\n if k in self.__insert_hide:\n continue\n if k in self.__dict__.keys():\n setattr(self, k, v)\n return self\n\n def deserialize(self):\n \"\"\"deserialize\"\"\"\n result = OrderedDict()\n for k, _ in self.__dict__.items():\n if k in self._repr_hide:\n continue\n result[k] = getattr(self, k)\n\n return result\n\n def __repr__(self):\n vals = \", \".join(\n \"%s=%r\" % (n, getattr(self, n))\n for n, _ in self.__dict__.items()\n if n not in self._repr_hide\n )\n return \"<%s={%s}>\" % (self.__class__.__name__, vals)\n","sub_path":"src/mixins/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"72898354","text":"import psycopg2\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef addApos(string):\n return string.replace('\\'', '\\'\\'')\n\ncon = psycopg2.connect(database='lolsalestracker', user='lolsalestracker_admin2', password='abc123')\ncur = con.cursor()\n\ncur.execute(\"SELECT * FROM items WHERE champ=key\")\n\nrows = cur.fetchall()\n\nfor row in rows:\n champ_key = row[1].lower()\n url = \"http://gameinfo.na.leagueoflegends.com/en/game-info/champions/\" + champ_key + \"/\" \n data = requests.get(url)\n\n if data.status_code is not 200:\n print(\"Could not load: \" + url)\n continue\n\n soup = BeautifulSoup(data.text)\n img_container = soup.find('div', 'gs-container default-3-col')\n skins_containers = img_container.find_all('a')\n \n for skin_c in skins_containers:\n img_url = skin_c.get('href')\n title = skin_c.get('title')\n\n if title == \"\":\n title = row[3]\n\n cur.execute(\"SELECT * FROM items WHERE name='\" + addApos(title) + \"'\")\n matched_items = cur.fetchall()\n\n if len(matched_items) == 0:\n print(\"Could not find match for :\" + title)\n\n matched_item = matched_items[0]\n cur.execute(\"UPDATE items SET splash_url='\" + addApos(img_url) + \"' WHERE name='\" + addApos(title) + \"'\")\n\ncon.commit()\n\n#verify valid img URLS\ncur.execute(\"SELECT * FROM items\")\nitems = cur.fetchall()\nfor item in items:\n img_url = item[4]\n if img_url is None:\n print(item)\n else:\n data = requests.get(img_url)\n if data.status_code is not 200:\n print(\"Invalid request: \" + img_url)\n\ncon.close()\n","sub_path":"flask_server/splash_scrap_psql.py","file_name":"splash_scrap_psql.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"413940091","text":"import threading\nimport time\nimport serial\n\n\nclass Pedal_Thread(threading.Thread):\n def __init__(self, threadID):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.ser = serial.Serial('/dev/cu.usbmodem14141', 9600)\n self.stop = False\n self.last_digit = None\n\n\n def run(self):\n\n while not self.stop:\n\n read = self.ser.readline().decode(\"utf-8\")\n #print(read)\n if self.last_digit != read and read != \"\":\n self.last_digit = int(read)\n\n\n\n\n","sub_path":"pedal_thread.py","file_name":"pedal_thread.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"485614628","text":"__author__ = 'anna'\n\ndef censor(text, word):\n if word == '':\n return None\n else:\n index = None\n l = list(text)\n while text[len(text)-1] != \"*\":\n index = text.find(word)\n if index == -1:\n break\n else:\n l[index: index + len(word)] = '*' * len(word)\n print('l:', l)\n text = ''.join(l)\n return text\n\n\n\nprint(censor('banana', 'na'))\nprint(censor('kukushka', 'u'))\nprint(censor('kisamurysa', 'r'))\nprint(censor('kisamurysa', ''))\n","sub_path":"Codecademy/Python_course/censor.py","file_name":"censor.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"210467213","text":"import utils_tasks as utils\nimport hydra\nimport os\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef run_task(task):\n log.info(f\"Task name: {task.name}\")\n task_args = task.args if \"args\" in task else \"\"\n task_args = task_args.replace(\"$\\\\\", \"\\\\$\")\n command = f\"CUDA_VISIBLE_DEVICES={utils.WORKER_CUDA_DEVICE} HYDRA_CONFIG_PATH={task.config_path} {task.environ} python {task.command} repeat={task.repeat} {task_args}\"\n log.info(f\"Command: {command}\")\n ret = os.system(command)\n ret = str(ret)\n log.info(f'Task \"{task.name}\" finished with return code: {ret}.')\n return ret\n\n\n@hydra.main(config_path=os.environ[\"HYDRA_CONFIG_PATH\"])\ndef main(configs):\n auto_generated_dir = os.getcwd()\n os.chdir(hydra.utils.get_original_cwd())\n utils.run_tasks(configs, run_task)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/run_tasks_on_multiple_gpus.py","file_name":"run_tasks_on_multiple_gpus.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"81011332","text":"import json\r\nimport numpy as np\r\n\r\nfrom time import process_time\r\nfrom yellowbrick.classifier import ClassificationReport\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom supervised import plotting\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\n\r\ndef knn_learner(X_train, X_test, y_train, y_test, task, params_file):\r\n knn_learner = KNeighborsClassifier(n_neighbors=1, weights=\"uniform\")\r\n knn_learner_plot = plotting.plot_learning_curve(knn_learner, \"KNN Learner (default parameters)\", X_train, y_train, n_jobs=4)\r\n knn_learner_plot.show()\r\n knn_learner.fit(X_train, y_train)\r\n knn_learner_score = knn_learner.score(X_test, y_test)\r\n print('KNN learner score = ' + str(knn_learner_score))\r\n conf_mat = plotting.plot_conf_mat(knn_learner, X_test, y_test, \"KNN Learner Confusion Matrix (default)\")\r\n conf_mat.show()\r\n\r\n with open(params_file) as f:\r\n params = json.load(f)\r\n tuning_params = params['KNNLearner']['tuning']\r\n best_params = params['KNNLearner']['best']\r\n\r\n if task == 'grid_search':\r\n param_grid = {\"n_neighbors\": tuning_params['n_neighbors'],\r\n \"weights\": tuning_params['weights']}\r\n grid_search = GridSearchCV(knn_learner, param_grid=param_grid, scoring='accuracy', n_jobs=4, cv=10)\r\n grid_search.fit(X_train, y_train)\r\n print('Best params chosen by grid search....\\n')\r\n print(grid_search.best_params_)\r\n grid_best = grid_search.best_estimator_\r\n predictions = grid_best.predict(X_test)\r\n class_report = classification_report(y_test, predictions)\r\n print(class_report)\r\n knn_learner_plot = plotting.plot_learning_curve(grid_best, \"KNN Learner (Grid Search) \"+ str(grid_search.best_params_), X_train, y_train, n_jobs=4, cv=10)\r\n knn_learner_plot.show()\r\n #class_plot = plotting.plot_classification_report(class_report)\r\n knn_learner_tuned = grid_search.best_estimator_.fit(X_train, y_train)\r\n knn_learner_score = knn_learner_tuned.score(X_test, y_test)\r\n print('knn learner score (Grid Search) = ' + str(knn_learner_score))\r\n\r\n conf_mat = plotting.plot_conf_mat(knn_learner_tuned, X_test, y_test, \"KNN Learner Confusion Matrix (Grid Search)\")\r\n conf_mat.show()\r\n\r\n elif task == 'mca':\r\n knn_learner_tuned = KNeighborsClassifier(n_neighbors=best_params['n_neighbors'], weights=best_params['weights'])\r\n if len(tuning_params['n_neighbors']) != 1:\r\n tuning_param = 'n_neighbors'\r\n tuning_range = range(tuning_params[tuning_param][0], tuning_params[tuning_param][1])\r\n set_param = 'weights'\r\n elif len(tuning_params['weights']) != 1:\r\n tuning_param = 'weights'\r\n tuning_range = tuning_params['weights']\r\n set_param = 'n_neighbors'\r\n else:\r\n print('Error, no params have multiple tuning values... exiting')\r\n return\r\n title = 'Model Complexity Curve, ' + str(set_param) + '=' + str(best_params[set_param]) + ' varying ' + str(tuning_param)\r\n mcc = plotting.plot_validation_curve(knn_learner_tuned, title, X_train, y_train, param_name=tuning_param, param_range=tuning_range, n_jobs=None)\r\n mcc.show()\r\n\r\n elif task == 'plot_best':\r\n knn_learner_tuned = KNeighborsClassifier(n_neighbors=best_params['n_neighbors'], weights=best_params['weights'])\r\n fit_time_start = process_time()\r\n knn_learner_tuned.fit(X_train, y_train)\r\n fit_time_end = process_time()\r\n print(' KNN Learner (tuned) fit time: ' + str(fit_time_end-fit_time_start))\r\n\r\n predict_time_start = process_time()\r\n predictions = knn_learner_tuned.predict(X_test)\r\n predict_time_end = process_time()\r\n\r\n print(' KNN Learner (tuned) predict time: ' + str(predict_time_end-predict_time_start))\r\n\r\n class_report = classification_report(y_test,predictions)\r\n print(class_report)\r\n #class_plot = plot_classification_report(class_report)\r\n #class_plot.show()\r\n knn_learner_score = knn_learner_tuned.score(X_test, y_test)\r\n print('KNN learner best score = ' + str(knn_learner_score))\r\n knn_learner_plot_tuned = plotting.plot_learning_curve(knn_learner_tuned, \"KNN Learner (tuned) \" + str(best_params), X_train, y_train, n_jobs=4, cv=10)\r\n knn_learner_plot_tuned.show()\r\n\r\n conf_mat = plotting.plot_conf_mat(knn_learner_tuned, X_test, y_test, \"KNN Learner Confusion Matrix (tuned)\")\r\n conf_mat.show()\r\n\r\n else:\r\n print('Invalid task')\r\n return\r\n\r\n return","sub_path":"assignment_1/supervised/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"191936970","text":"from gevent import monkey\n\nmonkey.patch_all()\nfrom gevent.pool import Pool\nimport requests\nimport time\nfrom lxml import etree\nfrom queue import Queue\n\n\nclass QiuShi(object):\n def __init__(self):\n self.url = \"https://www.qiushibaike.com/text/page/{}\"\n self.header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36\"}\n self.queue = Queue()\n self.pool = Pool(5)\n self.is_running = True\n self.total_request_num = 0\n self.total_response_num = 0\n\n def cret_url(self, url):\n # 构建url管理器,生成url列表\n url_list = [url.format(i) for i in range(14)]\n # 使用线程池导入url链接\n for i in url_list:\n self.queue.put(i)\n self.total_request_num += 1\n # print(i)\n\n def parse_url(self, url):\n # 定义一个解析网址的方法\n response = requests.get(url, headers=self.header)\n return response.content.decode()\n\n def get_content(self, html_str):\n # 提取数据\n html = etree.HTML(html_str)\n # 使用xpath分析获取id为content-lest下的所有div标签,因为内容都存在这些标签里\n div_list = html.xpath(\"//div[@id='content-left']/div\")\n # 定义一个列表,存储用户名和内容\n cont_list = []\n # 然后遍历这个列表,从中提取出用户名和内容\n for div in div_list:\n cont_dict = {}\n cont_dict[\"作者\"] = div.xpath(\".//h2/text()\")[0].strip()\n cont_str = str([i.strip() for i in div.xpath(\".//div[@class='content']/span/text()\")]).replace(\"', '\", \"\")\n cont_dict[\"内容\"] = cont_str\n cont_list.append(cont_dict)\n return cont_list\n\n def save_data(self, cont_list):\n # 传入一个列表,然后遍历出来,\n for data in cont_list:\n print(data)\n\n # 进行一次url地址的请求和保存\n def execute_request_content_save(self):\n urli = self.queue.get()\n res = self.parse_url(urli)\n cont_list = self.get_content(res)\n # 4、筛选数据,保存数据\n self.save_data(cont_list)\n self.total_response_num += 1\n\n def _callback(self, temp):\n if self.is_running:\n self.pool.apply_async(self.execute_request_content_save, callback=self._callback)\n\n def run(self):\n # 1.获取url地址,\n url = self.url\n # 2.构建rul管理器,列表\n self.cret_url(url)\n # 3、发送url请求,获取数据\n for i in range(5):\n self.pool.apply_async(self.execute_request_content_save, callback=self._callback)\n while True:\n time.sleep(0.0001)\n if self.total_response_num >= self.total_request_num:\n self.is_running = False\n break\n\n\nif __name__ == '__main__':\n t1 = time.time()\n qiushi = QiuShi()\n qiushi.run()\n print(\"total cost:\", time.time() - t1)\n","sub_path":"糗事百科/qiubai协程.py","file_name":"qiubai协程.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"584981099","text":"\"\"\"desmondblog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom blog import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nadmin.autodiscover()\n\nurlpatterns = [\n url(r'^$', views.main_view),\n url(r'^home$', views.home_view, name=\"home\"),\n url(r'^profile$', views.profile_view, name=\"profile\"),\n url(r'^posts$', views.post_view, name=\"post\"),\n url(r'^posts/new/$', views.post_view_new, name=\"post_new\"),\n url(r'^posts/(?P[0-9]+)/$', views.post_details_view, name=\"post_details\"),\n url(r'^posts/(?P[0-9]+)/edit/$', views.post_edit, name='post_edit'),\n url(r'^posts/(?P[0-9]+)/edit/delete$', views.post_delete, name='post_delete'),\n url(r'^posts/(?P[0-9]+)/add_comment$', views.add_comment_to_post, name=\"add_comment_to_posts\"),\n url(r'^posts/(?P[0-9]+)/flag_comment$', views.flag_comment, name=\"flag_comment\"),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^ckeditor/', include('ckeditor.urls')),\n]\n","sub_path":"desmondblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"573876081","text":"# fast and stable connection\nimport asyncio\nimport inspect\nimport json\nimport re\nimport time\nimport traceback\nfrom asyncio.base_futures import _PENDING\nfrom asyncio.futures import Future\nfrom typing import Any, Awaitable, Callable, List, Optional, Union\nfrom weakref import WeakValueDictionary\n\nfrom aiohttp.client_exceptions import ClientError\nfrom aiohttp.http import WebSocketError, WSMsgType\nfrom torequests.dummy import NewResponse, Requests, Pool\nfrom torequests.utils import UA, quote_plus, urljoin\n\nfrom .base import ChromeDaemon, Tag\nfrom .logs import logger\n\"\"\"\nAsync utils for connections and operations.\n[Recommended] Use daemon and async utils with different scripts.\n\"\"\"\n\ntry:\n from asyncio.futures import TimeoutError\nexcept ImportError:\n # for python 3.8\n from asyncio.exceptions import TimeoutError\n\n\nasync def ensure_awaitable_result(callback_function, result):\n if callable(callback_function):\n callback_result = callback_function(result)\n else:\n return result\n if inspect.isawaitable(callback_result):\n return await callback_result\n else:\n return callback_result\n\n\nclass _TabConnectionManager(object):\n\n def __init__(self, tabs):\n self.tabs = tabs\n self.ws_connections = set()\n\n async def __aenter__(self) -> None:\n for tab in self.tabs:\n ws_connection = tab()\n await ws_connection.connect()\n self.ws_connections.add(ws_connection)\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n for ws_connection in self.ws_connections:\n if not ws_connection._closed:\n await ws_connection.shutdown()\n\n\nclass _WSConnection(object):\n\n def __init__(self, tab):\n self.tab = tab\n self._closed = None\n\n def __str__(self):\n return f'<{self.__class__.__name__}: {not self._closed}>'\n\n async def __aenter__(self):\n return await self.connect()\n\n async def connect(self):\n \"\"\"Connect to websocket, and set tab.ws as aiohttp.client_ws.ClientWebSocketResponse.\"\"\"\n try:\n session = await self.tab.req.session\n self.tab.ws = await session.ws_connect(\n self.tab.webSocketDebuggerUrl,\n timeout=self.tab.timeout,\n **self.tab.ws_kwargs)\n asyncio.ensure_future(self.tab._recv_daemon(), loop=self.tab.loop)\n logger.debug(\n f'[connected] {self.tab} websocket connection created.')\n except (ClientError, WebSocketError) as err:\n # tab missing(closed)\n logger.error(f'[missing] {self.tab} missing ws connection. {err}')\n # start the daemon background.\n return self.tab.ws\n\n async def shutdown(self):\n if self.tab.ws and not self.tab.ws.closed:\n await self.tab.ws.close()\n self._closed = self.tab.ws.closed\n self.tab.ws = None\n else:\n self._closed = True\n\n async def __aexit__(self, *args):\n await self.shutdown()\n\n def __del__(self):\n logger.debug(\n f'[disconnected] {self.tab!r} ws_connection closed[{self._closed}]')\n\n\nclass Tab(object):\n _log_all_recv = False\n\n def __init__(self,\n tab_id=None,\n title=None,\n url=None,\n webSocketDebuggerUrl=None,\n json=None,\n chrome=None,\n timeout=5,\n ws_kwargs=None,\n loop=None,\n **kwargs):\n tab_id = tab_id or kwargs.pop('id')\n if not tab_id:\n raise ValueError('tab_id should not be null')\n self.loop = loop\n self.tab_id = tab_id\n self.title = title\n self._url = url\n self.webSocketDebuggerUrl = webSocketDebuggerUrl\n self.json = json\n self.chrome = chrome\n self.timeout = timeout\n self._created_time = None\n self.ws_kwargs = ws_kwargs or {}\n self._closed = False\n self._message_id = 0\n self.ws = None\n if self.chrome:\n self.req = self.chrome.req\n else:\n self.req = Requests(loop=self.loop)\n self._listener = Listener()\n self._enabled_methods = set()\n\n def __hash__(self):\n return self.tab_id\n\n def __eq__(self, other):\n return self.__hash__() == other.__hash__()\n\n @property\n def status(self) -> str:\n status = 'disconnected'\n if self.ws and not self.ws.closed:\n status = 'connected'\n return status\n\n def connect(self) -> _WSConnection:\n '''`async with tab.connect:`'''\n self._enabled_methods.clear()\n return _WSConnection(self)\n\n def __call__(self) -> _WSConnection:\n '''`async with tab():`'''\n return self.connect()\n\n @property\n def msg_id(self):\n self._message_id += 1\n return self._message_id\n\n @property\n def url(self) -> str:\n \"\"\"The init url since tab created.\n `await self.current_url` for the current url.\n \"\"\"\n return self._url\n\n async def refresh_tab_info(self) -> bool:\n for tab in await self.chrome.tabs:\n if tab.tab_id == self.tab_id:\n self.tab_id = tab.tab_id\n self.title = tab.title\n self._url = tab.url\n self.webSocketDebuggerUrl = tab.webSocketDebuggerUrl\n self.json = tab.json\n return True\n return False\n\n async def activate_tab(self) -> Union[str, bool]:\n \"\"\"activate tab with chrome http endpoint\"\"\"\n return await self.chrome.activate_tab(self)\n\n async def close_tab(self) -> Union[str, bool]:\n \"\"\"close tab with chrome http endpoint\"\"\"\n return await self.chrome.close_tab(self)\n\n async def activate(self) -> Union[dict, None]:\n \"\"\"activate tab with cdp websocket\"\"\"\n await self.enable('Page')\n return await self.send(\"Page.bringToFront\")\n\n async def close(self) -> Union[dict, None]:\n \"\"\"close tab with cdp websocket\"\"\"\n await self.enable('Page')\n return await self.send(\"Page.close\")\n\n async def crash(self) -> Union[dict, None]:\n await self.enable('Page')\n return await self.send(\"Page.crash\")\n\n async def _recv_daemon(self):\n \"\"\"Daemon Coroutine for listening the ws.recv.\n\n event examples:\n {\"id\":1,\"result\":{}}\n {\"id\":3,\"result\":{\"result\":{\"type\":\"string\",\"value\":\"http://p.3.cn/\"}}}\n {\"id\":2,\"result\":{\"frameId\":\"7F34509F1831E6F29351784861615D1C\",\"loaderId\":\"F4BD3CBE619185B514F0F42B0CBCCFA1\"}}\n {\"method\":\"Page.frameStartedLoading\",\"params\":{\"frameId\":\"7F34509F1831E6F29351784861615D1C\"}}\n {\"method\":\"Page.frameNavigated\",\"params\":{\"frame\":{\"id\":\"7F34509F1831E6F29351784861615D1C\",\"loaderId\":\"F4BD3CBE619185B514F0F42B0CBCCFA1\",\"url\":\"http://p.3.cn/\",\"securityOrigin\":\"http://p.3.cn\",\"mimeType\":\"application/json\"}}}\n {\"method\":\"Page.loadEventFired\",\"params\":{\"timestamp\":120277.621681}}\n {\"method\":\"Page.frameStoppedLoading\",\"params\":{\"frameId\":\"7F34509F1831E6F29351784861615D1C\"}}\n {\"method\":\"Page.domContentEventFired\",\"params\":{\"timestamp\":120277.623606}}\n \"\"\"\n async for msg in self.ws:\n if self._log_all_recv:\n logger.debug(f'[recv] {self!r} {msg}')\n if msg.type in (WSMsgType.CLOSED, WSMsgType.ERROR):\n break\n if msg.type != WSMsgType.TEXT:\n continue\n data_str = msg.data\n if not data_str:\n continue\n try:\n data_dict = json.loads(data_str)\n # ignore non-dict type msg.data\n if not isinstance(data_dict, dict):\n continue\n except (TypeError, json.decoder.JSONDecodeError):\n logger.debug(\n f'[json] data_str can not be json.loads: {data_str}')\n continue\n f = self._listener.find_future(data_dict)\n if f:\n if f._state == _PENDING:\n f.set_result(data_dict)\n else:\n del f\n logger.debug(f'[break] {self!r} _recv_daemon loop break.')\n\n def _check_duplicated_on_off(self, method: str) -> bool:\n \"\"\"ignore nonsense enable / disable method.\n return True means need to send.\n return False means ignore sending operations.\"\"\"\n if not re.match(r'^\\w+\\.(enable|disable)$', method):\n return True\n function, action = method.split('.')\n if action == 'enable':\n if function in self._enabled_methods:\n # ignore\n return False\n else:\n # update _enabled_methods\n self._enabled_methods.add(function)\n return True\n elif action == 'disable':\n if function in self._enabled_methods:\n # update _enabled_methods\n self._enabled_methods.discard(function)\n return True\n else:\n # ignore\n return False\n else:\n return True\n\n async def send(self,\n method: str,\n timeout: Union[int, float] = None,\n callback_function: Optional[Callable] = None,\n check_duplicated_on_off: bool = False,\n **kwargs) -> Union[None, dict]:\n request = {\"method\": method, \"params\": kwargs}\n if check_duplicated_on_off and not self._check_duplicated_on_off(\n method):\n logger.debug(f'{method} sended before, ignore. {self}')\n return None\n request[\"id\"] = self.msg_id\n if not self.ws or self.ws.closed:\n logger.error(\n f'[closed] {self} ws has been closed, ignore send {request}')\n return None\n try:\n timeout = self.timeout if timeout is None else timeout\n\n logger.debug(f\"[send] {self!r} {request}\")\n await self.ws.send_json(request)\n if timeout <= 0:\n # not care for response\n return None\n event = {\"id\": request[\"id\"]}\n msg = await self.recv(\n event, timeout=timeout, callback_function=callback_function)\n return msg\n except (ClientError, WebSocketError) as err:\n logger.error(f'{self} [send] msg failed for {err}')\n return None\n\n async def recv(self,\n event_dict: dict,\n timeout: Union[int, float] = None,\n callback_function=None) -> Union[dict, None]:\n \"\"\"Wait for a event_dict or not wait by setting timeout=0. Events will be filt by `id` or `method` or the whole json.\n\n :param event_dict: dict like {'id': 1} or {'method': 'Page.loadEventFired'} or other JSON serializable dict.\n :type event_dict: dict\n :param timeout: await seconds, None for permanent, 0 for 0 seconds.\n :type timeout: float / None, optional\n :param callback_function: event callback_function function accept only one arg(the event dict).\n :type callback_function: callable, optional\n :return: the event dict from websocket recv.\n :rtype: dict\n \"\"\"\n result = None\n timeout = self.timeout if timeout is None else timeout\n if timeout <= 0:\n return result\n f = self._listener.register(event_dict)\n try:\n result = await asyncio.wait_for(f, timeout=timeout)\n except TimeoutError:\n logger.debug(f'[timeout] {event_dict} [recv] timeout.')\n finally:\n return await ensure_awaitable_result(callback_function, result)\n\n @property\n def now(self) -> int:\n return int(time.time())\n\n async def enable(self, name: str, force: bool = False):\n '''name: Network / Page and so on, will send `Name.enable`. Will check for duplicated sendings.'''\n return await self.send(\n f'{name}.enable', check_duplicated_on_off=not force)\n\n async def disable(self, name: str, force: bool = False):\n '''name: Network / Page and so on, will send `Name.disable`. Will check for duplicated sendings.'''\n return await self.send(\n f'{name}.disable', check_duplicated_on_off=not force)\n\n async def get_all_cookies(self, timeout: Union[int, float] = None):\n \"\"\"Network.getAllCookies\"\"\"\n await self.enable('Network')\n # {'id': 12, 'result': {'cookies': [{'name': 'test2', 'value': 'test_value', 'domain': 'python.org', 'path': '/', 'expires': -1, 'size': 15, 'httpOnly': False, 'secure': False, 'session': True}]}}\n result = (await self.send(\"Network.getAllCookies\",\n timeout=timeout)) or {}\n return result['result']['cookies']\n\n async def clear_browser_cookies(self, timeout: Union[int, float] = None):\n \"\"\"clearBrowserCookies\"\"\"\n await self.enable('Network')\n return await self.send(\"Network.clearBrowserCookies\", timeout=timeout)\n\n async def delete_cookies(self,\n name: str,\n url: Optional[str] = '',\n domain: Optional[str] = '',\n path: Optional[str] = '',\n timeout: Union[int, float] = None):\n \"\"\"deleteCookies by name, with url / domain / path.\"\"\"\n if not any((url, domain)):\n raise ValueError(\n 'At least one of the url and domain needs to be specified')\n await self.enable('Network')\n return await self.send(\n \"Network.deleteCookies\",\n name=name,\n url=url,\n domain=domain,\n path=path,\n timeout=timeout or self.timeout,\n )\n\n async def get_cookies(self,\n urls: Union[List[str], str] = None,\n timeout: Union[int, float] = None) -> List:\n \"\"\"get cookies of urls.\"\"\"\n await self.enable('Network')\n if urls:\n if isinstance(urls, str):\n urls = [urls]\n urls = list(urls)\n result = await self.send(\n \"Network.getCookies\", urls=urls, timeout=None)\n else:\n result = await self.send(\"Network.getCookies\", timeout=None)\n result = result or {}\n try:\n return result[\"result\"][\"cookies\"]\n except Exception:\n return []\n\n async def set_cookie(self,\n name: str,\n value: str,\n url: Optional[str] = '',\n domain: Optional[str] = '',\n path: Optional[str] = '',\n secure: Optional[bool] = False,\n httpOnly: Optional[bool] = False,\n sameSite: Optional[str] = '',\n expires: Optional[int] = None,\n timeout: Union[int, float] = None):\n \"\"\"name [string] Cookie name.\nvalue [string] Cookie value.\nurl [string] The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie.\ndomain [string] Cookie domain.\npath [string] Cookie path.\nsecure [boolean] True if cookie is secure.\nhttpOnly [boolean] True if cookie is http-only.\nsameSite [CookieSameSite] Cookie SameSite type.\nexpires [TimeSinceEpoch] Cookie expiration date, session cookie if not set\"\"\"\n if not any((url, domain)):\n raise ValueError(\n 'At least one of the url and domain needs to be specified')\n # expires = expires or int(time.time())\n kwargs = dict(\n name=name,\n value=value,\n url=url,\n domain=domain,\n path=path,\n secure=secure,\n httpOnly=httpOnly,\n sameSite=sameSite,\n expires=expires)\n kwargs = {\n key: value for key, value in kwargs.items() if value is not None\n }\n await self.enable('Network')\n return await self.send(\n \"Network.setCookie\",\n timeout=timeout or self.timeout,\n callback_function=None,\n check_duplicated_on_off=False,\n **kwargs)\n\n async def get_current_url(self) -> str:\n result = await self.js(\"window.location.href\")\n if result:\n url = result[\"result\"][\"result\"][\"value\"]\n else:\n url = ''\n return url\n\n @property\n def current_url(self):\n return self.get_current_url()\n\n async def get_current_title(self) -> str:\n result = await self.js(\"document.title\")\n if result:\n title = result[\"result\"][\"result\"][\"value\"]\n else:\n title = ''\n return title\n\n @property\n def current_title(self) -> Awaitable[str]:\n return self.get_current_title()\n\n async def get_html(self) -> str:\n \"\"\"return html from `document.documentElement.outerHTML`\"\"\"\n response = None\n try:\n response = await self.js(\"document.documentElement.outerHTML\")\n if not response:\n return \"\"\n value = response[\"result\"][\"result\"][\"value\"]\n return value\n except (KeyError, json.decoder.JSONDecodeError):\n logger.error(\n f\"tab.content error {response}:\\n{traceback.format_exc()}\")\n return \"\"\n\n @property\n def html(self) -> Awaitable[str]:\n \"\"\"`await tab.html`. return html from `document.documentElement.outerHTML`\"\"\"\n return self.get_html()\n\n async def wait_loading(self,\n timeout: Union[int, float] = None,\n callback_function: Optional[Callable] = None,\n timeout_stop_loading=False) -> Union[dict, None]:\n data = await self.wait_event(\n \"Page.loadEventFired\",\n timeout=timeout,\n callback_function=callback_function)\n if data is None and timeout_stop_loading:\n await self.send(\"Page.stopLoading\", timeout=0)\n return data\n\n async def wait_event(\n self,\n event_name: str,\n timeout: Union[int, float] = None,\n callback_function: Optional[Callable] = None,\n filter_function: Optional[Callable] = None) -> Union[dict, None]:\n \"\"\"Similar to self.recv, but has the filter_function to distinct duplicated method of event.\"\"\"\n timeout = self.timeout if timeout is None else timeout\n start_time = time.time()\n while 1:\n if time.time() - start_time > timeout:\n break\n # avoid same method but different event occured, use filter_function\n event = {\"method\": event_name}\n result = await self.recv(event, timeout=timeout)\n if filter_function:\n try:\n ok = await ensure_awaitable_result(filter_function, result)\n if ok:\n break\n except Exception:\n continue\n elif result:\n break\n return await ensure_awaitable_result(callback_function, result)\n\n async def wait_response(\n self,\n filter_function: Optional[Callable] = None,\n callback_function: Optional[Callable] = None,\n timeout: Union[int, float] = None) -> Union[str, None, Any]:\n '''wait a special response filted by function, then run the callback_function'''\n await self.enable('Network')\n request_dict = await self.wait_event(\n \"Network.responseReceived\",\n filter_function=filter_function,\n timeout=timeout)\n if request_dict and callback_function:\n if asyncio.iscoroutinefunction(callback_function):\n return await callback_function(request_dict)\n elif callable(callback_function):\n return callback_function(request_dict)\n return request_dict\n\n async def get_response(\n self,\n request_dict: dict,\n timeout: Union[int, float] = None,\n ) -> Union[dict, None]:\n '''{'id': 30, 'result': {'body': 'xxxxxxxxx', 'base64Encoded': False}}'''\n if request_dict is None:\n return None\n await self.enable('Network')\n request_id = request_dict[\"params\"][\"requestId\"]\n resp = await self.send(\n \"Network.getResponseBody\", requestId=request_id, timeout=timeout)\n return resp\n\n async def reload(self, timeout: Union[None, float, int] = None):\n \"\"\"\n Reload the page\n \"\"\"\n if timeout is None:\n timeout = self.timeout\n return await self.set_url(timeout=timeout)\n\n async def set_headers(self,\n headers: dict,\n timeout: Union[float, int] = None):\n '''\n # if 'Referer' in headers or 'referer' in headers:\n # logger.warning('`Referer` is not valid header, please use the `referrer` arg of set_url')'''\n logger.info(f'[set_headers] {self!r} headers => {headers}')\n await self.enable('Network')\n data = await self.send(\n 'Network.setExtraHTTPHeaders', headers=headers, timeout=timeout)\n return data\n\n async def set_ua(self,\n userAgent: str,\n acceptLanguage: Optional[str] = '',\n platform: Optional[str] = '',\n timeout: Union[float, int] = None):\n logger.info(f'[set_ua] {self!r} userAgent => {userAgent}')\n await self.enable('Network')\n data = await self.send(\n 'Network.setUserAgentOverride',\n userAgent=userAgent,\n acceptLanguage=acceptLanguage,\n platform=platform,\n timeout=timeout)\n return data\n\n async def set_url(self,\n url: Optional[str] = None,\n referrer: Optional[str] = None,\n timeout: Union[float, int] = None):\n \"\"\"\n Navigate the tab to the URL\n \"\"\"\n if timeout is None:\n timeout = self.timeout\n logger.debug(f'[set_url] {self!r} url => {url}')\n start_load_ts = self.now\n await self.enable('Page')\n if url:\n self._url = url\n if referrer is None:\n data = await self.send(\n \"Page.navigate\", url=url, timeout=timeout)\n else:\n data = await self.send(\n \"Page.navigate\",\n url=url,\n referrer=referrer,\n timeout=timeout)\n else:\n data = await self.send(\"Page.reload\", timeout=timeout)\n time_passed = self.now - start_load_ts\n real_timeout = max((timeout - time_passed, 0))\n await self.wait_loading(timeout=real_timeout, timeout_stop_loading=True)\n return data\n\n async def js(self, javascript: str,\n timeout: Union[float, int] = None) -> Union[None, dict]:\n \"\"\"\n Evaluate JavaScript on the page.\n `js_result = await tab.js('document.title', timeout=10)`\n js_result:\n {'id': 18, 'result': {'result': {'type': 'string', 'value': 'Welcome to Python.org'}}}\n if timeout: return None\n \"\"\"\n await self.enable('Runtime')\n logger.debug(f'[js] {self!r} insert js `{javascript}`.')\n return await self.send(\n \"Runtime.evaluate\", timeout=timeout, expression=javascript)\n\n async def querySelectorAll(\n self,\n cssselector: str,\n index: Union[None, int, str] = None,\n action: Union[None, str] = None,\n timeout: Union[float, int] = None) -> Union[List[Tag], Tag, None]:\n \"\"\"CDP DOM domain is quite heavy both computationally and memory wise, use js instead.\n If index is not None, will return the tag_list[index]\n else return the tag list.\n tab.querySelectorAll(\"#sc_hdu>li>a\", index=2, action=\"removeAttribute('href')\")\n for i in tab.querySelectorAll(\"#sc_hdu>li\"):\n \"\"\"\n if \"'\" in cssselector:\n cssselector = cssselector.replace(\"'\", \"\\\\'\")\n if index is None:\n index = \"null\"\n else:\n index = int(index)\n if action:\n action = f\"item.result=el.{action} || '';item.result=item.result.toString()\"\n\n else:\n action = \"\"\n javascript = \"\"\"\n var elements = document.querySelectorAll('%s');\n\n var result = []\n var index_filter = %s\n\n for (let index = 0; index < elements.length; index++) {\n const el = elements[index];\n if (index_filter!=null && index_filter!=index) {\n continue\n }\n\n var item = {\n tagName: el.tagName,\n innerHTML: el.innerHTML,\n outerHTML: el.outerHTML,\n textContent: el.textContent,\n result: \"\",\n attributes: {}\n }\n for (const attr of el.attributes) {\n item.attributes[attr.name] = attr.value\n }\n try {\n %s\n } catch (error) {\n }\n result.push(item)\n }\n JSON.stringify(result)\n \"\"\" % (\n cssselector,\n index,\n action,\n )\n response = None\n try:\n response = (await self.js(javascript, timeout=timeout)) or {}\n response_items_str = response[\"result\"][\"result\"][\"value\"]\n items = json.loads(response_items_str)\n result = [Tag(**kws) for kws in items]\n if isinstance(index, int):\n if result:\n return result[0]\n else:\n return None\n else:\n return result\n except Exception as e:\n logger.error(f\"querySelectorAll error: {e}, response: {response}\")\n if isinstance(index, int):\n return None\n return []\n\n async def inject_js_url(self,\n url,\n timeout=None,\n retry=0,\n verify=0,\n **requests_kwargs) -> Union[dict, None]:\n\n r = await self.req.get(\n url,\n timeout=timeout,\n retry=retry,\n headers={'User-Agent': UA.Chrome},\n verify=verify,\n **requests_kwargs)\n if r:\n javascript = r.text\n return await self.js(javascript, timeout=timeout)\n else:\n logger.error(f\"inject_js_url failed for request: {r.text}\")\n return None\n\n async def click(\n self,\n cssselector: str,\n index: int = 0,\n action: str = \"click()\",\n timeout: Union[float, int] = None) -> Union[List[Tag], Tag, None]:\n \"\"\"\n await tab.click(\"#sc_hdu>li>a\") # click first node's link.\n await tab.click(\"#sc_hdu>li>a\", index=3, action=\"removeAttribute('href')\") # remove href of the a tag.\n \"\"\"\n return await self.querySelectorAll(\n cssselector, index=index, action=action, timeout=timeout)\n\n def __str__(self):\n return f\"\"\n\n def __repr__(self):\n return f\"\"\n\n def __del__(self):\n if self.ws and not self.ws.closed:\n logger.debug('[unclosed] WSConnection is not closed.')\n asyncio.ensure_future(self.ws.close(), loop=self.loop)\n\n async def close_browser(self):\n await self.send('Browser.close')\n\n\nclass Listener(object):\n\n def __init__(self):\n self._registered_futures = WeakValueDictionary()\n\n @staticmethod\n def _normalize_dict(dict_obj):\n \"\"\"input a dict_obj, return the hashable item list.\"\"\"\n if not dict_obj:\n return None\n result = []\n for item in dict_obj.items():\n key = item[0]\n try:\n value = json.dumps(item[1], sort_keys=1)\n except TypeError:\n value = str(item[1])\n result.append((key, value))\n return tuple(result)\n\n def _arg_to_key(self, event_dict):\n if not isinstance(event_dict, dict):\n logger.error(\n \"Listener event_dict should be dict type, such as {'id': 1} or {'method': 'Page.loadEventFired'}\"\n )\n if \"id\" in event_dict:\n # id is unique\n key = f'id={event_dict[\"id\"]}'\n elif \"method\" in event_dict:\n # method may be duplicate\n key = f'method={event_dict[\"method\"]}'\n else:\n key = f'json={self._normalize_dict(event_dict)}'\n return key\n\n def register(self, event_dict: dict):\n '''Listener will register a event_dict, such as {'id': 1} or {'method': 'Page.loadEventFired'}, maybe the dict doesn't has key [method].'''\n f: Future = Future()\n key = self._arg_to_key(event_dict)\n self._registered_futures[key] = f\n return f\n\n def find_future(self, event_dict):\n key = self._arg_to_key(event_dict)\n return self._registered_futures.get(key)\n\n\nclass InvalidRequests(object):\n\n def __getattr__(self, name: str) -> Any:\n raise AttributeError(\n 'Chrome has not connected. `await chrome.connect()` before request.'\n )\n\n def __bool__(self):\n return False\n\n\nclass Chrome:\n\n def __init__(self,\n host: str = \"127.0.0.1\",\n port: int = 9222,\n timeout: int = 2,\n retry: int = 1,\n loop: Optional[asyncio.AbstractEventLoop] = None):\n self.host = host\n self.port = port\n self.timeout = timeout\n self.retry = retry\n self.loop = loop\n self.status = 'init'\n self.req = InvalidRequests()\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.__del__()\n\n async def __aenter__(self):\n await self.connect()\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.close()\n\n @property\n def server(self) -> str:\n \"\"\"return like 'http://127.0.0.1:9222'\"\"\"\n return f\"http://{self.host}:{self.port}\"\n\n async def get_version(self) -> dict:\n \"\"\"`await self.get_version()`\n /json/version\"\"\"\n resp = await self.get_server('/json/version')\n if resp:\n return resp.json()\n else:\n raise resp.error\n\n @property\n def version(self) -> Awaitable[dict]:\n \"\"\"`await self.version`\n {'Browser': 'Chrome/77.0.3865.90', 'Protocol-Version': '1.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36', 'V8-Version': '7.7.299.11', 'WebKit-Version': '537.36 (@58c425ba843df2918d9d4b409331972646c393dd)', 'webSocketDebuggerUrl': 'ws://127.0.0.1:9222/devtools/browser/b5fbd149-959b-4603-b209-cfd26d66bdc1'}\"\"\"\n return self.get_version()\n\n async def connect(self) -> bool:\n \"\"\"await self.connect()\"\"\"\n self.req = Requests(loop=self.loop)\n if await self.check():\n return True\n else:\n return False\n\n async def check(self) -> bool:\n \"\"\"Test http connection to cdp. `await self.check()`\n \"\"\"\n r = await self.get_server()\n if r:\n self.status = 'connected'\n logger.debug(f'[{self.status}] {self} checked.')\n return True\n else:\n self.status = 'disconnected'\n logger.debug(f'[{self.status}] {self} checked.')\n return False\n\n @property\n def ok(self):\n \"\"\"await self.ok\"\"\"\n return self.check()\n\n async def get_server(self, api: str = '') -> 'NewResponse':\n # maybe return failure request\n url = urljoin(self.server, api)\n resp = await self.req.get(url, timeout=self.timeout, retry=self.retry)\n if not resp:\n self.status = resp.text\n return resp\n\n async def get_tabs(self, filt_page_type: bool = True) -> List[Tab]:\n \"\"\"`await self.get_tabs()`.\n cdp url: /json\"\"\"\n try:\n r = await self.get_server('/json')\n if r:\n return [\n Tab(chrome=self, **rjson)\n for rjson in r.json()\n if (rjson[\"type\"] == \"page\" or filt_page_type is not True)\n ]\n except Exception:\n logger.error(\n f'fail to get_tabs {self.server}, {traceback.format_exc()}')\n return []\n\n async def get_tab(self, index: int = 0) -> Union[Tab, None]:\n \"\"\"`await self.get_tab(1)` <=> await `(await self.get_tabs())[1]`\n If not exist, return None\n cdp url: /json\"\"\"\n tabs = await self.get_tabs()\n try:\n return tabs[index]\n except IndexError:\n return None\n\n @property\n def tabs(self) -> Awaitable[List[Tab]]:\n \"\"\"`await self.tabs`\"\"\"\n # [{'description': '', 'devtoolsFrontendUrl': '/devtools/inspector.html?ws=127.0.0.1:9222/devtools/page/30C16F9165C525A4002E827EDABD48A4', 'id': '30C16F9165C525A4002E827EDABD48A4', 'title': 'about:blank', 'type': 'page', 'url': 'about:blank', 'webSocketDebuggerUrl': 'ws://127.0.0.1:9222/devtools/page/30C16F9165C525A4002E827EDABD48A4'}]\n return self.get_tabs()\n\n async def kill(self, timeout: Union[int, float] = None,\n max_deaths: int = 1) -> None:\n if self.req:\n loop = self.req.loop\n await self.req.close()\n else:\n loop = asyncio.get_event_loop()\n await loop.run_in_executor(\n Pool(1), ChromeDaemon.clear_chrome_process, self.port, timeout,\n max_deaths)\n\n async def new_tab(self, url: str = \"\") -> Union[Tab, None]:\n api = f'/json/new?{quote_plus(url)}'\n r = await self.get_server(api)\n if r:\n rjson = r.json()\n tab = Tab(chrome=self, **rjson)\n tab._created_time = tab.now\n logger.debug(f\"[new_tab] {tab} {rjson}\")\n return tab\n else:\n return None\n\n async def do_tab(self, tab_id: Union[Tab, str],\n action: str) -> Union[str, bool]:\n ok = False\n if isinstance(tab_id, Tab):\n tab_id = tab_id.tab_id\n r = await self.get_server(f\"/json/{action}/{tab_id}\")\n if r:\n if action == 'close':\n ok = r.text == \"Target is closing\"\n elif action == 'activate':\n ok = r.text == \"Target activated\"\n else:\n ok == r.text\n logger.debug(f\"[{action}_tab] : {ok}\")\n return ok\n\n async def activate_tab(self, tab_id: Union[Tab, str]) -> Union[str, bool]:\n return await self.do_tab(tab_id, action='activate')\n\n async def close_tab(self, tab_id: Union[Tab, str]) -> Union[str, bool]:\n return await self.do_tab(tab_id, action='close')\n\n async def close_tabs(self,\n tab_ids: Union[None, List[Tab], List[str]] = None,\n *args) -> List[Union[str, bool]]:\n if tab_ids is None:\n tab_ids = await self.tabs\n return [await self.close_tab(tab_id) for tab_id in tab_ids]\n\n def connect_tabs(self, *tabs) -> '_TabConnectionManager':\n '''async with chrome.connect_tabs([tab1, tab2]):.\n or\n async with chrome.connect_tabs(tab1, tab2)'''\n if not tabs:\n raise ValueError('tabs should not be null.')\n tab0 = tabs[0]\n if isinstance(tab0, (list, tuple)):\n tabs_todo = tab0\n else:\n tabs_todo = tabs\n return _TabConnectionManager(tabs_todo)\n\n def __repr__(self):\n return f\"\"\n\n def __str__(self):\n return f\"\"\n\n async def close(self):\n if self.req:\n await self.req.close()\n self.status = 'closed'\n\n def __del__(self):\n asyncio.ensure_future(self.close())\n","sub_path":"ichrome/async_utils.py","file_name":"async_utils.py","file_ext":"py","file_size_in_byte":36721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"164775415","text":"import os\nimport time\n\n\n# a=os.path.dirname(__file__)\n# a=a[:a.rfind('\\\\')]\n# a=a+'\\\\test_30.py'\n# os.system(\"{} 1\".format(a))\n# print (a)\n# os.system(\"test.bat 1\")\n# print (time.time())\nb=time.time()+(3600*3)\nwhile True:\n if b<=time.time():\n a=os.path.dirname(__file__)\n a=a[:a.rfind('\\\\')]\n a=a+'\\\\test_30.py'\n os.system(\"{} 1\".format(a))\n break\n else:\n time.sleep(500)\n\nc=time.time()+(3600*2)\nwhile True:\n if c<=time.time():\n os.system(\"exit60sec.bat 1\")\n break\n else:\n time.sleep(200)\nf = open('text.txt', 'w')\nf.write('complete. 30.')\n","sub_path":"v6/py+bat/py.py","file_name":"py.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"378596750","text":"\nimport torch\nfrom efficientnet_pytorch import EfficientNet\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom functions.args import args\nfrom dataload import train_loader, test_loader\nfrom functions.radam import RAdam\nimport numpy as np\n\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n\n self.cnn = EfficientNet.from_pretrained('efficientnet-b7')\n # feature = self.cnn._fc.in_features\n # self.cnn._fc = nn.Linear(in_features=feature, out_features=240, bias=True)\n\n def forward(self, x):\n feature = self.cnn(x)\n return feature\n\nclass LINEAR(nn.Module):\n def __init__(self):\n super(LINEAR, self).__init__()\n self.linear = torch.nn.Sequential(\n nn.Linear(120, 84),\n nn.Dropout(0.5), # drop 50% of the neuron\n nn.Linear(84, 2))\n\n def forward(self, x):\n x = F.relu(self.nn.Linear(x))\n x = self.nn.Linear(x)\n return x\n\n\nclass CLASSIFIER(nn.Module):\n def __init__(self):\n super(CLASSIFIER, self).__init__()\n self.cnn = CNN()\n self.rnn = nn.LSTMCell(1000, 120)\n self.out = LINEAR()\n\n def forward(self, x):\n X_t_1 = x[:, :, 0, :, :].squeeze(1)\n X_t_2 = x[:, :, 1, :, :].squeeze(1)\n out_t_1 = self.cnn(X_t_1)\n out_t_2 = self.cnn(X_t_2)\n # print(out_t_1.size())\n # order\n feature = torch.stack((out_t_1, out_t_2),0)\n output = []\n for i in range(2):\n hx, cx = self.rnn(feature[i,:,:])\n output.append(hx)\n # print(np.shape(output))\n out = output[1]\n # print(out.size())\n return out\n\nargs = args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\ntorch.manual_seed(args.seed)\nif args.cuda: torch.cuda.manual_seed(args.seed)\n\nmodel = CLASSIFIER()\nif args.cuda: model.cuda()\n\noptimizer = RAdam(model.parameters())\n\n\ndef train(epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data = data.type(torch.FloatTensor)\n target = target.type(torch.LongTensor)\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n optimizer.zero_grad()\n output = model(data)\n output1 = torch.nn.functional.log_softmax(output, dim=1)\n loss = F.nll_loss(output1, target)\n loss.backward()\n optimizer.step()\n\n # new ynh\n # 每10个batch画个点用于loss曲线\n # if batch_idx % 10 == 0:\n # niter = epoch * len(train_loader) + batch_idx\n # writer.add_scalar('Train/Loss', loss.data, niter)\n\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef test():\n # 不启用 BatchNormalization 和 Dropout\n model.eval()\n test_loss = 0\n correct = 0\n for data, target in test_loader:\n data = data.type(torch.FloatTensor)\n target = target.type(torch.LongTensor)\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n output = model(data)\n test_loss += F.nll_loss(\n output, target, size_average=False).data # sum up batch loss\n pred = output.data.max(\n 1, keepdim=True)[1] # get the index of the max log-probability\n correct += pred.eq(target.data.view_as(pred)).long().cpu().sum()\n\n test_loss /= len(test_loader.dataset)\n print(\n '\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\n\nif __name__ == '__main__':\n for epoch in range(1, args.epochs + 1):\n train(epoch)\n test()\n\n # cnn_lstm_test()\n # cnn_lstm_test()","sub_path":"cnnlstm.py","file_name":"cnnlstm.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"605042839","text":"import csv\nimport itertools\nimport numpy as np\nimport nltk\nimport time\nimport sys\nimport operator\nimport io\nimport array\nfrom datetime import datetime\nfrom gru_theano import GRUTheano\nfrom nltk.tokenize import sent_tokenize, word_tokenize,RegexpTokenizer\nfrom nltk.corpus import wordnet as wn\nimport csv\nimport pandas as pd\nimport csv\nimport nltk\nimport numpy as np\nimport theano as theano\nimport theano.tensor as T\n\n\nSENTENCE_START_TOKEN = \"sent_start\"\nSENTENCE_END_TOKEN = \"sent_end\"\nUNKNOWN_TOKEN = \"UNKNOWN_TOKEN\"\n\n\n\nf=open(\"Sentence.txt\",\"r\")\nx= f.read()\nprint()\nrow_of_sentences=sent_tokenize(x);\n\nfor i in range (len(row_of_sentences)):\n tok=word_tokenize(row_of_sentences[i]) #list type\n tok.insert(0,\"sent_start\")\n tok.append(\"sent_end\")\n row_of_sentences[i]=tok;\n #print(tok)\n \ndf=pd.read_csv(\"final.csv\",names=['Words']) \ndf=df['Words']\n#df.loc[0]='sent_start'\nvoc=df.values.tolist()\n\n\n#vecx=[]\n#vecy=[]\nindex_to_word=dict()\nword_to_index=dict()\n\nfor i in row_of_sentences:\n vecx=[]\n for j in i[:-1]:\n #print (j)\n if(j in voc):\n x=voc.index(j)\n vecx.append(x)\n index_to_word[x]=j\n word_to_index[j]=x\n else:\n x=len(voc)\n df.loc[len]=j\n df.to_csv(\"final.csv\")\n voc=df.values.tolist()\n vecx.append(x)\n index_to_word[x]=j\n word_to_index[j]=x\n\n\nx=voc.index(\"sent_end\")\nindex_to_word[x]=\"sent_end\"\nword_to_index[\"sent_end\"]=x \n\ndef train_with_sgd(model, X_train, y_train, learning_rate=0.001, nepoch=20, decay=0.9,\n callback_every=10000, callback=None):\n num_examples_seen = 0\n for epoch in range(nepoch):\n # For each training example...\n for i in np.random.permutation(len(y_train)):\n # One SGD step\n model.sgd_step(X_train[i], y_train[i], learning_rate, decay)\n num_examples_seen += 1\n # Optionally do callback\n if (callback and callback_every and num_examples_seen % callback_every == 0):\n callback(model, num_examples_seen) \n return model\n\ndef save_model_parameters_theano(model, outfile):\n np.savez(outfile,\n E=model.E.get_value(),\n U=model.U.get_value(),\n W=model.W.get_value(),\n V=model.V.get_value(),\n b=model.b.get_value(),\n c=model.c.get_value())\n print(\"Saved model parameters to %s.\" % outfile)\n\ndef load_model_parameters_theano(path, modelClass=GRUTheano):\n npzfile = np.load(path)\n E, U, W, V, b, c = npzfile[\"E\"], npzfile[\"U\"], npzfile[\"W\"], npzfile[\"V\"], npzfile[\"b\"], npzfile[\"c\"]\n hidden_dim, word_dim = E.shape[0], E.shape[1]\n print(\"Building model model from %s with hidden_dim=%d word_dim=%d\" % (path, hidden_dim, word_dim))\n sys.stdout.flush()\n model = modelClass(word_dim, hidden_dim=hidden_dim)\n model.E.set_value(E)\n model.U.set_value(U)\n model.W.set_value(W)\n model.V.set_value(V)\n model.b.set_value(b)\n model.c.set_value(c)\n return model \n\ndef gradient_check_theano(model, x, y, h=0.001, error_threshold=0.01):\n # Overwrite the bptt attribute. We need to backpropagate all the way to get the correct gradient\n model.bptt_truncate = 1000\n # Calculate the gradients using backprop\n bptt_gradients = model.bptt(x, y)\n # List of all parameters we want to chec.\n model_parameters = ['E', 'U', 'W', 'b', 'V', 'c']\n # Gradient check for each parameter\n for pidx, pname in enumerate(model_parameters):\n # Get the actual parameter value from the mode, e.g. model.W\n parameter_T = operator.attrgetter(pname)(model)\n parameter = parameter_T.get_value()\n print(\"Performing gradient check for parameter %s with size %d.\" % (pname, np.prod(parameter.shape)))\n # Iterate over each element of the parameter matrix, e.g. (0,0), (0,1), ...\n it = np.nditer(parameter, flags=['multi_index'], op_flags=['readwrite'])\n while not it.finished:\n ix = it.multi_index\n # Save the original value so we can reset it later\n original_value = parameter[ix]\n # Estimate the gradient using (f(x+h) - f(x-h))/(2*h)\n parameter[ix] = original_value + h\n parameter_T.set_value(parameter)\n gradplus = model.calculate_total_loss([x],[y])\n parameter[ix] = original_value - h\n parameter_T.set_value(parameter)\n gradminus = model.calculate_total_loss([x],[y])\n estimated_gradient = (gradplus - gradminus)/(2*h)\n parameter[ix] = original_value\n parameter_T.set_value(parameter)\n # The gradient for this parameter calculated using backpropagation\n backprop_gradient = bptt_gradients[pidx][ix]\n # calculate The relative error: (|x - y|/(|x| + |y|))\n relative_error = np.abs(backprop_gradient - estimated_gradient)/(np.abs(backprop_gradient) + np.abs(estimated_gradient))\n # If the error is to large fail the gradient check\n if relative_error > error_threshold:\n print(\"Gradient Check ERROR: parameter=%s ix=%s\" % (pname, ix))\n print(\"+h Loss: %f\" % gradplus)\n print(\"-h Loss: %f\" % gradminus)\n print(\"Estimated_gradient: %f\" % estimated_gradient)\n print(\"Backpropagation gradient: %f\" % backprop_gradient)\n print(\"Relative Error: %f\" % relative_error)\n return \n it.iternext()\n print(\"Gradient check for parameter %s passed.\" % (pname))\n \n\n\n'''def print_sentence(s, index_to_word):\n sentence_str = [index_to_word[x] for x in s[1:-1]]\n print(\" \".join(sentence_str))\n sys.stdout.flush()\n'''\ndef generate_sentence(model,word):\n x=1\n #print(\"hello\")\n # We start the sentence with the given start word\n new_sentence = [voc.index(word)]\n sent=word\n #print(sent)\n while (not new_sentence[-1] ==voc.index(\"sent_end\") and (not x>5)):\n x+=1;\n next_word_probs=model.predict(new_sentence)[-1]\n samples = np.random.multinomial(1, next_word_probs)\n sampled_word = np.argmax(samples)\n new_sentence.append(sampled_word)\n if(not (voc[sampled_word]==\"sent_start\")):\n sent=sent+\" \"+voc[sampled_word]\n # Seomtimes we get stuck if the sentence becomes too long, e.g. \"........\" :(\n # And: We don't want sentences with UNKNOWN_TOKEN's\n \n # sentence_str = [index_to_word[x] for x in new_sentence[1:-1]]\n print(\"Generated text\")\n print(sent)\n print()\n","sub_path":"utilsss.py","file_name":"utilsss.py","file_ext":"py","file_size_in_byte":6680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"556238280","text":"# export MPLBACKEND=\"agg\"\n# CUDA_VISIBLE_DEVICES=1 ipython2\n\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.realpath('../src/models/lstm_mixture_density_model.py')))\nimport numpy as np\nimport tensorflow as tf\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# load code\nfrom lstm_mixture_density_model import tf_lstm_mixture_density_model\n# =======================================================================================\n# Section\n# =======================================================================================\nmodel_name = 'my_lstm_model'\n\n# input_length = 5\ninput_length = 50\nn_lstm_units = 32\n# n_lstm_units = 256\nn_layers = 1\n# pred_x_dim = 4\n# obs_x_dim = 5\npred_x_dim = 4\nobs_x_dim = 5; use_feature = False # for label only\n# obs_x_dim = 4 + 64; use_feature = True # for all features\n# n_mixtures = 3\nn_mixtures = 7\ndropout_prob = 0.1\n# y_dim = 8\ny_dim = 55\n# batch_size=1\nbatch_size=16\nlearning_rate = 0.01\nstart_time_sd = 0.01\n\n# with tf.device('/cpu:0'):\nwith tf.device('/gpu:0'):\n lstm_DM = tf_lstm_mixture_density_model(name=model_name,\n input_length=input_length, # length of h_t\n n_lstm_units=n_lstm_units, # no. of hidden units\n n_layers=n_layers, # layer no.\n pred_x_dim=pred_x_dim, # predict x_t = 4 dim\n obs_x_dim=obs_x_dim, # x_t = 5dim\n y_dim=y_dim, # y dim\n batch_size=batch_size,\n n_loc_mixtures=n_mixtures, # no. of gaussian mixture\n dropout_prob = dropout_prob,\n learning_rate=learning_rate,\n start_time_sd=start_time_sd)\n# =======================================================================================\n# real data\n# =======================================================================================\nimport pandas as pd\n\n# data with label\nLabel = pd.read_csv('../data_new/Traj_Label_Data2.csv', index_col=[0]).reset_index()\ncolnames = ['Idx','TrueLabel','PredLabel1','PredLabel2','PredLabel3'] + ['Feature' + str(i) for i in range(1,65)]\nFeature = pd.read_csv('../data_cnnout/PredictedLabelFeature.csv', names=colnames)\nNew_Label = Label.merge(Feature, left_on='index', right_on='Idx', how='left')\nFID_with_missing_data = New_Label.loc[New_Label['PredLabel1'].index[New_Label['PredLabel1'].apply(np.isnan)]].FID.unique()\ndata_raw_withfeature = New_Label[~New_Label.FID.isin(FID_with_missing_data)]\n# np.unique(New_Label.FID[New_Label.FID.isin(FID_with_missing_data)])\n\ndata_raw = data_raw_withfeature\n\n# data with true label\n# Label = pd.read_csv('../data_new/Traj_Label_Data2.csv', index_col=[0]).reset_index()\n# colnames = ['Idx','TrueLabel','PredLabel1','PredLabel2','PredLabel3'] + ['Feature' + str(i) for i in range(1,65)]\n# Feature = pd.read_csv('../data_cnnout/PredictedLabelFeature.csv', names=colnames)\n# data_raw = Label.merge(Feature, left_on='index', right_on='Idx')\n\n# no label\n# data_raw = pd.read_csv('../data_new/Traj_Label_Data2.csv')\n\nn_subj = len(np.unique(data_raw['FID']))\n\nlocation_list = data_raw[['Lon','Lat']].as_matrix()\n\nlocation_list1 = np.zeros((n_subj, 50, 2))\nfor it in xrange(0,n_subj):\n # print location_list[(50*it):(50*(it+1)), :].shape\n location_list1[it, :, :] = location_list[(50*it):(50*(it+1)), :]\n# location_list1 = data_raw[['Lon','Lat']].as_matrix()\n\n\n\nstart_time_list1 = np.linspace(start = 1, stop = 50, num=50)\nstart_time_list1 = start_time_list1[np.newaxis, :, np.newaxis]\nstart_time_list1 = np.tile(start_time_list1, (n_subj, 1, 1))\n\n# start_time_list1 = np.tile(np.linspace(start = 1, stop = 50, num=50), reps = n_subj)\n# start_time_list1 = np.expand_dims(start_time_list1, axis = 1)\n\n\nduration_list1 = np.repeat(1, repeats = 50)\nduration_list1 = duration_list1[np.newaxis,:,np.newaxis]\nduration_list1 = np.tile(duration_list1, (n_subj, 1, 1))\n\n# duration_list1 = np.repeat(1, repeats = n_subj * 50)\n# duration_list1 = np.expand_dims(duration_list1, axis = 1)\n\nactivity_type_list1 = np.eye(50)\nactivity_type_list1 = activity_type_list1[np.newaxis,:]\nactivity_type_list1 = np.tile(activity_type_list1, (n_subj, 1, 1))\n\n# activity_type_list1 = np.reshape(np.tile(np.array([0, 1, 0]), 48), [48,3])\n# activity_type_list1 = np.vstack(([1,0,0], activity_type_list1, [0,0,1]))\n# activity_type_list1 = activity_type_list1[np.newaxis,:,:]\n# activity_type_list1 = np.tile(activity_type_list1, (n_subj, 1, 1))\n\n# activity_type_list1 = np.reshape(np.tile(np.array([0, 1, 0]), 48), [48,3])\n# activity_type_list1 = np.vstack(([1,0,0], activity_type_list1, [0,0,1]))\n# activity_type_list1 = np.tile(activity_type_list1, (n_subj, 1))\n\n\nend_of_day_list1 = np.zeros((49, 1))\nend_of_day_list1 = np.vstack((end_of_day_list1, 1))\nend_of_day_list1 = end_of_day_list1[np.newaxis,:,:]\nend_of_day_list1 = np.tile(end_of_day_list1, (n_subj, 1, 1))\n\n# end_of_day_list1 = np.zeros((49, 1))\n# end_of_day_list1 = np.vstack((end_of_day_list1, 1))\n# end_of_day_list1 = np.tile(end_of_day_list1, (n_subj, 1))\n\nactivity_information1 = np.dstack((location_list1,\n start_time_list1,\n duration_list1,\n activity_type_list1,\n end_of_day_list1))\n\n# activity_information1 = np.hstack((location_list1,\n# start_time_list1,\n# duration_list1,\n# activity_type_list1,\n# end_of_day_list1))\n# activity_information1 = activity_information1[np.newaxis, :]\n\n# ct: Contextual variables\n\nhome_location_list1 = np.array([-95.3,29.98333333])\nwork_location_list1 = np.array([-70.96666667,42.36666667])\n\ncontextual_variables1 = np.hstack((np.array([home_location_list1] * activity_information1.shape[1]),\n np.array([work_location_list1] * activity_information1.shape[1])))\ncontextual_variables1 = contextual_variables1[np.newaxis, :]\ncontextual_variables1 = np.tile(contextual_variables1, (n_subj, 1, 1))\n\n#\n# use true label\n# ---------------------------------------------------------------------------------------\nlabel_list = data_raw[['NewLabel']].as_matrix()\nlabel_list = np.reshape(label_list, [n_subj, 50])\nlabel_list = label_list[:, :, np.newaxis]\nlabel_list.shape\n\ncontextual_variables1 = np.concatenate((contextual_variables1, label_list), axis = 2)\n#\n# use CNN feature\n# ---------------------------------------------------------------------------------------\n# feature_list = data_raw_withfeature.as_matrix()[:,14:]\n# feature_list = np.reshape(feature_list, [n_subj, 50, 64])\n\n# contextual_variables1 = np.concatenate((contextual_variables1, feature_list), axis = 2)\n#\n# use predicted label\n# ---------------------------------------------------------------------------------------\n# feature_list = data_raw_withfeature.as_matrix()[:,10]\n# feature_list = np.reshape(feature_list, [n_subj, 50, 1])\n\n# contextual_variables1 = np.concatenate((contextual_variables1, feature_list), axis = 2)\n\n# Initilization for LSTM model\nX_init = np.zeros((1, pred_x_dim))\nX_init = np.tile(X_init, (n_subj, 1))\n\n\n# activity_information1[0,:,:]\n# =======================================================================================\n# normalize data\n# =======================================================================================\n# Center latitude and longitude\nlat_mean = np.mean(activity_information1[:, :, 0])\nlon_mean = np.mean(activity_information1[:, :, 1])\nactivity_information1[:, :, 0] -= lat_mean\nactivity_information1[:, :, 1] -= lon_mean\n\ncontextual_variables1[:, :, 0] -= lat_mean\ncontextual_variables1[:, :, 2] -= lat_mean\ncontextual_variables1[:, :, 1] -= lon_mean\ncontextual_variables1[:, :, 3] -= lon_mean\n\n\n# Normalize latitude and longitude to -1~1\n# Normalize starting time and duration to 0~1\nlat_max = np.max(np.abs(activity_information1[:, :, 0]))\nlon_max = np.max(np.abs(activity_information1[:, :, 1]))\n\ntemp = np.array([lat_max,\n lon_max,\n 24.,\n 24.,\n 1.])\ntemp = np.concatenate((temp , np.ones(50)))\nactivity_information1 /= temp\n# activity_information1 /= np.array([lat_max,\n# lon_max,\n# 24.,\n# 24.,\n# 1.,\n# 1.,\n# 1.,\n# 1.])\n\n# no label\n# contextual_variables1 /= np.array([lat_max,\n# lon_max,\n# lat_max,\n# lon_max])\n\n# for label only\nif not use_feature:\n contextual_variables1 /= np.array([lat_max,\n lon_max,\n lat_max,\n lon_max,\n 1])\n\n# for all features\nif use_feature:\n part1 = [lat_max,\n lon_max,\n lat_max,\n lon_max]\n to_divide = np.concatenate((part1, np.ones(64)))\n contextual_variables1 /= to_divide\n\n\n# contextual_variables1 /= np.array([lat_max,\n# lon_max,\n# lat_max,\n# lon_max])\n\n# =======================================================================================\n# artificial eg.\n# =======================================================================================\n# We made up 5 activities with location, starting time, duration, and activity types\n# The 5 activity types are home -> other -> work -> other -> home\n\n\n# # xt: Activity information\n# location_list = np.array([[37.750460, -122.429491],\n# [37.944496, -122.351648],\n# [37.856912, -122.288567],\n# [37.754701, -122.188187],\n# [37.750460, -122.429491]])\n\n# start_time_list = np.array([[7.0],\n# [8.4],\n# [12.5],\n# [16.0],\n# [18.0]])\n# start_time_list.shape\n\n# duration_list = np.array([[1.4],\n# [4.1],\n# [5.5],\n# [2.0],\n# [12.0]])\n# duration_list.shape\n\n# activity_type_list = np.array([[1, 0, 0],\n# [0, 0, 1],\n# [0, 1, 0],\n# [0, 0, 1],\n# [1, 0, 0]])\n# activity_type_list.shape\n\n# end_of_day_list = np.array([[0],\n# [0],\n# [0],\n# [0],\n# [1]])\n# end_of_day_list.shape\n\n# activity_information = np.hstack((location_list,\n# start_time_list,\n# duration_list,\n# activity_type_list,\n# end_of_day_list))\n# activity_information = activity_information[np.newaxis, :]\n\n# # ct: Contextual variables\n# home_location_list = np.array([37.750460, -122.429491])\n# work_location_list = np.array([37.856912, -122.288567])\n\n# contextual_variables = np.hstack((np.array([home_location_list] * 5),\n# np.array([work_location_list] * 5)))\n# contextual_variables = contextual_variables[np.newaxis, :]\n\n# # Initilization for LSTM model\n# X_init = np.zeros((1, pred_x_dim))\n# =======================================================================================\n# normalize data\n# =======================================================================================\n# # Center latitude and longitude\n# lat_mean = np.mean(activity_information[:, :, 0])\n# lon_mean = np.mean(activity_information[:, :, 1])\n# activity_information[:, :, 0] -= lat_mean\n# activity_information[:, :, 1] -= lon_mean\n\n# contextual_variables[:, :, 0] -= lat_mean\n# contextual_variables[:, :, 2] -= lat_mean\n# contextual_variables[:, :, 1] -= lon_mean\n# contextual_variables[:, :, 3] -= lon_mean\n\n\n# # Normalize latitude and longitude to -1~1\n# # Normalize starting time and duration to 0~1\n# lat_max = np.max(np.abs(activity_information[:, :, 0]))\n# lon_max = np.max(np.abs(activity_information[:, :, 1]))\n\n# activity_information /= np.array([lat_max,\n# lon_max,\n# 24.,\n# 24.,\n# 1.,\n# 1.,\n# 1.,\n# 1.])\n\n# contextual_variables /= np.array([lat_max,\n# lon_max,\n# lat_max,\n# lon_max])\n# =======================================================================================\n# train\n# =======================================================================================\nconfig = tf.ConfigProto(allow_soft_placement = True)\nsess = tf.Session(config = config)\nsess.run(tf.global_variables_initializer())\n\nlocation_sd_bias = 0.0\ntime_sd_bias = 0.0\npi_bias = 0.0\n\nlstm_DM.train(X_init=X_init,\n X_input_seq=contextual_variables1, # c_t\n y=activity_information1, # x_t\n # epochs=1000,\n epochs=5000,\n sess=sess,\n start_time_list=start_time_list1[:,0,:]/24. ,\n per=1000,\n location_sd_bias=location_sd_bias,\n time_sd_bias=time_sd_bias,\n pi_bias=pi_bias)\n\n# ho =start_time_list1[:,0,:]\n# ho=start_time_list1[0,0]\n# =======================================================================================\n# generate sequence\n# =======================================================================================\n# config = tf.ConfigProto(allow_soft_placement = True)\nsaver = tf.train.Saver()\n\n# Later, launch the model, use the saver to restore variables from disk, and\n# do some work with the model.\nsess = tf.Session(config = config)\nsess.run(tf.global_variables_initializer())\n# Restore variables from disk.\nsaver.restore(sess, \"./model_save/model.ckpt\")\n# saver.restore(sess, \"./model_save2/model.ckpt\")\nprint(\"Model restored.\")\n\n\ngen_seq, \\\ngen_coef, \\\ngen_states, \\\ngen_mixture_coef = lstm_DM.generate_sequence_coefficients(sess=sess,\n X_init=X_init,\n X_input_seq=contextual_variables1,\n # X_init=X_init[0,:],\n # X_input_seq=contextual_variables1[0,:,:],\n start_time_list=start_time_list1[:,0,:]/24.,\n n=200)\ncontextual_variables1[0,:,:].shape\n# =======================================================================================\n# plot sequence\n# =======================================================================================\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport matplotlib as mpl\nmpl.use('Agg')\n# plt.interactive(True)\n\n# Scale data back\nactivity_information1[:, :, 0] *= lat_max\nactivity_information1[:, :, 1] *= lon_max\nactivity_information1[:, :, 0] += lat_mean\nactivity_information1[:, :, 1] += lon_mean\nactivity_information1[:, :, 2] *= 24.\nactivity_information1[:, :, 3] *= 24.\n\ngen_seq[:, :, 0] *= lat_max\ngen_seq[:, :, 1] *= lon_max\ngen_seq[:, :, 0] += lat_mean\ngen_seq[:, :, 1] += lon_mean\ngen_seq[:, :, 2] *= 24\ngen_seq[:, :, 3] *= 24\n\n# plot coordinate\nplt.figure()\n\nfor i in xrange(200):\n plt.plot(gen_seq[i][:,1], gen_seq[i][:,0], 'b.', alpha =0.3)\n\n# red center is truth coordinate\nplt.plot(activity_information1[0][:,1], activity_information1[0][:,0], 'ro', lw=3)\n\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\nplt.savefig('1.png')\n#\n# plot duration\n# ---------------------------------------------------------------------------------------\nplt.figure()\n\nfor i in xrange(200):\n plt.plot(gen_seq[i][:,2], gen_seq[i][:,3], 'b.', alpha =0.3)\n\nplt.plot(activity_information1[0][:,2], activity_information1[0][:,3], 'ro', lw=3)\n\n\nplt.xlabel('Starting Time')\nplt.ylabel('Duration')\nplt.xlim((0, 24))\nplt.ylim((0, 24))\n\nplt.savefig('2.png')\n\n#\n# plot path for single person\n# ---------------------------------------------------------------------------------------\nplt.figure()\n\ni = 75\nplt.plot(gen_seq[i][:,1], gen_seq[i][:,0], 'b-o', alpha =0.3)\n\n# red center is truth coordinate\nplt.plot(activity_information1[i][:,1], activity_information1[i][:,0], 'ro', lw=3)\n\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\n\nplt.savefig('3.png')\n\n#\n# calculate distribution mean\n# ---------------------------------------------------------------------------------------\ngen_colmean = gen_seq.mean(axis=0)\n\n# plot mean path\nplt.figure()\n\nplt.plot(gen_colmean[:,1], gen_colmean[:,0], 'b-o', alpha =0.3)\n\n# red center is truth coordinate\nmean_play = np.mean(activity_information1, axis=0)\n# plt.plot(activity_information1[0][:,1], activity_information1[0][:,0], 'ro', lw=3)\nplt.plot(mean_play[:,1], mean_play[:,0], 'ro', lw=3)\n\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\n\nplt.savefig('4.png')\n\n#\n# calculate distribution median\n# ---------------------------------------------------------------------------------------\ngen_colmedian = np.median(gen_seq, axis=0)\n\n# plot mean path\nplt.figure()\n\nplt.plot(gen_colmedian[:,1], gen_colmedian[:,0], 'b-o', alpha =0.3)\n\n# red center is truth coordinate\nmedian_play = np.median(activity_information1, axis=0)\nplt.plot(median_play[:,1], median_play[:,0], 'ro', lw=3)\n# plt.plot(activity_information1[10][:,1], activity_information1[10][:,0], 'ro', lw=3)\n\n\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\n\nplt.savefig('5.png')\n\n#\n# mean path for single person\n# ---------------------------------------------------------------------------------------\ni = 25\n\ncontextual_variables2 = contextual_variables1[i,:,:][np.newaxis,:,:]\ncontextual_variables2 = np.repeat(contextual_variables2, n_subj, axis = 0)\ncontextual_variables2.shape\n\ngen_seq, \\\ngen_coef, \\\ngen_states, \\\ngen_mixture_coef = lstm_DM.generate_sequence_coefficients(sess=sess,\n X_init=X_init,\n X_input_seq=contextual_variables2,\n start_time_list=start_time_list1[:,0,:]/24.,\n n=200)\n\ngen_colmean = gen_seq.mean(axis=0)\n\n# plot mean path\nplt.figure()\n\nplt.plot(gen_colmean[:,1], gen_colmean[:,0], 'b-o', alpha =0.3)\n\n# red center is truth coordinate\nplt.plot(activity_information1[i][:,1], activity_information1[i][:,0], 'ro', lw=3)\n\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\n\nplt.savefig('6.png')\n\n\ngen_colmedian = np.median(gen_seq, axis=0)\n\n# plot mean path\nplt.figure()\n\nplt.plot(gen_colmedian[:,1], gen_colmedian[:,0], 'b-o', alpha =0.3)\n\n# red center is truth coordinate\nplt.plot(activity_information1[i][:,1], activity_information1[i][:,0], 'ro', lw=3)\n\n\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\n\nplt.savefig('7.png')\n","sub_path":"with_label/lstm_withlabel.py","file_name":"lstm_withlabel.py","file_ext":"py","file_size_in_byte":19733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"644566748","text":"#include:utf-8\n\"\"\"\nAuthor : Horairy Hakim\nemail : hakim.horairy@telecom-sudparis.eu\nTel : 07 69 22 52 55\n\"\"\"\nimport numpy\nimport os\nimport json\nimport readchar\nimport sys\nimport time\n\n\nclass Frame:\n\n\tdef __init__(self, frameID):\n\n\t\tself.frameID = frameID\n\n\t\tself.getMetaData() # generate 3 attributs\n\n\t\tself.getTerminalSize() # generate 2 attributs \n\t\t\n\t\tself.positionLinksOnLogicalGrid = {} # this dict is cleaned and filled during the execution of \"generateLogicalGrid\".\n\t\tself.positionCursor = None #Its value is instantiated the first time the positionLinksOnLogicalGrid is filled.\n\n\t\tself.logicalGrid = self.generateLogicalGrid() \n\t\tself.graphicalGrid = self.generateGraphicalGrid()\n\n################################################################################################################################################\t\t\n############################## Meta-data Frame ############################################################################\n################################################################################################################################################\n\t\n\n\tdef getMetaData(self):\n\t\t\"\"\"This function allows you to get the information needed to build the frame.\n\t\t\tIt instantiate 3 attributes for the frame class :\n\t\t\t\t\tmetaData : it's the dictionary that is generated by the user when \n\t\t\t\t\t\t\t he uses the framework to generate a frame.\"\"\"\n\n\t\twith open(\"metaDataFiles/metadataFrameID{0}\".format(self.frameID)) as jsonFile:\n\t\t\tself.metaData = json.load(jsonFile)\n\t\t\n\t\tself.numberLinksToFrames = len(self.metaData[\"links\"])\n\t\tself.numberButtons = len(self.metaData[\"buttons\"])\n\n\n\n################################################################################################################################################\n\n################################################################################################################################################\n############################### \t\t\t\tLogics \t\t\t\t############################################################################\n################################################################################################################################################\n\n\t\n\tdef getTerminalSize(self):\n\t\t\"\"\"Instantiate 2 attributes for the frame class : \n\t\t\t\t\tThe number of rows and columns of the frame\"\"\"\n\t\trows, columns = os.popen('stty size', 'r').read().split()\n\t\tself.NumberLines = int(rows) - 4\n\t\tself.numberColumns = int(columns)\n\n\tdef getTerminalCenterPosition(self):\n\t\treturn [self.NumberLines//2, self.numberColumns//2]\n\n\tdef getTermialBottomLeftPosition(self):\n\t\treturn [3*(self.NumberLines//4), self.numberColumns//4]\n\n\t\n\tdef generateEmptyLogicalGrid(self):\n\t\t\n\t\temptyLogicalGrid = numpy.ones(shape=(self.NumberLines, self.numberColumns), dtype=int)\n\t\temptyLogicalGrid[1:-1, 1:-1] = numpy.zeros(shape=(self.NumberLines-2, self.numberColumns-2), dtype=int)\n\t\t\n\t\treturn emptyLogicalGrid\n\n\n\tdef addLinksOnLogicalGrid(self, logicalGrid, position=\"center\"):\n\n\t\tself.positionLinksOnLogicalGrid = {}\n\n\t\tif position == \"center\":\n\t\t\tposition = self.getTerminalCenterPosition()\n\t\t\tposition[0] -= (self.numberLinksToFrames - 1)\n\n\t\t\tfor indexLink in range(self.numberLinksToFrames):\n\n\t\t\t\tif self.positionCursor == None:\n\t\t\t\t\tlogicalGrid[position[0], position[1] - 2] = 4\n\t\t\t\t\tself.positionCursor = [0, [position[0], position[1] - 2]]\n\n\t\t\t\tlogicalGrid[position[0], position[1]] = 2\n\t\t\t\tself.positionLinksOnLogicalGrid[str(indexLink)] = [position[0], position[1] - 2]\n\t\t\t\tposition[0] += 2\n\n\t\treturn logicalGrid\n\n\tdef modifyPostionCursor(self, direction):\n\t\tself.logicalGrid[self.positionCursor[1][0], self.positionCursor[1][1]] = 0\n\t\t\n\t\tif direction == \"up\":\n\t\t\t\n\t\t\tif self.positionCursor[0] == 0:\n\t\t\t\tself.positionCursor[0] = self.numberLinksToFrames - 1\n\t\t\t\t\t\n\t\t\telse :\n\t\t\t\tself.positionCursor[0] -= 1\n\n\n\t\telif direction == \"down\":\n\t\t\t\n\t\t\tif self.positionCursor[0] == self.numberLinksToFrames -1:\n\t\t\t\tself.positionCursor[0] = 0\n\t\t\telse :\n\t\t\t\tself.positionCursor[0] += 1\n\n\t\t\n\t\tself.positionCursor[1] = self.positionLinksOnLogicalGrid[ str(self.positionCursor[0]) ]\n\n\t\tself.logicalGrid[self.positionCursor[1][0], self.positionCursor[1][1]] = 4\t\t\n\n\n\n\tdef addButtonsOnLogicalGrid(self, logicalGrid, position=\"bottomleft\"):\n\n\t\tif position == \"bottomleft\":\n\t\t\tposition = self.getTermialBottomLeftPosition()\n\t\t\tposition[0] -= (self.numberButtons -1)\n\t\t\t\n\t\t\tfor indexButton in range(self.numberButtons):\n\t\t\t\tlogicalGrid[position[0], position[1]] = 3\n\t\t\t\tposition[0] += 2\n\n\t\treturn logicalGrid\n\n\n\n\tdef generateLogicalGrid(self):\n\n\t\temptyLogicalGrid = self.generateEmptyLogicalGrid()\n\t\tlogicalGridWithLinks = self.addLinksOnLogicalGrid(logicalGrid=emptyLogicalGrid)\n\t\tlogicalGrid = self.addButtonsOnLogicalGrid(logicalGrid=logicalGridWithLinks)\n\n\t\treturn logicalGrid\n\t\t\n\n\tdef quitTUI(self):\n\t\tos.system(\"clear\")\n\t\tsys.exit()\n\n#######################################################################################################################################\n\n\n#######################################################################################################################################\n##############################\t\t\t\t\tGraphics\t\t\t###################################################################\n#######################################################################################################################################\n\n\tdef command(self):\n\n\n\t\tinputCommand = readchar.readkey()\n\n\t\tif inputCommand == readchar.key.UP:\n\t\t\tself.modifyPostionCursor(direction=\"up\")\n\n\t\telif inputCommand == readchar.key.DOWN:\n\t\t\tself.modifyPostionCursor(direction=\"down\")\n\n\t\telif inputCommand == self.metaData[\"buttons\"][\"-1\"][0] :\n\t\t\tself.quitTUI()\n\n\t\t\n#######################################################################################################################################\n\n\n\n#######################################################################################################################################\n##############################\t\t\t\t\tGraphics\t\t\t###################################################################\n#######################################################################################################################################\n\t\n\tdef generateGraphicalGrid(self):\n\n\t\tlisteCharacs = [\" \", \"X\", None, None, \">\"]\n\t\tgraphicalGrid = \"\"\n\t\t\n\t\tdoNotAddAnything = 0\n\t\tcounterLinks = 0\n\t\tcounterButtons = 0\n\n\t\tfor logicLine in self.logicalGrid:\n\t\t\tfor logicValue in logicLine:\n\t\t\t\t\n\t\t\t\tif doNotAddAnything != 0:\n\t\t\t\t\tdoNotAddAnything -= 1\n\t\t\t\t\tpass\n\t\t\t\t\n\t\t\t\telif logicValue == 0 or logicValue == 1 or logicValue == 4:\n\t\t\t\t\tgraphicalGrid += listeCharacs[logicValue]\n\t\t\t\t\t\n\t\t\t\telif logicValue == 2:\n\t\t\t\t\tgraphicalGrid += self.metaData[\"links\"][str(counterLinks)][1]\n\t\t\t\t\tdoNotAddAnything += len(self.metaData[\"links\"][str(counterLinks)][1]) - 1\n\t\t\t\t\tcounterLinks += 1\n\t\t\t\t\n\t\t\t\telif logicValue ==3:\n\t\t\t\t\tif counterButtons < self.numberButtons - 1:\n\n\t\t\t\t\t\tgraphicalGrid = graphicalGrid[:-6] + \"[{}] : \".format(self.metaData[\"buttons\"][str(counterButtons)][0])\n\t\t\t\t\t\tgraphicalGrid += self.metaData[\"buttons\"][str(counterButtons)][1]\n\t\t\t\t\t\tdoNotAddAnything += len(self.metaData[\"buttons\"][str(counterButtons)][1]) - 1\n\t\t\t\t\t\tcounterButtons += 1\n\n\t\t\t\t\telif counterButtons == self.numberButtons - 1 :\n\t\t\t\t\t\tcounterButtons = \"-1\"\n\n\t\t\t\t\t\tgraphicalGrid = graphicalGrid[:-6] + \"[{}] : \".format(self.metaData[\"buttons\"][counterButtons][0])\n\t\t\t\t\t\tgraphicalGrid += self.metaData[\"buttons\"][counterButtons][1]\n\t\t\t\t\t\tdoNotAddAnything += len(self.metaData[\"buttons\"][counterButtons][1]) - 1\n\t\t\t\t\t\tcounterButtons = self.numberButtons - 1\n\n\t\t\t\t\n\t\t\tgraphicalGrid += \"\\n\"\n\t\t\n\t\treturn graphicalGrid \n\n\tdef ShowGraphicalGrid(self):\n\t\tself.graphicalGrid = self.generateGraphicalGrid()\n\t\tos.system(\"clear\")\n\t\tprint(self.graphicalGrid)\n\n\t\treturn None\n\n\n##########################################################################################################################################\n","sub_path":"Frame.py","file_name":"Frame.py","file_ext":"py","file_size_in_byte":7950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"479198865","text":"\"\"\" Util functions to split data into train/val. \"\"\"\nfrom __future__ import print_function, division\n\nimport os\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom pandas.api.types import is_string_dtype\nfrom collections import OrderedDict\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom sklearn.model_selection import ShuffleSplit, KFold\nfrom sklearn.model_selection import GroupShuffleSplit, GroupKFold\nfrom sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold\n\nfrom utils.plots import plot_hist\n\n\ndef data_splitter( n_splits=1, gout=None, outfigs=None, ydata=None, \n print_fn=print, **kwargs):\n \"\"\"\n This func calls get_single_splits() a total of n_splits times to generate\n multiple train/val/test splits.\n Args:\n n_splits : number of splits\n gout : global outdir to dump the splits\n outfigs : outdir to dump the distributions of target variable\n ydata : the target variable\n split_on : vol name in the dataframe to use for hard (group) partition\n print_fn : print function\n Return:\n tr_dct, vl_dct, te_dct : tuple of split dicts\n \"\"\"\n seeds = np.random.choice(1000000, n_splits, replace=False)\n\n # These dicts will contain the splits\n tr_dct = {}\n vl_dct = {}\n te_dct = {}\n\n for i, seed in enumerate( seeds ):\n tr_id, vl_id, te_id = gen_single_split(ydata=ydata, seed=seed, **kwargs)\n\n tr_dct[i] = tr_id\n vl_dct[i] = vl_id\n te_dct[i] = te_id\n\n # digits = len(str(n_splits))\n seed_str = str(i) # f\"{seed}\".zfill(digits)\n output = '1fold_s' + seed_str \n \n if gout is not None:\n np.savetxt( gout/f'{output}_tr_id.csv', tr_id.reshape(-1,1), fmt='%d', delimiter='', newline='\\n' )\n np.savetxt( gout/f'{output}_vl_id.csv', vl_id.reshape(-1,1), fmt='%d', delimiter='', newline='\\n' )\n np.savetxt( gout/f'{output}_te_id.csv', te_id.reshape(-1,1), fmt='%d', delimiter='', newline='\\n' )\n \n if (ydata is not None) and (outfigs is not None):\n plot_hist(ydata, title=f'Train Set Histogram',\n fit=None, bins=100, path=outfigs/f'{output}_y_hist_train.png')\n plot_hist(ydata, title=f'Val Set Histogram',\n fit=None, bins=100, path=outfigs/f'{output}_y_hist_val.png')\n plot_hist(ydata, title=f'Test Set Histogram',\n fit=None, bins=100, path=outfigs/f'{output}_y_hist_test.png')\n return (tr_dct, vl_dct, te_dct)\n\n\ndef gen_single_split( data, te_method='simple', cv_method='simple', te_size=0.1,\n mltype='reg', ydata=None, split_on=None, seed=None, print_fn=print ):\n \"\"\"\n This func generates train/val/test split indices. \n Args:\n data : dataframe\n te_method : method to split data (D) into test (E) and train (T0)\n cv_method : method to split the test from te_method (T0) into train (T1) and validation (V)\n te_size : fraction of data (D) to extract for test set (E)\n mltype : ml type (task)\n ydata : the target variable\n split_on : vol name in the dataframe to use for hard (group) partition\n seed : see value\n print_fn : print function\n Return:\n tr_id, vl_id, te_id : tuple of 1-D arrays specifying the indices in the original input data\n \"\"\"\n np.random.seed( seed )\n idx_vec = np.random.permutation( data.shape[0] )\n y_vec = ydata.values[idx_vec]\n \n # Create splitter that splits the full dataset into tr and te\n te_folds = int(1/te_size)\n te_splitter = cv_splitter(cv_method=te_method, cv_folds=te_folds, test_size=None,\n mltype=mltype, shuffle=False, random_state=seed)\n \n te_grp = None if split_on is None else data[split_on].values[idx_vec]\n if is_string_dtype(te_grp): te_grp = LabelEncoder().fit_transform(te_grp)\n \n # Split data (D) into tr (T0) and te (E)\n tr_id, te_id = next( te_splitter.split(X=idx_vec, y=y_vec, groups=te_grp) )\n tr_id = idx_vec[tr_id] # adjust the indices! we'll split the remaining tr into tr and vl\n te_id = idx_vec[te_id] # adjust the indices!\n\n # Update a vector array that excludes the test indices\n idx_vec_ = tr_id; del tr_id\n y_vec_ = ydata.values[idx_vec_]\n\n # Define vl_size while considering the new full size of the available samples\n vl_size = te_size / (1 - te_size)\n cv_folds = int(1/vl_size)\n\n # Create splitter that splits tr (T0) into tr (T1) and vl (V)\n cv = cv_splitter(cv_method=cv_method, cv_folds=cv_folds, test_size=None,\n mltype=mltype, shuffle=False, random_state=seed) \n \n cv_grp = None if split_on is None else data[split_on].values[idx_vec_]\n if is_string_dtype(cv_grp): cv_grp = LabelEncoder().fit_transform(cv_grp)\n \n # Split tr into tr and vl\n tr_id, vl_id = next( cv.split(X=idx_vec_, y=y_vec_, groups=cv_grp) )\n tr_id = idx_vec_[tr_id] # adjust the indices!\n vl_id = idx_vec_[vl_id] # adjust the indices!\n\n # Make sure that indices do not overlap\n assert len( set(tr_id).intersection(set(vl_id)) ) == 0, 'Overlapping indices btw tr and vl'\n assert len( set(tr_id).intersection(set(te_id)) ) == 0, 'Overlapping indices btw tr and te'\n assert len( set(vl_id).intersection(set(te_id)) ) == 0, 'Overlapping indices btw tr and vl'\n \n # Print split ratios\n print_fn('Train samples {} ({:.2f}%)'.format( len(tr_id), 100*len(tr_id)/data.shape[0] ))\n print_fn('Val samples {} ({:.2f}%)'.format( len(vl_id), 100*len(vl_id)/data.shape[0] ))\n print_fn('Test samples {} ({:.2f}%)'.format( len(te_id), 100*len(te_id)/data.shape[0] ))\n \n # Confirm that group splits are correct (no intersect)\n if split_on is not None:\n print_intersect_on_var(data, tr_id=tr_id, vl_id=vl_id, te_id=te_id, grp_col=split_on, print_fn=print_fn)\n\n return tr_id, vl_id, te_id\n\n\ndef cv_splitter(cv_method: str='simple', cv_folds: int=1, test_size: float=0.2,\n mltype: str='reg', shuffle: bool=False, random_state=None):\n \"\"\" Creates a cross-validation splitter.\n Args:\n cv_method: 'simple', 'stratify' (only for classification), 'groups' (only for regression)\n cv_folds: number of cv folds\n test_size: fraction of test set size (used only if cv_folds=1)\n mltype: 'reg', 'cls'\n \"\"\"\n # Classification\n if mltype == 'cls':\n if cv_method == 'simple':\n if cv_folds == 1:\n cv = ShuffleSplit(n_splits=cv_folds, test_size=test_size, random_state=random_state)\n else:\n cv = KFold(n_splits=cv_folds, shuffle=shuffle, random_state=random_state)\n \n elif cv_method == 'strat':\n if cv_folds == 1:\n cv = StratifiedShuffleSplit(n_splits=cv_folds, test_size=test_size, random_state=random_state)\n else:\n cv = StratifiedKFold(n_splits=cv_folds, shuffle=shuffle, random_state=random_state)\n\n elif cv_method == 'group':\n if cv_folds == 1:\n raise ValueError('GroupShuffleSplit splits groups based on group count and not based on sample count.')\n # https://github.com/scikit-learn/scikit-learn/issues/13369\n # https://github.com/scikit-learn/scikit-learn/issues/9193\n cv = GroupShuffleSplit(n_splits=cv_folds, test_size=test_size, random_state=random_state)\n else:\n cv = GroupKFold(n_splits=cv_folds)\n\n # Regression\n elif mltype == 'reg':\n if cv_method == 'simple':\n if cv_folds == 1:\n cv = ShuffleSplit(n_splits=cv_folds, test_size=test_size, random_state=random_state)\n else:\n cv = KFold(n_splits=cv_folds, shuffle=shuffle, random_state=random_state)\n\n elif cv_method == 'group':\n if cv_folds == 1:\n raise ValueError('GroupShuffleSplit splits groups based on group count and not based on sample count.')\n # https://github.com/scikit-learn/scikit-learn/issues/13369\n # https://github.com/scikit-learn/scikit-learn/issues/9193\n cv = GroupShuffleSplit(n_splits=cv_folds, test_size=test_size, random_state=random_state)\n else:\n cv = GroupKFold(n_splits=cv_folds)\n return cv\n\n\ndef print_intersect_on_var(df, tr_id, vl_id, te_id, grp_col='CELL', print_fn=print):\n \"\"\" Print intersection between train, val, and test datasets with respect\n to grp_col column if provided. df is usually a metadata.\n \"\"\"\n if grp_col in df.columns:\n tr_grp_unq = set( df.loc[tr_id, grp_col] )\n vl_grp_unq = set( df.loc[vl_id, grp_col] )\n te_grp_unq = set( df.loc[te_id, grp_col] )\n print_fn(f'\\tTotal intersects on {grp_col} btw tr and vl: {len(tr_grp_unq.intersection(vl_grp_unq))}')\n print_fn(f'\\tTotal intersects on {grp_col} btw tr and te: {len(tr_grp_unq.intersection(te_grp_unq))}')\n print_fn(f'\\tTotal intersects on {grp_col} btw vl and te: {len(vl_grp_unq.intersection(te_grp_unq))}')\n print_fn(f'\\tUnique {grp_col} in tr: {len(tr_grp_unq)}')\n print_fn(f'\\tUnique {grp_col} in vl: {len(vl_grp_unq)}')\n print_fn(f'\\tUnique {grp_col} in te: {len(te_grp_unq)}') \n else:\n raise(f'The column {grp_col} was not found!')\n\n\ndef split_size(x):\n \"\"\" Split size can be float (0, 1) or int (casts value as needed). \"\"\"\n assert x > 0, 'Split size must be greater than 0.'\n return int(x) if x > 1.0 else x\n\n \ndef plot_ytr_yvl_dist(ytr, yvl, title=None, outpath='.'):\n \"\"\" Plot distributions of response data of train and val sets. \"\"\"\n fig, ax = plt.subplots()\n plt.hist(ytr, bins=100, label='ytr', color='b', alpha=0.5)\n plt.hist(yvl, bins=100, label='yvl', color='r', alpha=0.5)\n if title is None: title = ''\n plt.title(title)\n plt.tight_layout()\n plt.grid(True)\n plt.legend()\n if outpath is None:\n plt.savefig(Path(outpath)/'ytr_yvl_dist.png', bbox_inches='tight')\n else:\n plt.savefig(outpath, bbox_inches='tight')\n\n\n","sub_path":"src/datasplit/splitter.py","file_name":"splitter.py","file_ext":"py","file_size_in_byte":10207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"14881610","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0011_auto_20120103_1700'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Report',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('text', models.CharField(max_length=10000)),\n ('pub_date', models.DateField()),\n ('author', models.ForeignKey(to='app.Char')),\n ('related_mission', models.ForeignKey(to='app.Mission')),\n ],\n ),\n ]\n","sub_path":"xcom40k/app/migrations/0012_report.py","file_name":"0012_report.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"533093295","text":"import numpy as np\nimport mdtraj as md\nimport multiprocessing\nimport glob\nimport pyemma\n\n# list of contacts to check from extraction of top5\ncontacts_dict = {3: [(55, 93), (55, 94), (55, 126), (55, 127)],\n 5: [(134, 1), (158, 35), (158, 107)],\n 6: [(134, 1)],\n 8: [(76, 96)],\n 10: [(152, 82), (157, 80), (160, 74), (160, 77)],\n 12: [(82, 93),\n (89, 58),\n (89, 59),\n (90, 58),\n (90, 92),\n (91, 57),\n (91, 93),\n (83, 92),\n (61, 85),\n (61, 88)],\n 13: [(8, 119), (15, 4), (48, 3), (48, 5), (68, 149), (72, 151), (79, 159)],\n 14: [(55, 58), (55, 100), (100, 97), (101, 54), (102, 54)],\n 15: [(100, 37)],\n 17: [(106, 145), (158, 107)],\n 18: [(124, 119)],\n 21: [(55, 58), (55, 93), (55, 94), (55, 126), (55, 127), (158, 107)],\n 22: [(146, 116), (146, 82)]}\n \nframe_indexes = np.load('extract_frames_max_relative_paper_fixnoframes.npy')\n\n# now with Booleyan contacts\ndef get_run_contact_map(run):\n \n traj_started = False\n\n for clone in range(40):\n traj = md.load('data/run%d-clone%d.h5' % (run,clone))\n # trajs are 0.5 ns / frame, we want only the part after 750 ns == 1500 frames\n if not (len(traj) > 1500):\n continue\n else:\n traj = traj[1500:]\n distances, residue_pairs = md.compute_contacts(traj)\n contact_map = md.geometry.squareform(distances, residue_pairs)\n contact_map_bool = contact_map < 0.4\n\n contacts_to_check = contacts_dict[run]\n for frame_index, frame_contact_map in enumerate(contact_map_bool):\n if all([frame_contact_map[x[0],x[1]] for x in contacts_to_check]):\n if traj_started:\n all_frames_traj = md.join([all_frames_traj, traj[frame_index].atom_slice(traj.top.select('name CA'))])\n else:\n all_frames_traj = traj[frame_index].atom_slice(traj.top.select('name CA'))\n traj_started = True\n \n return all_frames_traj \n \ndef cluster_trajs(run):\n no = {3:0,5:1,6:2,8:3,10:4,12:5,13:6,14:7,15:8,17:9,18:10,21:11,22:12}[run]\n frames = frame_indexes[no]\n # now cluster\n all_frames_traj = md.load('all_frames_traj_%d.h5' % run) \n top = all_frames_traj.top\n del all_frames_traj\n data = pyemma.coordinates.load('all_frames_traj_%d.h5' % run, top=top)\n clustering = pyemma.coordinates.cluster_regspace(data, dmin=0.3, metric='minRMSD')\n cluster_indexes = clustering.index_clusters\n \n cluster_indexes_ = []\n for cluster in cluster_indexes:\n center = cluster[0][1]\n cluster_indexes_.append(frames[center])\n \n frame = cluster_indexes_[0]\n cluster_traj = md.load('data/run%d-clone%d.h5' % (run,frame[0]))[frame[1]+1500]\n for frame in cluster_indexes_[1:]:\n cluster_traj = md.join([cluster_traj,md.load('data/run%d-clone%d.h5' % (run,frame[0]))[frame[1]+1500]])\n\n return cluster_traj\n\n# now run stuff\npool = multiprocessing.Pool(13)\n\nall_frames_trajs = pool.map(get_run_contact_map, [3,5,6,8,10,12,13,14,15,17,18,21,22])\n\nfor i,traj in enumerate(all_frames_trajs):\n no = [3,5,6,8,10,12,13,14,15,17,18,21,22][i]\n traj.save('all_frames_traj_%d.h5' % no)\n \npool = multiprocessing.Pool(13) \n \ncluster_trajs = pool.map(cluster_trajs, [3,5,6,8,10,12,13,14,15,17,18,21,22])\n\nfor i,traj in enumerate(cluster_trajs):\n no = [3,5,6,8,10,12,13,14,15,17,18,21,22][i]\n traj.save('cluster_traj_%d.h5' % no)\n traj.save('cluster_traj_%d.pdb' % no)\n","sub_path":"MUTANTS/analysis/extract_frames_max_relative_paper_cluster.py","file_name":"extract_frames_max_relative_paper_cluster.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"86552917","text":"from __future__ import print_function\nimport numpy as np\nimport pickle\nimport os\n\nos.environ['KERAS_BACKEND'] = 'theano'\nfrom load import *\nfrom metrics.accuracy import conlleval\nfrom load import *\nfrom keras.models import Sequential\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.recurrent import SimpleRNN, GRU, LSTM\nfrom keras.layers.core import Dense, Dropout\nfrom keras.layers.wrappers import TimeDistributed\nfrom keras.layers import Convolution1D, MaxPooling1D\nfrom accuracy import conlleval\nimport progressbar\n\n\n\n### Load Data\ntrain_set, valid_set,test_set,dicts = load_dataset(2)\nw2idx, ne2idx, labels2idx = dicts['words2idx'], dicts['tables2idx'], dicts['labels2idx']\n\n# get index to word dict\nidx2w = get_id_to_word_dict(dicts)\nidx2la = get_id_to_label_dict(dicts)\n\n\n### Model\nn_classes = len(idx2la)\nn_vocab = len(idx2w)\n\n# Define model\nmodel = Sequential()\nmodel.add(Embedding(n_vocab,100))\nmodel.add(Convolution1D(64,5,border_mode='same', activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(SimpleRNN(100,return_sequences=True))\nmodel.add(TimeDistributed(Dense(n_classes, activation='softmax')))\nmodel.compile('rmsprop', 'categorical_crossentropy')\n\n\ntrain_x, train_ne, train_label = train_set\nval_x, val_ne, val_label = valid_set\ntest_x, test_ne, test_label = test_set\nvalidationX = [ list(map(lambda x: idx2w[x], w)) for w in val_x]\nvalidationY = [ list(map(lambda x: idx2la[x], y)) for y in val_label]\ntrainX = [ list(map(lambda x: idx2w[x], w)) for w in train_x]\ntrainY = [ list(map(lambda x: idx2la[x], y)) for y in train_label]\ntestX = [ list(map(lambda x: idx2w[x], w)) for w in test_x]\ntestY = [ list(map(lambda x: idx2la[x], y)) for y in test_label]\n\n### Training\nn_epochs = 100\n\ntrain_f_scores = []\nval_f_scores = []\ntest_f_scores = []\nbest_val_f1 = 0\nbest_test_f1 = 0\n\nfor i in range(n_epochs):\n print(\"Epoch {}\".format(i))\n \n print(\"Training =>\")\n train_pred_label = []\n avgLoss = 0\n \n bar = progressbar.ProgressBar(max_value=len(train_x))\n for n_batch, sent in bar(enumerate(train_x)):\n label = train_label[n_batch]\n label = np.eye(n_classes)[label][np.newaxis,:]\n sent = sent[np.newaxis,:]\n #print(sent)\n if sent.shape[1] > 1: #some bug in keras\n loss = model.train_on_batch(sent, label)\n avgLoss += loss\n\n pred = model.predict_on_batch(sent)\n pred = np.argmax(pred,-1)[0]\n #print(pred)\n train_pred_label.append(pred)\n\n avgLoss = avgLoss/n_batch\n predword_train = [ list(map(lambda x: idx2la[x], y)) for y in train_pred_label]\n con_dict = conlleval(predword_train, trainY, trainY , 'r.txt')\n train_f_scores.append(con_dict['f1'])\n print('Loss = {}, Precision = {}, Recall = {}, F1 = {}'.format(avgLoss, con_dict['r'], con_dict['p'], con_dict['f1']))\n\n print(\"Validating =>\")\n \n val_pred_label = []\n avgLoss = 0\n \n bar = progressbar.ProgressBar(max_value=len(val_x))\n for n_batch, sent in bar(enumerate(val_x)):\n label = val_label[n_batch]\n label = np.eye(n_classes)[label][np.newaxis,:]\n sent = sent[np.newaxis,:]\n \n if sent.shape[1] > 1: #some bug in keras\n loss = model.test_on_batch(sent, label)\n avgLoss += loss\n\n pred = model.predict_on_batch(sent)\n pred = np.argmax(pred,-1)[0]\n val_pred_label.append(pred)\n\n avgLoss = avgLoss/n_batch\n \n predword_val = [ list(map(lambda x: idx2la[x], y)) for y in val_pred_label]\n con_dict = conlleval(predword_val, validationY, validationX, 'r.txt')\n val_f_scores.append(con_dict['f1'])\n \n print('Loss = {}, Precision = {}, Recall = {}, F1 = {}'.format(avgLoss, con_dict['r'], con_dict['p'], con_dict['f1']))\n\n if con_dict['f1'] > best_val_f1:\n best_val_f1 = con_dict['f1']\n open('model_architecture.json','w').write(model.to_json())\n model.save_weights('best_model_weights.h5',overwrite=True)\n print(\"Best validation F1 score = {}\".format(best_val_f1))\n print()\n\n print(\"Testing =>\")\n \n test_pred_label = []\n avgLoss = 0\n \n bar = progressbar.ProgressBar(max_value=len(test_x))\n for n_batch, sent in bar(enumerate(test_x)):\n label = test_label[n_batch]\n label = np.eye(n_classes)[label][np.newaxis,:]\n sent = sent[np.newaxis,:]\n \n if sent.shape[1] > 1: #some bug in keras\n loss = model.test_on_batch(sent, label)\n avgLoss += loss\n\n pred = model.predict_on_batch(sent)\n pred = np.argmax(pred,-1)[0]\n test_pred_label.append(pred)\n\n avgLoss = avgLoss/n_batch\n \n predword_test = [ list(map(lambda x: idx2la[x], y)) for y in test_pred_label]\n con_dict1 = conlleval(predword_test, testY, testX, 'r.txt')\n test_f_scores.append(con_dict1['f1'])\n \n print('Loss = {}, Precision = {}, Recall = {}, F1 = {}'.format(avgLoss, con_dict1['r'], con_dict1['p'], con_dict1['f1']))\n\n if con_dict1['f1'] > best_test_f1:\n best_test_f1 = con_dict1['f1']\n open('model_architecture1.json','w').write(model.to_json())\n model.save_weights('best_model_weights1.h5',overwrite=True)\n print(\"Best test F1 score = {}\".format(best_test_f1))\n print()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"497107132","text":"import base64\nimport boto3\nfrom PIL import Image\nimport io\nfrom lambda_util.util import get_logger\nlog = get_logger()\n\ndef process_image(image_data):\n image_jpg = to_jpeg(image_data)\n string_image = encode_image(image_jpg)\n return(string_image)\n\n\ndef decode_image(image_string, output_file='test_output.jpg'):\n binary_image = base64.decodestring(image_string)\n image_result = open(output_file, 'wb')\n image_result.write(binary_image)\n\n\ndef process_image2(image_name, width = None, height = None):\n \"\"\"\n Fetch and base64 encode image\n \"\"\"\n if width == None and height == None:\n return(encode_image(to_jpeg(get_s3_image(image_name))))\n else:\n return(encode_image(resize_image(to_jpeg(get_s3_image(image_name)), width, height)))\n\n\ndef encode_image(image_data):\n \"\"\"\n Given binary image data, base64 encode and return results\n \"\"\"\n image_bytes = base64.b64encode(image_data)\n image_str = image_bytes.decode('ascii')\n return(image_str)\n\n\ndef get_local_image(file_name):\n with open(file_name, 'rb') as f:\n image_data = f.read()\n return(image_data)\n\n\ndef get_s3_image(key, bucket='images.findawayworld.com'):\n \"\"\"\n Given a key, fetch the image data into memory and return image data\n \"\"\"\n s3 = boto3.resource('s3')\n obj = s3.Object(bucket, key)\n image_data = obj.get()['Body'].read()\n return(image_data)\n\n\ndef to_jpeg(image_data):\n img = Image.open(io.BytesIO(image_data))\n img_jpeg = img.convert('RGB')\n img_byte = io.BytesIO()\n img_jpeg.save(img_byte, format='jpeg')\n return(img_byte.getvalue())\n\n\ndef resize_image(image_data, width, height):\n img = Image.open(io.BytesIO(image_data))\n img_size = img.size\n if width == None:\n img_ratio = img_size[0] / img_size[1]\n width = int(height * img_ratio)\n elif height == None:\n img_ratio = img_size[1] / img_size[0]\n height = int(width * img_ratio)\n log.debug(\"resize to \" + str(width) + \" by \" + str(height))\n img_resize = img.resize((width, height))\n img_byte = io.BytesIO()\n img_resize.save(img_byte, format='jpeg')\n return(img_byte.getvalue())","sub_path":"image_processor.py","file_name":"image_processor.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"258755255","text":"'''\nCreated on Mar 11, 2016\n\n@author: John\n'''\nimport numpy as np\nimport random\n\n\nclass KM:\n def __init__(self, X, k_number = 2, iteration = 100):\n self.X = X #(N,D)\n self.K = k_number #K\n self.u = np.zeros((k_number, X.shape[1])) #(K,D)\n self.iter = iteration\n self.c = np.zeros(X.shape[0])\n check = []\n for i in range(k_number):\n num = random.randint(0,self.X.shape[0]-1)\n while num in check:\n num = random.randint(0,self.X.shape[0]-1)\n else:\n check.append(num)\n self.u[i] = self.X[num]\n \n def predict(self):\n num_data = self.X.shape[0]\n dim = self.X.shape[1]\n for it in range(self.iter):\n dis = np.zeros((num_data, self.K))\n for i in range(num_data):\n for j in range(self.K):\n dis[i,j] = np.sum((self.X[i] - self.u[j])**2)\n self.c[i] = np.argmin(dis[i])\n for j in range(self.K):\n tot = np.zeros(dim)\n num_of_x = 0\n for i in range(num_data):\n if self.c[i] == j:\n tot += self.X[i]\n num_of_x += 1\n if num_of_x != 0:\n self.u[j] = tot/num_of_x\n return self.u\n\n def loss(self):\n dis = 0\n for i in range(self.X.shape[0]):\n dis+=np.sqrt(np.sum((self.X[i] - self.u[int(self.c[i])])**2))\n return dis\n # min_dis = np.zeros(num_data)+np.infty\n # for j in range(self.K):\n # dis_X_to_uj_sqr = np.sum((self.X - self.u[j-1])**2, axis = 1)\n # check = np.argmin(np.vstack((min_dis, dis_X_to_uj_sqr)), axis = 0)\n # min_dis = np.minimum(min_dis, dis_X_to_uj_sqr)\n # self.c += check\n # for j in range(self.K):\n # if np.sum(self.c==j)!=0:\n # self.u[j] = np.sum((self.c == j).reshape(-1,1)*self.X, axis = 0)/np.sum(self.c == j)\n # print(self.u)\n\n def show_the_label(self):\n return self.c","sub_path":"MachineLearningAssignment/MLA4/ML_Assignment_4/clustering_recommendation/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"584142885","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef transferDisks(n,fromTower,toTower,bufferTower):\n\tif(n == 1):\n\t\tfromPosition,toPosition = 0,0\n\t\t# Il faut rechercher le disque au sommet de la tour fromTower\n\t\t# i.e. la valeur la plus petite de fromTower > 0\n\t\tfor i in range(1,len(fromTower)):\n\t\t\tif(fromTower[i] > 0 and fromTower[i] < fromTower[fromPosition]):\n\t\t\t\tfromPosition = i\n\t\t# afin de le déplacer vers le sommet de la tour toTower\n\t\t# i.e. la première position de valeur 0\n\t\twhile(toTower[toPosition] > 0): toPosition += 1\n\t\t# Ensuite, il faut déplacer le disque fromTower[fromPosition]\n\t\t# vers toTower[toPosition]\n\t\t# i.e. échanger les valeurs\n\t\tfromTower[fromPosition],toTower[toPosition] = toTower[toPosition],fromTower[fromPosition]\n\t\t# interrompre la fonction car l'échange d'un disque s'est déroulé correctement\n\t\treturn\n\t# Cas général, on transfère tous les disques plus petit\n\t# que celui à la base de la tour, sur la tour tampon\n\ttransferDisks(n-1,fromTower,bufferTower,toTower)\n\t# Ensuite, on peut déplacer le plus grand disque sur sa destination\n\ttransferDisks(1,fromTower,toTower,bufferTower)\n\t# Enfin, tous les disques qui ont été déplacés sur la tour tampon\n\t# sont redéplacés vers la tour de destination\n\ttransferDisks(n-1,bufferTower,toTower,fromTower)\n\ndef solverHanoi(towerSize):\n\thanoiTowerA = [i for i in range(towerSize,0,-1)]\n\thanoiTowerB = [0] * towerSize\n\thanoiTowerC = [0] * towerSize\n\tprint(\"Before transfer\")\n\tprint('Tower A: '+str(hanoiTowerA))\n\tprint('Tower B: '+str(hanoiTowerB))\n\tprint('Tower C: '+str(hanoiTowerC))\n\ttransferDisks(towerSize,hanoiTowerA,hanoiTowerC,hanoiTowerB)\n\tprint(\"\\nAfter transfer\")\n\tprint('Tower A: '+str(hanoiTowerA))\n\tprint('Tower B: '+str(hanoiTowerB))\n\tprint('Tower C: '+str(hanoiTowerC))\n\nsolverHanoi(2)\n","sub_path":"Algorithmique/Récursivité/HanoiTowers.py","file_name":"HanoiTowers.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"226211260","text":"# test_database.py\n\"\"\" This module defines all the test functions for database.py \"\"\"\nfrom unittest import TestCase\nimport database as db\n\n\nclass database_Tests(TestCase):\n \"\"\" This class defines unit test fuctions for database.py \"\"\"\n def setUp(self):\n self.csv_file = 'csv_files_dr'\n self.product_file = 'products.csv'\n self.product_failure_file = 'failure_file'\n self.customer_file = 'customers.csv'\n self.rental_file = 'rentals.csv'\n\n def test_import_data(self):\n \"\"\" Test import_data() function \"\"\"\n db.LOGGER.info('--- Start Test import_data() ---')\n actual_res = db.import_data(self.csv_file, self.product_file,\n self.customer_file, self.rental_file)\n client = db.MongoDBConnection()\n with client:\n hp_norton_db = client.connection.rental\n products = hp_norton_db['products']\n customers = hp_norton_db['customers']\n rentals = hp_norton_db['rentals']\n self.assertEqual(products.count(), 5)\n self.assertEqual(customers.count(), 5)\n self.assertEqual(rentals.count(), 9)\n expect_res = [(5, 5, 9), (0, 0, 0)]\n self.assertEqual(actual_res, expect_res)\n db.LOGGER.info('--- End Test import_data() ---')\n\n def test_import_data_failure(self):\n \"\"\" Test import_data() function \"\"\"\n db.LOGGER.info('--- Start Test failure import_data() ---')\n actual_res = db.import_data(self.csv_file, self.product_failure_file,\n self.customer_file, self.rental_file)\n expect_res = [(0, 5, 9), (1, 0, 0)]\n self.assertEqual(actual_res, expect_res)\n db.LOGGER.info('--- End Test failure import_data() ---')\n\n def test_show_available_products(self):\n \"\"\" Test show_available_products() function \"\"\"\n db.LOGGER.info('--- Start Test show_available_products() ---')\n db.import_data(self.csv_file, self.product_file,\n self.customer_file, self.rental_file)\n the_dict = db.show_available_products()\n expect_dict = {'prd001': {'description': '60-inch TV stand',\n 'product_type': 'livingroom',\n 'quantity_available': '3'},\n 'prd002': {'description': 'L-shaped sofa',\n 'product_type': 'livingroom',\n 'quantity_available': '1'},\n 'prd004': {'description': 'microwave oven',\n 'product_type': 'kitchen',\n 'quantity_available': '2'},\n 'prd005': {'description': 'queen size bed',\n 'product_type': 'bedroom',\n 'quantity_available': '3'}}\n self.assertEqual(expect_dict, the_dict)\n for key, val in the_dict.items():\n db.LOGGER.info(f\"-- \\'{key}\\': {val}\")\n db.LOGGER.info('--- End Test show_available_products() ---')\n\n def test_show_rentals(self):\n \"\"\" Test show_rentals() function \"\"\"\n db.LOGGER.info('--- Start Test show_rentals() ---')\n db.import_data(self.csv_file, self.product_file,\n self.customer_file, self.rental_file)\n the_dict = db.show_rentals('prd001')\n expect_dict = {'user002': {'name': 'Maya Data',\n 'address': '4936 Elliot Avenue',\n 'phone_number': '206-777-1927',\n 'email': 'mdata@uw.edu'},\n 'user003': {'name': 'Alen King',\n 'address': '1234 Main Street',\n 'phone_number': '425-889-1200',\n 'email': 'kinga@hotmail.com'}}\n self.assertEqual(expect_dict, the_dict)\n db.LOGGER.info(f'The customers info for renting product: prd001')\n for key, val in the_dict.items():\n db.LOGGER.info(f\"-- \\'{key}\\': {val}\")\n db.LOGGER.info('--- End Test show_rentals() ---')\n","sub_path":"students/zhen_yang/lesson09/assignment/ContextManager_dr/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"179470593","text":"# -*- coding: utf-8 -*-\n\nimport darknet_video\nimport cv2\nimport os \n#from pylsd import lsd\nimport numpy as np\nimport pickle \nfrom pc_lines_diamond.utils import take_lane_towards_horizon, calculate_distance,rotationMatrixToEulerAngles\nfrom random import randrange\nimport random\nimport math\n\nvideos_root = '/media/ixtiyor/New Volume/datasets/auto_callibration/videos/g1'\nvideos = os.listdir(videos_root)\ntry:\n video_src = videos_root + \"/\" + videos[1] # \"GOPR2036_half.mp4\" #\nexcept: \n video_src = 0\ncap = cv2.VideoCapture(video_src)\nprint('creating sort object')\n#print('starting the detection')\n\n\nwith open('calibration.pickle','rb') as f:\n loaded_obj = pickle.load(f)\nvp_1 = loaded_obj['vp1']\nvp_2 = loaded_obj['vp2']\nvp_3 = loaded_obj['vp3']\nf = loaded_obj['f']\nR = loaded_obj['R']\n\n\nwhile(True):\n _, frame = cap.read()\n if(_):\n# frame = cv2.imread(\"dasdadasdasdasd.jpg\",-1); #\"/media/ixtiyor/New Volume/datasets/bdd/bdd100k_images/bdd100k/images/10k/test/af962335-00000000.jpg\",-1)\n detections = darknet_video.detect_from_image(frame)\n \n original_height, original_width , _ = np.shape(frame)\n detections_new, output_formatted = darknet_video.resize_detections(detections, original_height, original_width)\n ## second one is x1,y1, x2,y2\n ## print(detections) \n #frame = darknet_video.cvDrawBoxes(detections_new,frame)\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n for detection in detections_new:\n x, y, w, h = detection[2][0],\\\n detection[2][1],\\\n detection[2][2],\\\n detection[2][3]\n xmin, ymin, xmax, ymax = darknet_video.convertBack(\n float(x), float(y), float(w), float(h))\n # xmin = 150\n # xmax = 205\n # ymin=231 \n # ymax=257\n # padding = 3 \n # frame_gray = frame_gray[ymin-padding:ymax+padding, xmin-padding:xmax+padding]\n # print(np.shape(frame_gray))\n # if(frame_gray.shape[0] * frame_gray.shape[1] > 0):\n # lines = lsd.lsd(np.array(frame_gray, np.float32))\n # lines = lines[:,0:4] \n # for j in range(lines.shape[0]):\n # if(int(lines[j, 0] + xmin) < original_height and int(lines[j, 1] + ymin) < original_width):\n # pt1 = (int(lines[j, 0] + xmin - padding), int(lines[j, 1] + ymin - padding))\n # pt2 = (int(lines[j, 2] + xmin - padding), int(lines[j, 3] + ymin - padding))\n # length = np.sqrt(np.sum(np.square(np.array(pt1) - np.array(pt2))))\n # print(length)\n # if(length > 10):\n # cv2.line(frame, pt1,pt2, (0, 255, 255), 1)\n # cv2.imshow('frame', frame_gray)\n # print(ymin, vp_1)\n angles = rotationMatrixToEulerAngles(R,False) \n thigma = math.atan( vp_1[1] / math.sqrt(vp_1[0]* vp_1[0] + f*f))\n print('thigma = ', thigma)\n dist_ = calculate_distance(vp_1, ymax, f,3.2672, thigma)\n cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), (255,0,0), 1)\n cv2.putText(frame,\n detection[0].decode() + \" \" + str(np.round(dist_, 2)) + \" m\",\n (xmin, ymin - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.4,\n [0, 255, 255], 1)\n for i in range(3):\n random.seed(i)\n line1 = []\n line2 = []\n line3 = []\n point_r = (randrange(original_width), randrange(original_height))\n if(len(vp_1) > 0):\n line1 = take_lane_towards_horizon(point_r,vp_1, length=30)\n if(len(vp_2) > 0):\n line2 = take_lane_towards_horizon(point_r,vp_2, length=30) \n if(len(vp_3) > 0):\n line3 = take_lane_towards_horizon(point_r,vp_3, length=30) \n \n if(len(line1) > 0):\n cv2.arrowedLine(frame, line1[1], line1[0] , (0,0,255), 2, 8)\n if(len(line2) > 0):\n cv2.arrowedLine(frame, line2[1], line2[0], (255,0,0), 2, 8)\n if(len(line3) > 0):\n cv2.arrowedLine(frame, line3[1], line3[0], (0,255,0), 2, 8) \n cv2.imshow('img', frame)\n ch = cv2.waitKey(500)\n if(ch == 27):\n cv2.destroyAllWindows()\n break\n\n","sub_path":"yolo_detection.py","file_name":"yolo_detection.py","file_ext":"py","file_size_in_byte":4595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"316602357","text":"# -*- coding: utf-8 -*-\nfrom flask import render_template, redirect, url_for, flash, request\nfrom flask.ext.login import login_user, logout_user, login_required\nfrom .. import db, login_manager\nfrom . import auth\nfrom .forms import LoginForm, RegisterForm, flash_form_errors\nfrom .models import User\n\n@login_manager.user_loader\ndef load_user(id):\n return User.query.get(int(id))\n\n@auth.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm(request.form)\n if request.method == 'POST':\n if form.validate_on_submit():\n login_user(form.user, form.remember_me.data)\n flash(\"You are logged in.\", \"success\")\n return redirect(request.args.get('next') or url_for('main.index'))\n else:\n flash_form_errors(form)\n return render_template('auth/login.html', form=form)\n\n@auth.route('/logout', methods=['GET'])\n@login_required\ndef logout():\n logout_user()\n flash('You have been logged out', 'success')\n\n return redirect(url_for('auth.login'))\n\n@auth.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n form = RegisterForm(request.form)\n if request.method == 'POST':\n if form.validate_on_submit():\n new_user = User(username=form.username.data,\n password=form.password.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Thank you for registering.', 'success')\n login_user(new_user)\n return redirect(url_for('main.index'))\n else:\n flash_form_errors(form)\n return render_template('auth/register.html', form=form)\n","sub_path":"raffle/auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"400758830","text":"from aiworkbench.optimization.basicoptimizer import BasicOptimizer\nimport numpy as np\n\n\nclass BatchGradientDescentOptimizer(BasicOptimizer):\n def __init__(self, **kwargs):\n super().__init__()\n self.learning_rate = 0.005\n self.relative_change = 0.01\n self.max_iterations = 1000\n if \"learning_rate\" in kwargs:\n self.learning_rate = kwargs[\"learning_rate\"]\n if \"relative_change\" in kwargs:\n self.relative_change = kwargs[\"relative_change\"]\n if \"max_iterations\" in kwargs:\n self.max_iterations = kwargs[\"max_iterations\"]\n\n def optimize(self, function, function_prime, start_parameter):\n start = function(start_parameter)\n self.cost_history.append(start)\n self.parameter_history.append(np.copy(start_parameter))\n parameter = start_parameter\n while True:\n derivs = function_prime(parameter)\n parameter -= np.transpose(self.learning_rate * derivs)\n cost = function(parameter)\n self.cost_history.append(cost)\n self.parameter_history.append(np.copy(parameter))\n if len(self.cost_history) >= self.max_iterations or self.learning_rate * np.linalg.norm(\n derivs) < self.relative_change:\n break\n return parameter\n","sub_path":"aiworkbench/optimization/gradientdescent.py","file_name":"gradientdescent.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"547224965","text":"import uuid\nimport json\n\nfrom flask import url_for\n\nfrom dataservice.extensions import db\nfrom dataservice.api.cavatica_task.models import CavaticaTask\nfrom dataservice.api.cavatica_app.models import CavaticaApp\nfrom tests.utils import FlaskTestCase\n\nCAVATICA_TASK_URL = 'api.cavatica_tasks'\nCAVATICA_TASK_LIST_URL = 'api.cavatica_tasks_list'\n\n\nclass CavaticaTaskTest(FlaskTestCase):\n \"\"\"\n Test cavatica_task api endpoints\n \"\"\"\n\n def test_post_cavatica_task(self):\n \"\"\"\n Test creating a new cavatica_task\n \"\"\"\n response = self._make_cavatica_task(name='task1')\n resp = json.loads(response.data.decode('utf-8'))\n\n self.assertEqual(response.status_code, 201)\n\n self.assertIn('cavatica_task', resp['_status']['message'])\n self.assertIn('created', resp['_status']['message'])\n\n cavatica_task = resp['results']\n task = CavaticaTask.query.get(cavatica_task['kf_id'])\n self.assertEqual(task.name, cavatica_task['name'])\n\n def test_get_cavatica_task(self):\n \"\"\"\n Test retrieving a cavatica_task by id\n \"\"\"\n resp = self._make_cavatica_task('task1')\n resp = json.loads(resp.data.decode('utf-8'))\n kf_id = resp['results']['kf_id']\n\n response = self.client.get(url_for(CAVATICA_TASK_URL,\n kf_id=kf_id),\n headers=self._api_headers())\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 200)\n\n cavatica_task = resp['results']\n task = CavaticaTask.query.get(kf_id)\n self.assertEqual(kf_id, cavatica_task['kf_id'])\n self.assertEqual(kf_id, task.kf_id)\n self.assertEqual(task.name, cavatica_task['name'])\n\n def test_get_all_cavatica_tasks(self):\n \"\"\"\n Test retrieving all cavatica_tasks\n \"\"\"\n self._make_cavatica_task(name='TEST')\n\n response = self.client.get(url_for(CAVATICA_TASK_LIST_URL),\n headers=self._api_headers())\n status_code = response.status_code\n response = json.loads(response.data.decode('utf-8'))\n content = response.get('results')\n self.assertEqual(status_code, 200)\n self.assertIs(type(content), list)\n self.assertEqual(len(content), 1)\n\n def test_patch_cavatica_task(self):\n \"\"\"\n Test updating an existing cavatica_task\n \"\"\"\n orig = CavaticaTask.query.count()\n response = self._make_cavatica_task(name='TEST')\n resp = json.loads(response.data.decode('utf-8'))\n cavatica_task = resp['results']\n kf_id = cavatica_task['kf_id']\n body = {\n 'name': 'new name',\n }\n self.assertEqual(orig + 1, CavaticaTask.query.count())\n response = self.client.patch(url_for(CAVATICA_TASK_URL,\n kf_id=kf_id),\n headers=self._api_headers(),\n data=json.dumps(body))\n # Status code\n self.assertEqual(response.status_code, 200)\n\n # Message\n resp = json.loads(response.data.decode('utf-8'))\n self.assertIn('cavatica_task', resp['_status']['message'])\n self.assertIn('updated', resp['_status']['message'])\n\n # Content - check only patched fields are updated\n task = CavaticaTask.query.get(kf_id)\n self.assertEqual(task.name, resp['results']['name'])\n self.assertEqual(orig + 1, CavaticaTask.query.count())\n\n def test_delete_cavatica_task(self):\n \"\"\"\n Test deleting a cavatica_task by id\n \"\"\"\n orig = CavaticaTask.query.count()\n resp = self._make_cavatica_task('TEST')\n resp = json.loads(resp.data.decode('utf-8'))\n kf_id = resp['results']['kf_id']\n\n response = self.client.delete(url_for(CAVATICA_TASK_URL,\n kf_id=kf_id),\n headers=self._api_headers())\n\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 200)\n self.assertEqual(CavaticaTask.query.count(), orig)\n\n response = self.client.get(url_for(CAVATICA_TASK_URL,\n kf_id=kf_id),\n headers=self._api_headers())\n\n resp = json.loads(response.data.decode('utf-8'))\n self.assertEqual(response.status_code, 404)\n\n def _make_cavatica_task(self, name='task1'):\n \"\"\"\n Create a new cavatica_task with given name\n \"\"\"\n data = {\n 'external_cavatica_app_id': 'app1',\n 'name': 'ImAwsammmmm',\n 'revision': 1,\n }\n app = CavaticaApp(**data)\n db.session.add(app)\n db.session.commit()\n body = {\n 'name': name,\n 'external_cavatica_task_id': str(uuid.uuid4()),\n 'cavatica_app_id': app.kf_id\n }\n response = self.client.post(url_for(CAVATICA_TASK_LIST_URL),\n headers=self._api_headers(),\n data=json.dumps(body))\n return response\n","sub_path":"tests/cavatica_task/test_cavatica_task_resources.py","file_name":"test_cavatica_task_resources.py","file_ext":"py","file_size_in_byte":5254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"632461064","text":"# encoding: utf-8\n\nimport numpy as np\nimport tensorflow as tf\nimport os\nimport cv2\nfrom tqdm import tqdm\nimport re\nimport sys\nsys.path.append('..')\nfrom config import cfg\n\ndef load_file(file_path):\n '''\n load imgs_path, classes and labels\n '''\n imgs_path = []\n classes = []\n labels = []\n labels_and_classes = []\n with open(file_path, 'r') as f:\n lines = f.readlines()\n for line in lines:\n img_path = line.strip().split(' ')[0]\n cls = int(line.strip().split(' ')[1])\n label = [float(i) for i in line.strip().split(' ')[2:]]\n imgs_path.append(img_path)\n classes.append(cls)\n labels.append(label)\n label.append(cls)\n labels_and_classes.append(label)\n return np.asarray(imgs_path), np.asarray(classes), np.asarray(labels), np.array(labels_and_classes)\n\ndef extract_image(image_path, height, width, is_resize=True):\n '''\n get b->g->r image data\n '''\n image = cv2.imread(image_path)\n if is_resize:\n print('is_resize')\n image = cv2.resize(image, (width, height))\n image_data = np.array(image, dtype='float32') / 255.0\n return image_data\n\ndef run_encode(file_path, tf_records_filename):\n '''\n encode func\n '''\n imgs_path, classes, labels, labels_and_classes = load_file(file_path)\n height, width = 1080, 1920\n imgs = []\n writer = tf.python_io.TFRecordWriter(tf_records_filename)\n for i in tqdm(range(imgs_path.shape[0])):\n img = extract_image(imgs_path[i], height, width, is_resize=False)\n img = img.tostring()\n label_and_class = labels_and_classes[i].flatten().tolist()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'label_and_class' : tf.train.Feature(float_list = tf.train.FloatList(value=label_and_class)),\n 'feature': tf.train.Feature(bytes_list = tf.train.BytesList(value=[img]))\n }))\n writer.write(example.SerializeToString())\n writer.close()\n\nif __name__ == '__main__':\n file_path = re.sub(r'prepare_data', '', os.getcwd()) + 'data/train_list/train.txt'\n tf_records_filename = cfg.data_path\n run_encode(file_path, tf_records_filename)\n","sub_path":"bar_chart_detect/prepare_data/gen_tf_records_fast.py","file_name":"gen_tf_records_fast.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"17787798","text":"\"\"\"\nDummy\n\"\"\"\n\n\nclass Dummy(object):\n \"\"\"\n Dummy class\n \"\"\"\n def __init__(self):\n self.some_property = None\n\n\nif __name__ == '__main__':\n\n register = {\n 'String': str,\n 'Dummy': Dummy\n }\n\n d = Dummy()\n\n # Find the registered type\n for k, v in register.items():\n if isinstance(d, v):\n print(k)\n break\n else:\n print('Not registered')\n","sub_path":"core/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"50581754","text":"from django.conf.urls import url\nfrom nursing import views\n\n\nurlpatterns = [\n url(r'^$', views.nursing, name='nursing'),\n url(r'^nursingCreate/$', views.nursingCreate, name='nursingCreate'),\n url(r'^nursingRead/(?P[0-9]+)/$', views.nursingRead, name='nursingRead'),\n url(r'^nursingUpdate/(?P[0-9]+)/$', views.nursingUpdate, name='nursingUpdate'),\n url(r'^nursingSearch/$', views.nursingSearch, name='nursingSearch'),\n]","sub_path":"healthcare/nursing/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"542927071","text":"\nfrom ModelUtils import ModelUtils\n\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import *\nfrom matplotlib import pyplot\nfrom FeatureExtraction import *\nfrom sklearn import metrics\nfrom datetime import datetime\nimport time\nfrom FeatureExtraction import dataset_path\n\n\ndef trainTheModel():\n\n\n model_data=extractFeaturesFromData()\n print(\"Training Start\")\n #need to reverse the data frame so that subsequent rows represent later timepoints\n model_data = model_data.sort_values(by='date')\n \n \n # #create Training and Test set\n # training_set, test_set = model_data[model_data['date'] < split_date], model_data[model_data['date'] >= split_date]##2 yr data for training and 4 mnth for testing\n # test_set=test_set[test_set['date']<=end_date]\n\n # training_set,test_set=train_test_split(model_data,shuffle=False,test_size=.3)\n training_set=model_data\n\n # # we don't need the date columns anymore\n training_set = training_set.drop('date', 1)\n \n # test_set = test_set.drop('date', 1)\n \n #Prepare model input and output\n LSTM_training_inputs = ModelUtils.buildLstmInput(training_set, None, window_len)\n LSTM_training_outputs = ModelUtils.buildLstmOutput(training_set, 'bt_close', window_len)\n \n # LSTM_test_inputs = ModelUtils.buildLstmInput(test_set, None, window_len)\n # LSTM_test_outputs = ModelUtils.buildLstmOutput(test_set, 'bt_close', window_len)\n\n print(\"\\nNumber Of Input Training's sequences: {}\".format(len(LSTM_training_inputs)))\n print(\"\\nNumber Of Output Training's sequences: {}\".format(len(LSTM_training_outputs)))\n # print(\"\\nNumber Of Input Test's sequences: {}\".format(len(LSTM_test_inputs)))\n # print(\"\\nNumber Of Output Test's sequences: {}\".format(len(LSTM_test_outputs)))\n \n #convert to numpy array\n LSTM_training_inputs = [np.array(LSTM_training_input) for LSTM_training_input in LSTM_training_inputs]\n LSTM_training_inputs = np.array(LSTM_training_inputs)\n LSTM_training_inputs=[x.ravel() for x in LSTM_training_inputs]\n LSTM_training_inputs = np.array(LSTM_training_inputs)\n \n LSTM_training_outputs = [np.array(LSTM_training_output) for LSTM_training_output in LSTM_training_outputs]\n LSTM_training_outputs = np.array(LSTM_training_outputs)\n LSTM_training_outputs=[x.ravel() for x in LSTM_training_outputs]\n LSTM_training_outputs = np.array(LSTM_training_outputs)\n \n # LSTM_test_inputs = [np.array(LSTM_test_input) for LSTM_test_input in LSTM_test_inputs]\n # LSTM_test_inputs = np.array(LSTM_test_inputs)\n # LSTM_test_inputs = [x.ravel() for x in LSTM_test_inputs]\n # LSTM_test_inputs = np.array(LSTM_test_inputs)\n #\n # LSTM_test_outputs = [np.array(LSTM_test_output) for LSTM_test_output in LSTM_test_outputs]\n # LSTM_test_outputs = np.array(LSTM_test_outputs)\n # LSTM_test_outputs = [x.ravel() for x in LSTM_test_outputs]\n # LSTM_test_outputs = np.array(LSTM_test_outputs)\n\n #reshape input to be 3D [samples, timesteps, features] as LSTM accepts only 3D vector\n train_X = LSTM_training_inputs.reshape((LSTM_training_inputs.shape[0], 1, LSTM_training_inputs.shape[1]))\n # test_X = LSTM_test_inputs.reshape((LSTM_test_inputs.shape[0], 1, LSTM_test_inputs.shape[1]))\n # print(train_X.shape, LSTM_training_outputs.shape, test_X.shape, LSTM_test_outputs.shape)\n \n #Build the model\n model = ModelUtils.build_model(train_X.shape[1:], output_size=2, neurons_lv1=num_of_neurons_lv1, neurons_lv2=num_of_neurons_lv2,\n neurons_lv3=num_of_neurons_lv3,neurons_lv4=num_of_neurons_lv4)\n # #Fit data to the model\n # history = model.fit(train_X, LSTM_training_outputs, epochs=200, batch_size=3000, validation_data=(test_X,LSTM_test_outputs), verbose=2, shuffle=False)\n history = model.fit(train_X, LSTM_training_outputs, epochs=300, batch_size=3000, verbose=2, shuffle=False)\n\n # #Make predictions to find accuracy\n # pre = (model.predict(test_X))\n #\n # #Classification report\n # b = np.zeros_like(pre)\n # b[np.arange(len(pre)), pre.argmax(1)] = 1\n # print( metrics.classification_report(LSTM_test_outputs,b))\n \n #Save trained model\n \n model.save(model_path)\n model.save_weights(model_weights_path)\n print('model saved')\n\n\ndatenow=lambda :datetime.utcnow().day\ntimetospeep = 20 * 60\nDategaptoTrain = timeToTrainInDays\nnextTrainingDate=datenow()\nlastTraingDate=datenow()\nwhile True:\n if (datenow() ==nextTrainingDate and lastTraingDate!=datenow()):\n print(\"trianing started at \", datetime.utcnow())\n startTime=datetime.utcnow()\n trainTheModel()\n lastTraingDate=datenow()\n nextTrainingDate=datenow()+DategaptoTrain\n print(\"trianing Ended at \", datetime.utcnow(),' in time ',datetime.utcnow()-startTime)\n time.sleep(timetospeep)\n\n","sub_path":"BTCUSD1hrs/ClosePridiction/TrainingServer.py","file_name":"TrainingServer.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"541555517","text":"#스타크래프트 게임 프로젝트\nfrom random import *\n\nclass Unit: #부모 클래스\n def __init__(self, name, hp, speed):\n self.name=name\n self.hp=hp\n self.speed= speed\n print(\"{0} 유닛이 생성되었습니다.\".format(name))\n\n def move(self,location):\n print(\"{0} : {1} 방향으로 이동합니다. [속도 : {2}]\".format(self.name,location,self.speed))\n\n def damaged(self, damage):\n print(\"{0} : {1} damaged\".format(self.name,damage))\n self.hp-=damage\n print(\"{0} : now hp {1}\".format(self.name,self.hp))\n if self.hp<=0:\n print(\"{0} destroyed\".format(self.name))\n\nclass AttackUnit(Unit): #자식 클래스\n def __init__(self, name, hp, speed ,damage):\n Unit.__init__(self,name,hp,speed)\n self.damage=damage\n def attack(self, location):\n print(\"{0} : {1}방향으로 공격 {2}damage\".format(self.name, location, self.damage))\n\nclass Marine(AttackUnit):\n def __init__(self):\n AttackUnit.__init__(self,\"마린\",40,1,5)\n #스팀팩\n def stimpack(self):\n if self.hp>10:\n self.hp-=10\n print(\"{0} : 스핌팩을 사용합니다. (HP 10감소)\".format(self.name))\n else:\n print(\"{0} : 체력이 부족하여 스핌팩을 사용하지 않습니다.\".format(self.name))\n\nclass Tank(AttackUnit):\n seize_developed = False\n def __init__(self):\n AttackUnit.__init__(self, \"탱크\" , 150, 1, 25)\n self.seize_mood=False\n def set_seize_mood(self):\n if Tank.seize_developed ==False:\n return\n\n #현재 시즈모드가 아닐때 -> 시즈모드\n if self.seize_mood==False:\n print(\"{0} : 시즈모드로 전환합니다.\".format(self.name))\n self.damage*=2\n self.seize_mood=True\n\n #현재 시즈모드 일때 ->시즈모드 해제\n else:\n print(\"{0} : 시즈모드를 해제합니다.\".format(self.name))\n self.damage /= 2\n self.seize_mood = False\n\nclass Flyable: # 날 수 있는 기능을 가진 클래스\n def __init__(self, flying_speed):\n self.flying_speed = flying_speed\n def fly(self, name, location):\n print(\"{0}이 {1}로 날아갑니다. [속도 : {2}]\".format(name,location,self.flying_speed))\n\nclass FlyableAttackUnit(AttackUnit,Flyable):\n def __init__(self,name,hp,damage,flying_speed):\n AttackUnit.__init__(self,name,hp,0 ,damage) #지상 speed 0\n Flyable.__init__(self,flying_speed)\n\n def move(self, location):\n self.fly(self.name,location)\n\nclass Wraith(FlyableAttackUnit):\n def __init__(self):\n FlyableAttackUnit.__init__(self, \"레이스\", 80, 20, 5)\n self.clocked = False #클로킹 해제 상태\n def clocking(self):\n if self.clocked==True:\n print(\"{0} : 클로킹 모드 해제합니다.\".format(self.name))\n self.clocked=False\n else:\n print(\"{0} : 클로킹 모드 실행합니다.\".format(self.name))\n self.clocked = True\n\ndef game_start():\n print(\"[알림] 새로운 게임을 시작합니다.\")\n\ndef game_over():\n print(\"Player : gg\")\n print(\"[Player] 님이 게임에서 퇴장하셨습니다.\")\n\n#실제 게임 시작\ngame_start()\n\n#마린 3마리\nm1=Marine()\nm2=Marine()\nm3=Marine()\n\n#탱크 2마리\nt1=Tank()\nt2=Tank()\n\n#레이스 1마리\nw1=Wraith()\n\n#유닛 일괄 관리\nattack_units=[]\nattack_units.append(m1)\nattack_units.append(m2)\nattack_units.append(m3)\nattack_units.append(t1)\nattack_units.append(t2)\nattack_units.append(w1)\n\n# 전군 이동\nfor unit in attack_units:\n unit.move(\"1시\")\n\n#탱크 시즈모드 개발\nTank.seize_developed=True\nprint(\"[일림] 탱크 시즈 모드 개발이 완료되었습니다.\")\n\n#공격 모드 준비 (탱크 : 시즈모드, 레이스 : 클로킹, 마린 : 스팀팩)\nfor unit in attack_units:\n if isinstance(unit, Marine):\n unit.stimpack()\n elif isinstance(unit, Tank):\n unit.set_seize_mood()\n elif isinstance(unit, Wraith):\n unit.clocking()\n\n#전군 공격\nfor unit in attack_units:\n unit.attack(\"1시\")\n\n#전군 피해\nfor unit in attack_units:\n unit.damaged(randint(5,21)) #공격을 랜덤으로 받음 (5~20)\n\n#게임 종료\ngame_over()","sub_path":"starcraft_project_1.py","file_name":"starcraft_project_1.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"437322584","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nLOG_COV_MAX = 2\nLOG_COV_MIN = -1\n\nclass RecurrentModel(nn.Module):\n def __init__(self):\n super().__init__()\n conv_channels = 32\n self.conv_encoder = nn.Sequential(\n nn.Conv2d(3, conv_channels, 4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(conv_channels),\n nn.ReLU(),\n nn.Conv2d(conv_channels, conv_channels, 4, stride=2, padding=1, bias=False),\n nn.BatchNorm2d(conv_channels),\n nn.ReLU(),\n nn.Conv2d(conv_channels, conv_channels, 1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(conv_channels),\n nn.ReLU(),\n nn.Conv2d(conv_channels, conv_channels, 1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(conv_channels),\n nn.ReLU()\n )\n ae_dim = 512\n lstm_dim = 512\n self.lstm_dim = lstm_dim\n img_h = 5\n flat_inter_img_dim = img_h * img_h * conv_channels\n act_dim = 64\n\n self.conv_channels = conv_channels\n self.img_h = img_h\n \n self.lstm_act_proc_fc = nn.Linear(4, act_dim, bias=True)\n self.recon_act_proc_fc = nn.Linear(4, act_dim, bias=True)\n self.mask_act_proc_fc = nn.Linear(4, act_dim, bias=True)\n\n self.attention_seq = nn.Sequential(\n nn.Linear(lstm_dim + act_dim, lstm_dim, bias=False),\n nn.BatchNorm1d(lstm_dim),\n nn.ReLU(),\n nn.Linear(lstm_dim, lstm_dim),\n # nn.Sigmoid()\n # nn.Softmax()\n )\n\n self.fc_encoder = nn.Sequential(\n nn.Linear(flat_inter_img_dim + act_dim, ae_dim, bias=False),\n nn.BatchNorm1d(ae_dim),\n nn.ReLU(),\n # nn.Linear(ae_dim, ae_dim, bias=False),\n # nn.BatchNorm1d(ae_dim),\n # nn.ReLU(),\n # nn.Linear(ae_dim, ae_dim, bias=False),\n # nn.BatchNorm1d(ae_dim),\n # nn.ReLU(),\n # nn.Linear(ae_dim, ae_dim, bias=False),\n # nn.BatchNorm1d(ae_dim),\n # nn.ReLU()\n )\n self.lstm = nn.GRUCell(\n ae_dim, lstm_dim, bias=True\n )\n self.fc_decoder = nn.Sequential(\n nn.Linear(lstm_dim + act_dim, flat_inter_img_dim, bias=False),\n nn.BatchNorm1d(flat_inter_img_dim),\n nn.ReLU(),\n # nn.Linear(ae_dim, ae_dim, bias=False),\n # nn.BatchNorm1d(ae_dim),\n # nn.ReLU(),\n # # nn.Linear(ae_dim, ae_dim, bias=False),\n # # nn.BatchNorm1d(ae_dim),\n # # nn.ReLU(),\n # # nn.Linear(ae_dim, ae_dim, bias=False),\n # # nn.BatchNorm1d(ae_dim),\n # # nn.ReLU(),\n # nn.Linear(ae_dim, flat_inter_img_dim, bias=False),\n # nn.BatchNorm1d(flat_inter_img_dim),\n # nn.ReLU(),\n )\n self.conv_decoder = nn.Sequential(\n nn.ConvTranspose2d(conv_channels, conv_channels, 4, stride=2, padding=1, output_padding=0, bias=False),\n nn.BatchNorm2d(conv_channels),\n nn.ReLU(),\n # nn.Conv2d(conv_channels, conv_channels, 1, stride=1, padding=0, bias=False),\n # nn.BatchNorm2d(conv_channels),\n # nn.ReLU(),\n nn.ConvTranspose2d(conv_channels, conv_channels, 4, stride=2, padding=1, output_padding=0, bias=False),\n nn.BatchNorm2d(conv_channels),\n nn.ReLU(),\n # nn.Conv2d(conv_channels, conv_channels, 1, stride=1, padding=0, bias=False),\n # nn.BatchNorm2d(conv_channels),\n # nn.ReLU(),\n )\n self.mean_decoder = nn.Sequential(\n nn.Conv2d(conv_channels, 3, 1, stride=1, padding=0, bias=True),\n nn.Sigmoid()\n )\n self.log_cov_decoder = nn.Sequential(\n nn.Conv2d(conv_channels, 3, 1, stride=1, padding=0, bias=True),\n )\n \n \n def forward(self, obs_batch, act_batch, prev_h_batch, prev_c_batch):\n # print(self.lstm_dim)\n lstm_act_proc = self.lstm_act_proc_fc(act_batch)\n recon_act_proc = self.recon_act_proc_fc(act_batch)\n mask_act_proc = self.mask_act_proc_fc(act_batch)\n \n hidden = torch.cat([prev_h_batch, mask_act_proc], 1)\n mask_logits = self.attention_seq(hidden)\n # self.reg_loss = (mask_logits**2).mean()\n self.reg_loss = 0.\n mask = F.sigmoid(mask_logits)\n # print(mask[0])\n # print(torch.sum(mask, 1))\n hidden = prev_h_batch * mask\n # ------\n # hidden = prev_h_batch\n\n hidden = torch.cat([hidden, recon_act_proc], 1)\n hidden = self.fc_decoder(hidden).view(obs_batch.size(0), self.conv_channels, self.img_h, self.img_h)\n hidden = self.conv_decoder(hidden)\n recon = self.mean_decoder(hidden)\n log_cov = self.log_cov_decoder(hidden)\n log_cov = torch.clamp(log_cov, LOG_COV_MIN, LOG_COV_MAX)\n\n enc = self.conv_encoder(obs_batch)\n enc = enc.view(obs_batch.size(0), -1)\n enc = self.fc_encoder(torch.cat([enc, lstm_act_proc], 1))\n # prev_h_batch, prev_c_batch = self.lstm(enc, (prev_h_batch, prev_c_batch))\n prev_h_batch = self.lstm(enc, prev_h_batch)\n \n\n return recon, log_cov, prev_h_batch, prev_c_batch\n","sub_path":"gen_models/recurrent_model.py","file_name":"recurrent_model.py","file_ext":"py","file_size_in_byte":5364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"124087198","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom svgDict import svg\nfrom solve import backtrack\n\n\ndef main():\n board = []\n global driver\n driver = webdriver.Chrome(ChromeDriverManager().install())\n driver.get(\"https://www.sudoku.com\")\n try:\n elements_present = EC.presence_of_all_elements_located(\n (By.CLASS_NAME, \"game-cell\"))\n WebDriverWait(driver, 5).until(elements_present)\n for row in driver.find_elements_by_class_name('game-row'):\n rowToAppend = []\n for element in row.find_elements_by_class_name(\"game-cell\"):\n try:\n path = element.find_element_by_tag_name(\"path\")\n d = path.get_attribute(\"d\")\n rowToAppend.append(svg[d])\n except:\n rowToAppend.append(\"\")\n board.append(rowToAppend)\n backtrack(board)\n index = 0\n for element in driver.find_elements_by_class_name('game-cell'):\n if \"game-value\" in element.get_attribute(\"class\"):\n index += 1\n continue\n else:\n element.click()\n for number in driver.find_elements_by_class_name(\"numpad-item\"):\n if number.get_attribute(\"data-value\") == board[index // 9][index % 9]:\n number.click()\n index += 1\n print(board)\n\n except TimeoutException:\n print(\"couldn't locate cells\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"364290027","text":"import numpy, cv2\r\nfrom PIL import Image\r\n\r\nface_cascade = cv2.CascadeClassifier(\"C:/Users/Wottle of Bine/Documents/Python Projects/piiillow_test/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml\")\r\n\r\ndef find_faces(image_for_faces):\r\n # filter faces from image\r\n # resize face images to thumbnail size\r\n image = image_for_faces.resize((1800,3150))\r\n image_np = numpy.asarray(image)\r\n image_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(image_gray) #correct numpy array, prints correct coordinates per face\r\n face_list = []\r\n for face in faces:\r\n box = (face[0], face[1], face[0]+face[2], face[1]+face[3]) #correctly produces numpy coordinates\r\n copy_image = image.copy()\r\n cropped = copy_image.crop(box = (box))\r\n cropped.thumbnail((128,128))\r\n print(type(cropped))\r\n face_list.append(cropped)\r\n return face_list\r\n\r\ny = Image.open('famphoto.jpg')\r\nz = y.convert('RGB')\r\n\r\nx = find_faces(z)\r\nprint(x)","sub_path":"tester2.py","file_name":"tester2.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"553569808","text":"from telegram.ext import Updater\nfrom telegram.ext import MessageHandler, Filters\nimport pandas as pd\nimport requests\nimport json\n\nAPIKEY = '1601770966:AAG_M12JkBrT0CXnLiCK62bVDW4QzNMjKz4'\n\n# updater\nupdater = Updater(token=APIKEY, use_context=True)\ndef fn_getCoin(text):\n df = pd.read_excel('altCoin.xlsx', sheet_name='Sheet1', engine='openpyxl')\n print(df.head())\n res = df[df['korean_name'].str.contains(text)]\n codeList = res['market'].values.tolist()\n url = 'https://api.upbit.com/v1/ticker?markets='\n coinInfo_code = []\n coinInfo_price = []\n for i in codeList:\n resp = requests.get(url + i)\n text = resp.text\n json_data = json.loads(text)\n coinInfo_code.append(json_data[0]['market'])\n coinInfo_price.append(json_data[0]['trade_price'])\n return coinInfo_code, coinInfo_price\n\n# message handler\ndef echo(update, context):\n user_id = update.effective_chat.id\n user_text = update.message.text\n print(user_text)\n coinCode, coinPrice = fn_getCoin(user_text)\n for i, v in enumerate(coinCode):\n text = \"코드 : \" + coinCode[i] + ', 현재 가격 : ' + str(coinPrice[i])\n context.bot.send_message(chat_id=user_id, text=text)\n\necho_handler = MessageHandler(Filters.text &(~Filters.command), echo)\nupdater.dispatcher.add_handler(echo_handler)\nupdater.start_polling()\nupdater.idle()","sub_path":"day5/day5/ex-bot-1.py","file_name":"ex-bot-1.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"349108974","text":"# Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.\n#\n# In this problem, we will not be dealing with a minimum monthly payment rate.\n#\n# The following variables contain values as described below:\n#\n# balance - the outstanding balance on the credit card\n#\n# annualInterestRate - annual interest rate as a decimal\n#\n# The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:\n#\n# Lowest Payment: 180\n\nbalance = 1000\nannualInterestRate = 0.1\nmonthlyInterestRate = annualInterestRate / 12\nmonthlypay = 10\n\ndef eachmonth(x):\n balancenew = round((x - monthlypay)*(1 + monthlyInterestRate), 2)\n return balancenew\n\ndef showBalance(y):\n for i in range(1, 13):\n temp = y\n y = eachmonth(temp)\n # print('In', i,'month, should pay: ', monthlypay)\n # print('In', i,'month, the balance is: ', y)\n return y\n\n\nwhile showBalance(balance) > 0:\n monthlypay +=10\n\n\nprint('Lowest Payment:', monthlypay)","sub_path":"PSet/Week2/HW2.py","file_name":"HW2.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"391790184","text":"\"Game entry point\"\n\nimport pygame\nfrom pygame.math import Vector2\nfrom chaikin_algorithm import chaikin_algorithm\n\nSCREEN_SIZE = 800\n\n\ndef main():\n \"Game Main\"\n\n pygame.init()\n pygame.display.set_caption(\"Chaikin's Algorithm\")\n\n screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))\n running = True\n\n points = (\n Vector2(0, 400),\n Vector2(200, 100),\n Vector2(400, 700),\n Vector2(600, 600),\n Vector2(700, 50),\n Vector2(800, 0)\n )\n pygame.draw.lines(screen, (255, 0, 0), False, points)\n\n new_points = chaikin_algorithm(points, 6)\n pygame.draw.lines(screen, (0, 255, 0), False, new_points)\n\n pygame.display.update()\n # Game Loop\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"381347867","text":"def selection_sort(L):\n for i in range(len(L)):\n idx_min = i\n for j in range(i, len(L)):\n if L[j] < L[i]:\n idx_min = j\n L[idx_min], L[i] = L[i], L[idx_min]\n\nnums = [2, 4, 3, 1]\nselection_sort(nums)\nprint(nums)\n","sub_path":"tyler/cs320/f20/materials/lec-05/selection-sort.py","file_name":"selection-sort.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"475891367","text":"#!/usr/bin/env python\n\nDEFAULT_TABLE_FORMAT = 'ascii.fixed_width'\n\ndef my_loadtxt(fname, \n as_table=False, \n as_dict=False, \n table_format=DEFAULT_TABLE_FORMAT, \n **kwargs):\n \"\"\"\n read a collimated text file and return the data as requested.\n\n leverages :meth:`astropy.table.Table.read` to read the \n actual text file, then does some post-processing to return\n it in a useful format.\n\n Args:\n fname:\n name of the input file to read \n\n as_table:\n whether to return the data directly, with no \n post processing\n\n as_dict:\n whether to return the data as a dictionary with\n the keys being the column names\n\n table_format:\n format of the table to read\n \n kwargs:\n passed to :meth:`astropy.table.Table.read`\n\n \n Returns:\n the data in `fname`, either as an :class:`astropy.table.Table`,\n as a dictionary, or (if both are `as_table` and `as_dict` are false)\n as a list of arrays in the order the columns appear.\n \"\"\"\n\n import os\n if not os.path.isfile(fname):\n raise IOError(\"unable to find {} for reading\".format(fname))\n\n from astropy.table import Table\n import numpy as np\n t = Table.read(fname, format=table_format, **kwargs)\n if as_table:\n return t\n elif as_dict:\n return dict([(key, np.array(t[key])) for key in t.colnames])\n else:\n return [np.array(t[key]) for key in t.colnames]\n\n\ndef my_savetxt(outname, list_dict_or_arrays, colnames=None, order_dict=None,\n dtypes=None, table_format=DEFAULT_TABLE_FORMAT, overwrite=True,\n backup=True, replace_nan=-2, **kwargs):\n \"\"\"\n flexibly save data to a file in ascii format using astropy\n\n preserves integer dtypes; otherwise tries float and defaults \n to unicode otherwise\n\n Args:\n outname: name of output file\n\n list_dict_or_arrays: many possibilities, assumes \n that you want to save M columns:\n\n * a numpy structured array with M dtypes where each dtype \n is a column. this will get converted to, then treated like, \n a dictionary of arrays\n * a list where each M items is a len N array\n (or list, in which case they'll be cast to arrays)\n * an N x M array\n * a dictionary of where each entry is an len N array\n (or list, in which case they'll be cast to arrays)\n\n colnames:\n single item (if list_dict_or_arrays is 1xN or Nx1), \n list (must be len M) or dictionary giving column names.\n otherwise, will be constructed as 'col0', 'col1', 'col2', etc.\n if a dictionary is passed in, colnames will be constructed \n from colnames if given, and dictionary keys otherwise. if \n a dictionary is passed in and colnames is NOT a dictionary,\n then order_dict must be handed in to assing column_names\n \n dtypes: either a single item or a list or dictionary giving data\n types. useful if data is mixed type. note that these should\n be numpy datatypes, as I'll be doing np.array(ar).astype(dtype).\n can also pass in a single item for everything. \n\n if None, then I'll\n\n 1. check if I'm an int (leave alone if so)\n 2. check if I can become a float\n 3. leave as a string\n\n order_dict:\n ignored unless list_dict_or_arrays is a dictionary, in which\n case this gives the order in which the columns should be saved.\n if this isn't given, they're saved in alphabetical order -- that'll\n at least get things like vx, vy, vz and x, y, z together\n \"\"\"\n import numpy as np\n\n if not len(kwargs.get('delimiter', '|').strip()):\n raise Warning(\n \"!! -- warning -- white-space delimiters can cause problems! recommend using a character such as |\")\n\n assert type(list_dict_or_arrays) in [list, dict, np.ndarray, tuple]\n if type(list_dict_or_arrays) == dict and order_dict is not None:\n assert type(order_dict) == dict\n if colnames is not None:\n assert type(colnames) in [dict, list, np.ndarray, str]\n if dtypes is not None:\n assert type(dtypes) in [dict, list, str, np.dtype]\n\n def nan_replace(ar):\n if ar.dtype.kind in ['U', 'S']:\n return ar\n else:\n msk = np.isnan(ar)\n ar[msk] = replace_nan\n return ar\n\n def get_as_array(vals, dts, idx, cname):\n if type(dts) == list:\n ar = np.array(vals).astype(dts[idx])\n elif type(dts) in [str, np.dtype]:\n try:\n # allow for some allowances if I pass in just one dtype\n ar = np.array(vals).astype(dts)\n except (ValueError, TypeError):\n ar = np.array(vals).astype('U')\n elif type(dts) == dict:\n ar = np.array(vals).astype(dts[cname])\n else:\n ar = np.array(vals)\n if ar.dtype.kind != 'i':\n try:\n ar = ar.astype('f')\n except ValueError: # it's a string\n ar = ar.astype('U')\n ar = nan_replace(ar)\n return ar\n\n # OK, lots to do here cause I'm trying to handle every possible case\n\n # first, if I hand in a structured array, convert it to a dictionary\n # i'll then handle dictionaries later\n if type(list_dict_or_arrays) == np.ndarray:\n if list_dict_or_arrays.dtype.names is not None:\n names = list_dict_or_arrays.dtype.names\n list_dict_or_arrays = dict(\n [(n, list_dict_or_arrays[n]) for n in names])\n\n # ok, now if got passed in a length 1 array, everything is (relatively) easy:\n input_as_array = np.transpose(np.array(list_dict_or_arrays, copy=True))\n onecol = False\n # single array; assume that you want to save as column, cause one line for a long array is dumb\n if len(input_as_array.shape) == 1:\n onecol = True\n if len(input_as_array.shape) > 1:\n if input_as_array.shape[1] == 1: # single column\n onecol = True\n\n if onecol:\n if colnames is None:\n header = 'col0'\n elif type(colnames) in [list, np.ndarray]:\n header = colnames[0]\n else:\n header = colnames\n\n if dtypes is not None:\n if type(dtypes) == list:\n dtypes = dtypes[0]\n\n input_as_array = input_as_array.astype(dtypes)\n\n if backup:\n backup_file(outname)\n np.savetxt(outname, input_as_array, fmt='%'+dtype_dict.get(\n input_as_array.dtype.kind, input_as_array.dtype.kind), header=header)\n print(\"Wrote a single column to {}\".format(outname))\n\n else:\n from astropy.table import Table\n t = Table()\n\n # ok, now handle the cases where I have multple entries to pass in.\n # first, let's do the most common, a list/sequence of arrays\n if type(list_dict_or_arrays) in [list, tuple]:\n if colnames is None:\n colnames = ['col'+str(ii)\n for ii in range(len(list_dict_or_arrays))]\n for ii in range(len(list_dict_or_arrays)):\n ar = get_as_array(\n list_dict_or_arrays[ii], dtypes, ii, colnames[ii])\n t[colnames[ii]] = ar\n\n # now handle a dictionary, in which case I have to worry about the order\n elif type(list_dict_or_arrays) == dict:\n keys = list(list_dict_or_arrays.keys())\n if colnames is None:\n colnames = keys\n else:\n assert (order_dict is not None) or type(colnames) == dict\n\n if order_dict is not None:\n order = [order_dict[k] for k in keys]\n sorti = np.argsort(order)\n keys = keys[sorti]\n if type(colnames) != dict:\n colnames = colnames[sorti]\n\n for ii, key in enumerate(keys):\n if type(colnames) in [list, np.ndarray]:\n c = colnames[ii]\n else:\n c = colnames[key]\n\n ar = get_as_array(list_dict_or_arrays[key], dtypes, ii, key)\n t[c] = ar\n\n # now handle a single array, where I want to save a collimated version\n elif type(list_dict_or_arrays) == np.ndarray:\n ncol = list_dict_or_arrays.shape[1]\n if colnames is None:\n colnames = ['col'+str(ii) for ii in range(ncol)]\n assert type(colnames) in [list, np.ndarray]\n for ii in range(list_dict_or_arrays.shape[1]):\n ar = get_as_array(\n list_dict_or_arrays[:, ii], dtypes, ii, colnames[ii])\n t[colnames[ii]] = ar\n else:\n raise ValueError(\"Don't know how I got here!\")\n\n if backup:\n backup_file(outname)\n t.write(outname, format=table_format, overwrite=overwrite, **kwargs)\n print(\"Saved a table with {} rows and {} columns to {}\".format(\n t.columns[0].size, len(t.columns), outname))\n","sub_path":"sgklibs/ascii_io.py","file_name":"ascii_io.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"157382448","text":"from custom.enikshay.private_sector_datamigration.models.migrated_beneficiary_counter import (\n MigratedBeneficiaryCounter,\n)\nfrom custom.enikshay.private_sector_datamigration.models.jun14 import (\n Adherence_Jun14,\n Agency_Jun14,\n Beneficiary_Jun14,\n Episode_Jun14,\n EpisodePrescription_Jun14,\n UserDetail_Jun14,\n Voucher_Jun14,\n)\nfrom custom.enikshay.private_sector_datamigration.models.jun30 import (\n Adherence_Jun30,\n Agency_Jun30,\n Beneficiary_Jun30,\n Episode_Jun30,\n EpisodePrescription_Jun30,\n UserDetail_Jun30,\n Voucher_Jun30,\n)\nfrom custom.enikshay.private_sector_datamigration.models.jul7 import (\n Adherence_Jul7,\n Agency_Jul7,\n Beneficiary_Jul7,\n Episode_Jul7,\n EpisodePrescription_Jul7,\n UserDetail_Jul7,\n Voucher_Jul7,\n)\nfrom custom.enikshay.private_sector_datamigration.models.jul13 import (\n Adherence_Jul13,\n Agency_Jul13,\n Beneficiary_Jul13,\n Episode_Jul13,\n EpisodePrescription_Jul13,\n UserDetail_Jul13,\n Voucher_Jul13,\n)\nfrom custom.enikshay.private_sector_datamigration.models.jul19 import (\n Adherence_Jul19,\n Agency_Jul19,\n Beneficiary_Jul19,\n Episode_Jul19,\n EpisodePrescription_Jul19,\n UserDetail_Jul19,\n Voucher_Jul19,\n)\n\nAdherence = Adherence_Jul19\nAgency = Agency_Jul19\nBeneficiary = Beneficiary_Jul19\nEpisode = Episode_Jul19\nEpisodePrescription = EpisodePrescription_Jul19\nUserDetail = UserDetail_Jul19\nVoucher = Voucher_Jul19\n","sub_path":"custom/enikshay/private_sector_datamigration/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"460445176","text":"import random\n''' import silence_tensorflow.auto '''\nimport tensorflow as tf\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, array_to_img, img_to_array\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport os\nimport cv2\nimport numpy as np\nfrom PIL import Image as pillow\nimport pandas as pd\n\nim_count = 3680 \n\nIMG_SIZE = 200\n\n\ntrain_data_dir = 'D:\\ders\\MASTER\\_Thesis\\VirtualEnv\\_datasets\\_arcDataset\\_traindata'\nCATEGORIES = ['-2600_-2000', '-550_-220', '1200_1600', '1600_1700', '1720_1840',\n '1800-1900', '1890_1935', '1895_1920', '1900_1940', '1919-1965',\n '1920-1950', '1960_2000', '1980-2015', '600_800', '800_1200']\n\nBATCH_SIZE = 48\nVAL_SPLIT = 0.4\n\ntrain_images = []\ntrain_labels = []\n\nba_count = im_count // BATCH_SIZE\n\ndef create_training_data():\n for category in CATEGORIES:\n path = os.path.join(train_data_dir, category)\n class_num = CATEGORIES.index(category)\n for img in os.listdir(path):\n try:\n img_array = cv2.imread(os.path.join(\n path, img), cv2.IMREAD_GRAYSCALE)\n new_array = cv2.resize(\n img_array, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_AREA)\n train_images.append(new_array)\n train_labels.append(class_num)\n except Exception as e:\n pass\n\n\ncreate_training_data()\n\ntrain_labels = pd.get_dummies(train_labels).values\ntrain_images = np.array(train_images).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n\nprint(train_images.shape)\nprint(train_labels.shape)\n\n\ntrain_features, test_features, train_targets, test_targets = train_test_split(\n train_images, train_labels,\n train_size=1 - VAL_SPLIT,\n test_size=VAL_SPLIT,\n shuffle=True,\n)\n\n\nprint(train_features.shape)\nprint(train_targets.shape)\nprint(test_features.shape)\nprint(test_targets.shape)\n\n\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255,\n rotation_range=40,\n zoom_range=0.2,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True,\n fill_mode=\"nearest\"\n)\n\n\ntrain_generator = train_datagen.flow(\n train_features,\n train_targets,\n batch_size=BATCH_SIZE,\n shuffle=True\n)\n\nvalidation_datagen = ImageDataGenerator(\n rescale=1. / 255,\n)\n\nvalidation_generator = validation_datagen.flow(\n test_features,\n test_targets,\n batch_size=BATCH_SIZE,\n shuffle=True\n)\n\n\nmodel = Sequential()\n\nmodel.add(Conv2D(32, (3, 3), activation=\"relu\", input_shape=(IMG_SIZE, IMG_SIZE, 1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\n\nmodel.add(Conv2D(64, (3, 3), activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.3))\n\nmodel.add(Conv2D(64, (3, 3), activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.2))\n\n\nmodel.add(Conv2D(128, (5, 5), activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.3))\n\n\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation=\"relu\"))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(256, activation=\"relu\"))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(348, activation=\"relu\"))\n\n\nmodel.add(Dense(15, activation=\"softmax\"))\n\nopt = tf.keras.optimizers.Adam(lr=0.001)\n\n\nmodel.compile(loss=\"categorical_crossentropy\",\n optimizer=opt,\n metrics=[\"categorical_accuracy\"])\n\nhistory = model.fit_generator(train_generator,\n steps_per_epoch=ba_count - int(ba_count * (VAL_SPLIT)),\n epochs=300,\n validation_data=validation_generator,\n validation_steps=int(ba_count *(VAL_SPLIT))\n )\n\nmodel.save(\"_models/27-6-2020-ArchDatasetModel#19.model\")\n\n\n########################## TRAINING VISUALIZATION ############################\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nacc = history.history['categorical_accuracy']\nval_acc = history.history['val_categorical_accuracy']\n\nepochs = range(1, len(loss) + 1)\n\nplt.plot(epochs, loss, 'bo', label='Training loss')\nplt.plot(epochs, val_loss, 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\nplt.clf()\n\nplt.plot(epochs, acc, 'bo', label='Training acc')\nplt.plot(epochs, val_acc, 'b', label='Validation acc')\nplt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\n\n########################## TRAINING VISUALIZATION ############################\n","sub_path":"Scripts/FirstGen/20-6-27-MulticlassArchitectureClassification5.py","file_name":"20-6-27-MulticlassArchitectureClassification5.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"196062787","text":"\"\"\"\n This is the 2020 drive code for the FRC team 5613 Thunderdogs.\n We used the robotpy_ext autonomous for multiple autonomous modes. Note how the directory we get the Autonomous\n modes from is different than the one used in the the SimRobot.py file.\n We are using the TimedRobot class which inherits from the IterativeRobot base. That means that we can use the\n autonomous selector like it would normally be used on the IterativeRobot class.\n If there are issues check the autonomous directory and make sure there is an __init__.py file. Not having one causes\n issues because it is meant to be a package and you have to have it as a placeholder, even if there is nothing in it.\n\"\"\"\nimport wpilib\nfrom wpilib.drive import DifferentialDrive\nfrom robotpy_ext import autonomous\nfrom networktables import NetworkTables\nfrom numpy import tan\nimport ctre\n# from rev.color import ColorSensorV3\n\n\nclass MyRobot(wpilib.IterativeRobot):\n # Defines the channels that are used on the inputs.This is really useful when you have a variable used hundreds\n # of times and you want to have it set so you can change it all in one go.\n\n FLChannel = 4\n FRChannel = 2\n RLChannel = 3\n RRChannel = 1\n\n DriveStickChannel = 0\n\n # ExtraStickChannel = 1\n\n # RobotInit is where everything is initialized.\n def robotInit(self):\n # Initializes the network table\n # NetworkTables.initialize(server=\"10.56.13.2\")\n # self.table = NetworkTables.getTable(\"limelight\")\n # f is a control constant that will be used to change variable values quickly\n # self.f = 1\n # self.ControlConstant = -0.1 * self.f\n # self.minCommand = -0.05 * self.f\n\n # self.Blue = (RGB value or blue color)\n # self.Green = (RGB value of green color)\n # self.Red = (RGB value of red color)\n # self.Yellow = (RGB value of Yellow color)\n\n # Defines the Joystick that we will be using for driving.\n self.DriveStick = wpilib.Joystick(self.DriveStickChannel)\n\n # Initializing drive motors\n self.FLMotor = wpilib.Spark(self.FLChannel)\n self.FRMotor = wpilib.Spark(self.FRChannel)\n\n self.RLMotor = wpilib.Spark(self.RLChannel)\n self.RRMotor = wpilib.Spark(self.RRChannel)\n\n self.LoaderGrab = ctre.VictorSPX(1)\n\n # Puts the motors into groups so that they fit the parameters of the function.\n self.LMG = wpilib.SpeedControllerGroup(self.FLMotor, self.RLMotor)\n self.RMG = wpilib.SpeedControllerGroup(self.FRMotor, self.RRMotor)\n\n # The drive function that tells the computer what kind of drive to use and where the motors are.\n self.drive = DifferentialDrive(self.LMG, self.RMG)\n\n # self.ColorSensor = ColorSensorV3(wpilib.I2C.Port.kOnboard)\n\n # Components is a dictionary that contains any variables you want to put into it. All of the variables put into\n # components dictionary is given to the autonomous modes.\n # self.components = {\"drive\": self.drive}\n\n # Sets up the autonomous mode selector by telling it where the autonomous modes are at and what the autonomous\n # modes should inherit.\n # self.automodes = autonomous.AutonomousModeSelector(\"autonomous\", self.components)\n\n self.timer = wpilib.Timer()\n\n # def autonomousPeriodic(self):\n # Runs the autonomous mode selector.\n # self.automodes.run()\n\n def operatorControl(self):\n\n self.drive.setSafetyEnabled(True)\n\n while self.isOperatorControlEnabled():\n\n # Checks to see if you are holding button 2 and if so automatically aims the robot. Else, normal drive.\n # if self.DriveStick.getrawButton(2):\n\n # Tx and Ty are variables marking the angle to the target.\n # If they are 0 then the calibrated crosshair is right on the target.\n # tx = self.table.getNumber(\"tx\")\n # ty = self.table.getNumber(\"ty\")\n\n # Angle to the target based off of the angle the camera is mounted at and the angle the camera measures.\n # targetAngle = 20 + ty\n # Distance from the target as calculated off of the equation\n # (TargetHeight - CameraHeight) / Tan(MountAngle + TargetAngle) = D\n # For a more in-depth explanation look a the limelight docs at docs.limelightvision.io\n # distance = 8 / tan(targetAngle)\n\n # The error in your robot's heading based off of the angle to the target.\n # headingError = tx\n # SteerAdjust = 0\n\n # Turns the robot if it is more than one degree off.\n # if tx > 1.0:\n # SteerAdjust = self.ControlConstant * headingError + self.minCommand\n # elif tx < -1.0:\n # SteerAdjust = self.ControlConstant * headingError - self.minCommand\n\n # Uses the calculations to turn the robot.\n # self.drive.tankDrive(\n # SteerAdjust,\n # -SteerAdjust,\n # squareInputs=False\n # )\n\n # else:\n # drives the robot with the arcade drive, which uses one joystick and is a bit easier to use. It is a\n # part of DifferentialDrive\n self.drive.arcadeDrive(\n self.DriveStick.getY(),\n self.DriveStick.getX(),\n squareInputs=True\n )\n\n wpilib.Timer.delay(.005)\n\n\n# Runs the class MyRobot.\nif __name__ == '__main__':\n wpilib.run(MyRobot)\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":5500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"361192742","text":"from django import forms\n\nfrom company.models import Company, Office\nfrom .models import Vacancy\n\n\nclass VacancyForm(forms.ModelForm):\n class Meta:\n exclude = ('uuid', 'enabled', 'published',)\n model = Vacancy\n\n labels = {\n 'description': 'Vacancy description',\n 'experience': 'Required work experience, years',\n 'requirement': 'Requirements',\n 'salary_from': 'Salary from, $',\n 'salary_up_to': 'Salary up to, $'\n }\n\n def __init__(self, *args, **kwargs):\n employer = kwargs.pop('employer')\n super().__init__(*args, **kwargs)\n self.fields['company'].queryset = Company.objects.filter(employer=employer)\n self.fields['office'].queryset = Office.objects.filter(company__in=self.fields['company'].queryset)\n\n\nclass EditVacancyForm(forms.ModelForm):\n class Meta:\n exclude = ('company', 'uuid', 'published', 'allowed_amount', 'enabled',)\n model = Vacancy\n\n labels = {\n 'description': 'Vacancy description',\n 'experience': 'Required work experience, years',\n 'requirement': 'Requirements',\n }\n","sub_path":"vacancy/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"392371487","text":"# -*- coding: utf-8 -*-\n# @Time : 04/04/2021 17:03\n# @Author : Cao Junhao\n# @Site : \n# @File : 03_Mask_Detection.py\n# @Software: PyCharm\nfrom tensorflow.keras.applications.densenet import preprocess_input\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.models import load_model\nimport numpy as np\nimport argparse\nimport cv2\n\n# Construct the argument parser to parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\",\n type=str,\n default='test_image/02.png',\n help=\"path to input image\")\nap.add_argument(\"-i1\", \"--image1\",\n type=str,\n default=\"test_image/03.jpg\",\n help=\"path to input image\")\nap.add_argument(\"-i2\", \"--image2\",\n type=str,\n default='test_image/Junhao_Yuan02.jpg',\n help=\"path to input image\")\nap.add_argument(\"-i3\", \"--image3\",\n type=str,\n default='test_image/Junhao.jpg',\n help=\"path to input image\")\nap.add_argument(\"-o\", \"--output\", type=str,\n default=\"detection_image_04.png\",\n help=\"path to optional output video file\")\nap.add_argument(\"-m\", \"--model\",\n type=str,\n default=\"DenseNet201_mask_detector.model\",\n help=\"path to trained face mask detector model\")\nap.add_argument(\"-c\", \"--confidence\",\n type=float,\n default=0.5,\n help=\"minimum probability to filter weak detections\")\nap.add_argument(\"-p\", \"--prototxt\",\n default=\"D:/01_CaoJunhao/FaceDetectSSD/deploy.prototxt\",\n help=\"path to Caffe 'deploy' prototxt file\")\nap.add_argument(\"-f\", \"--face_detector\",\n type=str,\n default=\"D:/01_CaoJunhao/FaceDetectSSD/VGG_WIDERFace_SSD_300x300_iter_120000.caffemodel\",\n help=\"path to face detector model directory\")\nargs = vars(ap.parse_args())\n\n# Define the colour corresponding each situation of the mask respectively.\nlabels_dict = {0: 'Incorrect Mask',\n 1: 'Correct Mask',\n 2: \"No Mask\"}\ncolor_dict = {0: (255, 255, 0),\n 1: (0, 255, 0),\n 2: (0, 0, 255)}\n\n\ndef mask_detection():\n # Loading the face detector training with SSD\n net = cv2.dnn.readNetFromCaffe(args['prototxt'],\n args['face_detector'])\n\n # Loading the mask detector model\n model = load_model(args['model'])\n\n # Loading the image from Mask_ML, and extract its spatial dimensions\n image = cv2.imread(args['image3'])\n (high, weight) = image.shape[:2]\n print(high)\n print(weight)\n\n # Construct a blob format for the image\n blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), 127.5)\n\n # Pass the blob through network and acquire the face detections\n print('Extracting the face detections ....')\n net.setInput(blob)\n detections = net.forward()\n\n # Loop over obtained detections\n for i in range(0, detections.shape[2]):\n # Grab the confidence (probability) associated with the detection\n confidence = detections[0, 0, i, 2]\n\n # Cutting off the weak detections guarantees the result is great than the minimum probability\n if confidence > args[\"confidence\"]:\n # Confirm the (x,y) to bounding box for each object\n box_object = detections[0, 0, i, 3:7] * np.array([weight,\n high,\n weight,\n high])\n x_start, y_start, x_end, y_end = box_object.astype('int')\n # To ensure the bounding box is inserted into the dimensions of the frame\n (x_start, y_start) = (max(0, x_start-7),\n max(0, y_start-7))\n (x_end, y_end) = (min(weight - 1, x_end+7),\n min(high - 1, y_end+7))\n\n # Extract the ROI (Region Of Interest)\n # Transform it from BGR to RGB channel\n # Resize it to 224*224, and process it\n face_object = image[y_start: y_end, x_start: x_end]\n # cv2.imshow(\"Cropped\", face_object)\n # cv2.waitKey(0)\n\n face_object = cv2.cvtColor(face_object, cv2.COLOR_BGR2RGB)\n face_object = cv2.resize(face_object, (224, 224))\n face_object = img_to_array(face_object)\n face_object = preprocess_input(face_object)\n face_object = np.expand_dims(face_object, axis=0)\n print(face_object.shape)\n result = model.predict(face_object)\n label = np.argmax(result, axis=1)[0]\n face_label = labels_dict[label]\n color_label = color_dict[label]\n\n (Incorrect_Mask, Correct_Mask, No_Mask) = model.predict(face_object)[0]\n\n # Include the probability in the label\n label = \"{}: {:.2f}%\".format(face_label,\n max(Incorrect_Mask,\n Correct_Mask,\n No_Mask) * 100)\n\n cv2.putText(image, label,\n (x_start, y_start - 10),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.45, color_label, 2)\n\n cv2.rectangle(image, (x_start, y_start),\n (x_end, y_end), color_label, 2)\n\n cv2.imshow('Image', image)\n key = cv2.waitKey(0)\n cv2.imwrite(args[\"output\"], image)\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n mask_detection()\n\n","sub_path":"03_Mask_Detection.py","file_name":"03_Mask_Detection.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"347362998","text":"#! /usr/bin/env python\n# Copyright (C) 2016 ETH Zurich, rijulian@phys.ethz.ch\n#\n# This file fetches the original SDSS CMASS galaxy spectra\n#\n# System imports\nimport numpy as np\nimport astropy.io.fits as aif\n\n# Local modules\nfrom get_plate_id import *\n\n\ndef sdss_data():\n\n ####################\n # define #\n ####################\n\n # define survey wave length parameters\n wavelength_min = 3650.\n wavelength_max = 10400.\n num_pixels = 4639.\n\n # input plates\n # original source of the plates is:\n # https://data.sdss.org/sas/dr13/eboss/spectro/redux/v5_9_0/\n\n pl_num = np.zeros((10,2))\n\n #ten random plates\n pl_num[0][0] = int(4288)\n pl_num[0][1] = int(55501)\n pl_num[1][0] = int(4412)\n pl_num[1][1] = int(55912)\n pl_num[2][0] = int(4540)\n pl_num[2][1] = int(55863)\n pl_num[3][0] = int(5044)\n pl_num[3][1] = int(56186)\n pl_num[4][0] = int(5206)\n pl_num[4][1] = int(56033)\n pl_num[5][0] = int(5710)\n pl_num[5][1] = int(56658)\n pl_num[6][0] = int(5962)\n pl_num[6][1] = int(56265)\n pl_num[7][0] = int(6426)\n pl_num[7][1] = int(56334)\n pl_num[8][0] = int(6434)\n pl_num[8][1] = int(56362)\n pl_num[9][0] = int(7111)\n pl_num[9][1] = int(56741)\n\n\n # select CMASS galaxies of the plates\n cmass_mask = get_plate_id()\n\n\n # define and assign spectra and variables\n sdss_spec_obs = []\n sdss_spec_filtered = []\n spec_obs = []\n lam = []\n observed_spec = [[] for i in range(len(pl_num))]\n\n # get observed spectra of the CMASS galaxies\n for index in range(len(pl_num)):\n sdss_spec_obs.append('uspec/data/DR13/spPlate-%s-%s.fits'%(int(pl_num[index][0]),int(pl_num[index][1])))\n sdss_spec_filtered.append('uspec/data/DR13/spZbest-%s-%s.fits'%(int(pl_num[index][0]),int(pl_num[index][1])))\n hdulist = aif.open(sdss_spec_obs[index])\n\n # plate lam\n c0 = hdulist[0].header['coeff0']\n c1 = hdulist[0].header['coeff1']\n num = hdulist[0].header['NAXIS1']\n platelam = np.zeros(num)\n\n for idx in range(len(platelam)):\n platelam[idx] = c0 + idx * c1\n lam_now = 10**platelam\n lam.append(lam_now)\n\n # observed spectra\n spec_obs_data = hdulist[0].data[cmass_mask[index]]\n spec_obs.append(spec_obs_data)\n spec_obs[index] = np.array(spec_obs[index])\n\n\n # compute survey wave length grid\n coeff0 = np.log10(wavelength_min)\n coeff1 = (np.log10(wavelength_max) - np.log10(wavelength_min)) / num_pixels\n survey_lam = 10 ** (coeff0 + coeff1 * np.arange(num_pixels + 1))\n\n # interpolate spectra to survey wave length grid\n for idx in range(len(pl_num)):\n for i in range(len(spec_obs[idx])):\n observed_spec[idx].append(np.interp(survey_lam, lam[idx], spec_obs[idx][i]))\n observed_spec[idx] = np.array(observed_spec[idx])\n\n # merge sdss cmass spectra into one array\n observed_spec_i = observed_spec[0]\n for idx in range(len(pl_num)-1):\n observed_spectrum = np.concatenate((observed_spec_i,observed_spec[idx+1]))\n observed_spec_i = observed_spectrum.tolist()\n\n # for analysis purposes adjust number of sdss cmass spectra to number of uspec spectra\n uspec_num = 1492\n observed_spectrum = observed_spectrum[:uspec_num]\n quarters_len = len(survey_lam)-len(survey_lam)/4\n\n # outskirt rejection (get rid of the sky remnant)\n wo_sky_lam = survey_lam[:quarters_len]\n wo_sky_spec = np.zeros((len(observed_spectrum),quarters_len))\n for idx in range(len(observed_spectrum)):\n wo_sky_spec[idx] = observed_spectrum[idx][:quarters_len]\n\n\n return survey_lam[:quarters_len], wo_sky_spec\n","sub_path":"uspec_light/pca_sdss.py","file_name":"pca_sdss.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"344503042","text":"# Copyright Materialize, Inc. and contributors. All rights reserved.\n#\n# Use of this software is governed by the Business Source License\n# included in the LICENSE file at the root of this repository.\n#\n# As of the Change Date specified in that file, in accordance with\n# the Business Source License, use of this software will be governed\n# by the Apache License, Version 2.0.\n\nfrom materialize.mzcompose.services import Service\n\nSERVICES = [\n Service(\n \"jaeger\",\n {\n \"image\": \"jaegertracing/all-in-one:1.36\",\n \"ports\": [\"16686:16686\", \"4317:4317\", \"4318:4318\", 14268, 14250],\n \"command\": [\"--collector.grpc-server.max-message-size=16777216\"],\n \"environment\": [\"COLLECTOR_OTLP_ENABLED=true\"],\n \"allow_host_ports\": True,\n },\n ),\n]\n","sub_path":"misc/opentelemetry/mzcompose.py","file_name":"mzcompose.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"124021094","text":"class Solution:\n\n #time exceeded\n def getPermutation(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n res = []\n nums = [i for i in range(1, n + 1)]\n self.backtrack(nums, res, [])\n ans = \"\"\n for item in res[k - 1]:\n ans += str(item)\n return ans\n\n def backtrack(self, nums, res, temp):\n if len(temp) == len(nums):\n res.append(list(temp))\n for i in range(0, len(nums)):\n if nums[i] in temp:\n continue\n temp.append(nums[i])\n self.backtrack(nums, res, temp)\n temp.pop()\n\n #solution2\n def getPermutationV2(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n factorial = []\n factorial.append(1)\n fact = 1\n for i in range(1, n + 1):\n fact *= i\n factorial.append(fact)\n\n number = []\n for i in range(1, n + 1):\n number.append(i)\n k -= 1\n res = \"\"\n for i in range(1, n + 1):\n inx = k // factorial[n - i]\n k -= inx * factorial[n - i]\n res += str(number[inx])\n number.pop(inx)\n return res\n\nif __name__ == '__main__':\n n = 7\n k = 245\n print(Solution().getPermutation(n, k))\n print(Solution().getPermutationV2(n, k))","sub_path":"60PermutationSequence/60PermutationSequence.py","file_name":"60PermutationSequence.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"615105908","text":"#########################################################################################################\n# Process grey attenuation\n#########################################################################################################\n\n\nimport datetime\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\nimport matplotlib.dates as mdates\nfrom matplotlib import gridspec\n\nimport numpy as np\n\nfrom scipy.interpolate import interp1d\nfrom astropy.time import Time\nfrom astropy.table import Table,QTable\nfrom astropy.io import fits,ascii\nfrom astropy.visualization.mpl_normalize import (ImageNormalize,MinMaxInterval, SqrtStretch)\n\nimport os,sys\nfrom os import listdir\nfrom os.path import isfile, join\nimport pandas as pd\nimport re\n\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n\n\nif not 'workbookDir' in globals():\n workbookDir = os.getcwd()\nprint('workbookDir: ' + workbookDir)\n\nspectractordir=workbookDir+\"/../../Spectractor\"\nprint('spectractordir: ' + spectractordir)\ntoolsdir=workbookDir+\"/../common_tools\"\nprint(\"toolsdir:\",toolsdir)\n\n\nimport sys\nsys.path.append(workbookDir)\nsys.path.append(spectractordir)\nsys.path.append(os.path.dirname(workbookDir))\nsys.path.append(toolsdir)\n\n\n\nfrom spectractor import parameters\nfrom spectractor.extractor.extractor import Spectractor\nfrom spectractor.logbook import LogBook\nfrom spectractor.extractor.dispersers import *\nfrom spectractor.extractor.spectrum import *\nfrom spectractor.tools import ensure_dir\n\n\n\n\n\n# PhotUtil\nfrom astropy.stats import sigma_clipped_stats\nfrom photutils import aperture_photometry\nfrom photutils import CircularAperture,CircularAnnulus\nfrom astropy.visualization import SqrtStretch\nfrom astropy.visualization.mpl_normalize import ImageNormalize\nfrom astropy.visualization import astropy_mpl_style\n#plt.style.use(astropy_mpl_style)\n\nfrom photutils import DAOStarFinder\n\n\nfrom photutils import make_source_mask\nfrom astropy.stats import SigmaClip\nfrom photutils import Background2D, MedianBackground\n\nimport astropy\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import Angle\nfrom astropy.table import Table\nfrom astropy.coordinates import Angle\nfrom astropy.time import Time, TimezoneInfo\nfrom pytz import timezone\nimport pytz\nfrom astropy.coordinates import SkyCoord, EarthLocation, AltAz\nfrom astropy.coordinates import Longitude, Latitude\nfrom astropy.coordinates import get_sun,get_moon\n\n\n\nplt.rcParams[\"axes.labelsize\"]=\"large\"\nplt.rcParams[\"axes.linewidth\"]=2.0\nplt.rcParams[\"xtick.major.size\"]=8\nplt.rcParams[\"ytick.major.size\"]=8\nplt.rcParams[\"ytick.minor.size\"]=5\nplt.rcParams[\"xtick.labelsize\"]=\"large\"\nplt.rcParams[\"ytick.labelsize\"]=\"large\"\n\nplt.rcParams[\"figure.figsize\"]=(8,8)\nplt.rcParams['axes.titlesize'] = 12\nplt.rcParams['axes.titleweight'] = 'bold'\n#plt.rcParams['axes.facecolor'] = 'blue'\nplt.rcParams['xtick.direction'] = 'out'\nplt.rcParams['ytick.direction'] = 'out'\nplt.rcParams['lines.markeredgewidth'] = 0.3 # the line width around the marker symbol\nplt.rcParams['lines.markersize'] = 5 # markersize, in points\nplt.rcParams['grid.alpha'] = 0.75 # transparency, between 0.0 and 1.0\nplt.rcParams['grid.linestyle'] = '-' # simple line\nplt.rcParams['grid.linewidth'] = 0.4 # in points\n\n\n\n\nPDM_Longitude=Longitude(u'0°08′34″')\nPDM_Latitude=Latitude(u'42°56′11″')\nPDM_Height=2.877*u.m\n\n\n\n# where are the image\n#----------------------\nthedate = \"20190215\"\nrawinput_directory=\"/Users/dagoret/DATA/PicDuMidiFev2019/prod_\"+thedate+\"_v4\"\n\nimage_dir=\"allimgpng\"\nimage_name=\"pdmimg\"\npadding=4\n\nFLAG_MSK = True\nbadphotometrylist = np.array(\n [46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,\n 82, 83, 94, 96, 97, 98, 99, 100, 101, 102, 103, 104, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,\n 123, 124, 125,\n 187, 195, 202, 237, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271,\n 272, 273,\n 316, 317, 234, 326, 345])\n\n#-----------------------------------------------------------------------------------------------\ndef weighted_avg_and_std(values, weights):\n \"\"\"\n Return the weighted average and standard deviation.\n\n values, weights -- Numpy ndarrays with the same shape.\n\n For example for the PSF\n\n x=pixel number\n y=Intensity in pixel\n\n values-x\n weights=y=f(x)\n\n \"\"\"\n average = np.average(values, weights=weights)\n variance = np.average((values - average) ** 2, weights=weights) # Fast and numerically precise\n return average, np.sqrt(variance)\n\n\n#---------------------------------------------------------------\ndef PlotStarmagvsUTC(mydatetime, mystarmag,mystarmag_err,mymask,ax,TMIN,TMAX,Ntot):\n \"\"\"\n\n :param ifig:\n :param all_airmass:\n :param all_datetime:\n :param all_flag:\n :return:\n \"\"\"\n\n\n N=len(mydatetime)\n\n\n\n # wavelength bin colors\n jet = plt.get_cmap('jet')\n cNorm = colors.Normalize(vmin=0, vmax=Ntot)\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)\n all_colors = scalarMap.to_rgba(np.arange(Ntot), alpha=1)\n\n\n myFmt = mdates.DateFormatter('%d-%H:%M')\n ax.xaxis.set_major_formatter(myFmt)\n\n color_to_plot=all_colors[:N]\n\n if FLAG_MSK:\n mymask=np.array(mymask)\n msize = np.where(mymask, 0,10)\n\n\n #plt.errorbar(all_datetime, all_starmag, yerr=all_starmag_err, fmt='.', color=\"red\", ecolor='grey')\n\n if FLAG_MSK:\n ax.scatter(mydatetime, mystarmag, s=msize,marker=\"o\", c=all_colors[:N])\n else:\n ax.scatter(mydatetime, mystarmag,marker=\"o\", c=all_colors[:N])\n\n\n myFmt = mdates.DateFormatter('%d-%H:%M')\n #ax.gca().xaxis.set_major_formatter(myFmt)\n ax.xaxis.set_major_formatter(myFmt)\n\n #ax.gcf().autofmt_xdate()\n #ax.autofmt_xdate()\n\n ax.set_xlim(TMIN,TMAX)\n ax.set_ylim(-16.25,-15.75)\n\n ax.grid(True, color=\"k\")\n ax.set_xlabel(\"date (UTC)\")\n ax.set_ylabel(\"Star magnitude (mag)\")\n ax.set_title(\"Star magnitude vs date\")\n\n#---------------------------------------------------------------\ndef PlotBkgmagvsUTC(mydatetime, mybkgmag,mybkgmag_err,mymask,ax,TMIN,TMAX,Ntot):\n \"\"\"\n\n :param ifig:\n :param all_airmass:\n :param all_datetime:\n :param all_flag:\n :return:\n \"\"\"\n\n\n N=len(mydatetime)\n\n\n\n # wavelength bin colors\n jet = plt.get_cmap('jet')\n cNorm = colors.Normalize(vmin=0, vmax=Ntot)\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)\n all_colors = scalarMap.to_rgba(np.arange(Ntot), alpha=1)\n\n\n myFmt = mdates.DateFormatter('%d-%H:%M')\n ax.xaxis.set_major_formatter(myFmt)\n\n if FLAG_MSK:\n mymask=np.array(mymask)\n msize = np.where(mymask, 0,10)\n\n\n\n\n #plt.errorbar(all_datetime, all_starmag, yerr=all_starmag_err, fmt='.', color=\"red\", ecolor='grey')\n if FLAG_MSK:\n ax.scatter(mydatetime, mybkgmag, s=msize,marker=\"o\", c=all_colors[:N])\n else:\n ax.scatter(mydatetime, mybkgmag, marker=\"o\", c=all_colors[:N])\n\n\n myFmt = mdates.DateFormatter('%d-%H:%M')\n #ax.gca().xaxis.set_major_formatter(myFmt)\n ax.xaxis.set_major_formatter(myFmt)\n\n #ax.gcf().autofmt_xdate()\n #ax.autofmt_xdate()\n\n ax.set_xlim(TMIN,TMAX)\n\n ax.grid(True, color=\"k\")\n ax.set_xlabel(\"date (UTC)\")\n ax.set_ylabel(\"Bkb magnitude (mag)\")\n ax.set_title(\"Background magnitude vs date\")\n\n\n#------------------\ndef PlotElevation(delta_midnight,sunaltazs,moonaltazs,staraltazs,DTim,ax):\n \"\"\"\n\n :return:\n \"\"\"\n #plt.figure(figsize=(16., 10.))\n ax.plot(delta_midnight, sunaltazs.alt, color='r', label='Sun')\n ax.plot(delta_midnight, moonaltazs.alt, color='orange', label='Moon')\n ax.scatter(delta_midnight, staraltazs.alt,\n c=staraltazs.az, label='hd_116405', lw=0, s=8,\n cmap='viridis')\n\n ax.plot([DTim,DTim],[0,90],\"-b\")\n\n # plot astronomical crepuscule\n ax.fill_between(delta_midnight.to('hr').value, 0, 90,\n sunaltazs.alt < -0 * u.deg, color='0.5', zorder=0)\n # plot astronomical night\n ax.fill_between(delta_midnight.to('hr').value, 0, 90,\n sunaltazs.alt < -18 * u.deg, color='k', zorder=0)\n #plt.colorbar().set_label('Azimuth [deg]')\n ax.legend(loc='upper left',fontsize=8)\n ax.set_xlim(-12, 12)\n ax.set_xticks(np.arange(13) * 2 - 12)\n ax.set_ylim(0, 90)\n #ax.set_title('hd_116405 and Moon during night 15 to 16 February 2019')\n ax.set_xlabel('Hours from Midnight (France:Pic du Midi)')\n ax.set_ylabel('Altitude [deg]')\n ax.grid()\n #plt.show()\n\n\n\n\n#-------------------------------------------------------------------------\n#\n# MAIN()\n#\n#---------------------------------------------------\n\nif __name__ == \"__main__\":\n\n\n ensure_dir(image_dir)\n\n starloc = astropy.coordinates.SkyCoord.from_name('HD116405')\n # definition of the location to astropy\n site_location = astropy.coordinates.EarthLocation(lat=PDM_Latitude, lon=PDM_Longitude, height=PDM_Height)\n\n # UTC offset\n utcoffset = 1 * u.hour # France\n # local midnight in UTC\n midnight = Time('2019-2-16 00:00:00') - utcoffset\n delta_midnight = np.linspace(-12, 12, 1000) * u.hour\n\n # array of times in UTC\n times_seq = midnight + delta_midnight\n\n # sequence in altitude Azimuth object at current site\n frame_seq = AltAz(obstime=times_seq, location=site_location)\n\n # Altitude and Elevation at current site at selected time\n sunaltazs_seq = get_sun(times_seq).transform_to(frame_seq)\n moonaltazs_seq = get_moon(times_seq).transform_to(frame_seq)\n staraltazs_seq = starloc.transform_to(frame_seq)\n\n\n\n\n t = Table.read('processStarPhotometry.ecsv', format='ascii.ecsv')\n\n t[\"airmass\"].info.format = '%1.2f' # for consistent table output\n t[\"starmag\"].info.format = '%2.3f'\n t[\"bkgmag\"].info.format = '%2.3f'\n t[\"starmagerr\"].info.format = '%1.3g'\n t[\"bkgmagerr\"].info.format = '%1.3g'\n t[\"x0\"].info.format = '%3.0f'\n t[\"y0\"].info.format = '%3.0f'\n\n\n print(t)\n Nobs=len(t)\n Ntot=Nobs\n\n all_files=t[\"file\"]\n all_datetime = [Time(d, format='isot', scale='utc').to_datetime() for d in t[\"date\"]]\n TMIN=all_datetime[0]\n TMAX=all_datetime[-1]\n\n\n cutmax=10\n\n\n\n\n current_date=[]\n current_starmag=[]\n current_starmagerr=[]\n current_bkgmag = []\n current_bkgmagerr = []\n current_mask = []\n\n\n for idx in np.arange(Nobs):\n\n thefile = all_files[idx]\n therawfile=thefile.replace(\"_spectrum.fits\",\".fit\")\n\n #print(\"{}) : {}, {} \".format(idx, thefile,therawfile))\n\n fullfilename = os.path.join(rawinput_directory, therawfile)\n\n # definition de la grille\n fig, ax = plt.subplots(2, 2, figsize=(18,10), gridspec_kw={'height_ratios': [1, 1],'width_ratios': [1,2]})\n ax1 = ax[0, 0]\n ax2 = ax[0, 1]\n ax3 = ax[1, 0]\n ax4 = ax[1, 1]\n\n\n #try:\n if 1:\n hdu = fits.open(fullfilename)\n\n data=hdu[0].data\n vmin = data.min()\n vmax = data.max() / cutmax\n\n norm = ImageNormalize(data, interval=MinMaxInterval(), stretch=SqrtStretch())\n\n ax1.imshow(hdu[0].data,origin=\"lower\",cmap=\"jet\",vmin=vmin,vmax=vmax,norm=norm,aspect=\"equal\")\n title=\"{}) : {}\".format(idx,therawfile,fontsize=\"10\")\n title=title.split(\"Filter\")[0]\n label0=t[\"date\"][idx]\n label1=\"UTC : \"+label0.split(\"T\")[1]\n label2='airmass = {:1.2f}'.format(t[\"airmass\"][idx])\n ax1.text(100, 1900,title, fontsize=12,color='black',fontweight='bold')\n ax1.text(100, 1700,label1, fontsize=12,color='black',fontweight='bold')\n ax1.text(100, 1500, label2, fontsize=12,color='black',fontweight='bold')\n #ax1.set_title(title,fontsize=10)\n ax1.grid(color=\"white\")\n x0=t[\"x0\"][idx]\n y0=t[\"y0\"][idx]\n aperture = CircularAperture((x0,y0), r=2*30)\n\n # Do not plot only of not FLAG_MASK is ON\n if ( FLAG_MSK and idx not in badphotometrylist ):\n aperture.plot(color='red', lw=2,ax=ax1)\n\n current_date.append(all_datetime[idx])\n current_starmag.append(t[\"starmag\"][idx])\n current_starmagerr.append(t[\"starmagerr\"][idx])\n current_bkgmag.append(t[\"bkgmag\"][idx])\n current_bkgmagerr.append(t[\"bkgmagerr\"][idx])\n\n if idx in badphotometrylist:\n current_mask.append(True)\n else:\n current_mask.append(False)\n\n PlotStarmagvsUTC(current_date, current_starmag, current_starmagerr,current_mask, ax2, TMIN, TMAX, Ntot)\n PlotBkgmagvsUTC(current_date, current_bkgmag, current_bkgmagerr, current_mask,ax4, TMIN, TMAX, Ntot)\n\n #Detla time relative to midnight : current\n DTim=(Time(t[\"date\"][idx], format='isot', scale='utc')-(Time('2019-2-16 00:00:00') - utcoffset)).sec/3600.\n\n PlotElevation(delta_midnight, sunaltazs_seq, moonaltazs_seq, staraltazs_seq,DTim ,ax3)\n\n\n fig.tight_layout()\n fig.subplots_adjust(wspace=0, hspace=0)\n\n plt.draw()\n\n\n #image_dir = \"allpdm\"\n #image_name = \"pdmimg\"\n #padding = 4\n # convert -delay 100 pdmimg_*.png pdmimg.gif\n\n figfilename=image_name+\"_{0:04d}.png\".format(idx)\n\n plt.savefig(os.path.join(image_dir,figfilename))\n plt.pause(1e-9)\n #plt.clf()\n plt.close()\n\n\n\n #os.system('convert -delay 1 allpdm/pdmimg_*.png animation.gif')\n\n\n #except:\n if 0:\n print(\"Unexpected error:\", sys.exc_info()[0])\n pass\n\n #----------------------------------------------------------------------------------------------------------------------","sub_path":"ana_20190215_HD116405_Filtre_None/cineStarPhotometryMulti.py","file_name":"cineStarPhotometryMulti.py","file_ext":"py","file_size_in_byte":13898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"397790631","text":"#Helper functions for image preprocessing.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport tensorflow as tf\n\n\ndef distort_image(image, thread_id):\n #Perform random distortions on an image.\n\n # Randomly flip horizontally.\n with tf.name_scope(\"flip_horizontal\", values=[image]):\n image = tf.image.random_flip_left_right(image)\n\n # Randomly distort the colors based on thread id.\n color_ordering = thread_id % 2\n with tf.name_scope(\"distort_color\", values=[image]):\n if color_ordering == 0:\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.032)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n elif color_ordering == 1:\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n image = tf.image.random_saturation(image, lower=0.5, upper=1.5)\n image = tf.image.random_hue(image, max_delta=0.032)\n\n # The random_* ops do not necessarily clamp.\n image = tf.clip_by_value(image, 0.0, 1.0)\n\n return image\n\n\ndef process_image(encoded_image,\n is_training,\n height,\n width,\n resize_height=346,\n resize_width=346,\n thread_id=0,\n image_format=\"jpeg\"):\n #Decode an image, resize and apply random distortions.\n\n # Helper function to log an image summary to the visualizer.\n # only logged in thread 0.\n def image_summary(name, image):\n if not thread_id:\n tf.summary.image(name, tf.expand_dims(image, 0))\n\n\n with tf.name_scope(\"decode\", values=[encoded_image]):\n if image_format == \"jpeg\":\n image = tf.image.decode_jpeg(encoded_image, channels=3)\n elif image_format == \"png\":\n image = tf.image.decode_png(encoded_image, channels=3)\n else:\n raise ValueError(\"Invalid image format: %s\" % image_format)\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n image_summary(\"original_image\", image)\n\n # Resize image.\n assert (resize_height > 0) == (resize_width > 0)\n if resize_height:\n image = tf.image.resize_images(image,\n size=[resize_height, resize_width],\n method=tf.image.ResizeMethod.BILINEAR)\n\n # Crop to final dimensions.\n if is_training:\n image = tf.random_crop(image, [height, width, 3])\n else:\n # Central crop, assuming resize_height > height, resize_width > width.\n image = tf.image.resize_image_with_crop_or_pad(image, height, width)\n\n image_summary(\"resized_image\", image)\n\n # Randomly distort the image.\n if is_training:\n image = distort_image(image, thread_id)\n\n image_summary(\"final_image\", image)\n\n # Rescale to [-1,1] instead of [0, 1]\n image = tf.subtract(image, 0.5)\n image = tf.multiply(image, 2.0)\n return image","sub_path":"project/Source/inputs/image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"462440133","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth import get_user_model\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\n\n\nclass TokenModelAdminFormTestCase(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n cls.user = get_user_model().objects.create_user(\n 'foo', is_staff=True, is_superuser=True)\n\n def test_default_token_value(self):\n url = reverse('core_token_modeladmin_create')\n self.client.force_login(self.user)\n response = self.client.get(url)\n form = response.context_data['form']\n self.assertTrue(form.initial['key'])\n","sub_path":"privagal/core/tests/test_modeladmin.py","file_name":"test_modeladmin.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"101894874","text":"\r\nimport arcade\r\nfrom piece import Piece\r\n\r\nBLACK = 1\r\nWHITE = -1\r\nNONE = 0\r\n\r\nSCREEN_WIDTH = 1024\r\nSCREEN_HEIGHT = 768\r\n\r\nTILE_WIDTH = 80\r\nSTART_X = (SCREEN_WIDTH - TILE_WIDTH * 7) / 2\r\nSTART_Y = (SCREEN_HEIGHT - TILE_WIDTH * 7 ) / 2\r\n\r\nclass Board():\r\n\r\n def __init__(self, size):\r\n global START_X\r\n global START_Y\r\n self.pieces: arcade.SpriteList = arcade.SpriteList()\r\n self.valid_moves = []\r\n self.selected_piece = None\r\n self.board_state = []\r\n self.size = size\r\n START_X = (SCREEN_WIDTH - TILE_WIDTH * (size-1)) / 2\r\n START_Y = (SCREEN_HEIGHT - TILE_WIDTH * (size-1) ) / 2\r\n\r\n for i in range(size):\r\n row = []\r\n for j in range(size):\r\n row.append(NONE)\r\n self.board_state.append(row)\r\n\r\n for i in range(1, size - 1):\r\n #black pieces\r\n #bottom\r\n piece = Piece(BLACK, i, 0, size)\r\n self.append(piece)\r\n self.board_state[i][0] = BLACK\r\n\r\n #top\r\n piece = Piece(BLACK, i, size - 1, size)\r\n self.append(piece)\r\n self.board_state[i][size - 1] = BLACK\r\n\r\n #white piece\r\n #left\r\n piece = Piece(WHITE, 0, i, size)\r\n self.append(piece)\r\n self.board_state[0][i] = WHITE\r\n #right\r\n piece = Piece(WHITE, size - 1, i, size)\r\n self.append(piece)\r\n self.board_state[size - 1][i] = WHITE\r\n \r\n def draw(self):\r\n self.pieces.draw()\r\n for move in self.valid_moves:\r\n line = arcade.create_line(self.selected_piece.center_x, self.selected_piece.center_y, \r\n self.selected_piece.center_x + move[0] * TILE_WIDTH, self.selected_piece.center_y + move[1] * TILE_WIDTH, arcade.color.RED) \r\n line.draw()\r\n\r\n def append(self, piece):\r\n self.pieces.append(piece)\r\n \r\n def get_valid_moves(self, piece):\r\n\r\n #relative move from piece\r\n self.valid_moves = []\r\n self.selected_piece = piece\r\n\r\n vertical_count = 0\r\n horizontal_count = 0\r\n topLeft_bottomRight = 0\r\n topRight_bottomLeft = 0\r\n for p in self.pieces:\r\n if p.pos_x == piece.pos_x:\r\n vertical_count += 1\r\n if p.pos_y == piece.pos_y:\r\n horizontal_count += 1\r\n if p.pos_x + p.pos_y == piece.pos_x + piece.pos_y:\r\n topLeft_bottomRight += 1\r\n if p.pos_x - piece.pos_x == p.pos_y - piece.pos_y:\r\n topRight_bottomLeft += 1\r\n \r\n x = piece.pos_x\r\n y = piece.pos_y\r\n opponent_color = piece.type * -1\r\n #left\r\n #if inside and not same color\r\n if x - horizontal_count >= 0 and self.board_state[x - horizontal_count][y] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, horizontal_count ):\r\n if self.board_state[x-i][y] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [-horizontal_count, 0]\r\n self.valid_moves.append(move)\r\n \r\n\r\n #right\r\n if x + horizontal_count < self.size and self.board_state[x + horizontal_count][y] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, horizontal_count ):\r\n if self.board_state[x+i][y] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [horizontal_count, 0]\r\n self.valid_moves.append(move)\r\n \r\n #up\r\n if y + vertical_count < self.size and self.board_state[x][y + vertical_count] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, vertical_count ):\r\n if self.board_state[x][y + i] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [0, vertical_count]\r\n self.valid_moves.append(move)\r\n \r\n #down\r\n if y - vertical_count >= 0 and self.board_state[x][y - vertical_count] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, vertical_count ):\r\n if self.board_state[x][y - i] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [0, -vertical_count]\r\n self.valid_moves.append(move)\r\n \r\n #topleft\r\n if x - topLeft_bottomRight >= 0 and y + topLeft_bottomRight < self.size and self.board_state[x - topLeft_bottomRight][y + topLeft_bottomRight] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, topLeft_bottomRight ):\r\n if self.board_state[x - i][y + i] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [-topLeft_bottomRight, topLeft_bottomRight]\r\n self.valid_moves.append(move)\r\n \r\n #bottomRight\r\n if x + topLeft_bottomRight < self.size and y - topLeft_bottomRight >= 0 and self.board_state[x + topLeft_bottomRight][y - topLeft_bottomRight] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, topLeft_bottomRight ):\r\n if self.board_state[x + i][y - i] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [topLeft_bottomRight, -topLeft_bottomRight]\r\n self.valid_moves.append(move)\r\n \r\n #topRight\r\n if x + topRight_bottomLeft < self.size and y + topRight_bottomLeft < self.size and self.board_state[x + topRight_bottomLeft][y + topRight_bottomLeft] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, topRight_bottomLeft ):\r\n if self.board_state[x + i][y + i] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [topRight_bottomLeft, topRight_bottomLeft]\r\n self.valid_moves.append(move)\r\n \r\n \r\n #bottomLeft\r\n if x - topRight_bottomLeft >= 0 and y - topRight_bottomLeft >= 0 and self.board_state[x - topRight_bottomLeft][y - topRight_bottomLeft] != piece.type:\r\n #inside\r\n valid = True\r\n\r\n for i in range(1, topRight_bottomLeft ):\r\n if self.board_state[x - i][y - i] == opponent_color:\r\n valid = False\r\n break\r\n \r\n if valid:\r\n move = [-topRight_bottomLeft, -topRight_bottomLeft]\r\n self.valid_moves.append(move)\r\n\r\n\r\n\r\n #(x1, y1) to (x2, y2)\r\n def move_piece(self, x1, y1, x2, y2, turn):\r\n #select piece\r\n found = False\r\n for p in self.pieces:\r\n if p.pos_x == x1 and p.pos_y == y1 and p.type == turn:\r\n #sets selected piece and valid_moves variable\r\n self.get_valid_moves(p)\r\n found = True\r\n\r\n if not found:\r\n return False\r\n\r\n #relative position \r\n x = x2 - self.selected_piece.pos_x \r\n y = y2 - self.selected_piece.pos_y\r\n\r\n #get_valid_moves has relative pos\r\n for move in self.valid_moves:\r\n if move[0] == x and move[1] == y:\r\n #valid move\r\n target_x = self.selected_piece.pos_x + x\r\n target_y = self.selected_piece.pos_y + y\r\n\r\n self.board_state[self.selected_piece.pos_x][self.selected_piece.pos_y] = NONE\r\n self.board_state[target_x][target_y] = self.selected_piece.type\r\n\r\n collide = arcade.get_sprites_at_point( (START_X + target_x * TILE_WIDTH, START_Y + target_y * TILE_WIDTH ) , self.pieces)\r\n if len(collide) > 0:\r\n self.pieces.remove(collide[0])\r\n \r\n self.selected_piece.move(target_x, target_y)\r\n self.selected_piece = None\r\n self.valid_moves = []\r\n return True\r\n return False\r\n \r\n #returns BLACK WHITE OR NONE\r\n def check_end_state(self, last_color):\r\n black_count = self.connected_components(BLACK)\r\n white_count = self.connected_components(WHITE)\r\n if black_count == 1 and white_count == 1:\r\n return last_color\r\n if black_count == 1:\r\n return BLACK\r\n if white_count == 1:\r\n return WHITE\r\n return NONE\r\n \r\n \r\n\r\n def connected_components(self, type):\r\n vis = []\r\n count = 0\r\n for i in range(self.size):\r\n row = []\r\n for j in range(self.size):\r\n row.append(0)\r\n vis.append(row)\r\n \r\n for piece in self.pieces:\r\n if vis[piece.pos_x][piece.pos_y] == 1 or piece.type != type:\r\n continue\r\n count += 1\r\n q = []\r\n q.append([piece.pos_x, piece.pos_y])\r\n vis[piece.pos_x][piece.pos_y] = 1\r\n\r\n while len(q) > 0:\r\n current_piece = q.pop(0)\r\n dir = [-1, 0, 1]\r\n for i in dir:\r\n for j in dir:\r\n if i==0 and j==0:\r\n continue\r\n new_x = current_piece[0] + i\r\n new_y = current_piece[1] + j\r\n if new_x < 0 or new_x >= self.size or new_y < 0 or new_y >= self.size:\r\n continue\r\n if vis[new_x][new_y] == 0 and self.board_state[new_x][new_y] == type:\r\n q.append([new_x, new_y])\r\n vis[new_x][new_y] = 1\r\n return count\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","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":10287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"397400941","text":"import datetime\nfrom itertools import cycle\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.urls import reverse\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.views import generic\nfrom users.models import CustomUser\nfrom .models import Lunch\nfrom .forms import LunchForm\n\nfrom project.decorators import unacthenticated_user, allowed_user_types\n\n@login_required\ndef index(request):\n username = request.user\n user=CustomUser.objects.get(username=username)\n lunches = Lunch.objects.all()\n return render(request, 'lunches.html',\n {\n 'title': 'Lunches',\n 'lunches': lunches\n })\n\n@allowed_user_types(allowed_roles=['Teacher', 'Admin'])\ndef add_lunch(request):\n if request.method==\"GET\":\n lunchForm = LunchForm()\n lunches=Lunch.objects.all()\n return render(request, \"add_lunch.html\", {'lunchForm' : lunchForm})\n else:\n lunchForm = LunchForm(request.POST)\n if lunchForm.is_valid():\n try:\n lunch=Lunch()\n lunch.date = lunchForm.cleaned_data['date']\n lunch.title = lunchForm.cleaned_data['title']\n lunch.description = lunchForm.cleaned_data['description']\n lunch.save()\n messages.success(request,\"Successfully Added Lunch\")\n return HttpResponseRedirect(reverse(\"lunch:add_lunch\"))\n except:\n messages.error(request,\"Failed To Add Lunch\")\n return HttpResponseRedirect(reverse(\"lunch:add_lunch\"))\n\n@allowed_user_types(allowed_roles=['Teacher', 'Admin'])\ndef manage_lunches(request):\n lunches=Lunch.objects.all()\n return render(request,\"manage_lunches.html\", {\"lunches\":lunches})\n\n@allowed_user_types(allowed_roles=['Teacher', 'Admin'])\ndef edit_lunch(request,lunch_id):\n lunch=Lunch.objects.get(id=lunch_id)\n if request.method==\"GET\":\n lunchForm = LunchForm(\n initial={\n 'date': lunch.date,\n 'title': lunch.title,\n 'description': lunch.description\n }\n )\n return render(request,\"edit_lunch.html\", {\"lunch\": lunch, \"lunchForm\":lunchForm})\n else:\n lunchForm = LunchForm(request.POST)\n if lunchForm.is_valid():\n try:\n lunch.date = lunchForm.cleaned_data['date']\n lunch.title = lunchForm.cleaned_data['title']\n lunch.description = lunchForm.cleaned_data['description']\n lunch.save()\n messages.success(request,\"Successfully Edited Lunch\")\n return HttpResponseRedirect(reverse(\"lunch:edit_lunch\", kwargs={\"lunch_id\":lunch_id}))\n except:\n messages.error(request,\"Failed to Edit Lunch\")\n return HttpResponseRedirect(reverse(\"lunch:edit_course\", kwargs={\"lunch_id\":lunch_id}))\n else:\n messages.error(request,\"Invalid data\")\n return HttpResponseRedirect(reverse(\"lunch:edit_course\", kwargs={\"lunch_id\":lunch_id}))\n\n@allowed_user_types(allowed_roles=['Teacher', 'Admin'])\ndef delete_lunch(request,lunch_id):\n if request.method == 'GET':\n lunch=Lunch.objects.get(id=lunch_id)\n lunch.delete()\n messages.success(request,\"Successfully deleted Lunch\")\n return HttpResponseRedirect(reverse(\"lunch:manage_lunches\"))\n\ndef detail(request,lunch_id):\n lunch=Lunch.objects.get(id=lunch_id)\n if request.method==\"GET\":\n return render(request,\"lunch.html\", {\"lunch\": lunch})\n return HttpResponseRedirect(reverse(\"lunch:details\", kwargs={\"lunch_id\":lunch_id}))","sub_path":"lunch/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"544566227","text":"# coding: utf-8\nfrom __future__ import print_function\nimport sys\nfrom math import sqrt\n\n# RMSE is a measure of how spread out these residuals are. In other words, it tells you how concentrated the data is around the line of best fit\ndef rmse_metric(theta0, theta1, valuesX, valuesY):\n size = len(valuesX)\n sumError = 0.0\n for i in range(size):\n predictedY = theta0 + (valuesX[i] * theta1)\n predictionError = valuesY[i] - predictedY\n sumError += (predictionError ** 2)\n meanError = sumError / float(size)\n return sqrt(meanError)\n\n# provides a measure of how well observed outcomes are replicated by the model\ndef coef_determination(theta0, theta1, valuesX, valuesY):\n size = len(valuesX)\n sumSquare = 0.0\n sumSquareResiduals = 0.0\n meanY = sum(valuesY) / float(size)\n for i in range(size):\n predictedY = theta0 + (valuesX[i] * theta1)\n sumSquare += (valuesY[i] - meanY) ** 2\n sumSquareResiduals += (valuesY[i] - predictedY) ** 2\n measure = 1 - (sumSquareResiduals / sumSquare)\n return measure\n\n# mean/moyenne = sum(x) / len(x)\ndef mean(values):\n return (sum(values) / int(len(values)))\n\n# variance = sum((x - mean(x)) ^ 2)\ndef variance(values, mean):\n return (sum([(n - mean) ** 2 for n in values]))\n\n# covariance = sum((x(i) - mean(x)) * (y(i) - mean(y)))\ndef covariance(x, meanX, y, meanY):\n cvar = 0.0\n for i in range(len(x)):\n cvar += (x[i] - meanX) * (y[i] - meanY)\n return cvar\n\ndef trainModel(theta0, theta1, valuesX, valuesY):\n meanX, meanY = mean(valuesX), mean(valuesY)\n varX, varY = variance(valuesX, meanX), variance(valuesY, meanY)\n covar = covariance(valuesX, meanX, valuesY, meanY)\n theta1 = covar / varX\n theta0 = meanY - (theta1 * meanX)\n #print(\"theta0: %.3f, theta1: %.3f\" % (theta0, theta1))\n return theta0, theta1\n","sub_path":"linear_regression/simple_linear_regression.py","file_name":"simple_linear_regression.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"436951292","text":"#!/usr/bin/env python\n\n#\n# LSST Data Management System\n# Copyright 2016 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\nimport collections\nimport copy\nimport inspect\nimport itertools\nimport os\nimport uuid\n\nfrom lsst.daf.persistence import Access, Policy, Mapper, LogicalLocation, ButlerLocation\n\nimport yaml\n\nclass RepositoryCfg(Policy, yaml.YAMLObject):\n yaml_tag = u\"!RepositoryCfg\"\n yaml_loader = yaml.Loader\n yaml_dumper = yaml.Dumper\n\n def __init__(self, cls, id, accessCfg, parentCfgs, parentJoin, peerCfgs, mapper, mapperArgs):\n super(RepositoryCfg, self).__init__()\n if not hasattr(parentCfgs, '__iter__'):\n parentCfgs = (parentCfgs,)\n self.update({'cls':cls, 'id':id, 'accessCfg':accessCfg, 'parentCfgs':parentCfgs,\n 'parentJoin':parentJoin, 'peerCfgs':peerCfgs, 'mapper':mapper,\n 'mapperArgs':mapperArgs})\n\n @staticmethod\n def to_yaml(dumper, obj):\n return dumper.represent_mapping(RepositoryCfg.yaml_tag,\n {'cls':obj['cls'], 'id':obj['id'], 'accessCfg':obj['accessCfg'],\n 'parentCfgs':obj['parentCfgs'], 'parentJoin':obj['parentJoin'],\n 'peerCfgs':obj['peerCfgs'], 'mapper':obj['mapper'],\n 'mapperArgs':obj['mapperArgs']})\n @staticmethod\n def from_yaml(loader, node):\n obj = loader.construct_mapping(node)\n return RepositoryCfg(**obj)\n\n # todo these load & write methods are coupled to posix storage. need to invent butler mechanism for\n # multiple dispatch and implement it.\n @staticmethod\n def butlerRead(butlerLocation):\n if butlerLocation.getStorageName() is not \"YamlStorage\":\n raise NotImplementedError(\"RepositoryCfg only supports YamlStorage\")\n ret = []\n for location in butlerLocation.getLocations():\n logLoc = LogicalLocation(location, butlerLocation.getAdditionalData())\n with open(logLoc.locString()) as f:\n cfg = yaml.load(f)\n cfg['accessCfg.storageCfg.root'] = os.path.dirname(location)\n ret.append(cfg)\n return ret\n\n @staticmethod\n def butlerWrite(obj, butlerLocation):\n if butlerLocation.getStorageName() is not \"YamlStorage\":\n raise NotImplementedError(\"RepositoryCfg only supports YamlStorage\")\n ret = []\n for location in butlerLocation.getLocations():\n logLoc = LogicalLocation(location, butlerLocation.getAdditionalData())\n if not os.path.exists(os.path.dirname(logLoc.locString())):\n os.makedirs(os.path.dirname(logLoc.locString()))\n with open(logLoc.locString(), 'w') as f:\n yaml.dump(obj, f)\n\nclass Repository(object):\n \"\"\"\n Default Multiple Parent & Output Behaviors.\n * put/write operates only in non-parent repositories.\n * get/read operates only in parent repositories.\n Multiple output support:\n * a Repository can have peer repositories.\n * all outputs (writes) go to all non-parent repositories. (e.g. mapping with write==False will return\n mappings for from all peer Repositories.\n Multiple parent support:\n * parents are processed in priority order, as defined by the order of the tuple passed in as\n cfg['parentCfgs']\n * parent search is depth first (1st parent, parents of 1st parent, grandparents of 1st parent, 2nd parent,\n etc)\n * if parentJoin is 'left' returns after first result is found.\n * if parentJoin is 'outer' will return all results found.\n\n Recursion is implemented in a few functions which may be overridden to alter recursive behavior:\n def doPeersAndParents()\n def doPeers()\n def doParents()\n\n\n \"\"\"\n _supportedParentJoin = ('left', 'outer')\n\n @classmethod\n def cfg(cls, id=None, accessCfg=None, parentCfgs=[], parentJoin='left', peerCfgs=[], mapper=None, mapperArgs=None):\n \"\"\"\n Helper func to create a properly formatted Policy to configure a Repository.\n\n .. warning::\n\n cfg is 'wet paint' and very likely to change. Use of it in production code other than via the 'old\n butler' API is strongly discouraged.\n\n\n :param id: an identifier for this repository. Currently only used for debugging.\n :param accessCfg: cfg for the Access class\n :param parentCfgs: a tuple of repo cfgs of parent repositories, in search-priority order.\n :param parentJoin: behavior specifier for searching parents. must be one of _supportedParentJoin.\n :param peerCfgs: tuple of repo cfgs of peer repositories.\n :param mapper: mapper to use with this repo. May be a fully-qualified name\n (e.g. lsst.daf.butlerUtils.CameraMapper) to be instantiated, a class instance, or a\n class type to be instantiated.\n :param mapperArgs: a dict of arguments to pass to the Mapper if it is to be instantiated.\n :return: a properly populated cfg Policy.\n \"\"\"\n if parentJoin not in Repository._supportedParentJoin:\n raise RuntimeError('Repository.cfg parentJoin:%s not supported, must be one of:'\n % (parentJoin, Repository._supportedParentJoin))\n return RepositoryCfg(cls=cls, id=id, accessCfg=accessCfg, parentCfgs=parentCfgs,\n parentJoin=parentJoin, peerCfgs=peerCfgs, mapper=mapper, mapperArgs=mapperArgs)\n\n @staticmethod\n def makeFromCfg(repoCfg):\n '''Instantiate a Repository from a configuration.\n In come cases the repoCfg may have already been instantiated into a Repository, this is allowed and\n the input var is simply returned.\n\n .. warning::\n\n cfg is 'wet paint' and very likely to change. Use of it in production code other than via the 'old\n butler' API is strongly discouraged.\n\n\n :param repoCfg: the cfg for this repository. It is recommended this be created by calling\n Repository.cfg()\n :return: a Repository instance\n '''\n if isinstance(repoCfg, Policy):\n return repoCfg['cls'](repoCfg)\n return repoCfg\n\n\n def __init__(self, cfg):\n '''Initialize a Repository with parameters input via config.\n\n :param cfg: It is recommended that this config be created by calling Repository.cfg(...) to ensure all\n the required keys are set.\n :return:\n '''\n self.cfg = cfg\n self._access = Access(self.cfg['accessCfg']) if self.cfg['accessCfg'] is not None else None\n self._parentJoin = self.cfg['parentJoin']\n if not self._parentJoin in Repository._supportedParentJoin:\n raise RuntimeError('Repository.__init__ parentJoin:%s not supported, must be one of:'\n % (self._parentJoin, Repository._supportedParentJoin))\n self._parents = []\n parentCfgs = self.cfg['parentCfgs']\n if not hasattr(parentCfgs, '__iter__'):\n parentCfgs = (parentCfgs,)\n for parentCfg in parentCfgs:\n self._parents.append(Repository.makeFromCfg(parentCfg))\n self._peers = []\n for peerCfg in self.cfg['peerCfgs']:\n self._peers.append(Repository.makeFromCfg(peerCfg))\n self._id = self.cfg['id']\n\n self._initMapper(cfg)\n\n def _initMapper(self, repoCfg):\n '''Initialize and keep the mapper in a member var.\n\n :param repoCfg:\n :return:\n '''\n\n # rule: If mapper is:\n # - a policy: instantiate it via the policy\n # - an object: use it as the mapper.\n # - a string: import it and instantiate it with mapperArgs\n # - None: look for the mapper named in 'access' and use that string as in item 2.\n mapper = repoCfg['mapper']\n if mapper is None:\n if self._access is not None:\n mapper = self._access.mapperClass()\n if mapper is None:\n self._mapper = None\n return None\n # if mapper is a cfg (IE an instance of the badly-named Policy class), instantiate via the cfg.\n if isinstance(mapper, Policy):\n # code at this location that knows that the mapper needs to share the repo's access instance is\n # not ideal IMO. Not sure how to rectify in a good way.\n if mapper['access'] is None:\n #mapper = copy.copy(mapper)\n mapper['access'] = self._access\n mapper = Mapper.Mapper(mapper)\n # if mapper is a string, import it:\n if isinstance(mapper, basestring):\n mapper = __import__(mapper)\n # now if mapper is a class type (not instance), instantiate it:\n if inspect.isclass(mapper):\n # cameraMapper requires root which is not ideal. it should be accessing objects via storage.\n # cameraMapper and other existing mappers (hscMapper) will require much refactoring to support this.\n args = inspect.getargspec(mapper.__init__)\n useRootKeyword = not 'cfg' in args.args\n if not useRootKeyword:\n try:\n # try new style init first; pass cfg to mapper\n mapper = mapper(cfg=repoCfg['mapperCfg'])\n except TypeError:\n # try again, using old style cfg: using mapperArgs and root keywords\n useRootKeyword = True\n if useRootKeyword:\n mapperArgs = copy.copy(repoCfg['mapperArgs'])\n if mapperArgs is None:\n mapperArgs = {}\n if 'root' not in mapperArgs:\n mapperArgs['root'] = self._access.root()\n mapper = mapper(**mapperArgs)\n self._mapper = mapper\n\n\n def __repr__(self):\n return 'config(id=%s, accessCfg=%s, parent=%s, mapper=%s, mapperArgs=%s, cls=%s)' % \\\n (self.id, self.accessCfg, self.parent, self.mapper, self.mapperArgs, self.cls)\n\n @staticmethod\n def loadCfg(accessCfg):\n \"\"\"Load a repository cfg that has been saved in a location specified by accessCfg\n\n .. warning::\n\n cfg is 'wet paint' and very likely to change. Use of it in production code other than via the 'old\n butler' API is strongly discouraged.\n \"\"\"\n access = Access(accessCfg)\n return access.loadCfg()\n\n # todo want a way to make a repository read-only\n def write(self, butlerLocation, obj):\n \"\"\"Write a dataset to Storage.\n\n :param butlerLocation: Contains the details needed to find the desired dataset.\n :param dataset: The dataset to be written.\n :return:\n \"\"\"\n return self._access.write(butlerLocation, obj)\n\n #######################\n ## Recursion support ##\n\n def doSelfAndPeers(self, func, *args, **kwargs):\n \"\"\"Performs a function on self and each repository in _peers\n\n :param func: The fucntion to be performed\n :param args: args for the function\n :param kwargs: kwargs for the function\n :return: a list of return values from peers where the func did not return None.\n if the func returned None from all peers, then returns None.\n \"\"\"\n ret = []\n res = func(self, *args, **kwargs)\n if res is not None:\n # if res is a list, extend ret. else append ret:\n try:\n ret.extend(res)\n except TypeError:\n ret.append(res)\n for child in self._peers:\n res = func(child, *args, **kwargs)\n if res is not None:\n try:\n ret.extend(res)\n except TypeError:\n ret.append(res)\n if len(ret) is 0:\n ret = None\n return ret\n\n def doParents(self, func, *args, **kwargs):\n \"\"\"Performas a depth-first search on parents.\n\n For each parent:\n performs func.\n if results are none:\n performs func on parent.\n if results are not none and join is 'left':\n returns result\n else\n appends result to list of results\n returns results if the list is not empty, else None\n\n If self._parentJoin is 'left' will return the return value of the first func that does not return\n None. If self._parentJoin is 'outer' will return a list of all the results of first-level parents\n (i.e. not grandparents) from func that are not None.\n\n :param func: a function to perform parents\n :param args: args for the function\n :param kwargs: kwargs for the function\n :return: if only 1 parent is to be used: the element to return: the element.\n if many parents used: a list of results; one element from each parent.\n if all the parents returned None, then None.\n \"\"\"\n ret = []\n for parent in self._parents:\n res = func(parent, *args, **kwargs)\n if res is None:\n res = parent.doParents(func, *args, **kwargs)\n if res is not None:\n if self._parentJoin is 'left':\n return res\n else:\n ret.append(res)\n\n if len(ret) is 0:\n ret = None\n elif len(ret) is 1:\n ret = ret[0]\n return ret\n\n def read(self, butlerLocation):\n \"\"\"Read a dataset from Storage.\n\n :param butlerLocation: Contains the details needed to find the desired dataset.\n :return: An instance of the dataset requested by butlerLocation.\n \"\"\"\n return self._access.read(butlerLocation)\n\n ###################\n ## Mapper Access ##\n\n def mappers(self):\n return (self._mapper, )\n\n def getKeys(self, *args, **kwargs):\n \"\"\"\n Get the keys available in the repository/repositories.\n :param args:\n :param kwargs:\n :return: A dict of {key:valueType} or a list of these dicts, depending on the parentJoin rules.\n \"\"\"\n return self.doParents(Repository.doGetKeys, *args, **kwargs)\n\n def doGetKeys(self, *args, **kwargs):\n \"\"\"Get the keys from this repository only. Typically this function is called only by doParents, and\n other classes should call getKeys.\n\n :param args:\n :param kwargs:\n :return: A dict of {key:valueType}\n \"\"\"\n # todo: getKeys is not in the mapper API\n if self._mapper is None:\n return None\n return self._mapper.getKeys(*args, **kwargs)\n\n def map(self, *args, **kwargs):\n \"\"\"Find a butler location for the given arguments.\n\n If 'write' is in the kwargs and set to True then this is treated as a mapping intended to be used in a\n call to butler.put and will look in the output repositories. Otherwise it's treated as a mapping for\n butler.get and will look in the input repositories.\n\n See mapper documentation for more detials about the use of map.\n :param args: arguments to be passed on to mapper.map\n :param kwargs: keyword arguments to be passed on to mapper.map\n :return: An item or a list, depending on parentJoin rules. The type of item is dependent on the mapper\n being used but is typically a ButlerLocation.\n \"\"\"\n if 'write' in kwargs and kwargs['write'] is True:\n return self.doSelfAndPeers(Repository.doMap, *args, **kwargs)\n else:\n return self.doParents(Repository.doMap, *args, **kwargs)\n\n def doMap(self, *args, **kwargs):\n \"\"\"Perform the map function on this repository only.\n\n See mapper.map for more information about args and kwargs.\n\n :param args: arguments to be passed on to mapper.map\n :param kwargs: keyword arguments to be passed on to mapper.map\n :return: The type of item is dependent on the mapper being used but is typically a ButlerLocation.\n \"\"\"\n if self._mapper is None:\n return None\n loc = self._mapper.map(*args, **kwargs)\n if loc is None:\n return None\n loc.setRepository(self)\n return loc\n\n def queryMetadata(self, *args, **kwargs):\n \"\"\"Gets possible values for keys given a partial data id.\n\n See mapper documentation for more explanation about queryMetadata.\n\n :param args: arguments to be passed on to mapper.map\n :param kwargs: keyword arguments to be passed on to mapper.map\n :return: An item or a list, depending on parentJoin rules. The type of item is dependent on the mapper\n being used but is typically a set that contains available values for the keys in the format iarg.\n \"\"\"\n mdList= self.doParents(Repository.doQueryMetadata, *args, **kwargs)\n return mdList\n\n def doQueryMetadata(self, *args, **kwargs):\n \"\"\"Perform the queryMetadata function on this repository only.\n\n See mapper.queryMetadata for more information about args and kwargs.\n\n :param args: arguments to be passed on to mapper.queryMetadata\n :param kwargs: keyword arguments to be passed on to mapper.queryMetadata\n :return:The type of item is dependent on the mapper being used but is typically a set that contains\n available values for the keys in the format input argument.\n \"\"\"\n if self._mapper is None:\n return None\n ret = self._mapper.queryMetadata(*args, **kwargs)\n return ret\n\n def backup(self, *args, **kwargs):\n \"\"\"Calls mapper.backup on all output repositories.\n\n :param args: arguments to be passed on to mapper.backup\n :param kwargs: keyword arguments to be passed on to mapper.backup\n :return: None\n \"\"\"\n self.doSelfAndPeers(Repository.doBackup, *args, **kwargs)\n\n def doBackup(self, *args, **kwargs):\n \"\"\"Perform mapper.backup on this repository only.\n\n See mapper.backup for more information about args and kwargs.\n\n :param args: arguments to be passed on to mapper.backup\n :param kwargs: keyword arguments to be passed on to mapper.backup\n :return: None\n \"\"\"\n if self._mapper is None:\n return None\n self._mapper.backup(*args, **kwargs)\n\n def getMapperDefaultLevel(self):\n \"\"\"Get the default level for this repository only.\n\n This is typically used if no level is passed into butler methods that call repository.getKeys and/or\n repository.queryMetadata. There is a bug in that code because it gets the default level from this\n repository but then uses that value when searching all repositories. If this and other repositories\n have dissimilar data, the default level value will be nonsensical. A good example of this issue is in\n Butler.subset; it needs refactoring.\n\n :return:\n \"\"\"\n if self._mapper is None:\n return None\n return self._mapper.getDefaultLevel()\n\n\n","sub_path":"python/lsst/daf/persistence/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":19875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"503710183","text":"import numpy as np\nfrom sklearn.preprocessing import OneHotEncoder\n\ndict_encode = [\n {'青年': 0, '中年': 1, '老年': 2},\n {'否': 0, '是': 1},\n {'否': 0, '是': 1},\n {'一般': 0, '好': 1, '非常好': 2},\n {'否': 0, '是': 1}\n]\nX = [\n ['青年', '否', '否', '一般' ],\n ['青年', '否', '否', '好' ],\n ['青年', '是', '否', '好' ],\n ['青年', '是', '是', '一般' ],\n ['青年', '否', '否', '一般' ],\n ['中年', '否', '否', '一般' ],\n ['中年', '否', '否', '好' ],\n ['中年', '是', '是', '好' ],\n ['中年', '否', '是', '非常好'],\n ['中年', '否', '是', '非常好'],\n ['老年', '否', '是', '非常好'],\n ['老年', '否', '是', '好' ],\n ['老年', '是', '否', '好' ],\n ['老年', '是', '否', '非常好'],\n ['老年', '否', '否', '一般'],\n]\ny = ['否', '否', '是', '是', '否', '否', '否', '是', '是', '是', '是', '是', '是', '是', '否']\n\nclass Node():\n \"\"\"\n Attributes:\n index: 子树分类标签, 若为叶节点, 则为None\n childNode: 子树,若为叶节点, 则为分类标签; 否则为字典\n \"\"\"\n def __init__(self):\n self.index = None\n self.childNode = None\n\nclass DecisionTree():\n '''\n @note: \n - categorical features;\n - ID3\n '''\n def __init__(self):\n self.tree = None\n def fit(self, X, y):\n self.tree = self.creatNode(X, y)\n def creatNode(self, X, y):\n node = Node()\n # 若只含一种类别,则返回叶节点\n if len(set(y)) == 1: node.childNode = list(set(y))[0]; return node\n # entropy: H(D)\n y_encoded = OneHotEncoder().fit_transform(y.reshape(-1, 1)).toarray()\n p_y = np.mean(y_encoded, axis=0)\n p_y[p_y==0.0] = 1.0 # 因为 0*np.log(0)结果为nan, 而不是0, 用 1*np.log(1)替代\n H_D = - np.sum(p_y * np.log(p_y))\n # conditional entropy: H(D|A)\n H_D_A = np.zeros(shape=(X.shape[1],)) # initialize\n for i_feature in range(X.shape[1]):\n X_feature = X[:, i_feature]\n if len(set(X_feature)) == 1: \n H_D_A[i_feature] = float('inf'); continue # 若该特征只有一种取值,表示已使用该列作为分类特征\n X_feature_encoded = OneHotEncoder().fit_transform(X_feature.reshape((-1, 1))).toarray()\n p_X = np.mean(X_feature_encoded, axis=0) # 每个取值的概率\n for j_feature in range(X_feature_encoded.shape[1]): # 该特征取值有几种,编码后就有几列\n y_encoded_feature = y_encoded[X_feature_encoded[:, j_feature]==1] # 该特征某种取值下,其对应的标签值\n p_y_X = np.mean(y_encoded_feature, axis=0)\n p_y_X[p_y_X==0.0] = 1.0\n H_D_feature = - np.sum(p_y_X * np.log(p_y_X))\n H_D_A[i_feature] += p_X[j_feature] * H_D_feature # 条件熵\n # information gain: g(D, A) = H(D) - H(D|A)\n g_D_A = H_D - H_D_A\n # 选出最大的作为分类特征\n node.index = np.argmax(g_D_A)\n X_selected = X[:, node.index]\n # 分类后继续建立树\n node.childNode = dict()\n for val in set(X_selected):\n valIndex = (X_selected==val)\n X_val, y_val = X[valIndex], y[valIndex]\n node.childNode[val] = self.creatNode(X_val, y_val) # 存储在字典中,键为分类值,值为子树\n return node\n def predict(self, X):\n y_pred = np.zeros(shape=(X.shape[0],))\n for i_sample in range(X.shape[0]):\n currentNode = self.tree # 初始化为父节点\n while not currentNode.index==None: # 若为None, 表示为叶子结点\n val = X[i_sample, currentNode.index] # 当前样本在分类特征上的值\n currentNode = currentNode.childNode[val] # 递归\n else:\n y_pred[i_sample] = currentNode.childNode\n return y_pred\n def score(self, y_true, y_pred):\n ''' accuracy '''\n return np.mean(np.equal(y_true, y_pred).astype('float'))\n\nif __name__ == '__main__':\n X = np.array(X); y = np.array(y)\n # encode the data\n for c in range(X.shape[1]):\n for r in range(X.shape[0]):\n X[r, c] = dict_encode[c][X[r, c]]\n X = X.astype('int') # (15, 4)\n # encode the label\n for r in range(y.shape[0]):\n y[r] = dict_encode[4][y[r]]\n y = y.astype('int') # (15, )\n\n # train the estimator\n estimator = DecisionTree()\n estimator.fit(X, y)\n # predict the output of training data, calculate the accuracy score\n y_pred = estimator.predict(X)\n print(estimator.score(y, y_pred))","sub_path":"Algorithms/p110_decision_tree.py","file_name":"p110_decision_tree.py","file_ext":"py","file_size_in_byte":4896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"356933670","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 12 06:34:02 2019\n\n@author: minto\n\"\"\"\n\nfrom selenium import webdriver\nimport os\nimport time\n\nchrome_options = webdriver.ChromeOptions()\nprefs = {\"download.default_directory\": os.getcwd()}\nchrome_options.add_experimental_option(\"prefs\", prefs)\n\nBrowser = webdriver.Chrome(chrome_options=chrome_options)\nBrowser.get('https://querycourse.ntust.edu.tw/querycourse')\ncheck = Browser.find_element_by_xpath('//*[@id=\"main\"]/div/div/div[1]/div[2]/div/div[1]/div/div[5]/div/div/div[1]/div/div')\nif not check.is_selected():\n check.click()\nBrowser.find_element_by_xpath('//*[@id=\"main\"]/div/div/div[1]/div[2]/div/div[1]/div/div[8]/button').click()\ntime.sleep(1)\nBrowser.find_element_by_xpath('//*[@id=\"main\"]/div/div/div[3]/div/button').click()\nBrowser.close()","sub_path":"測試用/下載測試.py","file_name":"下載測試.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"454452375","text":"num1 = int(input(\"Inserta un número: \"))\r\nnum2 = int(input(\"Pon otro número: \"))\r\n\r\nif num1%2==0 and num2%2==0:\r\n print(\"Todos son pares.\")\r\nelif num1%2==0 and num2%2!=0:\r\n print(f\"{num1} es par. {num2} es impar\")\r\nelif num1%2!=0 and num2%2==0:\r\n print(f\"{num1} es impar. {num2} es par.\") \r\nelse:\r\n print(\"Todos son impares.\") ","sub_path":"impar_par.py","file_name":"impar_par.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"168745280","text":"class Menu:\n def __init__(self, n, p):\n self.name = n\n self.price = p\n\nclass Kiosk:\n\n def __init__(self, mlist):\n self.menu_list = mlist\n self.order_list = []\n\n def start_service(self):\n print(\"WELCOME.....\")\n num = 1\n print(\"----------------------------\")\n for menu in self.menu_list:\n print(num, menu.name, menu.price)\n num+=1\n print(\"----------------------------\")\n choice = int(input('메뉴번호를 선택하세요, 0을 누르면 완료\\n'))\n\n if choice == 0:\n return\n\n self.order_list.append(self.menu_list[choice -1])\n self.start_service()\n\n def print_bill(self):\n total = 0\n print(\"----------------------\")\n for order_menu in self.order_list:\n print(order_menu.name, order_menu.price)\n total+= order_menu.price\n print(\"----------------------\")\n print(\"TOTAL: \" , total)\n print(\"----------------------\")\n\nclass MainKiosk:\n\n def __init__(self,dic):\n self.kiosks = dic\n\n\n def service(self):\n print(self.kiosks)\n idx = int(input(\"0 or 1\"))\n kiosk = self.kiosks[idx]\n kiosk.start_service()\n kiosk.print_bill()\n\n\n\nkiosk1 = Kiosk([\n Menu('김밥',3000),\n Menu('라면', 4000),\n Menu('떡볶이', 4300),\n Menu('쫄면', 5000),])\n\nkiosk2 = Kiosk([\n Menu('봉골레',12000),\n Menu('까르보나라', 10000),\n Menu('알리올리오', 11000),\n Menu('크림치즈파스타', 13000),])\n\nmainKiosk = MainKiosk([kiosk1,kiosk2])\nmainKiosk.service()\n\n\n","sub_path":"oop3.py","file_name":"oop3.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"555600967","text":"import requests, time\r\nfrom bs4 import BeautifulSoup \r\n\r\nprint(\" === RETRAITE LABRUTE === \")\r\n\r\n########################################################################\r\nsid = \"\"\r\nnb_retraite=2\r\n########################################################################\r\n\r\ncookie = {\"sid\": sid}\r\n\r\nurl = \"http://labrute.muxxu.com/team\"\r\nrep_finale = requests.get(url, cookies=cookie)\r\nsoup2 = BeautifulSoup(rep_finale.text, 'html.parser')\r\nbrutes = []\r\nfor a in soup2.find_all(\"a\", {\"class\": \"button2\"}, href=True) :\r\n\tbrutes.append(a['href'])\r\n\r\ni = 1\r\nwhile i <= nb_retraite :\r\n\turl1 = \"http://labrute.muxxu.com\"+brutes[-i]\r\n\trep1 = requests.get(url1, cookies=cookie)\r\n\tsoup1 = BeautifulSoup(rep1.text, 'html.parser')\r\n\tchk = str(soup1.find_all(\"script\")).split(\"&k=\")[1][0:8]\r\n\turl2 = \"http://labrute.muxxu.com/old?retreat=\"+brutes[-i][3:]+\";chk=\"+chk\r\n\trequests.get(url2, cookies=cookie)\r\n\tprint(\"ok \"+str(i))\r\n\ti+=1\t\r\n","sub_path":"retraite.py","file_name":"retraite.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"189189819","text":"from functools import *\n\nclass SetOperations:\n def intersect(*ar):\n return reduce(__intersectSC, ar)\n\n\n def __intersectSC(listX, listY):\n setList = []\n for x in listX:\n if x in listY:\n setList.append(x)\n return setList\n\n def union(*ar):\n return reduce(__unionSC, ar)\n\n def __unionSC(listX, listY):\n setList = listX[:]\n for y in listY:\n if y not in setList:\n setList.append(y)\n return setList\n\n def difference(*ar):\n setList = []\n intersectSet = intersect(*ar)\n unionSet = union(*ar)\n for x in unionSet:\n if not x in intersectSet:\n setList.append(x)\n return setList","sub_path":"builtins/module/set/setmodule.py","file_name":"setmodule.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"366222136","text":"# Copyright 2022 Huawei Technologies Co., Ltd.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Copyright (c) OpenMMLab. All rights reserved.\nfrom ..builder import DETECTORS\nfrom .panoptic_two_stage_segmentor import TwoStagePanopticSegmentor\n\n\n@DETECTORS.register_module()\nclass PanopticFPN(TwoStagePanopticSegmentor):\n r\"\"\"Implementation of `Panoptic feature pyramid\n networks `_\"\"\"\n\n def __init__(\n self,\n backbone,\n neck=None,\n rpn_head=None,\n roi_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None,\n init_cfg=None,\n # for panoptic segmentation\n semantic_head=None,\n panoptic_fusion_head=None):\n super(PanopticFPN, self).__init__(\n backbone=backbone,\n neck=neck,\n rpn_head=rpn_head,\n roi_head=roi_head,\n train_cfg=train_cfg,\n test_cfg=test_cfg,\n pretrained=pretrained,\n init_cfg=init_cfg,\n semantic_head=semantic_head,\n panoptic_fusion_head=panoptic_fusion_head)\n","sub_path":"PyTorch/built-in/cv/detection/SSD_for_PyTorch/mmdet/models/detectors/panoptic_fpn.py","file_name":"panoptic_fpn.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"65955461","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n'''\nCopyright (c) 2014 trgk\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n'''\n\nfrom ... import core as c\nfrom ... import ctrlstru as cs\n\nfrom . import (\n dwepdio as dwm,\n modcurpl as cp,\n)\n\n\nclass EUDByteStream:\n \"\"\"Read and Write byte by byte.\"\"\"\n\n def __init__(self):\n self._suboffset = c.EUDVariable()\n self._offset = c.EUDVariable()\n\n # -------\n\n @c.EUDMethod\n def seekepd(self, epdoffset):\n \"\"\"Seek EUDByteStream to specific epd player address\"\"\"\n c.SeqCompute([\n (self._offset, c.SetTo, epdoffset),\n (self._suboffset, c.SetTo, 0)\n ])\n\n @c.EUDMethod\n def seekoffset(self, offset):\n \"\"\"Seek EUDByteStream to specific address\"\"\"\n # convert offset to epd offset & suboffset\n c.SetVariables([self._offset, self._suboffset], c.f_div(offset, 4))\n c.SeqCompute([(self._offset, c.Add, -0x58A364 // 4)])\n\n # -------\n\n @c.EUDMethod\n def readbyte(self):\n \"\"\"Read byte from current address. ByteStream will advance by 1 bytes.\n\n :returns: Read byte\n \"\"\"\n orig = cp.f_getcurpl()\n case = [c.Forward() for _ in range(5)]\n ret = c.EUDVariable()\n\n cs.DoActions([\n ret.SetNumber(0),\n c.SetCurrentPlayer(self._offset)\n ])\n\n for i in range(3):\n case[i] << c.NextTrigger()\n cs.EUDJumpIfNot(self._suboffset.Exactly(i), case[i + 1])\n for j in range(7, -1, -1):\n c.RawTrigger(\n conditions=[\n c.DeathsX(c.CurrentPlayer, c.AtLeast, 1, 0, 2**(j + 8 * i))\n ],\n actions=ret.AddNumber(2**j)\n )\n c.SeqCompute([\n (self._suboffset, c.Add, 1)\n ])\n cs.EUDJump(case[-1])\n\n # suboffset == 3\n case[3] << c.NextTrigger()\n\n for i in range(7, -1, -1):\n c.RawTrigger(\n conditions=[\n c.DeathsX(c.CurrentPlayer, c.AtLeast, 1, 0, 2**(i + 24))\n ],\n actions=ret.AddNumber(2**i)\n )\n c.SeqCompute([\n (self._offset, c.Add, 1),\n (self._suboffset, c.SetTo, 0)\n ])\n\n case[-1] << c.NextTrigger()\n cp.f_setcurpl(orig)\n return ret\n\n @c.EUDMethod\n def writebyte(self, byte):\n \"\"\"Write byte to current position.\n\n Write a byte to current position of EUDByteStream.\n ByteStream will advance by 1 byte.\n \"\"\"\n _dw = c.Forward()\n\n cs.EUDSwitch(self._suboffset)\n if cs.EUDSwitchCase()(0):\n cs.DoActions([\n c.SetMemoryXEPD(self._offset, c.SetTo, byte, 255),\n self._suboffset.AddNumber(1)\n ])\n c.EUDReturn()\n\n for i in range(1, 4):\n if cs.EUDSwitchCase()(i):\n cs.DoActions([\n c.SetMemory(_dw, c.SetTo, 255 * 256**i),\n c.SetMemory(_dw + 20, c.SetTo, 0),\n [self._suboffset.AddNumber(1) if i < 3 else self._suboffset.SetNumber(0)],\n ])\n for j in range(7, -1, -1):\n c.RawTrigger(\n conditions=[\n byte.AtLeastX(1, 2**j)\n ],\n actions=[\n c.SetMemory(_dw + 20, c.Add, 2 ** (j + i * 8))\n ]\n )\n cs.EUDBreak()\n\n cs.EUDEndSwitch()\n\n cs.DoActions([_dw << c.SetMemoryXEPD(self._offset, c.SetTo, 0, 0xFF00)])\n c.RawTrigger(\n conditions=self._suboffset.Exactly(0),\n actions=self._offset.AddNumber(1)\n )\n\n @classmethod\n def flushdword(cls):\n pass\n\n\nEUDByteReader, EUDByteWriter = EUDByteStream, EUDByteStream\n","sub_path":"eudplib/eudlib/memiof/byterw.py","file_name":"byterw.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"408995509","text":"import asyncio\n\n\nasync def compute(x, y):\n print(str.format(\n '[~] {} + {} ... (compute)', x, y\n ))\n\n # приостанавливаем выполнение курутины на 5 сек\n await asyncio.sleep(5)\n\n # возвращаем вычисленное значение из объекта курутины; результат может быть\n # присвоен переменной в вызываемом коде при помощи выражения:\n # result = await compute(10, 20)\n return x + y\n\n\nasync def show_sum(x, y, n):\n print('[~] Before await compute()')\n\n # выполнение курутины может быть отложено событийным циклом\n result = await compute(x, y)\n\n print('[~] After await compute()')\n\n # приостанавливаем выполнение курутины на n секунды\n print(str.format(\n '[~] Suspend processing coroutine on {} sec', n\n ))\n await asyncio.sleep(n)\n\n print(str.format(\n '[~] Resume coroutine after {} sec pause', n\n ))\n\n print(str.format(\n '[~] {} + {} = {}',\n x, y, result\n ))\n\n\ndef main():\n loop = asyncio.get_event_loop()\n\n try:\n loop.run_until_complete(show_sum(10, 20, 3))\n except KeyboardInterrupt:\n print('[*] Pressed Ctrl + C')\n finally:\n loop.close()\n print('[x] Event loop is closed')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"spl/asyncio_module/asyncio_docs/tasks_and_coroutines/app3.py","file_name":"app3.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"111912153","text":"from elasticsearch import Elasticsearch\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport sys\n\n\nes = Elasticsearch(['http://localhost'])\n\nurl = 'https://www.contabeis.com.br'\n\nbody = requests.get(\"{}/conteudo\".format(url))\nsoup = BeautifulSoup(body.content, features=\"lxml\")\n\nfor article in soup.find_all('article'):\n link = article.find('a', href=True)\n if link:\n contents = requests.get(\"{}/{}\".format(url, link['href']))\n\n if contents.status_code != 200:\n continue\n\n page = BeautifulSoup(contents.content, features=\"lxml\")\n section = page.find('section')\n categoria = section.find(\"p\", attrs={\"class\": 'chapeu'})\n titulo = section.find(\"h1\")\n conteudo = section.find('div', attrs={'itemprop': \"articleBody\"})\n\n data = {\n 'categoria': categoria.text if categoria else None,\n 'titulo': titulo.text if titulo else None,\n 'conteudo': conteudo.text if conteudo else None,\n 'pagina': \"{}/{}\".format(url, link['href']),\n 'importacao': time.strftime('%Y-%m-%d %H:%M:%S'),\n }\n\n res = es.index(index='teste', body=data)\n _id = None\n if '_id' in res:\n _id = res['_id']\n print(_id)\n\n # sys.exit(1)","sub_path":"api/teste/popular.py","file_name":"popular.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"483790353","text":"#!/usr/bin/env python\n#\n\nimport datetime\nimport unittest\nimport os\nimport sys\nfrom AxisMr import AxisMr\nfrom AxisCom import AxisCom\n\nfilnam = \"131xx.py\"\n###\n\n\nclass Test(unittest.TestCase):\n url_string = os.getenv(\"TESTEDMOTORAXIS\")\n print(\n f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} url_string={url_string}\"\n )\n\n axisCom = AxisCom(url_string, log_debug=True)\n axisMr = AxisMr(axisCom)\n\n # self.axisCom.put('-DbgStrToLOG', \"Start \" + os.path.basename(__file__)[0:20])\n\n saved_DLY = axisCom.get(\".DLY\")\n hlm = axisCom.get(\".HLM\")\n llm = axisCom.get(\".LLM\")\n jvel = axisCom.get(\".JVEL\")\n\n margin = 1.1\n # motorRecord stops jogging 1 second before reaching HLM\n jog_start_pos = llm + jvel + margin\n\n msta = int(axisCom.get(\".MSTA\"))\n\n print(\n f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} llm={llm:f} hlm={hlm:f} jog_start_pos={jog_start_pos:f}\"\n )\n\n # Make sure that motor is homed\n def test_TC_1311(self):\n tc_no = \"1311\"\n if not (self.msta & self.axisMr.MSTA_BIT_HOMED):\n self.axisMr.powerOnHomeAxis(tc_no)\n self.msta = int(self.axisCom.get(\".MSTA\"))\n self.assertNotEqual(\n 0,\n self.msta & self.axisMr.MSTA_BIT_HOMED,\n \"MSTA.homed (Axis is not homed)\",\n )\n\n # per10 UserPosition\n def test_TC_1312(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1312\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisMr.moveWait(tc_no, self.jog_start_pos)\n UserPosition = self.axisCom.get(\".RBV\", use_monitor=False)\n print(\n \"%s postion=%f jog_start_pos=%f\"\n % (tc_no, UserPosition, self.jog_start_pos)\n )\n\n # Low soft limit JOGR\n def test_TC_1313(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1313\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisCom.put(\".DLY\", 1.0)\n self.axisMr.jogDirection(tc_no, 0)\n lvio = int(self.axisCom.get(\".LVIO\"))\n msta = int(self.axisCom.get(\".MSTA\"))\n miss = int(self.axisCom.get(\".MISS\"))\n\n self.axisCom.put(\".DLY\", self.saved_DLY)\n self.axisMr.waitForMipZero(tc_no, self.saved_DLY)\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_PROBLEM,\n \"DLY JOGF should not give MSTA.Problem\",\n )\n self.assertEqual(\n 0, msta & self.axisMr.MSTA_BIT_MINUS_LS, \"DLY JOGF should not reach LLS\"\n )\n self.assertEqual(\n 0, msta & self.axisMr.MSTA_BIT_PLUS_LS, \"DLY JOGF should not reach HLS\"\n )\n self.assertEqual(0, miss, \"DLY JOGF should not have MISS set\")\n self.assertEqual(1, lvio, \"DLY JOGF should have LVIO set\")\n\n # per10 UserPosition\n def test_TC_1314(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1314\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisMr.moveWait(tc_no, self.jog_start_pos)\n UserPosition = self.axisCom.get(\".RBV\", use_monitor=False)\n print(\n \"%s postion=%f jog_start_pos=%f\"\n % (tc_no, UserPosition, self.jog_start_pos)\n )\n\n def test_TC_1315(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1315\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisCom.put(\".DLY\", 0.0)\n self.axisMr.jogDirection(tc_no, 0)\n lvio = int(self.axisCom.get(\".LVIO\"))\n msta = int(self.axisCom.get(\".MSTA\"))\n miss = int(self.axisCom.get(\".MISS\"))\n\n self.axisCom.put(\".DLY\", self.saved_DLY)\n self.axisCom.put(\".JOGF\", 0)\n self.axisMr.waitForMipZero(tc_no, self.saved_DLY)\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_PROBLEM,\n \"ndly JOGF should not give MSTA.Problem\",\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_MINUS_LS,\n \"ndly JOGF should not reach LLS\",\n )\n self.assertEqual(\n 0, msta & self.axisMr.MSTA_BIT_PLUS_LS, \"ndly JOGF should not reach HLS\"\n )\n self.assertEqual(0, miss, \"ndly JOGF should not have MISS set\")\n self.assertEqual(1, lvio, \"ndly JOGF should have LVIO set\")\n\n # Low soft limit JOGR\n def test_TC_1316(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1316\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisCom.put(\".DLY\", 0.0)\n mip1 = int(self.axisCom.get(\".MIP\"))\n\n lvio = int(self.axisCom.get(\".LVIO\"))\n msta = int(self.axisCom.get(\".MSTA\"))\n miss = int(self.axisCom.get(\".MISS\"))\n self.axisMr.waitForMipZero(tc_no, self.saved_DLY)\n mip2 = int(self.axisCom.get(\".MIP\"))\n jogr = int(self.axisCom.get(\".JOGR\"))\n\n self.axisCom.put(\".DLY\", self.saved_DLY)\n print(\n f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no} mip1={mip1:x} mip2={mip2:x}\"\n )\n\n self.assertEqual(\n 0, msta & self.axisMr.MSTA_BIT_PROBLEM, \"ndly2 No MSTA.Problem JOGF\"\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_MINUS_LS,\n \"ndly2 Minus hard limit not reached JOGF\",\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_PLUS_LS,\n \"ndly2 Plus hard limit not reached JOGF\",\n )\n self.assertEqual(0, miss, \"ndly2 MISS not set JOGF\")\n self.assertEqual(0, mip1, \"ndly2 MIP1 not set JOGF\")\n self.assertEqual(\n 0, mip2 & self.axisMr.MIP_BIT_JOGF, \"ndly2 MIP2.JOGF not set JOGF\"\n )\n self.assertEqual(0, jogr, \"ndly2 MIP1 not set JOGR\")\n self.assertEqual(1, lvio, \"ndly2 should have LVIO set\")\n\n # per10 UserPosition\n def test_TC_1317(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1317\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n UserPosition = self.axisCom.get(\".RBV\", use_monitor=False)\n print(\n \"%s postion=%f jog_start_pos=%f\"\n % (tc_no, UserPosition, self.jog_start_pos)\n )\n\n # Low soft limit JOGF + DIR\n def test_TC_1318(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1318\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n saved_DIR = self.axisCom.get(\".DIR\")\n saved_FOFF = self.axisCom.get(\".FOFF\")\n self.axisCom.put(\".FOFF\", 1)\n self.axisCom.put(\".DIR\", 1)\n self.axisMr.jogDirection(tc_no, 1)\n\n lvio = int(self.axisCom.get(\".LVIO\"))\n msta = int(self.axisCom.get(\".MSTA\"))\n\n self.axisCom.put(\".DIR\", saved_DIR)\n self.axisCom.put(\".FOFF\", saved_FOFF)\n\n self.assertEqual(\n 0, msta & self.axisMr.MSTA_BIT_PROBLEM, \"No Error MSTA.Problem JOGF DIR\"\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_MINUS_LS,\n \"Minus hard limit not reached JOGF DIR\",\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_PLUS_LS,\n \"Plus hard limit not reached JOGR DIR\",\n )\n","sub_path":"test/pytests36/131_Record-JOGR_DIR_DLY_LLM.py","file_name":"131_Record-JOGR_DIR_DLY_LLM.py","file_ext":"py","file_size_in_byte":7930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"56753279","text":"from reader import Reader\n\n\n\n# creates an object of the reader class\n# based upon given input values\nx = Reader('input.txt')\n\n# creates an empty matrix based on inputted values\nx.instantiate()\n\n# places the animals in spots specified by the input file\nx.placements()\n\n# updates board after the placement of animals have been assigned\nx.update_board()\n\n\n# updates the board continuously based on the number of moves inputted from the data file\nx.roam_and_kill()\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"212639789","text":"# -*- encoding: utf-8 -*-\nimport sys\nimport os\nimport csv\nimport re\n\n#入力ファイル\nfnme = sys.argv[1]\n#出力ファイル名\nonme = sys.argv[2]\n#単語整形用の削除文字列パターン:()部分を削除(例:生放送主)\nrmvptn = re.compile(r'(\\(|().+(\\)|))$')\nwith open(onme,'w') as wtfh:\n wt = csv.writer(wtfh)\n with open(fnme,\"r\") as rdfh:\n rd = csv.reader(rdfh)\n for row in rd:\n wrd = rmvptn.sub('',row[1])\n if(0 < len(wrd)):\n wrow=[wrd,\"0\",\"0\",int(max(-32768.0,(6000-200*(len(wrd)**1.3)))),\"名詞\",\"一般\",\"*\",\"*\",\"*\",\"*\",wrd,row[2],row[2],\"ニコニコ大百科\"]\n wt.writerow(wrow)\n","sub_path":"NDMEC.py","file_name":"NDMEC.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"320951225","text":"#!/usr/bin/env python\nfrom pynput import keyboard\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom plato_api.constants import max_speed, wheel_distance\nfrom publish_cmd_vel import CommandPublisher\nimport sys\n\n\ndef check(key):\n global lis\n values = [0, 0, 0, 0, 0, 0, 0, 0]\n try:\n k = key.char # single-char keys\n except:\n k = key.name # other keys\n if key == keyboard.Key.esc or k == 'n':\n lis.stop()\n sys.exit()\n print('Key pressed: ' + k)\n if (k == 'w') or (k == 'up'):\n values[0] = 1\n if (k == 's') or (k == 'down'):\n values[1] = 1\n if (k == 'a') or (k == 'left'):\n values[2] = 1\n if (k == 'd') or (k == 'right'):\n values[3] = 1\n if k == 'e':\n values[4] = 1\n if k == 'q':\n values[5] = 1\n if k == 'x':\n values[6] = 1\n if k == 'z':\n values[7] = 1\n return values\n\n\ndef on_release(key):\n global buttons_pressed\n buttons_released = [0, 0, 0, 0, 0, 0, 0, 0]\n if type(key) == list:\n print('It\\'s a list released!')\n for k_ in key:\n values = check(k_)\n buttons_released = [x + y for x,\n y in zip(buttons_released, values)]\n else:\n buttons_released = check(key)\n\n buttons_pressed = [0 if buttons_released[i] else buttons_pressed[i]\n for i in range(len(buttons_pressed))]\n\n\ndef on_press(key):\n global buttons_pressed\n buttons_pressed_curr = [0, 0, 0, 0, 0, 0, 0, 0]\n if type(key) == list:\n print('It\\'s a list pressed!')\n for k_ in key:\n values = check(k_)\n buttons_pressed_curr = [x + y for x,\n y in zip(buttons_pressed_curr, values)]\n else:\n buttons_pressed_curr = check(key)\n buttons_pressed = [1 if buttons_pressed_curr[i] else buttons_pressed[i]\n for i in range(len(buttons_pressed))]\n\n\ndef start():\n global pub, command_publisher, buttons_pressed, lis\n lis.start()\n while not rospy.is_shutdown():\n command_publisher.gas = buttons_pressed[0]\n command_publisher.reverse = buttons_pressed[1]\n command_publisher.left = buttons_pressed[2]\n command_publisher.right = buttons_pressed[3]\n command_publisher.increase_speed = buttons_pressed[4]\n command_publisher.decrease_speed = buttons_pressed[5]\n command_publisher.increase_angle_speed = buttons_pressed[6]\n command_publisher.decrease_angle_speed = buttons_pressed[7]\n command_publisher.publish_command()\n # lis.join()\n\n\npub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\nbuttons_pressed = [0, 0, 0, 0, 0, 0, 0, 0]\nrospy.init_node('teleop_twist_keyboard')\ncommand_publisher = CommandPublisher(\n pub, wheel_distance, max_speed=max_speed)\nlis = keyboard.Listener(on_press=on_press, on_release=on_release)\nstart()\n","sub_path":"plato_control/src/control_keyboard.py","file_name":"control_keyboard.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"362246896","text":"from django.contrib import messages\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse\n\nfrom ogrenci_dersleri.models import ogrenci_dersleri\nfrom .models import Devamsizlik, tarih_hesapla, saat_hesapla\n\n\ndef devamsizlik_listele(request):\n pass\n\n\ndef devamsizlik_excel(request):\n pass\n\n\ndef devamsizlik_sil(request, Id_devamsizlik):\n # if not request.user.is_authenticated or not request.user.is_admin:\n # messages.success(request, 'Bu sayfayı görüntülemek için izniniz yok!')\n # return redirect('user:login')\n devamsizlik = get_object_or_404(Devamsizlik, Id_devamsizlik=Id_devamsizlik)\n Id_ders = str(devamsizlik.ogrenci.ders.Id_ders)\n devamsizlik.delete()\n messages.success(request, 'Kayıt Silindi.')\n return reverse('devamsizlik:duzenle', kwargs={'Id_ders': Id_ders})\n\n\ndef duzenle(request, Id_ders):\n devamlizliklar_obj = Devamsizlik.objects.filter(ogrenci__ders__Id_ders=Id_ders, devamsizlik_tarihi=tarih_hesapla())\n context = {'devamsizliklar': devamlizliklar_obj, 'Id_ders': Id_ders}\n return render(request, 'devamsizlik/duzenle.html', context)\n\n\ndef dersi_alanlar(request, Id_ders):\n ogrenci_dersleri_obj = ogrenci_dersleri.objects.filter(ders__Id_ders=Id_ders) # Dersi alan öğrenciler bulunur.\n if request.POST:\n for ogrenci_ders_obj in ogrenci_dersleri_obj:\n id_dersogrenci = request.POST.get(\n ogrenci_ders_obj.ogrenci.ad_soyad) # Öğrenci Adını Gönderiyor Value Değerini alıyor.\n\n if id_dersogrenci is not None: # id değeri null değilse\n dersogrenci_obj = get_object_or_404(ogrenci_dersleri, Id_dersogrenci=id_dersogrenci)\n\n if devamsizlik_Saat_kontrol(dersogrenci_obj):\n devamsizlik = Devamsizlik()\n devamsizlik.ogrenci = dersogrenci_obj\n devamsizlik.save()\n messages.success(request, 'Kayıt Başarılı!')\n\n context = {'dersogrenci': ogrenci_dersleri_obj}\n return render(request, 'devamsizlik/dersi_alanlar.html', context=context)\n\n\ndef devamsizlik_Saat_kontrol(dersogrenci_obj):\n devamsizlik_var_mi = Devamsizlik.objects.filter(ogrenci=dersogrenci_obj,\n devamsizlik_tarihi=tarih_hesapla(), saat=saat_hesapla())\n if devamsizlik_var_mi:\n return False\n else:\n return True\n","sub_path":"devamsizlik/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"571374556","text":"#-*- coding:utf-8 -*-\n''' \n#文件名:\n#作者:陈圆圆\n#创建日期:2017/7/18\n#模块描述:资源账号管理\n#历史修改记录\n#修改人:\n#修改日期:\n#修改内容:\n'''\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nsys.path.append(\"/testIsomp/common\")\nfrom _icommon import commonFun,frameElement\nfrom _log import log\nsys.path.append(\"/testIsomp/testCase/role/\")\nfrom test_role import testRole\nsys.path.append(\"/testIsomp/webElement/role/\")\nfrom test_roledf import Role\nsys.path.append(\"/testIsomp/webElement/resource/\")\nfrom test_resource_accountmgr_ment import Accountmgr\nfrom test_linux_ment import LinuxResource\nsys.path.append(\"/testIsomp/testData/\")\nfrom _testDataPath import dataFileName\n\nclass testResourceAccount(object):\n\n\tdef __init__(self, driver):\n\t\tself.driver = driver\n\t\tself.log = log()\n\t\tself.cmf = commonFun(driver)\n\t\tself.frameElem = frameElement(driver)\n\t\tself.testrole = testRole(driver)\n\t\tself.linux = LinuxResource(driver)\n\t\tself.account = Accountmgr(driver)\n\t\tself.role = Role(driver)\n\t\tself.data = dataFileName()\n\n\tu'''添加和编辑资源账号'''\n\tdef add_edit_resource_account_001(self, dataPath, sheetName):\n\n\t\t#日志开始记录\n\t\tself.log.log_start(\"add_edit_resource_account\")\n\t\t#获取添加资源账号测试数据\n\t\taccountData = self.data.get_data(dataPath, sheetName)\n\t\t#保存成功的弹出框\n\t\taccountMsg = self.testrole.popup()\n\n\t\t#无检查点的测试项标识,如果为True说明通过\n\t\tflag = False\n\n\t\tfor dataRow in range(len(accountData)):\n\t\t\tdata = accountData[dataRow]\n\t\t\ttry:\n\t\t\t\t#如果不是第一行标题,则读取数据\n\t\t\t\tif dataRow != 0:\n\t\t\t\t\t#点击账号管理\n\t\t\t\t\tif dataRow == 1:\n\t\t\t\t\t\tself.account.click_account_manage_button(data[2])\n\t\t\t\t\tself.linux.add_edit_resource_account(data[3], data[4], data[5], data[6], data[7])\n\t\t\t\t\tself.frameElem.switch_to_content()\n\t\t\t\t\tself.cmf.test_win_check_point(\"xpath\", accountMsg, data, flag)\n\t\t\t\t\tself.cmf.back()\n\t\t\texcept Exception as e:\n\t\t\t\tprint (\"add_edit_resource_account fail:\" + str(e))\n\t\tself.cmf.back()\n\n\t\tself.log.log_end(\"add_edit_resource_account\")\n\n\tu'''查询资源账号'''\n\tdef query_resource_account_002(self, dataPath, sheetName):\n\n\t\t#日志开始记录\n\t\tself.log.log_start(\"query_resource_account\")\n\t\t#获取查询资源账号测试数据\n\t\taccountData = self.data.get_data(dataPath, sheetName)\n\n\t\tfor dataRow in range(len(accountData)):\n\t\t\tdata = accountData[dataRow]\n\t\t\ttry:\n\t\t\t\t#如果不是第一行标题,则读取数据\n\t\t\t\tif dataRow != 0:\n\t\t\t\t\tif dataRow == 1:\n\t\t\t\t\t\tself.account.click_account_manage_button(data[1])\n\t\t\t\t\t\tself.account.query_name(data[2])\n\t\t\t\t\tif dataRow == 2 or dataRow == 3:\n\t\t\t\t\t\tself.account.is_authorize(data[3])\n\t\t\t\t\tif dataRow == 4:\n\t\t\t\t\t\tself.account.query_name(data[2])\n\t\t\t\t\t\tself.account.is_authorize(data[3])\n\t\t\t\t\tself.account.click_account_query()\n\t\t\t\t\tself.role.click_reset()\n\t\t\t\t\tself.log.log_detail(data[0], True)\n\t\t\texcept Exception as e:\n\t\t\t\tprint (\"query_resource_account fail:\" + str(e))\n\t\tself.cmf.back()\n\n\t\tself.log.log_end(\"query_resource_account\")\n\n\tu'''检验资源账号'''\n\tdef check_resource_account_003(self, dataPath, sheetName):\n\n\t\t#日志开始记录\n\t\tself.log.log_start(\"check_resource_account\")\n\t\t#获取检验资源测试数据\n\t\tresourceData = self.data.get_data(dataPath, sheetName)\n\t\t#保存成功的弹出框\n\t\tresourceMsg = self.testrole.popup()\n\n\t\t#无检查点的测试项标识,如果为True说明通过\n\t\tflag = False\n\n\t\tfor dataRow in range(len(resourceData)):\n\t\t\tdata = resourceData[dataRow]\n\t\t\ttry:\n\t\t\t\t#如果不是第一行标题,则读取数据\n\t\t\t\tif dataRow != 0:\n\t\t\t\t\tif dataRow == 1:\n\t\t\t\t\t\tself.account.click_account_manage_button(data[2])\n\t\t\t\t\t\tself.account.click_account_add_edit_button()\n\t\t\t\t\tself.linux.check_resource_account(data[3], data[4], data[5], data[6])\n\t\t\t\t\tself.frameElem.switch_to_content()\n\t\t\t\t\tself.cmf.test_win_check_point(\"xpath\", resourceMsg, data, flag)\n\t\t\texcept Exception as e:\n\t\t\t\tprint (\"check_resource_account fail:\" + str(e))\n\n\t\tself.cmf.back()\n\n\t\tself.cmf.back()\n\n\t\tself.log.log_end(\"check_resource_account\")\n\n\tu'''删除资源账号'''\n\tdef del_resource_account_004(self, dataPath, sheetName):\n\n\t\t#日志开始记录\n\t\tself.log.log_start(\"del_resource_account\")\n\t\t#获取删除资源账号测试数据\n\t\taccountData = self.data.get_data(dataPath, sheetName)\n\t\t#保存成功的弹出框\n\t\taccountMsg = self.testrole.popup()\n\n\t\t#无检查点的测试项标识,如果为True说明通过\n\t\tflag = False\n\n\t\tfor dataRow in range(len(accountData)):\n\t\t\tdata = accountData[dataRow]\n\t\t\ttry:\n\t\t\t\t#如果不是第一行标题,则读取数据\n\t\t\t\tif dataRow != 0:\n\t\t\t\t\tself.account.click_account_manage_button(data[2])\n\t\t\t\t\tself.account.click_account_del(data[3])\n\t\t\t\t\tself.frameElem.switch_to_content()\n\t\t\t\t\tself.cmf.test_win_check_point(\"xpath\", accountMsg, data, flag)\n\t\t\t\t\tself.cmf.click_msg_button(1)\n\t\t\texcept Exception as e:\n\t\t\t\tprint (\"del_resource_account fail:\" + str(e))\n\t\tself.cmf.back()\n\t\tself.log.log_end(\"del_resource_account\")\n\n\tu'''全选删除资源账号'''\n\tdef bulkdel_resource_account_005(self, dataPath, sheetName):\n\n\t\t#日志开始记录\n\t\tself.log.log_start(\"bulkdel_resource_account\")\n\t\t#获取全选删除资源账号测试数据\n\t\taccountData = self.data.get_data(dataPath, sheetName)\n\t\t#保存成功的弹出框\n\t\taccountMsg = self.testrole.popup()\n\n\t\t#无检查点的测试项标识,如果为True说明通过\n\t\tflag = False\n\n\t\tfor dataRow in range(len(accountData)):\n\t\t\tdata = accountData[dataRow]\n\t\t\ttry:\n\t\t\t\t#如果不是第一行标题,则读取数据\n\t\t\t\tif dataRow != 0:\n\t\t\t\t\tself.account.click_account_manage_button(data[2])\n\t\t\t\t\tself.cmf.check_all()\n\t\t\t\t\tself.cmf.bulkdel(\"delete_account\")\n\t\t\t\t\tself.frameElem.switch_to_content()\n\t\t\t\t\tself.cmf.test_win_check_point(\"xpath\", accountMsg, data, flag)\n\t\t\t\t\tself.cmf.click_msg_button(1)\n\t\t\texcept Exception as e:\n\t\t\t\tprint (\"bulkdel_resource_account failure:\" + str(e))\n\t\tself.cmf.back()\n\n\t\tself.log.log_end(\"bulkdel_resource_account\")\n\n","sub_path":"testCase/resource/test_resource_accountmgr.py","file_name":"test_resource_accountmgr.py","file_ext":"py","file_size_in_byte":5992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"310008927","text":"import numpy as np\nimport pandas as pd\n\nfrom .tools import median_mad\n\ndef cut_chunks(signals, indexes, width):\n \"\"\"\n This cut small chunks on signals and return concatenate them.\n This use numpy.array for input/output.\n \n extract_peak_waveforms and extract_noise_waveforms ar higher level fonction\n than use dataFrame as Input/Ouput\n \n Arguments\n ---------------\n signals: np.ndarray \n shape (nb_campleXnb_channel)\n indexes: np.ndarray\n sample postion of the first sample\n width: int\n Width in sample of chunks.\n Returns\n -----------\n chunks : np.ndarray\n shape = (indexes.size, signals.shape[1], width)\n \n \"\"\"\n chunks = np.empty((indexes.size, signals.shape[1], width), dtype = signals.dtype)\n for i, ind in enumerate(indexes):\n chunks[i,:,:] = signals[ind:ind+width,:].transpose()\n return chunks\n\n\ndef extract_peak_waveforms(signals, peak_pos, peak_index, n_left, n_right):\n \"\"\"\n Extract waveforms around peak given signals and peak position (in sample).\n Note that peak_pos near border are eliminated, \n so waveforms.index is or is NOT peak_pos depending if there are spike to near borders.\n \n Arguments\n ---------------\n signals : pandas.DataFrame\n Signals\n peak_pos : np.ndarray\n Vector cthat contains peak position in index.\n peak_index : pandas.Index\n Index of peak for output can be depending of the needs:\n * multiindex 2 levels = (seg_num, peak_time) \n * or peak_time\n * or peak_pos\n n_left, n_right: int, int\n Nb of sample arround the peak to extract.\n The waveform length is = - n_left + n_right.\n n_left is negative, n_right is positve\n \n Output\n ----------\n waveforms: pandas.dataFrame\n Waveforms extract. \n index = peak_index\n columns = multindex 2 level = (channel,sample_pos in [n_left:n_right])\n \n \"\"\"\n assert n_left<0\n assert n_right>0\n \n keep = (peak_pos>-n_left+1) & (peak_pos0\n \n limit1 = peak_pos + n_left\n limit2 = peak_pos + n_right + 1\n \n positions = np.random.randint(low = -n_left, high = signals.shape[0]-n_right-1, size = size)\n for i, pos in enumerate(positions):\n while np.any((pos+n_right + 1 + safety_factor>=limit1) & (pos<=limit2)|(pos>=limit1) & (pos+n_left-safety_factor<=limit2)):\n pos = np.random.randint(low = -n_left, high = signals.shape[0]-n_right-1)\n positions[i] = pos\n \n sample_index = np.arange(n_left, n_right, dtype = 'int64')\n columns = pd.MultiIndex.from_product([signals.columns,sample_index], \n names = ['channel', 'sample'])\n chunks = cut_chunks(signals.values, positions+n_left, - n_left + n_right)\n chunks= chunks.reshape(chunks.shape[0], -1)\n waveforms = pd.DataFrame(chunks, index = positions, columns = columns)\n \n return waveforms\n\n\ndef get_good_events(waveforms, upper_thr=6.,lower_thr=-8., med = None, mad = None):\n \"\"\"\n Are individual events 'close enough' to the median event?\n \n Parameters\n ----------\n waveforms: pandas.DataFrame\n waveforms\n upper_thr a positive number, by how many time the MAD is the event allow to\n deviate from the median in the positive direction?\n lower_thr a negative number, by how many time the MAD is the event allow to\n deviate from the median in the negative direction? If None (default)\n lower_thr is set to -upper_thr \n med: None or np.array\n Already precomptued median (avoid recomputation)\n mad :None or np.array\n Already precomptued mad (avoid recomputation)\n \n Returns\n -------\n A Boolean vector whose elements are True if the event is 'good' and False otherwise.\n \n \"\"\"\n if lower_thr is None:\n lower_thr = -upper_thr\n assert upper_thr>=0, 'upper_thr must be positive'\n assert lower_thr<=0, 'lower_thr must be negative'\n\n if med is None:\n med = waveforms.median(axis=0)\n if mad is None:\n mad = np.median(np.abs(waveforms-med),axis=0)*1.4826\n \n normed = (waveforms-med)/mad\n \n # any is faster that all\n #keep = np.all((normed>lower_thr)& (normedupper_thr, axis=1))\n \n return keep\n\n\n\ndef find_good_limits(normed_mad, mad_threshold = 1.1):\n \"\"\"\n Find goods limits for the waveform.\n Where the MAD is above noise level (=1.)\n \n The technics constists in finding continuous samples above 10% of backgroud noise.\n \n Parameters\n ----------\n normed_mad: np.ndarray\n MAD for each waveform by channel.\n Already normed by channel.\n shape = (nb_channel, nb_sample)\n \n Returns\n ----------\n limit1, limi2: int\n Left and rigth limits\n Both are positive. They are relative to chunk (not peak).\n \"\"\"\n # any channel above MAD mad_threshold\n above = np.any(normed_mad>=mad_threshold, axis=0)\n #find max consequitive point that are True\n \n up, = np.where(np.diff(above.astype(int))==1)\n down, = np.where(np.diff(above.astype(int))==-1)\n \n if len(up)==0 or len(down)==0:\n return None, None\n \n up = up[upmin(up)]\n \n if len(up)==0 or len(down)==0:\n return None, None\n \n best = np.argmax(down-up)\n \n return up[best], down[best]+1\n\n\n\n\nclass WaveformExtractor_:\n def __init__(self, peakdetector, n_left=-30, n_right=45):\n \"\"\"\n \n \"\"\"\n assert hasattr(peakdetector, 'peak_pos'), 'peakdetector must execute first PeakDetector.detect_peaks(...)'\n \n self.peakdetector = peakdetector\n self.n_left = n_left\n self.n_right = n_right\n self.seg_num = self.peakdetector.seg_num\n\n #work on normed signals\n self.signals = self.peakdetector.normed_sigs\n self.nb_channel = self.signals.shape[1]\n\n \n #Initial waveform extraction with bigger chunk\n self.long_waveforms = extract_peak_waveforms(self.signals, self.peakdetector.peak_pos,self.peakdetector.peak_index, n_left, n_right)\n self.med, self.mad = median_mad(self.long_waveforms, axis=0)\n \n #~ self.med = self.long_waveforms.median(axis=0)\n #~ self.mad = np.median(np.abs(self.long_waveforms-self.med),axis=0)*1.4826\n \n def good_events(self, upper_thr=6.,lower_thr=-8.,):\n self.keep = good_events(self.long_waveforms, upper_thr=upper_thr,lower_thr=lower_thr, med = self.med, mad = self.mad)\n return self.keep\n \n def extract_noise(self, n_left, n_right, size=1000, safety_factor=2):\n # take some noise\n self.noises = extract_noise_waveforms(self.signals, self.peakdetector .peak_pos, n_left, n_right, size=size, safety_factor=safety_factor)\n return self.noises\n \n def find_good_limits(self, mad_threshold = 1.1):\n l1, l2 = find_good_limits(self.mad.values.reshape(self.nb_channel,-1), mad_threshold = mad_threshold)\n if l1 is None:\n self.limit_left, self.limit_right = None, None\n else:\n self.limit_left = self.long_waveforms.columns.levels[1][l1]\n self.limit_right = self.long_waveforms.columns.levels[1][l2]\n return self.limit_left, self.limit_right\n \n def get_ajusted_waveforms(self):\n \"\"\"\n Get ajusted waveform : between limit_left-margin and limit_right+margin.\n The margin of 2 sample is to get first and second derivative waveform to construct the catalogue.\n \"\"\"\n if self.limit_left is None:\n return self.long_waveforms\n else:\n sub = np.arange(self.limit_left-2, self.limit_right+2)\n self.long_waveforms.sortlevel(level=0, axis=1, inplace = True)\n short_waveforms = self.long_waveforms.loc[:, (slice(None), sub)]\n #reconstruct the real sub indexing\n # see http://pandas.pydata.org/pandas-docs/stable/advanced.html (Basic indexing on axis with MultiIndex)\n short_waveforms.columns = pd.MultiIndex.from_tuples(short_waveforms.columns.values)\n return short_waveforms\n \n\nfrom .mpl_plot import WaveformExtractorPlot\nclass WaveformExtractor(WaveformExtractor_, WaveformExtractorPlot):\n pass\n\n\n\n","sub_path":"tridesclous/waveformextractor.py","file_name":"waveformextractor.py","file_ext":"py","file_size_in_byte":10508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"386879904","text":"import re\nimport string\n\ndef word_count(s):\n # Your code here\n counts = {}\n\n remove = string.punctuation\n remove = remove.replace(\"'\", \"\") # don't remove apostrophes\n pattern = r\"[{}]\".format(remove) # create the pattern\n no_punctuation = re.sub(pattern, \" \", s)\n words = no_punctuation.split()\n\n words2 = []\n\n for word in words:\n word = word.lower()\n words2.append(word)\n\n for x in words2:\n if x in counts:\n counts[x] += 1\n else:\n counts[x] = 1\n\n return counts\n\n\nif __name__ == \"__main__\":\n print(word_count(\"\"))\n print(word_count(\"Hello\"))\n print(word_count('Hello, my cat. And my cat doesn\\'t say \"hello\" back.'))\n print(word_count('This is a test of the emergency broadcast network. This is only a test.'))\n","sub_path":"applications/word_count/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"489864023","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.forms import ModelForm, TextInput, Select, PasswordInput, Textarea, HiddenInput, NumberInput, DateInput\nfrom django.conf import settings\n\nfrom remuneraciones.models import ParametrosIndicadores,HaberesDescuentos\n\nfrom datetime import datetime\n\nclass ParametrosIndicadoresForm(ModelForm):\n \n pind_fechacreado = forms.DateField( label=\"Fecha creación\", input_formats=[\"%d/%m/%Y\"], widget=forms.DateInput(format=\"%d/%m/%Y\", attrs={ 'class':'form-control', 'data-inputmask':'\"mask\": \"99/99/9999\"', 'data-mask':'', 'autocomplete':'off', 'readonly':'readonly'}), required = False)\n pind_titulo = forms.CharField(label=\"Título\", widget=forms.TextInput(attrs={'class':'form-control', }))\n pind_ufmesanterior = forms.DecimalField(label='UF último dia mes anterior', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_ufmesactual = forms.DecimalField(label='UF último dia mes actual', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_utmmesactual = forms.DecimalField(label='UTM último dia mes actual', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_utamesactual = forms.DecimalField(label='UTA último dia mes actua', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentatopeafp = forms.DecimalField(label='Renta tope AFP', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentatopeips = forms.DecimalField(label='Renta tope IPS', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentatopeafc = forms.DecimalField(label='Renta tope AFC', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentatopeapvm = forms.DecimalField(label='Renta tope APV mensual', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentatopeapva = forms.DecimalField(label='Renta tope APV anual', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_segurocesantiapitrabajador = forms.DecimalField(label='Seguro cesantía plazo indefinido trabajador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_segurocesantiapiempleador = forms.DecimalField(label='Seguro cesantía plazo indefinido empleador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_segurocesantiapftrabajador = forms.DecimalField(label='Seguro cesantía plazo fijo trabajador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_segurocesantiapfempleador = forms.DecimalField(label='Seguro cesantía plazo fijo empleador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_segurocesantiapi11trabajador = forms.DecimalField(label='Seguro cesantía plazo indefinido más de 11 años trabajador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_segurocesantiapi11empleador = forms.DecimalField(label='Seguro cesantía plazo indefinido más de 11 años empleador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_cottrbajopesadopitrabajador = forms.DecimalField(label='Cotización para Trabajos Pesado plazo indefinido trabajador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_cottrbajopesadopiempleador = forms.DecimalField(label='Cotización para Trabajos Pesado plazo indefinido empleador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_cottrbajopesadopftrabajador = forms.DecimalField(label='Cotización para Trabajos Pesado plazo fijo trabajador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_cottrbajopesadopfempleador = forms.DecimalField(label='Cotización para Trabajos Pesado plazo fijo empleador', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_depositoconvenioanual = forms.DecimalField(label='Depósito Convenido Tope Anual', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentaminima1 = forms.DecimalField(label='Trab. Dependientes e Independientes', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentaminima2 = forms.DecimalField(label='Menores de 18 y Mayores de 65', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentaminima3 = forms.DecimalField(label='Trabajadores de Casa Particular', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_rentaminima4 = forms.DecimalField(label='Para fines no remuneracionales', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_asigfamiliartramo1 = forms.DecimalField(label='Monto tramo 1', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_asigfamiliartramo2 = forms.DecimalField(label='Monto tramo 2', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_asigfamiliartramo3 = forms.DecimalField(label='Monto tramo 3', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n pind_asigfamiliartramo4 = forms.DecimalField(label='Monto tramo 4', initial='0', widget=forms.NumberInput(attrs={'class': 'form-control', 'readonly':'readonly'}), required = False)\n\n def cleanDiasHabiles(self):\n\n fechaCreado = self.cleaned_data.get('pind_fechacreado')\n\n\n mensaje = \"\"\n error = False\n\n print(\"Día:\", fechaCreado.day) # Muestra día\n print(\"Mes:\", fechaCreado.month) # Muestra mes\n print(\"Año:\", fechaCreado.year) # Muestra año\n\n numeroDeDia = int(fechaCreado.strftime(\"%w\"))\n\n if numeroDeDia in [6,0]:\n error = True\n mensaje = \"No es día hábil, verifique que no sea ni Sábado ni Domingo\"\n\n if error:\n self.add_error('pind_fechacreado', mensaje)\n\n return fechaCreado\n\n\n\n class Meta:\n model = ParametrosIndicadores\n fields = [\n 'pind_fechacreado',\n 'pind_titulo',\n 'pind_ufmesanterior',\n 'pind_ufmesactual',\n 'pind_utmmesactual',\n 'pind_utamesactual',\n 'pind_rentatopeafp',\n 'pind_rentatopeips',\n 'pind_rentatopeafc',\n 'pind_rentatopeapvm',\n 'pind_rentatopeapva',\n 'pind_segurocesantiapitrabajador',\n 'pind_segurocesantiapiempleador',\n 'pind_segurocesantiapftrabajador',\n 'pind_segurocesantiapfempleador',\n 'pind_segurocesantiapi11trabajador',\n 'pind_segurocesantiapi11empleador',\n 'pind_cottrbajopesadopitrabajador',\n 'pind_cottrbajopesadopiempleador',\n 'pind_cottrbajopesadopftrabajador',\n 'pind_cottrbajopesadopfempleador',\n 'pind_depositoconvenioanual',\n 'pind_rentaminima1',\n 'pind_rentaminima2',\n 'pind_rentaminima3',\n 'pind_rentaminima4',\n 'pind_asigfamiliartramo1',\n 'pind_asigfamiliartramo2',\n 'pind_asigfamiliartramo3',\n 'pind_asigfamiliartramo4',\n ]\n \n \nclass PeriodoALiquidarForm(forms.Form):\n\n TIPO_AFILIACION = (\n ('', '--- Seleccione el mes ---'),\n (1, 'ENERO'),\n (2, 'FEBRERO'),\n (3, 'MARZO'),\n (4, 'ABRIL'),\n (5, 'MAYO'),\n (6, 'JUNIO'),\n (7, 'JULIO'),\n (8, 'AGOSTO'),\n (9, 'SEPTIEMBRE'),\n (10, 'OCTUBRE'),\n (11, 'NOVIEMBRE'),\n (12, 'DICIEMBRE'),\n )\n\n meses = forms.ChoiceField(initial='', label=\"Meses\", choices=TIPO_AFILIACION, widget=forms.Select(attrs={'class': 'form-control'}))\n anio = forms.IntegerField(label=\"Año\", widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder':'Año'}))\n \nclass HaberesALiquidarForm(forms.Form):\n\n TIPO_DETALLE = (\n ('', '--- Seleccione ---'),\n (7, 'Bono'),\n )\n\n TIPO_DETALLE_DESCUENTOS = (\n ('', '--- Seleccione ---'),\n (5, 'Días faltados'),\n (6, 'Minutos atrasados'),\n (8, 'Otros'),\n (21, 'Anticipo de sueldo'),\n )\n\n tipoDetalleLiquidacion = forms.ChoiceField(initial='', label=\"Detalle liquidación\", widget=forms.Select(attrs={'class': 'form-control select2', 'rel-label':'Detalle liquidación', 'style':'width: 100%'}))\n horasExtra = forms.CharField(label=\"Horas extras\", widget=forms.TextInput(attrs={'class': 'form-control', 'rel-label':'Horas extras', 'data-inputmask':'\"mask\": \"99:99\"', 'data-mask':'', 'autocomplete':'off', 'placeholder':'HH:MM'}), required=False)\n valorHoraExtra = forms.IntegerField(label=\"Factor\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Factor', 'autocomplete':'off', 'readonly':True}), required=False)\n montoBruto = forms.IntegerField(label=\"Monto bruto\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Monto bruto', 'autocomplete':'off'}), required=False)\n montoNeto = forms.IntegerField(label=\"Monto neto\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Monto neto', 'autocomplete':'off', 'readonly':True}))\n diasFaltados = forms.IntegerField(label=\"Días faltados\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Días faltados', 'autocomplete':'off'}), required=False)\n minutosAtrasos = forms.IntegerField(label=\"Minutos de atrasos\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Minutos de atrasos', 'autocomplete':'off'}), required=False)\n montoBono = forms.IntegerField(label=\"Monto bono\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Monto bono', 'autocomplete':'off'}))\n porcentaje = forms.IntegerField(label=\"Porcentaje\", initial=0, widget=forms.TextInput(attrs={'class': 'form-control', 'rel-label':'Porcentaje', 'autocomplete': 'off'}))\n porcentajeComision = forms.IntegerField(label=\"Porcentaje comision\", initial=0, widget=forms.TextInput(attrs={'class': 'form-control', 'rel-label':'Porcentaje', 'autocomplete': 'off', 'readonly':True}))\n tipoDetalle = forms.ChoiceField(initial='', label=\"Tipo detalle\", choices=TIPO_DETALLE, widget=forms.Select(attrs={'class': 'form-control select2', 'rel-label':'Tipo detalle', 'style':'width: 100%'}))\n monto = forms.IntegerField(label=\"Monto\", initial=0, widget=forms.NumberInput(attrs={'class': 'form-control', 'rel-label':'Monto', 'autocomplete': 'off'}))\n tipoDeMonto = forms.ChoiceField(initial='', label=\"Tipo de monto\", choices=HaberesDescuentos.TIPO_DE_MONTO[:3], widget=forms.Select(attrs={'class': 'form-control', 'rel-label':'Tipo de monto'}))\n tipoMontoDescuento = forms.ChoiceField(initial='', label=\"Tipo de descuento\", choices=TIPO_DETALLE_DESCUENTOS, widget=forms.Select(attrs={'class': 'form-control', 'rel-label':'Tipo de descuento'}))\n\n # *** MNI ***\n \n # *** BONO EX, IN ***\n tipoDeBono = forms.ChoiceField(initial='', label=\"Tipo de bono\", choices=HaberesDescuentos.TIPO_BONO, widget=forms.Select(attrs={'class': 'form-control', 'rel-label':'Tipo de bono'}))\n mni_monto = forms.IntegerField(label=\"Monto\", initial=0, widget=forms.NumberInput(attrs={'class':'form-control', 'rel-label':'Monto', 'autocomplete':'off'}), required=False)\n # *** BONO EX, IN ***\n \n # *** MNI ***\n \n def clean_horasExtra(self):\n\n horas_extras = self.cleaned_data.get('horasExtra')\n \n horas = int(horas_extras.split(':')[0])\n minutos = int(horas_extras.split(':')[1])\n \n mensaje = \"\"\n error=False\n \n if horas > 12 or horas < 1 :\n mensaje+=\"- El rango de hora no es valido, debe ser entre 1 a 12 horas

\"\n error = True\n if minutos > 60 or minutos < 1 :\n mensaje+=\"- El rango de minutos no es valido, debe ser entre 1 a 60 minutos\"\n error = True\n \n if error:\n self.add_error('horas_extras', mensaje)\n \n return horas_extras\n","sub_path":"remuneraciones/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":13560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"470396430","text":"\nclass HashTable(object):\n \"\"\"\n Class module of Hash Table\n \"\"\"\n def __init__(self):\n \"\"\"\n Class constructor which initialize size\n and the lists to store the keys and values\n of the HashTable\n \"\"\"\n # size of the HashTable\n self.size = 11\n # list to store the keys\n self.slots = [None]*self.size\n # list to store the values\n self.data = [None]*self.size\n\n def hashfunction(self, key, size):\n \"\"\"\n Method to compute hash function\n \"\"\"\n return key%size\n\n def rehash(self, oldhash, size):\n \"\"\"\n Method to compute rehash on the event of a collision\n \"\"\"\n return (oldhash+1)%size\n\n def put(self, key, data):\n \"\"\"\n Method to put i.e. insert key value pair into Hash Table\n \"\"\"\n hashvalue = self.hashfunction(key,len(self.slots))\n\n if self.slots[hashvalue] == None:\n self.slots[hashvalue] = key\n self.data[hashvalue] = data\n else:\n if self.slots[hashvalue] == key:\n self.data[hashvalue] = data #replace\n else:\n nextslot = self.rehash(hashvalue,len(self.slots))\n while self.slots[nextslot] != None and self.slots[nextslot] != key:\n nextslot = self.rehash(nextslot,len(self.slots))\n\n if self.slots[nextslot] == None:\n self.slots[nextslot]=key\n self.data[nextslot]=data\n else:\n self.data[nextslot] = data\n\n def get(self,key):\n \"\"\"\n Method to get value of the key from the HashTable if the key is present\n \"\"\"\n startslot = self.hashfunction(key,len(self.slots))\n data = None\n stop = False\n found = False\n position = startslot\n while self.slots[position] != None and not found and not stop:\n if self.slots[position] == key:\n found = True\n data = self.data[position]\n else:\n position=self.rehash(position,len(self.slots))\n if position == startslot:\n stop = True\n return data\n\n def __getitem__(self,key):\n \"\"\"\n Get method\n \"\"\"\n return self.get(key)\n\n def __setitem__(self,key,data):\n \"\"\"\n Set method\n \"\"\"\n self.put(key,data)\n\nif __name__ == \"__main__\":\n H=HashTable()\n H[54]=\"cat\"\n H[26]=\"dog\"\n H[93]=\"lion\"\n H[17]=\"tiger\"\n H[77]=\"bird\"\n H[31]=\"cow\"\n H[44]=\"goat\"\n H[55]=\"pig\"\n H[20]=\"chicken\"\n print(H.slots)\n print(H[20])\n print(H[17])\n H[20]='duck'\n print(H[20])\n print(H.data)\n print(H[99])\n","sub_path":"py_algo/data_struct/hash_table.py","file_name":"hash_table.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"531170857","text":"\"\"\"Platform for Bestin TCP switch integration.\"\"\"\n\nimport voluptuous as vol\n\n# Import the device class from the component that you want to support\nfrom homeassistant.components.switch import SwitchEntity\n\nfrom homeassistant import const\n\nfrom datetime import timedelta\nimport logging\nimport sys\nimport async_timeout\n\n_LOGGER = logging.getLogger(__name__)\n\nfrom homeassistant.helpers import entity\nfrom homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed\n\nfrom . import DOMAIN\n\n\n# async component so that calls can better be done by room instead of by switch entity.\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n rooms = discovery_info\n async def async_update_data():\n \"\"\"Fetch lighting data\"\"\"\n async with async_timeout.timeout(10):\n def fetch_light_status():\n for room in rooms:\n room.fetchOutletsStatus()\n await hass.async_add_executor_job(fetch_light_status)\n # XXX should maybe attempt error catching here?\n return True\n\n coordinator = DataUpdateCoordinator(\n hass,\n _LOGGER,\n # Name of the data. For logging purposes.\n name=\"bestintcp_switch\",\n update_method=async_update_data,\n # Polling interval. Will only be polled if there are subscribers.\n update_interval=timedelta(seconds=60),\n )\n\n outlets = []\n for room in discovery_info:\n _LOGGER.info(f\"{room}\")\n for name in room.outlets:\n outlet = BestinTCPOutlet(room, name, coordinator)\n outlets.append(outlet)\n\n # Fetch initial data so we have data when entities subscribe\n await coordinator.async_refresh()\n\n async_add_entities(outlets)\n\n\nclass BestinTCPOutlet(SwitchEntity):\n def __init__(self, room, name, coordinator):\n self.room = room\n self._name = name\n self.coordinator = coordinator\n\n @property\n def name(self):\n \"\"\"Return the display name of this switch.\"\"\"\n return f'bestin_r{self.room.name}_{self._name}'\n\n @property\n def is_on(self):\n \"\"\"Return true if switch is on.\"\"\"\n return self.room.isOutletOn(self._name)\n\n @property\n def available(self):\n return self.coordinator.last_update_success\n\n def should_poll(self):\n return False\n\n async def async_added_to_hass(self):\n \"\"\"When entity is added to hass.\"\"\"\n self.async_on_remove(\n self.coordinator.async_add_listener(\n self.async_write_ha_state\n )\n )\n\n def turn_on(self, **kwargs):\n \"\"\"Turn the switch on.\"\"\"\n self.room.setOutletStatus(self._name, 'on')\n\n def turn_off(self, **kwargs):\n \"\"\"Turn the switch off.\"\"\"\n self.room.setOutletStatus(self._name, 'off')\n\n async def async_update(self):\n \"\"\"Update the light.\"\"\"\n return await self.coordinator.async_request_refresh()\n\n","sub_path":"switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"355479892","text":"import unicodedata\nfrom fatchord_wavernn.utils.text import text_to_sequence, sequence_to_text\n\n\ndef test_vie():\n text = \"Hôm qua em tới trưỜng!!!\"\n seq = text_to_sequence(text, ['vie.vie_cleaners'])\n text_ = sequence_to_text(seq)\n print(text)\n print(seq)\n print(text_)\n assert text.lower() == text_\n\n\ndef test_vie_unicode_normalize():\n text = unicodedata.normalize('NFKD', \"Hôm qua em tới trưỜng!!!\")\n seq = text_to_sequence(text, ['vie.vie_cleaners'])\n text_ = sequence_to_text(seq)\n assert unicodedata.normalize('NFKC', text.lower()) == text_\n","sub_path":"tests/test_vie_text.py","file_name":"test_vie_text.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"270877447","text":"'''\nFaça um programa que leia o SEXO de uma pessoa, mas so aceite\nos valores M ou F. Caso esteja errado, peça a digitação novamente\naté ter um valor correto.\n'''\n\nnome = str(input('Nome: ')).strip().upper()\nsexo = str(input('Seu Sexo: ')).strip().upper()[0]\nwhile sexo not in 'MF':\n sexo = str(input('Digite o sexo corretamente [M/F]: ')).upper()[0]\nprint('Seu nome é {}, seu sexo é {}'.format(nome,sexo))\n\n\n","sub_path":"Fundamentos/9 - EstruturaRepeticaoWhile/057 - ValidacaoDeDados.py","file_name":"057 - ValidacaoDeDados.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"641379845","text":"\nfrom datetime import datetime\n\n#from vumi.tests.utils import UTCNearNow\nfrom vumi.message import (TransportEvent, TransportMessage,\n TransportUserMessage, Message)\nfrom vumi.transports.failures import FailureMessage\nfrom vusion.message import DispatcherControl\n\n\nclass DataLayerUtils:\n\n def setup_collections(self, names):\n for name in names:\n self.setup_collection(name)\n\n def setup_collection(self, name):\n if name in self.db.collection_names():\n self.collections[name] = self.db[name]\n else:\n self.collections[name] = self.db.create_collection(name)\n\n def drop_collections(self):\n for name, collection in self.collections.items():\n collection.drop()\n\n\n#TODO use UTC time rather than datetime\nclass MessageMaker:\n\n def mkmsg_ack(self, user_message_id='1', sent_message_id='abc',\n transport_metadata=None):\n if transport_metadata is None:\n transport_metadata = {}\n return TransportEvent(\n event_id=RegexMatcher(r'^[0-9a-fA-F]{32}$'),\n event_type='ack',\n user_message_id=user_message_id,\n sent_message_id=sent_message_id,\n timestamp=datetime.now(),\n transport_name=self.transport_name,\n transport_metadata=transport_metadata,\n )\n\n def mkmsg_delivery(self, event_type='delivery_report', user_message_id='1',\n sent_message_id='abc', delivery_status='delivered',\n failure_code=None, failure_level=None,\n failure_reason=None, transport_name=None,\n transport_metadata=None):\n if transport_metadata is None:\n transport_metadata = {}\n params = dict(\n event_type=event_type,\n user_message_id=user_message_id,\n sent_message_id=sent_message_id,\n delivery_status=delivery_status,\n failure_level=failure_level,\n failure_code=failure_code,\n failure_reason=failure_reason,\n transport_name=transport_name,\n transport_metadata=transport_metadata,\n )\n return TransportEvent(**params)\n\n def mkmsg_in(self, content='hello world',\n from_addr='+41791234567',\n to_addr='9292',\n session_event=TransportUserMessage.SESSION_NONE,\n message_id='abc', transport_type=None,\n transport_metadata=None, transport_name=None,\n timestamp=None):\n if timestamp is None:\n timestamp = datetime.now()\n if transport_type is None:\n transport_type = transport_type\n if transport_metadata is None:\n transport_metadata = {}\n return TransportUserMessage(\n from_addr=from_addr,\n to_addr=to_addr,\n group=None,\n message_id=message_id,\n transport_name=transport_name,\n transport_type=transport_type,\n transport_metadata=transport_metadata,\n content=content,\n session_event=session_event,\n timestamp=timestamp,\n )\n\n def mkmsg_out(self, content='hello world',\n session_event=TransportUserMessage.SESSION_NONE,\n message_id='1', to_addr='+41791234567', from_addr='9292',\n group=None, in_reply_to=None, transport_type=None,\n transport_metadata=None, helper_metadata=None,\n transport_name=None):\n if transport_type is None:\n transport_type = transport_type\n if transport_metadata is None:\n transport_metadata = {}\n if helper_metadata is None:\n helper_metadata = {}\n params = dict(\n to_addr=to_addr,\n from_addr=from_addr,\n group=group,\n message_id=message_id,\n transport_name=transport_name,\n transport_type=transport_type,\n transport_metadata=transport_metadata,\n content=content,\n session_event=session_event,\n in_reply_to=in_reply_to,\n helper_metadata=helper_metadata,\n )\n return TransportUserMessage(**params)\n\n def mkmsg_fail(self, message, reason,\n failure_code=FailureMessage.FC_UNSPECIFIED):\n return FailureMessage(\n timestamp=datetime.now(),\n failure_code=failure_code,\n message=message,\n reason=reason,\n )\n\n def mkmsg_dispatcher_control(self, action='add_exposed',\n exposed_name='app2', rules=None):\n if rules == None:\n rules = []\n return DispatcherControl(\n action=action,\n exposed_name=exposed_name,\n rules=rules)\n\n def mkmsg_multiworker_control(self, message_type='add_worker',\n worker_name='m4h', worker_class=None,\n config=None):\n if config == None:\n config = []\n return Message(\n message_type=message_type,\n worker_name=worker_name,\n worker_class=worker_class,\n config=config)\n\n def mkmsg_dialogueworker_control(self, action, dialogue_obj_id=None,\n phone_number=None):\n return Message(\n action=action,\n dialogue_obj_id=dialogue_obj_id,\n phone_number=phone_number)\n \n \nclass ObjectMaker:\n \n def mkobj_template_unmatching_keyword(self):\n return {\n 'name': 'error template',\n 'type-template': 'unmatching-keyword',\n 'template': 'KEYWORD does not match any keyword.'\n }\n \n def mkobj_shortcode(self, error_template=None):\n return {\n 'country': 'Uganda',\n 'internationalprefix': '256',\n 'shortcode': '8282',\n 'error-template': error_template\n }\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"560691308","text":"from typing import Optional\n\nfrom models.simulation.depot import Depot\n\n\nclass SimutationAgent:\n dummy_car: 'SimutationAgent' = None\n\n def __init__(\n self,\n cid: int,\n start_time: Optional[int],\n end_time: Optional[int],\n depot_point: Depot,\n car_type: Optional[CarType] = None\n ) -> None:\n self.type = ... # TODO:\n\n assert self.start_time is not None and self.end_time is not None, \"Время == None\"\n\n self.depot_point: Depot = depot_point\n\n self.type: Optional[CarType] = car_type\n\n self.containers: List = []\n\n self.is_active: bool = True # в работе ли машинапше\n self.current_price: float = 0.0\n self.current_weight: float = 0.0 # текущая масса в машине\n self.current_volume: float = 0.0 # текущий объем без прессовки\n self.current_distance: float = 0.0 # пройденное расстояние на текущий момент\n self.current_time: int = self.start_time # Текущее время в секундах для машины\n\n self.way_points: List[Visit] = [self.create_depot_visit(self.current_time)]\n\n self.id_ = cid\n self.driver_id: Optional[int] = None\n self.problem: \"Optional[VRPProblem]\" = None\n\n def __str__(self):\n try:\n depot_time = self.time_to_depot()\n landfill_time = self.time_to_landfill()\n except Exception:\n depot_time = -1\n landfill_time = -1\n\n return (\n f'Car(id:{self.id_}, тип:{self.type}, точка:{self.current_point}, '\n f'путь:{self.current_distance / 1000:.1f}км, время:{self.current_time / 3600:.2f}ч, '\n f'объем:{self.current_volume}, точек:{len(self.way_points)}, '\n f'до депо:{depot_time:.2f}ч, до выгрузки:{landfill_time:.2f}ч), '\n f'поддерживаемые типы {list(self.type.allowed_container_types)}, '\n f'конец рабочего дня {self.end_time / 3600:.2f} '\n )\n\n def __lt__(self, other):\n return self.id_ < other.id_\n\n def __repr__(self):\n return str(self)\n\n def __hash__(self):\n return self.id_.__hash__()\n\n def __eq__(self, other):\n return self.id_ == other.id\n\n @staticmethod\n def copy_attrs(src: 'SimutationAgent', dst: 'SimutationAgent') -> None:\n \"\"\"\n Копируем всю изменяемую информацию из одной машины в другую\n \"\"\"\n immutable_attrs = (\"is_active\", 'current_price', 'current_volume',\n 'current_weight', 'current_distance', 'current_time')\n\n for a in immutable_attrs:\n setattr(dst, a, getattr(src, a))\n\n dst.containers = src.containers[:]\n dst.way_points = src.way_points[:]\n\n def is_empty(self):\n return self.current_volume == 0 and self.current_weight == 0 and len(self.containers) == 0\n\n def goto_landfill(self) -> 'SimutationAgent':\n assert not (not self.is_bunker_car() and self.is_empty()), 'Разгружаем пустую машину'\n\n self.move_to(self.problem.landfill_point)\n self.current_time += self.problem.landfill_point.work_time\n self.current_weight = 0\n self.current_volume = 0\n self.containers = []\n\n return self\n\n def goto_depot(self) -> 'SimutationAgent':\n if isinstance(self.current_point, Depot):\n return self\n\n if not isinstance(self.current_point, Landfill) and not self.is_empty():\n self.goto_landfill() # выгрузить машину, если нужно\n\n self.move_to(point=self.depot_point)\n\n if self.current_time > self.end_time:\n raise ValueError(f\"Опоздаем в депо \"\n f\"{self.current_time / 3600:.2f}/{self.end_time / 3600:.2f}ч\")\n\n assert \\\n abs(self.current_volume) < 0.001 \\\n or abs(self.current_weight) < 0.001 \\\n or len(self.containers) == 0, \\\n 'Едем на базу не пустыми!'\n\n if self.can_take_containers():\n assert \\\n isinstance(self.way_points[-2].point, Landfill) \\\n and isinstance(self.way_points[-1].point, Depot), \\\n 'Последние 2 точки должны быть (Landfill, Depot)'\n\n self.is_active = False\n return self\n\n def atomic_goto_depot(self) -> 'SimutationAgent':\n \"\"\"\n Аналогично goto_depot, но в случае ошибки состояние не меняется\n \"\"\"\n SimutationAgent.copy_attrs(self, SimutationAgent.dummy_car)\n try:\n return self.goto_depot()\n except ValueError as e:\n SimutationAgent.copy_attrs(SimutationAgent.dummy_car, self)\n raise e\n\n # время от дистанции\n def get_duration(self, path) -> float:\n return self.type.calculate(distance=path)[1]\n\n # во сколько будет на точке\n # @lru_cache()\n def get_eta(self, point: Point) -> float:\n path = self.problem.distance(self.current_point, point) # расстояние до заявки\n\n duration = self.get_duration(path) # время до заявки\n return self.current_time + duration\n\n def finish_time(self, point: 'Container') -> int:\n \"\"\" Когда будем на базе \"\"\"\n assert point.point_type == 'container'\n duration = 0\n duration += self.score_path(self.current_point, point) # расстояние до заявки\n duration += self.score_path(point, self.problem.landfill_point) # расстояние до заявки\n duration += self.score_path(self.problem.landfill_point, self.depot_point) # расстояние до заявки\n\n duration += point.type_work_time\n duration += self.problem.landfill_point.work_time\n\n return self.current_time + duration\n\n # Можем ли мы взять конкретный реквест\n def pickup_problems(self, con: 'Container') -> Union[bool, str]:\n if self.is_bunker_car():\n return False if self.slow_check_can_take(con) else \"Этот бункеровоз не затащит\"\n\n problems = (\n lambda: self.will_overfill(con) * \"Перегруз\",\n\n lambda:\n (not con.is_car_compatible(self)) *\n f\"Несовместимый тип {con.type_id} not in {sorted(self.type.allowed_container_types)}\",\n\n lambda:\n self.will_overwork(con) *\n f\"Будет переработка {self.finish_time(con) / 3600:.2f}/{self.end_time / 3600:.2f}\",\n\n lambda: (not con.is_time_ok(self.get_eta(con))) * \"Не в окне\",\n lambda: (not self.is_active) * \"Неактивна\",\n )\n\n for problem in problems:\n p = problem()\n if p:\n return p\n\n return False\n\n def is_compatible(self, con: 'Container') -> bool:\n problems = (\n self.will_overfill(con),\n not con.is_car_compatible(self),\n )\n\n return not any(problems)\n\n # слишком много точек\n def too_many_points(self) -> bool:\n return len(self.containers) >= self.type.max_places_by_trip\n\n def slow_check_can_take(self, con: 'Container') -> bool:\n \"\"\" Проверяем можем ли взять \"\"\"\n try:\n test_copy = copy.deepcopy(self) # пробуем на липовой машине\n test_copy.take_bunker(con)\n test_copy.goto_depot()\n except ValueError as e:\n return False\n return True\n\n # слишком долгий маршрут\n def will_overwork(self, con) -> bool:\n problems = (\n self.finish_time(con) > self.end_time, # так как бывает 0 или None\n len(self.way_points) + 1 > self.type.max_places_by_trip,\n )\n\n return any(problems)\n\n # машина переполнится\n def will_overfill(self, con: 'Container') -> bool:\n problems = (\n self.current_volume + con.capacity > self.type.max_volume,\n self.current_weight + 0 > self.type.max_weight, # noqa\n )\n\n return any(problems)\n\n # взять реквест\n def take(self, con: 'Container') -> Tuple:\n m_stats = self.move_to(con)\n r_stats = self.score_request(con)\n self.update_stats(*r_stats)\n\n self.current_volume += con.capacity\n self.current_weight += 0 # noqa (потом он будет)\n\n self.containers += [con]\n\n return tuple(sum(p) for p in zip(m_stats, r_stats))\n\n def take_returnable(self, con: 'Container') -> 'SimutationAgent':\n \"\"\" Логика по взятию контейнера \"\"\"\n self.take(con)\n self.goto_landfill()\n self.move_to(con)\n\n return self\n\n def take_usual_bunker(self, con: 'Container') -> 'SimutationAgent':\n # если мы только что из возвратного, надо сгонять в landfill, взять контейнер\n if (\n len(self.way_points) > 1\n and self.way_points[-1].point.point_type == 'container'\n and self.way_points[-1].point.must_return\n ):\n self.goto_landfill()\n\n self.take(con)\n self.goto_landfill()\n\n return self\n\n def take_bunker(self, con: 'Container') -> 'SimutationAgent':\n if con.type_is_replacement:\n self.take_returnable(con)\n else:\n self.take_usual_bunker(con)\n\n return self\n\n def time_to_landfill(self) -> float:\n return self.dist_to(self.problem.landfill_point) / self.type.speed_avg / 3600\n\n def time_to_depot(self) -> float:\n return self.dist_to(self.depot_point) / self.type.speed_avg / 3600\n\n # доехать до точки\n def move_to(self, point: Point) -> Tuple[float, float, float]:\n assert self.is_active, 'Пытаемся куда-то ехать на неактивной машине'\n\n stats = self.score_move(point)\n self.update_stats(*stats)\n\n self.way_points += [Visit(point, self.current_time)]\n\n return stats\n\n # оценить ресурсы на перемещение машины в данную точку\n def score_move(self, point: Point) -> Tuple[float, float, float]:\n path = self.dist_to(point)\n\n return self.type.calculate(\n distance=path,\n departure=(self.current_point == self.depot_point),\n )\n\n def score_path(self, p1: Point, p2: Point) -> float:\n return self.type.calculate(\n distance=self.problem.distance(p1, p2),\n loads=0\n )[1]\n\n # оценить затраты кроме перемещения\n def score_request(self, dr: 'Container') -> Tuple[float, float, float]:\n assert dr.point_type == 'container'\n return self.type.calculate(\n loads=1,\n load_time=dr.type_work_time\n ) # погрузки\n\n # расстояние до точки\n def dist_to(self, point: Point) -> float:\n return self.problem.distance(self.current_point, point)\n\n # обновить текущую статистику машины\n def update_stats(self, distance: float, duration: int, price: float) -> 'SimutationAgent':\n self.current_distance += distance\n self.current_price += price\n self.current_time += duration\n return self\n\n # Добавить группу точек. При недопустимых значениях будет брошено ValueError\n def add_containers(self, containers) -> 'SimutationAgent':\n for r in containers: # пытаемся добавить каждый реквест\n p = self.pickup_problems(r) # проверяем, что можем взять заявку\n if p: # проверяем, что можем взять заявку\n raise ValueError(p)\n else:\n self.take(r)\n return self\n\n def atomic_add_containers(self, containers: Iterable['Container']) -> 'SimutationAgent':\n SimutationAgent.copy_attrs(self, SimutationAgent.dummy_car)\n try:\n self.add_containers(containers)\n success = SimutationAgent._get_dummy()\n SimutationAgent.copy_attrs(self, success)\n self.goto_depot()\n SimutationAgent.copy_attrs(success, self)\n except ValueError as e:\n SimutationAgent.copy_attrs(SimutationAgent.dummy_car, self)\n raise e\n return self\n\n # проверяем возможность обработки заявок\n def can_process(self, containers: Iterable['Container']) -> bool:\n SimutationAgent.copy_attrs(self, SimutationAgent.dummy_car)\n try:\n self.add_containers(containers)\n self.goto_depot()\n return True\n except ValueError:\n return False\n finally:\n SimutationAgent.copy_attrs(SimutationAgent.dummy_car, self)\n\n # проверяем возможность обработки заявок\n def adding_problems(self, containers: Iterable['Container']) -> str:\n SimutationAgent.copy_attrs(self, SimutationAgent.dummy_car)\n try:\n self.add_containers(containers)\n self.goto_depot()\n return ''\n except ValueError as e:\n return str(e)\n finally:\n SimutationAgent.copy_attrs(SimutationAgent.dummy_car, self)\n\n def time_left(self) -> float:\n return (self.end_time - self.current_time) / 3600\n\n def is_bunker_car(self) -> bool:\n return self.type.operation_mode == OperationMode.BUNKER\n\n def is_portal_car(self) -> bool:\n return self.type.operation_mode == OperationMode.PORTAL\n\n def is_container_car(self) -> bool:\n return self.type.operation_mode == OperationMode.CONTAINER\n\n def can_take_containers(self) -> bool:\n return self.is_container_car() or self.is_portal_car()\n\n @property\n def start_point(self) -> 'Point':\n return self.way_points[0].point\n\n @property\n def current_point(self) -> 'Point':\n return self.way_points[-1].point\n\n def merge(self, other: 'SimutationAgent') -> 'SimutationAgent':\n \"\"\" Продолжение этой машины сливается в нее \"\"\"\n if len(self.way_points) < 2:\n return copy.deepcopy(other)\n\n if len(other.way_points) < 2:\n return copy.deepcopy(self)\n\n res_car = copy.deepcopy(self)\n if len(res_car.way_points) > 2 and res_car.current_point.point_type == 'depot':\n res_car.undo_depot() # отменяем последнее депо\n\n assert res_car.current_point == other.start_point, 'Пытаемся вмержить машину, находящуюся в другом месте'\n\n res_car.way_points += other.way_points[1:]\n res_car.containers += other.containers # TODO: зачем нам вообще containers? Мб удалить?\n\n res_car.current_distance += other.current_distance\n res_car.current_price += other.current_price\n res_car.is_active = other.is_active\n res_car.current_time = other.current_time\n\n return res_car\n\n def transform_to_empty(self) -> 'SimutationAgent':\n \"\"\"\n Получаем эту машину в этой точке и времени, но без посещейний и контейнеров\n Нужно для передачи в другие решалки с последуюшим мержем\n \"\"\"\n if not self.way_points or len(self.way_points) == 1:\n return self\n\n new_car: SimutationAgent = copy.deepcopy(self)\n new_car.way_points = self.way_points[-1:] # оставляем только последнюю\n new_car.containers = []\n\n new_car.start_time = new_car.way_points[0].time # Текущее время в секундах для машины\n new_car.current_time = new_car.start_time\n\n new_car.is_active = True # активна и только начала\n new_car.current_price = 0.0\n new_car.current_distance = 0.0\n\n return new_car\n\n def unmove(self) -> Tuple[float, float, float]:\n assert len(self.way_points) >= 2, 'Пытаемся отменить ход, который не сделали'\n\n removed_point, self.way_points = self.way_points[-1].point, self.way_points[:-1]\n\n stats = self.score_move(removed_point)\n self.update_stats(*(-s for s in stats))\n\n return stats\n\n def undo_depot(self):\n assert isinstance(self.current_point, Depot), 'Отменяем депо в которое мы не приехали'\n\n self.unmove()\n\n # def untake(self):\n # r_stats = self.score_request(con)\n # self.update_stats(*r_stats)\n #\n # m_stats = self.move_to(con)\n #\n # self.current_volume += con.capacity\n # self.current_weight += 0 # noqa (потом он будет)\n #\n # self.containers += [con]\n #\n # return tuple(sum(p) for p in zip(m_stats, r_stats))\n\n # превращает машину в словарь\n def export(self) -> Dict[str, Any]:\n return dict(\n id=self.id_,\n price=self.current_price,\n loads=len(self.containers),\n distance=self.current_distance / 1000, # км->метры\n disposal_requests=[dr.export() for dr in self.containers],\n way_points=tuple(wp.export() for wp in self.way_points),\n start_time=self.start_time,\n end_time=self.end_time,\n type_id=self.type_id,\n depot_point=self.depot_point.export(),\n driver_id=self.driver_id,\n )\n\n def create_depot_visit(self, time: int) -> Visit:\n return Visit(self.depot_point, time)\n\n # как будто ничего не было\n def clear_requests(self) -> 'SimutationAgent':\n\n self.containers = []\n\n self.is_active = True # в работе ли машина\n self.current_price = 0\n self.current_weight = 0 # текущая масса в машине\n self.current_volume = 0 # текущий объем без прессовки\n self.current_distance = 0 # пройденное расстояние на текущий момент\n self.current_time = self.start_time # Текущее время в секундах для машины\n\n self.way_points = [self.way_points[0]]\n\n return self\n\n def print_visits(self):\n res = str(self)\n res += '\\n'\n res += '-' * 20 + '\\n'\n\n for i, p in enumerate(self.way_points[:-1]):\n try:\n dist = self.problem.distance(self.way_points[i].point, self.way_points[i + 1].point)\n dist = round(dist / 1000, 1)\n except Exception:\n dist = 'Fail'\n res += str(self.way_points[i])\n res += f'->{dist}->'\n res += str(self.way_points[i + 1]) + '\\n'\n\n print(res)\n\n @staticmethod\n def _get_dummy() -> 'SimutationAgent':\n # noinspection Mypy\n return SimutationAgent(0, 0, None, None, Null(), None) # noqa\n\n\nSimutationAgent.dummy_car = SimutationAgent._get_dummy()\n","sub_path":"models/simulation/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":19819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"78216307","text":"process = 'ee_ZH_any'\n'''\nAdapted example\nExample configuration file for an ee->ZH analysis in the 4 jet channel,\nwith the FCC-ee\n\nWhile studying this file, open it in ipython as well as in your editor to \nget more information: \n\nipython\nfrom analysis_ee_ZH_had_cfg import * \n\n'''\nPTMIN = 8\nimport os\nimport sys\nimport copy\nimport heppy.framework.config as cfg\n\nfrom heppy.framework.event import Event\nEvent.print_patterns=['*jet*', 'bquarks', '*higgs*', \n '*zed*', '*lep*']\n\nimport logging\n# next 2 lines necessary to deal with reimports from ipython\nlogging.shutdown()\nreload(logging)\nlogging.basicConfig(level=logging.WARNING)\n\n# setting the random seed for reproducible results\nimport heppy.statistics.rrandom as random\nrandom.seed(0xdeadbeef)\n\n# definition of the collider\nfrom heppy.configuration import Collider\nCollider.BEAMS = 'ee'\nCollider.SQRTS = 240.\n\n# mode = 'pythia/ee_to_ZH_Oct30'\nmode = 'all'\nnfiles = None\n\nfrom fcc_datasets.fcc_component import FCCComponent\n\nzh = FCCComponent( \n 'pythia/ee_to_ZH_Oct30',\n splitFactor=4\n)\n\nfrom fcc_ee_higgs.components.tools import get_components\nselectedComponents = get_components(mode, [zh], nfiles)\n\n# read FCC EDM events from the input root file(s)\n# do help(Reader) for more information\nfrom heppy.analyzers.fcc.Reader import Reader\nsource = cfg.Analyzer(\n Reader,\n gen_particles = 'GenParticle',\n gen_vertices = 'GenVertex'\n)\n\n# gen bosons\nfrom fcc_ee_higgs.analyzers.GenResonanceAnalyzer import GenResonanceAnalyzer\ngen_bosons = cfg.Analyzer(\n GenResonanceAnalyzer,\n pdgids=[23, 25],\n statuses=[62],\n # decay_pdgids=[11, 13],\n verbose=False\n)\n\n\n# the papas simulation and reconstruction sequence\nfrom heppy.test.papas_cfg import papas, pfreconstruct, papas_sequence\n# from heppy.papas.detectors.FCCHiggsDetectors.config.cfg_CLIC import papas_sequence, detector, papas, gen_particles_stable\n# on Detector change, change ROC curve!!!!\nfrom heppy.papas.detectors.CLIC import clic as detector\npapas.detector = detector \npfreconstruct.detector = detector\n\n# write out partons from Z and H decays\n#from heppy.analyzers.mytest_PartonAnalyzer import PartonsFromZH\n##from fcc_ee_higgs.analyzers.qqbb.PartonAnalyzer import PartonsFromZH\n##partons = cfg.Analyzer(\n## PartonsFromZH,\n## partons = 'partons'\n##)\n\n# Use a Selector to select leptons from the output of papas simulation.\n# Currently, we're treating electrons and muons transparently.\n# we could use two different instances for the Selector module\n# to get separate collections of electrons and muons\n# help(Selector) for more information\nfrom heppy.analyzers.Selector import Selector\ndef is_lepton(ptc):\n return ptc.e()> 5. and abs(ptc.pdgid()) in [11, 13]\n\nleptons = cfg.Analyzer(\n Selector,\n 'sel_leptons',\n output = 'leptons',\n input_objects = 'rec_particles',\n #input_objects = 'gen_particles_stable',\n filter_func = is_lepton \n)\n\n# Compute lepton isolation w/r other particles in the event.\n# help(IsolationAnalyzer) \n# help(isolation) \n# for more information\nfrom heppy.analyzers.IsolationAnalyzer import IsolationAnalyzer\nfrom heppy.particles.isolation import EtaPhiCircle\niso_leptons = cfg.Analyzer(\n IsolationAnalyzer,\n candidates = 'leptons',\n particles = 'rec_particles',\n #particles = 'gen_particles_stable',\n iso_area = EtaPhiCircle(0.4)\n)\n\n# Select isolated leptons with a Selector\ndef is_isolated(lep):\n '''returns true if the particles around the lepton\n in the EtaPhiCircle defined above carry less than 30%\n of the lepton energy.'''\n return lep.iso.sume/lep.e()<0.3 # fairly loose\n\nsel_iso_leptons = cfg.Analyzer(\n Selector,\n 'sel_iso_leptons',\n output = 'sel_iso_leptons',\n input_objects = 'leptons',\n filter_func = is_isolated\n)\n\n# make inclusive jets with pt>10GeV\nfrom heppy.analyzers.fcc.JetClusterizer import JetClusterizer\njets_inclusive = cfg.Analyzer(\n ## Colin : inclusive jets\n JetClusterizer,\n output = 'jets_inclusive',\n particles = 'rec_particles',\n #particles = 'gen_particles_stable',\n fastjet_args = dict(R=0.4, p=-1, emin=5), ##Colin replaced by lower E cut\n)\n\n# make inclusive gen jets with stable gen particles\n##genjets = cfg.Analyzer(\n## ## Colin : inclusive jets, gen particles\n## JetClusterizer,\n## output = 'exgenjets',\n## particles = 'gen_particles_stable',\n## fastjet_args = dict(R=0.4, p=-1, emin=5),\n##)\n\n# count exclusive jets\n##from fcc_ee_higgs.analyzers.qqbb.JetCounter import JetCounter\n##jetcounter = cfg.Analyzer(\n## ### Colin : appends number of jets to the event\n## JetCounter,\n## input_jets = 'exjets',\n## njets = 'n_jets'\n##)\n\nfrom heppy.analyzers.EventFilter import EventFilter \njetcounter = cfg.Analyzer(\n EventFilter ,\n 'jetcounter',\n input_objects = 'jets_inclusive',\n min_number = 4,\n veto = False\n)\n\n##genjetcounter = cfg.Analyzer(\n## ### Colin : appends number of jets to the event\n## JetCounter,\n## input_jets = 'exgenjets',\n## njets = 'n_genjets'\n##)\n\n# make four exclusive jets\nfrom heppy.analyzers.fcc.JetClusterizer import JetClusterizer\njets_exclusive = cfg.Analyzer(\n JetClusterizer,\n output = 'jets',\n particles = 'rec_particles',\n #particles = 'gen_particles_stable',\n fastjet_args = dict(njets=4) \n)\n\n# make four inclusive gen jets with stable gen particles\n##inclgenjets = cfg.Analyzer(\n## ## Colin : same with gen \n## JetClusterizer,\n## output = 'genjets',\n## particles = 'gen_particles_stable',\n## fastjet_args = dict(njets=4) \n##)\n\n#reject Z decays into Leptons\n##from fcc_ee_higgs.analyzers.qqbb.RejectZLeptonic import RejectZLeptonic\n##reject_Z_leptonic = cfg.Analyzer(\n## ## Colin : does not reject, just keep track of number of particles\n## ## and number of charged hadrons\n## ## adds ljets to the event, but the same as jets\n## RejectZLeptonic,\n## input_jets = 'jets',\n## output_jets = 'ljets'\n##)\n\nfrom heppy.analyzers.Tagger import Tagger\njet_tagger = cfg.Analyzer(\n Tagger,\n input_objects='jets',\n tags = dict(\n n_constituents=lambda x: x.constituents.n_particles(),\n n_charged_hadrons=lambda x: x.constituents.n_charged_hadrons(),\n is_photon=lambda x: x.constituents[22].e()/x.e()>0.95\n )\n)\n\n# rescale the jet energy taking according to initial p4\nfrom fcc_ee_higgs.analyzers.qqbb.JetEnergyComputer import JetEnergyComputer\ncompute_jet_energy = cfg.Analyzer(\n ## Colin rescale the jets. looks like beta4\n ## warning: original jets probably modified\n JetEnergyComputer,\n output_jets='rescaled_jets',\n out_chi = 'chi2',\n input_jets='jets',\n sqrts=Collider.SQRTS\n)\n\n# select b quarks for jet to parton matching.\n##def is_outgoing_quark(ptc):\n## '''returns True if the particle is an outgoing b quark,\n## see\n## http://home.thep.lu.se/~torbjorn/pythia81html/ParticleProperties.html\n## '''\n## return abs(ptc.pdgid()) <= 6 and ptc.status() == 23\n## \n##outgoing_quarks = cfg.Analyzer(\n## Selector,\n## 'outgoing_quarks',\n## output = 'outgoing_quarks',\n## input_objects = 'gen_particles',\n## filter_func =is_outgoing_quark\n##)\n\n# match genjets to b quarks \n##from heppy.analyzers.Matcher import Matcher\n##genjet_to_b_match = cfg.Analyzer(\n## Matcher,\n## match_particles = 'outgoing_quarks',\n## particles = 'genjets',\n## delta_r = 0.4 #default 0.4\n## )\n\n# match jets to genjets (so jets are matched to b quarks through gen jets)\n##jet_to_genjet_match = cfg.Analyzer(\n## Matcher,\n## match_particles='genjets',\n## particles='rescaled_jets',\n## delta_r=0.5\n##)\n\n#Reject events that are compatible with a fully hadronic ZZ or WW decay\nfrom fcc_ee_higgs.analyzers.qqbb.FullHadCompatible import FullHadCompatible\nfullhadcompatible = cfg.Analyzer(\n FullHadCompatible,\n input_jets='rescaled_jets',\n output_jets='hjets',\n dWW = 'deltaWW',\n dZZ = 'deltaZZ',\n pair1_m = 'm12',\n pair2_m = 'm34'\n)\n\nfrom heppy.analyzers.ParametrizedBTagger import ParametrizedBTagger\nfrom heppy.analyzers.roc import ROC\nimport numpy as np\nclic_roc = ROC(\n np.array([\n [1e-9, 1e-9],\n [0.8, 4e-3]\n ])\n)\n\nclic_roc.set_working_point(0.8)\nbtag = cfg.Analyzer(\n ParametrizedBTagger,\n# input_jets='hjets',\n input_jets='jets',\n roc=clic_roc\n)\n\n# pt-dependend b tagging, also based on CMS-performance\n# different efficiencies for b, c and other quarks.\n##from fcc_ee_higgs.analyzers.qqbb.BTagger import BTagger\n##btag_pt = cfg.Analyzer(\n## BTagger,\n## input_jets = 'hjets',\n##)\n\nfrom heppy.analyzers.Selector import Selector\nbjets = cfg.Analyzer(\n Selector,\n 'bjets',\n output = 'bjets',\n input_objects = 'jets',\n filter_func = lambda jet: jet.tags['b']\n)\n\ntwo_bjets = cfg.Analyzer(\n EventFilter,\n 'two_bjets',\n input_objects='bjets',\n min_number=2,\n veto=False\n)\n\n# compute the missing 4-momentum\nfrom heppy.analyzers.RecoilBuilder import RecoilBuilder\nmissing_energy = cfg.Analyzer(\n RecoilBuilder,\n instance_label = 'missing_energy',\n output = 'missing_energy',\n sqrts = Collider.SQRTS,\n to_remove = 'rec_particles'\n #to_remove = 'gen_particles_stable'\n) \n\nfrom heppy.analyzers.P4SumBuilder import P4SumBuilder\nsum_vis = cfg.Analyzer(\n P4SumBuilder,\n output = 'sum_vis',\n particles = 'rec_particles',\n) \n\n\n\n#Find the Particle (H, Z, ...) from which the jets originate\n##from fcc_ee_higgs.analyzers.qqbb.AncestorSeeker import AncestorSeeker\n##ancestors = cfg.Analyzer(\n## AncestorSeeker,\n## input_jets = 'genjets'\n##)\n\n##from fcc_ee_higgs.analyzers.qqbb.MatchTransfer import MatchTransfer\n##matchtransfer = cfg.Analyzer(\n## MatchTransfer,\n## input_jets = 'hjets',\n## input_genjets = 'genjets'\n##)\n\n# reconstruction of the H and Z resonances.\n# for now, use for the Higgs the two b jets with the mass closest to mH\n# the other 2 jets are used for the Z.\n# implement a chi2? \nfrom fcc_ee_higgs.analyzers.qqbb.ZHReconstruction import ZHReconstruction\nzhreco = cfg.Analyzer(\n ZHReconstruction,\n output_higgs='higgs',\n output_zed='zed', \n input_jets='hjets',\n numberOfCandidates = 'n_candidates',\n higgsmass='higgsmass', #Ausgabe der Higgsmasse nach der Formel aus dem Paper\n mHJet = 'mHJet',\n mZedJet = 'mZedJet',\n anc1 = 'higgs_anc1',\n anc2 = 'higgs_anc2',\n log_level=logging.INFO \n)\n\n# simple cut flow printout\nfrom fcc_ee_higgs.analyzers.qqbb.FinalSelection import FinalSelection\nselection = cfg.Analyzer(\n FinalSelection,\n## njets = 'n_jets',\n## rawjets='jets',\n## # cutjets='cjets',\n## # leptonjets='ljets',\n## # massjets='ejets',\n## # hadjets='hjets',\n## input_jets='hjets', \n## vismass = 'vismass',\n## dWW = 'deltaWW',\n## dZZ = 'deltaZZ',\n## mHJet = 'mHJet',\n## mZedJet = 'mZedJet',\n## higgs='higgs',\n## higgsmass='higgsmass', \n## anc1 = 'higgs_anc1',\n## anc2 = 'higgs_anc2',\n## zed='zed',\n## leptons='sel_iso_leptons',\n## numberOfCandidates = 'n_candidates',\n## chi2 = 'chi2',\n log_level=logging.INFO\n)\n\nfrom fcc_ee_higgs.analyzers.qqbb.BaseSelection import BaseSelection\nbase_cut_flow = cfg.Analyzer(\n BaseSelection, \n log_level=logging.INFO\n)\n\n# Analysis-specific ntuple producer\n# please have a look at the ZHTreeProducer class\nfrom fcc_ee_higgs.analyzers.qqbb.QQBBTreeProducer import QQBBTreeProducer\ntree = cfg.Analyzer(\n QQBBTreeProducer,\n misenergy = 'missing_energy', \n rawjets='jets',\n# cutjets = 'cjets',\n leptonjets = 'ljets',\n massjets = 'ejets',\n rejets = 'rescaled_jets',\n chi2 = 'chi2',\n hadjets = 'hjets',\n genjets='genjets',\n vismass = 'vismass',\n dWW = 'deltaWW',\n dZZ = 'deltaZZ',\n pair1_m = 'm12',\n pair2_m = 'm34',\n mHJet = 'mHJet',\n mZedJet = 'mZedJet',\n higgs='higgs',\n higgsmass='higgsmass', \n anc1 = 'higgs_anc1',\n anc2 = 'higgs_anc2',\n zed='zed',\n leptons='sel_iso_leptons',\n numberOfCandidates = 'n_candidates',\n njets = 'n_jets',\n ngenjets = 'n_genjets'\n)\n\n# definition of the sequence of analyzers,\n# the analyzers will process each event in this order\nsequence = cfg.Sequence(\n source,\n gen_bosons, \n papas_sequence,\n #gen_particles_stable, # need to include this only if papas_sequence is excluded\n# partons,\n leptons,\n iso_leptons,\n sel_iso_leptons,\n# lepton_veto, \n# genjets, \n# genjetcounter,\n missing_energy,\n sum_vis, \n jets_inclusive,\n jetcounter,\n jets_exclusive,\n btag,\n bjets,\n# inclgenjets,\n# reject_Z_leptonic,\n jet_tagger, \n# reject_missing_nrg,\n compute_jet_energy, \n# outgoing_quarks,\n# genjet_to_b_match,\n# jet_to_genjet_match, \n# ancestors,\n base_cut_flow, \n two_bjets, \n fullhadcompatible,\n# btag_pt,\n# matchtransfer,\n zhreco, \n selection, \n tree\n)\n\n# Specifics to read FCC events \nfrom ROOT import gSystem\ngSystem.Load(\"libdatamodelDict\")\nfrom EventStore import EventStore as Events\n\nconfig = cfg.Config(\n components = selectedComponents,\n sequence = sequence,\n services = [],\n events_class = Events\n)\n","sub_path":"Old/analysis_ee_ZH_fourjet.py","file_name":"analysis_ee_ZH_fourjet.py","file_ext":"py","file_size_in_byte":13096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"114060124","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\n\n#The MIT License (MIT)\n#Copyright (c) 2015 Johan Fosse\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the Software is\n#furnished to do so, subject to the following conditions:\n\n#The above copyright notice and this permission notice shall be included in\n#all copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n#THE SOFTWARE.\n\n__author__ = \"Johan Fosse\"\n__version__ = 0.0\n__doc__ = \"\"\"\n\n#####NOT ACTIVE#######\n\n#Useful OpenGL functions for generating textures and vertex buffers\nthis is an extension of the draw module\n\ncontent included:\n\n-Texture (class)\n-create_vbo (function)\n-create_vertex_array (function)\n-CompileShader (function)\n-TEXTURES (cache index)\n\n\"\"\"\n\n#imports\nimport numpy\nimport math, random\nimport os, sys\nimport ctypes\nimport OpenGL\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\n############################ Shaders #########################################\n\ndefault_vertex_shader = \"\"\"\n#version 120\n\nin vec4 position;\nvoid main()\n{\n gl_Position = position;\n}\n\"\"\"\n\ndefault_fragment_shader = \"\"\"\n#version 120\n\nvoid main()\n{\n gl_FragColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);\n}\n\"\"\"\n\ndef compile_shader(name, vshader_src=default_vertex_shader, fshader_src=default_fragment_shader,\n bound_attribs=None):\n program = glCreateProgram()\n for kind, src, text in ((GL_VERTEX_SHADER, vshader_src, 'vertex'),\n (GL_FRAGMENT_SHADER, fshader_src, 'fragment')):\n if src:\n shader = glCreateShader(kind)\n glShaderSource(shader, [src])\n glCompileShader(shader)\n result = glGetShaderiv(shader, GL_COMPILE_STATUS)\n if not result:\n print ('%s shader %s compilation failed: %s'\n % (name, text, glGetShaderInfoLog(shader)))\n sys.exit(1)\n glAttachShader(program, shader)\n glDeleteShader(shader)\n for i, b in enumerate(bound_attribs or []):\n glBindAttribLocation(program, i + 1, b)\n glLinkProgram(program)\n glValidateProgram(program)\n print (glGetProgramInfoLog(program))\n return program\n\n################# Vertex Buffers #############################################\n\n\ndef create_vertex_array(pointlist):\n return numpy.array(pointlist, dtype=numpy.float32)\n\ndef create_vbo(shader, vertices):\n # Create a new VAO (Vertex Array Object) and bind it\n vertex_array_object = glGenVertexArrays(1)\n glBindVertexArray( vertex_array_object )\n\n \"\"\"vertex buffer\"\"\"\n # Generate buffers to hold our vertices\n vertex_buffer = glGenBuffers(1)\n glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)\n # Get the position of the 'position' in parameter of our shader and bind it.\n position = glGetAttribLocation(shader, 'position')\n glEnableVertexAttribArray(position)\n # Describe the position data layout in the buffer\n glVertexAttribPointer(position, 4, GL_FLOAT, False, 0, ctypes.c_void_p(0))\n # Send the data over to the buffer\n glBufferData(GL_ARRAY_BUFFER, len(vertices)*8, vertices, GL_STATIC_DRAW)\n\n # Unbind the VAO first (Important)\n glBindVertexArray( 0 )\n\n # Unbind other stuff\n glDisableVertexAttribArray(position)\n glBindBuffer(GL_ARRAY_BUFFER, 0)\n\n #return\n return vertex_array_object\n\ndef display(shader, vertex_array_object):\n glUseProgram(shader)\n\n glBindVertexArray( vertex_array_object )\n glDrawArrays(GL_TRIANGLES, 0, 3)\n glBindVertexArray( 0 )\n\n glUseProgram(0)\n\n return\n\n#################################### Textures ################################\n\nclass Texture(object):\n\n def __init__(self, filepath):\n \"\"\" Generate a texture for screen drawing \"\"\"\n\n\n##############################################################################\n\nif __name__ == \"__main__\":\n shader = compile_shader(\"test\")\n print(shader)\n","sub_path":"RitzCore/gl.py","file_name":"gl.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"646321858","text":"def viktorina():\n d = {\n 'Роберт Рождественский': [['20', '06', '1932'], 'двадцатого июня 1932 года'],\n 'Лев Толстой': [['28', '08', '1828'], 'двадцать восьмого августа 1828 года'],\n 'Антон Чехов': [['17', '01', '1860'], 'семьнадцатого января 1860 года'],\n 'Сергей Есенин': [['21', '09', '1895'], 'двадцать первого января 1895 года'],\n 'Владимир Высоцкий': [['25', '01', '1938'], 'двадцать пятого января 1938 года']}\n\n # print(d.keys(), '\\n', d['Лев Толстой'][0], d['Лев Толстой'][1])\n\n def vopros(d):\n mistake = 0\n for person in d.keys():\n print('Введите дату рождения ', person)\n ans = input()\n ans = ans.split('.')\n if ans[0] != d[person][0][0] or ans[1] != d[person][0][1] or ans[2] != d[person][0][2]:\n print(d['Лев Толстой'][1])\n mistake += 1\n\n print('Количество ошибок: ', mistake)\n print('Количество правильных ответов: ', len(d.keys()) - mistake)\n print('Доля правильных ответов: ', (len(d.keys()) - mistake) / len(d.keys()))\n\n vopros(d)","sub_path":"lesson_5/ultrapro/viktorina.py","file_name":"viktorina.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"81524796","text":"from analizer.statement.expressions.primitive import Primitive\nfrom analizer.abstract import instruction\nimport analizer.symbol.c3dSymbols as SymbolTable\nfrom analizer.statement.functions.call import FunctionCall\nfrom analizer.statement.expressions.identifiers import Identifiers\nfrom analizer.abstract.expression import TYPE\nfrom analizer.statement.pl.instruccionesF1 import F1\nfrom analizer.reports.Nodo import Nodo\nfrom analizer.reports.AST import AST\nimport analizer.symbol.c3dSymbols as SymbolTable\nfrom analizer.abstract import expression\n\nclass Asignacion(instruction.Instruction):\n def __init__(self, identificador, expresion, row , column):\n instruction.Instruction.__init__(self, row , column)\n self.identificador = identificador\n self.expresion = expresion\n self.classType=str(self.expresion.__class__.__name__).casefold()\n \n def generate3d(self, environment, instanciaAux):\n name = None\n try:\n name,tipo,value = SymbolTable.search_symbol(self.identificador)\n except:\n instruction.semanticErrors.append(\n ( \"ERROR: con variable '%s' en asignacion\" %self.identificador,self.row)\n )\n if name != None:\n newTemp = self.expresion.generate3d(environment,instanciaAux)\n instanciaAux.addToCode(f'\\t{self.identificador} = {newTemp}')\n \n def dot(self):\n nuevo_nodo = Nodo(\"ASIGNACION\")\n identificador = Nodo(\"ID\")\n expresion = Nodo(\"EXPRESION\")\n id = Nodo(self.identificador)\n identificador.addNode(id)\n expresion.addNode(self.expresion.dot())\n nuevo_nodo.addNode(identificador)\n nuevo_nodo.addNode(expresion)\n return nuevo_nodo ","sub_path":"parser/fase2/team25/analizer/statement/pl/asignacion.py","file_name":"asignacion.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"63658077","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nPHI = 1.6180339887499\nPSI = -0.61803398871499\nREVERSE_SQUARE_ROOT_FIVE = 0.447213595499958\n\n\ndef fibonacci_number(n):\n return (PHI**n - PSI**n)*REVERSE_SQUARE_ROOT_FIVE\n\n\ndef fibonacci(goal_function, a, b, epsilon):\n x = 0\n n = 100\n\n while (b - a) > epsilon or n != 1:\n lamda = a + (b - a)*(fibonacci_number(n-2)/fibonacci_number(n))\n mu = a + (b - a)*(fibonacci_number(n-1)/fibonacci_number(n))\n\n if goal_function(lamda) <= goal_function(mu):\n b = mu\n x = lamda\n else:\n a = lamda\n x = mu\n\n n -= 1\n\n if n == 1:\n return (mu + lamda) / 2\n\n return x\n\nif __name__ == \"__main__\":\n goal_function = lambda x: x**4-4*x**2-4*x+1\n\n epsilon = 0.00001\n delta = epsilon / 1000\n a = -10\n b = 10\n n = 100\n\n x_min_fibonacci = fibonacci(goal_function, a, b, epsilon)\n \n # print(x_min_fibonacci)\n def draw(goal_function, a, b, x_min):\n x = np.linspace(a, b, 100)\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n\n # Move left y-axis and bottim x-axis to centre, passing through (0,0)\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n\n # Eliminate upper and right axes\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n\n # Show ticks in the left and lower axes only\n ax.xaxis.set_ticks_position('bottom')\n ax.yaxis.set_ticks_position('left')\n\n plt.plot(x, goal_function(x), color=\"violet\")\n plt.plot([x_min], [goal_function(x_min)], marker='s', markersize=8, color=\"red\", label=\"fibonacci\")\n plt.title(\"Minimum of F(x) by dichotomy method\")\n plt.legend()\n plt.show()\n draw(goal_function, a, b, x_min_fibonacci)","sub_path":"unconstrained_optimization/single_variable/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"32941196","text":"import os\nimport pandas as pd\nfrom flask import Flask, request, render_template,Response\nfrom flask_cors import cross_origin,CORS\nimport ReadData\nfrom DataSplitting import DataSplitting\nfrom Training_Data_Traonsfrmation import Preprocessing\nimport numpy as np\nfrom ModelFinder.finder import ModelFinder\nfrom predictionGetData import Data_Getter_Pred\nfrom PredictFromModel import prediction\nfrom wsgiref import simple_server\n\napp = Flask(__name__)\n\n@app.route('/',methods=['GET'])\n@cross_origin()\ndef home():\n return render_template('index.html')\n\n@app.route('/predict',methods=['POST'])\n@cross_origin()\ndef predict():\n try:\n if request.form is not None:\n path=request.form['filepath']\n data_obj=Data_Getter_Pred(path)\n data=data_obj.get_data()\n preprocess = Preprocessing.Preprocessor()\n X = preprocess.removeExtraSpace(data)\n columns_with_null_values, is_null_present = preprocess.columnsWithMissingVlaue(X)\n if (is_null_present):\n X = preprocess.imputeMissingValue(columns_with_null_values,X)\n preprocess.removeUnwantedFeatures(X, ['education'])\n X = preprocess.computeOutliars(X, 'fnlwgt')\n X = preprocess.outliarsCompute(X, 'hours-per-week')\n df_numeric = preprocess.scaleDownNumericFeatures(X)\n df_category = preprocess.encodeCategoryFeatures(X)\n df = pd.concat([df_numeric, df_category], axis=1)\n predict=prediction()\n path=predict.predict_results(df)\n #path=predict.predict_results(df)\n path=pd.concat([data, path], axis=1)\n #path.to_html(\"Table.htm\")\n html_file =path.to_html()\n return Response(html_file)\n\n except ValueError:\n return Response(\"Error Occurred! %s\" %ValueError)\n #print(\"Error Occurred! %s\" %ValueError)\n except KeyError:\n return Response(\"Error Occurred! %s\" %KeyError)\n #print((\"Error Occurred! %s\" %KeyError))\n except Exception as e:\n return Response(\"Error Occurred! %s\" %e)\n #print((\"Error Occurred! %s\" %e))\n\n\n\n\n@app.route('/train',methods=['POST'])\n@cross_origin()\ndef train_predict():\n try:\n readdataobj = ReadData.ReadData()\n data=readdataobj.readData()\n '''datasplitobj=DataSplitting(data)\n X_train, X_test, y_train, y_test = datasplitobj.split_data()'''\n\n preprocess=Preprocessing.Preprocessor()\n data=preprocess.removeExtraSpace(data)\n X, y = preprocess.seperateDependentIndependentColumns(data)\n y=y.map({'<=50K':0,'>50K':1})\n columns_with_null_values , is_null_present=preprocess.columnsWithMissingVlaue(X)\n if(is_null_present):\n X=preprocess.imputeMissingValue(columns_with_null_values,X)\n preprocess.removeUnwantedFeatures(X , ['education'])\n X = preprocess.computeOutliars(X, 'fnlwgt')\n X = preprocess.outliarsCompute(X, 'hours-per-week')\n df_numeric=preprocess.scaleDownNumericFeatures(X)\n df_category=preprocess.encodeCategoryFeatures(X)\n \n df=pd.concat([df_numeric,df_category], axis=1)\n X,y = preprocess.handleImbalancedDataSet(df,y)\n split_data = DataSplitting()\n X_train, X_test, y_train, y_test = split_data.split_data(X,y)\n \n modelfinder=ModelFinder()\n return modelfinder.get_best_model(X_train, X_test, y_train, y_test)\n\n\n except ValueError:\n print(\"Value error occurred %s\" %ValueError)\n\n except KeyError:\n print(\"Key error occurred %s\" %KeyError)\n\n except Exception as e:\n print(\"Error Occurred while training %s\" %e)\n\n\n\nif __name__=='__main__':\n app.run(debug=True,threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"214000396","text":"# import necessary packages\nimport numpy as np\nimport os\nfrom matplotlib import pyplot\n\n# import files\nimport config\n\ndef main():\n ''' Main function. '''\n\n # pie charts\n # pies = [('rede5_media5', ['Rede, 5%', 'Média, 5%'], [1, 4], [1, 4], ['C0', 'C2']),\n # ('rede5_media5_off', ['Rede, 5%', 'Média, 5%', 'Nenhum'], [0, 0, 1], [1, 0, 0], ['C0', 'C2', 'C7']),\n # ('rede20_media20', ['Rede, 20%', 'Média, 20%'], [2, 2], [0, 4], ['C1', 'C3']),\n # ('rede5_rede20', ['Rede, 5%', 'Rede, 20%'], [1, 1], [0, 2], ['C0', 'C1']),\n # ('media5_media20', ['Média, 5%', 'Média, 20%'], [0, 1], [0, 1], ['C2', 'C3']),\n # ('media5_media20_off', ['Média, 5%', 'Média, 20%', 'Nenhum'], [0, 1, 0], [0, 0, 1], ['C2', 'C3', 'C7'])]\n pies = [('rede5_media5', ['R5', 'M5'], [1, 4], [1, 4], ['C0', 'C2']),\n ('rede5_media5_off', ['R5', 'M5', 'D'], [0, 0, 1], [1, 0, 0], ['C0', 'C2', 'C7']),\n ('rede20_media20', ['R20', 'M20'], [2, 2], [0, 4], ['C1', 'C3']),\n ('rede5_rede20', ['R5', 'R20'], [1, 1], [0, 2], ['C0', 'C1']),\n ('media5_media20', ['M5', 'M20'], [0, 1], [0, 1], ['C2', 'C3']),\n ('media5_media20_off', ['M5', 'M20', 'D'], [0, 1, 0], [0, 0, 1], ['C2', 'C3', 'C7'])]\n\n # plot the pie charts\n for fname, labels, sizesp, sizeso, colors in pies:\n\n # save the image plots\n fig, (ax1, ax2) = pyplot.subplots(nrows=1, ncols=2, figsize=config.figsizeg, subplot_kw=dict(aspect=\"equal\"))\n fig.suptitle(f'Preferências | {\" vs. \".join(labels)}', x=0.5, y=0.95)\n wedges, texts = ax1.pie(sizesp, labels=labels, shadow=True, colors=colors,\n wedgeprops=dict(width=0.9), labeldistance=1.2, startangle=0)\n for size, text in zip(sizesp, texts):\n if size != 0:\n text.set_text(f'{text.get_text()}\\n{size} pessoa{\"\" if size == 1 else \"s\"}')\n # text.set_text(f'{text.get_text()}')\n # text.set_text(f'{text.get_text()} – {size}')\n pyplot.setp(text, size=10, weight=\"bold\")\n else:\n pyplot.setp(text, alpha=0.0)\n ax1.set_title('Prédio', x=0.5, y=1.05)\n wedges, texts = ax2.pie(sizeso, labels=labels, shadow=True, colors=colors,\n wedgeprops=dict(width=0.9), labeldistance=1.2, startangle=0)\n for size, text in zip(sizeso, texts):\n if size != 0:\n text.set_text(f'{text.get_text()}\\n{size} pessoa{\"\" if size == 1 else \"s\"}')\n # text.set_text(f'{text.get_text()}')\n # text.set_text(f'{text.get_text()} – {size}')\n pyplot.setp(text, size=10, weight=\"bold\")\n else:\n pyplot.setp(text, alpha=0.0)\n ax2.legend(wedges, labels,\n title=\"Método\",\n loc=\"center\",\n bbox_to_anchor=(1.0, 0, 0.5, 1))\n ax2.set_title('Oito', x=0.5, y=1.05)\n pyplot.subplots_adjust(wspace=0.4)\n pyplot.savefig(os.path.join('results', f'pie_gold_{fname}.png'), bbox_inches='tight')\n\n# if it is the main file\nif __name__ == '__main__':\n main()\n","sub_path":"pie.py","file_name":"pie.py","file_ext":"py","file_size_in_byte":3292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"108067924","text":"#!/usr/bin/env python\n\nimport logging\nimport re\nimport socket\nimport requests\n\nfrom flask import Flask, jsonify, request\n\nlogPath = \"/tmp/flasklog\"\n\nMyHostName = socket.gethostname()\nMyResolvedName = socket.gethostbyname(socket.gethostname())\n\nlogging.basicConfig(\n filename=logPath,\n level=logging.DEBUG, # if appDebug else logging.INFO,\n format=\"%(asctime)s ambassador-sds 0.0.1 %(levelname)s: %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\n\nlogging.info(\"ambassador-sds initializing on %s (resolved %s)\" % (MyHostName, MyResolvedName))\n\nTOKEN = open(\"/var/run/secrets/kubernetes.io/serviceaccount/token\", \"r\").read()\nENDPOINT_URL_TEMPLATE = \"https://kubernetes/api/v1/namespaces/default/endpoints/%s\"\nENDPOINTS = {}\n\nSERVICE_RE = re.compile(r'^[a-z0-9-_]+$')\n\napp = Flask(__name__)\n\n@app.route('/v1/registration/', methods=[ 'GET' ])\ndef handle_endpoint(service_name):\n if not SERVICE_RE.match(service_name):\n return \"invalid service name '%s'\" % service_name, 503\n\n url = ENDPOINT_URL_TEMPLATE % service_name\n\n r = requests.get(url, headers={\"Authorization\": \"Bearer \" + TOKEN}, verify=False)\n\n if r.status_code != 200:\n return jsonify({ \"hosts\": [] })\n\n endpoints = r.json()\n\n hostdicts = []\n ports = []\n\n subsets = endpoints.get(\"subsets\", [])\n\n for subset in subsets:\n for portdef in subset.get(\"ports\", []):\n if ((portdef['protocol'] == 'TCP') and\n (('name' not in portdef) or\n (portdef['name'] == service_name))):\n ports.append(portdef['port'])\n\n for addrdef in subset.get(\"addresses\", []):\n if \"ip\" in addrdef:\n for port in ports:\n hostdicts.append({\n \"ip_address\": addrdef[\"ip\"],\n \"port\": port,\n \"tags\": {}\n })\n\n return jsonify({ \"hosts\": hostdicts })\n\n@app.route('/v1/health')\ndef root():\n return jsonify({ \"ok\": True, \"msg\": \"SDS healthy!\" })\n\ndef main():\n app.run(host='0.0.0.0', port=5000, debug=True)\n\nif __name__ == '__main__':\n main()\n","sub_path":"sds/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"433889489","text":"import math\n\n\ndef is_prime(num):\n prime = True\n if num < 2:\n return False\n\n for i in range(2, int(math.sqrt(num) + 1)):\n if num % i == 0:\n return False\n\n return prime\n\n\ndef truncate_prime(digits, left):\n truncate_digits = digits.copy()\n if len(truncate_digits) == 0:\n return True\n\n if left:\n num = digits_to_string(truncate_digits)\n\n if not is_prime(int(num)):\n return False\n else:\n del truncate_digits[0]\n return truncate_prime(truncate_digits, left)\n else:\n num = digits_to_string(truncate_digits)\n\n if not is_prime(int(num)):\n return False\n else:\n del truncate_digits[len(truncate_digits) - 1]\n return truncate_prime(truncate_digits, left)\n\n\ndef get_digit_list(num):\n num_string = str(num)\n digits = []\n\n for i in range(len(num_string)):\n digits.append(int(num_string[i]))\n\n return digits\n\n\ndef digits_to_string(digits):\n string = \"\"\n for i in range(len(digits)):\n string = string + str(digits[i])\n\n return string\n\n\ndef sum_list(nums):\n sum = 0\n for i in range(len(nums)):\n sum = sum + nums[i]\n return sum\n\n\ndef get_truncatable_primes(limit):\n truncatable_primes = []\n for i in range(10, limit):\n digits = get_digit_list(i)\n if truncate_prime(digits, True):\n if truncate_prime(digits, False):\n truncatable_primes.append(i)\n\n return truncatable_primes\n\n\ntruncatable_prime_list = get_truncatable_primes(1000000)\nprint(truncatable_prime_list)\nprint(len(truncatable_prime_list))\nsum_truncatable_primes = sum_list(truncatable_prime_list)\nprint(sum_truncatable_primes)\n","sub_path":"euler/problem37.py","file_name":"problem37.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"629548525","text":"expected_output = {\n 'nve1': {\n 'nve_name': 'nve1',\n 'if_state': 'up',\n 'encap_type': 'vxlan',\n 'vpc_capability': 'vpc-only [not-notified]',\n 'local_rmac': 'abcd.ef12.3456',\n 'host_reach_mode': 'control-plane',\n 'source_if': 'loopback1',\n 'primary_ip': '90:90:90::3',\n 'secondary_ip': '0.0.0.0',\n 'src_if_state': 'up',\n 'ir_cap_mode': 'no',\n 'adv_vmac': False,\n 'nve_flags': '',\n 'nve_if_handle': 1224736769,\n 'src_if_holddown_tm': 180,\n 'src_if_holdup_tm': 30,\n 'src_if_holddown_left': 0,\n 'vip_rmac': 'N/A',\n 'sm_state': 'nve-intf-add-complete',\n 'peer_forwarding_mode': False,\n 'dwn_strm_vni_cfg_mode': 'n/a',\n 'src_intf_last_reinit_notify_type': 'none',\n 'mcast_src_intf_last_reinit_notify_type': 'none',\n 'multi_src_intf_last_reinit_notify_type': 'none'\n }\n}","sub_path":"src/genie/libs/parser/nxos/tests/ShowNveInterfaceDetail/cli/equal/golden_output3_expected.py","file_name":"golden_output3_expected.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"211614007","text":"# Location of the encoded lyrics\nfilePath = r\"03_Flow_Control\\performance_labs\\lab3B\\file.txt\"\n\n# With statement to open the file as file\nwith open(filePath, \"r\") as file:\n # Read the file\n text = file.readline()\n # Initialize a string accumulator\n newText = \"\"\n # For each character, get the ordinal, XOR 27 it, then convert back to a character and add to accumulator\n for char in text:\n newText += (chr(ord(char)^27))\n # Print result\n print(newText)","sub_path":"lab3b.py","file_name":"lab3b.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"145711085","text":"import os\nimport csv\n\nwith open('boards.csv', 'r') as csvfile:\n fieldnames = ['problem', 'fen']\n csvreader = csv.DictReader(csvfile, fieldnames=fieldnames)\n\n for row in csvreader:\n print(row['fen'], row['problem'])\n os.system(\"./fen2image -fen \\\"{}\\\" -output \\\"recognized/problem-{}.png\\\"\".format(row['fen'], row['problem']))\n","sub_path":"generate-recognized.py","file_name":"generate-recognized.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"447027511","text":"\"\"\"\nUrl pattern for projectbudgegt application\n\"\"\"\n\nfrom django.conf.urls.defaults import patterns\nfrom django.views.generic.simple import direct_to_template, redirect_to\n\nurlpatterns = patterns('project_management.alert.views', \n (r'^list/$', 'list'),\n (r'^edit/(?P\\w+\\d+)/$', 'edit'),\n (r'^save/$', 'save'),\n (r'^preview/$', 'preview'),\n (r'^payitstatus/$', 'pay_it_status'),\n (r'^payitstatus_xl/$', 'pay_it_status_days_genrte'),\n (r'^payitstatus_hours/$', 'pay_it_status_hours_genrte'),\n (r'^activate/$', 'alert_status',{'status': True}, \"activate-alert\"),\n (r'^deactivate/$', 'alert_status',{'status': False}, \"deactivate-alert\")\n #(r'^get_perms/$', 'get_perms'),\n)\n","sub_path":"project_management/alert/urls2.py","file_name":"urls2.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"632271727","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'seokjin.seo '\n\nimport unittest\nimport random\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\n\ndef waitUntilElementToBeLoaded(self, xpath):\n element = WebDriverWait(self.driver,self.waittime).until(EC.presence_of_element_located((By.XPATH,xpath)))\n return element\n\ndef waitUntilElementsToBeLoaded(self, xpath):\n element = WebDriverWait(self.driver,self.waittime).until(EC.presence_of_all_elements_located((By.XPATH,xpath)))\n return element\n\ndef functionC006(self):\n self.driver.get(self.baseUrl+'/customer/account/login')\n self.driver.find_element_by_name('login[username]').send_keys('seokjin.seo@linkshops.com')\n self.driver.find_element_by_name('login[password]').send_keys('tjrwls1234')\n self.driver.find_element_by_name('send').click()\n self.driver.find_element_by_id('wp_custom_menu_10').click()\n waitUntilElementsToBeLoaded(self,\"//div[contains(@class,'filterOption colorchip')]/a[@href = '#']\")\n colorPicker = self.driver.find_elements_by_xpath(\"//div[contains(@class,'filterOption colorchip')]/a[@href = '#']\")\n randNum = random.randrange(0,len(colorPicker)-1)\n productColor = colorPicker[randNum].get_attribute(\"data-option-id\")\n colorPicker[randNum].click()\n waitUntilElementsToBeLoaded(self,\"//div[contains(@class,'filterOption')]/button[contains(@class,'productOption')]\")\n sizePicker = self.driver.find_elements_by_xpath(\"//div[contains(@class,'filterOption')]/button[contains(@class,'productOption')]\")\n if len(sizePicker) == 1:\n randNum = 0\n else:\n randNum = random.randrange(0,len(sizePicker)-1)\n sizeInform = sizePicker[randNum].get_attribute(\"data-option-id\")\n sizePicker[randNum].click()\n waitUntilElementsToBeLoaded(self,'//div[contains(@class,\"product template_category col-lg-2 col-md-3 col-sm-4 col-xs-6\")]')\n soldOutNum = len(self.driver.find_elements_by_class_name('soldout'))\n assert len(self.driver.find_elements_by_xpath('//div[contains(@class,\"product template_category col-lg-2 col-md-3 col-sm-4 col-xs-6\")]')) == len(self.driver.find_elements_by_xpath(\"//div[contains(@class,'productColor productColor_\" + productColor +\"')]\")) - 1 + soldOutNum\n assert len(self.driver.find_elements_by_xpath('//div[contains(@class,\"product template_category col-lg-2 col-md-3 col-sm-4 col-xs-6\")]')) == len(self.driver.find_elements_by_xpath(\"//button[contains(@class,'btn btn-xs productOption option_\" + sizeInform +\"')]\")) - 1 + soldOutNum\n self.driver.find_element_by_class_name(\"bt_clear\").click()\n waitUntilElementToBeLoaded(self, \"//li[contains(@id,'wp_custom_menu_10')]\")\n assert self.driver.current_url.find('/new-arrivals')\n\n\n\nclass C006 (unittest.TestCase):\n waittime = 15\n \n def __init__(self, methodName='runTest', drive=None, base_url=\"http://dev.linkshops.com\"):\n unittest.TestCase.__init__(self, methodName)\n self.baseUrl = base_url\n self.drive = drive\n\n def setUp(self):\n if self.drive is not None:\n self.driver = self.drive.get_drive()\n else:\n self.driver = webdriver.Firefox(firefox_profile=webdriver.FirefoxProfile())\n self.driver.get(self.baseUrl)\n\n def tearDown(self):\n self.driver.close()\n\n def test_C006(self):\n functionC006(self)\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/Category/C006.py","file_name":"C006.py","file_ext":"py","file_size_in_byte":3586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"634877821","text":"import random\nfrom rpg_fortune import roll_a_dice\n\n\nclass Monster:\n\n def __init__(self):\n self.attack = 20 + roll_a_dice(100)\n self.defense = 20 + roll_a_dice(100)\n self.damage = 20 + roll_a_dice(100)\n self.hp = roll_a_dice(100)\n self.xp = 110\n\n def dic(self):\n uglyGreenBastard = {'attack': self.attack,\n 'defense': self.defense,\n 'damage': self.damage,\n 'HP': self.hp,\n 'XP': self.xp}\n return uglyGreenBastard\n\n @property\n def enemy(self):\n monster_stats = {}\n monster_spawn = roll_a_dice(8)\n\n if monster_spawn == 1 or monster_spawn == 4 or monster_spawn == 7:\n monster_stats['magic_attack'] = self.attack\n monster_stats['magic_defense'] = self.defense\n\n if monster_spawn == 2 or monster_spawn == 3:\n monster_stats['ranged_attack'] = self.attack\n monster_stats['ranged_defense'] = self.defense\n\n if monster_spawn == 5 or monster_spawn == 6 or monster_spawn == 8:\n monster_stats['melee_attack'] = self.attack\n monster_stats['melee_defense'] = self.defense\n\n monster_stats['damage'] = self.damage\n monster_stats['hp'] = self.hp\n monster_stats['xp'] = self.xp\n\n return monster_stats\n\n\ndef monstersOnBoard(horiz, vert, qty):\n monster_list = []\n while len(monster_list) < qty:\n x = random.randint(0, vert - 2)\n y = random.randint(0, horiz - 2)\n monster_list.append((x, y))\n return monster_list\n\n\nif __name__ == \"__main__\":\n \"__main__\"\n","sub_path":"rpg_class_Monster.py","file_name":"rpg_class_Monster.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"473537753","text":"import keras\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom PIL import Image\n\n# output of the last layer\noutputs = 2\nimg_height, img_width = 64, 64\n\n# sample model composition\ndef sampleModel():\n model = Sequential()\n # Conv2D: convolutional layer with 2 dimentions\n # Conv1D => 1 dimention is used for linear convolution such as time\n # Conv2D => for spatial convolution\n model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=(img_height, img_width, 3)))\n # filters => the amount of filters(kernels)\n # kernel_size => the size of filter(kernel)\n # stride => the value of stride of kernel(this time dose not use stride)\n # padding => the value of padding of input\n # activation => the activation function to utilize\n # input_shape => the shape of input?\n model.add(Conv2D(32, (3, 3), padding='same', activation='relu'))\n # extracting hightly featured points\n # the difference between 1D and 2D is the same logic as Conv1D and Conv2D\n model.add(MaxPooling2D(pool_size=(2,2)))\n # to avoid overfitting\n # the ratio how much cut the output\n model.add(Dropout(0.25))\n\n # repeating the same thing in the second layer as well\n # however, the filter amount is changed\n # is this normal to change amount of kernels in the second layer?\n model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n # flatten the input => does not make sense...\n model.add(Flatten())\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.5))\n # dense layer = fully connected layer\n # the amount of outpus\n model.add(Dense(outputs))\n # Activation adapts activation function to the output\n model.add(Activation('softmax'))\n\n return model\n\n\nmodel = sampleModel()\nmodel.summary()\n\nfor layer in model.layers:\n print(layer) # returns keras.layers objects\n # trainable true is what? https://keras.io/ja/getting-started/faq/\n layer.trainable = True\n\n# ImageDataGenerator https://keras.io/ja/preprocessing/image/\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255, # normalizing the pixel value\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n featurewise_center=True,\n featurewise_std_normalization=True,\n zca_whitening=True\n)\ntest_datagen = ImageDataGenerator(\n rescale=1. / 255,\n featurewise_center=True,\n featurewise_std_normalization=True,\n zca_whitening=True\n)\n\n# pass the data to ImageDataGenerator\ntrain_generator = train_datagen.flow_from_directory(\n 'Images/Train/', # where dataset is\n target_size=(img_height, img_width),\n batch_size=30,\n class_mode='categorical'\n)\nvalidation_generator = test_datagen.flow_from_directory(\n 'Images/Test/', # where dataset is\n target_size=(img_height, img_width),\n batch_size=1,\n class_mode='categorical'\n)\n# key: flow_from_directory, target_size, batch_size, class_mode\n\n# cofiguration for training\nhistory = model.fit_generator(\n train_generator,\n steps_for_epoch=50,\n epochs=100,\n validation_data=validation_generator,\n validation_steps=50\n)\n# key: fit_generator\n\n# save the model\nmodel.save('training_network.h5')\n\n#####################################################\n\n# test\nmodel = sampleModel()\nmodel.load_weights('training_network.h5')\n\nfile_path = ''\nimg = Image.open(file_path).convert('RGB')\nimg = img.resize((img_width, img_height))\nx = np.array(img, dtype=np.float32)\nx = x / 255.\nx = x[None, ...]\n\n# modelAPI https://keras.io/ja/models/model/#modelapi\nprediction = model.predict(x, batch_size=1, verbose=0)\nscore = np.max(prediction) # returns the maximun num\nprediction_label = np.maxarg(prediction) # returns the first index of the maximum num\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"439746555","text":"from flask import Blueprint, request\n\nfrom api.api import api_root\nfrom selenium import webdriver\nfrom api.scrape import linkedin_login\nfrom scraper.interface.candidate import Candidate\nfrom clustering.knn_probability import KNNProbabilityCalculator\nfrom clustering.similarity import similarity_metric, candidates_to_metrics\nimport json\n\ncluster_root = Blueprint('cluster', __name__, url_prefix=\"{}/cluster\".format(api_root.url_prefix))\n\n\n@cluster_root.route('/', methods=['POST'])\ndef recalculate_clustering():\n # get user resource\n\n data = request.get_json()\n username = data[\"username\"]\n password = data[\"password\"]\n link = data[\"link\"]\n\n # person to do comparison on\n driver = webdriver.Chrome()\n linkedin_login(driver, username, password)\n print('Scraping: {}'.format(link))\n candidate = Candidate(link, driver=driver, scrape=False)\n candidate.scrape(close_on_complete=False)\n\n experience = candidate.experiences[0] if candidate.experiences else None\n education = candidate.educations[0] if candidate.educations else None\n\n entry = [{\n 'name': candidate.name,\n 'job_title': experience.position_title if experience else None,\n 'company': experience.institution_name if experience else None,\n 'college': education.institution_name if education else None,\n 'location': experience.location if experience else None,\n }]\n\n seed1 = []\n labels1 = []\n with open('../files/praetorian.txt','r') as f:\n candidates_good = json.load(f)\n seed1 = candidates_to_metrics(candidates_good)\n seed2 = []\n labels1 = [0]*len(seed1)\n with open('../files/known_bad.txt', 'r') as f:\n candidates_bad = json.load(f)\n seed2 = candidates_to_metrics(candidates_bad)\n seed1.extend(seed2)\n labels1.extend([1]*len(seed2))\n all_users = candidates_to_metrics(entry)\n print(seed1)\n print(labels1)\n probability_calculator = KNNProbabilityCalculator(seed1,\n labels1,\n similarity_fn=similarity_metric)\n\n ret = []\n for (user, probability) in zip(all_users, probability_calculator.probability(all_users)):\n # update db for user probability\n ret.append({\"user\":link, \"prob\":probability})\n\n return json.dumps(ret)\n","sub_path":"web/api/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"267304617","text":"from tkinter import *\nfrom tkinter import filedialog\nimport speech_recognition as root\nimport tkinter as tk\n\nwindow = Tk()\nwindow.title(\"Speech_Recognition\")\n#window.configure(background='black')\n#window.geometry('600*500')\nl1=Label(window, text=\"Result\")\nl1.grid(row=1,column=3)\n11\ndef record():\n capture=sr.Recognizer()\n with root.Microphone() as source:\n print(\"ready\")\n audio=capture.listen(source)\n print(\"wait\")\n\n with open('audio.wav','wb') as f:\n f.write(audio.get_wav_data())\n #print(\"done\")\n text.insert(tk.INSERT,'Done')\n\nb2=Button(window,text=\"Record\",width=12,command=record)\nb2.grid(row=5,column=2)\n\ntext=tk.Text(window,height=8,width=30)\ntext.grid(row=1,column=2)\ntext.config(state='normal')\ndef audiop():\n\n capture=root.Recognizer()\n audio=filedialog.askopenfilename(initialdir='/',title='Select A File',filetype=(('audio','*.wav'),(\"All Files\",'*.*')))\n with root.AudioFile(audio) as source:\n text.insert(tk.INSERT,'audio picked\\n')\n audio=capture.record(source)\n text.insert(tk.INSERT,'Please wait...\\n')\n fron = capture.recognize_google(audio)\n fron1 = capture.recognize_google(audio,language='hi-IN')\n\n try:\n #fron = capture.recognize_google(audio)\n text.insert(tk.INSERT,fron )\n text.insert(tk.INSERT,fron1)\n #print(capture.recognize_google(audio))\n #print(capture.recognize_google(audio,language='hi-IN'))\n\n except:\n #print('error')\n text.insert(tk.INSERT,'Error')\n\n\n\nb4=Button(window,text='Browse audio',width=12,command=audiop)\nb4.grid(row=5,column=3)\n\ndef speak():\n capture=root.Recognizer()\n with root.Microphone() as source:\n #print(\"say\")\n text.insert(tk.INSERT,'Speak\\n')\n audio=capture.listen(source)\n text.insert(tk.INSERT,'Done\\n')\n #print(\"done\")\n speak1=capture.recognize_google(audio)\n speak2=capture.recognize_google(audio,language='hi=IN')\n try:\n text.insert(tk.INSERT,speak1)\n text.insert(tk.INSERT,speak2)\n #print(capture.recognize_google(audio))\n #print(capture.recognize_google(audio,language='hi-IN'))\n except:\n #print(\"sorry\")\n text.insert(tk.INSERT,'Somethink wrong')\n\nb1 = Button(window, text=\"Speak\", width=12, command=speak)\nb1.grid(row=5, column=1)\n\nwindow.mainloop()\n","sub_path":"Gui.py","file_name":"Gui.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"379553806","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.path.insert(0,'/web/pluto/')\nimport numpy as np\nimport math\n\nimport algorithms.machine_learning.data_preprocessing.feature_engineering as fe\nimport algorithms.machine_learning.model_generation.multilayer_perceptron as mlp\nimport configparser\nconfig = configparser.ConfigParser()\nconfigPath = '../../config/data.cfg'\n\nconfig.read(configPath)\n#print(config.keys())\ndataDir = config['data']['dataDir']\n\ncharId = fe.loadCharId(dataDir)\nidChar = fe.ID2Char(charId)\ntable = fe.loadQAarr()\ns = len(idChar)\nxs = [row[0] for row in table]\nys = [row[1] for row in table]\n\ndef convertToOneHot(vector, num_classes=None):\n\n assert isinstance(vector, np.ndarray)\n assert len(vector) > 0\n\n if num_classes is None:\n num_classes = np.max(vector)+1\n else:\n assert num_classes > 0\n assert num_classes >= np.max(vector)\n\n result = np.zeros(shape=(len(vector), num_classes))\n result[np.arange(len(vector)), vector] = 1\n return result.astype(int)\n\ndef onehotToIDvector(onehot):\n result = []\n for row in onehot:\n m = np.max(row)\n result.append(list(row).index(m))\n return np.array(result)\n\ndef sentence(idVec,idChar=idChar):\n s = ''\n for v in idVec:\n value = idChar[v]\n if value == 'EOS':\n return s\n if value == 'PAD':\n s += ''\n else:\n s += value\n return s\n\ndef lossV(answer,target):\n nga = []\n for i in range(len(answer)-1):\n nga.append(np.append(answer[i],answer[i+1]))\n #print(nga) \n ngt = []\n for i in range(len(target)-1):\n ngt.append(np.append(target[i],target[i+1]))\n \n #print(ngt)\n c1 = 0\n for char1 in nga:\n for char2 in ngt:\n \n c1 += np.sum(np.abs(char1-char2))\n c2 = 0\n for char1 in ngt:\n for char2 in nga:\n c2 += np.sum(np.abs(char1-char2))\n \n c = c1+c2\n d = math.fabs(len(answer)-len(target))\n return c + d\n\ndef loop(x,s,params_e,params_d):\n #x vectors stream,xvs\n xvs = convertToOneHot(np.array(x),num_classes=s)\n \n #initialize parameters\n# params_e = mlp.mlp(s+500,100, h=[500])\n# params_d = mlp.mlp(100+500,s, h=[500])\n# \n #decoder-encoder\n h_e = np.array([0]*500)\n h_d = np.array([0]*500)\n yvs = []\n #i=0\n for xv in xvs:\n\n c,hes = mlp.feedForward(np.append(xv,h_e),params_e,onehot=True)\n #print(np.sum(c))\n #c is the 'thought vector' internal to the model.\n h_e = hes[-1]\n #decoder\n yv,hds = mlp.feedForward(np.append(c,h_d),params_d,onehot=True)\n h_d = hds[-1]\n #print(np.shape(h_d))\n yvs.append(yv)\n #y = onehotToIDvector(yvs)\n return yvs \n#\ndef mutation(params, variation, rate=0.5, offsprings=10):\n os = []\n for i in range(offsprings):\n rparams = []\n for param in params:\n w,b = param\n rw = w + np.random.normal(0,variation,np.shape(w))\n rb = b + np.random.normal(0,variation,np.shape(b))\n rparam = rw,rb\n rparams.append(rparam)\n os.append(rparams)\n return os\n\ndef training(xs, ys):\n params_e = mlp.mlp(s+500,10, h=[500])\n params_d = mlp.mlp(10+500,s, h=[500])\n iteration = 0\n for x in xs[:-200]:\n iteration += 1\n params_e_offsprings = mutation(params_e,1)\n params_d_offsprings = mutation(params_d,1)\n offsprings = range(len(params_e_offsprings))\n print('training iteration',iteration)\n print(sentence(x))\n losses = []\n for i in offsprings:\n #i = 0,1,2,3,..., no of offsprings-1\n params_e = params_e_offsprings[i]\n params_d = params_d_offsprings[i]\n \n y = ys[xs.index(x)]\n target = convertToOneHot(np.array(y),num_classes=s)\n yvs = loop(x,s,params_e,params_d)\n #answer = sentence(onehotToIDvector(yvs))\n #print(answer)\n #print(len(answer))\n #loss = np.sum(np.abs(target-yvs))\n loss = lossV(yvs,target)\n #print(loss)\n losses.append(loss)\n minLoss = np.min(losses)\n minInd = losses.index(minLoss)\n #survival params\n params_e = params_e_offsprings[minInd]\n params_d = params_d_offsprings[minInd]\n yvs = loop(x,s,params_e,params_d)\n answer = sentence(onehotToIDvector(yvs))\n \n print('best answer:', answer)\n print('loss',minLoss)\n #print(len(answer))\n print('\\n#################\\n')\n \n return params_e,params_d\n\nparams_e, params_d = training(xs,ys)","sub_path":"algorithms/nlp/seq2seq.py","file_name":"seq2seq.py","file_ext":"py","file_size_in_byte":4650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"553725509","text":"from django.utils.translation import ugettext_lazy as _\n\nfrom cms import __version__ as cms_version\nfrom cms.plugin_pool import plugin_pool\nfrom cms.plugin_base import CMSPluginBase\n\nfrom contactform.models import ContactFormIntermediate\n\n\nclass ContactFormPlugin(CMSPluginBase):\n model = ContactFormIntermediate\n name = _(\"Contact Form\")\n render_template = \"contactform/form.html\"\n change_form_template = \"contactform/plugin_form.html\"\n\n def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):\n \"\"\"\n We override the change form template path\n to provide backwards compatibility with CMS 2.x\n \"\"\"\n if cms_version.startswith('2'):\n context['change_form_template'] = \"admin/cms/page/plugin_change_form.html\"\n return super(ContactFormPlugin, self).render_change_form(request, context, add, change, form_url, obj)\n\n def render(self, context, instance, placeholder):\n request = context['request']\n\n contact_form = instance.form\n FormClass = contact_form.get_form_class(unique_form_id=instance.pk)\n\n context['instance'] = instance\n context['placeholder'] = placeholder\n context['form_model'] = contact_form\n\n\n if request.method == \"POST\" and request.POST.get('unique_form_id', None) == str(instance.pk):\n form = FormClass(request.POST, request.FILES)\n if form.is_valid() and form.handle_submission(request):\n # form was processed sucessfully\n if instance.form.success_page:\n context['redirect'] = instance.form.success_page.get_absolute_url()\n context['form'] = form\n context['success'] = True\n else:\n context['form'] = form\n context['success'] = False\n else:\n context['form'] = FormClass()\n context['success'] = False\n\n return context\n\nplugin_pool.register_plugin(ContactFormPlugin)","sub_path":"contactform/cms_plugins.py","file_name":"cms_plugins.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"240880714","text":"from nltk.corpus import gutenberg\nfrom nltk.corpus import reuters\nimport string\nimport json\n\ndef load_corpus():\n ret = {}\n for w in gutenberg.words() + reuters.words():\n if w not in ret:\n ret[w] = 1\n else:\n ret[w] += 1\n return ret\ndic_corpus = load_corpus()\n\ndg = json.dumps(dic_corpus)\nf = open(\"dic_corpus.json\",\"w\")\nf.write(dg)\nf.close()\n\n\nclass TotalBigram():\n def __init__(self):\n self.corpus = gutenberg.sents() + reuters.sents()\n\n def CountTotalBigram(self):\n dic_bigram = {}\n for sen in self.corpus:\n sen = ['>'] + [word for word in sen if word not in string.punctuation]\n for i in range(2, len(sen)+1):\n bigram = str(sen[i-2:i])\n if bigram in dic_bigram:\n dic_bigram[bigram] += 1\n else:\n dic_bigram[bigram] = 1\n return dic_bigram\n\ntb = TotalBigram()\ndic = tb.CountTotalBigram()\n\nd = json.dumps(dic)\nf = open(\"TotalBigram.json\",\"w\")\nf.write(d)\nf.close()","sub_path":"totalBigram.py","file_name":"totalBigram.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"349974166","text":"#!/usr/bin/python\n\n# Caja script to create launchers on desktop without hand editing .desktop files\n# or manually setting options by \"mate-desktop-item-edit ./ --create-new\"\n#\n# - Retrieves mime-type based on selected file extension\n# - Retrieves application for execution based on mime-type\n# - Retrieves icon based on mime-type\n# - Creates launcher on current user's desktop\n#\n# The application name for .tar files isn't found until mime_apps_3, \n# where it's written as \"org.gnome.FileRoller.desktop\", which is \n# found in \"/usr/share/app-install/desktop\" as one of the following:\n# \"file-roller:file-roller.desktop\"\n# \"file-roller:org.gnome.FileRoller.desktop\"\n#\n# The other application shown this way is Totem. I don't currently \n# understand the \":\" in the name. Neither apps launch from terminal.\n#\n# What's more odd is that tar files are handled by \"engrampa\" when\n# opened directly. Shortcuts to tar files aren't important, but I \n# don't know what else might be affected.\n#\n# Todo:\n# - Override .tar launcher exec with Engrampa as application (discovered that\n# Engrampa is a Caja extension). No one needs a launcher for this but still...\n# - Simplify getting mime-type without using extension, use \"file\" command\n# (see get_mime_type function for example...)\n#\n\nimport os\nimport stat\nimport datetime\n\ndebug = False\ndebug_path = \"/home/user/Temp/\"\n\n\n# Output debug log file\ndef log(message):\n if debug == True:\n out = open(debug_path + \"Auto-Create-Launcher-Debug.log\", \"a\")\n out.write(str(datetime.datetime.now()).split('.')[0] + \"\\t\\t\" + message + \"\\n\")\n out.close()\n\n\n# Create and write contents of .desktop launcher file\ndef create_launcher(path, exec_string, icon_string): \n header_string = \"#!/usr/bin/env xdg-open\"\n name_string = \"Name=\" + path.rpartition('/')[2]\n footer_string = \"#Created by Auto-Create-Launcher.py\"\n\n log(\"path = \" + path)\n log(\"exec_string = \" + exec_string)\n log(\"name_string = \" + name_string)\n log(\"icon_string = \" + icon_string)\n\n desktop_dest_path = os.path.expanduser(\"~/Desktop/\") + path.rpartition('/')[2] + \".desktop\"\n\n desktop_file = open(desktop_dest_path, \"w+\")\n\n desktop_file.write(header_string + \"\\n\\n\" + \"[Desktop Entry]\" + \"\\n\" + \"Type=Application\" + \"\\n\" + exec_string + \"\\n\" + name_string + \"\\n\" + icon_string + \"\\n\" + footer_string)\n\n desktop_file.close()\n set_exec_permission(desktop_dest_path)\n \n log(\"Launcher created successfully.\")\n\n# Set file as executable to avoid prompt about \"untrusted\"...\ndef set_exec_permission(desktop_dest_path):\n # st.mode is offered by autocomplete but that's wrong, use st.st_mode\n # S_IXUSR and S_IRGRP and S_IXOTH make the file executable across the board\n # S_IEXEC would make it executable only by the user\n #\n #https://stackoverflow.com/questions/12791997/how-do-you-do-a-simple-chmod-x-from-within-python\n #\n desktop_file_name = desktop_dest_path\n st = os.stat(desktop_file_name)\n \n os.chmod(desktop_file_name, st.st_mode | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXOTH)\n\n\n# Get mime-type based on file extension\ndef get_mime_type(path):\n mime_type = \"\"\n\n # Get file extension\n file_extension = path.rpartition('.')[2]\n log(\"file_extension = \" + file_extension)\n\n # If the file didn't have an extension...\n if file_extension == path:\n log(\"file_extension == path\")\n # Should use this command to simplify script, was not previously aware...\n mime_type = os.popen(\"file --mime-type -b \" + path).read().rstrip()\n log(\"mime_type = \" + mime_type)\n return mime_type\n\n # If the file had an extension, look it up...\n if os.path.isfile(\"/etc/mime.types\"):\n log(\"/etc/mime.types file found.\")\n mime_types_file = open(\"/etc/mime.types\", \"r\")\n \n index = 0 \n\n # Load mime.types file into memory\n for line in mime_types_file:\n \n # Get string after first whitespace as right_column\n line_array = line.split(\"\\t\")\n right_column = \"\"\n\n i = 1\n while i < len(line_array):\n right_column += line_array[i] + \" \"\n i += 1\n\n # Find space+file_extension or tab+file_extension in right_column\n index = right_column.rfind(\" \" + file_extension + \" \")\n if index == -1:\n index = right_column.rfind(\"\\t\" + file_extension + \" \")\n if index == -1:\n index = right_column.rfind(\" \" + file_extension + \"\\n\")\n if index == -1:\n index = right_column.rfind(\"\\t\" + file_extension + \"\\n\")\n\n # If file_extension was found, get associated mime_type\n if index != -1:\n mime_type = line.split()[0]\n\n log(\"line = \" + chr(34) + line.rstrip() + chr(34))\n log(\"mime_type = \" + mime_type)\n\n mime_types_file.close()\n else:\n log(\"/etc/mime.types file not found.\")\n\n return mime_type\n\n\ndef parse_mime_app_file(mime_file_path):\n app_name = \"\"\n if os.path.isfile(mime_file_path):\n log(mime_file_path + \" file found.\")\n \n file = open(mime_file_path, \"r\")\n \n # Split on equal sign, find app_name in right column\n for line in file:\n left_column = line.partition(\"=\")[0]\n right_column = line.partition(\"=\")[2].rstrip()\n \n if left_column == mime_type:\n app_name = right_column\n log(\"line = \" + chr(34) + line.rstrip() + chr(34))\n log(\"app_name = \" + app_name)\n\n file.close()\n else:\n log(mime_file_path + \" file not found.\")\n \n return app_name\n\n# Get application for execution based on mime-type\ndef get_associated_application(mime_type): \n app_name = \"\"\n mime_apps_1 = os.path.expanduser(\"~/.config/mimeapps.list\")\n mime_apps_2 = os.path.expanduser(\"~/.local/share/applications/mimeapps.list\")\n mime_apps_3 = \"/usr/share/applications/defaults.list\"\n\n # Open most relevant file first if found\n app_name = parse_mime_app_file(mime_apps_1)\n\n # Open second most relevant file if no application name was found\n if app_name is None or app_name is \"\":\n app_name = parse_mime_app_file(mime_apps_2)\n\n # Lastly, try defaults file if still no application has been found\n if app_name is None or app_name is \"\":\n app_name = parse_mime_app_file(mime_apps_3)\n\n if app_name is None or app_name is \"\":\n log(\"No associated application for mime-type: \" + chr(34) + mime_type + chr(34))\n \n return app_name\n\n# Get path with filename (unless folder), default key to \"None\" if none selected\npath = os.environ.get('CAJA_SCRIPT_SELECTED_FILE_PATHS', None)\nlog(\"----------Start of log.----------\")\n\nif path is not None and path is not \"\":\n path = path.rstrip()\n log(\"Path is not None or empty.\")\n log(\"path = \" + path)\n\n # If the path is a folder...\n if os.path.isdir(path): \n log(\"Path is a directory.\")\n\n exec_string = \"Exec=caja \" + chr(34) + path + chr(34)\n icon_string = \"Icon=folder_color_orange\"\n \n create_launcher(path, exec_string, icon_string)\n # If the path is a file...\n else:\n log(\"Path is a file.\")\n \n # Get mime-type\n mime_type = get_mime_type(path)\n app_name = \"\"\n exec_string = \"\"\n\n # *** Override app_name's and exec_string's here ***\n #\n # Override app_name and exec_string for executable files\n if mime_type == \"application/x-executable\":\n app_name = path.rpartition(\"/\")[2].rstrip()\n exec_string = \"Exec=\" + app_name\n else:\n # Otherwise assign retrieved app_name's and exec_string's here...\n if mime_type is not None and mime_type is not \"\":\n # Get application for execution based on mime-type\n app_name = get_associated_application(mime_type).partition(\".\")[0]\n\n # Override app_name for sublime_text\n if app_name == \"sublime_text\":\n app_name = \"/opt/sublime_text/sublime_text\"\n\n exec_string = \"Exec=\" + app_name + \" \" + chr(34) + path + chr(34)\n \n if app_name is not None and app_name is not \"\":\n # Set icon based on mime-type\n icon_string = \"Icon=\" + mime_type.replace(\"/\", \"-\")\n\n # Create launcher\n create_launcher(path, exec_string, icon_string)\nelse:\n log(\"Path is None or empty.\")","sub_path":"Ubuntu/Caja-Scripts/Auto-Create-Launcher-On-Desktop.py","file_name":"Auto-Create-Launcher-On-Desktop.py","file_ext":"py","file_size_in_byte":8551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"198834638","text":"from getdata import getdata\nimport os\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn import tree\nfrom sklearn import svm\nfrom sklearn import metrics\nfrom sklearn import cross_validation\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import BaggingClassifier, RandomForestClassifier, AdaBoostClassifier\n\nWORKING_PATH, filename = os.path.split(os.path.abspath(__file__))\n# WORKING_PATH='/home/xavi/dataScience/projecte/datascience/xabarca-python'\n\nNUM_PLOT_GENERATOR = 0\ndef numPotGenerator():\n global NUM_PLOT_GENERATOR\n NUM_PLOT_GENERATOR += 1\n return str(NUM_PLOT_GENERATOR)\n\n# main page of ICS machine learning datasets\n# https://archive.ics.uci.edu/ml/datasets/Chess+(King-Rook+vs.+King-Pawn)\n\n# definition of the columns\n# http://notolog.blogspot.com/2011/01/features-of-uci-chess-data-sets.html\n#\n# sklearn cluster algorithms\n# http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_comparison.html\n\n# --------------------------------------------------------------------------------\n# 1\t\tbkblk\tthe BK is not in the way\n# 2\t\tbknwy\tthe BK is not in the BR's way\n# 3\t\tbkon8\tthe BK is on rank 8 in a position to aid the BR\n# 4\t\tbkona\tthe BK is on file A in a position to aid the BR\n# 5\t\tbkspr\tthe BK can support the BR\n# 6\t\tbkxbq\tthe BK is not attacked in some way by the pro- moted WP\n# 7\t\tbkxcr\tthe BK can attack the critical square (b7)\n# 8\t\tbkxwp\tthe BK can attack the WP\n# 9\t\tblxwp\tB attacks the WP (BR in direction x = -1 only)\n# 10\tbxqsq\tone or more Black pieces control the queening square\n# 11\tcntxt\tthe WK is on an edge and not on a8\n# 12\tdsopp\tthe kings are in normal opposition\n# 13\tdwipd\tthe WK distance to intersect point is too great\n# 14\thdchk\tthere is a good delay because there is a hidden check\n# 15\tkatri\tthe BK controls the intersect point \n# 16\tmulch\tB can renew the check to good advantage\n# 17\tqxmsq\tthe mating square is attacked in some way by the promoted WP\n# 18\tr2ar8\tthe BR does not have safe access to file A or rank 8\n# 19\treskd\tthe WK can be reskewered via a delayed skewer\n# 20\treskr\tthe BR alone can renew the skewer threat\n# 21\trimmx\tthe BR can be captured safely\n# 22\trkxwp\tthe BR bears on the WP (direction x = -1 only)\n# 23\trxmsq\tthe BR attacks a mating square safely\n# 24\tsimpl\ta very simple pattern applies (unexplained)\n# 25\tskach\tthe WK can be skewered after one or more checks\n# 26\tskewr\tthere is a potential skewer as opposed to fork\n# 27\tskrxp\tthe BR can achieve a skewer or the BK attacks the WP\n# 28\tspcop\tthere is a special opposition pattern present\n# 29\tstlmt\tthe WK is in stalemate\n# 30\tthrsk\tthere is a skewer threat lurking\n# 31\twkcti\tthe WK cannot control the intersect point\n# 32\twkna8\tthe WK is on square a8\n# 33\twknck\tthe WK is in check\n# 34\twkovl\tthe WK is overloaded\n# 35\twkpos\tthe WK is in a potential skewer position\n# 36\twtoeg\tthe WK is one away from the relevant edge\n# --------------------------------------------------------------------------------\n\n\n\n# --------------------------------------------------------------------\n# GETTING AND ARRANGING DATA\n# --------------------------------------------------------------------\ndf = getdata( WORKING_PATH )\nprint( \"dataframe shape : \" , df.shape )\n#print(df.head().T)\n\n\n \n# --------------------------------------------------------------------\n# CORRELATION AND HEATMAP\n# --------------------------------------------------------------------\n# calculate the correlation matrix\ncorr_matrix = df.corr()\n\n## plot the heatmap\n#sns_plot = sns.heatmap(corr_matrix, \n# xticklabels=corr_matrix.columns,\n# yticklabels=corr_matrix.columns)\n#fig = sns_plot.get_figure()\n#fig.savefig(WORKING_PATH + \"/1_corr_heatmap.png\") \n#fig.clf()\n#\n\n# Generate a mask for the upper triangle\nmask = np.zeros_like(corr_matrix, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n# Set up the matplotlib figure\nf, ax = plt.subplots(figsize=(11, 9))\n# Generate a custom diverging colormap\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\n# Draw the heatmap with the mask and correct aspect ratio\nsns_corrplot = sns.heatmap(corr_matrix, mask=mask, cmap=cmap, vmax=1,vmin=-1, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .8})\nfig = sns_corrplot.get_figure()\nfig.savefig(WORKING_PATH + \"/\" + numPotGenerator() + \"_corr_heatmap.png\") \nfig.clf()\n\n\n\n## --------------------------------------------------------------------\n## BALANCED OR UNBALANCED LABEL ?\n## --------------------------------------------------------------------\nprint( \"Our label has only 0s and 1s, so a mean of \", np.mean(df['win']), \" shows that our label is balanced\" )\n\nperc_win = df['win'].sum() / df['win'].count()\nheight = [1-perc_win, perc_win]\nbars = ('win=0 (%)', 'win=1 (%)')\ny_pos = np.arange(len(bars))\nplt.bar(y_pos, height)\nplt.xticks(y_pos, bars)\n#plt.title=\"histogram win\"\nplt.savefig(WORKING_PATH + \"/\" + numPotGenerator() + \"_win_histogram.png\") \nplt.clf()\n\n\n# --------------------------------------------------------------------\n# PCA ( principal component analysis )\n# --------------------------------------------------------------------\n# https://jakevdp.github.io/PythonDataScienceHandbook/05.09-principal-component-analysis.html\n\n\n\n\n\n# --------------------------------------------------------------------\n# K-NEIGHBORS\n# --------------------------------------------------------------------\nallColsAsFeatures = ['bkblk','bknwy','bkon8','bkona','bkspr','bkxbq','bkxcr','bkxwp','blxwp','bxqsq','cntxt','dsopp',\n\t 'hdchk','mulch','qxmsq','r2ar8','reskd','reskr','rimmx','rkxwp','rxmsq','simpl','skach','skewr',\n\t 'skrxp','spcop','stlmt','thrsk','wkcti','wkna8','wknck','wkovl','wkpos']\nX,y = df[ allColsAsFeatures ], df['win']\nprint( \"X shape = \" , X.shape, \" , y shape = \" , y.shape )\n\nPRC = 0.4\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=PRC, random_state=666)\n\nscores = []\nk_values = np.arange(1, 11)\nfor k in k_values:\n classifier = KNeighborsClassifier(n_neighbors=k )\n classifier.fit(X_train, y_train)\n #yhat = classifier.predict(X_test)\n #matrix_confusion = metrics.confusion_matrix( yhat, y_test )\n #print( k, \"matrix_confusion\" , matrix_confusion )\n scores.append( classifier.score(X_test, y_test) )\n\nplt.plot( k_values, scores )\nplt.title(\"KNeighbors accuracy\")\nplt.xlabel( '# neighbors')\nplt.ylabel( 'Accuracy' )\nplt.savefig(WORKING_PATH + \"/\" + numPotGenerator() + \"_KNeighbors_accuracy.png\")\nplt.clf()\n\n#TODO: confusion matrix\n# > True positives (TP): When the classifier predicts a sample as positive and it really is positive.\n# > False positives (FP): When the classifier predicts a sample as positive but in fact it is negative.\n# > True negatives (TN): When the classifier predicts a sample as negative and it really is negative.\n# > False negatives (FN): When the classifier predicts a sample as negative but in fact it is positive.\n\n# dintre el bucle de fits-scores :: matrix_confusion = metrics.confusion_matrix( yhat, y_test )\n\n#TODO: make different splits of data and then calculate mean of errors (or mean of scores)\n# page 76 llibre UB\n\n\n\n\n# --------------------------------------------------------------------\n# VALIDATION PROCESS FOR MODEL SELECTION (cross-validation)\n# --------------------------------------------------------------------\nPRC = 0.2\nseed = 7\nnum_trees = 30\nacc_r=np.zeros((10,7))\nfor i in np.arange(10):\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=PRC)\n nn1 = KNeighborsClassifier(n_neighbors=1)\n nn3 = KNeighborsClassifier(n_neighbors=3)\n svc = svm.SVC()\n dt = tree.DecisionTreeClassifier()\n bagg = BaggingClassifier(base_estimator=None)\n rf = RandomForestClassifier()\n ada = AdaBoostClassifier(n_estimators=num_trees, random_state=seed)\n \n nn1.fit(X_train,y_train)\n nn3.fit(X_train,y_train)\n svc.fit(X_train,y_train)\n dt.fit(X_train,y_train)\n bagg.fit(X_train,y_train)\n rf.fit(X_train,y_train)\n ada.fit(X_train,y_train)\n \n yhat_nn1=nn1.predict(X_test)\n yhat_nn3=nn3.predict(X_test)\n yhat_svc=svc.predict(X_test)\n yhat_dt=dt.predict(X_test)\n yhat_bagg=bagg.predict(X_test)\n yhat_rf=rf.predict(X_test)\n yhat_ada=ada.predict(X_test)\n \n acc_r[i][0] = metrics.accuracy_score(yhat_nn1, y_test)\n acc_r[i][1] = metrics.accuracy_score(yhat_nn3, y_test)\n acc_r[i][2] = metrics.accuracy_score(yhat_svc, y_test)\n acc_r[i][3] = metrics.accuracy_score(yhat_dt, y_test)\n acc_r[i][4] = metrics.accuracy_score(yhat_bagg, y_test)\n acc_r[i][5] = metrics.accuracy_score(yhat_rf, y_test)\n acc_r[i][6] = metrics.accuracy_score(yhat_ada, y_test)\n\n\nplt.boxplot(acc_r)\nfor i in np.arange(7):\n xderiv = (i+1)*np.ones(acc_r[:,i].shape)+(np.random.rand(10,)-0.5)*0.1\n plt.plot(xderiv,acc_r[:,i],'ro',alpha=0.3)\n \nax = plt.gca()\nax.set_xticklabels(['1-NN','3-NN','SVM','DT','bagging', 'RF', 'Adaboost'])\nplt.ylabel('Accuracy')\nplt.savefig(WORKING_PATH + \"/\" + numPotGenerator() + \"_error_model_selection.png\",dpi=300, bbox_inches='tight')\nplt.clf()\n\n\n# --------------------------------------------------------------------\n# DECISION TREE :: 10-fold CROSS VALIDATION\n# --------------------------------------------------------------------\n\n#Create a 10-fold cross validation set\nkf=cross_validation.KFold(n=y.shape[0], n_folds=10, shuffle=True, random_state=0)\n\n#Search the parameter among the following\nC=np.arange(2,20,)\n\nacc = np.zeros((10,18))\ni=0\nfor train_index, val_index in kf:\n X_train, X_val = X.take(train_index), X.take(val_index)\n y_train, y_val = y.take(train_index), y.take(val_index)\n j=0\n for c in C:\n dt = tree.DecisionTreeClassifier(min_samples_leaf=1, max_depth=c)\n dt.fit(X_train,y_train)\n yhat = dt.predict(X_val)\n acc[i][j] = metrics.accuracy_score(yhat, y_val)\n j=j+1\n i=i+1\n\nplt.boxplot(acc)\nfor i in np.arange(18):\n xderiv = (i+1)*np.ones(acc[:,i].shape)+(np.random.rand(10,)-0.5)*0.1\n plt.plot(xderiv,acc[:,i],'ro',alpha=0.3)\n\nprint ('Mean accuracy: ' , str(np.mean(acc,axis = 0)) )\nprint ('Selected model index: ' , str(np.argmax(np.mean(acc,axis = 0))) )\nprint ('Complexity: ' , str(C[np.argmax(np.mean(acc,axis = 0))]) )\nplt.ylim((0.7,1.))\nfig = plt.gcf()\nfig.set_size_inches(12,5)\nplt.xlabel('Complexity')\nplt.ylabel('Accuracy')\nplt.savefig(WORKING_PATH + \"/\" + numPotGenerator() + \"_decision_tree_model_selection.png\",dpi=300, bbox_inches='tight')\nplt.clf()\n\n# --------------------------------------------------------------------\n# NUMBER OF FEATURES ??? decrease so much the final accuracy ?\n# --------------------------------------------------------------------\n\n# modified by xag on 12-06-2018\n","sub_path":"xabarca-python/chess-endgame.py","file_name":"chess-endgame.py","file_ext":"py","file_size_in_byte":10753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"99513271","text":"import numpy as np\nimport math\nimport time\nfrom matplotlib import pyplot as plt\nfrom scipy.stats import norm\nfrom scipy.stats import expon\nimport pdb\n\nfrom MapReader import MapReader\n\nclass SensorModel:\n\n \"\"\"\n References: Thrun, Sebastian, Wolfram Burgard, and Dieter Fox. Probabilistic robotics. MIT press, 2005.\n [Chapter 6.3]\n \"\"\"\n\n def __init__(self, occupancy_map):\n \"\"\"\n Initialize Sensor Model parameters here\n \"\"\"\n self.map = occupancy_map\n self.Z_MAX = 8183\n self.P_HIT_SIGMA = 250\n self.P_SHORT_LAMBDA = 0.01\n self.Z_PHIT = 1000\n self.Z_PSHORT = 0.01\n self.Z_PMAX = 0.03\n self.Z_PRAND = 100000\n\n def bresenham(self, x0, y0, x1, y1):\n \"\"\"Yield integer coordinates on the line from (x0, y0) to (x1, y1).\n Input coordinates should be integers.\n The result will contain both the start and the end point.\n \"\"\"\n dx = x1 - x0\n dy = y1 - y0\n\n xsign = 1 if dx > 0 else -1\n ysign = 1 if dy > 0 else -1\n\n dx = abs(dx)\n dy = abs(dy)\n\n if dx > dy:\n xx, xy, yx, yy = xsign, 0, 0, ysign\n else:\n dx, dy = dy, dx\n xx, xy, yx, yy = 0, ysign, xsign, 0\n\n D = 2*dy - dx\n y = 0\n\n for x in range(dx + 1):\n yield x0 + x*xx + y*yx, y0 + x*xy + y*yy\n if D >= 0:\n y += 1\n D -= 2*dx\n D += 2*dy\n\n def ray_trace(self,x_t):\n def bresenham_collide_pt(x1,y1,x2,y2): \n x1 = min(int(x1), 799)\n y1 = int(y1) \n x2 = min(int(x2), 799)\n y2 = int(y2)\n if x1= 800:\n return final_pts\n if self.occupancy_map[pt[1]][pt[0]] > self.map_threshold:\n final_pts = [pt[0],pt[1]]\n return final_pts \n return final_pts\n def check_intersection(ray_origin, ray_direction, point1, point2):\n point1 = np.array(point1)\n point2 = np.array(point2)\n v1 = ray_origin - point1\n v2 = point2 - point1\n v3 = np.array([-ray_direction[1], ray_direction[0]])\n t1 = np.cross(v2, v1) / np.dot(v2, v3)\n t2 = np.dot(v1, v3) / np.dot(v2, v3)\n if t1 >= 0.0 and t2 >= 0.0 and t2 <= 1.0:\n return [ray_origin + t1 * ray_direction]\n return []\n\n map_size = self.occupancy_map.shape\n pos_x, pos_y, pos_theta = x_t\n pos_x = pos_x/10.\n pos_y = pos_y/10.\n \n ray_direction_x = math.cos(pos_theta)\n ray_direction_y = math.sin(pos_theta)\n ray_direction = np.array([ray_direction_x, ray_direction_y])\n ray_origin = np.array([pos_x, pos_y])\n pts1, pts2, pts3, pts4 = [0,0], [map_size[0], 0], [map_size[0],map_size[1]], [0,map_size[1]]\n for p1, p2 in zip([pts1, pts2, pts3, pts4], [pts2, pts3, pts4, pts1]):\n flag = check_intersection(ray_origin, ray_direction, p1, p2)\n if len(flag) > 0:\n final_x, final_y = flag[0]\n break\n collide_pts = bresenham_collide_pt(pos_x,pos_y,final_x,final_y)\n z_tk_star = np.linalg.norm(collide_pts - ray_origin)\n return z_tk_star + 2.5\n\n def p_hit(self, z_tk, x_t, z_tk_star):\n if 0 <= z_tk <= self.Z_MAX:\n gaussian = (math.exp(-(z_tk - z_tk_star)**2 / (2 * self.P_HIT_SIGMA**2)))/ math.sqrt(2 * math.pi * self.P_HIT_SIGMA**2)\n return gaussian\n else:\n return 0.0\n\n def p_short(self, z_tk, x_t, z_tk_star):\n if 0 <= z_tk <= z_tk_star:\n eta = 1 / (1 - math.exp(-self.P_SHORT_LAMBDA * z_tk_star))\n return eta * self.P_SHORT_LAMBDA * math.exp(-self.P_SHORT_LAMBDA * z_tk)\n else:\n return 0.0\n\n def p_max(self, z_tk, x_t):\n if z_tk == self.Z_MAX:\n return 1.0\n else:\n return 0.0\n\n def p_rand(self, z_tk, x_t):\n if 0 <= z_tk < self.Z_MAX:\n return 1.0 / self.Z_MAX\n else:\n return 0.0\n\n \n def beam_range_finder_model(self, z_t1_arr, x_t1):\n \"\"\"\n param[in] z_t1_arr : laser range readings [array of 180 values] at time t\n param[in] x_t1 : particle state belief [x, y, theta] at time t [world_frame]\n param[out] prob_zt1 : likelihood of a range scan zt1 at time t\n \"\"\"\n\n \"\"\"\n TODO : Add your code here\n \"\"\"\n pos_x, pos_y, pos_theta = x_t1\n temp = self.map[min(int(pos_y/10.), 799)][min(int(pos_x/10.), 799)]\n if temp > 0.4 or temp == -1:\n return 1e-100\n q = 0.0\n\n laser_x = 25.0 * np.cos(pos_theta)\n laser_y = 25.0 * np.sin(pos_theta)\n coord_x = int(round((pos_x + laser_x) / 10.0))\n coord_y = int(round((pos_y + laser_y) / 10.0))\n\n for deg in range (-90,90, 10):\n z_t1_true = self.rayCast(deg, pos_theta, coord_x, coord_y)\n z_t1_k = z_t1_arr[deg+90]\n p1 = self.Z_PHIT * self.p_hit(z_t1_k, x_t1, z_t1_true)\n p2 = self.Z_PSHORT * self.p_short(z_t1_k, x_t1, z_t1_true)\n p3 = self.Z_PMAX * self.p_max(z_t1_k, x_t1)\n p4 = self.Z_PRAND * self.p_rand(z_t1_k, x_t1)\n p = p1 + p2 + p3 + p4\n if p > 0:\n q = q + np.log(p)\n return math.exp(q)\n\n\n def rayCast(self, deg, ang, coord_x, coord_y):\n final_angle= ang + math.radians(deg)\n start_x = coord_x\n start_y = coord_y\n final_x = coord_x\n final_y = coord_y\n while 0 < final_x < self.map.shape[1] and 0 < final_y < self.map.shape[0] and abs(self.map[final_y, final_x]) < 0.0000001:\n start_x += 2 * np.cos(final_angle)\n start_y += 2 * np.sin(final_angle)\n final_x = int(round(start_x))\n final_y = int(round(start_y))\n end_p = np.array([final_x,final_y])\n start_p = np.array([coord_x,coord_y])\n dist = np.linalg.norm(end_p-start_p) * 10\n return dist\nif __name__=='__main__':\n pass\n","sub_path":"code/scripts/SensorModel.py","file_name":"SensorModel.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"275223353","text":"from __future__ import print_function\n\nimport sys\nsys.path.append(\"../\") \n\nimport pickle\nimport numpy as np\nimport os\nimport gzip\nimport matplotlib.pyplot as plt\nimport torch\n\nfrom utils import *\nfrom agent.bc_agent import BCAgent\nfrom tensorboard_evaluation import Evaluation\n\nif torch.cuda.device_count() > 0:\n DEVICE = 'cuda'\nelse:\n DEVICE = 'cpu'\n\ndevice = torch.device(DEVICE)\nprint(device)\n\ndef read_data(datasets_dir=\"./data\", frac = 0.1):\n \"\"\"\n This method reads the states and actions recorded in drive_manually.py \n and splits it into training/ validation set.\n \"\"\"\n print(\"... read data\")\n data_files = [\n # 'data.pkl_o.gzip'\n 'data.pkl_o1.gzip',\n 'data.pkl_cp.gzip'\n ]\n\n state = []\n action = []\n for fl in data_files:\n data_file = os.path.join(datasets_dir, fl)\n f = gzip.open(data_file, 'rb')\n data = pickle.load(f)\n state += data['state']\n action += data['action']\n\n # get images as features and actions as targets\n X = np.array(state).astype('float32')\n y = np.array(action).astype('float32')\n\n # split data into training and validation set\n n_samples = X.shape[0]\n X_train, y_train = X[:int((1-frac) * n_samples)], y[:int((1-frac) * n_samples)]\n X_valid, y_valid = X[int((1-frac) * n_samples):], y[int((1-frac) * n_samples):]\n print(X_train.shape)\n print(X_valid.shape)\n return X_train, y_train, X_valid, y_valid\n\n\ndef preprocessing(X_train, y_train, X_valid, y_valid, history_length=1):\n # TODO: preprocess your data here.\n # 1. convert the images in X_train/X_valid to gray scale. If you use rgb2gray() from utils.py, the output shape (96, 96, 1)\n # 2. you can train your model with discrete actions (as you get them from read_data) by discretizing the action space \n # using action_to_id() from utils.py.\n y_train = np.array([action_to_id(y_train[i]) for i in range(y_train.shape[0])])\n y_valid = np.array([action_to_id(y_valid[i]) for i in range(y_valid.shape[0])])\n X_train = rgb2gray(X_train)\n X_valid = rgb2gray(X_valid)\n # History:\n # At first you should only use the current image as input to your network to learn the next action. Then the input states\n # have shape (96, 96, 1). Later, add a history of the last N images to your state so that a state has shape (96, 96, N).\n \n return X_train, y_train, X_valid, y_valid\n\n\n\ndef slide(data, ids, width):\n return np.array([data[i - width:i] for i in ids])\n\ndef sample_minibatch(X, y, batch_size, hl, probs):\n elems = X.shape[0]\n rnd = np.random.choice(range(hl, elems), size=batch_size, replace=True, p=probs)\n # rnd = np.random.randint(low=hl, high=elems, size=batch_size)\n o_x = slide(X, rnd, hl)\n o_y = slide(y, rnd, hl)\n return o_x, o_y\n\ndef compute_accuracy(y_out, y_gt):\n true_preds = torch.where(y_out == y_gt, torch.tensor(1).to(device), torch.tensor(0).to(device)).sum()\n all_preds = y_gt.numel()\n return (true_preds.float() / all_preds).item()\n\n\ndef train_model(X_train, y_train, X_valid, y_valid, n_minibatches, batch_size, lr, hl = 1, model_dir=\"./models\", tensorboard_dir=\"./tensorboard\"):\n \n # create result and model folders\n if not os.path.exists(model_dir):\n os.mkdir(model_dir)\n\n train_p, t_weights = get_weights(y_train, hl)\n valid_p, _ = get_weights(y_valid, hl)\n t_probs = train_p / train_p.sum()\n v_probs = valid_p / valid_p.sum()\n \n print(\"... train model\")\n\n # TODO: specify your agent with the neural network in agents/bc_agent.py \n agent = BCAgent(device, lr=lr, history_length=hl)\n tensorboard_eval = Evaluation(tensorboard_dir, \"imitation_learning\", stats=['loss', 'train_accuracy', 'validation_accuracy'])\n\n # TODO: implement the training\n # \n # 1. write a method sample_minibatch and perform an update step\n # 2. compute training/ validation accuracy and loss for the batch and visualize them with tensorboard. You can watch the progress of\n # your training *during* the training in your web browser\n # \n # training loop\n # for i in range(n_minibatches):\n # ...\n # for i % 10 == 0:\n # # compute training/ validation accuracy and write it to tensorboard\n # tensorboard_eval.write_episode_data(...)\n print(\"Starting loop.\")\n lbs_sum = {\n 'str': 0,\n 'r': 0,\n 'l': 0,\n 'a': 0,\n 'b': 0\n }\n for i in range(n_minibatches):\n x, y = sample_minibatch(X_train, y_train, batch_size, hl, t_probs)\n x = torch.tensor(x).to(device)\n y = torch.tensor(y).to(device)\n loss = agent.update(x, y)\n\n if i % 10 == 0:\n # compute training/ validation accuracy and write it to tensorboard\n print(\"round \" + str(i))\n lbs = count_labls(y[:, hl - 1].cpu())\n lbs_sum['str'] += lbs['str']\n lbs_sum['l'] += lbs['l']\n lbs_sum['r'] += lbs['r']\n lbs_sum['a'] += lbs['a']\n lbs_sum['b'] += lbs['b']\n print(lbs)\n print(lbs_sum)\n outs = agent.predict(x)\n outs = outs.argmax(dim=2)\n train_acc = compute_accuracy(outs, y)\n\n val_acc_cum = 0\n for ii in range(10):\n inp, lba = sample_minibatch(X_valid, y_valid, batch_size, hl, v_probs)\n inp = torch.tensor(inp).to(device)\n lba = torch.tensor(lba).to(device)\n val_outs = agent.predict(inp)\n val_outs = val_outs.argmax(dim=2)\n val_acc = compute_accuracy(val_outs, lba)\n val_acc_cum += val_acc\n\n val_acc_cum = val_acc_cum / 10\n\n eval_dict = {\n \"loss\": loss.item(),\n \"train_accuracy\": train_acc,\n \"validation_accuracy\": val_acc_cum\n }\n\n print(eval_dict)\n tensorboard_eval.write_episode_data(i, eval_dict)\n \n # TODO: save your agent\n model_dir = agent.save(os.path.join(model_dir, \"agent.pt\"))\n print(\"Model saved in file: %s\" % model_dir)\n\n\n\ndef count_labls(ys):\n stra = np.where(ys == 0, 1, 0)\n le = np.where(ys == 1, 1, 0)\n rt = np.where(ys == 2, 1, 0)\n acc = np.where(ys == 3, 1, 0)\n br = np.where(ys == 4, 1, 0)\n ws = stra.sum()\n wl = le.sum()\n wr = rt.sum()\n wa = acc.sum()\n wb = br.sum()\n di = {\n 'str': ws,\n 'r': wr,\n 'l': wl,\n 'a': wa,\n 'b': wb\n }\n return di\n\ndef get_weights(data, hl):\n data = data[hl:]\n cnt = data.shape[0]\n stra = np.where(data == 0, 1, 0)\n le = np.where(data == 1, 1, 0)\n rt = np.where(data == 2, 1, 0)\n acc = np.where(data == 3, 1, 0)\n br = np.where(data == 4, 1, 0)\n ws = stra.sum()\n wl = le.sum()\n wr = rt.sum()\n wa = acc.sum()\n wb = br.sum()\n print('Straight ' + str(ws))\n print('Left ' + str(wl))\n print('Right ' + str(wr))\n print('Accelerate ' + str(wa))\n print('Break ' + str(wb))\n weights = 1 / (np.array([ws, wl, wr, wa, wb]) / cnt)\n print('Weights ' + str(weights))\n\n re = np.where(stra == 1, weights[0], 0)\n re += np.where(le == 1, weights[1], 0)\n re += np.where(rt == 1, weights[2], 0)\n re += np.where(acc == 1, weights[3], 0)\n re += np.where(br == 1, weights[4], 0)\n return re, weights\n\n\nif __name__ == \"__main__\":\n\n # read data \n X_train, y_train, X_valid, y_valid = read_data(\"./data\")\n\n hl = 10\n lr = 1e-4\n batch_size = 32\n\n # X_train = X_train[:100]\n # X_valid = X_valid[:100]\n # y_train = y_train[:100]\n # y_valid = y_valid[:100]\n\n # preprocess data\n X_train, y_train, X_valid, y_valid = preprocessing(X_train, y_train, X_valid, y_valid, history_length=hl)\n\n minibatches = 50000\n\n # train model (you can change the parameters!)\n train_model(X_train, y_train, X_valid, y_valid, hl=hl, n_minibatches=minibatches, batch_size=batch_size, lr=lr)\n \n","sub_path":"exercise3_R/imitation_learning/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"638182964","text":"# stdlib\nimport datetime as dt\n\n# convert string to list\n\n\ndef text_to_list(text, delimiter=';'):\n\n if text.strip() == \"\":\n return []\n return text.split(delimiter)\n\n# convert list to dict\n\n\ndef list_to_dict(lst, delimiter=\"=\"):\n\n result = dict(node_status=\"on\")\n for row in lst:\n split = row.split(delimiter, 1)\n if split == ['']:\n pass\n else:\n key, value = split\n if key not in result:\n result[key] = value\n else:\n result[key] = \"%s, %s\" % (result[key], value)\n return result\n\n# get time difference in seconds\n\n\ndef time_diffrence_in_sec(time1, time2):\n\n FMT = '%H:%M:%S'\n tdelta = dt.datetime.strptime(\n time1, FMT) - dt.datetime.strptime(time2, FMT)\n return tdelta.seconds\n\n# get time average\n\n\ndef time_average(time1, time2):\n\n diff = time_diffrence_in_sec(time1, time2)\n FMT = '%H:%M:%S'\n avg_time = dt.datetime.strptime(time2, FMT) + dt.timedelta(0, diff / 2)\n return avg_time.strftime(\"%H:%M:%S\")\n\n# get alert status\n\n\ndef get_alert_status(error_condition, warning_condition=None):\n\n if error_condition:\n return 'error'\n elif warning_condition:\n return 'warning'\n else:\n return 'success'\n","sub_path":"checks/libs/aerospike/convertor.py","file_name":"convertor.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"62525027","text":"#Chess Bate - Gathering Data + Bitboard Representation\n\nimport pgn\nimport chess.pgn\nimport chess\nimport numpy as np\n\n# Global Variables\nDATALOC = \"‪C:/Users/user/Desktop/ChessBate/data/sample_data/rawData.pgn\"\nNUM_GAMES = 11\nTESTINDEX = 9\nRESULTS = {'0-1':'0', '1-0':'1'}\n\n# Bitboard initialization\ndef bitboard (board):\n\t# Parameter : board - chess.board() variable\n\t# Output : bitboard - string type\n\n\tPIECE_INDEXES = {'P':'0001', 'N':'0010', 'B':'0011', 'R':'0100', 'Q':'0101', 'K':'0110',\n\t\t\t\t\t'p':'1001', 'n':'1010', 'b':'1011', 'r':'1100', 'q':'1101', 'k':'1110',\n\t\t\t\t\t'number':'0000'}\n\n\t# fenboard examples: \n\t# 5R2/8/4ppp1/3r1k1p/5P2/5PK1/8/8 w - - 0 40\n\t# rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\n\tfenboard = str(board.fen()).replace('\\\\', '/')\n\tsplitboard = fenboard.split()[:3]\n\tbitboard = \"\"\n\n\t# Board Representation - 256 bits (8*8*4)\n\tfor curChar in splitboard[0]:\n\t\tif curChar.isdigit():\n\t\t\tbitboard += PIECE_INDEXES['number'] * int(curChar)\n\t\telif curChar in PIECE_INDEXES:\n\t\t\tbitboard += PIECE_INDEXES[curChar]\n\t\telse:\n\t\t\tpass\n\t\n\t# Active Colour - White/Black to Move - 1 bit\n\tbitboard += '0' if splitboard[1] == 'w' else '1'\n\n\t# Castling Rights - 4 bits\n\tfor curChar in splitboard[2]:\n\t\tbitboard += '1' if curChar in ('K', 'Q', 'k', 'q') else '0'\n\n\treturn bitboard\n\n# Gathering Data\n# Sample Data - 11 games - C:/Users/user/Desktop/ChessBate/data/sample_data/lichess_OtherZ_2019-06-07.pgn\n# Real Data - C:/Users/user/Desktop/ChessBate/data/ficsgamesdb_2018_standard2000_nomovetimes_70500.pgn\npgn_file = open(DATALOC.strip(\"‪u202a\"))\n\n# Preparing Data\nx_train = []\ny_train = []\nx_test = []\ny_test = []\n\n# Iterating through each game\nfor gameIndex in range(NUM_GAMES):\n\n\t# Single Game\n\tgame = chess.pgn.read_game(pgn_file)\n\tboard = game.board()\n\n\t# Iterating through each move\n\tfor moveIndex, move in enumerate(game.mainline_moves()):\n\n\t\t# Push Move on board \n\t\tboard.push(move)\n\n\t\t# Taking every 5th move\n\t\tif moveIndex != 0 and moveIndex % 5 == 0:\n\n\t\t\t# Using first TESTINDEX number of games for training and the rest for testing\n\t\t\tif gameIndex <= TESTINDEX: \n\t\t\t\tx_train.append(bitboard(board))\n\t\t\t\ty_train.append(RESULTS[game.headers[\"Result\"]])\n\t\t\telse:\n\t\t\t\tx_test.append(bitboard(board))\n\t\t\t\ty_test.append(RESULTS[game.headers[\"Result\"]])\n\nnp.savez('cleanedData.npz', np.array(x_train), np.array(y_train), np.array(x_test), np.array(y_test))\ndata = np.load('cleanedData.npz')\n#print (data['arr_0']) -> x_train\n#print (data['arr_1']) -> y_train\n#print (data['arr_2']) -> x_test\n#print (data['arr_3']) -> y_test\n\nprint (data['arr_0']) \nprint (data['arr_1']) \nprint (data['arr_2']) \nprint (data['arr_3'])","sub_path":"source/engine/formatting_data.py","file_name":"formatting_data.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"388041266","text":"\"\"\"\nML for Text Mining\nAudrey Zhang\nHW1\n\"\"\"\n\nimport numpy as np\nfrom scipy.sparse import dok_matrix, lil_matrix, csc_matrix\nfrom collections import defaultdict\nimport os\nfrom os import listdir\nimport datetime\nimport time\n\n\nclass PageRank:\n \"\"\"when no outlinks: random walk. with outlinks: alpha \"\"\"\n\n def __init__(self, alpha=0.8):\n\n self.alpha = alpha\n self.transition_mat, self.non_transition_mat = self._get_transition_matrix()\n self.topic_doc_map = self._get_topic_map()\n self.query_topic_distro = self._get_topic_distro(distro_type='query')\n self.user_topic_distro = self._get_topic_distro(distro_type='user')\n self.topic_specific_ranking = None\n self.topic_sensitive_time = None\n self.GPR_ranking = None\n\n def _get_transition_matrix(self):\n # create an inverted index of all outgoing links for a given page\n transitions = {}\n num_pages = 0\n with open('./data/transition.txt', 'r') as f:\n for line in f:\n temp_line = [int(i) for i in line.strip().split(' ')]\n\n # substract 1 from page IDs to enable matrix indexing starting at 0\n temp_line[0] -= 1\n temp_line[1] -= 1\n if temp_line[2] == 1:\n if temp_line[0] not in transitions.keys():\n transitions[temp_line[0]] = [temp_line[1]]\n else:\n transitions[temp_line[0]].append(temp_line[1])\n num_pages = max(num_pages, temp_line[0], temp_line[1])\n self.transitions = transitions\n\n # add one to num_pages because indexing starts at 0\n self.num_pages = num_pages + 1\n\n teleport_probability = 1 / self.num_pages\n self.teleportation = np.full(self.num_pages, teleport_probability)\n\n mat = defaultdict(float)\n\n # for pages without outgoing links, use lil_matrix to allow for quick update operations over entire rows\n non_transition_mat = lil_matrix((self.num_pages, self.num_pages))\n\n for page in range(self.num_pages):\n # if page has outgoing links, update the transition probabilities\n if page in transitions.keys():\n transition_prob = 1 / len(transitions[page])\n links = zip([page] * len(transitions[page]), transitions[page])\n for link in links:\n mat[link] = transition_prob\n else:\n # otherwise, set transition probability = 1/N for all pages\n non_transition_mat[page] = teleport_probability\n\n # create sparse transition probability matrix\n transition_mat = dok_matrix((self.num_pages, self.num_pages), dtype=np.float64)\n dict.update(transition_mat, mat)\n\n return transition_mat.tocsr().transpose(), non_transition_mat.tocsr().transpose()\n\n @staticmethod\n def _get_topic_map():\n topic_doc_map = {}\n\n with open('./data/doc_topics.txt', 'r') as f:\n for line in f:\n line = [int(i) for i in line.strip().split(' ')]\n if line[1] not in topic_doc_map:\n topic_doc_map[line[1]] = [line[0] - 1]\n else:\n topic_doc_map[line[1]].append(line[0] - 1)\n\n return topic_doc_map\n\n @staticmethod\n def _get_topic_distro(distro_type):\n if distro_type == 'user':\n path = './data/user-topic-distro.txt'\n elif distro_type == 'query':\n path = './data/query-topic-distro.txt'\n\n topic_distro = {}\n\n with open(path, 'r') as f:\n for line in f:\n line = line.split()\n query = tuple((int(line[0]), int(line[1])))\n interest = [float(l[1]) for l in [i.split(':') for i in line[2:]]]\n topic_distro[query] = interest\n\n return topic_distro\n\n def _power_iteration(self, beta=None, transition_distro=None, epsilon=1e-8):\n\n # initialize r_0 as a random probabilistic distribution\n r = np.random.rand(self.num_pages)\n r = r / np.sum(r)\n\n if transition_distro is None:\n # if no other transition probability distribution is provided, use traditional GPR algorithm\n while True:\n\n r_new = self.alpha * (\n self.transition_mat.dot(r) + self.non_transition_mat.dot(r)\n ) + (1 - self.alpha) * self.teleportation\n\n # check stopping criterion\n if np.linalg.norm(r_new - r) < epsilon:\n break\n else:\n r = r_new\n\n else:\n # otherwise, use modified GPR algorithm to adjust for topic- or user-topic sensitivity\n gamma = 1 - self.alpha - beta\n\n while True:\n r_new = self.alpha * (self.non_transition_mat.dot(r) + self.transition_mat.dot(r)\n ) + beta * transition_distro + gamma * self.teleportation\n\n if np.linalg.norm(r_new - r) < epsilon:\n\n break\n else:\n r = r_new\n\n r = r / np.sum(r)\n return r\n\n def global_page_rank(self):\n\n if self.GPR_ranking is None:\n start_time = time.time()\n self.GPR_ranking = self._power_iteration()\n end_time = time.time()\n run_time = end_time - start_time\n\n return self.GPR_ranking, run_time\n\n else:\n return self.GPR_ranking, None\n\n def topic_sensitive_page_rank(self):\n\n start_time = time.time()\n topic_based_ranking = []\n\n for topic, pages in self.topic_doc_map.items():\n transition_prob = 1 / len(pages)\n transition_distro = np.zeros(self.num_pages)\n transition_distro[pages] = transition_prob\n\n r = self._power_iteration(beta=0.15, transition_distro=transition_distro)\n topic_based_ranking.append(r)\n\n end_time = time.time()\n\n return np.array(topic_based_ranking), end_time - start_time\n\n def specific_topic_sensitive_pr(self, query, distro_type):\n\n if self.topic_specific_ranking is None:\n self.topic_specific_ranking, self.topic_sensitive_time = self.topic_sensitive_page_rank()\n\n start_time = time.time()\n\n if distro_type == 'user':\n topic_probability = np.array(self.user_topic_distro[query])\n if distro_type == 'query':\n topic_probability = np.array(self.query_topic_distro[query])\n\n combined_ranking = np.sum(np.multiply(self.topic_specific_ranking.transpose(), topic_probability), axis=1)\n\n run_time = time.time() - start_time\n\n return combined_ranking, run_time\n\n\ndef combine_PR_and_relevance(ranking,\n relevant_docs,\n relevance_scores,\n method,\n weight=0.3):\n \"\"\"\n\n :param ranking: PR ranking results\n :param relevant_docs: relevant document IDs based on page_relevance data\n :param relevance_scores: relevance scores based on page_relevance data\n :param method: combination method: 'NS', 'WS', or 'CM'\n :param weight: weight for PR rankings to be used in weighted sum combination method\n :return: ranked results based on the final combined PR and search-relevance scores\n \"\"\"\n # minus 1 from relevant doc id's to get indices\n relevant_doc_indices = relevant_docs - 1\n\n # get PR scores for the relevant docs\n results = ranking[relevant_doc_indices]\n\n if method == 'NS':\n pass\n\n if method == 'WS':\n results = weight * results + (1 - weight) * relevance_scores\n\n # custom combination: element-wise multiplication\n if method == 'CM':\n results = (results + relevance_scores) * relevance_scores\n\n # sort in descending value\n ranking = np.argsort(results)[::-1]\n ranked_docs = relevant_docs[ranking]\n ranked_scores = results[ranking]\n order = np.arange(len(ranked_docs)) + 1\n ranked_results = list(map(list, zip(ranked_docs, order, ranked_scores)))\n return ranked_results\n\n\ndef output_ranking_scores(filename, rankings):\n \"\"\"writes ranking scores to an output file\"\"\"\n with open('./' + filename + '.txt', 'w') as f:\n for i in range(len(rankings)):\n f.write('{} {}\\n'.format(i+1, rankings[i]))\n\n\ndef main(path='./data/indri-lists', output_queries=None):\n \"\"\"\n main function call\n :param path: path to the search-relevance score docs\n :param output_queries: None, or list of query-ids that need the converged PR ranking scores written to output\n \"\"\"\n run_id = 'run_' + str(datetime.datetime.now())\n pr_algs = ['GPR', 'QTSPR', 'PTSPR']\n combination_methods = ['NS', 'WS', 'CM']\n\n # initiate time dict to track runtime\n time_tracker = {}\n\n for p in pr_algs:\n time_tracker[p + '_ranking'] = 0.0\n\n for c in combination_methods:\n time_tracker[p + '_' + c + '_retrieval'] = 0.0\n\n # remove previous files if exists\n if os.path.exists('./' + p + '_' + c + '.txt'):\n os.remove('./' + p + '_' + c + '.txt')\n\n pr = PageRank()\n\n # get list of queries from sub-folder\n queries = listdir(path)\n n_queries = len(queries)\n\n for q in queries:\n string_id = q.split('.')[0]\n q_id = tuple([int(i) for i in string_id.split('-')])\n relevant_docs = []\n relevance_scores = []\n with open(path + '/' + q, 'r') as f:\n for line in f:\n line = line.split()\n relevant_docs.append(int(line[2]))\n relevance_scores.append(float(line[4]))\n assert len(relevant_docs) == len(relevance_scores)\n relevant_docs = np.array(relevant_docs)\n relevance_scores = np.array(relevance_scores)\n\n # iterate through PageRank algorithms:\n for rank_alg in pr_algs:\n\n if rank_alg == 'GPR':\n ranking, run_time = pr.global_page_rank()\n if run_time is not None:\n time_tracker['GPR_ranking'] = run_time\n\n if output_queries is not None:\n if string_id in output_queries:\n output_ranking_scores(rank_alg, ranking)\n\n elif rank_alg == 'QTSPR':\n ranking, run_time = pr.specific_topic_sensitive_pr(q_id, distro_type='query')\n time_tracker[p + '_ranking'] += run_time\n\n if output_queries is not None:\n if string_id in output_queries:\n output_ranking_scores('{}-U{}Q{}'.format(rank_alg, q_id[0], q_id[1]), ranking)\n\n elif rank_alg == 'PTSPR':\n ranking, run_time = pr.specific_topic_sensitive_pr(q_id, distro_type='user')\n time_tracker[p + '_ranking'] += run_time\n\n if output_queries is not None:\n if string_id in output_queries:\n output_ranking_scores('{}-U{}Q{}'.format(rank_alg, q_id[0], q_id[1]), ranking)\n\n # iterate through methods for combining PR ranking with relevance scores:\n for method in combination_methods:\n out_name = rank_alg + '_' + method + '.txt'\n\n start_time = time.time()\n ranked_results = combine_PR_and_relevance(ranking, relevant_docs,\n relevance_scores, method=method)\n end_time = time.time()\n\n time_tracker[p + '_' + c + '_retrieval'] += (end_time - start_time)\n\n with open('./' + out_name, 'a') as f:\n for i in range(len(ranked_results)):\n f.write(' '.join([string_id, 'Q0'] + [str(m) for m in ranked_results[i]] + [run_id, '\\n']))\n\n # since only 1 iteration of topic sensitive ranking was done for both QTSPR and PTSPR ranking algs\n # add the run_time the ranking time for each algorithm\n time_tracker['QTSPR_ranking'] += pr.topic_sensitive_time\n time_tracker['PTSPR_ranking'] += pr.topic_sensitive_time\n\n print('ranking and retrieval times, averaged across queries: ')\n for k, v in time_tracker.items():\n print('{}: {}s'.format(k, v/n_queries))\n\n\nif __name__ == '__main__':\n main(output_queries = '2-1')\n","sub_path":"pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":12376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"161045897","text":"def get(self, app_identifier):\n app_entry = FieldApplicationEntry.first(FieldApplicationEntry.identifier == app_identifier)\n if not app_entry is None:\n try:\n self.session = get_current_session()\n except:\n self.response.out.write(\"You are not signed in with your rep credentials.\")\n return\n\n\n booking = SurveyBooking.first(SurveyBooking.identifier == app_entry.booking_identifier)\n if not booking is None:\n proposal = CustomerProposalInfo.first(CustomerProposalInfo.field_app_identifier == app_entry.identifier)\n if not proposal is None:\n rep = FieldApplicationUser.first(FieldApplicationUser.rep_id == app_entry.rep_id)\n if not rep is None:\n template_items = {}\n template_items[\"rep_name\"] = rep.first_name.strip().title() + \" \" + rep.last_name.strip().title()\n template_items[\"rep_first_name\"] = rep.first_name.strip()\n template_items[\"customer_name\"] = app_entry.customer_first_name.strip().title() + \" \" + app_entry.customer_last_name.strip().title()\n template_items[\"customer_first_name\"] = app_entry.customer_first_name.strip().title()\n template_items[\"docs\"] = []\n template_items[\"app_entry_identifier\"] = app_identifier\n docs = ComposedDocument.query(\n ndb.AND\n (\n ComposedDocument.bundle_key == \"rep_sales_docs\",\n ComposedDocument.displayed == True\n )\n )\n doc_items = []\n for doc in docs:\n doc_items.append(doc)\n doc_items = Helpers.bubble_sort(doc_items, \"idx\")\n docs = doc_items\n\n app_entry_ol = OfficeLocation.first(OfficeLocation.identifier == app_entry.office_identifier)\n market_ol = None\n if not app_entry_ol is None:\n market_ol = OfficeLocation.first(OfficeLocation.identifier == app_entry_ol.parent_identifier)\n for doc in docs:\n fn = Helpers.compile_document_formula(json.loads(doc.criteria)[\"formula\"])\n if fn[\"fn\"](app_entry, booking, proposal, market_ol):\n template_items[\"docs\"].append({\"identifier\": doc.identifier, \"items\": json.loads(doc.template_items), \"token\": doc.token, \"page_count\": doc.page_count, \"name\": doc.name})\n\n template_items[\"docs\"] = json.dumps(template_items[\"docs\"])\n path = Helpers.get_html_path('sign.html')\n self.response.out.write(template.render(path, template_items))\n\n else:\n pending_user_identifier = app_identifier\n kv_item = KeyValueStoreItem.first(KeyValueStoreItem.keyy == \"new_user_registration_\" + pending_user_identifier)\n if not kv_item is None:\n pending_user = json.loads(kv_item.val)\n template_items = {}\n template_items[\"pending_user_identifier\"] = pending_user_identifier\n template_items[\"rep_name\"] = pending_user[\"user_first\"].strip().title() + \" \" + pending_user[\"user_last\"].strip().title()\n template_items[\"rep_first_name\"] = pending_user[\"user_first\"].strip().title()\n template_items[\"docs\"] = []\n docs = ComposedDocument.query(ComposedDocument.bundle_key == \"rep_employment_docs\")\n doc_items = []\n for doc in docs:\n doc_items.append(doc)\n doc_items = Helpers.bubble_sort(doc_items, \"idx\")\n docs = doc_items\n for doc in docs:\n fn = Helpers.compile_document_formula(json.loads(doc.criteria)[\"formula\"], True)\n if fn[\"fn\"](pending_user):\n template_items[\"docs\"].append({\"identifier\": doc.identifier, \"items\": json.loads(doc.template_items), \"token\": doc.token, \"page_count\": doc.page_count, \"name\": doc.name})\n\n template_items[\"docs\"] = json.dumps(template_items[\"docs\"])\n path = Helpers.get_html_path('sign_rep.html')\n self.response.out.write(template.render(path, template_items))\n\n\n","sub_path":"classes/SignHandler_/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"430678526","text":"from django import forms\nfrom . models import *\n\n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n widgets = {'created_at':DateInput(),'updated_at':DateInput()}\n fields = ['user','text','created_at','updated_at']\n","sub_path":"UserApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"64645104","text":"#! /usr/bin/env python3\nimport argparse\nimport heapq\n\n\nclass Day15:\n \"\"\" Day 15: Oxygen System \"\"\"\n def __init__(self, input_file):\n self.x_max = 50\n self.y_max = 50\n self.oxygen = (0, 0)\n self.grid = Grid(self.x_max, self.y_max,\n (self.x_max // 2, self.y_max // 2))\n self.dir_val = [1, 4, 2, 3]\n self.process(input_file)\n\n def process(self, input_file):\n list = {}\n data = []\n # Read all input data.\n with open(input_file, \"r\") as input:\n list = str(input.read()).split(\",\")\n # Convert input data to integer array.\n for i in list:\n data.append(int(i))\n # Initialise program, explore map to find oxygen system.\n prog = Intcode(data)\n x = self.grid.start[0]\n y = self.grid.start[1]\n dir = 0\n turn = False\n while True:\n stat, out = prog.exec(self.dir_val[dir])\n if stat == 0:\n break\n # Process output.\n if out == 0:\n # Hit wall.\n x1, y1 = self.update_coordinate(x, y, self.dir_val[dir])\n self.grid.walls.add((x1, y1))\n elif out == 1:\n # Move ok.\n x, y = self.update_coordinate(x, y, self.dir_val[dir])\n turn = True\n elif out == 2:\n # Find oxygen system.\n self.grid.goal = (x, y)\n break\n # Update direction.\n dir, turn = self.update_direction(x, y, dir, turn)\n # Find paths and there cost from start to oxygen system.\n find_path = False\n path = {}\n while not find_path:\n came_from, _ = self.a_star_search()\n path = self.reconstruct_path(came_from)\n # Execute program with this path, check if walls missing.\n prog = Intcode(data)\n for i in range(len(path) - 1):\n a = (path[i][0], path[i][1])\n b = (path[i + 1][0], path[i + 1][1])\n # Next point is goal, can stop.\n if b == self.grid.goal:\n find_path = True\n break\n # Update robot position.\n stat, out = prog.exec(self.get_direction(a, b))\n if stat == 0:\n break\n if out == 0:\n # Hit wall, need to find new path.\n self.grid.walls.add(b)\n break\n elif out == 2:\n # Find oxygen system.\n find_path = True\n break\n print(f\"Cost: {len(path)}\")\n\n def update_direction(self, x, y, dir, turn = False):\n # Look on left if force turn.\n if turn:\n dir_l = dir - 1\n if dir_l == -1:\n dir_l = 3\n xl, yl = self.update_coordinate(x, y, self.dir_val[dir_l])\n if (xl, yl) not in self.grid.walls:\n dir = dir_l\n turn = False\n # Look in front.\n xf, yf = self.update_coordinate(x, y, self.dir_val[dir])\n if (xf, yf) in self.grid.walls:\n # Wall in front, go right.\n dir += 1\n dir %= 4\n turn = True\n return dir, turn\n\n def get_direction(self, a, b):\n dir = 0\n if a[0] < b[0]:\n # East.\n dir = 4\n elif a[0] > b[0]:\n # West.\n dir = 3\n else:\n if a[1] < b[1]:\n # South.\n dir = 2\n else:\n # North.\n dir = 1\n return dir\n\n def update_coordinate(self, x, y, dir):\n # Check direction.\n if dir == 1:\n # North.\n y -= 1\n elif dir == 2:\n # South.\n y += 1\n elif dir == 3:\n # West.\n x -= 1\n else:\n # East.\n x += 1\n return x, y\n\n def reconstruct_path(self, came_from):\n start = self.grid.start\n goal = self.grid.goal\n current = goal\n path = []\n while current != start:\n path.append(current)\n current = came_from[current]\n path.append(start) # optional\n path.reverse() # optional\n return path\n\n def heuristic(self, a, b):\n (x1, y1) = a\n (x2, y2) = b\n return abs(x1 - x2) + abs(y1 - y2)\n\n def a_star_search(self):\n start = self.grid.start\n goal = self.grid.goal\n frontier = []\n heapq.heappush(frontier, (0, start))\n came_from = {}\n cost_so_far = {}\n came_from[start] = None\n cost_so_far[start] = 0\n while len(frontier) != 0:\n current = heapq.heappop(frontier)[1]\n if current == goal:\n break\n for next in self.grid.neighbors(current):\n new_cost = cost_so_far[current] + 1\n if next not in cost_so_far or new_cost < cost_so_far[next]:\n cost_so_far[next] = new_cost\n priority = new_cost + self.heuristic(goal, next)\n heapq.heappush(frontier, (priority, next))\n came_from[next] = current\n return came_from, cost_so_far\n\n\nclass Grid:\n def __init__(self, width, height, start):\n self.width = width\n self.height = height\n self.walls = set()\n self.start = start\n self.goal = (0, 0)\n\n def in_bounds(self, id):\n (x, y) = id\n return 0 <= x < self.width and 0 <= y < self.height\n\n def passable(self, id):\n return id not in self.walls\n\n def neighbors(self, id):\n (x, y) = id\n results = [(x+1, y), (x, y-1), (x-1, y), (x, y+1)]\n if (x + y) % 2 == 0: results.reverse() # aesthetics\n results = filter(self.in_bounds, results)\n results = filter(self.passable, results)\n return results\n\n def print(self):\n s = \"\"\n for y in range(self.height):\n for x in range(self.width):\n if (x, y) in self.walls:\n s += str(\"#\")\n elif (x, y) == self.start:\n s += str(\"x\")\n elif (x, y) == self.goal:\n s += str(\"o\")\n else:\n s += str(\" \")\n s += str(\"\\n\")\n print(s)\n\n def print_cost(self, cost):\n s = \"\"\n for y in range(self.height):\n for x in range(self.width):\n if (x, y) in self.walls:\n s += str(\" # \")\n elif (x, y) == self.start:\n s += str(\" x \")\n elif (x, y) == self.goal:\n s += str(\" o \")\n elif (x, y) in cost:\n s += f\"{cost[(x, y)]:3d} \"\n else:\n s += str(\" \")\n s += str(\"\\n\")\n print(s)\n return\n\n\nclass Intcode:\n \"\"\" Intcode program \"\"\"\n def __init__(self, memory, debug = False):\n self.memory = memory.copy()\n self.memory.extend([0] * (5 * 1024))\n self.pc = 0\n self.rel = 0\n self.cmd = \"\"\n self.debug = debug\n\n def exec(self, in_params):\n out_params = 0\n halt = False\n pause = False\n while not halt and not pause and self.pc < len(self.memory):\n # Get opcode and mode.\n opcode = int(self.memory[self.pc] % 100)\n mode = [int(m) for m in str(int(self.memory[self.pc] / 100))]\n mode.reverse()\n if len(mode) < 3:\n mode.extend([0] * (3 - len(mode)))\n # Parse opcode.\n if opcode == 1:\n pause = self.inst_add(mode)\n elif opcode == 2:\n pause = self.inst_mul(mode)\n elif opcode == 3:\n pause = self.inst_stdin(mode, in_params)\n elif opcode == 4:\n pause, out_params = self.inst_stdout(mode)\n elif opcode == 5:\n pause = self.inst_cbnz(mode)\n elif opcode == 6:\n pause = self.inst_cbz(mode)\n elif opcode == 7:\n pause = self.inst_lt(mode)\n elif opcode == 8:\n pause = self.inst_eq(mode)\n elif opcode == 9:\n pause = self.inst_rel(mode)\n elif opcode == 99:\n halt = self.inst_halt(mode)\n # Print executed command.\n if self.debug:\n print(self.cmd)\n # Return program output.\n ret = 0\n if pause:\n ret = 1\n return ret, out_params\n\n def read_params(self, mode, nb):\n # Get arguments.\n args = []\n for j in range(1, nb + 1):\n args.append(self.memory[self.pc + j])\n # Check for mode.\n vals = []\n dbg = []\n for j in range(0, nb):\n # Position mode.\n if mode[j] == 0:\n vals.append(self.memory[args[j]])\n dbg.append(f\"[{args[j]}]\")\n # Immediate mode.\n elif mode[j] == 1:\n vals.append(args[j])\n dbg.append(f\"{args[j]}\")\n # Relative mode.\n else:\n vals.append(self.memory[self.rel + args[j]])\n dbg.append(f\"[r{args[j]} ({self.rel + args[j]})]\")\n args[j] += self.rel\n return args, vals, dbg\n\n def inst_add(self, mode):\n args, vals, dbg = self.read_params(mode, 3)\n self.cmd = f\"{self.pc:04d}: add {dbg[2]}, {dbg[0]}, {dbg[1]}\"\n self.cmd += f\" ; {args[2]}, {vals[0]}, {vals[1]}\"\n self.memory[args[2]] = vals[0] + vals[1]\n # Move to next opcode.\n self.pc += 4\n return False\n\n def inst_mul(self, mode):\n args, vals, dbg = self.read_params(mode, 3)\n self.cmd = f\"{self.pc:04d}: mul {dbg[2]}, {dbg[0]}, {dbg[1]}\"\n self.cmd += f\" ; {args[2]}, {vals[0]}, {vals[1]}\"\n self.memory[args[2]] = vals[0] * vals[1]\n # Move to next opcode.\n self.pc += 4\n return False\n\n def inst_stdin(self, mode, in_params):\n args, _, dbg = self.read_params(mode, 1)\n self.cmd = f\"{self.pc:04d}: in {dbg[0]}, {in_params}\"\n self.cmd += f\" ; {args[0]}\"\n self.memory[args[0]] = in_params\n # Move to next opcode.\n self.pc += 2\n return False\n\n def inst_stdout(self, mode):\n _, vals, dbg = self.read_params(mode, 1)\n self.cmd = f\"{self.pc:04d}: out {dbg[0]}\"\n self.cmd += f\" ; {vals[0]}\"\n # Move to next opcode.\n self.pc += 2\n return True, vals[0]\n\n def inst_cbnz(self, mode):\n _, vals, dbg = self.read_params(mode, 2)\n self.cmd = f\"{self.pc:04d}: cbnz {dbg[0]}, {dbg[1]}\"\n self.cmd += f\" ; {vals[0]}, {vals[1]}\"\n if vals[0] != 0:\n # Move to value.\n self.pc = vals[1]\n else:\n # Move to next opcode.\n self.pc += 3\n return False\n\n def inst_cbz(self, mode):\n _, vals, dbg = self.read_params(mode, 2)\n self.cmd = f\"{self.pc:04d}: cbz {dbg[0]}, {dbg[1]}\"\n self.cmd += f\" ; {vals[0]}, {vals[1]}\"\n if vals[0] == 0:\n # Move to value.\n self.pc = vals[1]\n else:\n # Move to next opcode.\n self.pc += 3\n return False\n\n def inst_lt(self, mode):\n args, vals, dbg = self.read_params(mode, 3)\n self.cmd = f\"{self.pc:04d}: lt {dbg[2]}, {dbg[0]}, {dbg[1]}\"\n self.cmd += f\" ; {args[2]}, {vals[0]}, {vals[1]}\"\n if vals[0] < vals[1]:\n self.memory[args[2]] = 1\n else:\n self.memory[args[2]] = 0\n # Move to next opcode.\n self.pc += 4\n return False\n\n def inst_eq(self, mode):\n args, vals, dbg = self.read_params(mode, 3)\n self.cmd = f\"{self.pc:04d}: eq {dbg[2]}, {dbg[0]}, {dbg[1]}\"\n self.cmd += f\" ; {args[2]}, {vals[0]}, {vals[1]}\"\n if vals[0] == vals[1]:\n self.memory[args[2]] = 1\n else:\n self.memory[args[2]] = 0\n # Move to next opcode.\n self.pc += 4\n return False\n\n def inst_rel(self, mode):\n _, vals, dbg = self.read_params(mode, 1)\n self.cmd = f\"{self.pc:04d}: rel {dbg[0]}\"\n self.cmd += f\" ; {vals[0]}\"\n self.rel += vals[0]\n # Move to next opcode.\n self.pc += 2\n return False\n\n def inst_halt(self, mode):\n self.cmd = f\"{self.pc:04d}: halt\"\n return True\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('input', help=\"File containing day 15 input data\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n Day15(args.input)\n","sub_path":"2019/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":12897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"538501572","text":"import config\nimport json\n\nfrom time import sleep\nfrom requests import get\nfrom vk_wall_listener import get_data_from_last_wall_record\n\n\ndef send_message(message_text):\n url = 'https://api.telegram.org/bot' + config.telegram_token + '/sendMessage'\n parameters = {'chat_id': config.chat_id,\n 'text': message_text,\n 'disable_web_page_preview': True}\n r = get(url, params=parameters)\n return r\n\n\ndef send_image(image_url, message_text=None):\n url = 'https://api.telegram.org/bot' + config.telegram_token + '/sendPhoto'\n parameters = {'chat_id': config.chat_id,\n 'photo': image_url}\n if message_text:\n parameters['caption'] = message_text\n else:\n parameters['disable_notification'] = True\n r = get(url, params=parameters)\n return r\n\n\ndef send_media_group(media_urls):\n input_media_list = list()\n for url in media_urls:\n input_media_list.append({'type':'photo','media':url})\n url = 'https://api.telegram.org/bot' + config.telegram_token + '/sendMediaGroup'\n parameters = {'chat_id': config.chat_id,\n 'media': json.dumps(input_media_list)}\n r = get(url, params=parameters)\n return r\n\n\ndef has_already_been_reposted(record, chat):\n hashes = get_posted_hashes(chat)\n ids = get_posted_ids(chat)\n if ((record['hash'] in hashes)\n or (record['record_id'] in ids)\n or ((record['original_record_id'] != None)\n and (record['original_record_id'] in ids))):\n return True\n else:\n return False\n\n\ndef get_posted_hashes(chat):\n return posted_records_hashes\n # заменить потом на нормальную имплементацию с БД\n\ndef get_posted_ids(chat):\n return posted_records_ids\n # заменить потом на нормальную имплементацию с БД\n\ndef get_posted_original_ids(chat):\n return posted_records_original_ids\n # заменить потом на нормальную имплементацию с БД\n\n\ndef add_record_to_posted(record, chat):\n add_hash_to_posted(record['hash'], chat)\n add_id_to_posted(record['record_id'], chat)\n if record['original_record_id'] != None:\n add_id_to_posted(record['original_record_id'], chat) # NB! я намеренно сливаю и id конечных постов, и id оригинальных постов в одно место (для чего — см. ниже)\n # тут мы проверяем на выполнение любого условия, приводящего к отмене переброса в Телеграм:\n # — либо такое содержимое уже перебрасывали\n # (определяем по хешу, учитывающему: а) текст, б) объём каждой картинки\n # в любом порядке, если есть картинки; подробнее см. в calculate_hash_for_record())\n # — либо перпебрасывали тот же самый пост, который сейчас пытаемся перебросить\n # (определяем по id этого поста)\n # — либо перебрасывали репост того же самого оригинального поста\n # или тот же пост, репост которого сейчас пытаемся перебросить\n # (определяем по id этого и id оригинального поста, сравнивая с общей базой id)\n\ndef add_hash_to_posted(new_hash, chat):\n posted_records_hashes.append(new_hash) # пока возвращаем временный общий список; заменить потом на нормальную имплементацию\n\ndef add_id_to_posted(new_id, chat):\n posted_records_ids.append(new_id) # то же самое\n\n\nif __name__ == '__main__':\n posted_records_hashes = []\n posted_records_ids = []\n current_chat = config.chat_id # потом надо будет подставлять сюда каждый чат отдельно, если мы хотим добавить работу с разными чатами\n while True:\n for group in config.vk_group_ids:\n current_record = get_data_from_last_wall_record(group)\n if has_already_been_reposted(current_record, current_chat):\n continue\n else:\n add_record_to_posted(current_record, current_chat)\n message_text = current_record['text'].replace(\"
\", '\\n')\n if 'images' in current_record:\n if len(current_record['images']) > 1:\n send_media_group(current_record['images'])\n continue\n if len(message_text) < 200:\n send_image(current_record['images'], message_text)\n continue\n else:\n send_image(current_record['images'])\n send_message(message_text)\n if len(posted_records_hashes) > 100:\n del posted_records_hashes[0] # это точно надо будет куда-то выводить отдельно, особенно когда это уже будет не временная переменная, а БД\n sleep(30)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"90330956","text":"import os\nimport subprocess\nimport sys\nfrom unittest.mock import patch\n\n# noqa: I003\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'scripts'))\nimport tts_worker # noqa: E402,I001,I003\n\n\n@patch('subprocess.run')\ndef test_process_speech_message(run):\n # Test an old-style message.\n #\n # Eventually we'll remove this test since `test_upgrade_speech_message`\n # should handle this, but we'll use belt-and-suspenders to avoid breaking\n # clients at first.\n with patch('tts_worker.SPEECH_COMMAND', new='speech-command'):\n tts_worker.process_speech_message(dict(message='Hello world'))\n run.assert_called_with(['speech-command', 'Hello world'],\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE)\n\n # Test a new-style message.\n with patch('tts_worker.SPEECH_COMMAND', new='speech-command'):\n tts_worker.process_speech_message(dict(version='1', text='Hello world'))\n run.assert_called_with(['speech-command', 'Hello world'],\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE)\n\n\ndef test_upgrade_speech_message():\n v0_message = dict(message='Hello world')\n v1_message = dict(version='1', text='Hello world')\n assert tts_worker.upgrade_speech_message(v0_message) == v1_message, \\\n \"upgrades old-style messages\"\n assert tts_worker.upgrade_speech_message(v1_message) == v1_message, \\\n \"preserves new-style messages\"\n","sub_path":"tests/tts_worker_test.py","file_name":"tts_worker_test.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"126883071","text":"import copy\n\nimport numpy as np\n\ndef random_bottomup(leaves):\n \"\"\"\n :type leaves: list of str\n :rtype: list of str\n \"\"\"\n x = copy.deepcopy(leaves)\n while len(x) > 1:\n i = np.random.randint(0, len(x)-1)\n merged = \"( * %s %s )\" % (x[i], x[i+1])\n x[i] = merged\n x.pop(i+1)\n sexp = x[0]\n return sexp.split()\n\n","sub_path":"baselines/bu.py","file_name":"bu.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"278085644","text":"from django.urls import path\n\nfrom .views import InventoryList, ScheduleForm, ProductUpdate, MaterialUpdate\n\napp_name = \"inventory\"\n\nurlpatterns = [\n path('', InventoryList.as_view(), name='list'),\n # path('product/', ProductDetail.as_view(), name='product_detail'),\n path('schedule', ScheduleForm.as_view(), name='schedule_form'),\n path('product//update', ProductUpdate.as_view(), name='product_update'),\n path('material//update', MaterialUpdate.as_view(), name='material_update')\n]\n","sub_path":"PMIS_new-final/apps/inventory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"485984522","text":"#The below code was used to scrpe the data for the application\n#Note the link used in the web scraping i sfor educational purpose only\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport pandas as pd\nfrom scipy.sparse import csr_matrix\nfrom sklearn.neighbors import NearestNeighbors\nimport os\nimport pickle\nimport shutil\n\npath=os.path.dirname(os.path.abspath(\"scrape.py\"))\n\n# datalink='https://studyabroad.shiksha.com/usa/ms-colleges-dc'\ndatalink=\"#\"\n\nagent = {\n\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36\",\n}\n\n\nwith open(path+f'/data.csv','w') as file:\n\n file.write('Image,Universities,link,Public_university,Scholarship,Accommodation,Fees,TOEFL,IELTS,PTE,GRE\\n')\n for i in range(25):\n if i==0:\n link=datalink\n else:\n time.sleep(10)\n link=datalink+str(i+1)\n url=requests.get(link,headers=agent).text\n soup=BeautifulSoup(url,'lxml')\n ul=soup.find('ul',class_='tuple-cont')\n lis=ul.find_all('li')\n\n\n\n\n for li in lis:\n time.sleep(1)\n if li.img:\n try:\n file.write(f\"{li.img['src']},\")\n except :\n file.write(f\"{li.img['data-original']},\")\n if(li.find('div',class_='tuple-detail')!=None):\n file.write(li.find('div',class_='tuple-detail').div.a.text.replace(',',''))\n file.write(f\",{li.find('div',class_='tuple-detail').div.a['href']}\")\n box=li.find('div',class_='uni-course-details flLt')\n dummy=box.find_all('p')\n fs=dummy[len(dummy)-3:len(dummy)]\n for f in fs:\n if f.text.strip()[0]=='✔':\n file.write(',1')\n else:\n file.write(',0')\n cds=box.find_all('div')\n for i,cd in enumerate(cds):\n if(i==0):\n if(cd.p==None):\n file.write(',0')\n else:\n file.write(',{}'.format(cd.p.text.split(' ')[1]))\n if(i==1):\n exams=[0,0,0,0]\n paras=cd.find_all('p')\n for para in paras:\n if(len(para.text.strip())<11):\n es=para.text.strip()\n x=es[:1]\n if(x=='T'):\n exams[0]=es.split(\":\")[1]\n if(x=='I'):\n exams[1]=es.split(\":\")[1]\n if(x=='P'):\n exams[2]=es.split(\":\")[1]\n if(x=='G'):\n exams[3]=es.split(\":\")[1]\n for exam in exams:\n file.write(f',{exam}')\n file.write('\\n')\n\n\nshutil.copyfile(path+'/data.csv',path+'/data1.csv')\ndata=pd.read_csv(path+f'/data1.csv')\ncol=['Image','link']\npdata=data.drop(col,1)\npivot_data=pdata.set_index('Universities')\nmatrix_data=csr_matrix(pivot_data.values)\nmodel=NearestNeighbors(metric='cosine',algorithm='brute')\nmodel.fit(matrix_data)\npickle.dump(model,open(path+f'/college.pkl','wb'))\nshutil.copyfile(path+'/college.pkl',path+'/college1.pkl')\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"447418351","text":"import sys\nimport joblib\nimport math\nimport numpy as np\nfrom sklearn.metrics import balanced_accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n \n \nclass FunctionalRandomForest:\n def __init__(self,estimator_type,n_estimators=100,class_weight='balanced',\n balanced_bootstrap=True,theta=0.01,random_state=None,\n n_jobs=-1,low_memory=True):\n if not(estimator_type=='regressor' or estimator_type=='classifier'):\n print('Illegal estimator_type, must be classifier or regressor')\n sys.exit() \n self.estimator_type = estimator_type \n self.n_estimators = n_estimators\n self.class_weight = class_weight\n self.balanced_bootstrap = balanced_bootstrap\n self.theta = theta\n self.random_state = random_state\n self.n_jobs = n_jobs\n self.low_memory = low_memory\n self.criterion = None\n self.min_samples_leaf = None\n self.tree_list = []\n self.ib_samples = None\n self.oob_samples = None\n self.parameters = {}\n\n \n def set_parameters(self,parameters):\n self.min_samples_leaf = parameters['min_samples_leaf']\n self.parameters['min_samples_leaf'] = self.min_samples_leaf\n self.criterion = parameters['criterion']\n self.parameters['criterion'] = self.criterion\n self.theta = parameters['theta']\n self.parameters['theta'] = self.theta\n\n\n def predict(self,X):\n prediction = None\n bagged_pred_Y = []\n for tree in self.tree_list:\n bagged_pred_Y.append(tree.predict(X)) \n bagged_pred_Y = np.array(bagged_pred_Y)\n if self.estimator_type=='classifier':\n major_vote_Y = [] \n for j in range(X.shape[0]): \n unique_labels = np.unique(bagged_pred_Y[:,j])\n counts_dict = {label:0 for label in unique_labels}\n for label in bagged_pred_Y[:,j]:\n counts_dict[label] += 1\n max_count = 0\n max_count_label = None \n for label in unique_labels:\n if counts_dict[label] >= max_count:\n max_count = counts_dict[label]\n max_count_label = label\n major_vote_Y.append(max_count_label) \n prediction = np.array(major_vote_Y) \n else:\n mean_Y = [] \n for j in range(X.shape[0]):\n mean_Y.append(np.mean(bagged_pred_Y[:,j]))\n prediction = np.array(mean_Y) \n return prediction\n \n\n def score(self,X,Y):\n score = None\n pred_Y = self.predict(X)\n if self.estimator_type=='classifier':\n score = balanced_accuracy_score(Y,pred_Y)\n else:\n score = np.mean((pred_Y-Y)**2)\n return score \n \n \n def fit(self,X,Y):\n if self.estimator_type=='classifier':\n if self.balanced_bootstrap:\n self._bootstrap_balanced(Y)\n else:\n self._bootstrap(Y.shape[0]) \n else:\n self._bootstrap(Y.shape[0])\n for i in range(self.n_estimators):\n if self.random_state:\n random_state = self.random_state+i\n else:\n random_state = i \n estimator = FunctionalTree(self.estimator_type,\n random_state=random_state,\n criterion=self.criterion,\n min_samples_leaf=self.min_samples_leaf,\n theta=self.theta,\n class_weight=self.class_weight)\n self.tree_list.append(estimator)\n if self.low_memory: \n for tree in self.tree_list:\n tree.fit(X[self.ib_samples[i]],Y[self.ib_samples[i]]) \n else:\n self.tree_list = joblib.Parallel(n_jobs=self.n_jobs)(joblib.delayed(self.tree_list[i].fit)(X[self.ib_samples[i]],Y[self.ib_samples[i]]) for i in range(self.n_estimators))\n return self \n \n\n def _bootstrap(self,n_samples):\n np.random.seed(self.random_state)\n self.ib_samples = np.random.choice(n_samples,(self.n_estimators,n_samples))\n all_indexes = [i for i in range(n_samples)]\n self.oob_samples = []\n for j in range(self.ib_samples.shape[0]):\n self.oob_samples.append([all_indexes[i] for i in range(len(all_indexes)) if not(all_indexes[i] in self.ib_samples[j])])\n \n \n def _bootstrap_balanced(self,Y):\n n_samples = Y.shape[0]\n unique_classes = np.unique(Y)\n n_classes = len(unique_classes)\n n_samples_balanced_classes = int(math.floor(n_samples/n_classes))\n indexes_by_class = {label:[i for i in range(len(Y)) if Y[i]==label] for label in unique_classes}\n ib_samples_by_class = {label:None for label in unique_classes}\n for key,val in indexes_by_class.items():\n np.random.seed(self.random_state)\n ib_samples_by_class[key] = np.random.choice(val,(self.n_estimators,n_samples_balanced_classes))\n self.ib_samples = []\n for i in range(self.n_estimators):\n tree_ib_samples = []\n for key,val in ib_samples_by_class.items():\n tree_ib_samples.extend(val[i])\n self.ib_samples.append(tree_ib_samples) \n all_indexes = [i for i in range(n_samples)]\n self.oob_samples = []\n for i in range(len(self.ib_samples)):\n ib = self.ib_samples[i]\n self.oob_samples.append([all_indexes[i] for i in range(len(all_indexes)) if not(all_indexes[i] in ib)])\n \n \nclass FunctionalTree:\n def __init__(self,estimator_type,random_state,criterion=None,\n min_samples_leaf=1,overlapping=False,theta=0.01,\n class_weight='balanced'):\n if estimator_type=='classifier':\n self.criterion = 'gini'\n if criterion:\n self.criterion = criterion\n self.tree = DecisionTreeClassifier(criterion=self.criterion,\n min_samples_leaf=min_samples_leaf,\n class_weight=class_weight) \n else:\n self.criterion = 'mse'\n if criterion:\n self.criterion = criterion\n self.tree = DecisionTreeRegressor(criterion=self.criterion,\n min_samples_leaf=min_samples_leaf)\n self.random_state = random_state\n self.criterion = criterion\n self.min_samples_leaf = min_samples_leaf\n self.class_weight = class_weight\n self.theta = theta\n self.transform_matrix = []\n \n\n def predict(self,X):\n transformed_X = self._transform(X)\n pred = self.tree.predict(transformed_X)\n return pred\n \n \n def fit(self,X,Y):\n np.random.seed(self.random_state)\n p = X.shape[1]\n scale = 1/self.theta\n begin = 0\n end = 0\n while beginp:\n end=p\n new_row[begin:end] = 1/(end-begin) \n self.transform_matrix.append(new_row)\n begin = end\n self.transform_matrix = np.array(self.transform_matrix).transpose()\n transformed_X = self._transform(X)\n self.tree.fit(transformed_X,Y) \n return self\n \n \n def _transform(self,X):\n transformed_X = []\n for x in X:\n transformed_x = np.matmul(x,self.transform_matrix)\n transformed_X.append(transformed_x)\n return np.array(transformed_X)\n \n \n \n \n \n","sub_path":"functional_random_forest.py","file_name":"functional_random_forest.py","file_ext":"py","file_size_in_byte":8413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"537570581","text":"# pylint: disable=missing-docstring\nfrom resolwe.flow.models import Data\n\nfrom resolwe_bio.utils.test import BioProcessTestCase\n\n\nclass AbyssProcessorTestCase(BioProcessTestCase):\n\n def test_abyss(self):\n se_reads = self.prepare_reads(['reads.fastq.gz'])\n\n inputs = {'src1': ['reads_paired_abyss_1.fastq.gz'], 'src2': ['reads_paired_abyss_2.fastq.gz']}\n reads = self.run_process('upload-fastq-paired', inputs)\n\n inputs = {'paired_end': reads.pk,\n 'se': se_reads.pk,\n 'options': {'k': 25,\n 'name': 'ecoli'}}\n\n self.run_process('assembler-abyss', inputs)\n\n inputs = {'paired_end': reads.pk,\n 'se': se_reads.pk,\n 'use_unmapped': True,\n 'options': {'k': 25,\n 'name': 'ecoli'}}\n\n self.run_process('assembler-abyss', inputs, Data.STATUS_ERROR)\n","sub_path":"resolwe_bio/tests/processes/test_assembler.py","file_name":"test_assembler.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"120859566","text":"#!/usr/bin/env python3\n\nimport os\nimport json\nimport csv\nimport pandas\nimport numpy\nfrom mapping import correct_dist_map\n\n# file name which stored district and their adjacent district\n# neighbor-districts-temp.json is generated by helper_for_mapping\n\nneighbor_file = \"neighbor-districts-temp.json\"\nin_file = open(neighbor_file)\nneighbor_json = json.load(in_file)\n\n# list of all district in above data\norigdist_sorted_list = sorted(neighbor_json.keys())\n# print(origdist_sorted_list)\n\norigdist_name_list = []\nfor dist in origdist_sorted_list:\n temp = dist.split('/')\n origdist_name_list.append(temp[0])\n\nkeeporigdist_obsdist_map = {}\n# consist of dist which are either directly present in obs dist list\n# or mapped to one of obs_dist list\n# name of this state must be of smaller case only upto this state\nfor dist in correct_dist_map.keys():\n if correct_dist_map[dist] != \"*\":\n keeporigdist_obsdist_map[correct_dist_map[dist]] = dist # dist here represent observed dist, so value is observed one\n\nfile_name = \"helper-data/obsdist-stateID/obsdist-stateID.csv\"\nobsdist_stateID_df = pandas.read_csv(file_name)\n# print(obsdist_stateID_df)\n\nobs_dist_name_list = list(obsdist_stateID_df[\"dist_transformed_name\"])\nfor dist in obs_dist_name_list:\n if dist in origdist_name_list:\n keeporigdist_obsdist_map[dist] = dist\n\n# print(keeporigdist_obsdist_map)\n# print(\"temp_dist_to_keep_list\", len(keeporigdist_obsdist_map))\n\norig_dist_to_keep_list = keeporigdist_obsdist_map.keys()\n\nnew_old_name_dict = {}\nfor dist in keeporigdist_obsdist_map.keys():\n new_name = keeporigdist_obsdist_map[dist] # new_name is obs_dist which is mapped with orig_dist\n for idx in obsdist_stateID_df.index: # observed data frame\n if obsdist_stateID_df.loc[idx, \"dist_transformed_name\"] == new_name:\n name_observed = obsdist_stateID_df.loc[idx, \"dist_name_at_portal\"]\n new_old_name_dict[dist] = name_observed\n break\n# print(new_old_name_dict)\n\n\nneighbor_districts_modified = {}\nfor dist in neighbor_json.keys():\n # print(dist)\n temp = dist.split('/') #split to separate name with Q id, temp[0] is name\n if temp[0] in orig_dist_to_keep_list:\n\n temp_adj_dist_list = [] # this list will keep all adjacent dist direct neighbor and \n # and if some neighbor is about to delete then neighbor of that neighbor\n\n set_size = 0 # help to keep status whether at each iteration whether adj dist is being added or not\n # otherwise we can quit as, we are sure that we have added all neighbor including nighbor of about to delete neighnor\n temp_adj_dist_set = set()\n\n adj_dist_list = neighbor_json[dist]\n for dist1 in adj_dist_list:\n temp_adj_dist_set.add(dist1)\n \n while len(temp_adj_dist_set) != set_size:\n set_size = len(temp_adj_dist_set) # to keep record of whether new element added to set or not\n temp_set = set()\n # iterate through each neighbor and add adj dist of neighbor which we are going to delete\n # from final neighbor list\n for dist2 in temp_adj_dist_set: #iterating in set\n temp2 = dist2.split('/') # separate name from Q id of orig dist\n\n # we are not going to add neighbor of district which is already going to be there in final neighbor list\n if temp2[0] in orig_dist_to_keep_list: \n continue\n else:\n # but add neighbor of all those district which are going to be deleted from final neighbor list\n temp_list_adj = neighbor_json[dist2]\n for dist3 in temp_list_adj:\n # temp3 = dist3.split('/')\n # if temp3[0] in orig_dist_to_keep_list:\n temp_set.add(dist3) # set will automatically remove repetition\n for set_elem in temp_set:\n temp_adj_dist_set.add(set_elem)\n for dist4 in temp_adj_dist_set:\n # print(adj_dist)\n temp4 = dist4.split('/')\n if temp4[0] in orig_dist_to_keep_list:\n old_name4 = new_old_name_dict[temp4[0]]\n old_name4 = old_name4 + \"/\" + temp4[1]\n temp_adj_dist_list.append(old_name4)\n old_name5 = new_old_name_dict[temp[0]]\n old_name5 = old_name5 + \"/\" + temp[1]\n # remove self loop as a district should not be district of itself\n if old_name5 in temp_adj_dist_list:\n temp_adj_dist_list.remove(old_name5)\n neighbor_districts_modified[old_name5] = temp_adj_dist_list\n\n\n# assigning id's to neighbor-district-modified\ndist_id_dict = {}\ndist_list = sorted(neighbor_districts_modified.keys())\n# print(dist_list)\nid = 101\nfor dist in dist_list:\n dist_id_dict[dist] = id\n id += 1\n\n# print(dist_id_dict)\n\ndist_id_path = \"origdist-id/\"\nif not os.path.exists(dist_id_path):\n os.mkdir(dist_id_path)\ndistid = os.path.join(dist_id_path, \"origdist-id.json\")\nwith open(distid, 'w') as fp_w :\n json.dump(dist_id_dict, fp_w, indent=4)\n# print(\"saving district-id jason -> origdist-id/origdist-id.json\")\n\n\nfile_name = \"neighbor-districts-modified.json\"\nwith open(file_name, 'w') as fp_w:\n json.dump(neighbor_districts_modified, fp_w, indent=4)\n# print(\"saving neighbor-districts-modified.json ...\")\n\nfolder_name = \"helper-data/new-old-dist-name\"\nif not os.path.exists(folder_name):\n os.mkdir(folder_name)\nfile_name = \"helper-data/new-old-dist-name/new-old-dist-name.json\"\nwith open(file_name, 'w') as fp_w:\n json.dump(new_old_name_dict, fp_w, indent=4)\n# print(\"A json to change original district name based on portal district name is saved -> helper-data/new-old-dist-name/new-old-dist-name.json\")","sub_path":"Code_and_Data/que1script.py","file_name":"que1script.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"188947105","text":"import hashlib\nimport math\nimport random as r\nimport pandas as pd\nimport time\nimport os\nimport psutil\nimport heapq\nimport json\nimport requests\nfrom threading import Thread\nfrom mlxtend.frequent_patterns import fpgrowth\nfrom mlxtend.frequent_patterns import apriori\nfrom mlxtend.frequent_patterns import association_rules\nimport socket\nimport wget\nimport subprocess as sp\nimport argparse\nimport config\nimport smtplib\nfrom email.message import EmailMessage\nimport pickle\nimport paho.mqtt.client as mqtt\nimport re\n\n\nclass Record:\n system = psutil.Process(os.getpid())\n\n def __init__(self, window_size, title):\n self.data_set = []\n self.window_size = window_size\n self.title = title\n self.count = 0\n\n def get_data(self):\n return 1\n\n def add_data(self):\n data = self.get_data()\n new_avg = self.calculate_mov_avg(data)\n self.check_window_size()\n self.data_set.append(new_avg)\n\n def check_window_size(self):\n if len(self.data_set) > self.window_size:\n outfile = open(f'results/{self.title}/{self.count}.pickle', 'wb')\n pickle.dump(self.data_set, outfile)\n outfile.close()\n self.data_set = self.data_set[-1:]\n self.count += 1\n\n def calculate_mov_avg(self, a1):\n _count = len(self.data_set)\n if _count == 0:\n avg1 = 0\n else:\n avg1 = self.data_set[-1]\n _count += 1\n avg1 = ((_count - 1) * avg1 + a1) / _count # cumulative average formula μ_n=((n-1) μ_(n-1) + x_n)/n\n return round(avg1, 4)\n\n\nclass CPU(Record):\n def get_data(self):\n cpu = psutil.cpu_percent(percpu=False)\n try:\n lst = self.data_set[-1]\n except IndexError:\n lst = psutil.cpu_percent(percpu=False)\n return round(abs(cpu - lst), 4)\n\n\nclass Memory(Record):\n\n def get_data(self):\n return round(self.system.memory_percent(), 4)\n\n\nclass Delay:\n def __init__(self, window_size):\n self.data_set = []\n self.window_size = window_size\n self.count = 0\n\n def add_data(self, data):\n new_avg = self.calculate_mov_avg(data)\n self.data_set.append(new_avg)\n self.check_window_size()\n\n def calculate_mov_avg(self, a1):\n _count = len(self.data_set)\n if _count == 0:\n avg1 = 0\n else:\n avg1 = self.data_set[-1]\n _count += 1\n avg1 = ((_count - 1) * avg1 + a1) / _count # cumulative average formula μ_n=((n-1) μ_(n-1) + x_n)/n\n return round(avg1, 4)\n\n def check_window_size(self):\n if len(self.data_set) > self.window_size:\n outfile = open(f'results/delay/{self.count}.pickle', 'wb')\n pickle.dump(self.data_set, outfile)\n outfile.close()\n self.data_set = self.data_set[-1:]\n self.count += 1\n\n\nclass Heap:\n def __init__(self):\n self.heap = [] # delay\n heapq.heapify(self.heap)\n self.table = {} # delay : mec\n\n def unique_delay(self, delay):\n if delay in self.heap:\n delay -= 0.00001\n return self.unique_delay(delay)\n else:\n return delay\n\n def push(self, delay, mec):\n if mec not in self.table.values():\n delay = self.unique_delay(delay)\n heapq.heappush(self.heap, delay)\n self.table[delay] = mec\n\n def remove(self, mec):\n if mec in self.table.values():\n t_mec = dict(zip(self.table.values(), self.table.keys()))\n delay_key = t_mec[mec]\n self.heap.remove(delay_key)\n heapq.heapify(self.heap)\n self.table.pop(delay_key)\n\n def get_head(self):\n if len(self.heap) != 0:\n return self.table[self.heap[0]]\n else:\n return None\n\n def __len__(self):\n return len(self.heap)\n\n def pop(self):\n return heapq.heappop(self.heap)\n\n def push_pop(self, item):\n \"\"\":arg\n Push item on the heap, then pop and return the smallest item from the heap\n \"\"\"\n return heapq.heappushpop(self.heap, item)\n\n def replace(self, item):\n \"\"\":arg\n Pop and return the smallest item from the heap, and also push the new item\n \"\"\"\n return heapq.heapreplace(self.heap, item)\n\n\nclass CollaborativeCache:\n def __init__(self, no_mec):\n self.cache_store = {} # {cache_id: heap({mec1, mec2}), ..}\n self.w = 0.1 # No of MEC that can store a cache in percentage\n self.no_mec = no_mec\n\n def cache_decision(self, length):\n if length < math.ceil(self.w * self.no_mec):\n return 1\n else:\n return 0\n\n @staticmethod\n def ping(host):\n cmd = [f'ping -c 1 {host}']\n try:\n output = str(sp.check_output(cmd, shell=True), 'utf-8').split('\\n')\n except sp.CalledProcessError:\n print(f'{host} -> destination unreachable..')\n return None\n try:\n value = float(output[-2].split('=')[-1].split('/')[0])\n except ValueError:\n print(f\"{output[-2].split('=')[-1].split('/')[0]} -> Ping Value Error\")\n value = None\n return value\n\n def get_delay(self, mec):\n rtt = self.ping(mec)\n if rtt:\n return round(rtt, 4)\n else:\n return self.get_delay(mec)\n\n def add_cache(self, cache_content_hash, mec): # multi-cast from mec\n mec_delay = self.get_delay(mec)\n if cache_content_hash not in self.cache_store:\n self.cache_store[cache_content_hash] = Heap()\n self.cache_store[cache_content_hash].push(mec_delay, mec)\n\n def find_cache(self, cache_content_hash):\n try:\n mec = self.cache_store[cache_content_hash].get_head()\n return mec, self.cache_decision(len(self.cache_store[cache_content_hash]))\n except KeyError:\n return None\n\n def replace(self, mec, old_cache, new_cache): # multi-cast from mec\n self.cache_store[old_cache].remove(mec)\n if len(self.cache_store[old_cache]) == 0:\n self.cache_store.pop(old_cache)\n self.add_cache(new_cache, mec)\n\n\n# A linked list node\nclass Node:\n # Constructor to create a new node\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n self.id = self.get_hash()\n self.count = 0\n self.last_access = time.time()\n self.retrieval_cost = 0\n self.content_id = None\n\n @property\n def page_no(self):\n return re.findall('[0-9]+', self.data.split('/')[-1])\n\n def get_hash(self):\n y = str.encode(str(self.data))\n ha = hashlib.sha256(y)\n hash_no = ha.hexdigest()\n return hash_no\n\n @property\n def details(self):\n d = lambda x: None if x is None else x.data\n return {'data': self.data, 'next': d(self.next), 'prev': d(self.prev), 'count': self.count}\n\n def reduce_count(self):\n self.count = math.ceil(self.count / 2)\n\n\nclass FIFO:\n def __init__(self, maxsize):\n self.head = None\n self.tail = None\n self.length = 0\n self.table = {}\n self.maxsize = maxsize\n\n # Given a reference to the head of a list and an\n # integer, inserts a new node on the front of list\n def push(self, new_node):\n\n # 1. Allocates node\n # 2. Put the data in it\n\n self.table[new_node.id] = new_node\n\n # 3. Make next of new node as head and\n # previous as None (already None)\n new_node.next = self.head\n\n # 4. change prev of head node to new_node\n if self.head is not None:\n self.head.prev = new_node\n\n # 5. move the head to point to the new node\n self.head = new_node\n if not self.tail:\n self.tail = new_node\n\n self.length += 1\n self.maintain_size()\n\n return new_node\n\n def maintain_size(self):\n if self.length > self.maxsize:\n self.delete(self.tail)\n\n def delete(self, node):\n if node.id in self.table:\n node = self.table.pop(node.id)\n if node.prev:\n if node.next: # delete a middle node\n node.prev.next = node.next\n node.next.prev = node.prev\n else: # delete last node\n node.prev.next = None\n self.tail = node.prev\n\n else: # delete head node\n self.head = node.next\n if node.next:\n node.next.prev = None\n else:\n self.tail = None\n self.length -= 1\n return node\n\n def list(self):\n d_list = []\n node = self.head\n while node:\n d_list.append(node.data)\n node = node.next\n return d_list\n\n def reduce_count(self):\n node = self.head\n while node:\n node.reduce_count()\n node = node.next\n\n\n# Class to create a Doubly Linked List\nclass LRUChain:\n\n # Constructor for empty Doubly Linked List\n def __init__(self):\n self.head = None\n self.tail = None\n self.length = 0\n self.table = {}\n\n # Given a reference to the head of a list and an\n # integer, inserts a new node on the front of list\n def push(self, new_node):\n\n # 1. Allocates node\n # 2. Put the data in it\n\n if new_node.id in self.table:\n new_node = self.delete_node(self.table[new_node.id])\n new_node.next = None\n new_node.prev = None\n self.table[new_node.id] = new_node\n\n # 3. Make next of new node as head and\n # previous as None (already None)\n new_node.next = self.head\n\n # 4. change prev of head node to new_node\n if self.head is not None:\n self.head.prev = new_node\n\n # 5. move the head to point to the new node\n self.head = new_node\n if not self.tail:\n self.tail = new_node\n\n self.length += 1\n\n return new_node\n\n def print_list(self, node):\n print(\"\\nTraversal in forward direction\")\n while node is not None:\n print(node.data)\n node = node.next\n\n print(\"\\nTraversal in reverse direction\")\n last = self.tail\n while last is not None:\n print(last.data)\n last = last.prev\n\n def find(self, id_):\n node = self.head\n while node:\n if node.id == id_:\n result = f'id: {id_} \\nData: {node.data}'\n print(result)\n return node\n node = node.next\n return None\n\n def remove_with_id(self, id_):\n node = self.find(id_)\n if node:\n if node.prev:\n if node.next: # delete a middle node\n node.prev.next = node.next\n node.next.prev = node.prev\n else: # delete last node\n node.prev.next = None\n self.tail = node.prev\n print(f'Deleted {id_}')\n else: # delete head node\n self.head = node.next\n if node.next:\n node.next.prev = None\n else:\n self.tail = None\n print(f'Deleted {id_}')\n self.length -= 1\n return node\n\n def remove_with_data(self, data):\n node = self.head\n while node:\n if node.data == data:\n if node.prev:\n if node.next: # delete a middle node\n node.prev.next = node.next\n node.next.prev = node.prev\n else: # delete last node\n node.prev.next = None\n self.tail = node.prev\n print(f'Deleted {data}')\n else: # delete head node\n self.head = node.next\n if node.next:\n node.next.prev = None\n else:\n self.tail = None\n print(f'Deleted {data}')\n self.length -= 1\n return node\n node = node.next\n return None\n\n def delete_node(self, node):\n if node.id in self.table:\n node = self.table.pop(node.id)\n if node.prev:\n if node.next: # delete a middle node\n node.prev.next = node.next\n node.next.prev = node.prev\n else: # delete last node\n node.prev.next = None\n self.tail = node.prev\n\n else: # delete head node\n self.head = node.next\n if node.next:\n node.next.prev = None\n else:\n self.tail = None\n self.length -= 1\n return node\n\n def list(self):\n d_list = []\n node = self.head\n while node:\n d_list.append(node.data)\n node = node.next\n return d_list\n\n def details(self):\n d_list = []\n node = self.head\n while node:\n d_list.append(node.details)\n node = node.next\n return d_list\n\n def count_display(self):\n d_list = []\n node = self.head\n while node:\n d_list.append(node.count)\n node = node.next\n return d_list\n\n def hash_table(self):\n d_list = {}\n node = self.head\n while node:\n d_list[node.id] = node.data\n node = node.next\n return d_list\n\n\nclass NameResolutionServer:\n def __init__(self, content_name_server):\n self.content_name_server = content_name_server\n\n def get_json_data(self, endpoint, send=None):\n url = f'http://{self.content_name_server}/'\n if send:\n response = requests.post(url + endpoint, json=json.dumps(send))\n else:\n response = requests.get(url + endpoint)\n data = json.loads(response.content)\n return data\n\n def add_to_server(self, location_hash, content_hash, url):\n self.get_json_data(endpoint='add/', send=[location_hash, content_hash, url])\n\n def get_content_hash(self, location_hash):\n return self.get_json_data(endpoint=f'read/hash/{location_hash}')['hash']\n\n\nclass LocalCache:\n\n def __init__(self, cache_size, max_freq, avg_max, window_size, content_name_server, delay):\n self.cache_size = cache_size\n self.max_freq = max_freq\n self.history = FIFO(cache_size * 8)\n self.chain = {}\n self.table = {}\n self.length = 0\n self.hit = 0\n self.miss = 0\n self.mec_hit = 0\n self.avg_max = avg_max\n self.min_freq = 1\n self.content_name_server = content_name_server\n self.delay = delay\n self.cache_dir = '/srv/ftp/cache'\n self.req_window = window_size ** 2\n self.window_size = window_size\n self.req = []\n self.to_delete = ['test']\n self.pre_cached = 0\n self.no_rules = 6\n self.rules = RuleStore(ant_max=4, max_length=20)\n self.content_name_resolution = NameResolutionServer(content_name_server=content_name_server)\n self.rule_matches = {'match': [], 'right': 0, 'wrong': 0, 'window_count': 0,\n 'window_size': int(self.window_size / 2), 'rule_count': 0, 'pre_cache_check': 0,\n 'right_pre_cache': 0, 'wrong_pre_cache': 0}\n\n @staticmethod\n def web_page(request):\n return f\"https://competent-euler-834b51.netlify.app/pages/{request}.html\"\n\n @staticmethod\n def get_hash(data):\n y = str.encode(str(data))\n ha = hashlib.sha256(y)\n hash_no = ha.hexdigest()\n return hash_no\n\n @staticmethod\n def mec_cache_link(content_hash, mec):\n return f\"ftp://{mec}/cache/{content_hash}.html\"\n\n def rename_to_content_hash(self, web_link, filename, temp=0):\n file_ = open(filename, 'rb')\n content_hash = hashlib.sha256(file_.read()).hexdigest()\n file_.close()\n self.content_name_resolution.add_to_server(content_hash=content_hash, url=web_link,\n location_hash=self.get_hash(web_link))\n if temp == 0:\n os.system(f'mv {self.cache_dir}/temp {self.cache_dir}/{content_hash}.html')\n return content_hash\n\n def get_file(self, request_link, temp=0):\n name = request_link.split('/')[-1]\n start = time.perf_counter()\n if temp == 1:\n filename = f'temp/{name}'\n try:\n wget.download(request_link, filename)\n except Exception as e:\n wget.download(request_link, filename)\n else:\n filename = f'{self.cache_dir}/temp'\n try:\n wget.download(request_link, filename)\n except Exception as e:\n wget.download(request_link, filename)\n cost = round(time.perf_counter() - start, 5)\n content_hash = self.rename_to_content_hash(web_link=request_link, filename=filename, temp=temp)\n\n return cost, content_hash\n\n def association_match_count(self, req):\n if len(self.rule_matches['match']) != 0:\n if req in self.rule_matches['match']:\n self.rule_matches['right'] += 1\n if self.rule_matches['pre_cache_check'] != 0:\n self.rule_matches['right_pre_cache'] += 1\n self.rule_matches['pre_cache_check'] = 0\n else:\n self.rule_matches['wrong'] += 1\n if self.rule_matches['pre_cache_check'] != 0:\n self.rule_matches['wrong_pre_cache'] += 1\n self.rule_matches['pre_cache_check'] = 0\n self.rule_matches['match'] = []\n\n def add_req_to_list(self, cache):\n self.window_check()\n self.req.append(cache)\n\n def window_check(self):\n if len(self.req) > self.req_window:\n self.req.pop(0)\n\n @property\n def average_count(self):\n return round(sum(self.chain.keys()) / len(self.chain), 2)\n\n def maintain_count(self):\n if self.average_count > self.avg_max:\n # print('start: ', self.details_display())\n new_chain = {}\n event = 'maintaining count... ..'\n display_event(kind='notify', event=event, origin='maintain_count')\n\n def reduce_count(node):\n while node:\n node.reduce_count()\n if node.count not in new_chain: new_chain[node.count] = LRUChain()\n new_chain[node.count].push(node)\n if node.count < self.min_freq: self.min_freq = node.count\n node = node.prev\n\n for chain in self.chain.values():\n reduce_count(chain.tail)\n self.history.reduce_count()\n self.chain = new_chain\n\n def increment_count_decision(self, node):\n diff = 1\n # event = f'loop list -> {list(range(node.count-1, 0, -1))}'\n # display_event(kind='notify', event=event, origin='increment_count_decision')\n for tf in range(node.count - 1, 0, -1):\n try:\n q = self.chain[tf]\n print('in->', tf, q)\n break\n except KeyError:\n diff += 1\n if diff < self.max_freq:\n return True, diff\n else:\n return False, diff\n\n def request(self, page):\n self.push(page)\n self.association_match_count(page)\n if self.rule_matches['window_count'] == self.rule_matches['window_size']:\n self.get_association_rules()\n self.apply_association()\n self.rule_matches['window_count'] = 0\n else:\n if len(self.rules) > 0:\n self.apply_association()\n self.rule_matches['window_count'] += 1\n\n def push(self, page, precache=0):\n web_link = self.web_page(page)\n new_node = Node(web_link)\n if precache == 0:\n self.add_req_to_list(page)\n decision = [1, None] # 0 means don't cache, 1 means cache\n if new_node.id in self.table:\n if precache == 1:\n decision[0] = 0\n display_event(kind='notify', event='Association Precache already in store', origin='push')\n else:\n self.delay.add_data(0)\n display_event(kind='notify', event=f'Cache Hit', origin='push from LocalCache')\n new_node = self.table[new_node.id] # dont remove this, it is useful, even if you dont think it is\n new_node = self.chain[new_node.count].delete_node(new_node) # self.table[new_node.id]\n new_node.prev, new_node.next = None, None\n new_node.last_access = time.time()\n self.hit += 1\n result = self.increment_count_decision(new_node)\n if self.chain[new_node.count].length == 0:\n self.chain.pop(new_node.count)\n\n if result[0] and (self.min_freq == new_node.count):\n self.min_freq += 1\n if result[0]:\n display_event(kind='notify', event=f'incrementing ->{result}', origin='push from LocalCache')\n new_node.count += 1\n else:\n display_event(kind='notify', event=f'Not incrementing ->{result}', origin='push from LocalCache')\n # print('hit')\n\n else:\n display_event(kind='notify', event='cache miss', origin='push from LocalCache')\n mec = self.check_mec(new_node) # (mec, cache_decision[0,1])\n if mec:\n self.mec_hit += 1\n decision[0] = mec[1]\n link = self.mec_cache_link(content_hash=new_node.content_id, mec=mec[0])\n event = 'cached from mec'\n display_event(kind='notify', event=event, origin='push from LocalCache')\n if (decision[0] == 1) and (self.length >= self.cache_size): # cache and cache is full\n decision = self.maintain_cache_size(new_node)\n new_node = new_node if decision[1] is None else decision[1]\n if (decision[0] == 1) and ((precache == 0) or (new_node.count == 0)): # do if only cache is to be stored! maintain min freq\n if new_node.count + 1 < self.min_freq:\n if self.min_freq - self.max_freq > new_node.count + 1:\n new_node.count = self.min_freq - self.max_freq\n self.min_freq = new_node.count + 1\n new_node.count += 1\n self.table[new_node.id] = new_node\n self.length += 1\n # if (precache == 0) or (new_node.count == 0):\n # new_node.count += 1\n event = f'incrementing new ->{new_node.count} | {self.chain.keys()}' # incremented always for miss\n display_event(kind='notify', event=event, origin='push from LocalCache')\n # decision 1 => cache\n # temp 1 => dont cache\n new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=link, temp=decision[0]^1)\n elif (decision[0] == 1) and (self.length < self.cache_size): # cache and cache not full\n\n self.table[new_node.id] = new_node\n self.length += 1\n if (precache == 0) or (new_node.count == 0):\n if new_node.count + 1 < self.min_freq:\n if self.min_freq - self.max_freq > new_node.count + 1:\n new_node.count = self.min_freq - self.max_freq\n self.min_freq = new_node.count + 1\n new_node.count += 1\n event = f'incrementing new ->{new_node.count} | {self.chain.keys()}' # incremented always for miss\n display_event(kind='notify', event=event, origin='push from LocalCache')\n new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=link,\n temp=decision[0] ^ 1)\n else: # dont cache\n if precache == 0:\n new_node.count += 1\n event = f'Not stored |incrementing new ->{new_node.count} | {self.chain.keys()}'\n else:\n event = f'Not stored | Not incrementing new ->{new_node.count} | {self.chain.keys()}'\n new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=link, temp=1)\n display_event(kind='notify', event=event, origin='push from LocalCache')\n if len(decision) == 3:\n if decision[2]:\n messenger.publish('cache/replace',\n pickle.dumps([ip_address(), decision[2].content_id, new_node.content_id]))\n elif self.length < self.cache_size: # decision is right | send add cache only when length > cache_size\n messenger.publish('cache/add', pickle.dumps([new_node.content_id, ip_address()]))\n else:\n if precache == 0:\n self.miss += 1\n if self.length >= self.cache_size:\n decision = self.maintain_cache_size(new_node)\n\n if decision[0] == 1:\n new_node = new_node if decision[1] is None else decision[1]\n if (precache == 0) or (new_node.count == 0):\n if new_node.count + 1 < self.min_freq:\n if self.min_freq - self.max_freq > new_node.count + 1:\n new_node.count = self.min_freq - self.max_freq\n self.min_freq = new_node.count + 1\n new_node.count += 1\n event = f'incrementing new ->{new_node.count} | {self.chain.keys()}'\n display_event(kind='notify', event=event, origin='push from LocalCache')\n self.table[new_node.id] = new_node\n self.length += 1\n new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=web_link, temp=0)\n else:\n if precache == 0:\n new_node.count += 1\n new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=web_link, temp=1)\n event = f'incrementing new ->{new_node.count} | {self.chain.keys()}'\n display_event(kind='notify', event=event, origin='push from LocalCache')\n if len(decision) == 3:\n if decision[2]:\n messenger.publish('cache/replace',\n pickle.dumps([ip_address(), decision[2].content_id, new_node.content_id]))\n\n elif self.length < self.cache_size: # decision is right | send add cache only when length > cache_size\n messenger.publish('cache/add', pickle.dumps([new_node.content_id, ip_address()]))\n\n if precache == 1:\n self.pre_cached += 1\n self.rule_matches['pre_cache_check'] += 1\n else:\n self.delay.add_data(new_node.retrieval_cost)\n\n if decision[0] == 1:\n try:\n self.chain[new_node.count].push(new_node)\n except KeyError:\n self.chain[new_node.count] = LRUChain()\n self.chain[new_node.count].push(new_node)\n self.maintain_count()\n\n def check_mec(self, new_node):\n if new_node.id in self.history.table:\n return collaborative_cache.find_cache(new_node.content_id)\n else:\n content_id = self.content_name_resolution.get_content_hash(location_hash=new_node.id)\n if content_id:\n new_node.content_id = content_id\n return collaborative_cache.find_cache(content_id)\n return None\n\n def find_new_min_freq(self):\n found = False\n for i in range(self.min_freq, self.min_freq + self.max_freq + 1):\n try:\n tail_node = self.chain[i].tail\n self.min_freq = tail_node.count\n found = True\n break\n except KeyError:\n pass\n if found:\n event = f'next min freq found -> {self.min_freq}'\n display_event(kind='notify', event=event, origin='find_new_min_freq')\n else:\n event = f'next min freq not found-> {self.min_freq} | ' \\\n f'{list(range(self.min_freq, self.min_freq + self.max_freq + 1))}'\n display_event(kind='notify', event=event, origin='find_new_min_freq')\n\n def maintain_cache_size(self, node):\n cache_decision = 0 # 0 means don't cache, 1 means cache\n replaced = None\n if node.id in self.history.table:\n node = self.history.delete(node)\n node.next, node.prev = None, None\n min_queue = self.chain[self.min_freq]\n victim = min_queue.tail\n # print(self.sorted_freq.heap)\n # print('comparing: ', node.data, victim.data, '->', self.data_display())\n if (node.last_access > victim.last_access) or (node.retrieval_cost > victim.retrieval_cost):\n # print('before eviction ++++', self.data_display() )\n self.evict(victim)\n replaced = victim\n victim.next, victim.prev = None, None\n self.history.push(victim)\n node.last_access = time.time()\n cache_decision += 1\n # print('evicted: ++++', victim.data, 'recap: ', self.data_display())\n else:\n node.last_access = time.time()\n self.history.push(node)\n\n else:\n self.history.push(node)\n\n return cache_decision, node, replaced\n\n def evict(self, victim):\n os.system(f'rm {self.cache_dir}/{self.to_delete.pop(0)}.html')\n self.to_delete.append(victim.content_id)\n self.chain[victim.count].delete_node(victim)\n self.length -= 1\n self.table.pop(victim.id)\n if self.chain[victim.count].length == 0:\n self.chain.pop(victim.count)\n self.find_new_min_freq()\n\n return victim\n\n def apply_association(self):\n match = 0\n for i in range(1, self.rules.ant_max + 1):\n try:\n cons = self.rules.rules[i][tuple(self.req[-i:])]\n self.rule_matches['match'] += list(cons)\n display_event(kind='notify', event=f'association match {cons}', origin='apply_association')\n for page in cons:\n self.push(page, precache=1)\n match += 1\n except KeyError:\n pass\n if match == 0:\n display_event(kind='notify', event=f'No association Match', origin='apply_association')\n\n def get_association_rules(self):\n if len(self.req) >= self.window_size:\n group_no = len(set(self.req[-self.window_size:]))\n data_len = group_no ** 2\n if len(self.req) >= data_len:\n data = self.req[-data_len:]\n print(f'Generating Association rules for data {group_no}x{len(data)}')\n t1 = time.time()\n rules = AssociateCache(data=data, rule_no=self.no_rules, group_no=group_no).gen_rules()\n self.rules.add_rules(rules)\n self.rule_matches['rule_count'] += 1\n t2 = time.time()\n display_event(kind=f'Association Rules | Time: {round(t2-t1, 5)}', event=rules,\n origin='get_association_rules')\n\n def total_hit_ratio(self):\n return round((((self.hit + self.mec_hit) / (self.hit + self.mec_hit + self.miss)) * 100), 2)\n\n def mec_hit_ratio(self):\n return round((self.mec_hit / (self.hit + self.mec_hit)) * 100, 2)\n\n def hit_ratio(self):\n return round((self.hit / (self.hit + self.mec_hit + self.miss)) * 100, 2)\n\n def right_predictions(self):\n return round((self.rule_matches['right'] / (self.rule_matches['right'] + self.rule_matches['wrong'])) * 100)\n\n def data_display(self):\n return {i: self.chain[i].list() for i in self.chain}\n\n def details_display(self):\n return {i: self.chain[i].details() for i in self.chain}\n\n def outcome_details(self):\n text = {'right_match': self.rule_matches['right'],\n 'Wrong_match': self.rule_matches['wrong'],\n 'right_pre_cache': self.rule_matches['right_pre_cache'],\n 'wrong_pre_cache': self.rule_matches['wrong_pre_cache'],\n 'total_hit_ratio': self.total_hit_ratio(),\n 'mec_hit_ratio': self.mec_hit_ratio(),\n 'hit_ratio': self.hit_ratio()\n }\n\n return text\n\n def experiment_details(self):\n print('Total Hit ratio: ', self.total_hit_ratio(), '%')\n print('mec hit ratio: ', self.mec_hit_ratio(), '%')\n print('hit ratio: ', self.hit_ratio(), '%')\n print('Pre-cached: ', self.pre_cached)\n total_matches = (self.rule_matches['right'] + self.rule_matches['wrong'])\n if total_matches != 0:\n pred = round((self.rule_matches['right'] / total_matches) * 100)\n else:\n pred = 0\n print('Right Predictions: ', pred, '%')\n print(f\"Generated {self.rule_matches['rule_count']} rules \")\n print(f\"No of association matches: \", self.rule_matches['right'] + self.rule_matches['wrong'])\n print(f\"Right: {self.rule_matches['right']} | Wrong: {self.rule_matches['wrong']}\")\n print(f\"right Pre_cache: {self.rule_matches['right_pre_cache']} |\"\n f\" wrong pre_cache: {self.rule_matches['wrong_pre_cache']}\")\n\n\nclass RuleStore:\n def __init__(self, ant_max, max_length):\n self.rules = {i: {} for i in range(1, ant_max + 1)} # {length_of_ant: {ant: cons}, ..}\n self.lru_list = [] # stores antecedants\n self.ant_max = ant_max\n self.max_length = max_length\n\n def add_rules(self, rules):\n # [((13,), (88, 18, 47)), ((13, 47), (88, 18)), ((18, 47), (88, 13))]\n self.maintain_length(len(rules))\n for rule_set in rules:\n if rule_set[0] in self.lru_list:\n self.lru_list.remove(rule_set[0])\n self.rules[len(rule_set[0])].pop(rule_set[0])\n self.lru_list.append(rule_set[0])\n self.rules[len(rule_set[0])][rule_set[0]] = rule_set[1]\n\n def maintain_length(self, length):\n new_length = len(self.lru_list) + length\n if new_length > self.max_length:\n remove_no = new_length - self.max_length\n for i in range(remove_no):\n victim = self.lru_list.pop(0)\n self.rules[len(victim)].pop(victim)\n\n def __len__(self):\n return len(self.lru_list)\n\n\nclass AssociateCache:\n def __init__(self, data, rule_no, group_no):\n self.data = data # a list of dataset = [2, 3, 4, 5, ...]\n self.rule_no = rule_no # how many rules you want to generate\n self.group_no = group_no # group_no = len(set(self.data))\n self.mem_max = 80\n self.min_support = 0.45\n self.sparse_threshold = 0.55\n\n def data_preparation(self):\n length = len(self.data)\n\n b = list(range(0, length - 1, self.group_no))\n a = list(range(self.group_no, length, self.group_no))\n h = {i: [0] * len(a) for i in set(self.data)}\n pos = 0\n for i in range(len(a)):\n data_sliced = self.data[b[i]:a[i]]\n for j in data_sliced:\n h[j][pos] = 1\n pos += 1\n df = pd.DataFrame.from_dict(h)\n # sdf = df.astype(pd.SparseDtype(\"int\", 0))\n return df\n\n def get_freq_items(self, algorithm, support, data):\n print('supp->', support)\n if algorithm == 'apriori':\n freq_items = apriori(data, min_support=support, use_colnames=True)\n else:\n freq_items = fpgrowth(data, min_support=support, use_colnames=True)\n if freq_items.size == 0:\n print('reducing support')\n return self.get_freq_items(algorithm, support - 0.25, data)\n else:\n # print('freq items->', freq_items)\n return freq_items\n\n def freq_items_algorithm_decision(self, sdf):\n # sdf.columns = [str(i) for i in sdf.columns]\n if (memory_record.get_data() < self.mem_max) and (\n sdf.astype(pd.SparseDtype(\"int\", 0)).sparse.density > self.sparse_threshold):\n event = 'using apriori'\n display_event(kind='notify', event=event, origin='Association | freq_items_algorithm')\n return self.get_freq_items(algorithm='apriori', support=self.min_support, data=sdf)\n else:\n event = 'using fpgrowth'\n display_event(kind='notify', event=event, origin='Association | freq_items_algorithm')\n return self.get_freq_items(algorithm='fpgrowth', support=self.min_support, data=sdf)\n\n def gen_rules(self):\n sdf = self.data_preparation()\n frequent_items = self.freq_items_algorithm_decision(sdf)\n rules = association_rules(frequent_items, metric='lift', min_threshold=1)\n rul_sort = rules.sort_values(by=['support', 'conviction', 'lift']) # ['support', 'confidence', 'lift']\n if len(rul_sort) > self.rule_no:\n rule_dict = [(tuple(rul_sort.values[-i, 0]), tuple(rul_sort.values[-i, 1])) for i in\n range(1, self.rule_no + 1)]\n else:\n event = f'generated rules less than rule number | {len(rul_sort)} rules'\n display_event(kind='Notify', event=event, origin='ApAssociate gen_rules')\n rule_dict = [(tuple(rul_sort.values[i, 0]), tuple(rul_sort.values[i, 1])) for i in range(len(rul_sort))]\n return rule_dict\n\n\nclass BrokerCom:\n def __init__(self, user, pw, ip, sub_topic):\n self.user = user\n self.pw = pw\n self.ip = ip\n self.port = 1883\n self.topic = sub_topic\n self.client = mqtt.Client()\n self.mec_ip = ip_address()\n self.run = 1\n\n def on_connect(self, connect_client, userdata, flags, rc):\n print(\"Connected with Code :\" + str(rc))\n # Subscribe Topic from here\n connect_client.subscribe(self.topic)\n\n def on_message(self, message_client, userdata, msg):\n print(f'Topic received: {msg.topic}')\n topic_recv = msg.topic\n if topic_recv == 'cache/add':\n data = pickle.loads(msg.payload)\n if data[1] != self.mec_ip:\n collaborative_cache.add_cache(data[0], data[1]) # cache/add [cache_content_hash, mec]\n\n elif topic_recv == 'cache/replace':\n data = pickle.loads(msg.payload)\n if data[1] != self.mec_ip:\n collaborative_cache.replace(data[0], data[1], data[2]) # [mec, old_cache, new_cache]\n\n def publish(self, topic, data):\n self.client.publish(topic, data)\n\n def broker_loop(self):\n self.client.on_connect = self.on_connect\n self.client.on_message = self.on_message\n\n self.client.username_pw_set(self.user, self.pw)\n self.client.connect(self.ip, self.port, 60)\n self.client.loop_start()\n while True:\n if self.run == 0:\n self.client.loop_stop()\n self.client.disconnect()\n break\n\n def __del__(self):\n print('Broker Communication Object Deleted!')\n\n\ndef display_event(kind, event, origin):\n tab = 50\n print('\\n' + '*' * tab)\n print(f'Kind : {kind}')\n print('-' * tab)\n print(f'Kind : {origin}')\n print('-' * tab)\n print(event)\n print('\\n' + '*' * tab + '\\n')\n\n\ndef ip_address():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n return s.getsockname()[0]\n\n\ndef get_hostname():\n cmd = ['cat /etc/hostname']\n hostname = str(sp.check_output(cmd, shell=True), 'utf-8')[0:-1]\n return hostname\n\n\ndef data_slice(no_mec, total_req_no, initial):\n host = get_hostname()\n host_no = int(re.findall('[0-9]+', host)[0])\n step = int(total_req_no / no_mec)\n start = host_no * step\n return start + initial, start + step + initial\n\n\ndef send_email(msg):\n try:\n server = smtplib.SMTP_SSL('smtp.gmail.com')\n server.ehlo()\n server.login(config.email_address, config.password)\n subject = 'Caching results {} {}'.format('Proposed caching', get_hostname())\n # msg = 'Attendance done for {}'.format(_timer)\n _message = 'Subject: {}\\n\\n{}\\n\\n SENT BY RIHANNA \\n\\n'.format(subject, msg)\n server.sendmail(config.email_address, config.send_email, _message)\n server.quit()\n print(\"Email sent!\")\n except Exception as e:\n print(e)\n\n\ndef send_email_attachment(file):\n msg = EmailMessage()\n\n msg['Subject'] = 'Caching results {} {}'.format('Proposed caching', get_hostname())\n\n msg['From'] = config.email_address\n\n msg['To'] = config.send_email\n msg.set_content(file)\n with open(file, 'rb') as f:\n file_data = f.read()\n # file_type = imghdr.what(f.name)\n file_name = f.name\n\n msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)\n\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n smtp.login(config.email_address, config.password)\n smtp.send_message(msg)\n\n\ndef save_data(mem, cpu, delay, no, cache_details):\n host = get_hostname()\n host_no = int(re.findall('[0-9]+', host)[0])\n data = f\"\"\"\n memory{host_no}_{no} = {mem}\n cpu{host_no}_{no} = {cpu}\n delay{host_no}_{no} = {delay}\n \"\"\"\n detail = '\\n'\n for det in cache_details:\n detail += f'{det}{host_no}_{no} = {cache_details[det]}\\n'\n data += detail\n send_email(data)\n file = open(f'results/output{host_no}_{no}.py', 'w')\n file.write(data)\n file.close()\n send_path = '/home/osboxes/results/'\n sp.run(\n [\"scp\", f'results/output{host_no}_{no}.py', f\"osboxes@{result_server_ip}:{send_path}\"])\n for res in ['memory', 'cpu', 'delay']:\n os.system(f'zip results/{res}{host_no}_{no}.zip results/{res}/*')\n sp.run(\n [\"scp\", f'results/{res}{host_no}_{no}.zip', f\"osboxes@{result_server_ip}:{send_path}\"])\n send_email_attachment(f'results/{res}{host_no}_{no}.zip')\n time.sleep(r.uniform(1, 10))\n\n\ndef arrival_distribution():\n # Poisson Distribution\n host = get_hostname()\n host_no = int(re.findall('[0-9]+', host)[0])\n file = open(f'LSTM_caching/dist/{host_no}.pickle', 'rb')\n arrival_dist = pickle.load(file)\n file.close()\n return (i for i in arrival_dist)\n\n\nresult_server_ip = '192.168.122.195'\nmemory_record = Memory(window_size=200, title='memory')\ncpu_record = CPU(window_size=200, title='cpu')\n\n\nclass BrokerRequest:\n def __init__(self, user, pw, ip, sub_topic):\n self.user = user\n self.pw = pw\n self.ip = ip\n self.port = 1883\n self.topic = sub_topic\n self.response = None\n self.client = mqtt.Client()\n\n def on_connect(self, connect_client, userdata, flags, rc):\n print(\"Connected with Code :\" + str(rc))\n # Subscribe Topic from here\n connect_client.subscribe(self.topic)\n\n def on_message(self, message_client, userdata, msg):\n if pickle.loads(msg.payload):\n self.response = pickle.loads(msg.payload)\n\n def broker_loop(self):\n self.client.on_connect = self.on_connect\n self.client.on_message = self.on_message\n\n self.client.username_pw_set(self.user, self.pw)\n self.client.connect(self.ip, self.port, 60)\n self.client.loop_start()\n while True:\n if self.response:\n self.client.loop_stop()\n self.client.disconnect()\n return self.response\n\n def __del__(self):\n print('BrokerRequest Object Deleted!')\n\n\ndef initialization():\n br = BrokerRequest(user='mec', pw='password', ip=broker_ip, sub_topic='control')\n br.broker_loop()\n del br\n print('starting ....')\n\n\ndef run(no_mec):\n global collaborative_cache\n global messenger\n\n os.system('clear')\n print('Waiting for Start command from Control...')\n initialization()\n broker_dict = {'user': 'mec', 'pw': 'password', 'sub_topic': 'cache/#', 'ip': broker_ip}\n messenger = BrokerCom(**broker_dict)\n h1 = Thread(target=messenger.broker_loop)\n h1.start()\n\n collaborative_cache = CollaborativeCache(no_mec=no_mec)\n request_data = pd.read_csv(f'request_data.csv')\n # no_reqs = int(request_data.shape[0] * 0.3) # testing data is 30 % => 67,259\n no_reqs = 20000 # testing data is 30 % => 67,259\n n = 5 * 8 * 10\n no_of_requests = (no_reqs // n) * n # No of requests should be divisible by 5, 10, 15 MECs | 67,200\n\n network_cost_record = Delay(window_size=200)\n content_name_server = '192.168.122.195'\n # (self, cache_size, max_freq, avg_max, window_size, content_name_server, delay)\n d_slice = data_slice(no_mec=no_mec, total_req_no=no_of_requests, initial=request_data.shape[0] - no_of_requests)\n store = LocalCache(cache_size=50, max_freq=15, avg_max=20, window_size=15,\n content_name_server=content_name_server,\n delay=network_cost_record)\n # pickle_in = open('dict.pickle','rb')\n # example_dict = pickle.load(pickle_in)\n arrival_dist = arrival_distribution()\n s = d_slice[1] - d_slice[0]\n for i in range(d_slice[0], d_slice[1]):\n print(f\"requesting-> {request_data['movieId'][i]}\")\n store.request(request_data['movieId'][i])\n cpu_record.add_data()\n memory_record.add_data()\n time.sleep(arrival_dist.__next__())\n s -= 1\n print(f'\\nRemaining -> {s} \\n')\n store.experiment_details()\n save_data(mem=memory_record.data_set, cpu=cpu_record.data_set, delay=network_cost_record.data_set, no=no_mec,\n cache_details=store.outcome_details())\n\n messenger.run = 0\n print('experiment concluded!')\n\n\ndef main():\n global broker_ip\n\n parser = argparse.ArgumentParser() # --n=5\n parser.add_argument('--n', type=int, default=1, help='Number of MEC nodes')\n parser.add_argument('--ip', type=str, default='localhost', help='broker ip address')\n args = parser.parse_args()\n broker_ip = args.ip\n run(no_mec=args.n)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"3proposed.py","file_name":"3proposed.py","file_ext":"py","file_size_in_byte":47081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"429577044","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 9 13:49:21 2020\r\n\r\n@author: Wamiq\r\n\r\n\"\"\"\r\nfrom sklearn.preprocessing import Normalizer\r\nimport torchvision.transforms as transforms\r\nfrom torchvision import datasets\r\nimport pickle as pkl\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\nfrom matplotlib import pyplot as plt\r\nimport numpy\r\nfrom sklearn.metrics import confusion_matrix\r\nimport itertools\r\n\r\n\r\n\"\"\"\r\n # loadv data from Pickle file with this function\r\n # pickleFileName = name of pickle file that needed to load\r\n # return dataArray=loaded data from pickle file\r\n\"\"\"\r\ndef loadPickle(pickleFileName):\r\n with open(pickleFileName, 'rb') as fileObject:\r\n dataArray = pkl.load(fileObject)\r\n fileObject.close()\r\n return dataArray\r\n\r\n\r\n'-------------------------------------------------------------------------------------'\r\n# Device configuration\r\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\n\r\n'-------------------------------------------------------------------------------------'\r\n# Hyper parameters\r\nnum_epochs = 250\r\nnum_classes = 25\r\nbatch_size = 32\r\nlearning_rate = 0.01\r\nn_params=[16,32,64]\r\n'-------------------------------------------------------------------------------------'\r\n\r\n\"\"\"\r\n Reading dataset from pickle file\r\n\"\"\"\r\n\r\nX_train = loadPickle(\"XTrainPickle.pkl\")\r\ny_train = loadPickle(\"yTrainPickle.pkl\")\r\n\r\nX_validate = loadPickle(\"XValidatePickle.pkl\")\r\ny_validate = loadPickle(\"yValidatePickle.pkl\")\r\n\r\nX_test = loadPickle(\"XTestPickle.pkl\")\r\ny_test = loadPickle(\"yTestPickle.pkl\")\r\n\r\n\"\"\"\r\n performing L2 normalization\r\n\"\"\"\r\nData_normalizer = Normalizer(norm='l2').fit(X_train)\r\nX_train = Data_normalizer.transform(X_train)\r\n\r\nData_normalizer = Normalizer(norm='l2').fit(X_validate)\r\nX_validate = Data_normalizer.transform(X_validate)\r\n\r\nData_normalizer = Normalizer(norm='l2').fit(X_test)\r\nX_test = Data_normalizer.transform(X_test)\r\n\r\n\r\n\"\"\"\r\n # Transformation\r\n\"\"\"\r\ntransform = transforms.Compose([\r\n transforms.Resize((32,32)),\r\n transforms.ToTensor() \r\n ])\r\n#transforms.Normalize([0.485,0.456,0.406], [0.229,0.224,0.225])//l2 normalization\r\n#train_dataset = datasets.ImageFolder(root=train_path,transform=transform)\r\n#val_dataset = datasets.ImageFolder(root=val_path,transform=transform) \r\n#test_dataset=datasets.ImageFolder(root=test_path,transform=transform)\r\n\r\n\r\n\r\n'-------------------------------------------------------------------------------------'\r\n\"\"\"\r\n# Data loader\r\n#train_loader = torch.utils.data.DataLoader(dataset=X_train,\r\n #batch_size=batch_size, \r\n #shuffle=True)\r\n\r\nval_loader = torch.utils.data.DataLoader(dataset=X_validate,\r\n batch_size=batch_size, \r\n shuffle=True)\r\n\r\ntest_loader = torch.utils.data.DataLoader(dataset=X_test,\r\n batch_size=batch_size, \r\n shuffle=True)\r\n\"\"\"\r\n'-------------------------------------------------------------------------------------'\r\n\r\n'-------------------------------------------------------------------------------------'\r\n# Convolutional neural network\r\nclass ConvNet(nn.Module):\r\n def __init__(self, num_classes=2):\r\n super(ConvNet, self).__init__()\r\n self.layer1 = nn.Sequential(\r\n nn.Conv1d(in_channels =1, out_channels =1, kernel_size=1, stride=1, padding=0), \r\n #nn.BatchNorm1d(1),\r\n #nn.Softmax(),\r\n #nn.ReLU(), //softmax activation function\r\n nn.MaxPool1d(kernel_size=1, stride=1))\r\n #self.lstm = nn.LSTM(1024,256)\r\n self.fc = nn.Linear(1024, num_classes)\r\n\r\n \r\n def forward(self, x):\r\n out = self.layer1(x)\r\n #out = self.lstm(x)\r\n out = out.reshape(out.size(0), -1)\r\n out = self.fc(out)\r\n return out\r\n\r\nmodel = ConvNet(num_classes).float()#.to(device)\r\n'-------------------------------------------------------------------------------------'\r\n'-------------------------------------------------------------------------------------'\r\n# Loss and optimizer\r\ncriterion = nn.CrossEntropyLoss()\r\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\r\n\r\n'-------------------------------------------------------------------------------------'\r\n\r\n# Train the model\r\nconfusion_mat_train = torch.zeros(num_classes, num_classes)\r\nconfusion_mat_val = torch.zeros(num_classes, num_classes)\r\n\r\nfor epoch in range(num_epochs):\r\n total=0\r\n correct = 0\r\n train_acc=0\r\n train_hist=[]\r\n images= torch.from_numpy(numpy.array(X_train))\r\n labels=torch.from_numpy(numpy.array(y_train))\r\n images = images.reshape(6537,1,1024)\r\n outputs= model(images.float())\r\n loss_train = criterion(outputs, labels)\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum().item()\r\n train_hist.append(loss_train)\r\n \r\n # Backward and optimize\r\n optimizer.zero_grad()\r\n loss_train.backward()\r\n optimizer.step()\r\n for t, p in zip(labels.view(-1), predicted.view(-1)):\r\n confusion_mat_train[t.long(), p.long()] += 1\r\n\r\n train_acc=(correct/total)*100\r\n print ('Epoch [{}/{}], Train Loss: {:.4f}, train Acc: {:,.4f}'\r\n .format(epoch+1, num_epochs, loss_train.item(), train_acc))\r\n\r\n model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\r\n with torch.no_grad():\r\n correct = 0\r\n total = 0\r\n val_acc=0\r\n val_hist=[]\r\n images= torch.from_numpy(numpy.array(X_validate))\r\n labels=torch.from_numpy(numpy.array(y_validate))\r\n images = images.reshape(2802,1,1024)\r\n outputs = model(images.float())\r\n loss_val = criterion(outputs, labels)\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum().item()\r\n val_hist.append(loss_val)\r\n for t, p in zip(labels.view(-1), predicted.view(-1)):\r\n confusion_mat_val[t.long(), p.long()] += 1\r\n val_acc=(correct/total)*100\r\n print ('Epoch [{}/{}], Val Loss: {:.4f} , Val Acc: {:,.4f}'\r\n .format(epoch+1, num_epochs, loss_val.item(), val_acc))\r\n \r\n'-----------------------------------------------------------------------------'\r\n#Plotting graph \r\nplt.plot(train_hist,label='Training loss')\r\nplt.plot(val_hist,label='Validation loss')\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\n\r\n'-----------------------------------------------------------------------------'\r\n#Printingconfusion matrix\r\nprint('Confusion Matrix for Training Data', confusion_mat_train)\r\nprint('Confusion Matrix for Validation Data', confusion_mat_val)\r\n\r\n'-----------------------------------------------------------------------------' \r\n### Model save ####\r\ntorch.save(model.state_dict(), 'E:/RIS/CNN.pt')\r\n\r\n\r\n\r\n'-----------------------------------------------------------------------------'\r\n# Test the model###\r\n#model = ConvNet(num_classes).to(device)\r\nmodel.load_state_dict(torch.load('E:/RIS/CNN.pt'))\r\nmodel.eval() \r\nconfusion_mat = torch.zeros(num_classes, num_classes)\r\nwith torch.no_grad():\r\n correct = 0\r\n total = 0\r\n images= torch.from_numpy(numpy.array(X_test))\r\n labels=torch.from_numpy(numpy.array(y_test))\r\n outputs = model(images.float())\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum().item()\r\n for t, p in zip(labels.view(-1), predicted.view(-1)):\r\n confusion_mat[t.long(), p.long()] += 1\r\n\r\n print('Test Accuracy of the model on the 20 test images: {} %'.format(100 * correct / total))\r\n print('Confusion Matrix for Test Data',confusion_mat)\r\n","sub_path":"RIMD_DL.py","file_name":"RIMD_DL.py","file_ext":"py","file_size_in_byte":8009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"510721227","text":"import wave\nimport sys\nimport os\n# import struct\n\n\ndef toInt(*args):\n\t# Hard coded to two because we know the len of the hex\n\tfor j in range(1, len(args), 2):\n\t\tprint(args[j - 1] * 16 + args[j])\n\nif not os.path.exists(sys.argv[1]):\n\tprint(\"File does not exist\")\n\tsys.exit(1)\n\nwith open(sys.argv[1], \"rb\") as audio:\n\taudioFile = wave.open(audio)\n\tparams = audioFile.getparams()\n\tprint(params)\n\tprint(\"File len in sec\", params.nframes / params.framerate)\n\n\t# length = audioFile.getnframes()\n\t# for i in range(2500, 2601):\n\t# \twaveData = audioFile.readframes(1)\n\t# \tprint(i / audioFile.getnframes(), \"sec\")\n\t# \ttoInt(*waveData)\n","sub_path":"scripts/read_wave.py","file_name":"read_wave.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"258731131","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 26 15:57:11 2018\n\n@author: Bailey group PC\n\"\"\"\nimport pandas as pd\nimport minimalmodbus\nimport time\n\n#ss1 = SS(inst_id=1,com_port='COM6',baudrate=115200)\n#timer=[]\n#t_start=time.time()\n#while time.time()-t_start < 10:\n# ss1.read_data_raw()\n# #time.sleep(0.02)\n# timer.append(time.time())\n#timer=pd.Series(np.array(timer)-t_start)\n#print('average time',timer.diff().mean())\n#ss1.ss.serial.close()\n\ntimer=[]\nss=minimalmodbus.Instrument('COM6',1)\nss.serial.baudrate=115200\nt_start=time.time()\nwhile time.time()-t_start < 10:\n #ss.read_registers(12,2)\n \n #ss.read_register(12)\n #time.sleep(0.02)\n timer.append(time.time())\ntimer=pd.Series(np.array(timer)-t_start)\nprint('average time',timer.diff().mean())\nss.serial.close()","sub_path":"testing/ss_cmd_speed_test.py","file_name":"ss_cmd_speed_test.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"354946862","text":"import argparse\nimport gym\nimport torch\nfrom torch.optim import Adam\nfrom torch.nn import MSELoss, SmoothL1Loss\nfrom matplotlib import pylab as plt\n\nfrom train import train\nfrom model import DeepQ\n\n# Parse incoming arguments for the trainer\nparser = argparse.ArgumentParser()\nparser.add_argument(\"environment\", help=\"which environment to run training on\")\nparser.add_argument(\"--render\", action=\"store_true\", help=\"render the environment\")\nargs = parser.parse_args()\n\n# Instantiate our gym\nenv = gym.make(args.environment)\n\n# Make our DeepQ network\nmodel = DeepQ(env)\n\n# Solved is being passed to on_episode_complete, which is called\n# upon each episode completion. From there, we will check to see\n# if our environment has reached the appropriate \"solved\" condition\n# if one exists\ndef solved(episode, step, steps, total_reward, rewards):\n solved = False\n\n # LunarLander solved if we are 100 consecutive episodes\n # with an average reward above 200\n if args.environment == \"LunarLander-v2\":\n if len(rewards) > 100 and sum(rewards[-100:])/100 >= 200:\n solved = True\n # MountainCar-v0 is considered solved if you have 100\n # conesecutive episodes with an average reward over -110\n elif args.environment == \"MountainCar-v0\":\n if len(rewards) > 100 and sum(rewards[-100:])/100 >= -110:\n solved = True\n\n # CartPole-v0 is considered solved if you have 100\n # consecutive episodes with an average reward over 195.\n elif args.environment == \"CartPole-v0\":\n if len(rewards) > 100 and sum(rewards[-100:])/100 >= 195:\n solved = True\n\n if solved:\n print()\n print(f\"Solved after {len(steps)} steps\")\n return True\n\n print(f\"Episode {episode+1} took {step} steps for a reward of {total_reward:.2f}. - REWARDS - Last 100: {sum(rewards[-100:])/len(rewards[-100:]) if len(rewards) > 0 else 0:.2f} - Last 10: {sum(rewards[-10:])/len(rewards[-10:]) if len(rewards) > 0 else 0:.2f}\", end=\"\\r\")\n \n return False\n\ndef state_transform(state):\n return torch.Tensor(state).float()\n\n# Train\nsteps, rewards = train(model, env, MSELoss(), Adam, render = args.render,\n episodes = 1000,\n experience_replay = True, experience_memory_size=1_000_000, batch_size=64,\n target_network = True, sync_every_steps = 1e4,\n gamma = 0.99, epsilon = 1.0, epsilon_minimum=0.10,\n epsilon_minimum_at_episode=500,\n learning_rate = 5e-4,\n on_episode_complete=solved, state_transform=state_transform)\n\nprint()\nprint(\"Training complete\")\n\nplt.figure(figsize=(10,7))\nplt.plot(steps)\nplt.xlabel(\"Episodes\", fontsize=22)\nplt.ylabel(\"Steps\", fontsize=22)\nplt.savefig(\"steps.png\")\n\nplt.figure(figsize=(10,7))\nplt.plot(rewards)\nplt.xlabel(\"Episodes\", fontsize=22)\nplt.ylabel(\"Rewards\", fontsize=22)\nplt.savefig(\"rewards.png\")\n\nfilepath = \"deep.q.model.pt\"\n\nmodel.save(filepath)\nprint(f\"Model saved to {filepath}\")","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"227046037","text":"import networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nk = int(input(\"enter K?\"))\r\np = (k/2)**2 #number of servers in pod \r\ns = ((k/2)**2)*k\r\ng = []\r\ncolor_map = []\r\nn = s+(k*k/2)+(k*k/2)+((k/2)**2)\r\n\r\nedge=s+(k/2)*k\r\nagg=(k/2)*k + edge\r\n\r\n\r\nG1 = nx.Graph()\r\n\r\nfor i in range(int(n)):\r\n G1.add_node(i)\r\n g.append([])\r\n\r\nfor node in G1:\r\n if nodes:\r\n color_map.append('red')\r\nfor node in G1:\r\n if nodeedge: \r\n color_map.append('green')\r\nfor node in G1:\r\n if node>agg:\r\n color_map.append('yellow')\r\n \r\n \r\n\r\n#print(g)\r\ni = 0\r\nwhile i < s:\r\n for j in range(int(p)):\r\n top = s+int((i+j)/(k/2))\r\n g[int(i+j)].append(int(top))\r\n g[int(top)].append(int(i+j))\r\n i += p\r\n#print(g)\r\ne = s + (k*k/2)\r\ni = 0\r\nwhile i < (k*k/2):\r\n for j in range(int(k/2)):\r\n for l in range(int(k/2)):\r\n top = int(e+i+l)\r\n g[int(s+i+j)].append(top)\r\n g[top].append(int(s+i+j))\r\n i += k/2\r\n#print(g)\r\na = e + (k*k/2)\r\ni = 0\r\n\r\nwhile i < (k*k/2):\r\n temp = int(i/(k/2))\r\n for j in range(int(k/2)):\r\n for l in range(int(k/2)):\r\n top = int(a+(temp%((k/2)*(k/2))))\r\n g[int(e+i+j)].append(top)\r\n g[top].append(int(e+i+j))\r\n temp += 1\r\n i += k/2\r\nprint(g)\r\n\r\nf=open(\"result.txt\",\"w+\")\r\n\r\nfor i in range(int(n)):\r\n for l in range(int(n)):\r\n flag = False\r\n for j in range(len(g[i])): \r\n if g[i][j]==l:\r\n flag = True\r\n if flag:\r\n f.write(f\"{i} {l} ------>1\\n\")\r\n G1.add_edge(i,l)\r\n else:\r\n f.write(f\"{i} {l} ------>9999\\n\") \r\n\r\nf.close()\r\n\r\n#nx.draw(G1,node_color = color_map,with_labels=True, font_weight='bold')\r\nnx.write_gml(G1,'g.gml')\r\nnx.write_graphml(G1,'g.xml')\r\n\r\n#plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"cloud-plot.py","file_name":"cloud-plot.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"100402480","text":"'''\nTitle: Project task\nDate: 23.5.2021\nMade by: Aditya Mangal\n\n'''\n\n\nfrom os import write\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nfrom termcolor import cprint\nfrom time import sleep\n\nwith open(\"data.txt\", 'rt') as file:\n title_list = []\n availability_list = []\n url_list = []\n try:\n cprint('Fetching the URL from file...', 'yellow')\n sleep(2)\n cprint('Fetching the Products data and availability...', 'yellow')\n sleep(2)\n cprint('Wait for processing...', 'yellow')\n a = file.readlines()\n for i in range(len(a)):\n url = a[i]\n if \"\\n\" in url:\n url = a[i][:-1]\n else:\n url = a[i]\n url_list.append(url)\n data = requests.get(url).text\n html = BeautifulSoup(data, \"html.parser\")\n title = html.find('title')\n title = str(title)[7:-8]\n title_list.append(title)\n availability = html.find(\n class_=\"link-button text-bold product-block-status-availability\")\n availability = str(availability)\n if \"Available\" in availability:\n current_av = 'In Stock'\n availability_list.append(current_av)\n elif \"Out of Stock\" and 'Temporarily unavailable' in availability:\n current_av = 'Out of Stock'\n availability_list.append(current_av)\n elif \"Mixed Availability\" in availability:\n current_av = 'Variant'\n availability_list.append(current_av)\n elif \"Discontinued\" in availability:\n current_av = 'Discontinued'\n availability_list.append(current_av)\n except:\n cprint('Somthing Wrong! Check your URL data txt.', 'yellow')\n\ncprint('Fetching and writing the saving the data...', 'yellow')\nsleep(2)\nwith open('output.txt', 'a') as file:\n try:\n for i in range(len(availability_list)):\n file.writelines(str(i+1))\n file.writelines(' ,')\n file.writelines(title_list[i])\n file.writelines(' ,')\n file.writelines(availability_list[i])\n file.writelines(' ,')\n file.writelines(url_list[i])\n file.write('\\n')\n except:\n cprint(\"Some error occured.\", 'yellow')\ncprint(\"Saving Data to output.csv.\", 'yellow')\nsleep(2)\ndataframe1 = pd.read_csv(\"output.txt\", header=None)\ndataframe1.columns = ['S.No', 'Products from given URL', 'Stock Status','Hyperlink']\ndataframe1.to_csv('output.csv', index=None)\ncprint(\"Saved Succesfully.\", 'yellow')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"285189645","text":"import tkinter\n\nroot = tkinter.Tk()\nroot.title(\"background\")\nroot.geometry(\"600x400\")\ncanvas = tkinter.Canvas(width=300, height=100, bg='white')\ncanvas.pack()\nframe = tkinter.Frame(root)\nframe.pack()\nl1 = tkinter.Label(frame, text='달러', font='helvetica 16 italic')\nl1.pack()\nb2 = tkinter.Button(frame, text='원->달러')\nb2.pack()\n\nroot.mainloop()","sub_path":"programming/python/python_game/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"251348135","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\nfrom keras.datasets import mnist\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers.convolutional import Convolution2D\r\nfrom keras.layers.convolutional import MaxPooling2D\r\nfrom keras.layers import Flatten\r\nfrom keras.layers import Dropout\r\n\r\nfrom keras.utils import np_utils\r\nimport numpy\r\nimport matplotlib.pyplot as plt\r\n\r\nseed = 7\r\nnumpy.random.seed(seed)\r\n\r\n(x_train,y_train),(x_test,y_test) = mnist.load_data()\r\n#asd = plt.imshow(x_train[1],cmap='gray')\r\n\r\n# Get the number of pixels\r\nnumPixels = x_train[0].shape[0] * x_train[0].shape[1]\r\nnumTrainImages = x_train.shape[0]\r\nnumTestImages = x_test.shape[0]\r\n\r\n# Reshape the data to be a column vector\r\nx_train = x_train.reshape(numTrainImages,28,28,1).astype('float32')\r\nx_test = x_test.reshape(numTestImages,28,28,1).astype('float32')\r\n\r\nx_train = x_train/255\r\nx_test = x_test/255\r\n\r\n\r\n\r\ny_train = np_utils.to_categorical(y_train)\r\ny_test = np_utils.to_categorical(y_test)\r\nnumClasses = y_train.shape[1]\r\n\r\n#Create a cnn model\r\ndef cnn_model():\r\n model = Sequential()\r\n model.add(Convolution2D(32,5,5,\r\n border_mode='valid',\r\n activation = 'relu',\r\n input_shape= (28,28,1)))\r\n model.add(MaxPooling2D(pool_size=(2,2)))\r\n model.add(Dropout(0.2))\r\n model.add(Flatten())\r\n model.add(Dense(128,activation='relu'))\r\n \r\n model.add(Dense(numClasses,\r\n activation='softmax'))\r\n # Compile the model\r\n model.compile(optimizer='adam',\r\n loss = 'categorical_crossentropy',\r\n metrics=['accuracy'])\r\n return model\r\n \r\n#Build the model\r\nmodel = cnn_model()\r\n\r\n#Fit the model\r\nhistory = model.fit(x_train,y_train,batch_size=200,nb_epoch=10,\r\n validation_data=(x_test,y_test),verbose=2)\r\n\r\n#Final evaluation of the model\r\nscores = model.evaluate(x_test,y_test,verbose=0)\r\nprint(\"Baseline Error: %.2f%%\" % (100-scores[1]*100))\r\n\r\n\r\n \r\n \r\n\r\n","sub_path":"prework/keras/first_test_cnn.py","file_name":"first_test_cnn.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"545400383","text":"'''\r\nUFRJ - Universidade Federal do Rio de Janeiro\r\n\r\nIM - Instituto de Matematica\r\n\r\nPedro Feteira Gueventer - 119.017.382\r\n\r\nLista 4 - Questão 1\r\n'''\r\n\r\ndef main():\r\n\r\n try:\r\n file = input('Qual o nome do arquivo?')\r\n arq = open(f'{file}','r')\r\n a=[]\r\n for line in arq.readlines():\r\n \r\n a.append( [ float(x) for x in line.split(',')] )\r\n for i in range(len(a[1])):\r\n if len(a[i]) != len(a[i+1]):\r\n raise IndexError\r\n print(f'{len(a),len(a[1])}')\r\n for l in range(0, len(a)):\r\n for c in range(0,len(a[1])):\r\n print(f'{a[l][c]}', end = ' ')\r\n print()\r\n \r\n except FileNotFoundError:\r\n print('\\nArquivo não encontrado, tente novamente.\\n')\r\n main()\r\n except IndexError:\r\n print('Linhas de tamanhos')\r\nmain() \r\n \r\n \r\n\r\n","sub_path":"Lista4 - Questão 1.py","file_name":"Lista4 - Questão 1.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"169636102","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 14 10:53:29 2018\n@author: Okarim\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nimport datetime\nfrom pathlib import Path\nimport time\nfrom sklearn.model_selection import train_test_split\n\ndef bottomToTop(texto):\n \"\"\"\n texto=nivel en formato de texto\n secuencia= secuencia de caracteres obtenidos al recorrer el nivel de abajo hacia arriba\n \"\"\"\n secuencia=[]\n for i in range(len(texto[0])):\n for j in reversed(range(len(texto))):\n secuencia.append(texto[j][i])\n return secuencia\n\ndef snaking(texto, direction=0):\n \"\"\"\n texto=nivel en formato de texto\n secuencia= secuencia de caracteres obtenidos al recorrer el nivel serpenteando\n direction = dirección inicial del snaking (0 = arriba-abajo, 1 = abajo-arraba)\n \"\"\"\n secuencia=[]\n for i in range(len(texto[0])):\n for j in range(len(texto)):\n if(i%2==direction):\n secuencia.append(texto[j][i])\n else:\n secuencia.append(texto[len(texto)-j-1][i])\n return secuencia\n\ndef timestamp():\n return datetime.datetime.fromtimestamp(time.time()).strftime('%y%m%d-%H%M%S')\n\nclass Dataset():\n def __init__(self, filepath, snak=False, include_path=False, reduce=False):\n self.text = []\n p = Path(filepath).glob('**/*')\n files = [x for x in p if x.is_file()]\n self.n=len(files)\n for f in files:\n texto=np.loadtxt(f, dtype=str, comments=\"~\")\n \n if reduce:\n new_text=[]\n for i in range(len(texto)):\n t=np.array(list(texto[i]))\n t[np.where(t == 'd')]='p'\n t[np.where(t == 'D')]='P'\n t[np.where(t == '{')]='['\n t[np.where(t == '}')]=']'\n t[np.where(t == 'v')]='#'\n t[np.where(t == '|')]='-'\n t[np.where(t == 'X')]='V'\n t[np.where(t == 'H')]='?'\n t[np.where(t == ',')]='-'\n new_text.append(''.join(t))\n texto=new_text\n if include_path:\n\t camino=np.loadtxt(\"Player_Path/\"+f.name, dtype=str, comments=\"~\")\n\t new_text=[]\n\t for i in range(len(texto)):\n\t t=np.array(list(texto[i]))\n\t c=np.array(list(camino[i]))\n\t t[np.where(c == 'x')]='m'\n\t new_text.append(''.join(t))\n\t texto=new_text\n \n if snak:\n self.seq=snaking(texto,0)\n self.text.append(self.seq)\n self.seq=snaking(texto,1)\n self.text.append(self.seq)\n else:\n self.seq=bottomToTop(texto)\n self.text.append((self.seq, [int(f.parents[0].name)-1]*len(self.seq)))\n self.X_train, self.X_test = train_test_split(self.text, test_size=0.2)\n self.idx_char = sorted(list(set(str(self.text))))\n self.char_idx = {c: i for i, c in enumerate(self.idx_char)}\n for x in self.X_test:\n print(x[1][0])\n\n def batch(self):\n for t in self.X_train:\n t2=t[0]\n W=t[1]\n X=[self.encode(t2[:-1]), W[:-1]]\n Y=self.encode(t2[1:])\n yield [X], [Y]\n\n def test(self):\n for t in self.X_test:\n t2=t[0]\n W=t[1]\n X=[self.encode(t2[:-1]), W[:-1]]\n Y=self.encode(t2[1:])\n yield [X], [Y]\n \n def decode(self, text):\n return [self.idx_char[c] for c in text]\n\n def encode(self, text):\n return [self.char_idx[c] for c in text]\n\nclass Generador:\n def __init__(self, alpha_size, cell_size, num_layers, dropout):\n self.dropout=dropout\n self.alpha_size = alpha_size\n self.cell_size = cell_size\n self.num_layers = num_layers\n self.state_size = self.cell_size * self.num_layers\n self._input()\n self._model()\n self._output()\n self._loss()\n self._metrics()\n self._summaries()\n self._optimizer()\n #config = tf.ConfigProto(device_count = {'GPU': 0})\n #self.sess = tf.Session(config=config)\n self.sess = tf.Session()\n self.last_state = None\n\n def __del__(self):\n if hasattr(self, 'sess'):\n del self.sess\n\n def _input(self,):\n \"\"\" Define las entradas \"\"\"\n with tf.variable_scope('input'):\n # [batch_size,seq_size]\n self.X = tf.placeholder(tf.int32, [1, 2, None], name='X')\n self.W_1h = tf.one_hot([self.X[0][1]], 3)\n \n # [batch_size,seq_size] -> \n # [batch_size,seq_size,alpha_size]\n self.X_1 = tf.one_hot([self.X[0][0]], self.alpha_size)\n self.X_1h = tf.concat([self.X_1, self.W_1h], 2)\n # [batch_size,seq_size]\n self.Y_true = tf.placeholder(tf.int32, [1, None], name='Y_true')\n #self.Wy_1h = tf.one_hot([self.Y_true[0][1]], 3)\n # [batch_size,seq_size] -> \n # [batch_size,seq_size,alpha_size]\n self.Y_true_1h = tf.one_hot(self.Y_true, self.alpha_size)\n #self.Y_true_1h = tf.concat([self.Y_true_1, self.Wy_1h], 2)\n # rnn initial state\n # [batch_size,cell_size*layers_num]\n self.init_state = tf.placeholder(tf.float32,\n [None, self.state_size], name='init_state')\n self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n #self.alpha_size+=3 \n def _model(self):\n \"\"\" Define el modelo de la red \"\"\"\n with tf.variable_scope('model'):\n with tf.variable_scope('rnn'):\n # define las capas de la rnn\n rnn_layers = [tf.nn.rnn_cell.DropoutWrapper( tf.nn.rnn_cell.GRUCell(self.cell_size),\n output_keep_prob=1.0-self.keep_prob)\n for _ in range(self.num_layers)]\n # Encadena las capas de la rnn\n rnn = tf.nn.rnn_cell.MultiRNNCell(rnn_layers, state_is_tuple=False)\n # [batch_size,seq_size,alpha_size] ->\n # [batch_size,seq_size,cell_size]\n Y_rnn, self.state = tf.nn.dynamic_rnn(rnn, self.X_1h, \n initial_state=self.init_state, dtype=tf.float32)\n self.seq_size = tf.shape(Y_rnn)[1]\n with tf.variable_scope('fc'):\n # Convierte cada secuencia a multiples ejemplos, uno por paso\n # [batch_size,seq_size,cell_size] ->\n # [batch_size*seq_size,cell_size]\n Y_rnn = tf.reshape(Y_rnn, [-1, self.cell_size])\n # [batch_size*seq_size,cell_size] -> \n # [batch_size*seq_size,alpha_size]\n self.L_flat = tf.layers.dense(Y_rnn, self.alpha_size)\n self.S_flat = tf.nn.softmax(self.L_flat)\n # [batch_size*seq_size,alpha_size] -> \n # [batch_size,seq_size,alpha_size]\n Y_shape = [-1, self.seq_size, self.alpha_size]\n self.L = tf.reshape(self.L_flat, Y_shape, name='L')\n self.S = tf.reshape(self.S_flat, Y_shape, name='S')\n\n def _output(self):\n \"\"\" Define el modelo de salida \"\"\"\n with tf.variable_scope('output'):\n # [batch_size*seq_size,alpha_size] ->\n # [batch_size*seq_size]\n self.Y_pred_flat = tf.argmax(self.S_flat, 1)\n # [batch_size*seq_size] ->\n # [batch_size,seq_size]\n Y_shape = [-1, self.seq_size]\n self.Y_pred = tf.reshape(self.Y_pred_flat, Y_shape)\n self.Y_pred = tf.cast(self.Y_pred, tf.int32, name='Y_pred')\n\n def _loss(self):\n \"\"\" Define la funcion de perdida. \"\"\"\n with tf.variable_scope('loss'):\n # [batch_size,seq_size,alpha_size] ->\n # [batch_size*seq_size,alpha_size]\n Y_true_flat = tf.reshape(self.Y_true_1h, [-1, self.alpha_size])\n # cs(labels=[batch_size*seq_size,alpha_size]\n # logits=[batch_size*seq_size,alpha_size])\n loss = tf.nn.softmax_cross_entropy_with_logits_v2(\n labels=Y_true_flat, logits=self.L_flat)\n self.loss = tf.reduce_mean(loss, name='loss')\n\n def _metrics(self):\n \"\"\" Agregar metricas. \"\"\"\n with tf.variable_scope('metrics'):\n equal = tf.cast(tf.equal(self.Y_true, self.Y_pred), tf.float32)\n self.acc = tf.reduce_mean(equal, name='acc')\n\n def _summaries(self):\n \"\"\" Agregar resumenes para Tensorboard. \"\"\"\n with tf.variable_scope('summaries'):\n tf.summary.scalar('loss', self.loss)\n tf.summary.scalar('acc', self.acc)\n self.summary = tf.summary.merge_all()\n\n def _optimizer(self):\n \"\"\" Preparar el optimizador. \"\"\"\n with tf.variable_scope('optimizer'):\n grad = tf.train.AdamOptimizer(learning_rate=0.001)\n self.opt = grad.minimize(self.loss)\n\n def _evaluate(self, sess, X, Y_true):\n \"\"\" Realizar la evaluacion del modelo sobre X, Y. \"\"\"\n self.last_state = np.zeros([len(X), self.state_size])\n #if self.last_state is None:\n # self.last_state = np.zeros([len(X), self.state_size])\n # init_state = np.zeros([len(X), self.state_size])\n feed = {self.X: X, self.Y_true: Y_true, \n self.init_state: self.last_state, self.keep_prob : 0.0}\n fetches = [self.loss, self.acc, self.summary]\n return sess.run(fetches, feed)\n\n def _train_step(self, sess, X, Y_true):\n \"\"\" Run one training step. \"\"\"\n self.last_state = np.zeros([len(X), self.state_size])\n #if self.last_state is None:\n # self.last_state = np.zeros([len(X), self.state_size])\n # init_state = np.zeros([len(X), self.state_size])\n stepX=[[X[0][0][:], X[0][1][:]]]\n stepY=[Y_true[0][:]]\n feed = {self.X: stepX, self.Y_true: stepY, \n self.init_state: self.last_state, self.keep_prob : self.dropout}\n fetches = [self.opt, self.state]\n _, self.last_state = sess.run(fetches, feed)\n\n #n=200 #200 data points for BPTT\n #for i in range(0, len(X[0][0]), n): \n # stepX=[[X[0][0][i:i+n], X[0][1][i:i+n]]]\n # stepY=[Y_true[0][i:i+n]]\n # feed = {self.X: stepX, self.Y_true: stepY, \n # self.init_state: self.last_state, self.keep_prob : self.dropout}\n # fetches = [self.opt, self.state]\n # _, self.last_state = sess.run(fetches, feed)\n\n def train(self, ds, epochs=1):\n \"\"\" Train the model. \"\"\"\n # output message\n msg = \"I{:4d} loss: {:5.4f}, acc: {:4.4f}\"\n # initialize variables (params)\n self.sess.run(tf.global_variables_initializer())\n # writers for TensorBoard\n ts = timestamp()\n writer_trn = tf.summary.FileWriter(\n 'graphs/11_lstm_class/{}/trn'.format(ts))\n writer_trn.add_graph(self.sess.graph)\n best_acc = 0\n best_err = 1.0\n saver = tf.train.Saver()\n save_path = 'checkpoints/best_acc'\n print(\"Training {}\".format(ts))\n for j in range(epochs):\n for i, (X, Y_true) in enumerate(ds.batch()):\n # evaluation\n if not i % 1:\n err_trn, acc_trn, sum_trn = 0, 0, 0\n for k, (X_evl, Y_evl) in enumerate(ds.test()): \n e, a, s = self._evaluate(self.sess, X_evl, Y_evl)\n err_trn+=e\n acc_trn+=a\n sum_trn=s\n err_trn/=len(ds.X_test)\n acc_trn/=len(ds.X_test)\n\n if (acc_trn > best_acc) or (acc_trn == best_acc and err_trn < best_err) :\n best_acc=acc_trn\n best_err = err_trn\n saver.save(sess=self.sess, save_path=save_path)\n writer_trn.add_summary(sum_trn, i+j*len(ds.X_train))\n print(msg.format(i+j*len(ds.X_train), err_trn, acc_trn))\n # train step\n #X, Y_true = ds.batch()\n self._train_step(self.sess, X, Y_true)\n\n # final evaluation\n err_trn, acc_trn, sum_trn = 0, 0, 0\n for k, (X_evl, Y_evl) in enumerate(ds.test()): \n e, a, s = self._evaluate(self.sess, X_evl, Y_evl)\n err_trn+=e\n acc_trn+=a\n sum_trn=s\n err_trn/=len(ds.X_test)\n acc_trn/=len(ds.X_test)\n writer_trn.add_summary(sum_trn, i+j*len(ds.X_train))\n print(msg.format(i+j*len(ds.X_train), err_trn, acc_trn))\n\n def restore(self, ds, save_path, evaluate=False):\n msg = \"I{:4d} loss: {:5.3f}, acc: {:4.2f}\"\n self.sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver()\n saver.restore(self.sess, save_path+\"/best_acc\")\n if evaluate:\n err_trn, acc_trn, sum_trn = 0, 0, 0\n for k, (X_evl, Y_evl) in enumerate(ds.test()): \n e, a, s = self._evaluate(self.sess, X_evl, Y_evl)\n err_trn+=e\n acc_trn+=a\n sum_trn=s\n err_trn/=len(ds.X_test)\n acc_trn/=len(ds.X_test)\n print(msg.format(0, err_trn, acc_trn))\n\n def generate(self, X, reset=False):\n \"\"\"\n Corre la red una vez para obtener la siguiente salida.\n \"\"\"\n if reset:\n init_state = np.zeros([len(X), self.state_size])\n else:\n init_state = self.last_state\n feed = {self.X: X, self.init_state: init_state, self.keep_prob : 0.0}\n S, self.last_state = self.sess.run([self.S, self.state], feed)\n return S\n\ndef sample_from_probabilities(ds, probabilities, minProb=0.1):\n \"\"\"Tira los dados para producir un entero aleatorio en el rango de ds.idx_char, \n de acuerdo con las probabilidades proporcionadas. \n Si se especifica minProb, solo se tienen en cuenta las probabilidades que sean mayores a ese valor.\n ds = dataset\n probabilities = lista de probabilidades para cada loseta\n minProb = probabilidad minima a considerar\n \n return carácter (loseta) escogido\n \"\"\"\n p = np.squeeze(probabilities)\n if 1 in p:\n \tp[np.where(p<1)]=0\n else:\n \tp[np.where(p /dev/null\")\n\nimport json,requests\n#@title #FLASK SERVER\ntest_mode = True #@param {type:\"boolean\"}\n# import socket\n# print(socket.gethostbyname(socket.getfqdn(socket.gethostname())))\n\n#load static files\n#PENDING \n\n\n#!curl -s http://localhost:4040/api/tunnels | python3 -c \\\n# \"import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])\"\n\n\n# SEND NEW URL TO UBIDOTS FOR PARSING\n#requests.get(\"https://industrial.ubidots.com/api/v1.6/devices/colab/?token=BBFF-M7ILRHc7jaPB0QRbebTJP6T4zmQL2D&_method=post&ngport=\"+port)\nDEVICE = \"colab\"\nTOKEN = \"BBFF-M7ILRHc7jaPB0QRbebTJP6T4zmQL2D\"\nurl = \"http://industrial.api.ubidots.com/api/v1.6/devices/{}\".format(DEVICE)\nheaders = {\"X-Auth-Token\": TOKEN, \"Content-Type\": \"application/json\"}\n\ndef send_payload(payload):\n requests.post(url, headers=headers, json=payload)\n\ndef get_tunnel():\n try:\n # print(\"creating a tunnel over ngrok\")\n portfwd = \"6006\"\n os.system('./ngrok http '+portfwd+' &')\n # get_ipython().system_raw('./ngrok http '+portfwd+' &')\n tunnel_list = requests.get(\"http://localhost:4040/api/tunnels\").json()\n # print(tunnel_list)\n new_tunnel = tunnel_list['tunnels'][0]['public_url']\n print(new_tunnel)\n if new_tunnel is not None:\n send_payload({\"flask1\":{\"value\":1,\"context\":{\"tunnel\":new_tunnel}}})\n return new_tunnel\n except:\n # print(\"retry ...\")\n get_tunnel()\n\ntun = get_tunnel()\nprint(tun)\n\nfrom tasks import *\nfrom flask import Flask,request\nimport time\napp = Flask(__name__,static_folder=\"/content/\",root_path='/content/')\n\n#redis \nimport redis\nfrom rq import Queue\nr = redis.Redis()\nq = Queue(connection=r)\n\n\n# @app.route(\"/\")\n# def hello():\n# return app.send_static_file(\"web/index.html\")\n\n@app.route(\"/\",methods = ['POST', 'GET'])\ndef proc():\n try:\n if(method == 'POST'):\n song = request.form['song']\n mail = request.form['mail']\n print(\"request from :\",mail,\"song :\",song)\n import ytdl\n ytdl.dl(song)\n return \"processing:\"+song\n except:\n return \"No song name\"\n \n #add to task queue and return task-id\n \n # return app.send_static_file(\"web/proc.html\")\n\n\n@app.route(\"/task\")\ndef index():\n if request.args.get(\"n\"):\n job = q.enqueue(background_task, request.args.get(\"n\"))\n return f\"Task ({job.id}) added to queue at {job.enqueued_at}\"\n return \"No value for count provided\"\n\n@app.route('/login',methods = ['POST', 'GET'])\ndef login():\n if(request.method == 'POST'):\n user = request.form['nm']\n passw = request.form['pass']\n if(user == 'admin' and passw == 'admin123'):\n return redirect(url_for('success',name = user))\n else:\n return app.send_static_file('./login.html')\n\nif(test_mode): \n app.run(host = '0.0.0.0',port = 6006) \n# !export FLASK_APP=run.py;export FLASK_ENV=development;flask run\nelse:\n import threading\n threading.Thread(target=app.run, kwargs={'host':'0.0.0.0','port':6006}).start() \n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"37624135","text":"import os\nimport json\nfrom flask import Flask, render_template, request, redirect, url_for \nglobal score, name\nscore = 0\nscore2 = 0\n\napp = Flask(__name__)\n\nclass Question:\n def __init__(self, prompt, answer):\n self.prompt = prompt\n self.answer = answer\n \nquestions = [\n Question([0], \"Python\"),\n Question([1], \"Paris\"),\n Question([2], \"Moonlight\"),\n Question([3], \"Lemonade\"),\n Question([4], \"Yes\"),\n Question([5], \"Call Me By Your Name\"),\n Question([6], \"Engels & Marx\"),\n Question([7], \"Freud\"),\n Question([8], \"Gordon Ramsay\")\n \n]\n\n@app.route('/')\ndef quiz():\n global score\n return render_template('index.html')\n@app.route('/start',methods=[\"POST\"])\ndef getUser():\n name = request.form[\"username\"]\n global username\n username = name\n return render_template('index.html')\n \n@app.route('/quiz', methods=['POST']) \ndef quiz_answers():\n for Question in questions:\n answer = request.form['language']\n global score\n if answer == Question.answer:\n score = score+1\n return render_template('capitals.html',data=score) \n return render_template(\"index.html\") + answer + \"

is not correct, guess again.

\"\n \n@app.route('/question', methods=['POST'])\ndef question_two():\n for Question in questions:\n answer = request.form['capital']\n global score\n if answer == Question.answer:\n score = score+1\n return render_template('movies.html',data=score)\n return render_template('capitals.html', data=score) + answer + \"

is not correct, guess again.

\"\n \n@app.route('/movie', methods=['POST'])\ndef question_three():\n for Question in questions:\n answer = request.form['movie']\n if answer == Question.answer:\n global score\n score += 1\n return render_template('music.html',data=score)\n return render_template(\"movies.html\", data=score) + answer + \"

is not correct. Wanna guess again

\"\n \n \n@app.route('/music', methods=['POST'])\ndef question_four():\n for Question in questions:\n answer = request.form['album']\n if answer == Question.answer:\n global score\n score += 1\n return render_template('results.html',data=score)\n return render_template(\"music.html\", data=score) + answer + \"

is not correct, guess again.

\"\n \n@app.route('/ready', methods=['POST'])\ndef results1():\n for Question in questions:\n answer = request.form['ready']\n if answer == Question.answer:\n return render_template('novel.html')\n return render_template('novel.html') \n \n@app.route('/novel', methods=['POST'])\ndef question5():\n for Question in questions:\n answer = request.form['novel']\n if answer == Question.answer:\n global score2\n score2 += 1\n return render_template('history.html',data2=score2)\n return render_template('novel.html',data2=score2) + answer + \"

is not correct, guess again.

\"\n \n@app.route('/history', methods=['POST'])\ndef question6():\n for Question in questions:\n answer = request.form['history']\n if answer == Question.answer:\n global score2\n score2 += 1\n return render_template('psychology.html',data2=score2)\n return render_template('history.html',data2=score2) + answer + \"

is not correct, guess again.

\"\n \n@app.route('/psychology', methods=['POST'])\ndef question7():\n for Question in questions:\n answer = request.form['psychology']\n if answer == Question.answer:\n global score2\n score2 += 1\n return render_template('cuisine.html',data2=score2)\n return render_template('psychology.html',data2=score2) + answer + \"

is not correct, guess again.

\"\n \n@app.route('/cuisine', methods=['POST'])\ndef question8():\n for Question in questions:\n global score\n answer = request.form['cuisine']\n if answer == Question.answer:\n global score2\n score2 += 1\n return render_template('results2.html',data2=score2, data=score)\n return render_template('cuisine.html',data2=score2) + answer + \"

is not correct, guess again.

\"\n \nif __name__ == '__main__':\n app.run(host=os.environ.get('IP'),\n port=int(os.environ.get('PORT')),\n debug=True)\n ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"219921272","text":"import komand\nfrom .schema import ModifySavedSearchPropertiesInput, ModifySavedSearchPropertiesOutput\n# Custom imports below\nimport json\n\n\nclass ModifySavedSearchProperties(komand.Action):\n\n def __init__(self):\n super(self.__class__, self).__init__(\n name='modify_saved_search_properties',\n description='Modifies the properties of a saved search',\n input=ModifySavedSearchPropertiesInput(),\n output=ModifySavedSearchPropertiesOutput())\n\n def run(self, params={}):\n saved_search_name = params.get(\"saved_search_name\")\n properties = params.get(\"properties\")\n\n param_dict = json.loads(\n json.dumps(properties, default=lambda o: o.__dict__, indent=4, sort_keys=True)\n )\n\n try:\n saved_search_to_update = self.connection.client.saved_searches[saved_search_name]\n saved_search_to_update.update(**param_dict).refresh()\n except KeyError as error:\n self.logger.error(error)\n return {\"success\": False}\n\n return {\"success\": True}\n\n def test(self):\n return {}\n","sub_path":"splunk/komand_splunk/actions/modify_saved_search_properties/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"380722899","text":"'''\nEscreva um programa que faça o computador \"pensar\", em um número inteiro entre 0 e 5, e peça para o usuário tentar \ndescobrir qual número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.\n'''\nfrom random import randint\ncomputador = randint(0,5) #Faz o computador sortear um número\nprint('Estou pensando em um número entre 0 e 5, tente advinhar:')\njogador = int(input('Em que numero eu pensei?'))\nif (jogador == computador):\n print('Parabens voce acertou')\nelse:\n print('Que pena você errou, eu estava pensando no numero {}'.format(computador))\n\n","sub_path":"ex28.py","file_name":"ex28.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"401366458","text":"from django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom blog.forms import *\nfrom django.contrib import messages\nfrom blog.models import *\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import path, reverse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Count, Q\nfrom .models import *\nfrom .forms import *\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect, Http404, HttpResponseForbidden, HttpResponseNotFound\nfrom django.core.exceptions import PermissionDenied\nimport json\nimport requests\nfrom django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.decorators import login_required, user_passes_test, permission_required\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.core.mail import send_mail\nfrom django.template.loader import get_template\nimport logging\nfrom django.contrib.auth import get_user_model\nfrom blog.utils import *\n\nUser = get_user_model()\n# logger = logging.getLogger(__name__) \n\n\n@login_required\ndef profile(request):\n p_form = ProfileForm(request.POST or None, request.FILES or None, instance = request.user.profile)\n u_form = UserForm(request.POST or None, instance = request.user)\n if request.method == 'POST' and u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, 'Ваши данные были обновлены')\n return redirect(reverse('profile'))\n return render(request, 'blog/profile.html', locals())\n\n\ndef profile_pk(request, pk):\n profile = Profile.objects.get(pk=pk)\n return render(request, 'blog/profile_pk.html', {'profile':profile})\n\n\n@login_required\ndef profile_delete(request, pk):\n if int(pk) == request.user.profile.pk:\n profile = get_object_or_404(Profile, pk=int(pk))\n user = get_object_or_404(User, pk=int(pk))\n profile.delete()\n user.delete()\n messages.success(request, 'Ваши аккаунт был удален')\n request.session.flush()\n return redirect('blog')\n messages.success(request, 'Неверные данные')\n return redirect('blog')\n\n\ndef profile_posts(request, username):\n user = User.objects.get(username=username)\n posts = Post.objects.all().filter(profile__pk=user.pk)\n for post in posts:\n print(post.content)\n return render(request, 'blog/profile_posts.html', {'posts':posts})\n\n\ndef index(request):\n ''' тестовая работа с почтой, потом надо будет подключить sendgrid или mailchimp'''\n # logger.debug('debug info!')\n if request.method == 'POST':\n name = request.POST['name']\n email = request.POST['email']\n message = request.POST['message']\n subject = ' Contact form Received '\n from_email = settings.DEFAULT_FROM_EMAIL\n to_email = [settings.DEFAULT_FROM_EMAIL, email]\n new_signup = Signup()\n new_signup.name = name\n new_signup.email = email\n new_signup.message = message\n new_signup.save()\n context = {\n 'user': name,\n 'email': email,\n 'message': message,\n } \n contact_message = get_template('blog/contact_message.txt').render(context)\n # contact_message = '{}, from {} with email {}'.format(message, name,email)\n send_mail(subject, contact_message, from_email, to_email, fail_silently=True)\n return redirect(reverse('index'))\n return render(request, 'blog/index.html', {})\n\n\ndef search(request):\n posts = Post.objects.all()\n query = request.GET.get('q')\n if query:\n posts = posts.filter(\n Q(title__icontains=query) |\n Q(overview__icontains=query)\n ).distinct()\n context = {\n 'posts': posts\n }\n template = 'blog/search_results.html'\n return render(request, template, context)\n\n\n# posts CRUD\n\ndef blog(request):\n posts = Post.objects.all()\n return render(request, 'blog/blog.html', locals())\n\n\n@login_required\ndef post_create(request):\n title = \"Создать статью\"\n form = PostForm(request.POST or None, request.FILES or None)\n if request.method == 'POST':\n if form.is_valid():\n form.instance.profile = request.user\n form.save() \n messages.success(request, 'Статья была успешно создана!')\n return redirect('post_detail', pk=form.instance.id)\n return render(request, 'blog/create_or_update.html', locals())\n\n\ndef post_detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/post.html', locals())\n\n\n@login_required\ndef post_update(request, pk):\n title = 'Изменить Статью'\n post = get_object_or_404(Post, pk=pk)\n if request.user != post.profile:\n raise PermissionDenied\n form = PostForm(\n request.POST or None, \n request.FILES or None,\n instance=post\n )\n if request.method == 'POST':\n if form.is_valid():\n form.instance.profile = request.user\n form.save()\n messages.success(request, 'Статья была успешно изменена!')\n return redirect('post_detail', pk=form.instance.pk) #pk=post.pk)\n return render(request, 'blog/create_or_update.html', locals())\n\n\n@login_required\ndef post_delete(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == 'POST':\n if request.user != post.profile:\n return HttpResponseForbidden() \n post.delete()\n messages.success(request, 'Статья была успешно удалена!')\n return redirect('posts_list') \n return render(request, 'blog/post_delete.html', locals()) \n\n\n# Categories CRUD\n\ndef cats_list(request):\n cats = Category.objects.all()\n return render(request, 'blog/cats_list.html', {'cats':cats})\n\n@staff_member_required\ndef cat_create(request):\n form = CatForm(request.POST or None)\n if request.method == 'POST' and form.is_valid():\n form.save()\n return redirect(reverse('cat_detail', kwargs={'id':form.instance.id}))\n return render(request, 'blog/create_or_update.html', {'form':form})\n\n \n@staff_member_required\ndef cat_update(request, pk):\n title = 'Изменить категорию'\n cat = get_object_or_404(Category, id=id)\n form = TagForm(request.POST or None, instance=cat)\n # form = TagForm(request.POST or None, {'title': cat.title, \n # 'slug': cat.slug})\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return redirect(reverse('cat_detail', kwargs={'id':form.instance.id}))\n return render(request, 'blog/create_or_update.html', {'form':form,'title': title})\n\n\n@staff_member_required\ndef cat_delete(request, pk):\n cat = get_object_or_404(Category, pk=pk)\n cat.delete()\n return redirect(reverse('blog'))\n # return render(request, 'blog/delete.html', {})\n\n \n# Tags CRUD\n\ndef tags_list(request):\n tags = Tag.objects.all()\n return render(request, 'blog/tags_list.html', {'tags':tags})\n\n\n@staff_member_required\ndef tag_create(request):\n title = 'Создать новый тэг'\n form = TagForm(request.POST or None)\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return redirect(reverse('tag_detail', kwargs={'id':form.instance.id}))\n return render(request, 'blog/create_or_update.html', {'form':form, 'title':title})\n\n\n@staff_member_required\ndef tag_update(request, pk):\n title = 'Изменить тэг'\n tag = get_object_or_404(Tag, pk=pk)\n form = TagForm(request.POST or None, instance=tag) #{'title': tag.title, 'slug': tag.slug})\n if request.method == 'POST':\n if form.is_valid():\n form.save()\n return redirect(reverse('tag_detail', kwargs={'pk':form.instance.pk}))\n return render(request, 'blog/create_or_update.html', {'form':form,'title': title})\n\n\n@staff_member_required\ndef tag_delete(request, pk):\n tag = get_object_or_404(Tag, pk=pk)\n tag.delete()\n return redirect(reverse('blog'))\n # return render(request, 'blog/delete.html', {})","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"279307108","text":"from ..tasks.tasks import process_rates, clean_rates\nfrom unittest.mock import Mock, call\n\n\ndef test_process_rates(monkeypatch):\n \"\"\"\n Testing rates processing (succession of calls).\n :param monkeypatch: a monkeypatch instance.\n :return:\n \"\"\"\n mocked_rates = Mock(json=Mock(return_value={'rates': {'EUR': '1'}}))\n mock = Mock(return_value=mocked_rates)\n monkeypatch.setattr('usio.tasks.tasks.fetch_rates', mock)\n monkeypatch.setattr('usio.tasks.tasks.prepare_rates', mock)\n monkeypatch.setattr('usio.tasks.tasks.store_rates', mock)\n process_rates()\n # First fetching the rates, then preparing the rates based on the json eventually storing the rates object.\n assert mock.mock_calls == [call(),\n call({'EUR': '1'}),\n call(mocked_rates)]\n","sub_path":"tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"591433517","text":"from googlesearch import search\r\nimport requests\r\nimport os\r\nimport preprocessor as p\r\nfrom urllib.request import urlopen\r\nfrom bs4 import BeautifulSoup\r\nfrom ScrapeSearchEngine.ScrapeSearchEngine import Google\r\nfrom ScrapeSearchEngine.ScrapeSearchEngine import Duckduckgo\r\nfrom ScrapeSearchEngine.ScrapeSearchEngine import Givewater\r\nfrom ScrapeSearchEngine.ScrapeSearchEngine import Bing\r\nfrom ScrapeSearchEngine.ScrapeSearchEngine import Yahoo\r\nfrom ScrapeSearchEngine.ScrapeSearchEngine import Ecosia\r\n\r\nuserAgent = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'\r\n ' Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68')\r\n#search on google \"my user agent\"\r\n\r\n#check a url can be doawnloaded as a file?\r\ndef is_downloadable(url):\r\n \"\"\"\r\n Does the url contain a downloadable resource\r\n \"\"\"\r\n h = requests.head(url, allow_redirects=True)\r\n header = h.headers\r\n content_type = header.get('content-type')\r\n if 'text' in content_type.lower():\r\n return False\r\n if 'html' in content_type.lower():\r\n return False\r\n return True\r\n# search keyword from multiple search engine include\r\ndef search_keyword(search):\r\n list_url = []\r\n list_url.extend(Google(search, userAgent))\r\n list_url.extend(Bing(search, userAgent))\r\n list_url.extend( Yahoo(search, userAgent))\r\n list_url.extend(Duckduckgo(search, userAgent))\r\n list_url.extend(Givewater(search, userAgent))\r\n list_url.extend (Ecosia(search, userAgent))\r\n return list(dict.fromkeys(list_url))\r\n\r\n# download file downloadable such as: pdf, docx,...\r\ndef download_document(url):\r\n if (is_downloadable(url)):\r\n name = os.path.basename(url)\r\n r = requests.get(url, allow_redirects=True)\r\n open(\"file_downloaded\\\\\" + name, 'wb').write(r.content)\r\n return \"file_downloaded\\\\\" + name\r\n\r\n# crawl text from html website then preprocess and give output: list sentence after preprocessing.\r\ndef crawl_web(url):\r\n html = urlopen(url).read()\r\n soup = BeautifulSoup(html, features=\"html.parser\")\r\n\r\n # kill all script and style elements\r\n for script in soup([\"script\", \"style\"]):\r\n script.extract() # rip it out\r\n # get text\r\n text = soup.get_text()\r\n\r\n # break into lines and remove leading and trailing space on each\r\n lines = (line.strip() for line in text.splitlines())\r\n # break multi-headlines into a line each\r\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\r\n\r\n # drop blank lines\r\n text = '\\n'.join(chunk for chunk in chunks if chunk)\r\n temp = p.list_para2txt(text.split(\"\\n\"))\r\n res = p.convert2listsentence(temp)\r\n return res #list sentence","sub_path":"preprocessing/internet.py","file_name":"internet.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"635734894","text":"import config\nimport cgi, cgitb\nfrm=cgi.FieldStorage()\n\nname=frm.getvalue('name')\ncontact=frm.getvalue('contact')\ncrop1=frm.getvalue('crop1')\ncrop2=frm.getvalue('crop2')\ncrop3=frm.getvalue('crop3')\ncrop4=frm.getvalue('crop4')\ncrop5=frm.getvalue('crop5')\nlocation=frm.getvalue('location')\naddress=frm.getvalue('address')\npwd=frm.getvalue('pwd')\n\ncur=config.db.cursor()\ncur.execute(\"SELECT contact FROM freg WHERE contact='{}'\".format(contact))\nrs=cur.fetchall()\n\nif rs:\n print ('''''')\nelse:\n try:\n cursor=config.db.cursor()\n sql=\"INSERT INTO freg (name,contact,crop1,crop2,crop3,crop4,crop5,location,address,pwd)VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')\"%(name,contact,crop1,crop2,crop3,crop4,crop5,location,address,pwd)\n if cursor.execute(sql):\n config.db.commit()\n config.db.close()\n print (''''''')\n except Exception as e:\n print (e)\n","sub_path":"Final_Project/fregister_code1.py","file_name":"fregister_code1.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"516463986","text":"\"\"\"\n=============================\nAuthor : lsw\nTime : 2019-09-20\nE-mail :591271859@qq.com\n=============================\n\"\"\"\nimport os\nimport time\nimport unittest\nfrom class21_test_api_webservice.common.mylogger import log\nfrom class21_test_api_webservice.common.config import myconf\nfrom class21_test_api_webservice.pack_lib.ddt import ddt, data\nfrom class21_test_api_webservice.common.do_mysql import ReadSQL\nfrom class21_test_api_webservice.common.constant import DATA_DIR\nfrom class21_test_api_webservice.common.read_excel import ReadExcel\nfrom class21_test_api_webservice.common.random_var import RandomeVar\nfrom class21_test_api_webservice.common.web_requests import WebRequests\nfrom class21_test_api_webservice.common.text_replace import data_replace, ConText\n\n\n@ddt\nclass BankCardTestCase(unittest.TestCase):\n \"\"\"绑定银行卡接口\"\"\"\n excel = ReadExcel(os.path.join(DATA_DIR, 'cases.xlsx'), 'bankcard')\n cases = excel.read_data_obj()\n db = ReadSQL()\n r_var = RandomeVar()\n web_s = WebRequests()\n\n def setUp(self):\n # 前置条件1:发送验证码\n url = myconf.get('url', 'test_url') + '/sms-service-war-1.0/ws/smsFacade.ws?wsdl'\n ip = self.r_var.random_ip()\n log.info(\"随机生成的IP:{}\".format(ip))\n phone = self.r_var.random_phone()\n log.info(\"随机生成的手机号:{}\".format(phone))\n\n data = {\"client_ip\": ip, \"tmpl_id\": 1, \"mobile\": phone}\n log.info(\"请求数据:{}\".format(data))\n response1 = self.web_s.requests(url=url, interface=\"sendMCode\", data=data)\n log.info(\"请求返回结果:{}\".format(response1))\n db_no = phone[-2:]\n info_no = phone[-3]\n code = self.db.find_data(\n \"SELECT Fverify_code FROM sms_db_{0}.t_mvcode_info_{1} WHERE Fmobile_no='{2}'\".format(db_no, info_no,\n phone), res_num=1)\n log.info(\"{0}接收到的验证码为:{1}\".format(phone, code[0]))\n setattr(ConText, 'phone', phone)\n\n # 前置条件2:注册新用户\n url = myconf.get('url', 'test_url') + '/finance-user_info-war-1.0/ws/financeUserInfoFacade.ws?wsdl'\n user = self.r_var.random_user()\n log.info(\"随机生成的用户名:{}\".format(user))\n\n data = {\"verify_code\": code[0], \"user_id\": user, \"channel_id\": \"1\", \"pwd\": \"123456\", \"mobile\": phone, \"ip\": ip}\n log.info(\"请求数据:{}\".format(data))\n response2 = self.web_s.requests(url=url, interface=\"userRegister\", data=data)\n log.info(\"请求返回结果:{}\".format(response2))\n uid = self.db.find_data(\"SELECT Fuid FROM user_db.t_user_info WHERE Fuser_id ='{}'\".format(user), res_num=1)\n log.info(\"{} 的UID:{}\".format(phone, uid[0]))\n # 将查询出来的用户UID,保存为临时变量\n setattr(ConText, 'uid', uid[0])\n db_no = phone[-2:]\n info_no = phone[-3]\n bind_card_table = \"user_db_{0}.t_bind_card_{1}\".format(db_no, info_no)\n setattr(ConText, 'table', bind_card_table[0])\n\n # 前置条件3:实名认证\n name = self.r_var.random_name()\n log.info(\"随机生成姓名:{}\".format(name))\n setattr(ConText, 'name', name[0])\n now = time.strftime('%Y%m%d', time.localtime(time.time()))\n id_num = self.r_var.random_idnum('19800101', now)\n log.info(\"随机生成身份证号:{}\".format(id_num))\n setattr(ConText, 'id_num', id_num[0])\n\n data = {\"uid\": uid, \"true_name\": name, \"cre_id\": id_num}\n log.info(\"请求数据:{}\".format(data))\n response3 = self.web_s.requests(url=url, interface=\"verifyUserAuth\", data=data)\n log.info(\"请求返回结果:{}\".format(response3))\n try:\n self.assertEqual({\"retCode\": \"0\", \"retInfo\": \"ok\"}, response3)\n except AssertionError as e:\n log.info(\"{}实名认证失败,无法进行银行卡绑定!\".format(phone))\n log.exception(e)\n raise e\n\n @data(*cases)\n def test_case_bank_card(self, case):\n \"\"\"绑定银行卡\"\"\"\n url = myconf.get('url', 'test_url') + case.url\n\n bank_card = self.r_var.random_bankcard()\n log.info(\"随机生成的银行卡号:{}\".format(bank_card))\n case.data = case.data.replace('*bank_card*', bank_card)\n\n case.data = data_replace(case.data)\n log.info(\"请求数据:{}\".format(case.data))\n response = self.web_s.requests(url=url, interface=\"bindBankCard\", data=eval(case.data))\n log.info(\"请求返回结果:{}\".format(response))\n\n try:\n self.assertEqual(eval(case.excepted), response)\n if case.check_sql:\n case.check_sql = data_replace(case.check_sql)\n log.info(\"请求数据库数据:{}\".format(case.check_sql))\n db_res = self.db.find_count(case.check_sql)\n self.assertEqual(1, db_res)\n except AssertionError as e:\n self.excel.write_data(row=case.case_id + 1, column=7, value=\"未通过\")\n log.info('{},该条测试用例执行未通过!'.format(case.title))\n log.exception(e)\n raise e\n else:\n self.excel.write_data(row=case.case_id + 1, column=7, value=\"通过\")\n log.info('{},该条测试用例执行通过!'.format(case.title))\n","sub_path":"class21_test_api_webservice/testcases/test_bindbankcard.py","file_name":"test_bindbankcard.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"64495035","text":"# 1620. 나는야 포켓몬 마스터 이다솜 (실버4)\n\nimport sys\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\npokemons = [input().rstrip() for _ in range(n)]\nbook = dict(zip(pokemons, map(str, range(1, n+1))))\nresult = []\nfor _ in range(m):\n question = input().rstrip()\n if question.isdecimal():\n result.append(pokemons[int(question)-1])\n else:\n result.append(book[question])\nprint('\\n'.join(result))","sub_path":"week11_6_8/BOJ_1620_영주.py","file_name":"BOJ_1620_영주.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"625387246","text":"\"\"\"\ndayong.bot\n~~~~~~~~~~\n\nThis module defines the startup logic for Dayong.\n\"\"\"\nimport os\nfrom pathlib import Path\n\nimport hikari\nimport tanjun\n\nfrom dayong.configs import DayongConfig, DayongConfigLoader\nfrom dayong.impls import MessageDBImpl\nfrom dayong.settings import BASE_DIR\n\n\ndef run() -> None:\n \"\"\"Run Dayong with configs and deps.\"\"\"\n loaded_config = DayongConfigLoader.load()\n bot = hikari.GatewayBot(\n loaded_config.bot_token,\n banner=\"dayong\",\n intents=hikari.Intents.ALL,\n )\n (\n tanjun.Client.from_gateway_bot(\n bot, set_global_commands=hikari.Snowflake(loaded_config.guild_id)\n )\n .load_modules(*Path(os.path.join(BASE_DIR, \"components\")).glob(\"*.py\"))\n .add_prefix(loaded_config.bot_prefix)\n .set_type_dependency(DayongConfig, lambda: loaded_config)\n .set_type_dependency(\n MessageDBImpl, tanjun.cache_callback(MessageDBImpl.connect)\n )\n )\n bot.run()\n","sub_path":"dayong/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"644435297","text":"'''\nzip 파일 압축 해제\n'''\n\n\nimport zipfile, os\n\n# ------------------------------------------------------------\n\n\nfilepath = 'C:\\\\CodeLab\\example.zip'\n# 존재하는 zip파일을 오픈한 후 zipfile객체를 반환합니다.\n# exampleZip = zipfile.ZipFile('Arduino-master.zip')\nexampleZip = zipfile.ZipFile(filepath)\n\n# print(os.path.basename(filepath)) \n\n\n# 압축풀 폴더 생성 후 해당 폴더로 이동\nif os.path.exists(\"C:\\\\CodeLab\\example\"):\n os.chdir('C:\\\\CodeLab\\example')\nelse:\n os.mkdir(\"C:\\\\CodeLab\\example\")\n\nprint (os.getcwd())\n\n# zip파일의 모든 내용을 압축해제합니다.\nexampleZip.extractall()\n\nexampleZip.close()","sub_path":"PythonData/src/ch-zip/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"537184886","text":"\"\"\"\nConvenience module for access of custom pages application settings,\nwhich enforces default settings when the main settings module does not\ncontain the appropriate settings.\n\"\"\"\nfrom os.path import join\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\n\n# Which templates should be used for extracting the placeholders?\n# example: CMS_TEPLATES = (('base.html', 'default template'),)\nCMS_TEMPLATES = getattr(settings, 'CMS_TEMPLATES', None)\nif CMS_TEMPLATES is None:\n raise ImproperlyConfigured('Please make sure you specified a CMS_TEMPLATES setting.')\n\n# Whether to enable permissions.\nCMS_PERMISSION = getattr(settings, 'CMS_PERMISSION', True)\n\n# Whether a slug should be unique together with its parent and in the same lanuage?\ni18n_installed = not 'cms.middleware.MultilingualURLMiddleware' in settings.MIDDLEWARE_CLASSES\nCMS_UNIQUE_SLUGS = getattr(settings, 'CMS_UNIQUE_SLUGS', i18n_installed)\n\n# Wheter the cms has a softroot functionionality\nCMS_SOFTROOT = getattr(settings, 'CMS_SOFTROOT', False)\n\n# Defines which languages should be offered.\nCMS_LANGUAGES = getattr(settings, 'CMS_LANGUAGES', settings.LANGUAGES)\n\n# Defines which language should be used by default and falls back to LANGUAGE_CODE\nCMS_DEFAULT_LANGUAGE = getattr(settings, 'CMS_DEFAULT_LANGUAGE', settings.LANGUAGE_CODE)[:2]\n\n# Defines how long page content should be cached, including navigation and admin menu.\nCMS_CONTENT_CACHE_DURATION = getattr(settings, 'CMS_CONTENT_CACHE_DURATION', 60)\n\n# The id of default Site instance to be used for multisite purposes.\nSITE_ID = getattr(settings, 'SITE_ID', 1)\nDEBUG = getattr(settings, 'DEBUG', False)\nMANAGERS = settings.MANAGERS\nDEFAULT_FROM_EMAIL = settings.DEFAULT_FROM_EMAIL\nINSTALLED_APPS = settings.INSTALLED_APPS\nLANGUAGES = settings.LANGUAGES\n\n# if the request host is not found in the db, should the default site_id be used or not? False means yes\nCMS_USE_REQUEST_SITE = getattr(settings, 'CMS_USE_REQUEST_SITE', False)\n\n# You can exclude some placeholder from the revision process\nCMS_CONTENT_REVISION_EXCLUDE_LIST = getattr(settings, 'CMS_CONTENT_REVISION_EXCLUDE_LIST', ())\n\n# URL that handles pages' media and uses /pages by default.\nCMS_MEDIA_URL = getattr(settings, 'CMS_MEDIA_URL', join(settings.MEDIA_URL, 'cms/'))\n\n# Show the publication date field in the admin, allows for future dating\n# Changing this from True to False could cause some weirdness. If that is required,\n# you should update your database to correct any future dated pages\nCMS_SHOW_START_DATE = getattr(settings, 'CMS_SHOW_START_DATE', False)\n\n# Show the publication end date field in the admin, allows for page expiration\n# Changing this from True to False could cause some weirdness. If that is required,\n# you should update your database and null any pages with publication_end_date set.\nCMS_SHOW_END_DATE = getattr(settings, 'CMS_SHOW_END_DATE', False)\n\n# Whether the user can overwrite the url of a page\nCMS_URL_OVERWRITE = getattr(settings, 'CMS_URL_OVERWRITE', True)\n\n# a tuble with a python path to a function that returns a list of navigation nodes\nCMS_NAVIGATION_EXTENDERS = getattr(settings, 'CMS_NAVIGATION_EXTENDERS', ())\n","sub_path":"cms/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"375427779","text":"# -*- coding:utf-8 -*-\n# Copyright (c) 2011 Renato de Pontes Pereira, renato.ppontes at gmail dot com\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy \n# of this software and associated documentation files (the \"Software\"), to deal \n# in the Software without restriction, including without limitation the rights \n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \n# copies of the Software, and to permit persons to whom the Software is \n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all \n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \n# SOFTWARE.\n\n'''This module contains the main classes for game creation\n\nA game that inherits the Game class have the following flow:\n\n 1. initialize\n 2. load_content\n 3. repeat:\n\n 1. update\n 2. draw\n'''\n\nimport pyglet\nimport batma\nfrom batma.camera import Camera\nfrom batma.input import KeyboardState\nfrom batma.input import MouseState\nfrom batma.util import singleton\nfrom batma.algebra import Vector2\nfrom batma import colors\n\n@singleton\nclass Batch(pyglet.graphics.Batch):\n def __init__(self):\n pyglet.graphics.Batch.__init__(self)\n\n self.base_group = pyglet.graphics.OrderedGroup(2)\n self.fringe_group = pyglet.graphics.OrderedGroup(4)\n self.object_group = pyglet.graphics.OrderedGroup(8)\n self.text_group = pyglet.graphics.OrderedGroup(16)\n\nclass Game(pyglet.window.Window):\n '''\n Game flow control.\n\n This class inherits a ``pyglet.window.Window`` to create a graphical \n application, every method related to pyglet window can be applied here.\n\n **Important!** Do not overrid ``__init__`` or ``on_draw``.\n\n :Ivariables:\n keyboard : `KeyboardState`\n A `KeyboardState` object that handle keyboard input.\n mouse : `MouseState`\n A `MouseState` object that handle mouse input.\n '''\n\n def __init__(self, *args, **kwargs):\n '''Create a Game window instance.\n\n All parameters are sent to ``pyglet.window.Window`` and they are \n optional.\n\n Consult pyglet's documentation for better understand.\n\n :Parameters:\n width : int\n Width of the window, in pixels. Defaults to 640, or the\n screen width if ``fullscreen`` is True.\n height : int\n Height of the window, in pixels. Defaults to 480, or the\n screen height if ``fullscreen`` is True.\n caption : str or unicode\n Initial caption (title) of the window. Defaults to \"A Batma \n Game\".\n resizable` : bool\n If True, the window will be resizable. Defaults to False.\n style : int\n One of the ``WINDOW_STYLE_*`` constants specifying the\n border style of the window.\n fullscreen : bool\n If True, the window will cover the entire screen rather\n than floating. Defaults to False.\n visible : bool\n Determines if the window is visible immediately after\n creation. Defaults to True. Set this to False if you\n would like to change attributes of the window before\n having it appear to the user.\n vsync : bool\n If True, buffer flips are synchronised to the primary screen's\n vertical retrace, eliminating flicker.\n display : ``Display``\n The display device to use. Useful only under X11.\n screen : ``Screen``\n The screen to use, if in fullscreen.\n config : ``pyglet.gl.Config``\n Either a template from which to create a complete config,\n or a complete config.\n context : ``pyglet.gl.Context``\n The context to attach to this window. The context must\n not already be attached to another window.\n mode : ``ScreenMode``\n The screen will be switched to this mode if ``fullscreen`` is\n True. If None, an appropriate mode is selected to accomodate\n ``width`` and ``height``.\n '''\n if len(args) < 3 and 'caption' not in kwargs:\n kwargs['caption'] = 'A Batma Game'\n\n super(Game, self).__init__(*args, **kwargs)\n\n self.batch = Batch()\n self.background_color = batma.colors.LAVANDERBLUE\n \n # TESTES\n self.__main_scene = None\n self._scenes = []\n self.camera = Camera(self.center)\n\n # Input\n self.keyboard = KeyboardState()\n self.mouse = MouseState()\n self.push_handlers(self.keyboard)\n self.push_handlers(self.mouse)\n\n self.set_mouse_visible(True)\n self.set_exclusive_mouse(False)\n\n # Callbacks\n pyglet.clock.schedule(self.on_update)\n\n # Resources\n pyglet.resource.path = []\n batma.add_resource_path('.')\n\n # Calls\n self.initialize()\n pyglet.resource.reindex()\n self.load_content()\n\n def get_background_color(self):\n return batma.Color(int(self.__background_color[0]*255),\n int(self.__background_color[1]*255),\n int(self.__background_color[2]*255),\n int(self.__background_color[3]*255))\n def set_background_color(self, value):\n alpha = value[3] if len(value) > 3 else 255\n self.__background_color = (\n value[0]/255.0,\n value[1]/255.0,\n value[2]/255.0,\n alpha/255.0\n )\n background_color = property(get_background_color, set_background_color)\n\n\n @property\n def size(self):\n return Vector2(self.width, self.height)\n \n @size.setter\n def size(self, value):\n self.set_size(value[0], value[1])\n\n @property\n def center(self):\n return Vector2(self.width/2.0, self.height/2.0) \n\n def on_update(self, tick):\n for scene in self._scenes:\n scene.update(tick)\n\n self.update(tick)\n self.camera.update(tick)\n\n def on_draw(self):\n '''\n The window contents must be redrawn. Inherited from \n ``pyglet.window.Window``.\n '''\n self.clear()\n pyglet.gl.glClearColor(*self.__background_color)\n \n pyglet.gl.glPushMatrix()\n self.camera.reset(self.center)\n\n for scene in self._scenes:\n scene.draw()\n\n self.draw()\n\n self.camera.apply(self.center)\n pyglet.gl.glPopMatrix()\n\n def add_scene(self, scene):\n scene.game = self\n scene.load_content()\n if not scene.popup:\n if self.__main_scene:\n self.remove_scene(self.__main_scene)\n self.__main_scene = scene\n self._scenes.insert(0, scene)\n else:\n self._scenes.append(scene)\n \n def remove_scene(self, scene):\n self._scenes.remove(scene)\n\n def initialize(self):\n '''\n Initialize method. Override Me =]\n\n This is the first method called on Game instantiation, you can set game\n properties overriding it, e.g., screen and pyglet configurations.\n '''\n pass\n\n def load_content(self):\n '''\n Load Content method. Override Me =]\n\n Called after `initialize`, the goal of this method is to loads every \n game asset such images, animation, sounds, fonts, etc.\n '''\n pass\n\n def update(self, tick):\n '''\n Update method. Override Me =]\n\n Called every frame **BEFORE** `draw`. This is the best method for game \n logic.\n '''\n pass\n\n def draw(self):\n '''\n Draw method. Override Me =]\n\n Called every frame **AFTER** `update`. This method is the place to draw\n every object in screen.\n '''\n pass\n\n","sub_path":"batma/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":8483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"587443051","text":"\"\"\"\nRegroup all Adventure Man language commands \n\"\"\"\n\nfrom discord.ext import commands\nfrom modules.lang import guilds_language as guildsLanguage\nfrom modules.role import role\n\nclass Language(commands.Cog):\n \"\"\" Regroup all language commands \"\"\"\n @commands.command(description='Change language of discord server')\n async def lang(self, ctx, arg: str):\n role_member = ctx.message.author.roles\n id_guilds = str(ctx.guild.id)\n\n if role.check_role(role_member, id_guilds) is True:\n result = guildsLanguage.change_guilds_language(arg, id_guilds)\n else:\n language_module = guildsLanguage.check_guilds_language(id_guilds)\n result = language_module.NO_PERMISSION\n\n await ctx.send(result)\n","sub_path":"commands/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"55064447","text":"##########################################\n # File name: runProb1.py\n # Author: Harrison Agrusa, Ramsey Karim, Julian Marohnic\n # Date created: 11/12/2017\n # Date last modified: 11/19/2017\n # Description: Create intial conditions files for problem 1, run code, produce plots\n##########################################\n\n\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport sys\n#from astropy import constants as C\n#import constants as cgs\n#import time\nimport subprocess\n\n####################################################################\n############################## Set up ##############################\n####################################################################\n\n\n# No need for tree code -- 2 particles\ntheta_crit = 0.0\n# No softening\nepsilon = 0.0\n# nsteps is on order of 5000 fyi\noutfreq = 20\n# Data is a massive dictionary that will be populated with all output from each run\ndata = {}\n# Eccentricity\neccentricities = [0.5, 0.9]\n# m = m1 = m2 = 1\nm = 1\n# Separation of particles\nr = 1\nvelocities = [np.sqrt(2.*(1-e)) for e in eccentricities]\n# 100 orbits\norbits = 100\n# Orbital period\nperiods = [np.pi*np.sqrt(2./(1+e)**3) for e in eccentricities]\n# Total integration times to get 100 orbits\ntimes = [orbits*P for P in periods]\n# Time steps\nhs = [0.05, 0.003]\n# Number of steps needed\nNs = [int(t/h) for t, h in zip(times, hs)]\n\n# Change directories into the code directory, src/\nos.chdir(\"src\")\nif len(sys.argv) == 2 and sys.argv[1] == \"-m\":\n\tsubprocess.call(\"make\")\nelif len(sys.argv) > 1:\n\tprint(\"You called the function with improper/too many arguments.\")\n\tprint(\"This function is normally called without arguments.\")\n\tprint(\"You may optionally add the flag '-m' to the end of the call to make/clean the C binaries.\")\n\tsys.exit()\n\n####################################################################\n######################### Helper Functions #########################\n####################################################################\n\ndef run_code(key):\n\tindex, integrator = key.split('_')\n\tindex = int(index[1]) - 1\n\toutdir_1 = \"output1/\" #output directory\n\t# Make output directory\n\tsubprocess.call(\"mkdir {}\".format(outdir_1), shell=True)\n\tsubprocess.call(\"./nbodymain {} {} {} {} {} {} {} {}\".format('prob1_{}.txt'.format(index),\n\t\ths[index], Ns[index], epsilon, outfreq, integrator, theta_crit, outdir_1), shell=True)\n\t# For reference: nbody takes arguments of this form:\n\t# \tUsage: ./nbodymain data.txt h Nsteps epsilon outfreq integrator theta_critical output_dir starting_index(optional)\n\toutfiles = sorted(os.listdir(outdir_1))\n\tdata[key] = np.empty((len(outfiles), 2, 7)) #2 particles, 7 data points\n\t# Get data\n\tfor i in range(0, len(outfiles)):\n\t\tdata[key][i, :, :] = np.genfromtxt(outdir_1 + str(outfiles[i]))\n\t# Remove directory, dont need it anymore\n\tsubprocess.call(\"rm -r {}\".format(outdir_1), shell=True)\n\ndef plot_xy(key):\n\tindex, integrator = key.split('_')\n\tindex = int(index[1]) - 1\n\tplt.plot(data[key][:, 0, 1], data[key][:, 0, 2], \".\", label = r\"$\\rm Particle \\ 1$\")\n\tplt.plot(data[key][:, 1, 1], data[key][:, 1, 2], \"x\", label = r\"$\\rm Particle \\ 2$\")\n\tplt.xlabel(r\"$\\rm X \\ Position$\", fontsize = 18)\n\tplt.ylabel(r\"$\\rm Y \\ Position$\", fontsize = 18)\n\tplt.title(r\"$\\rm X \\ vs \\ Y \\ e = {}$, {}\".format(eccentricities[index], integrators[integrator]))\n\tplt.tight_layout()\n\tplt.legend(loc='best')\n\tplt.axis(\"equal\")\n\tplt.savefig(\"XY_{}.pdf\".format(key))\n\tplt.show()\n\tplt.close()\n\ndef plot_phase_energy(key):\n\tindex, integrator = key.split('_')\n\tindex = int(index[1]) - 1\n\t# r = sqrt(x^2+y^2+z^2)\n\tr_1 = np.sqrt(data[key][:, 0, 1]**2 + data[key][:, 0, 2]**2 + data[key][:, 0, 3]**2)\n\tVr_1 = np.sum(data[key][:, 0, 4:7] * data[key][:, 0, 1:4])/r_1 #(v*r)/r\n\n\tr_2 = np.sqrt(data[key][:, 1, 1]**2 + data[key][:, 1, 2]**2 + data[key][:, 1, 3]**2)\n\tVr_2 = np.sum(data[key][:, 1, 4:7] * data[key][:, 1, 1:4])/r_2\n\n\tplt.subplot(211)\n\tplt.plot(r_1, Vr_1, \".\", label = r\"$\\rm Particle \\ 1$\")\n\tplt.plot(r_2, Vr_2, \".\", label = r\"$\\rm Particle \\ 2$\")\n\tplt.xlabel(r\"$\\rm r \\ (magnitude)$\")\n\tplt.ylabel(r\"$\\rm Radial \\ Velocity$\")\n\tplt.title(r\"$\\rm Phase \\ Diagram \\ e = {}$, {}\".format(eccentricities[index], integrators[integrator]))\n\tplt.legend()\n\tplt.tight_layout()\n\tplt.subplot(212)\n\tv1_sq = np.sum(data[key][:, 0, 4:7]**2, axis=1)\n\tv2_sq = np.sum(data[key][:, 1, 4:7]**2, axis=1)\n\trecip_r_sep = np.reciprocal(np.sqrt(np.sum((data[key][:, 1, 1:4] - data[key][:, 0, 1:4])**2, axis=1)))\n\tE = -recip_r_sep + (v1_sq + v2_sq)/2.\n\tE = (-2*E/(1 + eccentricities[index])) - 1\n\ttime_array1 = np.arange(E.size) * hs[index]\n\tplt.plot(time_array1, E, '-', color='g')\n\tplt.title(\"Fractional Change in Total Energy vs Time\")\n\tplt.ylabel(\"$\\Delta E / E_{0}$\")\n\tplt.xlabel(\"Time\")\n\tplt.tight_layout()\n\tplt.savefig(\"phase_energy_{}.pdf\".format(key))\n\tplt.show()\n\tplt.close()\n\n####################################################################\n################### Generate Initial Conditions ####################\n####################################################################\n\ndef generate_input(index):\n\tf = open('prob1_{}.txt'.format(index), 'w')\n\tf.write(\"{} {} {} {} {} {} {}\\n\".format(m, -r/2.0, 0.0, 0.0, 0.0, -velocities[index]/2.0, 0.0))\n\tf.write(\"{} {} {} {} {} {} {}\\n\".format(m, r/2.0, 0.0, 0.0, 0.0, velocities[index]/2.0, 0.0))\n\tf.close()\n\nfor i in range(2):\n\tgenerate_input(i)\n\n####################################################################\n########################## Run Code ################################\n####################################################################\nsys.stdout.write(\"Running code.... \\r\")\nsys.stdout.flush()\n\nkeys = [\"e1_LF2\", \"e1_RK4\", \"e2_LF2\", \"e2_RK4\"]\nintegrators = {\"LF2\": \"Leapfrog\", \"RK4\": \"Runge-Kutta\"}\n\nfor k in keys:\n\trun_code(k)\n\nsubprocess.call(\"rm prob1*.txt\", shell=True)\nif len(sys.argv) == 2 and sys.argv[1] == \"-m\":\n\tsubprocess.call(\"make clean\", shell=True)\nos.chdir(\"..\")\n\n\n####################################################################\n######################### Make Plots ###############################\n####################################################################\n\nfor k in keys:\n\tplot_xy(k)\n\tplot_phase_energy(k)\n\n\n","sub_path":"runProb1.py","file_name":"runProb1.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"455943448","text":"\"\"\"\nFile: reverse.py\nProject 3.2\nDefines a function to reverse the elements in a list.\nComputational complexity:\n\"\"\"\n\ndef reverse(lyst):\n \"\"\"Reverses the elements in a list in linear time.\"\"\"\n # Use indexes to the first and last element\n # and move them toward each other.\n count = len(lyst)\n pos = count - 1\n\n for rep in range(0, count):\n if pos <= rep:\n break\n else:\n swap(lyst, lyst[rep], lyst[pos])\n pos -= 1\n\n\ndef swap(lyst, x, y):\n \"\"\"Exchanges the elements at positions x and y.\"\"\"\n temp = lyst[x]\n lyst[x] = lyst[y]\n lyst[y] = temp\n \ndef main():\n \"\"\"Tests with two lists.\"\"\"\n lyst = list(range(4))\n reverse(lyst)\n print(lyst)\n lyst = list(range(3))\n reverse(lyst)\n print(lyst)\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"ch_3_notes/ex_3_2/ex_3_2.py","file_name":"ex_3_2.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"94307801","text":"import sys\nimport urllib.request\nimport re\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.luoxia.com/santi/\"\n\ndef GetHtml(url):\n html = urllib.request.urlopen(url).read().decode('utf-8')\n return html\n\na = re.compile(r'santi/(.+?)\\.htm',re.M)\nContent = GetHtml(url)\nnumber = re.findall(a,Content)\n\nwith open(\"santi.txt\",'w',encoding='utf-8') as f:\n for i in number:\n new_url = url+i+\"/htm\"\n# print(new_url)\n try:\n soup = BeautifulSoup(GetHtml(new_url),\"lxml\")\n title = soup.find(class_=\"post-title\").string\n content = soup.find(id=\"nr1\").get_text()\n finally:\n f.write(title)\n f.write(content)\n f.write(\"\\n\\n\\n\")","sub_path":"爬虫/novel_santi.py","file_name":"novel_santi.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"577101545","text":"# Final Project - Nirav Ilango.py\r\n# Created on: 2016-11-28 12:10:46.00000\r\n# Description: This tool allows you to create an animation of changing demographics in Georgia public schools for the years between 2001 and 2015.\r\n# The tool allows you to select a file (ideally, the GA DOE joined shapefile generated for this tool), year range, and the demographic you would like to visualize.\r\n# For year range, omit the \"200\". For example, if you want a map with a range from 2002 to 2003, type in \"2\" for Start Year and \"3\" for End Year. If you want a map \r\n# with a range from 2010 to 2015, type in \"10\" for Start Year and \"15\" for End Year. For Demographic, type in \"Hispanic\", \"Asian\", \"American Indian\", \"Black\", \"White\",\r\n# or \"Multi\". For County, type in the name of the county that you would like to focus on, or leave the default value for \"State\" (for example, type in \"Fulton\"). \r\n# For Workspace, type in the folder for which you would like the final product to be exported to. For Map Document, add the map document that was included in the \r\n# final project folder named \"FinalProject1\".\r\n# ---------------------------------------------------------------------------\r\n\r\n# Import arcpy module\r\nimport arcpy\r\nimport sys\r\nimport os\r\n\r\n# Variables taken in as parameters:\r\nFile = arcpy.GetParameterAsText(0)\r\nLayer1 = arcpy.GetParameterAsText(1)\r\nindex1 = arcpy.GetParameterAsText(2)\r\nend1 = arcpy.GetParameterAsText(3)\r\ndem = arcpy.GetParameterAsText(4)\r\nCounty = arcpy.GetParameterAsText(5)\r\nWorkspace = arcpy.GetParameterAsText(6)\r\nMapDoc = arcpy.GetParameterAsText(7)\r\n\r\n# Workspace set to parameter\r\narcpy.env.workspace = Workspace\r\n\r\n# Checks inputted year range\r\nif (index1 < 1) and (index1 > 14) and (end1 < 2) and (end1 > 16):\r\n\tarcpy.AddError(\"Incorrect year range.\")\r\n\tsys.exit(0)\r\n\r\n#allows for proper indexing\r\nstartind = int(index1)+1\r\nendind = int(end1)+1\r\n\r\n# Hispanic\r\nif dem == \"Hispanic\":\r\n\tvalueF = \"HD_\" #prefix for created field name\r\n\tindex = int(index1) + 1 #for indexing\r\n\tend = int(end1) + 1\r\n\tstartindex = index\r\n\tif index < 10:\r\n\t\tfield1 = \"!Ethnic_H_\" + str(startindex-1) + \"!\"\r\n\telse:\r\n\t\tfield1 = \"!Ethnic__\" + str(startindex-1) + \"!\"\r\n\t\r\n\twhile index < end:\r\n\t\tif index < 10:\r\n\t\t\tfstring = \"HD_0\" + str(index)\r\n\t\t\tfield2 = \"!Ethnic_H_\" + str(index) + \"!\"\r\n\t\telse:\r\n\t\t\tfstring = \"HD_\" + str(index)\r\n\t\t\tfield2 = \"!Ethnic__\" + str(index) + \"!\"\r\n\r\n\t\t# Process: Add Field\r\n\t\tarcpy.AddField_management(File, fstring, \"FLOAT\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\r\n\t\t\r\n\t\t# Process: Calculate Field\r\n\t\tarcpy.CalculateField_management(File, fstring, fstring + \"( \" + field1 + \",\" + field2 + \")\", \"PYTHON_9.3\", \"def \" + fstring + \"(v1, v2):\\\\n\tv1 = float(v1)\\\\n\tv2 = float(v2)\\\\n\tif v1 == 0 or v2 == 0:\\\\n\t\treturn 0\\\\n\telse:\\\\n\t\treturn (v2-v1)/v1\")\r\n\t\t\r\n\t\tindex = index + 1\r\n\r\n# American Indian\r\nelif dem == \"American Indian\":\r\n\tvalueF = \"ND_\"\r\n\tindex = int(index1) + 1\r\n\tend = int(end1) + 1\r\n\tstartindex = index\r\n\tif index < 10:\r\n\t\tfield1 = \"!Race_Ame_\" + str(startindex-1) + \"!\"\r\n\telse:\r\n\t\tfield1 = \"!Race_Am_\" + str(startindex-1) + \"!\"\r\n\t\r\n\twhile index < end:\r\n\t\tif index < 10:\r\n\t\t\tfstring = \"ND_0\" + str(index)\r\n\t\t\tfield2 = \"!Race_Ame_\" + str(index) + \"!\"\r\n\t\telse:\r\n\t\t\tfstring = \"ND_\" + str(index)\r\n\t\t\tfield2 = \"!Race_Am_\" + str(index) + \"!\"\r\n\r\n\t\t# Process: Add Field\r\n\t\tarcpy.AddField_management(File, fstring, \"FLOAT\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\r\n\t\t\r\n\t\t# Process: Calculate Field\r\n\t\tarcpy.CalculateField_management(File, fstring, fstring + \"( \" + field1 + \",\" + field2 + \")\", \"PYTHON_9.3\", \"def \" + fstring + \"(v1, v2):\\\\n\tv1 = float(v1)\\\\n\tv2 = float(v2)\\\\n\tif v1 == 0 or v2 == 0:\\\\n\t\treturn 0\\\\n\telse:\\\\n\t\treturn (v2-v1)/v1\")\r\n\t\tindex = index + 1\r\n# Asian\r\nelif dem == \"Asian\":\r\n\tvalueF = \"AD_\"\r\n\tindex = int(index1) + 1\r\n\tend = int(end1) + 1\r\n\tstartindex = index\r\n\tif index < 10:\r\n\t\tfield1 = \"!Race_Asi_\" + str(startindex-1) + \"!\"\r\n\telse:\r\n\t\tfield1 = \"!Race_As_\" + str(startindex-1) + \"!\"\r\n\t\r\n\twhile index < end:\r\n\t\tif index < 10:\r\n\t\t\tfstring = \"AD_0\" + str(index)\r\n\t\t\tfield2 = \"!Race_Asi_\" + str(index) + \"!\"\r\n\t\telse:\r\n\t\t\tfstring = \"AD_\" + str(index)\r\n\t\t\tfield2 = \"!Race_As_\" + str(index) + \"!\"\r\n\r\n\t\t# Process: Add Field\r\n\t\tarcpy.AddField_management(File, fstring, \"FLOAT\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\r\n\t\t\r\n\t\t# Process: Calculate Field\r\n\t\tarcpy.CalculateField_management(File, fstring, fstring + \"( \" + field1 + \",\" + field2 + \")\", \"PYTHON_9.3\", \"def \" + fstring + \"(v1, v2):\\\\n\tv1 = float(v1)\\\\n\tv2 = float(v2)\\\\n\tif v1 == 0 or v2 == 0:\\\\n\t\treturn 0\\\\n\telse:\\\\n\t\treturn (v2-v1)/v1\")\r\n\t\tindex = index + 1\r\n# Black\r\nelif dem == \"Black\":\r\n\tvalueF = \"BD_\"\t\r\n\tindex = int(index1) + 1\r\n\tend = int(end1) + 1\r\n\tstartindex = index\r\n\tif index < 10:\r\n\t\tfield1 = \"!Race_Bla_\" + str(startindex-1) + \"!\"\r\n\telse:\r\n\t\tfield1 = \"!Race_Bl_\" + str(startindex-1) + \"!\"\r\n\t\r\n\twhile index < end:\r\n\t\tif index < 10:\r\n\t\t\tfstring = \"BD_0\" + str(index)\r\n\t\t\tfield2 = \"!Race_Bla_\" + str(index) + \"!\"\r\n\t\telse:\r\n\t\t\tfstring = \"BD_\" + str(index)\r\n\t\t\tfield2 = \"!Race_Bl_\" + str(index) + \"!\"\r\n\r\n\t\t# Process: Add Field\r\n\t\tarcpy.AddField_management(File, fstring, \"FLOAT\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\r\n\t\t\r\n\t\t# Process: Calculate Field\r\n\t\tarcpy.CalculateField_management(File, fstring, fstring + \"( \" + field1 + \",\" + field2 + \")\", \"PYTHON_9.3\", \"def \" + fstring + \"(v1, v2):\\\\n\tv1 = float(v1)\\\\n\tv2 = float(v2)\\\\n\tif v1 == 0 or v2 == 0:\\\\n\t\treturn 0\\\\n\telse:\\\\n\t\treturn (v2-v1)/v1\")\r\n\t\tindex = index + 1\r\n# White\r\nelif dem == \"White\":\r\n\tvalueF = \"WD_\"\r\n\tindex = int(index1) + 1\r\n\tend = int(end1) + 1\r\n\tstartindex = index\r\n\tif index < 10:\r\n\t\tfield1 = \"!Race_Whi_\" + str(startindex-1) + \"!\"\r\n\telse:\r\n\t\tfield1 = \"!Race_Wh_\" + str(startindex-1) + \"!\"\r\n\t\r\n\twhile index < end:\r\n\t\tif index < 10:\r\n\t\t\tfstring = \"WD_0\" + str(index)\r\n\t\t\tfield2 = \"!Race_Whi_\" + str(index) + \"!\"\r\n\t\telse:\r\n\t\t\tfstring = \"WD_\" + str(index)\r\n\t\t\tfield2 = \"!Race_Wh_\" + str(index) + \"!\"\r\n\r\n\t\t# Process: Add Field\r\n\t\tarcpy.AddField_management(File, fstring, \"FLOAT\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\r\n\t\t\r\n\t\t# Process: Calculate Field\r\n\t\tarcpy.CalculateField_management(File, fstring, fstring + \"( \" + field1 + \",\" + field2 + \")\", \"PYTHON_9.3\", \"def \" + fstring + \"(v1, v2):\\\\n\tv1 = float(v1)\\\\n\tv2 = float(v2)\\\\n\tif v1 == 0 or v2 == 0:\\\\n\t\treturn 0\\\\n\telse:\\\\n\t\treturn (v2-v1)/v1\")\r\n\t\tindex = index + 1\r\n# Two or more Races\r\nelif dem == \"Multi\":\r\n\tvalueF = \"MD_\"\r\n\tindex = int(index1) + 1\r\n\tend = int(end1) + 1\r\n\tstartindex = index\r\n\tif index < 10:\r\n\t\tfield1 = \"!Two_or_m_\" + str(startindex-1) + \"!\"\r\n\telse:\r\n\t\tfield1 = \"!Two_or__\" + str(startindex-1) + \"!\"\r\n\t\r\n\twhile index < end:\r\n\t\tif index < 10:\r\n\t\t\tfstring = \"MD_0\" + str(index)\r\n\t\t\tfield2 = \"!Two_or_m_\" + str(index) + \"!\"\r\n\t\telse:\r\n\t\t\tfstring = \"MD_\" + str(index)\r\n\t\t\tfield2 = \"!Two_or__\" + str(index) + \"!\"\r\n\r\n\t\t# Process: Add Field\r\n\t\tarcpy.AddField_management(File, fstring, \"FLOAT\", \"\", \"\", \"\", \"\", \"NULLABLE\", \"NON_REQUIRED\", \"\")\r\n\t\t\r\n\t\t# Process: Calculate Field\r\n\t\tarcpy.CalculateField_management(File, fstring, fstring + \"( \" + field1 + \",\" + field2 + \")\", \"PYTHON_9.3\", \"def \" + fstring + \"(v1, v2):\\\\n\tv1 = float(v1)\\\\n\tv2 = float(v2)\\\\n\tif v1 == 0 or v2 == 0:\\\\n\t\treturn 0\\\\n\telse:\\\\n\t\treturn (v2-v1)/v1\")\r\n\t\tindex = index + 1\r\nelse:\r\n\tarcpy.AddError(\"Incorrect demographic value.\")\r\n\tsys.exit(0)\r\n\r\n#adds map to document\r\nmxd = arcpy.mapping.MapDocument(MapDoc)\r\ndf = arcpy.mapping.ListDataFrames(mxd, \"*\")[0]\r\nlayerFile = arcpy.mapping.Layer(Layer1)\r\n\r\n#exports each jpg\r\nwhile startind < endind:\r\n\tnewlayer = arcpy.mapping.Layer(File)\r\n\tarcpy.mapping.AddLayer(df, newlayer, \"TOP\") \r\n\tupdatelayer = arcpy.mapping.ListLayers(mxd, \"\", df)[0]\r\n\tarcpy.SelectLayerByAttribute_management(updatelayer, \"NEW_SELECTION\", \" \\\"Name\\\" = '\" + County + \"'\")\r\n\tdf.zoomToSelectedFeatures() #zooms to given county\r\n\tarcpy.mapping.UpdateLayer(df, updatelayer, layerFile, True)\r\n\tif startind < 10:\r\n\t\tfstring = valueF + \"0\" + str(startind)\r\n\r\n\telse:\r\n\t\tfstring = valueF + str(startind)\r\n\r\n\tfor elm in arcpy.mapping.ListLayoutElements(mxd, \"TEXT_ELEMENT\"): #updates Title\r\n\t\tif startind < 10:\r\n\t\t\telm.text = dem + \" Demographic Data \" + \"200\" + str(startind)\r\n\t\telse:\r\n\t\t\telm.text = dem + \" Demographic Data \" + \"20\" + str(startind)\r\n\t\r\n\tupdatelayer.symbology.valueField = fstring #changes symbology\r\n\tarcpy.mapping.ExportToJPEG(mxd, os.path.join(Workspace, str(startind)), resolution = 300) #exports jpg to given workspace\r\n\tarcpy.RefreshActiveView()\r\n\tarcpy.RefreshTOC() #loads to screen\r\n\tstartind = startind + 1\r\n\r\n\r\n","sub_path":"Final Project - Nirav Ilango.py","file_name":"Final Project - Nirav Ilango.py","file_ext":"py","file_size_in_byte":8524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"16077580","text":"#!/usr/bin/env python\nfrom paraview.simple import *\n\n# create a new 'XML Image Data Reader'\ntimeTrackingvti = XMLImageDataReader(FileName=[\"timeTracking.vti\"])\ntimeTrackingvti.CellArrayStatus = []\n# select data arrays 000, 002, 004, ..., 118\ntimeTrackingvti.PointArrayStatus = [\"{:0>3}\".format(i) for i in range(0, 120, 2)]\n\n# create a new 'TTK TrackingFromFields'\ntTKTrackingFromFields1 = TTKTrackingFromFields(Input=timeTrackingvti)\ntTKTrackingFromFields1.ForceZtranslation = 1\ntTKTrackingFromFields1.ZTranslation = 0.125\n\n# create a new 'Extract Surface'\nextractSurface1 = ExtractSurface(Input=tTKTrackingFromFields1)\n\n# save the output\nSaveData(\"timeTracking.vtp\", extractSurface1)\n","sub_path":"python/timeTracking.py","file_name":"timeTracking.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"407740504","text":"from imports import *\n\ndef k_model(input_shape):\n \"\"\"\n keras cnn\n\n Params\n ----------------\n input shape: shape of input images\n \"\"\"\n\n X_input = Input(input_shape)\n\n X = Conv2D(30, (3,3), strides=(1,1), padding='same', name = 'Cov0')(X_input)\n X = Activation('relu')(X)\n\n X = Conv2D(30, (3,3), strides=(1,1), padding='same', name='Cov1')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((2,2), strides=(2,2), name='max_pool0')(X)\n\n X = Conv2D(60, (3,3), strides=(1,1), padding='same', name='Cov2')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((2,2), strides=(2,2), name='max_pool1')(X)\n\n X = Conv2D(120, (3,3), strides=(1,1), padding='same', name='Cov3')(X)\n X = Activation('relu')(X)\n X = MaxPooling2D((2,2), strides=(2,2), name='max_pool2')(X)\n\n X = Flatten()(X)\n X = Dense(1000, activation='relu', name='fc1')(X)\n X = Dense(10, activation='softmax', name='soft')(X)\n\n model = Model(inputs=X_input, output=X, name='keras basic cnn')\n\n return model\n\n\n\n","sub_path":"code/keras_model.py","file_name":"keras_model.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"229198333","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/ale/progr/github/wasp-general/wasp_general/version.py\n# Compiled at: 2018-01-17 05:18:06\n# Size of source mod 2**32: 1977 bytes\nimport os, json, subprocess\nwith open(os.path.join(os.path.dirname(__file__), 'package.json'), 'r') as (f):\n __package_data__ = json.load(f)\n\ndef package_version():\n result = __package_data__['numeric_version']\n if __package_data__['dev_suffix'] is True:\n try:\n cwd = os.getcwd()\n try:\n os.chdir(os.path.dirname(__file__))\n with open(os.devnull, 'w') as (f):\n output = subprocess.check_output(['git', 'rev-parse', 'HEAD'], stderr=f)\n if isinstance(output, bytes) is True:\n output = output.decode()\n result += '.dev%s' % output[:7]\n finally:\n os.chdir(cwd)\n\n except (subprocess.CalledProcessError, OSError):\n result += '--'\n\n return result\n\n\n__author__ = __package_data__['author']\n__email__ = __package_data__['author_email']\n__credits__ = __package_data__['credits']\n__license__ = __package_data__['license']\n__copyright__ = __package_data__['copyright']\n__status__ = __package_data__['status']\n__version__ = package_version()","sub_path":"pycfiles/wasp-general-0.0.3.3.tar/version.cpython-35.py","file_name":"version.cpython-35.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"97156682","text":"import tensorflow as tf\nimport numpy as np\nimport cv2\n\nreconstructed_images = []\ntfFile = 'C:/Users/xx665/OneDrive/Desktop/Python/Machine Learning/Luis/cnn/tensorflow Estimator/floor.tfrecords'\n\nrecord_iterator = tf.python_io.tf_record_iterator(path=tfFile)\n\nfor string_record in record_iterator:\n \n example = tf.train.Example()\n example.ParseFromString(string_record)\n \n height = int(example.features.feature['height']\n .int64_list\n .value[0])\n \n width = int(example.features.feature['width']\n .int64_list\n .value[0])\n \n img_string = (example.features.feature['image_raw']\n .bytes_list\n .value[0])\n \n annotation_string = (example.features.feature['mask_raw']\n .bytes_list\n .value[0])\n \n img_1d = np.fromstring(img_string, dtype=np.uint8)\n reconstructed_img = img_1d.reshape((height, width, -1))\n \n annotation_1d = np.fromstring(annotation_string, dtype=np.uint8)\n \n # Annotations don't have depth (3rd dimension)\n reconstructed_annotation = annotation_1d.reshape((height, width))\n \n reconstructed_images.append((reconstructed_img, reconstructed_annotation))\n \nprint(len(reconstructed_images))\ncv2.imshow('test', reconstructed_images[0][0])\ncv2.imshow('test_label', reconstructed_images[0][1])\ncv2.waitKey(0)","sub_path":"cnn/tensorflow Estimator/tfrecords use/load_tf.py","file_name":"load_tf.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"573575172","text":"from journal_re.journal_template import JournalTemplate\r\n\r\nclass Cell(JournalTemplate):\r\n \r\n search_mode = 1\r\n\r\n journal_name = 'Cell'\r\n journal_url = 'https://www.cell.com'\r\n latest_articles_url = '/cell/newarticles'\r\n sql_database_path = 'database/{}.sqlite'.format(journal_name)\r\n\r\n pat_article = r'
[\\s\\S]+?
'\r\n pat_title = r''\r\n pat_url = r'(.+?)'\r\n pat_publish_date = r'
.+?:(.+?)
'\r\n pat_authors = r'
  • (.+?)[,<]'\r\n pat_abstract = r'
    [^<]*
    ([\\s\\S]+?)
    '\r\n\r\n def format_date(self, date):\r\n \r\n [month, day, year] = date.split()\r\n day = day[:2]\r\n\r\n if month == 'January':\r\n month = '01'\r\n elif month == 'February':\r\n month = '02'\r\n elif month == 'March':\r\n month = '03'\r\n elif month == 'April':\r\n month = '04'\r\n elif month == 'May':\r\n month = '05'\r\n elif month == 'June':\r\n month = '06'\r\n elif month == 'July':\r\n month = '07'\r\n elif month == 'August':\r\n month = '08'\r\n elif month == 'September':\r\n month = '09'\r\n elif month == 'October':\r\n month = '10'\r\n elif month == 'November':\r\n month = '11'\r\n elif month == 'December':\r\n month = '12'\r\n\r\n return '{}-{}-{}'.format(year, month, day)\r\n\r\nclass CancerCell(Cell):\r\n\r\n journal_name = 'Cancer_Cell'\r\n latest_articles_url = \"/cancer-cell/newarticles\"\r\n sql_database_path = 'database/{}.sqlite'.format(journal_name)\r\n\r\nclass Immunity(Cell):\r\n journal_name = 'Immunity'\r\n latest_articles_url = \"/immunity/newarticles\"\r\n sql_database_path = 'database/{}.sqlite'.format(journal_name)","sub_path":"src/journal_re/cell_press.py","file_name":"cell_press.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"579747553","text":"\ndef correct_signs(s):\n numlst = []\n sign = [] \n res = []\n count = 0 \n if '<' in s and ('>' not in s): \n a = s.split('<')\n for num in a:\n numlst.append(int(num))\n for x in range(len(numlst)-1):\n if (numlst[x] < numlst[x+1]):\n count += 1 \n if count == len(numlst) -1: \n return True \n else:\n return False \n elif '>' in s and ('<' not in s):\n a = s.split('>')\n for num in a:\n numlst.append(int(num))\n for x in range(len(numlst)-1):\n if (numlst[x] > numlst[x+1]):\n count += 1 \n if count == len(numlst) -1: \n return True \n else:\n return False \n elif '>' in s and '<' in s:\n for x in s: \n if x.isdigit()==False and x != ' ': \n sign.append(x)\n a = s.split('>')\n for equation in a[0]:\n b = equation.split('<')\n for i in b:\n if i.isdigit(): \n i = int(i)\n numlst.append(i) \n for x in range(len(numlst)-1):\n if (numlst[x] < numlst[x+1]):\n count += 1 \n if count == len(numlst) -1: \n partial = True \n else:\n partial = False \n if partial == True: \n if (numlst[-1] > int(a[1])):\n return partial \n else: \n return False \n else:\n return False\n\n","sub_path":"eA94BuKYjwMoNQSE2_17.py","file_name":"eA94BuKYjwMoNQSE2_17.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"390571956","text":"import re\n\n'''\nIdentifiers:\n\\d = any number\n\\D = anything but a number\n\\s = space\n\\S = anything but a space\n\\w = any letter\n\\W = anything but a letter\n. = any character, except for a new line\n\\b = space around whole words\n\\. = period. must use backslash, because . normally means any character.\n\nModifiers:\n{1,3} = for digits, u expect 1-3 counts of digits, or \"places\"\n+ = match 1 or more\n? = match 0 or 1 repetitions.\n* = match 0 or MORE repetitions\n$ = matches at the end of string\n^ = matches start of a string (a moje she - not)\n| = matches either/or. Example x|y = will match either x or y\n[] = range, or \"variance\" [A-Z]\n{x} = expect to see this amount of the preceding code.\n{x,y} = expect to see this x-y amounts of the precedng code\n\nWhite Space Charts:\n\\n = new line\n\\s = space\n\\t = tab\n\\e = escape\n\\f = form feed\n\\r = carriage return\n\nCharacters to REMEMBER TO ESCAPE IF USED!\n. + * ? [ ] $ ^ ( ) { } | \\\n\nBrackets:\n[] = quant[ia]tative = will find either quantitative, or quantatative.\n[a-z] = return any lowercase letter a-z\n[1-5a-qA-Z] = return all numbers 1-5, lowercase letters a-q and uppercase A-Z\n\nEXAMPLES:\nquantitative\nquantatative\nquant[ia]tative\n\n[a-zA-Z] [1-9]\n\n'''\n\nexampleString = '''\nJessica is 15 years old, and Daniel is 27 years old.\nEdward is 97 years old, and his grandfather, Oscar, is 102.\n'''\n\nages = re.findall(r'\\d+', exampleString)\nnames = re.findall(r'[A-Z][a-z]*', exampleString)\n\nprint(ages)\nprint(names)\n\n\n'''\nEXAMPLE\n\nline = \"Cats are smarter than dogs\"\n\nmatchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)\n\nif matchObj:\n print \"matchObj.group() : \", matchObj.group()\n print \"matchObj.group(1) : \", matchObj.group(1)\n print \"matchObj.group(2) : \", matchObj.group(2)\nelse:\n print \"No match!!\"\n\n\nmatchObj.group() : Cats are smarter than dogs\nmatchObj.group(1) : Cats\nmatchObj.group(2) : smarter\n'''\n\n\n\n\n\n\n","sub_path":"6_Regular Expressions/6_main.py","file_name":"6_main.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"356644836","text":"#!/usr/bin/python\nimport sys\nimport csv\ninfile = sys.stdin\n#next(infile)\nvenue = ''\nfor line in infile:\n\tline = line.strip()\n\tmy_list = line.split(',') #splitting the line based on comma\n\tif(my_list[0] == 'info' and my_list[1] == 'venue'): #checking if line has info and if it does checking if that info is a venue about the match\n\t\tif(len(my_list)==4): #if length of that list is 4, there is something after the comma to be considered\n\t\t\tvenue = my_list[2]+','+my_list[3] #adding the appropriate fields\n\t\telse:\n\t\t\tvenue = my_list[2] #if there is nothing after the comma, just adding the venue\n\telif(my_list[0] == \"ball\"): #if the line contains info of ball bowled\n\t\tif(int(my_list[8]) != 0): #checking if extras are there\n\t\t\tcontinue\n\t\telse:\n\t\t\tkey_list = venue #setting key as venue\n\t\t\tval_list = my_list[4]+','+my_list[7] #setting value as batsman and runs scored by batsman\n\t\t\tprint('%s\\t%s' % (key_list,val_list))\t\n\t\t \n","sub_path":"adminmgr/media/code/python/map3/BD_058_217_267_1417_mapper.py","file_name":"BD_058_217_267_1417_mapper.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"103746021","text":"import socket\nimport sys\nimport struct\nfrom binascii import hexlify\nfrom threading import Thread\n\n# send a TCP DNS query to the upstream DNS server\ndef sendTCP(DNSserverIP, query):\n server = (DNSserverIP, 53)\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect(server)\n\n # convert the UDP DNS query to the TCP DNS query\n pay = chr(len(query))\n tcp_query = b'\\x00' + pay.encode() + query\n\n sock.send(tcp_query) \t\n data = sock.recv(1024)\n return data\n\n# a new thread to handle the UPD DNS request to TCP DNS request\ndef handler(data, addr, socket, DNSserverIP):\n TCPanswer = sendTCP(DNSserverIP, data)\n UDPanswer = TCPanswer[2:]\n socket.sendto(UDPanswer, addr)\n\n\nif __name__ == '__main__':\n DNSserverIP = sys.argv[1]\n port = int(sys.argv[2])\n host = ''\n try:\n # setup a UDP server to get the UDP DNS request\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind((host, port))\n \n while True:\n data, addr = sock.recvfrom(1024)\n th = Thread(target=handler, args=(data, addr, sock, DNSserverIP))\n th.start()\n except Exception as err:\n print(err)\n sock.close()\n","sub_path":"DNSProxyServer.py","file_name":"DNSProxyServer.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"120167395","text":"# Module 4C - Vehicle Mileage Factors with Gradient Boosted Tree Algorithm:\n\n# Implement and analyze decision tree regression with Spark ML\n# Reference: HW10, Q5\n\n# Reference: https://stackoverflow.com/questions/46956026/how-to-convert-column-with-string-type-to-int-form-in-pyspark-data-frame\nvehpub_sp = vehpub_sp.withColumn(\"ANNMILES\", vehpub_sp[\"ANNMILES\"].cast(IntegerType()))\nvehpub_sp = vehpub_sp.withColumn(\"DRVRCNT\", vehpub_sp[\"DRVRCNT\"].cast(IntegerType()))\nvehpub_sp = vehpub_sp.withColumn(\"HHFAMINC\", vehpub_sp[\"HHFAMINC\"].cast(IntegerType()))\nvehpub_sp = vehpub_sp.withColumn(\"HHSIZE\", vehpub_sp[\"HHSIZE\"].cast(IntegerType()))\nvehpub_sp = vehpub_sp.withColumn(\"HHVEHCNT\", vehpub_sp[\"HHVEHCNT\"].cast(IntegerType()))\nvehpub_sp = vehpub_sp.withColumn(\"URBAN\", vehpub_sp[\"URBAN\"].cast(IntegerType()))\nvehpub_sp = vehpub_sp.withColumn(\"URBANSIZE\", vehpub_sp[\"URBANSIZE\"].cast(IntegerType()))\n\n# Per slide 37 of lab 10 notes, prepare data for ML:\nvectorAssembler = VectorAssembler(inputCols=['DRVRCNT', 'HHFAMINC', 'HHSIZE', 'HHVEHCNT', 'URBAN', 'URBANSIZE'], outputCol='features')\n\n# Normalize each Vector using $L^1$ norm.\n# Reference: https://spark.apache.org/docs/latest/ml-features.html#normalizer\n# normalizer = Normalizer(inputCol=\"features\", outputCol=\"normFeatures\", p=1.0)\n# l1NormData = normalizer.transform(vehpub_sp)\n\nvvehpub_sp = vectorAssembler.transform(vehpub_sp)\nvvehpub_sp\n\n# Per slide 38 of lab 10 notes, split into train/test datasets:\nsplits = vvehpub_sp.randomSplit([0.7, 0.3])\ntrain = splits[0]\ntest = splits[1]\n\n# Per slide 47 of lab 10 notes, prepare data for ML:\ndt = GBTRegressor(featuresCol='features', labelCol='ANNMILES')\ndt_model = dt.fit(train)\n\n# Per slide 40 of lab 10 notes, describe summary:\n# print(\"DT Model Summary:\")\n# train.describe().show()\n\n# Per slide 47 of lab 10 notes, create output table:\ndt_predictions = dt_model.transform(test)\ndt_predictions.select(\"prediction\",\"DRVRCNT\",\"HHFAMINC\",\"HHSIZE\",\"HHVEHCNT\",\"URBAN\",\"URBANSIZE\",\"features\").show(10)\n\n# Per slide 47 of lab 10 notes, evaluate accuracy:\ndt_evaluator = RegressionEvaluator(labelCol=\"ANNMILES\", predictionCol=\"prediction\", metricName=\"rmse\")\nrmse = dt_evaluator.evaluate(dt_predictions)\nprint(\"Root Mean Squared Error (RMSE) on test data = %g\" % rmse)\nprint('')\n\n# Per slide 47 of lab 10 notes, evaluate accuracy:\ndt_evaluator = RegressionEvaluator(labelCol=\"ANNMILES\", predictionCol=\"prediction\", metricName=\"r2\")\nr2 = dt_evaluator.evaluate(dt_predictions)\nprint(\"R Squared (R2) on test data = %g\" % r2)\nprint('')\n\n# Print feature importance:\n# Reference: https://towardsdatascience.com/building-a-linear-regression-with-pyspark-and-mllib-d065c3ba246a\nprint('Feature Importance:')\nprint(gbt_model.featureImportances)\n\n# Plot bar chart for feature importance:\nfeature_importance = {\n 'feature': [0,1,2,3,4,5],\n 'score': [0.039418766457,0.419406388312,0.0504730968827,0.403731009982,0.0729282733944,0.0140424649711]\n}\nfeature_importance_plot = pd.DataFrame(\n feature_importance,\n columns = ['feature', 'score']\n)\n\n# Plot bar chart for feature importance:\n# Reference: https://chrisalbon.com/python/data_visualization/matplotlib_bar_plot/\nax = feature_importance_plot['score'].plot(\n kind='bar',\n title =\"Weighted Value\",\n figsize=(12, 6),\n legend=True,\n fontsize=12\n)\nx_labels = [\n 'Household Driver Count',\n 'Household Annual Income',\n 'Household Size (Count)',\n 'Household Vehicle Count',\n 'Urban Density (Cateogry)',\n 'Urban Density (Count)'\n]\nplt.title('Factors Influencing Miles Driven Annually - Feature Importance (Gradient Boosted Tree Algorithm)', fontsize=16)\nax.set_xlabel(\"Feature, Factors Influencing Miles Driven Annually\", fontsize=12)\nax.set_ylabel(\"Feature Importance Score (0=Low; 1=High)\", fontsize=12)\nax.set_xticklabels(x_labels)\nplt.show()\n","sub_path":"modules/04C_miles_subway_gbt.py","file_name":"04C_miles_subway_gbt.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"519193589","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 15 12:16:33 2019\n\n@author: Morrison-Lab\n\"\"\"\n#from mpl_toolkits import mplot3d\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef z_function(x, y):\n return np.sin(np.sqrt(x ** 2 + y ** 2))\n\nx = np.linspace(-6, 6, 30)\ny = np.linspace(-6, 6, 30)\n\nX, Y = np.meshgrid(x, y)\nZ = z_function(X, Y)\n\n#fig = plt.figure()\n#ax = plt.axes(projection=\"3d\")\n#ax.plot_wireframe(X, Y, Z, color='green')\n#ax.set_xlabel('x')\n#ax.set_ylabel('y')\n#ax.set_zlabel('z')\n\n#plt.show()\n\n\nnoofangles = 12\nX1 = np.zeros((noofangles,399))\nY1 = np.zeros((noofangles,399))\nZ1 = np.zeros((noofangles,399))\n\ninput_angles = np.arange(0, 181, 180/noofangles)\n\nangle = np.arange(-89.55, 90, 0.45) \nanglex = angle\nfor difAngle in range (0, noofangles+1):\n Z1[difAngle] = np.cos(np.deg2rad(angle))\n X1[difAngle] = angle*np.cos(np.deg2rad(input_angles[difAngle]))\n Y1[difAngle] = angle*np.sin(np.deg2rad(input_angles[difAngle]))\n\nfig = plt.figure()\nax = plt.axes(projection=\"3d\")\nax.plot_wireframe(X1, Y1, Z1, color='red')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\n\n","sub_path":"Cosine Response/3d-graph-example.py","file_name":"3d-graph-example.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"271330312","text":"import Proweb.Commands.Commands as Commands\nimport Proweb.Commands.Elements as Elements\nimport Proweb.Commands.Snippets as Snippets\nimport Proweb.Commands.Process as Process\nimport Proweb.Commands.Tasks as Tasks\nimport Proweb.Commands.Libs as Libs\nimport Proweb.Exceptions as Ex\nimport Proweb.Output as Output\nimport Proweb.Tools as Tools\nimport Proweb.Input as Input\nimport Proweb.Order as Order\nimport Proweb.Conf as C\n\nimport threading\nimport pathlib\nimport shutil\nimport json\nimport time\nimport glob\nimport sys\nimport re\nimport os\n\n\n\nclass Main(Commands.Commands):\n\tdef __init__(self):\n\t\tself.snippets = Snippets.Snippets();\n\t\tself.elements = Elements.Elements();\n\t\tself.checkDir();\n\n\t\n\tdef cmd_echo(self, args):\n\t\t\"\"\"Repeats the input\"\"\"\n\t\tprint(args[0])\n\n\n\tdef cmd_echo(self, c, t):\n\t\t\"\"\"Repeats the input with color\"\"\"\n\t\tOutput.ColorPrint(c, t)\n\n\t\n\tdef cmd_exit(self, *args):\n\t\t\"\"\"Exits the program\"\"\"\n\t\treturn True;\n\n\t\n\tdef cmd_show(self, *args):\n\t\t\"\"\"Shows hirachical tree of current dir\"\"\"\n\t\tif len(args) == 1:\n\t\t\tOrder.tree(C.DIR, int(args[0]));\n\t\telse:\n\t\t\tOrder.tree(C.DIR);\n\n\n\tdef cmd_cd(self, *args):\n\t\t\"\"\"Changes directory\"\"\"\n\t\ttemp = (C.DIR / args[0]).resolve();\n\t\tif not temp.is_relative_to(C.ROOT):\n\t\t\tprint(\"No puedes subir mas!\");\n\t\t\treturn \n\t\tC.DIR = temp;\n\t\tself.checkDir();\n\t\n\n\tdef cmd_pwd(self):\n\t\t\"\"\"Shows current path\"\"\"\n\t\tprint(C.DIR);\n\n\n\tdef cmd_mkdir(self, *args):\n\t\t\"\"\"Creates new dir\"\"\"\n\t\targs = C.DIR / args[0]\n\t\tTools.mkdir(args);\n\n\n\tdef cmd_mkfile(self, *args):\n\t\t\"\"\"Creates new file\"\"\"\n\n\t\tif len(args) > 1:\n\t\t\tTools.mkfile(args[0], args[1]);\n\t\t\treturn\n\t\tTools.mkfile(args[0]);\n\n\n\tdef cmd_rm(self, *args):\n\t\t\"\"\"Removes file/dir\"\"\"\n\t\tTools.rm(C.DIR / args[0]);\n\n\n\tdef cmd_cp(self, *args):\n\t\t\"\"\"Copies file/dir\"\"\"\n\t\tTools.cp(args[0], args[1]);\n\n\n\tdef cmd_mv(self, *args):\n\t\t\"\"\"Moves file/dir\"\"\"\n\t\tTools.mv(args[0], args[1]);\n\n\n\tdef cmd_read(self, *args):\n\t\t\"\"\"Reads file\"\"\"\n\t\tprint(Tools.read(args[0]));\n\n\n\tdef cmd_init(self, *args):\n\t\tif not Tools.exists(C.DIR / \"proweb.json\"):\n\t\t\tprops = {};\n\t\t\tprops[\"name\"] = input(\"Name: \");\n\t\t\tprops[\"elements\"] = \"./IN/ELEMENTS/\";\n\t\t\tsnips = input(\"Snippets [E]mpty [D]efault:\");\n\t\t\tif snips == \"E\":\n\t\t\t\tprops[\"snippets\"] = {};\n\t\t\telif snips == \"D\":\n\t\t\t\tprops[\"snippets\"] = {\n\t\t\t\t\t\"GET\":\"document.querySelector\",\n \t\t\t\t\"GETALL\":\"document.querySelectorAll\",\n \t\t\t\t\"NEW\":\"document.createElement\",\n \t\t\t\t\"CHILD\":\"appendChild\",\n \t\t\t\t\"EVENT\":\"addEventListener\"\n \t\t\t}\n\t\t\telse:\n\t\t\t\tprint(\"No project was created\");\n\t\t\t\treturn\n\n\t\t\tTools.writeJson(C.DIR / \"proweb.json\", props);\n\t\t\tTools.mkdir(C.DIR / \"IN\");\n\t\t\tTools.mkdir(C.DIR / \"IN\" / \"CSS\");\n\t\t\tTools.mkdir(C.DIR / \"IN\" / \"JS\");\n\t\t\tTools.mkdir(C.DIR / \"IN\" / \"ELEMENTS\");\n\t\t\tTools.mkfile(C.DIR / \"index.html\");\n\t\telse:\n\t\t\tprint(\"there is another project in this folder\");\n\n\tdef cmd_process(self, *args):\n\t\t\"\"\"Process Web\"\"\"\n\t\tProcess.call(C.DIR);\n\n\n\tdef cmd_tasks(self, *args):\n\t\t\"\"\"Task commands\"\"\"\n\t\tTasks.command(args);\n\n\n\tdef cmd_libs(self, *args):\n\t\t\"\"\"Libs commands\"\"\"\n\t\tLibs.command(args, Main.DIR);\n\n\n\tdef cmd_elements(self, *args):\n\t\t\"\"\"Elements commands\"\"\"\n\t\tself.elements.call(*args);\n\n\n\tdef cmd_project(self, *args):\n\t\t\"\"\"Project commands\"\"\"\n\t\tProject.command(args, Main.DIR);\n\n\n\tdef cmd_snippet(self, *args):\n\t\t\"\"\"Snippets commands\"\"\"\n\t\tself.snippets.call(*args);\n\n\n\tdef checkDir(self):\n\t\tif Tools.exists(C.DIR / \"proweb.json\"):\n\t\t\ttxt = Tools.readJson(C.DIR / \"proweb.json\");\n\t\t\tC.P_NAME = f\" [Pro-{txt['name']}]\";\n\t\t\tC.P_FILE = C.DIR / \"proweb.json\";\n\t\t\tC.P_PATH = C.DIR;\n\n\t\telif Tools.exists(C.DIR / \"lib.json\"):\n\t\t\ttxt = Tools.read(C.DIR / \"lib.json\");\n\t\t\tdata = json.loads(txt);\n\t\t\tC.P_NAME = f\" [Lib-{data['name']}\";\n\t\t\tC.P_FILE = C.DIR / \"lib.json\";\n\t\t\tC.P_PATH = C.DIR;\n\t\t\n\t\telse:\n\t\t\tC.P_NAME = \"\";\n\t\t\tC.P_FILE = pathlib.Path();\n\t\t\tC.P_PATH = pathlib.Path();\n\n\n\ndef Run():\n\tglobal exit, main\n\twhile not exit.is_set():\n\t\ttry:\n\t\t\tTasks.process(main.call);\n\t\t\texit.wait(10);\n\t\texcept KeyboardInterrupt:\t\n\t\t\tpass\n\tprint(\"\\nbye...\");\n\n\nmain = Main();\nexit = threading.Event()\ninputThread = Input.Input(exit, main.call);\n\nRun();","sub_path":"v2/proweb.py","file_name":"proweb.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"294818675","text":"from copy import deepcopy\nfrom collections import defaultdict\nfrom pprint import pprint\n\nfrom flask import Blueprint, jsonify, request\nfrom flask_jwt_extended import jwt_required, get_jwt_claims, current_user\n\nfrom app.adresses.models import Address\nfrom app.adresses.utils import check_existing_address_delivery\nfrom app.orders.models import Order, OrderItem\nfrom app.factory import db, jwt\nfrom sqlalchemy import desc, text\n\nfrom app.orders.serializer import OrderListSerializer\nfrom app.orders.serializer import check_product_availability, show_order_detail_by_role\nfrom app.products.models import Product\nfrom app.shared import security\nfrom app.shared.decorators import has_role\nfrom app.shared.serializers import get_error_response, get_success_response\nfrom app.authentication.models import User\n\norder = Blueprint('orders', __name__, url_prefix='/orders')\n\n\n# client order operation\n@order.route('/client-orders', methods=['GET'])\n@jwt_required\n@has_role('ROLE_USER')\ndef get_all_client_orders():\n claims_data = get_jwt_claims()\n user_id = claims_data.get('user_id')\n\n if not user_id:\n return get_error_response('UNAUTHORIZED', 401)\n\n orders = Order.query.filter_by(user_id=user_id).order_by(desc(Order.created_at)).paginate()\n return jsonify(OrderListSerializer(orders).get_data()), 200\n\n\n@order.route('/user-orders/', methods=['GET'])\n@jwt_required\ndef get_order_details(order_id):\n user = current_user\n\n single_order = Order.query.filter(Order.id == order_id).first()\n\n if single_order is None:\n return get_error_response('ERROR ORDER DOES NOT EXIST IN DATABASE', 400)\n\n return show_order_detail_by_role(user, single_order)\n\n\n@order.route('/client-orders/create-order', methods=['POST'])\n@jwt_required\n@has_role('ROLE_USER')\ndef create_order():\n user = current_user # demander a yoa si ce n'est pas dangereux de recuperer tous l'utilisateur\n # print(user.id)\n # print(request.get_json())\n address_id = request.json.get('address_id', None)\n # print(address_id)\n import faker\n fake = faker.Faker()\n if address_id is None:\n if check_existing_address_delivery(user.id) is None:\n return get_error_response('you address is required for delivery', 400)\n address_id = check_existing_address_delivery(user.id)\n\n check_address = Address.query.filter(Address.user_id == user.id).filter(Address.id == address_id).first()\n # print(check_address)\n if check_address is None:\n return get_error_response('unauthorized address', 401)\n\n cart_items = request.json.get('cart_items', None)\n print(len(cart_items))\n # print(cart_items)\n if not cart_items:\n return get_error_response('YOU CAN\\'T SUBMIT AN ORDER WITH NO ITEM', 400)\n\n delivery_mode = request.json.get('delivery_mode', 0)\n paiement_method = request.json.get('paiement_method', 0)\n product_ids = [ci['product_id'] for ci in cart_items]\n products_ordered = Product.query.filter(Product.id.in_(product_ids)).all()\n print(len(products_ordered))\n checking_avl = check_product_availability(products_ordered) # voir si c'est pas mieux dans un middleware\n\n if type(checking_avl) == dict:\n return jsonify({'message': checking_avl['message'], 'product_ids': checking_avl['product_ids']})\n\n if len(products_ordered) != len(cart_items):\n return get_error_response('make sure that all product you want to order is available', 400)\n\n final_products = list(map(lambda x: {\"prdt\": x, \"quantity\": list(filter(lambda y: y[\"product_id\"] == x.id,\n cart_items))[0][\"quantity\"],\n \"seller_id\": x.seller_id}, products_ordered))\n f = defaultdict(list)\n for v in final_products:\n f[v[\"seller_id\"]].append(v)\n\n test_tuple = (\"seller_id\", \"products\")\n result = [{test_tuple[i]: fitem[i] for i, _ in enumerate(fitem)} for fitem in f.items()]\n pprint(result)\n all_orders = []\n for order_from_client in result:\n new_order = Order(order_status=5,\n tracking_number=fake.uuid4(),\n address_id=address_id,\n delivery_mode=delivery_mode,\n user_id=user.id,\n seller_id=order_from_client['seller_id'],\n paiement_method=paiement_method)\n all_orders.append(new_order)\n\n print(all_orders)\n\n for index, s_order in enumerate(all_orders):\n for order_item in result[index]['products']:\n s_order.order_items.append(OrderItem(price=order_item['prdt'].price,\n quantity=order_item['quantity'],\n product_id=order_item['prdt'].id,\n product=order_item['prdt'],\n name=order_item['prdt'].name))\n\n for o in all_orders:\n o.get_total_amount()\n for item in o.order_items:\n item.slug_generator_for_item(prdt_name=item.name, username=user.username)\n\n db.session.add_all(all_orders)\n db.session.commit()\n n_orders = Order.query.filter(Order.tracking_number.in_([o.tracking_number for o in all_orders])).all()\n print(n_orders)\n return get_success_response('Order created successfully', data=[o.get_summary() for o in n_orders], status_code=201)\n\n\n# seller order operation\n@order.route('/seller-orders', methods=['GET'])\n@jwt_required\n@has_role('ROLE_SELLER')\ndef get_all_orders_of_seller_concerned_with():\n user = current_user\n\n seller_orders = Order.query.order_by(desc(Order.created_at)).filter(Order.seller_id == user.id).paginate()\n\n return jsonify(OrderListSerializer(seller_orders).get_data()), 200\n\n\n@order.route('/edit-order/', methods=['PUT'])\n@jwt_required\n@has_role('ROLE_USER')\ndef edit_order(tracking_number):\n user = current_user\n order_to_edit = Order.query.filter(Order.tracking_number == tracking_number).first()\n print(order_to_edit)\n\n if not order_to_edit:\n return get_error_response('not found', 404)\n\n if order_to_edit.user_id != user.id: # demander a yoa si ce n'est pas mieux de coupler avec la requet precedente\n return get_error_response('unauthorized, this not belong to you', 401)\n\n if order_to_edit.order_status == 1 or order_to_edit.order_status == 2 or order_to_edit.order_status == 3 or order_to_edit.order_status == 4: # demander a yoa une facon plus professionell de faire\n return get_error_response('you can not edit this order because it is already delivered or in transit either '\n 'canceled', 401)\n order_items_to_edit = request.json.get('order_item', None)\n\n if not order_items_to_edit or len(order_items_to_edit) == 0:\n return get_error_response('you can not submit no editing data', 400)\n\n for item in order_items_to_edit:\n\n if not item['is_deleting']:\n try:\n if not item['quantity']:\n return get_error_response('you must supply a quantity to edit item', 400)\n except KeyError:\n return get_error_response('you must supply a quantity to edit item', 400)\n try:\n order_item_to_edit = OrderItem.query.filter(OrderItem.slug == item['slug']).filter(\n OrderItem.order_id == order_to_edit.id).first()\n\n order_item_to_edit.quantity = item['quantity']\n db.session.commit()\n print('editing ok', item['slug'])\n except Exception as e:\n print(e)\n return get_error_response('server error' + str(e))\n if item['is_deleting']:\n try:\n order_item_to_delele = OrderItem.query.filter(OrderItem.slug == item['slug']).filter(\n OrderItem.order_id == order_to_edit.id).first()\n db.session.delete(order_item_to_delele)\n db.session.commit()\n print('deleting ok', item['slug'])\n except Exception as e:\n print(e)\n return get_error_response('server error' + str(e))\n\n order_to_edit.get_total_amount()\n db.session.commit()\n\n return get_success_response('operation did successfully', 200)\n\n\n@order.route('/cancel-order/', methods=['DELETE'])\n@jwt_required\n@has_role('ROLE_USER')\ndef cancel_specific_order(tracking_number):\n user = current_user\n order_to_cancel = Order.query.filter(Order.tracking_number == tracking_number).first()\n\n if not order_to_cancel:\n return get_error_response('not found', 404)\n\n if order_to_cancel.user_id != user.id:\n return get_error_response('unauthorized, this not belong to you', 401)\n\n if order_to_cancel.order_status == 1 or order_to_cancel.order_status == 2 or order_to_cancel.order_status == 3 or order_to_cancel.order_status == 4: # demander a yoa une facon plus professionell de faire\n return get_error_response('you can not edit this order because it is already delivered or in transit either '\n 'canceled', 401)\n\n order_to_cancel.order_status = 4\n db.session.commit()\n\n return get_success_response('order was canceled', 200)\n\n\n@order.route('/processing-orders', methods=['PUT'])\n@jwt_required\n@has_role('ROLE_SELLER')\ndef process_order():\n pass\n","sub_path":"app/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"235804428","text":"import os\nimport numpy as np\nfrom tqdm import tqdm\n\ndef load(data_path='data/preprocessed'):\n \"\"\"\n loads the preprocessed files in '.npy' format and returns a 3-element tuple,\n\n ((train_data, train_label), (validation_data, validation_label), (test_data, test_label))\n\n where each data matrix is N-by-16000, and each label matrix is of size N.\n \"\"\"\n\n result = []\n last_files = None\n\n for split in ['train', 'validation', 'test']:\n path = os.path.join(data_path, split)\n files = [f for f in os.listdir(path) if f.endswith('.npy')]\n files.sort()\n\n if last_files is not None and not [x == y for x, y in zip(last_files, files)]:\n raise Exception(\"split %s has a different set of data files\" % split)\n\n matrices = []\n labels = []\n\n # label ranges betwen [0-30], where 0 is _background_noise_\n for i in tqdm(range(len(files)), desc='Loading %s files' % split):\n matrix = np.load(os.path.join(path, files[i]))\n label = np.zeros((matrix.shape[0], len(files)))\n label[:, i] = 1\n\n matrices.append(matrix)\n labels.append(label)\n\n result.append((np.vstack(matrices), np.vstack(labels)))\n\n return tuple(result)\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"521999524","text":"import os\nimport argparse\nimport datetime\nimport pandas\nimport collections\nfrom dotenv import load_dotenv\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\n\nYEAR_OF_FOUNDATION = 1920\n\n\ndef get_age():\n current_date = datetime.datetime.now()\n return current_date.year - YEAR_OF_FOUNDATION\n\n\ndef get_wines_by_category(file):\n excel_data_df = pandas.read_excel(file, na_values=' ', keep_default_na=False)\n wines = excel_data_df.to_dict(orient='record')\n\n wines_by_category = collections.defaultdict(list)\n\n for wine in wines:\n wines_by_category[wine[u'Категория']].append(wine)\n\n return wines_by_category\n\n\ndef create_parser():\n parser = argparse.ArgumentParser(description='Параметры запуска скрипта')\n parser.add_argument('-f', '--file', default='wine.xlsx', help='Файл excel с информацией для публикации на сайте')\n parser.add_argument('-t', '--template', default='template.html', help='Шаблон html')\n return parser\n\n\ndef main():\n\n load_dotenv()\n parser = create_parser()\n args = parser.parse_args()\n server_ip = os.getenv('SERVER_IP')\n server_port = int(os.getenv('SERVER_PORT'))\n env = Environment(\n loader=FileSystemLoader('.'),\n autoescape=select_autoescape(['html', 'xml'])\n )\n\n try:\n template = env.get_template(args.template)\n\n rendered_page = template.render(\n categories=get_wines_by_category(args.file).items(),\n age=get_age()\n )\n\n except (ValueError, TypeError, KeyError) as error:\n print('%s' % error)\n\n else:\n with open('index.html', 'w', encoding=\"utf8\") as file:\n file.write(rendered_page)\n\n server = HTTPServer((server_ip, server_port), SimpleHTTPRequestHandler)\n server.serve_forever()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"371120737","text":"\nfrom typing import List\n\n\nclass Solution:\n\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n INF = len(arr) + 1\n # the ith index represents the smallest length subarray we've found ending <= i that sums to target\n best_at_i = [INF]*len(arr)\n best = INF # output\n curr_sum = 0 # current sum between left and right\n\n left = 0\n for right in range(len(arr)):\n # update the running sum\n curr_sum += arr[right]\n\n # arr is strictly positive, so shrink window until we're not above target\n while curr_sum > target and left <= right:\n curr_sum -= arr[left]\n left += 1\n\n if curr_sum == target:\n # we have a new shortest candidate to consider\n best = min(best, best_at_i[left-1] + right - left + 1)\n best_at_i[right] = min(best_at_i[right-1], right - left + 1)\n else:\n # best we've seen is the previous best (overlaps to end if right == 0)\n best_at_i[right] = best_at_i[right-1]\n\n if best == INF:\n return -1\n return best\n\n\ns = Solution()\nprint(s.minSumOfLengths([3,2,2,4,3], 3))\nprint(s.minSumOfLengths([1, 2, 1, 3, 1], 4))\n","sub_path":"go/dp/1477/1477.py","file_name":"1477.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"211698396","text":"class Alumno():\n def __init__(self,nombre,edad,sexo):\n self.nombre=nombre\n self.edad=int(edad)\n self.sexo=sexo\n\nclass Universidad(Alumno):\n def __init__(self,Alumno,uni):\n super().__init__(Alumno.nombre,Alumno.edad,Alumno.sexo)\n self.nombreUni=uni\n def getDatos(self):\n dicc={\"Nombre\": self.nombre,\"Edad\":self.edad,\"Sexo\": self.sexo,\"Universidad\": self.nombreUni}\n return dicc\n\nlista=[]\nnum=0\n\na=input(\"Ingrese su nombre: \")\nb=int(input(\"Ingrese su edad: \"))\nc=input(\"Ingrese su sexo: \")\nd=input(\"Nombre de su universidad: \")\n\nx=Alumno(a,b,c)\ny=Universidad(x,d)\n\nfor i in range(5):\n lista.append(y)\n\nfor j in lista:\n #print(j.getDatos())\n print(\"---------------\")\n for k,v in j.getDatos().items():\n print(str(k)+\" : \",v)","sub_path":"Python 1/Lesson 2 - 3/Herencia - Condicionales - Loop.py","file_name":"Herencia - Condicionales - Loop.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"70065301","text":"# -*-coding: utf-8 -*-\n# Python 3.6\n# Author:Zhang Haitao\n# Email:13163385579@163.com\n# TIME:2018-09-15 19:36\n# NAME:FT_hp-6 fama_macbeth.py\n\nfrom collections import OrderedDict\nimport statsmodels.formula.api as sm\n\nfrom data.dataApi import get_filtered_ret\nfrom empirical.config_ep import DIR_DM, DIR_CHORDIA, DIR_DM_NORMALIZED, \\\n PERIOD_THRESH, DIR_BASEDATA\nimport os\nimport pandas as pd\nfrom empirical.data_mining.dm_api import get_playing_indicators\nfrom tools import multi_process\n\n\n\ndef famaMacBeth(formula, time_label, df, lags=5):\n res = df.groupby(time_label,sort=True).apply(lambda x: sm.ols(\n formula, data=x).fit())\n p=pd.DataFrame([x.params for x in res],index=res.index)\n means = {}\n for x in p.columns:\n if lags is 0:\n means[x] = sm.ols(formula=x + ' ~ 1',\n data=p[[x]]).fit(use_t=True)\n else:\n means[x] = sm.ols(formula=x + ' ~ 1',\n data=p[[x]]).fit(cov_type='HAC',\n cov_kwds={'maxlags': lags},\n use_t=True)\n result=pd.DataFrame([\n [means[x].params['Intercept'],means[x].bse['Intercept'],\n means[x].tvalues['Intercept'],means[x].pvalues['Intercept']]\n for x in p.columns\n ],index=p.columns,columns=['coef','stderr','tvalue','pvalue'])\n result['stars']=result['pvalue'].map(lambda x:'***' if x<0.01 else ('**' if x<0.05 else ('*' if x<0.1 else '')))\n return result\n\nCONTROL=['log_size','bm','mom','op','inv','roe']\n\ndef _get_other_data():\n #controlling variables,copy from E:\\haitong_new\\raw_data\n path=os.path.join(DIR_DM,'other.pkl')\n if os.path.exists(path):\n return pd.read_pickle(path)\n else:\n ss = []\n for ct in CONTROL:\n # s = pd.read_pickle(\n # r'G:\\FT_Users\\HTZhang\\haitong\\standardized\\{}.pkl'.format(\n # ct)).stack()\n s=pd.read_pickle(os.path.join(DIR_BASEDATA,'normalized_controlling',ct+'.pkl'))\n # s.name = ct\n ss.append(s)\n\n other = pd.concat(ss, axis=1, join='inner').groupby('stkcd').shift(1) #trick: use the indicator of time t-1\n other = other.dropna(how='all')\n other=other.groupby('month_end').filter(lambda s:len(s)>300)#trick: at least 300 stocks in each month\n ret=get_filtered_ret().swaplevel()\n other=pd.concat([other,ret],axis=1).dropna()\n other=other.fillna(0)\n other.to_pickle(path)\n return other\n\n_convert_name=lambda s:s[1:].replace('_','').replace('-','')\n\ncontrol_map=OrderedDict({\n 'capmM':[],\n 'ff3M':['log_size','bm'],\n 'ffcM':['log_size','bm','mom'],\n 'ff5M':['log_size','bm','op','inv'],\n 'ff6M':['log_size','bm','op','inv','mom'],\n 'hxz4M':['log_size','bm','inv','roe']\n})\n\nother=_get_other_data()\n\ndef _get_fmt(name):\n '''\n get tvalue of the alpha in fama macbeth regression\n Args:\n name:str,indicator name\n\n Returns:\n\n '''\n signal = pd.read_pickle(\n os.path.join(DIR_DM_NORMALIZED, name + '.pkl')).shift(1).stack()#trick:use the indicator of time t-1\n newname = _convert_name(name)\n signal.name = newname\n comb = pd.concat([other, signal], axis=1)\n comb = comb.dropna()\n comb=comb.groupby('month_end').filter(lambda df:len(df)>300) #trick: at least 300 stocks in each month\n if len(set(comb.index.get_level_values('month_end')))>PERIOD_THRESH:#trick: at least 60 periods\n ts=[]\n for mn in control_map:\n if len(control_map[mn])>0:\n formula=f'ret_m ~ {newname}' + ' + ' + ' + '.join(control_map[mn])\n else:\n formula=f'ret_m ~ {newname}'\n\n # formula = f'ret_m ~ {newname} + amihud + bp + cumRet + log_size + turnover + ivol'\n tvalue = famaMacBeth(formula, 'month_end', comb).at[newname,'tvalue']\n ts.append(tvalue)\n # print(mn)\n ts=pd.Series(ts,index=control_map.keys())\n ts.name=name\n ts.to_pickle(os.path.join(DIR_CHORDIA,'fm',name+'.pkl'))\n print(name)\n\n\ndef calculate_fmt():\n names=get_playing_indicators()\n # fns=os.listdir(os.path.join(DIR_DM_NORMALIZED))\n # names=[fn[:-4] for fn in fns]\n print('total',len(names))\n checked=[fn[:-4] for fn in os.listdir(os.path.join(DIR_CHORDIA,'fm'))]\n names=[n for n in names if n not in checked]#fixme:\n print('remainder',len(names))\n\n multi_process(_get_fmt, names, 20) #fixme:\n\n # for name in names:\n # _get_fmt(name)\n\n\ndef _get_t(fn):\n return pd.read_pickle(os.path.join(DIR_CHORDIA,'fm',fn))\n\ndef get_fmt():\n # _get_tvalue=lambda x:pd.read_pickle(os.path.join(DIR_CHORDIA,'fm',x)).at[_convert_name(x[:-4]),'tvalue']\n fns=os.listdir(os.path.join(DIR_CHORDIA,'fm'))\n df=pd.concat(multi_process(_get_t,fns),axis=1).T\n df.to_pickle(os.path.join(DIR_CHORDIA,'fmt.pkl'))\n\ndef analyze_fmt():\n df=pd.read_pickle(os.path.join(DIR_CHORDIA,'fmt.pkl'))\n df[abs(df)>3].notnull().sum(axis=1)\n\n\ndef main():\n calculate_fmt()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"empirical/data_mining/6 fama_macbeth.py","file_name":"6 fama_macbeth.py","file_ext":"py","file_size_in_byte":5091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"524043747","text":"# -*- coding:utf-8 -*-\n# Copyright (c) 2015, Galaxy Authors. All Rights Reserved\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\nimport datetime\nfrom ftrace import sdk\nfrom galaxy import log_pb2\nfrom galaxy import master_pb2\nfrom galaxy import galaxy_pb2\nfrom galaxy import agent_pb2\nfrom common import pb2dict\nfrom common import util\nimport logging\nlogger = logging.getLogger(\"console\")\n\nclass TraceDao(object):\n\n def __init__(self, trace_se):\n self.ftrace = sdk.FtraceSDK(trace_se)\n\n def get_job_event(self, jobid, \n start_time, \n end_time,\n limit=100):\n data_list, status = self.ftrace.simple_query(\"baidu.galaxy\", \n \"JobEvent\",\n jobid,\n int(start_time * 1000000),\n int(end_time * 1000000),\n limit = limit)\n if not status:\n logger.error(\"fail to query job stat\")\n return [], False\n events = []\n job_event = log_pb2.JobEvent()\n job_desc = master_pb2.JobDescriptor()\n for data in data_list:\n for d in data.data_list:\n job_event.ParseFromString(d)\n job_desc.ParseFromString(job_event.desc)\n data = pb2dict.protobuf_to_dict(job_event)\n data[\"desc\"] = pb2dict.protobuf_to_dict(job_desc)\n data[\"state\"] = master_pb2.JobState.Name(data[\"state\"])\n data[\"level\"] = log_pb2.TraceLevel.Name(job_event.level)\n data[\"update_state\"] = master_pb2.JobUpdateState.Name(data[\"update_state\"])\n data[\"time\"] = datetime.datetime.fromtimestamp(data[\"time\"]/1000000).strftime(\"%Y-%m-%d %H:%M:%S\") \n events.append(data)\n logger.info(\"query job %s event from %s to %s , count %d\"%(jobid,\n datetime.datetime.fromtimestamp(start_time).strftime(\"%Y-%m-%d %H:%M:%S\"),\n datetime.datetime.fromtimestamp(end_time).strftime(\"%Y-%m-%d %H:%M:%S\"),\n len(events)))\n return events, True\n\n def get_job_stat(self, jobid, start_time, end_time, limit = 100):\n data_list, status = self.ftrace.simple_query(\"baidu.galaxy\", \n \"JobStat\",\n jobid,\n int(start_time * 1000000),\n int(end_time * 1000000),\n limit = limit)\n if not status:\n logger.error(\"fail to query job stat\")\n return [], False\n stats = []\n job_stat = log_pb2.JobStat()\n for data in data_list:\n for d in data.data_list:\n job_stat.ParseFromString(d)\n job_stat.time = job_stat.time/1000\n stats.append(util.pb2dict(job_stat))\n logger.info(\"query job %s stat from %s to %s , count %d\"%(jobid,\n datetime.datetime.fromtimestamp(start_time).strftime(\"%Y-%m-%d %H:%M:%S\"),\n datetime.datetime.fromtimestamp(end_time).strftime(\"%Y-%m-%d %H:%M:%S\"),\n len(stats)))\n return stats, True\n\n def get_pod_stat(self, podid, start_time, end_time, limit = 100):\n data_list, status = self.ftrace.simple_query(\"baidu.galaxy\", \n \"PodStat\",\n podid,\n int(start_time * 1000000),\n int(end_time * 1000000),\n limit = limit)\n if not status:\n logger.error(\"fail to query job stat\")\n return [], False\n stats = []\n pod_stat = log_pb2.PodStat()\n for data in data_list:\n for d in data.data_list:\n pod_stat.ParseFromString(d)\n pod_stat.time = pod_stat.time/1000\n stats.append(util.pb2dict(pod_stat))\n\n return stats, True\n\n\n def get_pod_event(self, podid, start_time, end_time, limit = 100):\n data_list, status = self.ftrace.simple_query(\"baidu.galaxy\", \n \"PodEvent\",\n podid,\n int(start_time * 1000000),\n int(end_time * 1000000),\n limit = limit)\n if not status:\n logger.error(\"fail to query pod event\")\n return [], False\n events = []\n pod_event = log_pb2.PodEvent()\n for data in data_list:\n for d in data.data_list:\n pod_event.ParseFromString(d)\n e = util.pb2dict(pod_event)\n e[\"stage\"] = galaxy_pb2.PodStage.Name(pod_event.stage)\n e[\"level\"] = log_pb2.TraceLevel.Name(pod_event.level)\n e[\"state\"] = galaxy_pb2.PodState.Name(pod_event.state)\n events.append(e)\n return events, True\n\n def get_task_event(self, podid, start_time, end_time, limit=100):\n data_list, status = self.ftrace.index_query(\"baidu.galaxy\", \n \"TaskEvent\",\n \"pod_id\", \n podid,\n int(start_time * 1000000),\n int(end_time * 1000000),\n limit = limit)\n events = []\n task_event = log_pb2.TaskEvent()\n for data in data_list:\n for d in data.data_list:\n task_event.ParseFromString(d)\n e = util.pb2dict(task_event)\n e[\"id\"] = e[\"id\"][-8:]\n e[\"initd_port\"] = e[\"initd_addr\"].split(\":\")[-1]\n e[\"stage\"] = agent_pb2.TaskStage.Name(task_event.stage)\n e[\"level\"] = log_pb2.TraceLevel.Name(task_event.level)\n e[\"state\"] = galaxy_pb2.TaskState.Name(task_event.state)\n events.append(e)\n return events, True\n\n def get_pod_event_by_jobid(self, jobid, start_time, end_time, limit=1000):\n data_list, status = self.ftrace.index_query(\"baidu.galaxy\", \n \"PodEvent\",\n \"jobid\", \n jobid,\n int(start_time * 1000000),\n int(end_time * 1000000),\n limit = limit)\n events = []\n pod_event = log_pb2.PodEvent()\n for data in data_list:\n for d in data.data_list:\n pod_event.ParseFromString(d)\n e = util.pb2dict(pod_event)\n e[\"stage\"] = galaxy_pb2.PodStage.Name(pod_event.stage)\n e[\"level\"] = log_pb2.TraceLevel.Name(pod_event.level)\n e[\"state\"] = galaxy_pb2.PodState.Name(pod_event.state)\n events.append(e)\n return events, True\n\n\n","sub_path":"platform/src/trace/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":7701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"80592320","text":"from PIL import Image, ImageDraw\n\nsize = (100, 100) \nimg = Image.new('RGB', size)\ndraw = ImageDraw.Draw(img)\n\nlines = [(50, 0), (0, 40), (20, 100), (80, 100), (100, 40)]\n\ndraw.polygon(lines, fill=\"blue\")\n\nimg.save(\"pentagon.png\")\n","sub_path":"pentagon.py","file_name":"pentagon.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"599139113","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport pygame, sys, yaml\nfrom pygame.locals import *\nfrom os.path import normpath\n\nPLIK_KONFIGURACYJNY = \"config.yml\"\n\ndef czytaj_plik_yaml(sciezka):\n plik = open(normpath(sciezka), 'r')\n zawartosc_pliku = plik.read()\n plik.close()\n return yaml.safe_load(zawartosc_pliku)\n\nclass Odpowiedz:\n def __init__(self,tresc,punkty):\n self.tresc=tresc\n self.punkty=punkty\n\nclass Runda:\n def __init__(self,pytanie,mnoznik,odpowiedzi):\n self.pytanie=pytanie\n self.mnoznik=mnoznik\n self.odpowiedzi=odpowiedzi\n\nclass Dane:\n def __init__(self, plik_konfiguracyjny):\n\n dane_z_yaml = czytaj_plik_yaml(sciezka=plik_konfiguracyjny)\n\n self.rozmiar_ekranu=tuple(dane_z_yaml['rozmiar_ekranu'])\n\n #obrazy\n sekcja=dane_z_yaml['obrazy']\n (self.img_ekran_powitalny,\n self.img_tlo,\n self.blad_maly,\n self.blad_duzy,\n self.aktywna_druzyna,\n ) = (pygame.image.load(normpath(sekcja['ekran_powitalny'])),\n pygame.image.load(normpath(sekcja['tlo'])),\n pygame.image.load(normpath(sekcja['blad_maly'])),\n pygame.image.load(normpath(sekcja['blad_duzy'])),\n pygame.image.load(normpath(sekcja['aktywna_druzyna'])),\n )\n\n #dźwięki\n #Traktujemy je jako muzykę, nie dźwięki, gdyż Sound.play() kończy się Segmentation fault. Nie wiem dlaczego.\n sekcja=dane_z_yaml['dzwieki']\n (self.snd_bledna_odpowiedz,\n self.snd_poprawna_odpowiedz,\n self.snd_koniec_rundy,\n self.snd_nowa_runda,\n ) = (normpath(sekcja['bledna_odpowiedz']),#pygame.mixer.Sound(normpath(sekcja['bledna_odpowiedz'])),\n normpath(sekcja['poprawna_odpowiedz']),#pygame.mixer.Sound(normpath(sekcja['poprawna_odpowiedz'])),\n normpath(sekcja['koniec_rundy']),\n normpath(sekcja['nowa_runda']),\n )\n\n #muzyka\n sekcja=dane_z_yaml['muzyka']\n self.mus_muzyka_na_start=normpath(sekcja['muzyka_na_start'])\n\n #czcionki\n sekcja=dane_z_yaml['czcionki']\n (self.fnt_podstawowa,\n self.fnt_punkty_druzyn,\n ) = (pygame.freetype.Font(normpath(sekcja['podstawowa']['plik']),sekcja['podstawowa']['rozmiar']),\n pygame.freetype.Font(normpath(sekcja['punkty_druzyn']['plik']),sekcja['punkty_druzyn']['rozmiar']),\n )\n\n (self.fnt_podstawowa.fgcolor,\n self.fnt_punkty_druzyn.fgcolor,\n ) = (tuple(sekcja['podstawowa']['kolor']),\n tuple(sekcja['punkty_druzyn']['kolor']),\n )\n\n #współrzędne\n sekcja=dane_z_yaml['wspolrzedne']\n self.crd_bledy,self.crd_punkty_druzyn,self.crd_nazwy_druzyn,self.crd_aktywna_druzyna=[None,None],[None,None],[None,None],[None,None]\n\n (self.crd_odpowiedzi_lp,\n self.crd_odpowiedzi_haslo,\n self.crd_odpowiedzi_punkty,\n self.crd_odpowiedzi_odstep,\n self.crd_bledy[0],\n self.crd_bledy[1],\n self.crd_bledy_odstep,\n self.crd_punkty_druzyn[0],\n self.crd_punkty_druzyn[1],\n self.crd_punkty_przemnozone,\n self.crd_punkty_suma_napis,\n self.crd_punkty_suma_punkty,\n self.crd_nazwy_druzyn[0],\n self.crd_nazwy_druzyn[1],\n self.crd_aktywna_druzyna[0],\n self.crd_aktywna_druzyna[1],\n ) = (tuple(sekcja['odpowiedzi']['lp']),\n tuple(sekcja['odpowiedzi']['haslo']),\n tuple(sekcja['odpowiedzi']['punkty']),\n sekcja['odpowiedzi']['odstep'],\n tuple(sekcja['bledy']['druzyna_0']),\n tuple(sekcja['bledy']['druzyna_1']),\n sekcja['bledy']['odstep'],\n tuple(sekcja['punkty']['druzyna_0']),\n tuple(sekcja['punkty']['druzyna_1']),\n tuple(sekcja['punkty']['punkty_przemnozone']),\n tuple(sekcja['punkty']['suma_napis']),\n tuple(sekcja['punkty']['suma_punkty']),\n tuple(sekcja['nazwy_druzyn']['druzyna_0']),\n tuple(sekcja['nazwy_druzyn']['druzyna_1']),\n tuple(sekcja['aktywna_druzyna']['druzyna_0']),\n tuple(sekcja['aktywna_druzyna']['druzyna_1']),\n )\n\n #teksty\n sekcja=dane_z_yaml['teksty']\n (self.txt_suma,\n self.txt_ukryte_haslo,\n self.txt_ukryte_punkty,\n ) = (sekcja['suma'],\n sekcja['ukryte_punkty'],\n sekcja['ukryte_haslo'],\n )\n\n #rundy, nazwy drużyn i finał\n rundy_dane_z_yaml=czytaj_plik_yaml(sciezka=dane_z_yaml['pytania'])\n self.nazwy_druzyn=(rundy_dane_z_yaml['nazwy_druzyn']['druzyna_0'],\n rundy_dane_z_yaml['nazwy_druzyn']['druzyna_1'])\n self.rundy=[ Runda(pytanie=runda['pytanie'], \\\n mnoznik=runda['mnoznik'], \\\n odpowiedzi=[ Odpowiedz(tresc=odpowiedz['odp'], punkty=odpowiedz['pkt']) \\\n for odpowiedz in runda['odpowiedzi'] ] ) \\\n for runda in rundy_dane_z_yaml['rundy'] ]\n\ndef liczba_odpowiedzi(numer_rundy):\n return len(dane.rundy[numer_rundy].odpowiedzi)\n\ndef liczba_punktow(numer_rundy,numer_odpowiedzi):\n return dane.rundy[numer_rundy].odpowiedzi[numer_odpowiedzi].punkty\n\ndef mnoznik(numer_rundy):\n return dane.rundy[numer_rundy].mnoznik\n\ndef stworz_ekran(rozmiar=None):\n if rozmiar is None:\n info = pygame.display.Info()\n return pygame.display.set_mode((info.current_w, info.current_h), FULLSCREEN)\n else:\n return pygame.display.set_mode(rozmiar)\n\ndef odswiez_ekran():\n ekran.blit(pygame.transform.smoothscale(wyswietlacz,pygame.display.get_surface().get_size()),(0,0))\n pygame.display.update()\n\npygame.mixer.pre_init(44100, 16, 2, 4096)\npygame.init()\ndane = Dane(PLIK_KONFIGURACYJNY)\nekran = stworz_ekran(dane.rozmiar_ekranu)\nwyswietlacz = pygame.Surface(dane.img_tlo.get_size())","sub_path":"konfiguracja.py","file_name":"konfiguracja.py","file_ext":"py","file_size_in_byte":5564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"396593345","text":"#!/usr/bin/env python\n\n\n# -*- encoding: utf-8 -*-\n\"\"\"\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom builtins import (bytes, open, str, super, range,\n zip, round, input, int, pow, object, map, zip)\n\nimport os\nimport argparse\nimport multiprocessing\nimport yaml\n\nimport gunicorn.app.base\n\n#from gunicorn.six import iteritems\n\nfrom magic_data_server.backend_api import run_micro_service, micro_service\n\nfrom magic_data_server import conf_dir\nfrom magic_data_server.backend_api import Configurer\n\n\n\n\ndef number_of_workers():\n return (multiprocessing.cpu_count() * 2) + 1\n\n\nclass StandaloneApplication(gunicorn.app.base.BaseApplication):\n def __init__(self, app, app_runner,options=None, app_conf=None):\n self.options = options or {}\n self.application = app\n self.app_conf = app_conf\n self.app_runner = app_runner\n super(StandaloneApplication, self).__init__()\n\n def load_config(self):\n config = dict([(key, value) for key, value in iteritems(self.options)\n if key in self.cfg.settings and value is not None])\n\n for key, value in iteritems(config):\n print ('conf',key.lower(), value)\n self.cfg.set(key.lower(), value)\n\n def load(self):\n return self.application\n\n def run(self, conf, debug=False, threaded=False):\n self.app_runner(conf, debug=debug, threaded=threaded)\n #self.application.config_dir['osaconf'] = conf\n #self.application.run(host=conf.dispatcher_url, port=conf.dispatcher_port, debug=debug, threaded=threaded)\n\n\ndef main(argv=None):\n\n black_listed_evns=['https_proxy','http_proxy']\n\n for envvar in black_listed_evns:\n print ('removing env variable',envvar)\n os.unsetenv(envvar)\n if envvar in os.environ.keys():\n del os.environ[envvar]\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-conf_file', type=str, default=None)\n parser.add_argument('-use_gunicorn', action='store_true')\n parser.add_argument('-debug', action='store_true')\n\n args = parser.parse_args()\n\n conf_file = args.conf_file\n\n if conf_file is None:\n conf_file = os.path.join(conf_dir,'config.yml')\n\n conf=Configurer.from_conf_file(conf_file)\n\n use_gunicorn = args.use_gunicorn\n debug = args.debug\n\n if use_gunicorn is True:\n dispatcher_url = conf.url\n port = conf.port\n\n options = {\n 'bind': '%s:%s' % (dispatcher_url, port),\n 'workers': 2,\n 'threads': 4,\n #'worker-connections': 10,\n #'k': 'gevent',\n }\n StandaloneApplication(micro_service, run_micro_service, options).run(conf, debug=debug,threaded=True)\n else:\n run_micro_service(conf, debug=debug, threaded=False)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/run_magic_back_end.py","file_name":"run_magic_back_end.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"581050416","text":"import json\nfrom datetime import datetime\nfrom ripda.transaction.utils import Utils\nfrom ripda.blockchain.core import Blockchain\nfrom ripda.settings import getc\n\n\nif not __name__ == \"__main__\":\n if not __name__ == 'ripda.transaction.pool':\n from ripda.transaction.pool import Pool\n\n\nclass Block:\n \"\"\"\n Block é responsável por gerar o bloco de origem, bem como retornar o próximo bloco a ser validado na rede\n e verificar se um hash gerado é válido.\n \"\"\"\n\n def __init__(self):\n self.difficulty = '0' * int(getc('ripda_block', 'core_difficulty'))\n self.count = len(Blockchain().view())\n self.transactions = Pool().view()\n self.timestamp = datetime.utcnow().timestamp()\n self.forger = Pool().forging_required()\n self.nonce = None\n self.hash = None\n self.block = {}\n \"\"\"\n Se não houver nenhum bloco na cadeia, criar o bloco de origem.\n \"\"\"\n if len(Blockchain().view()) == 0:\n self.last_hash = None\n self.transactions = []\n self.create_genesis_block()\n else:\n self.last_hash = Blockchain().view()[-1]['hash']\n\n def view(self):\n \"\"\"\n Retorna a estrutura do bloco candidato a ser o próximo a\n ser adicionado à cadeia de blocos\n \"\"\"\n abstract_transactions_amount = 0\n if len(self.transactions) >> 0:\n for transaction in self.transactions:\n abstract_transactions_amount += transaction['amount']\n block = {\n 'last_hash': self.last_hash,\n 'count': self.count,\n 'abstract':{\n 'transactions': {\n 'count': len(self.transactions),\n 'amount': abstract_transactions_amount\n }\n },\n 'transactions': self.transactions,\n 'timestamp': self.timestamp,\n 'forger': self.forger,\n }\n self.block = block\n return block\n\n def create_genesis_block(self):\n \"\"\"\n Cria o bloco de origem\n \"\"\"\n self.hash = ''\n self.nonce = 1\n block = {}\n while not self.is_hash_valid(self.hash):\n block = {\n 'last_hash': self.last_hash,\n 'count': self.count,\n 'abstract':{\n 'transactions': {\n 'count': 0,\n 'amount': 0\n }\n },\n 'transactions': self.transactions,\n 'timestamp': self.timestamp,\n 'nonce': self.nonce,\n 'forging': '1QDHV2TfNDCoaMeVerRz6v6eHfDLNtiFNU'\n }\n self.hash = Utils.sha256(json.dumps(block))\n self.nonce += 1\n block['hash'] = self.hash\n return Blockchain().add_block(block)\n\n def is_hash_valid(self, _hash):\n \"\"\"\n Verifica se o hash informado é valido\n \"\"\"\n return _hash.startswith(self.difficulty)\n","sub_path":"src/ripda/block/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"551873778","text":"import re\nfrom collections import defaultdict, Counter\n\nfrom utils import is_word_capitalized\n\nclass Model():\n def __init__(self):\n self.training_sentences = None\n self.labeled_grams = None\n self.features = None\n self.test_words = None\n self.pred_probs = None\n \n\n def fit(self, sentences):\n \"\"\"\n Train the model\n\n sentences: a list of sentences. Each sentence is a list of words.\n \"\"\"\n print(\"Starting Training...\")\n self.training_sentences = sentences\n self.labeled_grams = self.get_3grams(sentences, labeled=True)\n self.features = self.get_features(self.labeled_grams, labeled=True)\n\n\n def predict_prob(self, words):\n \"\"\"\n Calculate the probability of each word to be the end of a sentence.\n\n words: a list of words\n \"\"\"\n print(\"Starting Testing...\")\n self.test_words = words\n grams = self.three_grams_from_sentence(words, '~', '~')\n raw_features = self._extract_raw_features(grams, labeled=False)\n self.pred_probs = self.get_probs(grams, raw_features)\n return self.pred_probs\n\n# ============================================= #\n\n def get_3grams(self, sentences, labeled):\n \"\"\" \n Create a list of 3grams from a list of sentences\n \"\"\"\n print(\"Extracting 3grams from sentences...\")\n\n grams = list()\n for i, sentence in enumerate(sentences):\n if i == 0: prev_word = '~'\n else: prev_word = sentences[i-1][-1]\n\n if i == len(sentences) - 1: next_word = '~'\n else: next_word = sentences[i+1][0]\n \n temp = self.three_grams_from_sentence(sentence, prev_word, next_word)\n \n if labeled is True: temp = self._label_sentence_grams(temp)\n \n grams.extend(temp)\n \n return grams\n \n\n def three_grams_from_sentence(self, sentence, prev_word, next_word):\n \"\"\"\n Create a list of 3grams from a sentence (list of words),\n the preceding word, and the following word\n \"\"\"\n grams = list()\n\n if len(sentence) < 2:\n return [(prev_word, sentence[0], next_word)]\n\n # First 3 gram of the sentence\n grams.append((prev_word, sentence[0], sentence[1]))\n \n grams.extend([(sentence[i-1], sentence[i], sentence[i+1]) for i in range(1, len(sentence) - 1)])\n \n # Last 3 gram of the sentence\n grams.append((sentence[-2], sentence[-1], next_word))\n\n return grams\n\n\n def _label_sentence_grams(self, grams):\n \"\"\"\n Label each 3gram of the list with 0,\n except for the last one (the end of a sentence) with one\n \"\"\"\n # Label all the others as not the end of the sentence\n labeled = [(g, 0) for g in grams[:-1]]\n # Label the last 3gram as the end of the sentence\n labeled.append((grams[-1], 1))\n return labeled\n\n\n def get_features(self, grams, labeled):\n print(\"Extracting Features...\")\n raw_features = self._extract_raw_features(grams, labeled)\n\n features = dict()\n # Initialize temporary dictionaries for calculation\n total = defaultdict(float)\n feature_dict = defaultdict(Counter)\n\n # learn the features of each 3gram with its label\n for gram, feats in zip(self.labeled_grams, raw_features):\n context, label = gram\n\n total[label] += len(context) + len(feats)\n \n # Context <-> Label \n for i, word in enumerate(context):\n feature_dict[label]['w' + str(i) + '_' + word] += 1\n \n # Arbitrary Features <-> Label \n for name, val in feats.items():\n feature_dict[label][name + '_' + val] += 1\n \n # Smoothing\n print(\"Smoothing...\")\n smooth_coeff = 0.1\n \n all_features = set()\n for label in total:\n all_features.update(feature_dict[label].keys())\n \n for label, counts in total.items():\n total[label] += len(all_features) * smooth_coeff\n\n for name in all_features:\n feature_dict[label][name] += smooth_coeff\n feature_dict[label][name] /= total[label]\n features[(label, name)] = feature_dict[label][name]\n\n # Prior probabiliy for each label\n s = sum(total.values())\n for label, count in total.items():\n features[(label, 'prior')] = count / s\n \n self.labels = list(total.keys())\n return features\n\n\n def _extract_raw_features(self, grams, labeled):\n \"\"\"\n For each 3gram, create a dictionary corresponding to some features\n used by the model.\n Return a list of dictionaries\n \"\"\"\n\n # Initialize the list\n features = [0 for _ in range(len(grams))]\n\n # Create a dictionary for each 3gram\n for i, gram in enumerate(grams):\n # The 3gram may be labeled, extract it if necessary\n if labeled is True: context, label = gram\n else: context = gram\n \n feat = dict()\n\n # Previous word is capitalized\n feat['prev_word_cap'] = str(is_word_capitalized(context[0]))\n # Length of previous word\n feat['prev_word_len'] = str(len(context[0]))\n # Current word in capitalized\n feat['curr_word_cap'] = str(is_word_capitalized(context[1]))\n # Length of current word\n feat['curr_word_len'] = str(len(context[1]))\n # Next word is capitalized\n feat['next_word_cap'] = str(is_word_capitalized(context[2]))\n # Length of next word\n feat['next_word_len'] = str(len(context[2]))\n \n features[i] = feat\n \n return features\n\n\n def group_sentence(self, words, start, end):\n return words[start:end+1]\n\n\n def get_probs(self, grams, raw_features):\n probs = list()\n for context, feats in zip(grams, raw_features):\n prob = self.get_prob(context, feats)\n probs.append(prob)\n \n return probs\n\n\n def get_prob(self, context, features):\n \"\"\"\n Return a list of dictionaries.\n Each dictionary corresponds to one gram and contains\n 2 probabilities corresponding to 'not an end of a sentence' and 'end of a sentence'\n \"\"\"\n # Initialize probabilities with the priori probability calculated during training\n label_prob = {label: self.features[(label, 'prior')] for label in self.labels}\n \n for label in self.labels:\n # Evaluate arbitrary features\n for name, val in features.items():\n feature_name = name + '_' + val\n key = (label, feature_name)\n if key in self.features:\n label_prob[label] *= self.features[key]\n \n # Evaluate context\n for i, word in enumerate(context):\n feature_name = 'w' + str(i) + '_' + word\n key = (label, feature_name)\n if key in self.features:\n label_prob[label] *= self.features[key]\n\n \n # Normalization\n total_prob = sum(label_prob.values())\n for label in self.labels:\n label_prob[label] /= total_prob\n\n return label_prob","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":7498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"351825665","text":"# coding:utf-8\r\nimport requests\r\n\r\nclass DJLogin(object):\r\n \"\"\"\r\n Django 制作登录页面测试web请求\r\n \"\"\"\r\n def __init__(self, url):\r\n '''初始化函数,传入参数 url'''\r\n self.url = url\r\n\r\n\r\n def get_url(self):\r\n '''get 方法'''\r\n dj = requests.get(self.url)\r\n return dj\r\n\r\n def post_url(self):\r\n param = {\r\n \"user\": \"123\",\r\n \"passwd\": \"hello\",\r\n \"csfrmiddlewaretoken\":\"EG67FRmit7WvQjC8rfZFjR7S6mbfszhy\"\r\n }\r\n\r\n dj = requests.post(self.url, params=param)\r\n return dj\r\n\r\nif __name__ == '__main__':\r\n url = 'http://127.0.0.1:8001/index/'\r\n DJ = DJLogin(url)\r\n result = DJ.post_url()\r\n print(result)\r\n\r\n","sub_path":"dj_project/login/DJ_login.py","file_name":"DJ_login.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"75803428","text":"#array rotation with first ellement\r\na=[]\r\nl=int(input('enter length of the lst:'))\r\nfor i in range(l):\r\n a.append(int(input('enter element:')))\r\nb=[]\r\nc=[]\r\nn=a[0]\r\nfor i in range(len(a)):\r\n if(len(a) A.shape[1]:\n\t\t\traise Exception('Too many variables properties for too few decision variables in the model.')\n\t\tsolver_method = pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING\n\t\tsolver_name = 'mixed_integer_programming'\n\telif method.upper() == 'CLP':\n\t\tif len(vars_properties.keys()) > A.shape[1]:\n\t\t\traise Exception('Too many variables properties for too few decision variables in the model.')\n\t\tsolver_method = pywraplp.Solver.CLP_LINEAR_PROGRAMMING\n\t\tsolver_name = 'continuous_linear_programming'\n\telse:\n\t\traise Exception('Unsupported method:', method)\n\t# creates the solver instance\n\tsolver = pywraplp.Solver(solver_name, solver_method)\n\tinfinity = solver.infinity()\n\n\t# sets the number of threads (currently doesn't works for some platforms like windows)\n\tif num_threads <= 0:\n\t\tnum_threads = 1\n\telse:\n\t\tnum_threads = int(num_threads)\n\tsolver.SetNumThreads(num_theads=num_threads)\n\n\t# creates the variables, setting all their properties\n\tif method.upper() == 'BOP':\n\t\tfor k in range(0, n):\n\t\t\tvariable = solver.BoolVar('x[%i]' % k)\n\t\t\tX.append(variable)\n\n\telif method.upper() == 'CBC':\n\t\tfor k in range(0, n):\n\t\t\tkth_type = 1\n\t\t\tkth_lb = 0.0\n\t\t\tkth_ub = infinity\n\t\t\tif k in vars_properties:\n\t\t\t\ttry:\n\t\t\t\t\tkth_type, kth_lb, kth_ub = vars_properties[k]\n\t\t\t\texcept ValueError:\n\t\t\t\t\traise Exception('The \"CBC: method expected tuples of size exactly 3 in the \"vars_properties\" dictionary.')\n\t\t\tif kth_lb > kth_ub:\n\t\t\t\traise Exception('Inconsistent '+str(k)+'-th variable bounds: the lower bound \"'+str(kth_lb)+'\" is greater than the upper bound \"'+str(kth_ub)+'\".')\n\n\t\t\tvariable = None\n\t\t\tif kth_type == 0:\n\t\t\t\tif kth_lb != 0 or kth_ub != 1:\n\t\t\t\t\traise Exception('Binary variables must always have their lower bound set to 0 and their upper bound set to 1.')\n\t\t\t\tvariable = solver.BoolVar('x[%i]' % k)\n\t\t\telif kth_type == 1:\n\t\t\t\tvariable = solver.IntVar(kth_lb, kth_ub, 'x[%i]' % k)\n\t\t\telif kth_type == 2:\n\t\t\t\tvariable = solver.Var(kth_lb, kth_ub, False,'x[%i]' % k)\n\t\t\telse:\n\t\t\t\traise Exception('Unknown variable type in vars_properties:', kth_type)\n\t\t\tX.append(variable)\n\n\telif method.upper() == 'CLP':\n\t\tfor k in range(0, n):\n\t\t\tkth_lb = 0.0\n\t\t\tkth_ub = infinity\n\t\t\tif k in vars_properties:\n\t\t\t\ttry:\n\t\t\t\t\tkth_lb, kth_ub = vars_properties[k]\n\t\t\t\texcept ValueError:\n\t\t\t\t\traise Exception('The \"CLP: method expected tuples of size exactly 2 in the \"vars_properties\" dictionary.')\n\t\t\tif kth_lb > kth_ub:\n\t\t\t\traise Exception('Inconsistent '+str(k)+'-th variable bounds: the lower bound \"'+str(kth_lb)+'\" is greater than the upper bound \"'+str(kth_ub)+'\".')\n\n\t\t\tvariable = solver.Var(kth_lb, kth_ub, False,'x[%i]' % k)\n\t\t\tX.append(variable)\n\n\t# creates the constraints, setting all their properties\n\tfor k in range(0, c):\n\t\tkth_lb = lb.item(k)\n\t\tkth_ub = ub.item(k)\n\t\tif kth_lb > kth_ub:\n\t\t\traise Exception('Inconsistent '+str(k)+'-th constraint bounds: the lower bound \"'+str(kth_lb)+'\" is greater than the upper bound \"'+str(kth_ub)+'\".')\n\t\t\n\t\tconstraint = solver.RowConstraint(kth_lb, kth_ub, 'constraint[%i]' % k)\n\t\tfor v in range(0, n):\n\t\t\tconstraint.SetCoefficient(X[v], A.item(k, v))\n\n\t# sets the LP objective\n\tobjective = solver.Objective()\n\tfor k in range(n):\n\t\tobjective.SetCoefficient(X[k], C.item(k))\n\tif maximization:\n\t\tobjective.SetMaximization()\n\telse:\n\t\tobjective.SetMinimization()\n\n\t# sets a hint for a initial basic feasible solution\n\tif len(hint) > 0:\n\t\tif len(hint) != n:\n\t\t\traise Exception('The hint list has an inconsistent number of elements:', len(hint))\n\t\tsolver.SetHint(solver.variables(), hint)\n\n\t# attempts to solve the problem\n\tstatus = solver.Solve()\n\tif method.upper() == 'BOP':\n\t\treturn solver.Objective().Value(), np.array([variable.solution_value() for variable in X]), status, solver.wall_time()\n\telif method.upper() == 'CBC':\n\t\treturn solver.Objective().Value(), np.array([variable.solution_value() for variable in X]), status, solver.wall_time(), solver.iterations(), solver.nodes()\n\telif method.upper() == 'CLP':\n\t\treturn solver.Objective().Value(), np.array([variable.solution_value() for variable in X]), status, solver.wall_time(), solver.iterations()\n\n","sub_path":"src/linear_programming_solver.py","file_name":"linear_programming_solver.py","file_ext":"py","file_size_in_byte":11641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"36109086","text":"# -*- coding:utf-8 -*-\nu'''\nCreated on 2021年4月19日\n@author: xianyu\n@description:主程序,训练流程实现\n'''\n__author__ = 'xianyu'\n__version__ = '1.0.0'\n__company__ = u'STDU'\n__updated__ = '2021-05-28'\n\nimport sys\nimport os\n\n# BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 当前程序文件的目录\n# sys.path.append(BASE_DIR) #添加环境变量\n\nfrom Algorithms import *\nfrom Utils import *\nfrom Pretreatment import *\n\nimport matplotlib.pyplot as plt\nimport time\n\n# 创建数据集部分\ndataSet_name = './data_set/caltech_vgg_data_l2.mat' # 数据集输入\nratio_marked_num = 0.05 # 数据集划分中,有标签这样本数量占除验证集之外的样本数量的比例\nratio_validation = 0.5 # 数据集划分中,验证集样本数量占总样本数量的比例\nsame_index = []\nstop_ratio = 0.5 # 测试集中训练停止比例。目前迭代训练的终止条件是,添加超过一半的无标记样本参与训练\nratio_BvSB = 0.05\nthreshold_BvSB = 0.7\nthreshold_Weight = 100 # 参与训练次数的权重。大于该值的样本不参与训练\nbatch_size = 198\n\n# 存储设置\ndir = './result_storage/caltech/'\nset_val = '_11vgg_' + str(ratio_marked_num) + '_' + str(round(1-ratio_marked_num, 2)) + '_' + \\\n str(ratio_validation) + '_C1000'\n\nstr_title = str(ratio_marked_num) + '_' + str(round(1-ratio_marked_num, 2)) + '_' + \\\n str(ratio_validation)\n\n# 配置部分\nisRSM = True\nisBvSB = True\nRSM_len = 900\nisAll4Train = True\n\n\nif __name__ == '__main__':\n\n # 记录程序开始运行的时间\n start_time = time.time()\n\n # 导入所需的工具和算法包\n utils = Utils()\n algorithms = Algorithms()\n pretreatment = Pretreatment()\n\n # 初始化数据集及权重,返回有编辑样本和无标记样本的数量\n data, target = utils.init_DataSet(dataSet_name)\n num_img_marked, num_img_unmarked, validation_x, validation_y = \\\n utils.split_Data(ratio_marked_num, ratio_validation, data, target, isRSM=isRSM, RSM_len=RSM_len)\n\n print('len(validation_x[0]) = ', len(validation_x[0]))\n\n # 程序运行前的准备工作\n num_unmarked_img_orig = num_img_unmarked # 记录unmarked文件夹下原始的图片数量\n num_loop = 1 # 记录训练的论数\n unchanged_times = 0 # 记录训练结果不变的次数,由此表征训练结果是否达到稳定\n threshold_satble = 10 # 训练结果不变的次数超过threshold_satble次,则证明训练已达稳定,训练终止\n accuracy_score_buf_1 = [] # 记录分类器1的精度\n accuracy_score_buf_2 = [] # 记录分类器2的精度\n accuracy_score_buf = [] # 记录两个分类器的度量精度\n moving_ratio = []\n\n label_list = utils.get_Label_List(dataSet_name)\n print('label_list = ', label_list)\n\n if isAll4Train:\n batch_size = num_img_marked\n\n while True:\n\n print('------------------------------第' + str(num_loop) + '轮训练--------------------------------')\n\n batch_size = batch_size + len(same_index)\n print('batch_size+len(same_index) = ', batch_size)\n\n # 获取数据集中的样本\n X_Train_1, X_Test_1, Y_Train_1, Y_Test_1, X_Train_2, X_Test_2, Y_Train_2, Y_Test_2\\\n = utils.get_train_test_data(batch_size)\n\n if len(X_Train_1) == len(X_Test_1) == len(Y_Train_1) == len(Y_Test_1) == len(X_Train_2) == len(X_Test_2) == \\\n len(Y_Train_2) == len(Y_Test_2) == 0:\n break\n\n # SVM训练\n Y_pred_proba_1, Y_pred_proba_2, score_1, score_2, score = algorithms.SVM_Training_And_Testing(\n X_Train_1, X_Train_2, Y_Train_1, Y_Train_2, X_Test_1, X_Test_2, Y_Test_1, Y_Test_2, validation_x,\n validation_y, label_list)\n print('score_1 = ', score_1, 'score_2 = ', score_2, 'score = ', score)\n\n # 记录两个分类器的精度\n accuracy_score_buf_1.append(score_1)\n accuracy_score_buf_2.append(score_2)\n accuracy_score_buf.append(score)\n\n # BvSB算法输出前ratio的候选值\n diff_B_SB_1, diff_B_SB_2 = algorithms.BvSB(Y_pred_proba_1, Y_pred_proba_2, ratio_BvSB, threshold_BvSB,\n isBvSB=isBvSB)\n\n print('diff_B_SB_1', diff_B_SB_1)\n print('diff_B_SB_2', diff_B_SB_2)\n\n # 判断两个预测结果是否相同且是否正确\n diff_B_SB_1_index = [i[0] for i in diff_B_SB_1] # 获取BvSB得到的样本下标\n diff_B_SB_2_index = [i[0] for i in diff_B_SB_2] # 获取BvSB得到的样本下标\n same_index = [x for x in diff_B_SB_1_index if x in diff_B_SB_2_index] # 寻找相同的元素\n print('same_index', same_index)\n\n # 移动数据集\n utils.update_DataSet(same_index, threshold_Weight)\n\n # 判断是否还有待移动的图片,若超过10次没有图片可以移动,则证明训练已达稳定,训练终止\n if len(same_index) == 0:\n unchanged_times = unchanged_times + 1\n else:\n unchanged_times = 0\n # 训练终止的条件:训练达到稳定\n if unchanged_times >= threshold_satble:\n print('训练已达到稳定,结束训练!')\n break\n\n # 训练终止的条件:超过50%的无标签样本被移动\n if (num_unmarked_img_orig - len(Y_Test_1)) / num_unmarked_img_orig > stop_ratio:\n print('超过'+str(stop_ratio*100)+'%的无标签样本被移动,结束训练!')\n break\n\n num_loop = num_loop + 1\n moving_ratio.append((num_unmarked_img_orig - len(Y_Test_1)) / num_unmarked_img_orig)\n print('{:.2%}的无标签样本被移动'.format((num_unmarked_img_orig - len(Y_Test_1)) / num_unmarked_img_orig))\n\n # 打印程序运行时间\n end_time = time.time()\n dtime = end_time - start_time\n print(\"程序运行时间:%.8s s\" % dtime) # 显示到微秒\n print('SVM1训练精度的最大值为:', round(max(accuracy_score_buf_1), 4))\n print('SVM2训练精度的最大值为:', round(max(accuracy_score_buf_2), 4))\n print('协同训练精度的最大值为:', round(max(accuracy_score_buf), 4))\n print()\n\n # # 绘制精度变化曲线\n # plt.figure(0, figsize=(14, 4))\n # plt.subplot(1, 2, 1)\n # plt.plot(accuracy_score_buf_1)\n # plt.title('classifier 1')\n # plt.xlabel('caltech')\n # plt.ylabel('accuracy')\n # plt.title(str_title)\n #\n # # plt.figure(1)\n # plt.subplot(1, 2, 2)\n # plt.plot(accuracy_score_buf_2)\n # plt.title('classifier 2')\n # plt.xlabel('caltech')\n # plt.ylabel('accuracy')\n # plt.title(str_title)\n #\n # plt.savefig(dir + 'classifier' + set_val + '.png')\n\n # 绘制无标签样本被移动比例图\n plt.figure(1, figsize=(14, 4))\n plt.subplot(1, 2, 1)\n plt.plot(accuracy_score_buf)\n plt.title('classifier')\n plt.xlabel('caltech')\n plt.ylabel('accuracy')\n plt.title(str_title)\n\n plt.subplot(1, 2, 2)\n plt.plot(moving_ratio)\n plt.title('moving ratio')\n plt.xlabel('caltech')\n plt.ylabel('ratio')\n plt.title(str_title)\n\n plt.savefig(dir + 'moving_ratio' + set_val + '.png')\n\n # 打印程序运行时间\n end_time = time.time()\n dtime = end_time - start_time\n print(\"程序运行时间:%.8s s\" % dtime) # 显示到微秒\n print('SVM1训练精度的最大值为:', round(max(accuracy_score_buf_1), 4))\n print('SVM2训练精度的最���值为:', round(max(accuracy_score_buf_2), 4))\n print('协同训练精度的最大值为:', round(max(accuracy_score_buf), 4))\n\n # 以文档的方式存储数据\n filename = dir + 'record' + set_val + '.txt'\n with open(filename, 'w') as file_object:\n file_object.write(str(len(accuracy_score_buf)) + '\\n')\n file_object.write(str(accuracy_score_buf_1) + '\\n')\n file_object.write(str(accuracy_score_buf_2) + '\\n')\n file_object.write(str(accuracy_score_buf) + '\\n')\n file_object.write(str(moving_ratio) + '\\n')\n file_object.write(str(dtime) + '\\n')\n file_object.write(str(max(accuracy_score_buf)) + '\\n')\n\n\n\n plt.show()\n\n\n\n\n\n\n\n\n\n","sub_path":"main_chapter_5_modified.py","file_name":"main_chapter_5_modified.py","file_ext":"py","file_size_in_byte":8167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"253942931","text":"import pygame\npygame.init()\nplaying = True\n\npygame.display.set_caption('new game')\nwidth = 1200\nheight = 720\nblack = (0,0,0)\nwhite = (255,255,255)\nbackcolour = (0, 200 ,255)\nwindow = pygame.display.set_mode((width,height))\nwindow.fill(backcolour)\npygame.display.update()\nclock = pygame.time.Clock()\n\ndef text(string, location = [800, 400], size = 115):\n str1 = pygame.font.Font('freesansbold.ttf',size).render(string, True, black)\n strec = str1.get_rect()\n strec.center = location\n window.blit(str1,strec)\n\nclass character:\n def __init__(self,img,location = [width * 0.45, height * 0.5],speed = 15):\n self.left_img = pygame.image.load(img)\n self.right_img = pygame.transform.flip(self.left_img,1,0)\n self.health = 100\n self.location = [width * 0.45, height * 0.5]\n self.facing_right = 0\n self.speed = speed\n self.name = img[:-4]\n \n def draw(self, new_location = False):\n if new_location:\n self.location = new_location \n if self.facing_right:\n window.blit(self.right_img,self.location)\n else:\n window.blit(self.left_img,self.location)\n \n def move(self,location_change):\n self.location[0] = max(min(self.location[0] + location_change[0],width - 250), 0)\n self.location[1] = max(min(self.location[1] + location_change[1],height - 250), 100)\n self.draw()\n \n def copy(self):\n return character(self.name + \".png\")\n\n def calc_dmg(self,other):\n if other.location[1] - 160 < self.location[1] < other.location[1]:\n if other.location[0] - 80 < self.location[0] < other.location[0] + 80:\n other.health -= 5\n \n#character initialize\naoba = character('aoba.png')\nyagami = character('yagami.png')\nrin = character('rin.png')\nhifumi = character('hifumi.png')\nhajime = character('hajime.png')\nyun = character('yun.png')\numiko = character('umiko.png')\nnene = character('nene.png')\nshizuku = character('shizuku.png')\nmomiji = character('momiji.png')\nnarumi = character('narumi.png')\nhotaru = character('hotaru.png')\nyamato = character('yamato.png')\ncharlist = [aoba, yagami, rin, hifumi, hajime, yun, umiko, nene, shizuku, momiji, narumi, hotaru, yamato]\n\n\n#character select\nselecting_character = True\npos = 0\ncurrent_player = 1\nplayerchars = []\nwhile selecting_character and playing:\n text(\"player \" + str(current_player),[width/2,60])\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n playing = False\n window.fill(backcolour)\n charlist[pos].draw([300,300])\n text(charlist[pos].name)\n pygame.display.update()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n pos = (pos + 1)%len(charlist)\n if event.key == pygame.K_DOWN:\n pos = (pos - 1)%len(charlist)\n if event.key == pygame.K_RETURN:\n selecting_character = 2 - current_player\n playerchars.append(charlist[pos].copy())\n current_player += 1\n\nplayerchars[0].draw([width * 0.25, height * 0.5])\nplayerchars[1].draw([width * 0.65, height * 0.5])\nlocation_changes = [[0, 0],[0, 0]]\nwhile playing:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n playing = False\n \n if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:\n #player1\n movement = playerchars[0].speed if event.type == pygame.KEYDOWN else -playerchars[0].speed\n if event.key == pygame.K_LEFT:\n location_changes[0][0] -= movement\n if movement > 0:playerchars[0].facing_right = 0\n elif event.key == pygame.K_RIGHT:\n location_changes[0][0] += movement\n if movement > 0: playerchars[0].facing_right = 1\n if event.key == pygame.K_UP:\n location_changes[0][1] -= movement\n elif event.key == pygame.K_DOWN:\n location_changes[0][1] += movement\n \n #player2\n movement = playerchars[1].speed if event.type == pygame.KEYDOWN else -playerchars[1].speed\n if event.key == pygame.K_a:\n location_changes[1][0] -= movement\n if movement > 0:playerchars[1].facing_right = 0\n elif event.key == pygame.K_d:\n location_changes[1][0] += movement\n if movement > 0: playerchars[1].facing_right = 1\n if event.key == pygame.K_w:\n location_changes[1][1] -= movement\n elif event.key == pygame.K_s:\n location_changes[1][1] += movement\n \n window.fill(backcolour)\n text(playerchars[0].name + \" \" + str(playerchars[0].health),[width /3,60],60)\n text(playerchars[1].name + \" \" + str(playerchars[1].health),[width*2/3,60],60) \n playerchars[0].move(location_changes[0])\n playerchars[1].move(location_changes[1])\n playerchars[0].calc_dmg(playerchars[1])\n playerchars[1].calc_dmg(playerchars[0])\n pygame.display.update()\n clock.tick(60)\n \npygame.quit()","sub_path":"new game game/crap/game sandbox.py","file_name":"game sandbox.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"199641179","text":"#!/usr/bin/python3\nfrom concurrent.futures import ProcessPoolExecutor\n# from time import sleep\nimport os\n\ndef recibir_matriz(vector):\n print(\"recibir: \",vector)\n for respuesta_2 in vector:\n var = multiplicar_matriz(respuesta_2)\n return (var) \n\ndef multiplicar_matriz(elemento):\n print(\"multiplicar: \",elemento)\n #return (os.getpid(), elemento*elemento)\n return (elemento*elemento)\n\nmatriz = [[3, 4, 5, 10, 6, 5],\n [10, 3, 7, 8, 3, 2],\n [6, 8, 2, 0, 8, 8],\n [4, 3, 9, 10, 10, 10],\n [4, 5, 7, 10, 8, 5],\n [10, 2, 6, 7, 2, 10]]\n\npool_2 = ProcessPoolExecutor(4)\n\nfor respuesta_1 in pool_2.map(recibir_matriz,matriz):\n print(respuesta_1)\n \n","sub_path":"computacion2/segundo_semestre/pool_matriz.py","file_name":"pool_matriz.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"98339523","text":"import email\nimport imaplib\n\nlogin = 'test@puzniak.pl'\nhaslo = 'Informatyka1!'\nserwer = 'mail.puzniak.pl'\n\nmail = imaplib.IMAP4_SSL(serwer)\nmail.login(login, haslo)\n\nmail.select('inbox')\n\nstatus, data = mail.search(None, 'ALL')\nmail_ids = []\nfor block in data:\n mail_ids += block.split()\nfor i in mail_ids:\n status, data = mail.fetch(i, '(RFC822)')\n for response_part in data:\n if isinstance(response_part, tuple):\n message = email.message_from_bytes(response_part[1])\n mail_from = message['from']\n mail_subject = message['subject']\n if message.is_multipart():\n mail_content = ''\n for part in message.get_payload():\n if part.get_content_type() == 'text/plain':\n mail_content += part.get_payload()\n else:\n mail_content = message.get_payload()\n print('Od: '+ mail_from)\n print('Temat: '+ mail_subject)\n print('Treść: ' + mail_content + '\\n')","sub_path":"zadania-cwiczenia/funkcja.py","file_name":"funkcja.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"129761931","text":"\"\"\"\nGiven n non-negative integers a1, a2, ..., an,\nwhere each represents a point at coordinate (i, ai).\nn vertical lines are drawn such that the two endpoints of line i\nis at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container,\nsuch that the container contains the most water.\n\nNote: You may not slant the container.\n\"\"\"\n\n\nclass Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n maxArea = float('-inf')\n n = len(height)\n lo, hi = 0, n - 1\n while lo < hi:\n maxArea = max(maxArea, (hi - lo) * min(height[lo], height[hi]))\n if height[lo] < height[hi]:\n lo += 1\n else:\n hi -= 1\n return maxArea\n","sub_path":"medium/ContainerWithMostWater.py","file_name":"ContainerWithMostWater.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"415415973","text":"from NN_analysis import read_dictionary\nfrom NN_analysis import read_bag_of_word\nimport dow_jones\nfrom sklearn import svm\nfrom count_sentiments import create_feature_matrix\nimport datetime\n\n# This file contains feature of word vector. Each dimension indicates the count for each sentimental categories.\n# Make sure you have run preprocessing.py, dictionary_separator.py before this analysis.\ndow_jones_labels = dow_jones.label_nominal(dow_jones.index_changing_rate(dow_jones.read_indices('YAHOO-INDEX_DJI_longer.csv')))\n\ndef cross_validation(fold,dates,features_dict):\n \"Cross-alidation using SVM and sentimental features\"\n # The most important aspect is that using previous months to predict several days afterwards has accuracy 75%.\n # All folds have accuracy greater than benchmark\n chunk=len(dates)/fold\n average=0\n for i in range(0,fold):\n if (i+1)*chunk0:\n count += 1\n accuracy=float(count)/len(testing_set)\n print(testing_keys)\n print(\"accuracy={0}\".format(accuracy))\n average+=accuracy\n print('{0}-fold cross validation accuracy={1}'.format(fold,average/fold))\n\ndef main():\n #read in pre-processed features\n print('reading preprocessed data')\n bag = read_bag_of_word('features')\n #read in sentimental dictionary\n print('reading dictionary')\n [word_vector, sentiments] = read_dictionary(\"positive.txt\", \"negative.txt\")\n features,target,features_dict=create_feature_matrix(bag, sentiments)\n # Sort dates in order\n # Sort dates in order\n dates=dow_jones_labels.keys()\n dates = [datetime.datetime.strptime(ts, \"%Y-%m-%d\") for ts in dates]\n dates.sort()\n dates = [datetime.datetime.strftime(ts, \"%Y-%m-%d\") for ts in dates]\n # transform target dow jones index to binary\n cross_validation(10, dates, features_dict)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Analysis/svm_analysis.py","file_name":"svm_analysis.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"14775441","text":"#!/usr/bin/env python3\n\"\"\"\nSubtract sky from image by summing sky principal components with pre-computed coefficients\nfor this exposure.\nAlso create or overwrite a weight image, using read noise, flat-field noise, and shot\nnoise either from all counts or just from sky.\n\"\"\"\n\nfrom os import path\nimport numpy as np\n\nfrom despyfits.DESImage import DESDataImage, DESImage, weight_dtype, section2slice\nfrom pixcorrect.corr_util import logger, do_once, items_must_match\nfrom pixcorrect.PixCorrectDriver import PixCorrectImStep\nfrom pixcorrect import skyinfo\nfrom pixcorrect.skyinfo import SkyError\nfrom pixcorrect import decaminfo\nfrom pixcorrect.null_weights import null_weights\n\n# Which section of the config file to read for this step\nconfig_section = 'skysubtract'\n\nclass SkySubtract(PixCorrectImStep):\n description = \"Subtract sky from images based on principal-component fit and calculate\" +\\\n \" weight image\"\n\n step_name = config_section\n config_section = config_section\n\n @classmethod\n @do_once(1, 'DESSKYSB')\n def __call__(cls, image, fit_filename, pc_filename, weight, dome, skymodel_filename):\n \"\"\"\n Subtract sky from image using previous principal-components fit. Optionally\n build weight image from fitted sky or all counts, in which case the dome flat\n is needed and proper gain values are expected in the image header.\n\n :Parameters:\n - `image`: DESImage that has been flattened with dome already and fit\n - `fit_filename`: filename with the coefficients from minisky fitting. Sky\n subtraction is skipped if this is None.\n - `pc_filename`: filename for the stored full-res sky principal components\n - `weight`: 'none' to skip weights, 'sky' to calculate weight at sky level,\n 'all' to use all counts\n - `dome`: DESImage for the dome flat, needed if weight is not 'none'.\n - `skymodel_filename`: optional output filename for 'sky'\n \"\"\"\n\n if weight == 'sky' and fit_filename is None:\n raise SkyError('Cannot make sky-only weight map without doing sky subtraction')\n\n if fit_filename is not None:\n logger.info('Subtracting sky')\n mini = skyinfo.MiniDecam.load(fit_filename)\n templates = skyinfo.SkyPC.load(pc_filename)\n if templates.detpos != image['DETPOS']:\n # Quit if we don't have the right CCD to subtract\n logger.error('Image DETPOS {:s} does not match sky template {:s}'.format(\n templates.detpos, image['DETPOS']))\n return 1\n try:\n image['BAND']\n except:\n image['BAND'] = decaminfo.get_band(image['FILTER'])\n try:\n items_must_match(image, mini.header, 'BAND', 'EXPNUM')\n items_must_match(image, templates.header, 'BAND')\n # ??? Could check that template and image use same dome flat\n except:\n return 1\n sky = templates.sky(mini.coeffs)\n image.data -= sky\n image.write_key('SKYSBFIL', path.basename(pc_filename), comment='Sky subtraction template file')\n for i, c in enumerate(mini.coeffs):\n image.write_key('SKYPC{:>02d}'.format(i), c, comment='Sky template coefficient')\n logger.info('Finished sky subtraction')\n#\n# Optionally write the sky model that was subtracted from the image.\n#\n if skymodel_filename is not None:\n # Create HDU for output skymodel, add some header info, save output to file\n logger.info('Optional output of skymodel requested')\n skymodel_image = DESDataImage(sky)\n skymodel_image.write_key('SKYSBFIL', path.basename(pc_filename), comment='Sky subtraction template file')\n for i, c in enumerate(mini.coeffs):\n skymodel_image.write_key('SKYPC{:>02d}'.format(i), c, comment='Sky template coefficient')\n skymodel_image.write_key('BAND', image['BAND'], comment='Band')\n skymodel_image.write_key('EXPNUM', image['EXPNUM'], comment='Exposure Number')\n skymodel_image.write_key('CCDNUM', image['CCDNUM'], comment='CCD Number')\n skymodel_image.write_key('NITE', image['NITE'], comment='Night')\n# skymodel_image.copy_header_info(image, cls.propagate, require=False)\n ## ?? catch exception from write error below?\n skymodel_image.save(skymodel_filename)\n\n else:\n sky = None\n\n if weight == 'none':\n do_weight = False\n sky_weight = False\n elif weight == 'sky':\n do_weight = True\n sky_weight = True\n elif weight == 'all':\n do_weight = True\n sky_weight = False\n else:\n raise SkyError('Invalid weight value: ' + weight)\n\n if do_weight:\n if dome is None:\n raise SkyError('sky_subtract needs dome flat when making weights')\n\n if sky_weight:\n logger.info('Constructing weight image from sky image')\n data = sky\n else:\n logger.info('Constructing weight image from all counts')\n if sky is None:\n # If we did not subtract a sky, the image data gives total counts\n data = image.data\n else:\n # Add sky back in to get total counts\n data = image.data + sky\n\n if image.weight is not None or image.variance is not None:\n image.weight = None\n image.variance = None\n logger.warning('Overwriting existing weight image')\n\n \"\"\"\n We assume in constructing the weight (=inverse variance) image that\n the input image here has been divided by the dome flat already, and that\n its GAIN[AB] keywords are correct for a pixel that has been divided\n by the FLATMED[AB] of the flat image. So the number of *electrons* that\n were read in a pixel whose current value=sky is\n e = sky * (dome/FLATMED) * GAIN\n\n\n The variance has three parts: read noise, and sky Poisson noise, and\n multiplicative errors from noise in the flat field.\n The read noise variance, in electrons, is\n Var = RDNOISE^2\n ...and the shot noise from sky was, in electrons,\n Var = sky * (dome/FLATMED) * GAIN\n\n This means the total variance in the image, in its present form, is\n\n Var = (RDNOISE * FLATMED / dome / GAIN)^2 + (FLATMED/GAIN)*sky/dome\n\n We can also add the uncertainty propagated from shot noise in the dome flat,\n if the dome image has a weight or variance. In which case we would add\n\n Var += var(dome) * sky^2 / dome^2\n\n (remembering that sky has already been divided by the dome).\n\n If sky_weight = False, we can substitute the image data for sky in the above\n calculations.\n \"\"\"\n\n # Transform the sky image into a variance image\n var = np.array(data, dtype=weight_dtype)\n for amp in decaminfo.amps:\n sec = section2slice(image['DATASEC' + amp])\n invgain = (image['FLATMED' + amp] / image['GAIN' + amp]) / dome.data[sec]\n var[sec] += image['RDNOISE'+amp]**2 * invgain\n var[sec] *= invgain\n # Add noise from the dome flat shot noise, if present\n if dome.weight is not None:\n var += data * data / (dome.weight * dome.data * dome.data)\n elif dome.variance is not None:\n var += data * data * dome.variance / (dome.data * dome.data)\n\n image.variance = var\n\n # Now there are statistics desired for the output image header.\n # First, the median variance at sky level on the two amps, SKYVAR[AB]\n meds = []\n for amp in decaminfo.amps:\n sec = section2slice(image['DATASEC' + amp])\n v = np.median(var[sec][::4, ::4])\n image.write_key('SKYVAR' + amp, v,\n comment='Median noise variance at sky level, amp ' + amp)\n meds.append(v)\n # SKYSIGMA is overall average noise level\n image.write_key('SKYSIGMA', np.sqrt(np.mean(meds)),\n comment='RMS noise at sky level')\n # SKYBRITE is a measure of sky brightness. Use the sky image if we've got it, else\n # use the data\n if sky is None:\n skybrite = np.median(data[::4, ::4])\n else:\n skybrite = np.median(sky[::2, ::2])\n image.write_key('SKYBRITE', skybrite, comment='Median sky brightness')\n\n logger.debug('Finished weight construction')\n\n # Run null_mask or resaturate if requested in the command-line\n if cls.do_step('null_mask') or cls.do_step('resaturate'):\n logger.info(\"Running null_weights\")\n # We need to fix the step_name if we want to call 'step_run'\n null_weights.__class__.step_name = config_section\n #null_weights.__class__.step_name = cls.config_section\n null_weights.step_run(image, cls.config)\n\n ret_code = 0\n return ret_code\n\n @classmethod\n def step_run(cls, image, config):\n \"\"\"Customized execution for sky subtraction\n\n :Parameters:\n - `config`: the configuration from which to get other parameters\n\n \"\"\"\n\n # Passing config to the class\n cls.config = config\n\n if config.has_option(cls.step_name, 'fitfilename'):\n fit_filename = config.get(cls.step_name, 'fitfilename')\n else:\n fit_filename = None\n\n if config.has_option(cls.step_name, 'pcfilename'):\n pc_filename = config.get(cls.step_name, 'pcfilename')\n else:\n pc_filename = None\n\n weight = config.get(cls.step_name, 'weight')\n\n if config.has_option(cls.step_name, 'domefilename'):\n dome_filename = config.get(cls.step_name, 'domefilename')\n dome = DESImage.load(dome_filename)\n else:\n dome = None\n\n if config.has_option(cls.step_name, 'skymodel'):\n skymodel_filename = config.get(cls.step_name, 'skymodel')\n else:\n skymodel_filename = None\n\n logger.info('Sky fitting output to %s', image)\n\n ret_code = cls.__call__(image, fit_filename, pc_filename,\n weight, dome, skymodel_filename)\n return ret_code\n\n @classmethod\n def add_step_args(cls, parser):\n \"\"\"Add arguments specific to sky compression\n \"\"\"\n parser.add_argument('--fitfilename', type=str,\n help='Filename for minisky FITS image with PC coefficients')\n parser.add_argument('--pcfilename', type=str,\n help='Filename for full-res sky principal components')\n parser.add_argument('--domefilename', type=str,\n help='Filename for dome flat (for weight calculation)')\n parser.add_argument('--weight', choices=('sky', 'all', 'none'),\n default=skyinfo.DEFAULT_WEIGHT,\n help='Construct weight from sky photons, ' \\\n 'from all photons, or not at all')\n parser.add_argument('--skymodel', type=str,\n help='Optional output file showing the model sky that was subtracted.')\n # Adding the null_weights options\n null_weights.add_step_args(parser)\n\n @classmethod\n def do_step(cls, step_name):\n if not cls.config.has_option(cls.config_section, step_name):\n return False\n\n try:\n # If the parameter is a boolean, interpret is\n # as an on/off switch\n doit = cls.config.getboolean(cls.config_section, step_name)\n return doit\n except:\n # Otherwise, interpret it as a value associated with\n # the step, and assume we want to perform the step\n return True\n\n\nsky_subtract = SkySubtract()\n\n# internal functions & classes\n\nif __name__ == '__main__':\n sky_subtract.main()\n","sub_path":"python/pixcorrect/sky_subtract.py","file_name":"sky_subtract.py","file_ext":"py","file_size_in_byte":12556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"411993711","text":"from alerting import Alerting\r\n\r\n\r\nclass Service:\r\n alert_mute = False\r\n alert_count = 0\r\n name = ''\r\n status = 'service is OK'\r\n alerting_stop = False\r\n wait2upservice = False\r\n alerting_status = 'active'\r\n alert = Alerting()\r\n\r\n def make_mute(self):\r\n self.alert_mute = True\r\n\r\n def make_alert_stop(self):\r\n self.alerting_stop = True\r\n self.alerting_status = 'waiting to service up'\r\n\r\n def make_alert_continue(self):\r\n self.alerting_stop = False\r\n self.alerting_status = 'active'\r\n\r\n def alerting_status_active(self):\r\n self.alerting_status = 'active'\r\n\r\n def alert_send(self, des):\r\n if not self.alerting_stop:\r\n if not self.alert_mute:\r\n self.alert.alert_send(des)\r\n self.alert_count = self.alert_count + 1\r\n if self.alert_count > 1:\r\n self.make_alert_stop()\r\n print(\"count greater than 2\")\r\n self.alert.alert_send(\"waiting to come up\")\r\n self.wait2upservice = True\r\n self.alert_count = 0\r\n\r\n\r\n\r\n","sub_path":"service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"119305282","text":"import tensorflow as tf\nimport numpy as np\nimport cv2\n\nfrom tqdm import tqdm_notebook as tqdm\n\nfrom tensorflow.keras.models import Model, load_model\n\ntf.enable_eager_execution()\n\ndef InitializeImage(img_in_path):\n\n tensor2 = cv2.imread(img_in_path, 0).astype('float32')\n tensor3 = tf.keras.backend.expand_dims(tensor2, axis=-1)\n tensor4 = tf.keras.backend.expand_dims(tensor3, axis=0) / 255.\n\n return tensor2, tensor4\n\ndef ConvLayerActivMaps(model_load_path, img_in_path, img_out_path, input_layer_name, conv_layer_name, num_of_filters):\n\n raw_image, img_tensor = InitializeImage(img_in_path=img_in_path)\n\n model = load_model(model_load_path)\n\n conv_layer = Model(inputs=model.get_layer(name=input_layer_name).input, outputs=model.get_layer(name=conv_layer_name).output)\n\n conv_layer_output = conv_layer(img_tensor)\n\n nulls = len(str(num_of_filters))\n\n empty_image = np.zeros(raw_image.shape, dtype=np.float32)\n\n for filter_index in tqdm(range(num_of_filters), desc=conv_layer_name + ' activ. maps visualisation:', leave=True):\n\n act_tensor = conv_layer_output[:, :, :, filter_index].numpy()\n\n act_matrix = act_tensor[0, :, :]\n\n normalized = cv2.normalize(act_matrix, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)\n resized = cv2.resize(normalized, raw_image.shape)\n\n bgr_act_map = cv2.merge((empty_image, resized, empty_image))\n bgr_raw_img = cv2.merge((raw_image, resized, empty_image))\n\n bordered_bgr = cv2.copyMakeBorder(bgr_act_map, top=4, bottom=4, left=4, right=2, borderType=cv2.BORDER_CONSTANT, value=255)\n bordered_raw = cv2.copyMakeBorder(bgr_raw_img, top=4, bottom=4, left=2, right=4, borderType=cv2.BORDER_CONSTANT, value=255)\n \n both = np.concatenate((bordered_bgr, bordered_raw), axis=1)\n\n ind = str(filter_index + 1).zfill(nulls)\n\n cv2.imwrite(img_out_path + conv_layer_name + '_activation_map_' + ind + '.png', both)\n\nvisexp_activ_maps = ConvLayerActivMaps(model_load_path='/saved/model/directory/model.h5',\n img_out_path='/activation/maps/save/directory/',\n img_in_path='input/image/path.png',\n input_layer_name='model_input_layer',\n conv_layer_name='x_conv_layer_to_output_activation_maps',\n num_of_features=1024) #Number of the named gap layer filters.\n","sub_path":"Visualisation/ConvLayerActivMaps_v3.6.0.py","file_name":"ConvLayerActivMaps_v3.6.0.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"21451472","text":"#!/usr/bin/env python\nimport sys\n\nfor line in sys.stdin:\n line=line.strip()\n key_value=line.split(\",\")\n key_in= key_value[0].split(\" \")\n key_in=''.join(key_in)\n value=key_value[1]\n print('%s\\t%s'%(key_in, value))\n\n\n\n","sub_path":"cloudera/groupby.py","file_name":"groupby.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"287752563","text":"import socket\nimport sys\n\n# Create a UDP socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nserver_address = ('localhost', 5000)\nmessage = \"msg\"\n\ntry:\n\n # Send data\n print >>sys.stderr, 'sending \"%s\"' % message\n sent = sock.sendto(message, server_address)\n \n print >>sys.stderr, 'waiting to receive'\n data, server = sock.recvfrom(4096)\n print >>sys.stderr, 'received \"%s\"' % data\n\n sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n server_address2 = ('localhost', int(data))\n \n n1 = raw_input(\"n1= \")\n n2 = raw_input(\"n2= \")\n \n sent = sock2.sendto(n1, server_address2)\n sent = sock2.sendto(n2, server_address2)\n \n data, server = sock2.recvfrom(4096)\n \n print (data)\n \nfinally:\n print >>sys.stderr, 'closing socket'\n sock.close()","sub_path":"third semester/compnet/labs/udp-python/concurent/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"366917642","text":"__version__ = '1.2.0'\n\nfrom collections import OrderedDict, defaultdict\n\nfrom spacy.tokens import Doc, Span\n\n# NOTE: SpacyConllParser is deprecated\n# import here for backward-compatibility\nfrom spacy_conll.SpacyConllParser import Spacy2ConllParser\n\n\nclass ConllFormatter:\n \"\"\" Pipeline component for spaCy that adds CoNLL-U properties to a Doc and\n its sentences. A string representation, representation including a\n header, and the CoNLL-U format in tuples, are added as custom attributes.\"\"\"\n name = 'conll_formatter'\n\n def __init__(self,\n nlp,\n *,\n ext_names=None,\n field_names=None,\n conversion_maps=None\n ):\n \"\"\" ConllFormatter constructor. The names of the extensions that are set\n can be changed with '*_attr' arguments.\n\n :param nlp: an initialized spaCy nlp object\n :param ext_names: dictionary containing names for the custom spaCy extensions\n :param field_names: dictionary containing names for the CoNLL fields\n :param conversion_maps: two-level dictionary that contains a field_name (e.g. 'lemma', 'upostag')\n on the first level, and the conversion map on the second.\n E.g. {'lemma': {'-PRON-': 'PRON'}} will map the lemma '-PRON-' to 'PRON'\n \"\"\"\n # To get the morphological info, we need a tag map\n self._tagmap = nlp.Defaults.tag_map\n\n # Set custom attribute names\n self._ext_names = {\n 'conll_str': 'conll_str',\n 'conll_str_headers': 'conll_str_headers',\n 'conll': 'conll'\n }\n if ext_names:\n self._ext_names = self._merge_dicts_strict(self._ext_names, ext_names)\n\n self._field_names = OrderedDict({\n 'id': 'id',\n 'form': 'form',\n 'lemma': 'lemma',\n 'upostag': 'upostag',\n 'xpostag': 'xpostag',\n 'feats': 'feats',\n 'head': 'head',\n 'deprel': 'deprel',\n 'deps': 'deps',\n 'misc': 'misc'\n })\n\n if field_names:\n self._field_names = self._merge_dicts_strict(self._field_names, field_names)\n\n self._conversion_maps = conversion_maps\n\n # Initialize extensions\n self._set_extensions()\n\n def __call__(self, doc):\n \"\"\" Runs the pipeline component, adding the extensions to ._..\n Adds a string representation, string representation containing a header,\n and a tuple representation of the CoNLL format to the given Doc and its\n sentences.\n\n :param doc: the input Doc\n :return: the modified Doc containing the newly added extensions\n \"\"\"\n # We need to hook the extensions again when using\n # multiprocessing in Windows\n # see: https://github.com/explosion/spaCy/issues/4903\n self._set_extensions()\n\n conll_strs = []\n conll_strs_w_headers = []\n conlls = []\n for sent_idx, sent in enumerate(doc.sents, 1):\n conll_str, conll_str_w_headers, conll = self._get_span_conll(sent, sent_idx)\n conll_strs.append(conll_str)\n conll_strs_w_headers.append(conll_str_w_headers)\n conlls.append(conll)\n\n sent._.set(self._ext_names['conll_str'], conll_str)\n sent._.set(self._ext_names['conll_str_headers'], conll_str_w_headers)\n sent._.set(self._ext_names['conll'], conll)\n\n doc._.set(self._ext_names['conll_str'], '\\n'.join(conll_strs))\n doc._.set(self._ext_names['conll_str_headers'], '\\n'.join(conll_strs_w_headers))\n doc._.set(self._ext_names['conll'], conlls)\n\n return doc\n\n def _get_span_conll(self, span, span_idx=1):\n \"\"\" Converts a span's properties into CoNLL-U format.\n\n :param span: a spaCy Span\n :param span_idx: optional index, corresponding to the n-th sentence\n in the parent Doc\n :return: a string representation, string representation containing a header,\n and a list of tuples representation of the CoNLL format of 'span'\n \"\"\"\n conll_str_w_headers = f\"# sent_id = {span_idx}\\n# text = {span.text}\\n\"\n\n conll_str = ''\n conll = defaultdict(list)\n for word_idx, word in enumerate(span, 1):\n if word.dep_.lower().strip() == 'root':\n head_idx = 0\n else:\n head_idx = word.head.i + 1 - span[0].i\n\n token_conll = (\n word_idx,\n word.text,\n word.lemma_,\n word.pos_,\n word.tag_,\n self._get_morphology(word.tag_),\n head_idx,\n word.dep_,\n '_',\n '_'\n )\n\n token_conll_d = dict(zip(self._field_names.values(), token_conll))\n\n if self._conversion_maps:\n token_conll_d = self._map_conll(token_conll_d)\n token_conll = token_conll_d.values()\n\n for column_name, v in token_conll_d.items():\n conll[column_name].append(v)\n\n conll_str += '\\t'.join(map(str, token_conll)) + '\\n'\n\n conll_str_w_headers += conll_str\n\n return conll_str, conll_str_w_headers, dict(conll)\n\n def _get_morphology(self, tag):\n \"\"\" Expands a tag into its morphological features by using a tagmap.\n\n :param tag: the tag to expand\n :return: a string entailing the tag's morphological features\n \"\"\"\n if not self._tagmap or tag not in self._tagmap:\n return '_'\n else:\n feats = [f\"{prop}={val}\" for prop, val in self._tagmap[tag].items() if not self._is_number(prop)]\n if feats:\n return '|'.join(feats)\n else:\n return '_'\n\n def _map_conll(self, token_conll_d):\n \"\"\" Maps labels according to a given `self._conversion_maps`.\n This can be useful when users want to change the output labels of a\n model to their own tagset.\n\n :param token_conll_d: a token's conll representation as dict (field_name: value)\n :return: the modified dict where the labels have been replaced according to the converison maps\n \"\"\"\n for k, v in token_conll_d.items():\n try:\n token_conll_d[k] = self._conversion_maps[k][v]\n except KeyError:\n continue\n\n return token_conll_d\n\n def _set_extensions(self):\n \"\"\" Sets the default extensions if they do not exist yet. \"\"\"\n for obj in Span, Doc:\n if not obj.has_extension(self._ext_names['conll_str']):\n obj.set_extension(self._ext_names['conll_str'], default=None)\n if not obj.has_extension(self._ext_names['conll_str_headers']):\n obj.set_extension(self._ext_names['conll_str_headers'], default=None)\n if not obj.has_extension(self._ext_names['conll']):\n obj.set_extension(self._ext_names['conll'], default=None)\n\n\n @staticmethod\n def _is_number(s):\n \"\"\" Checks whether a string is actually a number.\n :param s: string to test\n :return: whether or not 's' is a number\n \"\"\"\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n @staticmethod\n def _merge_dicts_strict(d1, d2):\n \"\"\" Merge two dicts in a strict manner, i.e. the second dict overwrites keys\n of the first dict but all keys in the second dict have to be present in\n the first dict.\n :param d1: base dict which will be overwritten\n :param d2: dict with new values that will overwrite d1\n :return: the merged dict (but d1 will be modified in-place anyway!)\n \"\"\"\n for k, v in d2.items():\n if k not in d1:\n raise KeyError(f\"This key does not exist in the original dict. Valid keys are {list(d1.keys())}\")\n d1[k] = v\n\n return d1\n","sub_path":"spacy_conll/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"154126577","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow.contrib import rnn\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"./mnist_data/\", one_hot=True)\n\nX = tf.placeholder(tf.float32, [None, 28, 28])\ny = tf.placeholder(tf.float32, [None, 10])\n\n\ndef BiRNN(x):\n out_W = tf.Variable(tf.random_normal([128 * 2, 10]))\n out_H = tf.Variable(tf.random_normal([10]))\n\n x = tf.unstack(x, 28, 1)\n lstm_fw_cell = rnn.BasicLSTMCell(128, forget_bias=1.0)\n lstm_bw_cell = rnn.BasicLSTMCell(128, forget_bias=1.0)\n\n outputs, _, _ = rnn.static_bidirectional_rnn(\n lstm_fw_cell, lstm_bw_cell, x, dtype=tf.float32)\n return tf.matmul(outputs[-1], out_W) + out_H\n\n\nlogits = BiRNN(X)\npred = tf.nn.softmax(logits=logits)\n\nloss_op = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\ntrain_op = tf.train.AdamOptimizer(0.001).minimize(loss_op)\n\ncorrect_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(1000):\n batch_x, batch_y = mnist.train.next_batch(128)\n batch_x = batch_x.reshape((128, 28, 28))\n sess.run(train_op, feed_dict={X: batch_x, y: batch_y})\n if i % 100 == 0:\n loss_curr, acc_curr = sess.run(\n [loss_op, accuracy], feed_dict={\n X: batch_x,\n y: batch_y\n })\n\n print(\"Step \" + str(i) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss_curr) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(acc_curr))\n","sub_path":"bidirectional_rnn.py","file_name":"bidirectional_rnn.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"609632675","text":"from Products.CMFCore.permissions import AddPortalContent\nfrom Products.Archetypes.public import DisplayList\nfrom bika.lims import bikaMessageFactory as _\n\nADD_CONTENT_PERMISSION = AddPortalContent\nPROJECTNAME = \"bika.lims\"\n\nGLOBALS = globals()\n\n# Very Old permissions:\nManageBika = 'BIKA: Manage Bika'\nManageClients = 'BIKA: Manage Clients'\nManageWorksheets = 'BIKA: Manage Worksheets'\nManageOrders = 'BIKA: Manage Orders'\nDispatchOrder = 'BIKA: Dispatch Order'\nManageAnalysisRequests = 'BIKA: Manage Analysis Requests'\nManageARImport = 'BIKA: Manage ARImport'\nManageSample = 'BIKA: Manage Sample'\nManageReferenceSuppliers = 'BIKA: Manage Reference Suppliers'\nManageReference = 'BIKA: Manage Reference'\nPostInvoiceBatch = 'BIKA: Post Invoice batch'\nManagePricelists = 'BIKA: Manage Pricelists'\n# New or changed permissions:\nReceiveSample = 'BIKA: Receive Sample'\nExpireSample = 'BIKA: Expire Sample'\nDisposeSample = 'BIKA: Dispose Sample'\nImportAnalysis = 'BIKA: Import Analysis'\nRejectWorksheet = 'BIKA: Reject Worksheet'\nRetract = \"BIKA: Retract\"\nVerify = 'BIKA: Verify'\nVerifyOwnResults = 'BIKA: Verify own results'\nPublish = 'BIKA: Publish'\nEditSample = 'BIKA: Edit Sample'\nEditAR = 'BIKA: Edit AR'\nEditWorksheet = 'BIKA: Edit Worksheet'\nManageResults = 'BIKA: Manage Results'\nResultsNotRequested = 'BIKA: Results not requested'\nManageInvoices = 'BIKA: Manage Invoices'\nViewResults = 'BIKA: View Results'\nEditResults = 'BIKA: Edit Results'\nCancelAndReinstate = 'BIKA: Cancel and reinstate'\n\nVERSIONABLE_TYPES = ('AnalysisService',\n 'Calculation',\n 'SamplePoint',\n 'SampleType',\n 'AnalysisSpec',\n 'WorksheetTemplate',\n )\n\nBIKA_PERMISSIONS = (\n (ManageBika, ()),\n (ManageClients, ()),\n (ManageWorksheets, ()),\n (ManageOrders, ()),\n (ManageAnalysisRequests, ()),\n (ManageSample, ()),\n (ManageReferenceSuppliers, ()),\n (ManageReference, ()),\n (ManagePricelists, ()),\n (ManageARImport, ()),\n (DispatchOrder, ()),\n (PostInvoiceBatch, ()),\n (ReceiveSample, ()),\n (ExpireSample, ()),\n (DisposeSample, ()),\n (ImportAnalysis, ()),\n (RejectWorksheet, ()),\n (Retract, ()),\n (Verify, ()),\n (VerifyOwnResults, ()),\n (Publish, ()),\n (EditSample, ()),\n (EditAR, ()),\n (EditWorksheet, ()),\n (ManageResults, ()),\n (ResultsNotRequested, ()),\n (ManageInvoices, ()),\n (ViewResults, ()),\n (EditResults, ()),\n (CancelAndReinstate, ()),\n)\n\n\nPUBLICATION_PREFS = DisplayList((\n ('email', _('Email')),\n ('fax', _('Fax')),\n ('file', _('File')),\n ('pdf', _('PDF')),\n ('print', _('Print')),\n ('sms', _('SMS')),\n))\n\nPOINTS_OF_CAPTURE = DisplayList((\n ('field', _('Field Analyses')),\n ('lab', _('Lab Analyses')),\n))\n\nSERVICE_POINT_OF_CAPTURE = DisplayList((\n ('field', _('Field')),\n ('lab', _('Lab')),\n))\n\nPRESERVATION_CATEGORIES = DisplayList((\n ('field', _('Field Preservation')),\n ('lab', _('Lab Preservation')),\n))\n\nPRICELIST_TYPES = DisplayList((\n ('AnalysisService', _('Analysis Services')),\n ('LabProduct', _('Lab Products')),\n))\n\nCLIENT_TYPES = DisplayList((\n ('corporate', 'Bulk Discount'),\n ('noncorporate', 'Standard Price'),\n))\n\nANALYSIS_TYPES = DisplayList((\n ('a', _('Analysis')),\n ('b', _('Blank')),\n ('c', _('Control')),\n ('d', _('Duplicate')),\n))\nSTD_TYPES = DisplayList((\n ('c', _('Control')),\n ('b', _('Blank')),\n))\nATTACHMENT_OPTIONS = DisplayList((\n ('r', _('Required')),\n ('p', _('Permitted')),\n ('n', _('Not Permitted')),\n))\nARIMPORT_OPTIONS = DisplayList((\n ('c', _('Classic')),\n ('p', _('Profiles')),\n ('s', _('Special')),\n))\nEMAIL_SUBJECT_OPTIONS = DisplayList((\n ('ar', _('Analysis Request ID')),\n ('co', _('Order ID')),\n ('cr', _('Client Reference')),\n ('cs', _('Client Sample ID')),\n))\n\nGENDERS = DisplayList((\n ('male', _('Male')),\n ('female', _('Female')),\n ))\n\nADDRESS_TYPES = DisplayList((\n ('physical', _('Physical address')),\n ('mailing', _('Mailing address')),\n ('billing', _('Billing address')),\n ('shipping', _('Shipping address')),\n ))\n","sub_path":"bika/lims/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"259976785","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import *\n\n\n# Create your views here.\ndef index(request):\n bullies = Bully.objects.all().order_by('-votes')\n return render(request, 'index.html', {\"bullies\":bullies})\n\n\ndef new(request, name):\n ip = get_client_ip(request)\n ipRecord = IPAddress.objects.filter(address=ip)\n if not canVote(ip, ipRecord, name):\n return HttpResponse(\"not allowed to vote\")\n\n # vote for the bully or create a new bully class\n bully = Bully.objects.filter(name__iexact=name)\n if bully.exists():\n bully.votes = bully.votes + 1\n bully.save()\n else:\n Bully(\n name=name,\n votes=1\n ).save()\n return HttpResponse(\"saved\")\n\n\ndef vote(request, name):\n ip = get_client_ip(request)\n ipRecord = IPAddress.objects.filter(address=ip)\n if not canVote(ip, ipRecord, name):\n return HttpResponse(\"not allowed to vote\")\n\n bully = Bully.objects.get(name=name)\n bully.votes += 1\n bully.save()\n return HttpResponse(\"voted\")\n\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef canVote(ip, ipRecord, bully):\n if ipRecord.exists():\n ipRecord = ipRecord.get(address=ip)\n bullies = ipRecord.bullies.split(\",\")\n if bully in bullies:\n print(\"not allowed\")\n return False\n else:\n print(\"allowed\")\n bullies.append(bully)\n ipRecord.bullies = \",\".join(bullies)\n ipRecord.save()\n return True\n else:\n record = IPAddress(\n address=ip,\n bullies=bully\n )\n record.save()\n print(\"totally allowed\")\n return True\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"411566869","text":"from __future__ import print_function\nimport sys\nimport re\nimport json\n\n__DEFAULT_ROUT__ = \"placements-frontend/conf/routes\"\n__DEFAULT_PK__ = \"placements-frontend/pk.json\"\n__ACTIONS__ = {\"GET\", \"POST\", \"->\"}\n__EXIT_STATUS__ = {True: 0, False: -1}\n__NO_PK__ = {'@noPageKeyNeeded'}\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\ndef extract_page_keys(routes_file_path=__DEFAULT_ROUT__, output_path=__DEFAULT_PK__):\n no_error = True\n errors = list()\n warns = list()\n page_keys = dict()\n with open(routes_file_path) as f:\n content = f.readlines()\n for idx, line in enumerate(content):\n line = line.strip()\n words = line.split()\n if len(words) > 0 and words[0] in __ACTIONS__:\n line = re.sub(r\" +\", \"\\t\", line)\n # the previous line must have the page key\n last_line = content[idx - 1]\n if not last_line.startswith(\"#\"):\n errors.append(\"Line {} : No PageKey for {}\".format(idx + 1, line))\n no_error = no_error and False\n continue\n c_words = last_line.split()\n if not c_words[1].startswith(\"@\"):\n errors.append(\"Line {} : No PageKey for {}\".format(idx + 1, line))\n no_error = no_error and False\n continue\n if c_words[1] in __NO_PK__:\n warns.append(\"Line {} : {} is defined as PageKey for {}\".format(idx + 1, c_words[1], line))\n continue\n if c_words[2] in page_keys:\n # duplicate page key\n errors.append(\"Line {} : Duplicate PageKey for {}\".format(idx + 1, line))\n no_error = no_error and False\n continue\n page_keys[c_words[2]] = words[1]\n print('{}\\t{}'.format(c_words[2], words[1]))\n pass\n # log errors\n if not no_error:\n eprint(\"Following Errors Were generated:\")\n for e in errors:\n eprint(e)\n # log warnings\n if len(warns) > 0:\n print(\"\\n====WARNING====\\n\")\n for w in warns:\n print(w)\n # dump json\n json_str = json.dumps(page_keys)\n with open(output_path, \"w\") as text_file:\n text_file.write(json_str)\n return no_error\n pass\n\n\nif \"__main__\" == __name__:\n sys.exit(__EXIT_STATUS__[extract_page_keys()])\n","sub_path":"placements-frontend/test/py/ExtractPageKeys.py","file_name":"ExtractPageKeys.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"128752900","text":"'''\nCreated on Nov 10, 2015\n\n@author: ssood26\n'''\n\nimport threading\nimport time\nimport multithreading\n\nexitFlag = 0\n\nclass myThread(threading.Thread):\n def __init__(self,threadId,name,counter):\n #need to call the init constructor of the parent Thread class\n threading.Thread.__init__(self)\n self.threadID=threadId\n self.name = name\n self.counter = counter\n \n #override the run method of the Thread class \n def run(self):\n print(\"Starting:\",self.name)\n multithreading.print_time(self.name,self.counter)\n print(\"Exiting\",self.name)\n \ndef runMain():\n #creating new threads\n thread1 = myThread(1,\"Thread-1\",1)\n thread2 = myThread(2,\"Thread-2\",2)\n \n\n ##When a python file is executed it is assigned a name. The initial file that is \n #executed via \"python file.py\" is assigned the name \"main\" and it is stored under \n #the variable __name__. In other cases, say the file is imported (\"import file\") \n #then __name__ is assigned a different name.\n\n#Now \n#if __name__ == \"main\":\n#is used to execute some code only if the file was run directly, and not imported. \n\nif __name__ == '__main__':\n print(\"I am main\")\nrunMain()","sub_path":"Python/PythonDevelopment/pysrc/ThreadingMainModule.py","file_name":"ThreadingMainModule.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"16763654","text":"#!/bin/python\r\nimport socket, string, time, random, sys, subprocess\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.connect((\"insomnia247.nl\", 5015))\r\nnickname = \"SaladBot\"\r\npassword = \"\" # Bot's NickServ password goes here\r\nadminpass = \"authpl0x\" # Bot's auth password\r\nchannels = [\"#moontest\",\"#mtcm\",\"##pingpong\",\"#main\"]\r\npublic = [\"!auth\",\"!ninja\",\"#hashtag\",\"!time\",\"!say\",\"PING\",\"PONG\",nickname + \"!\",\"XD\",nickname + \": you suck\"]\r\nlog = 1\r\ngrant = []\r\nchan1 = \"\"\r\nchan2 = \"\"\r\nword1 = \"\"\r\nword2 = \"\"\r\nchanset = channels[0]\r\nadmins = [\"zsoltisawesome\",\"zsoltisawesome_\",\"zsoltisawesome__\"]\r\nreadbuffer = \"\"\r\ns.send(\"USER %s %s %s %s \\n\" % (nickname, nickname, nickname, nickname))\r\ns.send(\"NICK %s \\n\" % nickname)\r\ns.send(\"PRIVMSG NickServ :IDENTIFY %s \\n\" % password)\r\nfor i in channels:\r\n s.send(\"JOIN %s \\n\" % i)\r\n#########################\r\nclass irc(object):\r\n def join(self, channel):\r\n s.send(\"JOIN %s\\n\" % channel)\r\n def part(self, channel):\r\n s.send(\"PART %s :OMG, Who turned out the lights!\\n\" % channel)\r\n def say(self, target, message):\r\n s.send(\"PRIVMSG %s :%s\\n\" % (target, message))\r\n irc.logger(message)\r\n def saynick(self, target, message):\r\n s.send(\"PRIVMSG %s :\" % (target) + nick + \": %s\\n\" % (message))\r\n irc.logger(nick + \": %s\\n\" % (message))\r\n def notice(self, target, message):\r\n s.send(\"NOTICE %s :%s\\n\" % (target, message))\r\n def kick(self, nickname, reason=nickname):\r\n s.send(\"KICK %s :%s\\n\" % (nickname, reason))\r\n def op(self, target, nickname):\r\n s.send(\"MODE %s +o %s\\n\" % (target, nickname))\r\n def deop(self, target, nickname):\r\n s.send(\"MODE %s -o %s\\n\" % (target, nickname))\r\n def voice(self, target, nickname):\r\n s.send(\"MODE %s +v %s\\n\" % (target, nickname))\r\n def devoice(self, target, nickname):\r\n s.send(\"MODE %s -v %s\\n\" % (target, nickname))\r\n def ban(self, target, nickname):\r\n s.send(\"MODE %s +b %s\\n\" % (target, nickname))\r\n def unban(self, target, nickname):\r\n s.send(\"MODE %s -b %s\\n\" % (target, nickname))\r\n def nick(self, newnick):\r\n s.send(\"NICK %s\\n\" % newnick)\r\n def quit(self):\r\n s.send(\"QUIT :OMG, Who turned out the lights!\\n\")\r\n def logger(self, loggable):\r\n print(\"[\"+nickname+\"]: \"+loggable+\"\\n\")\r\n f = open(\"log\", \"a\")\r\n f.write(\"[\"+nickname+\"]: \"+loggable+\"\\n\")\r\n f.close()\r\nirc = irc()\r\n#########################\r\nwhile 1:\r\n try: \r\n readbuffer=readbuffer+s.recv(1024)\r\n temp=string.split(readbuffer, \"\\n\")\r\n readbuffer=temp.pop()\r\n rndm = float(\"0.\" + str(random.randint(1,99999999999999999)))\r\n\r\n for msg in temp:\r\n msg=string.rstrip(msg)\r\n\r\n if msg.find('PING') != -1:\r\n s.send('PONG ' + msg.split() [1] + '\\r\\n')\r\n\r\n if msg.split(' ')[1] == \"PRIVMSG\" or msg.split(' ')[1] == \"NOTICE\":\r\n message = ' '.join(msg.split(' ')[3:])[1:]\r\n nick = msg.split('!')[0][1:]\r\n target = msg.split(' ')[2]\r\n #print message, nick, target\r\n if target == nickname:\r\n target = nick\r\n split = message.split()\r\n if len(split) > 0:\r\n cmd = split[0]\r\n if log == 1:\r\n print(\"[Message from \"+target+\"]: \"+nick+\": \"+message+\"\\n\")\r\n f = open(\"log\", \"a\")\r\n f.write(\"[Message from \"+target+\"]: \"+nick+\": \"+message+\"\\n\")\r\n f.close()\r\n\r\n #########################\r\n def gen(number):\r\n if auth() and wordc(number):\r\n return True\r\n\r\n def wordc(num):\r\n if len(split) == num:\r\n return True\r\n\r\n def auth():\r\n if nick in admins:\r\n return True\r\n if nick+\":\"+cmd in grant:\r\n return True\r\n if cmd in public:\r\n return True\r\n #########################\r\n # hmm = str(sys.stdin.readlines())\r\n # s.send(\"PRIVMSG \"+target+\" :\"+hmm)\r\n #########################\r\n if cmd == \"!file\" and len(split) > 1 and auth():\r\n irc.saynick(target, \"Appending to User File!\")\r\n f = open(nick + \".txt\",'a')\r\n f.write(\" \".join(split[1:]) + '\\n')\r\n f.close()\r\n irc.saynick(target, \"Done!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!file\" and gen(1):\r\n irc.saynick(target, \"Argument pl0x!\")\r\n\r\n if cmd == \"!fortune\" and gen(1):\r\n outputs = \"\"\"\"\"\".join(subprocess.check_output(\"fortune\"))\r\n irc.say(target, outputs)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!testcmd\" and gen(1):\r\n if rndm > 0.5:\r\n rndmTxt = \"Leave me alone!\"\r\n else:\r\n rndmTxt = \"Did I miss something?\"\r\n #irc.say(target, rndm)\r\n irc.saynick(target, \"What? \" + rndmTxt)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!ninja\" and gen(2):\r\n irc.say(target, split[1] + \": You have been cut by \" + nick + \"!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n elif cmd == \"!ninja\" and gen(1):\r\n irc.saynick(target, \"Give me someone to cut!\")\r\n\r\n if cmd == \"!salad\" and gen(1):\r\n irc.saynick(target, \"where my name comes from: https://www.youtube.com/watch?v=-KRnCnuE3xU\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n\r\n if cmd == \"!join\" and gen(2):\r\n irc.join(split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!part\" and gen(2):\r\n irc.part(split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!cmd\" and len(split) > 1 and auth():\r\n s.send(\" \".join(split[1:])+\"\\n\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!say\" and len(split) > 1 and auth():\r\n irc.saynick(chanset, \" \".join(split[1:]))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!rev\" and len(split) > 1 and auth():\r\n string = \" \".join(split[1:])\r\n irc.saynick(chanset, string[::-1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!notice\" and len(split) > 1 and auth():\r\n irc.notice(chanset, \" \".join(split[1:]))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!chanset\" and gen(2):\r\n chanset = split[1]\r\n irc.saynick(target, \"chanset = %s\" % chanset)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!chanset\" and gen(1):\r\n chanset = target\r\n irc.saynick(target, \"chanset = %s\" % chanset)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!kick\" and gen(2):\r\n irc.kick(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!op\" and gen(2):\r\n irc.op(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n elif cmd == \"!op\" and gen(1):\r\n irc.op(chanset, nick)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!deop\" and gen(2):\r\n irc.deop(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n elif cmd == \"!deop\" and gen(1):\r\n irc.deop(chanset, nick)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n\r\n if cmd == \"!voice\" and gen(2):\r\n irc.voice(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!devoice\" and gen(2):\r\n irc.devoice(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!ban\" and gen(2):\r\n irc.ban(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!unban\" and gen(2):\r\n irc.unban(chanset, split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n\r\n if cmd == \"!nick\" and gen(2):\r\n irc.nick(split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!ping\" and gen(1):\r\n irc.saynick(target, \"PONG!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!relay\" and gen(3):\r\n chan1 = split[1]\r\n chan2 = split[2]\r\n irc.saynick(target, \"Messages from %s will be relayed to %s\" % (chan1, chan2))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if chan1 != \"\" and chan2 != \"\" and target == chan1:\r\n irc.saynick(chan2, message)\r\n\r\n if cmd == \"!cond\" and gen(3):\r\n word1 = split[1]\r\n word2 = split[2]\r\n irc.saynick(target, \"Messages matching %s will be followed with %s\" % (word1, word2))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if word1 != None and word2 != None and cmd == word1:\r\n irc.saynick(target, word2)\r\n\r\n if cmd == \"!flush\" and gen(1):\r\n chan1 = \"\"\r\n chan2 = \"\"\r\n word1 = \"\"\r\n word2 = \"\"\r\n irc.saynick(target, \"Variables flushed\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!reset\" and gen(1):\r\n public = []\r\n log = 1\r\n grant = []\r\n chan1 = \"\"\r\n chan2 = \"\"\r\n word1 = \"\"\r\n word2 = \"\"\r\n chanset = channels[0]\r\n admins = [\"zsoltisawesome\"]\r\n irc.saynick(target, \"Bot has been reset\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!log\" and gen(1) and log == 0:\r\n log = 1\r\n irc.saynick(target, \"log = 1\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!log\" and gen(1) and log == 1:\r\n log = 0\r\n irc.saynick(target, \"log = 0\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!add\" and gen(3):\r\n grant.append(split[1]+\":\"+split[2])\r\n irc.saynick(target, \"%s can use %s\" % (split[1], split[2]))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!del\" and gen(3):\r\n grant.remove(split[1]+\":\"+split[2])\r\n irc.saynick(target, \"%s can no longer use %s\" % (split[1], split[2]))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!addmod\" and gen(2):\r\n admins.append(split[1])\r\n irc.saynick(target, \"%s added to admins\" % split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!delmod\" and gen(2) and split[1] in admins:\r\n admins.remove(split[1])\r\n irc.saynick(target, \"%s removed from admins\" % split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!auth\" and wordc(2) and split[1] == adminpass:\r\n admins.append(nick)\r\n irc.saynick(target, \"Congrats! You are now a tempadmin!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!pubadd\" and gen(2):\r\n public.append(split[1])\r\n irc.saynick(target, \"%s added as a public command\" % split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n elif cmd == \"!pubdel\" and gen(2) and split[1] in public:\r\n public.remove(split[1])\r\n irc.saynick(target, \"%s is no longer a public command\" % split[1])\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!quit\" and gen(1):\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\") \r\n irc.quit()\r\n time.sleep(5)\r\n exit()\r\n\r\n if cmd == (nickname + \": die\") and gen(2):\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n irc.quit()\r\n time.sleep(5)\r\n exit()\r\n\r\n if cmd == \"PING\" and gen(1):\r\n irc.saynick(target, \"PONG\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"PONG\" and gen(1):\r\n irc.saynick(target, \"PING\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"#hashtag\" and gen(1):\r\n irc.saynick(target, \"Shut up...\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == (nickname + \"!\") and gen(1):\r\n irc.say(target, \"Hi \" + nick + \"!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == (nickname + \": you suck\") and gen(3):\r\n irc.say(target, \":(\")\r\n irc.kick(chanset, nick, \"No, you suck!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!dumb\" and gen(1):\r\n irc.saynick(target, \"DUN DUN DUN!\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == (\"!time\") and gen(1):\r\n localtime = time.asctime(time.localtime(time.time()))\r\n irc.saynick(target, \"It is currently \" + localtime + \" in my timezone\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!help\" and gen(1):\r\n irc.saynick(target, \"Help: http://harpnet.comuv.com/ndrku/\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!dump\" and gen(1):\r\n print(\"message dump: \" + msg)\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!allow\" and gen(1):\r\n irc.say(target, \"Am I allowed in here?\")\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!sum\" and gen(3):\r\n try:\r\n dasum = float(split[1]) + float(split[2])\r\n except ValueError:\r\n continue\r\n irc.saynick(target, \"Sum is: \" + str(dasum))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!dif\" and gen(3):\r\n try:\r\n dadif = float(split[1]) - float(split[2])\r\n except ValueError:\r\n continue\r\n irc.saynick(target, \"Difference is: \" + str(dadif))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!rem\" and gen(3):\r\n if split[2] == \"0\":\r\n irc.saynick(target, \"You think I'm an idiot? I'm not gonna divide by zero!\")\r\n continue\r\n try:\r\n darem = float(split[1]) / float(split[2])\r\n except ValueError:\r\n continue\r\n irc.saynick(target, \"Remainder is: \" + str(darem))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n if cmd == \"!pro\" and gen(3):\r\n try:\r\n dapro = float(split[1]) * float(split[2])\r\n except ValueError:\r\n continue\r\n irc.saynick(target, \"Product is: \" + str(dapro))\r\n irc.logger(nick+\" used the '\"+cmd+\"' command!\")\r\n except KeyboardInterrupt:\r\n irc.quit()\r\n sys.exit()\r\n","sub_path":"sal.py","file_name":"sal.py","file_ext":"py","file_size_in_byte":15213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"205788344","text":"from impacket.ldap.ldaptypes import SR_SECURITY_DESCRIPTOR\nimport ldap3\n\nsid_name_dict = {\n 'S-1-5-10': 'Principal Self',\n 'S-1-3-0': 'Creator Owner',\n 'S-1-1-0': 'Everyone',\n 'S-1-5-18': 'Local System',\n}\n\nrights_dict = {\n 'GenericAll': 983551,\n 'GenericWrite': 131112,\n 'WriteDACL': 262144,\n 'WriteOwner': 524288,\n}\n\nextended_rights = {\n '00299570-246d-11d0-a768-00aa006e0529': 'UserForceChangePassword',\n 'e362ed86-b728-0842-b27d-2dea7a9df218': 'ReadGMSAPassword',\n 'e503b3aa-d05d-44ab-85fa-04fa08251e25': 'ReadLAPSPassword',\n}\n\ndef parse_accesscontrol(security_descriptor, ldap):\n a = SR_SECURITY_DESCRIPTOR()\n a.fromString(security_descriptor)\n\n for ace_b in a['Dacl'].aces:\n ace = parse_ace(ace_b)\n\n name = search_name(ace['sid'], ldap)\n ace['name'] = name\n\n yield ace\n\ndef parse_ace(ace_b):\n ace = {\n 'type': ace_b['TypeName'],\n 'mask': ace_b['Ace']['Mask']['Mask'],\n }\n\n sid = parse_sid(ace_b['Ace']['Sid'])\n ace['sid'] = sid\n\n if ace['type'] in ['ACCESS_ALLOWED_ACE', 'ACCESS_DENIED_ACE']:\n rights = parse_mask(ace['mask'])\n ace['rights'] = rights\n elif ace['type'] in ['ACCESS_ALLOWED_OBJECT_ACE', 'ACCESS_DENIED_OBJECT_ACE']:\n rights = parse_object_ace(ace_b['Ace'])\n ace['rights'] = rights\n\n if ace['type'] in ['ACCESS_ALLOWED_ACE', 'ACCESS_ALLOWED_OBJECT_ACE']:\n ace['type'] = 'ALLOWED'\n elif ace['type'] in ['ACCESS_DENIED_ACE', 'ACCESS_DENIED_OBJECT_ACE']:\n ace['type'] = 'DENIED'\n\n return ace\n\ndef parse_sid(sid_b):\n sid = \"S\"\n sid += \"-\" + str(sid_b['Revision'])\n sid += \"-\" + str(int.from_bytes(sid_b['IdentifierAuthority']['Value'], 'big'))\n for i in range(sid_b['SubAuthorityCount']):\n sid += \"-\" + str(int.from_bytes(sid_b['SubAuthority'][i*4:i*4+4], 'little'))\n\n return sid\n\ndef parse_mask(mask):\n out = []\n\n for r, val in rights_dict.items():\n if mask & val == val:\n out.append(r)\n\n return out\n\ndef parse_object_ace(ace):\n out = []\n\n if len(ace['ObjectType']) == 16:\n b = ace['ObjectType']\n\n guid = b[0:4][::-1].hex() + '-'\n guid += b[4:6][::-1].hex() + '-'\n guid += b[6:8][::-1].hex() + '-'\n guid += b[8:10].hex() + '-'\n guid += b[10:16].hex()\n\n if guid in extended_rights:\n out.append(extended_rights[guid])\n\n return out\n\ndef search_name(sid, ldap):\n if sid in sid_name_dict:\n return sid_name_dict[sid]\n\n ldap[0].search(ldap[1], '(objectsid=%s)' % sid, attributes=ldap3.ALL_ATTRIBUTES)\n for entry in ldap[0].entries:\n try:\n domain = \".\".join([item.split(\"=\", 1)[-1] for item in str(entry['distinguishedName']).split(',') if item.split(\"=\",1)[0].lower() == \"dc\"])\n username = str(entry['sAMAccountName'])\n\n sid_name_dict[sid] = '%s\\\\%s' % (domain, username)\n except ldap3.core.exceptions.LDAPKeyError:\n sid_name_dict[sid] = str(entry['objectCategory'])\n\n return sid_name_dict[sid]\n\n sid_name_dict[sid] = sid\n","sub_path":"lib/adscan/accesscontrol.py","file_name":"accesscontrol.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"175150185","text":"# -*- coding: utf-8 -*-\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom os.path import join, dirname\n\nimport mock\nfrom vkontakte_groups.factories import GroupFactory\n\nimport simplejson as json\nfrom vkontakte_comments.models import Comment\nfrom vkontakte_users.factories import UserFactory, User\nfrom vkontakte_users.tests import user_fetch_mock\nfrom . factories import AlbumFactory, PhotoFactory\nfrom . models import Album, Photo\n\n\nGROUP_ID = 16297716\nALBUM_ID = 154228728\nPHOTO_ID = 280118215\n\nGROUP_CRUD_ID = 59154616\nPHOTO_CRUD_ID = 321155660\nALBUM_CRUD_ID = 180124643\nUSER_AUTHOR_ID = 201164356\n\n\nclass VkontaktePhotosTest(TestCase):\n\n def setUp(self):\n self.objects_to_delete = []\n\n def tearDown(self):\n for object in self.objects_to_delete:\n object.delete(commit_remote=True)\n\n def test_fetch_group_albums(self):\n\n group = GroupFactory(remote_id=GROUP_ID)\n\n self.assertEqual(Album.objects.count(), 0)\n\n albums = group.fetch_albums()\n\n self.assertGreater(len(albums), 0)\n self.assertEqual(Album.objects.count(), len(albums))\n self.assertEqual(albums[0].owner, group)\n\n # check force ordering\n self.assertItemsEqual(albums, Album.objects.order_by('-updated'))\n\n # testing `after` parameter\n after = Album.objects.order_by('-updated')[10].updated\n\n albums_count = Album.objects.count()\n Album.objects.all().delete()\n self.assertEqual(Album.objects.count(), 0)\n\n albums = group.fetch_albums(after=after)\n self.assertEqual(albums.count(), Album.objects.count())\n self.assertLess(albums.count(), albums_count)\n\n # testing `before` parameter\n before = Album.objects.order_by('-updated')[5].updated\n\n albums_count = Album.objects.count()\n Album.objects.all().delete()\n self.assertEqual(Album.objects.count(), 0)\n\n albums = group.fetch_albums(before=before, after=after)\n self.assertEqual(albums.count(), Album.objects.count())\n self.assertLess(albums.count(), albums_count)\n\n def test_fetch_group_photos(self):\n\n group = GroupFactory(remote_id=GROUP_ID)\n album = AlbumFactory(remote_id=ALBUM_ID, owner=group)\n\n self.assertEqual(Photo.objects.count(), 0)\n\n photos = album.fetch_photos(extended=True)\n\n self.assertGreater(len(photos), 0)\n self.assertEqual(Photo.objects.count(), len(photos))\n self.assertEqual(photos[0].owner, group)\n self.assertEqual(photos[0].album, album)\n self.assertGreater(photos[0].likes_count, 0)\n self.assertGreater(photos[0].comments_count, 0)\n\n # testing `after` parameter\n after = Photo.objects.order_by('-date')[4].date\n\n photos_count = Photo.objects.count()\n Photo.objects.all().delete()\n self.assertEqual(Photo.objects.count(), 0)\n\n photos = album.fetch_photos(after=after)\n self.assertEqual(photos.count(), Photo.objects.count())\n self.assertLess(photos.count(), photos_count)\n\n # testing `before` parameter\n before = Photo.objects.order_by('-date')[2].date\n\n photos_count = Photo.objects.count()\n Photo.objects.all().delete()\n self.assertEqual(Photo.objects.count(), 0)\n\n photos = album.fetch_photos(before=before, after=after)\n self.assertEqual(photos.count(), Photo.objects.count())\n self.assertLess(photos.count(), photos_count)\n\n @mock.patch('vkontakte_users.models.User.remote._fetch', side_effect=user_fetch_mock)\n def test_fetch_photo_comments(self, *kwargs):\n\n group = GroupFactory(remote_id=GROUP_ID)\n album = AlbumFactory(remote_id=ALBUM_ID, owner=group)\n photo = PhotoFactory(remote_id=PHOTO_ID, album=album, owner=group)\n\n comments = photo.fetch_comments(count=20, sort='desc')\n self.assertEqual(comments.count(), photo.comments.count())\n self.assertEqual(comments.count(), 20)\n\n # testing `after` parameter\n after = Comment.objects.order_by('date')[0].date\n\n comments_count = Comment.objects.count()\n Comment.objects.all().delete()\n self.assertEqual(Comment.objects.count(), 0)\n\n comments = photo.fetch_comments(after=after, sort='desc')\n self.assertEqual(comments.count(), Comment.objects.count())\n self.assertEqual(comments.count(), photo.comments.count())\n self.assertEqual(comments.count(), comments_count)\n\n # testing `all` parameter\n Comment.objects.all().delete()\n self.assertEqual(Comment.objects.count(), 0)\n\n comments = photo.fetch_comments(all=True)\n self.assertEqual(comments.count(), Comment.objects.count())\n self.assertEqual(comments.count(), photo.comments.count())\n self.assertGreater(photo.comments.count(), comments_count)\n\n @mock.patch('vkontakte_users.models.User.remote._fetch', side_effect=user_fetch_mock)\n def test_fetch_photo_likes(self, *kwargs):\n\n group = GroupFactory(remote_id=GROUP_ID)\n album = AlbumFactory(remote_id=ALBUM_ID, owner=group)\n photo = PhotoFactory(remote_id=PHOTO_ID, album=album, owner=group)\n\n self.assertEqual(photo.likes_count, 0)\n users_initial = User.objects.count()\n\n users = photo.fetch_likes(all=True)\n\n self.assertGreater(photo.likes_count, 0)\n self.assertEqual(photo.likes_count, len(users))\n self.assertEqual(photo.likes_count, User.objects.count() - users_initial)\n self.assertEqual(photo.likes_count, photo.likes_users.count())\n\n def test_fetch_photo_likes_parser(self):\n\n group = GroupFactory(remote_id=GROUP_ID)\n album = AlbumFactory(remote_id=ALBUM_ID, owner=group)\n photo = PhotoFactory(remote_id=PHOTO_ID, album=album, owner=group)\n\n self.assertEqual(photo.likes_count, 0)\n photo.fetch_likes_parser()\n self.assertGreater(photo.likes_count, 0)\n\n def test_fetch_photo_comments_parser(self):\n\n group = GroupFactory(remote_id=GROUP_ID)\n album = AlbumFactory(remote_id=ALBUM_ID, owner=group)\n photo = PhotoFactory(remote_id=PHOTO_ID, album=album, owner=group)\n\n #self.assertEqual(photo.comments_count, 0)\n photo.fetch_comments_parser()\n self.assertGreater(photo.comments_count, 0)\n\n def test_parse_album(self):\n\n response = '''{\"response\":[{\"id\":16178407,\"thumb_id\":\"96509883\",\"owner_id\":6492,\"title\":\"qwerty\",\n \"description\":\"desc\",\"created\":\"1298365200\",\"updated\":\"1298365201\",\"size\":\"3\",\n \"privacy\":\"3\"},{\"id\":\"17071606\",\"thumb_id\":\"98054577\",\"owner_id\":-6492,\n \"title\":\"\",\"description\":\"\",\"created\":\"1204576880\",\"updated\":\"1229532461\",\n \"size\":\"3\",\"privacy\":\"0\"}]}\n '''\n instance = Album()\n owner = UserFactory(remote_id=6492)\n instance.parse(json.loads(response)['response'][0])\n instance.save()\n\n self.assertEqual(instance.remote_id, 16178407)\n self.assertEqual(instance.thumb_id, 96509883)\n self.assertEqual(instance.owner, owner)\n self.assertEqual(instance.title, 'qwerty')\n self.assertEqual(instance.description, 'desc')\n self.assertEqual(instance.size, 3)\n self.assertEqual(instance.privacy, 3)\n self.assertIsNotNone(instance.created)\n self.assertIsNotNone(instance.updated)\n\n instance = Album()\n group = GroupFactory(remote_id=6492)\n instance.parse(json.loads(response)['response'][1])\n instance.save()\n\n self.assertEqual(instance.remote_id, 17071606)\n self.assertEqual(instance.owner, group)\n\n def test_parse_photo(self):\n\n response = '''{\"response\":[{\"id\":\"146771291\",\"album_id\":\"100001227\",\"owner_id\":6492,\n \"photo_130\":\"http://cs9231.vkontakte.ru/u06492/100001227/m_7875d2fb.jpg\",\n \"text\":\"test\",\"user_id\":6492,\"width\":10,\"height\":10,\n \"date\":\"1298365200\"},\n\n {\"id\":\"146772677\",\"album_id\":\"100001227\",\"owner_id\":-6492,\n \"photo_130\":\"http://cs9231.vkontakte.ru/u06492/100001227/m_fd092958.jpg\",\n \"text\":\"test\",\"user_id\":6492,\"width\":10,\"height\":10,\n \"date\":\"1260887080\"}]}\n '''\n instance = Photo()\n owner = UserFactory(remote_id=6492)\n album = AlbumFactory(remote_id=100001227, owner=owner)\n instance.parse(json.loads(response)['response'][0])\n instance.save()\n\n self.assertEqual(instance.remote_id, 146771291)\n self.assertEqual(instance.album, album)\n self.assertEqual(instance.owner, owner)\n self.assertEqual(instance.src, instance.photo_130)\n self.assertEqual(instance.src, 'http://cs9231.vkontakte.ru/u06492/100001227/m_7875d2fb.jpg')\n self.assertEqual(instance.text, 'test')\n self.assertEqual(instance.width, 10)\n self.assertEqual(instance.height, 10)\n self.assertIsNotNone(instance.created)\n\n instance = Photo()\n group = GroupFactory(remote_id=6492)\n #album = AlbumFactory(remote_id=100001227, owner=owner)\n instance.parse(json.loads(response)['response'][1])\n instance.save()\n\n self.assertEqual(instance.remote_id, 146772677)\n self.assertEqual(instance.album, album)\n self.assertEqual(instance.owner, group)\n\n def test_parse_comment(self):\n\n response = '''{\"response\":[21, {\"date\": 1387173931, \"message\": \"[id94721323|\\u0410\\u043b\\u0435\\u043d\\u0447\\u0438\\u043a], \\u043d\\u0435 1 \\u0430 3 \\u0431\\u0430\\u043d\\u043a\\u0430 5 \\u043b\\u0438\\u0442\\u0440\\u043e\\u0432 =20 \\u0431\\u0430\\u043b\\u043b\\u043e\\u0432\", \"from_id\": 232760293, \"likes\": {\"count\": 1, \"can_like\": 1, \"user_likes\": 0}, \"id\": 91121},\n {\"date\": 1386245221, \"message\": \"\\u0410 1\\u043b. \\u0432 \\u043f\\u043e\\u0434\\u0430\\u0440\\u043e\\u043a,\\u0431\\u043e\\u043d\\u0443\\u0441 +))))\", \"from_id\": 94721323, \"likes\": {\"count\": 0, \"can_like\": 1, \"user_likes\": 0}, \"id\": 88976},\n {\"date\": 1354592120, \"message\": \"\\u0445\\u0430\\u0445
    \", \"from_id\": 138571769, \"likes\": {\"count\": 0, \"can_like\": 1, \"user_likes\": 0}, \"cid\": 50392}]}\n '''\n group = GroupFactory(remote_id=GROUP_ID)\n album = AlbumFactory(remote_id=ALBUM_ID, owner=group)\n photo = PhotoFactory(remote_id=PHOTO_ID, album=album, owner=group)\n instance = Comment(object=photo)\n instance.parse(json.loads(response)['response'][1])\n instance.save()\n\n self.assertEqual(instance.remote_id, '-%s_91121' % GROUP_ID)\n self.assertEqual(instance.object, photo)\n self.assertEqual(instance.author.remote_id, 232760293)\n self.assertGreater(len(instance.text), 10)\n self.assertIsNotNone(instance.date)\n\n def test_comment_crud_methods(self):\n group = GroupFactory(remote_id=GROUP_CRUD_ID)\n album = AlbumFactory(remote_id=ALBUM_CRUD_ID, owner=group)\n photo = PhotoFactory(remote_id=PHOTO_CRUD_ID, owner=group, album=album)\n\n def assert_local_equal_to_remote(comment):\n comment_remote = Comment.remote.fetch_by_object(object=comment.object).get(remote_id=comment.remote_id)\n self.assertEqual(comment_remote.remote_id, comment.remote_id)\n self.assertEqual(comment_remote.text, comment.text)\n self.assertEqual(comment_remote.author, comment.author)\n\n # try to delete comments from prev tests\n for comment in Comment.remote.fetch_by_object(object=photo):\n comment.delete(commit_remote=True)\n # checks there is no remote and local comments\n comments = Comment.remote.fetch_by_object(object=photo)\n self.assertEqual(Comment.objects.count(), 0, 'Error: There are %s comments from previous test. Delete them manually here %s' % (\n comments.count(), photo.get_url()))\n\n # create\n comment = Comment(text='Test comment', object=photo, author=group, date=timezone.now())\n comment.save(commit_remote=True)\n self.objects_to_delete += [comment]\n\n self.assertEqual(Comment.objects.count(), 1)\n self.assertEqual(comment.author, group)\n self.assertNotEqual(len(comment.remote_id), 0)\n assert_local_equal_to_remote(comment)\n\n # create by manager\n comment = Comment.objects.create(\n text='Test comment created by manager', object=photo, author=group, date=timezone.now(), commit_remote=True)\n self.objects_to_delete += [comment]\n self.assertEqual(Comment.objects.count(), 2)\n\n self.assertEqual(Comment.objects.count(), 2)\n self.assertEqual(comment.author, group)\n self.assertNotEqual(len(comment.remote_id), 0)\n assert_local_equal_to_remote(comment)\n\n # update\n comment.text = 'Test comment updated'\n comment.save(commit_remote=True)\n\n self.assertEqual(Comment.objects.count(), 2)\n assert_local_equal_to_remote(comment)\n\n # delete\n comment.delete(commit_remote=True)\n\n self.assertEqual(Comment.objects.count(), 2)\n self.assertTrue(comment.archived)\n self.assertEqual(Comment.remote.fetch_by_object(\n object=comment.object).filter(remote_id=comment.remote_id).count(), 0)\n\n # restore\n comment.restore(commit_remote=True)\n self.assertFalse(comment.archived)\n\n self.assertEqual(Comment.objects.count(), 2)\n assert_local_equal_to_remote(comment)\n\n\nclass VkontakteUploadPhotos(TestCase):\n\n def setUp(self):\n self.objects_to_delete = []\n\n path = dirname(__file__)\n path = join(path, 'tests')\n\n file1 = join(path, 'test_photo1.jpg')\n file2 = join(path, 'test_photo2.png')\n file3 = join(path, 'тест_фото3.jpg')\n file3_1 = join(path, u'тест_фото3.jpg')\n\n self.files = [file1, file2, file3, file3_1]\n\n def tearDown(self):\n for object in self.objects_to_delete:\n object.delete(commit_remote=True)\n\n def test_upload_to_group_album(self):\n group = GroupFactory(remote_id=59154616)\n album = AlbumFactory(remote_id=209832918, owner=group)\n\n caption = 'test_upload'\n photos = album.upload_photos(self.files, caption=caption)\n\n self.objects_to_delete += photos # delete photos\n\n self.assertEqual(len(photos), len(self.files))\n self.assertEqual(photos[0].text, caption)\n\n def test_upload_to_user_album(self):\n user = UserFactory(remote_id=201164356)\n album = AlbumFactory(remote_id=209873101, owner=user)\n\n caption = 'test_upload'\n photos = album.upload_photos(self.files, caption=caption)\n\n self.objects_to_delete += photos # delete photos\n\n self.assertEqual(len(photos), len(self.files))\n self.assertEqual(photos[0].text, caption)\n","sub_path":"vkontakte_photos/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":14779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"582454937","text":"from unittest import TestCase\nfrom test.error_colors import ErrorColors\nfrom calculator import Calculator\n\n\nclass TestCalcStateChange(TestCase):\n\n def _test(self, calc_object, method, tests):\n for num, expected_state in tests:\n starting_state = calc_object.get_state() # store the starting state\n result = method(starting_state, num) # stort the result of the operation using starting state\n calc_object.set_state(result) # set the new state of the object\n error_message = self.__return_calc_error(starting_state, num, calc_object.get_state(), expected_state)\n self.assertEqual(calc_object.get_state(), expected_state, error_message)\n \n def __return_calc_error(self, starting_state, num, actual_state, expected_state):\n result = f\"\"\"\n {ErrorColors.GREEN}Expected: ({starting_state}, {num}) -> {expected_state}\n {ErrorColors.RED}Actual: ({actual_state}, {num}) -> {actual_state}{ErrorColors.RESET}\n \"\"\"\n return result\n\n # The test results are cummulative\n def test_add_state(self):\n c = Calculator()\n self._test(c, c.add, [ # (num_to_add, expected_state)\n (1,1),(2,3),(5,8),(16,24),(-4,20),(-77,-57),(23,-34),(56,22)\n ])\n\n def test_subtract_state(self):\n c = Calculator()\n self._test(c, c.subtract, [ # (num_to_subtract, expected_state)\n (1,-1),(2,-3),(5,-8),(16,-24),(-4,-20),(-77,57),(23,34),(56,-22)\n ])\n\n def test_multiply_state(self):\n c = Calculator()\n c.set_state(1)\n self._test(c, c.multiply, [ # (num_to_multiply, expected_state)\n (1,1),(2,2),(5,10),(16,160),(-4,-640),(-77,49280),(23,1133440),(56,63472640)\n ])\n\n def test_divide_state(self):\n c = Calculator()\n c.set_state(50000)\n self._test(c, c.divide, [ # (divisor, expected_state)\n (3,16666.666666666668),(2,8333.333333333334),(5,1666.6666666666667),\n (2,833.3333333333334),(10,83.33333333333334),(10,8.333333333333334)\n ])\n","sub_path":"test/test_state_change.py","file_name":"test_state_change.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"159960611","text":"#!/usr/bin/env python\n\n__author__ = \"Elisa Londero\"\n__email__ = \"elisa.londero@inaf.it\"\n__date__ = \"June 2018\"\n\nimport os\nfrom glob import glob\nfrom database import db_query\nfrom utilities import md5Checksum\nfrom utilities import LoggingClass\nfrom read_json import ReadJson\nfrom database import MySQLDatabase\nfrom utilities import MissingConfParameter\nfrom utilities import SendEmail\n\nrj = ReadJson()\nlog = LoggingClass('',True).get_logger()\n\nclass NewdataFilesList(object):\n\n def create_list(self):\n try:\n ing_fldr = rj.get_ingest_folder()\n fits_list = []\n for i in ing_fldr:\n fits_list.append(list(glob(i + '/*.fit*')))\n flat_list = [item for sublist in fits_list for item in sublist]\n return flat_list\n except Exception as e:\n msg = \"Newdata files list excep - NewdataFilesList.create_list -- \"\n log.error(\"{0}{1}\".format(msg,e))\n\ndef main():\n dbuser = rj.get_db_user(); dbpwd = rj.get_db_pwd() \n dbhost = rj.get_db_host(); dbname = rj.get_db_name() \n dbport = rj.get_db_port(); dbtables = rj.get_db_tables()\n sender = rj.get_sender(); smtphost = rj.get_smtp_host() \n recipient = rj.get_recipient() \n\n db = MySQLDatabase(dbuser, dbpwd, dbname, dbhost, dbport)\n\n Session = db.mysql_session()\n \n files_list = NewdataFilesList().create_list()\n\n for file_path in files_list:\n cks_newdata = md5Checksum(file_path).calculate_checksum()\n fname = os.path.basename(os.path.splitext(os.path.normpath(file_path))[0])\n fname_gz = fname + '.fits.gz' \n\n for tbl in dbtables:\n db_element = db_query(tbl, Session, fname_gz) \n\n if db_element is not None:\n storage_path = db_element[0]\n cks_db = db_element[1]\n cksgz_db = db_element[2]\n cksgz_stg = md5Checksum(storage_path).calculate_checksum() \n cks_stg = md5Checksum(storage_path).get_checksum_gz()\n print(fname_gz,cks_db,cks_stg,cks_newdata,cksgz_db,cksgz_stg) \n if cksgz_stg == cksgz_db and cks_stg == cks_db == cks_newdata:\n try:\n os.remove(file_path)\n except Exception as e:\n msg = \"File removal exception --\"\n log.error(\"{0}{1}\".format(msg,e)) \t\n else: \n message = 'Severe alert - newdata, storage and DB file checksums DO NOT MATCH'\n SendEmail(message,recipient,sender,smtphost).send_email()\n else:\n pass\n\n db.close_session()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"456220651","text":"#! /usr/bin/env python\n## Hey, Python: encoding=utf-8\n#\n# Copyright (c) 2007-2008, 2010 Adeodato Simó (dato@net.com.org.es)\n# Licensed under the terms of the MIT license.\n\nimport justrok\nfrom justrok import util\nfrom justrok.enumerations import EngineState, RandomMode, RepeatMode\nimport os\nfrom PyQt5.QtCore import pyqtSignal, Qt, QTimer\nfrom PyQt5.QtGui import QIcon, QPixmap\nfrom PyQt5.QtWidgets import QLabel, QSizePolicy, QSlider, QStatusBar\n\nclass StatusBar(QStatusBar):\n def __init__(self, *args):\n QStatusBar.__init__(self, *args)\n self._seek_to = None\n self._length = None\n self._elapsed = None\n self._remaining = None\n self._update_timer = QTimer(self)\n self._blink_timer = QTimer(self)\n self._blink_flag = True\n self.repeat = RepeatLabel(self)\n self.random = RandomLabel(self)\n self._slider = QSlider(Qt.Horizontal, self)\n self._elapsed_time_label = TimeLabel(self)\n self._remaining_time_label = NegativeTimeLabel(self)\n self._slider.setTracking(False)\n self._slider.setMaximumWidth(150)\n self._slider.setFocusPolicy(Qt.NoFocus)\n self.setContentsMargins(0, 0, 4, 0)\n self.addPermanentWidget(self.repeat, 0)\n self.addPermanentWidget(self.random, 0)\n self.addPermanentWidget(self._elapsed_time_label, 0)\n self.addPermanentWidget(self._slider, 0)\n self.addPermanentWidget(self._remaining_time_label, 0)\n self.slot_stop()\n self._connect_update_timer()\n self._blink_timer.timeout.connect(self._on_blink_timer_timeout)\n self._slider.sliderPressed.connect(self._on_slider_pressed)\n self._slider.sliderMoved.connect(self._on_slider_moved)\n self._slider.sliderReleased.connect(self._on_slider_released)\n justrok.Globals.playlist.playing_new_track_started.connect(self._on_playlist_playing_new_track_started)\n justrok.Globals.engine.state_changed.connect(self._on_engine_state_changed)\n justrok.Globals.engine.seeking_finished.connect(self._on_engine_seeking_finished)\n util.create_action('next_repeat_mode', 'Change repeat mode', self.repeat.mousePressEvent, QIcon(os.path.join(justrok.Globals.files_and_directories.runtime_directory, \"images\", \"repeat_track.png\")), 'Ctrl+T')\n util.create_action('toggle_random_mode', 'Toggle random mode', self.random.mousePressEvent, QIcon(os.path.join(justrok.Globals.files_and_directories.runtime_directory, \"images\", \"random.png\")), 'Ctrl+R')\n\n def slot_update(self):\n if self._length is not None:\n self._elapsed = justrok.Globals.engine.get_position()\n self._remaining = self._length - self._elapsed\n self._slider.setValue(self._elapsed)\n self._elapsed_time_label.set_time(self._elapsed)\n self._remaining_time_label.set_time(self._remaining)\n else:\n self._slider.setValue(0)\n self._elapsed_time_label.set_time(None)\n self._remaining_time_label.set_time(None)\n \n def _on_playlist_playing_new_track_started(self):\n tags = justrok.Globals.playlist.get_current_tags()\n self._length = tags.get('length', 0)\n self._slider.setRange(0, self._length)\n self._update_timer.start(200)\n self._slider.setEnabled(True)\n self._elapsed_time_label.setEnabled(True)\n self._remaining_time_label.setEnabled(True)\n self.slot_update()\n \n def slot_stop(self):\n self._update_timer.stop()\n self._blink_timer.stop()\n self._slider.setEnabled(False)\n self._elapsed_time_label.setEnabled(False)\n self._remaining_time_label.setEnabled(False)\n self._length = self._elapsed = self._remaining = None\n self.slot_update()\n\n def _on_engine_state_changed(self, new_state):\n if new_state == EngineState.PAUSED:\n self._update_timer.stop()\n self._blink_timer.start(750)\n elif new_state == EngineState.PLAYING:\n self._update_timer.start(200)\n self._blink_timer.stop()\n elif new_state == EngineState.STOPPED:\n self.slot_stop()\n\n def _on_blink_timer_timeout(self):\n self._blink_flag = not self._blink_flag\n if self._blink_flag:\n self._elapsed_time_label.set_time(self._elapsed)\n self._remaining_time_label.set_time(self._remaining)\n else:\n self._elapsed_time_label.clear()\n self._remaining_time_label.clear()\n\n def _on_engine_seeking_finished(self):\n self._connect_update_timer()\n \n def _on_slider_pressed(self):\n self._disconnect_update_timer()\n \n def _on_slider_moved(self, value):\n self._seek_to = value\n self._elapsed_time_label.set_time(value)\n self._remaining_time_label.set_time(self._length - value)\n \n def _on_slider_released(self):\n if self._seek_to is not None:\n justrok.Globals.engine.set_position(self._seek_to)\n self._seek_to = None\n\n def _connect_update_timer(self):\n self._update_timer.timeout.connect(self.slot_update)\n \n def _disconnect_update_timer(self):\n self._update_timer.timeout.disconnect(self.slot_update)\n\nclass TimeLabel(QLabel):\n PREFIX = ' '\n def __init__(self, *args):\n QLabel.__init__(self, *args)\n self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)\n \n def set_time(self, seconds):\n if seconds is not None:\n self.setText(\"%s%s\" % (self.PREFIX, util.fmt_seconds(seconds)))\n else:\n self.setText(\"--:--\")\n self.setFixedSize(self.sizeHint()) # Make the label.clear() above DTRT.\n\nclass NegativeTimeLabel(TimeLabel):\n PREFIX = '-'\n\nclass MultiIconLabel(QLabel):\n \n clicked = pyqtSignal(int)\n \n def __init__(self, parent, icons=(), tooltips=()):\n QLabel.__init__(self, parent)\n self.clicked.connect(self.slot_clicked)\n self._icons = icons\n self._tooltips = tooltips\n self._state = self.get_current_state()\n self._update_from_state()\n\n def mousePressEvent(self, mouse_event):\n if mouse_event.button() == Qt.LeftButton:\n self._state += 1\n self._update_from_state()\n self.clicked.emit(self._state)\n \n def _update_from_state(self):\n if self._state >= len(self._icons):\n self._state = 0\n self.setPixmap(self._icons[self._state])\n tooltip = self._tooltips[self._state]\n if tooltip is not None:\n self.setToolTip(tooltip)\n else:\n self.setToolTip(\"\")\n \n @staticmethod\n def get_current_state():\n raise NotImplementedError(\"MultiIconLabel.get_current_state() must be implemented in subclasses.\")\n \n def slot_clicked(self, state):\n raise NotImplementedError(\"MultiIconLabel.slot_clicked must be reimplemented in subclasses.\")\n\nclass RepeatLabel(MultiIconLabel):\n def __init__(self, parent):\n icons = [\n QIcon.fromTheme(\"go-bottom\").pixmap(16, QIcon.Active, QIcon.Off),\n QPixmap(os.path.join(justrok.Globals.files_and_directories.runtime_directory, \"images\", \"repeat_track.png\")),\n QPixmap(os.path.join(justrok.Globals.files_and_directories.runtime_directory, \"images\", \"repeat_playlist.png\"))\n ]\n tooltips = [\n 'Repeat: Off',\n 'Repeat: Track',\n 'Repeat: Playlist'\n ]\n MultiIconLabel.__init__(self, parent, icons, tooltips)\n \n @staticmethod\n def get_current_state():\n return justrok.Globals.playlist.repeat_mode.value\n \n def slot_clicked(self, state):\n justrok.Globals.playlist.repeat_mode = RepeatMode(state)\n\nclass RandomLabel(MultiIconLabel):\n def __init__(self, parent):\n icons = [\n QIcon.fromTheme('go-next').pixmap(16, QIcon.Active, QIcon.Off),\n QPixmap(os.path.join(justrok.Globals.files_and_directories.runtime_directory, \"images\", \"random.png\"))\n ]\n tooltips = [\n 'Random mode: Off',\n 'Random mode: On',\n ]\n MultiIconLabel.__init__(self, parent, icons, tooltips)\n\n @staticmethod\n def get_current_state():\n return justrok.Globals.playlist.random_mode.value\n\n def slot_clicked(self, state):\n justrok.Globals.playlist.random_mode = RandomMode(state)\n","sub_path":"justrok/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":8398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"449598223","text":"import scrapy\nfrom scrapy.http import FormRequest\nfrom ..items import Product\nfrom selenium import webdriver\n\nclass SnowbeachSpider(scrapy.Spider):\n name = 'snowbeach'\n allowed_domains = ['snowbeach.com']\n\n def __init__(self, *args, **kwargs):\n super(SnowbeachSpider, self).__init__(*args, **kwargs)\n self.start_urls = [kwargs.get('start_url')]\n\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n self.driver = webdriver.Chrome(chrome_options=options)\n\n def parse(self, response):\n item = Product()\n\n self.driver.get(response.url)\n item['name'] = self.driver.find_element_by_xpath('//*[@itemtype=\"http://schema.org/Product\"]/meta[@itemprop=\"name\"]').get_attribute('content').strip()\n item['image'] = self.driver.find_element_by_xpath('//*[@itemtype=\"http://schema.org/Product\"]/meta[@itemprop=\"image\"]').get_attribute('content')\n item['price'] = self.driver.find_element_by_xpath('//*[@itemtype=\"http://schema.org/Offer\"]/meta[@itemprop=\"price\"]').get_attribute('content')\n\n self.driver.close()\n\n yield item\n","sub_path":"scrapers/scrapers/spiders/snowbeach-spider.py","file_name":"snowbeach-spider.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"628316420","text":"#chenqumi@20170704\r\n#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport sys,os,re\r\n\r\nif len(sys.argv) ==1:\r\n print(\"\\nUsage: {} \".format(sys.argv[0]))\r\n sys.exit()\r\n\r\nvcf,dist,out = sys.argv[1:4]\r\n\r\ndist = int(dist)\r\nindex = 0\r\n\r\nOT = open(out,\"w\")\r\nwith open(vcf) as VCF:\r\n \r\n init_pos = int\r\n \r\n for line in VCF:\r\n \r\n if line.startswith(\"#\"):\r\n continue\r\n\r\n pos = int(line.split(\"\\t\")[1])\r\n \r\n if index == 0:\r\n init_pos = pos\r\n \r\n m = init_pos + index*dist\r\n\r\n if pos >= m:\r\n OT.write(line)\r\n index += 1\r\n else:\r\n continue\r\n\r\nOT.close()\r\n","sub_path":"python/extract_interval_snp2.py","file_name":"extract_interval_snp2.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"356656221","text":"# -*- coding: utf-8 -*-\n\n# @File : exceptions-example.py\n# @Date : 2018-09-21\n# @Author : Peng Shiyu\n\n\n# 自定义异常\nclass MyException(Exception):\n def __init__(self, url, errcode, errmsg):\n self.url = url\n self.errcode = errcode\n self.errmsg = errmsg\n\n def __str__(self):\n return \"\" % (\n self.url, self.errcode, self.errmsg\n )\n\n\nif __name__ == '__main__':\n try:\n raise MyException(\"www.baidu.com\", 404, \"not found\")\n except MyException as e:\n print(e.url)\n print(e.errcode)\n print(e.errmsg)\n raise # 重新抛出异常\n","sub_path":"source/learning/example/exceptions-example.py","file_name":"exceptions-example.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"273646987","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\ndef load(l, nodes):\n if len(nodes) == 0:\n nodes = [ListNode(l.val)]\n else:\n nodes[-1].next = ListNode(l.val)\n nodes.append(nodes[-1].next)\n return nodes\n\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n nodes = []\n while l1 or l2:\n if l1 is None:\n print(\"load l2\", l2.val)\n nodes = load(l2, nodes)\n l2 = l2.next\n elif l2 is None:\n print(\"load l1\", l1.val)\n nodes = load(l1, nodes)\n l1 = l1.next\n elif l1.val < l2.val:\n print(\"load l1\", l1.val)\n nodes = load(l1, nodes)\n l1 = l1.next\n else:\n print(\"load l2\", l2.val)\n nodes = load(l2, nodes)\n l2 = l2.next\n return None if len(nodes) == 0 else nodes[0]\n","sub_path":"LeetCode (Python 3)/Merge Two Sorted Lists.py","file_name":"Merge Two Sorted Lists.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"86147790","text":"#!/usr/bin/env python3\n\n# This script can pull metadata from an ERDDAP server and write\n# an XML file using the metadata_xml package.\n\nimport os\nimport click\nimport sys\nimport logging\n\nfrom pathlib import Path\nfrom metadata_xml.iso_template import iso_template, ValidationError\nfrom erddap_xml_creator.ERDDAP import ERDDAP\nfrom erddap_xml_creator.setup_logging import setup_logging\n\nlogger = setup_logging()\n\nxml_dir_default = 'xml'\n\n\ndef create_folder_from_path(path):\n # Create xml folder if it doesn't exist\n if not os.path.exists(path):\n try:\n os.makedirs(path)\n logger.debug(\"Created directory '{}'\".format(path))\n except Exception as err:\n raise RuntimeError(\"Could not create direcory\" + path + err)\n\n\n@click.command()\n@click.option('--datasets', 'datasets_csv',\n help='Comma separated list of ERDDAP ids')\n@click.option('--validate-only', 'validate_only',\n help=\"Just validate, don't create any XML files\", is_flag=True)\n@click.option('--xml_dir', default=xml_dir_default,\n help='Set the directory where XML files are written to')\n@click.option('--debug', default=None, is_flag=True, help='Verbose output')\n@click.argument('erddap_url')\ndef main(erddap_url, validate_only, datasets_csv, xml_dir, debug):\n \"\"\"EG: python create_xml.py http://example.com/erddap\"\"\"\n if debug:\n logger.setLevel(logging.DEBUG)\n\n erddap = ERDDAP(erddap_url)\n logger.info(\"Quering ERDDAP server at \" + erddap_url)\n\n datasets = []\n # if user picked dataset ID's instead of taking all of them\n if datasets_csv:\n datasets = list(filter(None, datasets_csv.replace(' ', '').split(',')))\n\n if datasets:\n logger.info(\"Using datasets \" + ','.join(datasets))\n else:\n # query allDatasets to get IDs\n datasets = erddap.get_dataset_ids()\n\n num_datasets = str(len(datasets))\n\n if not datasets:\n raise RuntimeError(\"No datasets found\")\n else:\n logger.info(\n \"Creating XML files for {} datasets..\".format(num_datasets))\n\n create_folder_from_path(xml_dir)\n\n num_successful = 0\n # loop through each dataset to be processed\n for dataset_id in datasets:\n logger.info(\"Querying \" + dataset_id)\n # query dataset for metadata. This is all the metadata for this dataset\n dataset_metadata_all = {}\n try:\n dataset_metadata_all = erddap.get_metadata_for_dataset(dataset_id)\n except Exception as err:\n logger.error(err)\n continue\n\n dataset_globals = dataset_metadata_all['NC_GLOBAL']\n dataset_globals['erddap_dataset_url'] = '{}/tabledap/{}.html'.format(\n erddap_url, dataset_id)\n\n if 'id' not in dataset_globals:\n dataset_globals['id'] = dataset_id\n logger.warning('Attribute \"id\" not found in dataset, '\n + 'defaulting to \"{}\"'.format(dataset_id))\n\n # a dict that has been setup for the tempolate\n try:\n xml = iso_template(record=dataset_globals)\n except ValidationError as e:\n logger.error(e)\n continue\n\n if not validate_only:\n xml_path = '{}/{}_iso19115.xml'.format(xml_dir, dataset_id)\n\n # write the XML\n try:\n f = open(xml_path, \"w\")\n f.write(xml)\n logger.debug(\"Wrote \" + xml_path)\n num_successful += 1\n except Exception as e:\n logger.error(\"Could not write to \" + xml_path + e)\n\n logger.info(\"Wrote {}/{} datasets to directory: {}\".format(num_successful,\n num_datasets,\n xml_dir))\n\n\nif __name__ == '__main__':\n\n try:\n main()\n except RuntimeError as err:\n logger.error(err)\n sys.exit(1)\n","sub_path":"create_xml.py","file_name":"create_xml.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"639202192","text":"#!/usr/bin/python3 import os\n\n# sleep(15)\n\n# how to set to autostart:\n# lo mismo pero adaptado a raspi: https://www.raspberrypi-spy.co.uk/2014/05/how-to-autostart-apps-in-rasbian-lxde-desktop/\n# lo que funcó para hacer autostart: editamos este file: \n# sudo nano ~/.config/lxsession/LXDE-pi/autostart\n# y alli adentro ponemos lo sgte: \n# @sudo /home/pi/Desktop/igua-toolkit/run.sh\n# notar que debes escribilo antes de la linea que dice \"screensaver\"\n# luego conviene crear un bookmark en el filemanager (pcmanfm) a la carpeta .config/lxsession/LXDE-pi/\n\n# para configurar qué redes queremos aprender u olvidar: \n# sudo nano /etc/wpa_supplicant/wpa_supplicant.conf\n\n# para clonar la carpeta de github a local:\n# git clone http://github.com/kikomayorga/igua_toolkit/\n\n\n#importando modulos genericos\nfrom time import sleep\nfrom time import strftime \nimport time\nimport serial\nimport re\nimport socket\nREMOTE_SERVER = \"www.google.com\"\n\n# configuaracion de entradas/saldas del RPI\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nbutton = 4\t\t\t\t# GPIO04, pin nro 07 \nvalve_relay = 17\t\t# GPIO17, pin nro 11 \nbutton2 = 27\t\t\t# GPIO27, pin nro 13\nspritz_relay = 22\t\t# GPIO22, pin nro 15\ncoinhibitor_relay = 23\t# GPIO23, pin nro 16\nUV_relay = 18\t\t\t# GPIO18, pin nro 12\n\nGPIO.setup(button, GPIO.IN, GPIO.PUD_UP)\nGPIO.setup(button2, GPIO.IN, GPIO.PUD_UP)\nGPIO.setup(valve_relay, GPIO.OUT)\nGPIO.setup(spritz_relay, GPIO.OUT)\nGPIO.setup(coinhibitor_relay, GPIO.OUT)\nGPIO.setup(UV_relay, GPIO.OUT)\n\n#para carriots\nfrom urllib.request import urlopen, Request\nfrom time import mktime, sleep\nfrom datetime import datetime\nfrom json import dumps\n\nclass Client (object):\n api_url = \"http://api.carriots.com/streams\"\n api_read_url = \"http://api.carriots.com/streams/IGUA01@kikomayorga.kikomayorga/\"\n\n def __init__(self, api_key=None, client_type='json'):\n self.client_type = client_type\n self.api_key = api_key\n self.content_type = \"application/vnd.carriots.api.v2+%s\" % self.client_type\n self.headers = {'User-Agent': 'Raspberry-Carriots',\n 'Content-Type': self.content_type,\n 'Accept': self.content_type,\n 'Carriots.apikey': self.api_key}\n self.data = None\n self.response = None\n\n def send(self, data):\n self.data = dumps(data).encode('utf8')\n request = Request(Client.api_url, self.data, self.headers) \n self.response = urlopen(request)\n return self.response\n \ndef rc_time(pipin):\n measurement = 0\n GPIO.setup(pipin, GPIO.OUT)\n GPIO.output(pipin, GPIO.LOW)\n sleep(0.1)\n\n GPIO.setup(pipin, GPIO.IN)\n\n while GPIO.input(pipin) == GPIO.LOW:\n measurement += 1\n\n return measurement\n \n \n#fin para carriots\n\n# declaramos una función que la usaremos mas adelante para \n# validar conexion disponible\n\ndef is_connected():\n try:\n host = socket.gethostbyname(REMOTE_SERVER)\n s = socket.create_connection((host, 80), 2)\n return True\n except:\n pass\n return False\n\n\n\n\t\t\n# ser = serial.Serial('/dev/ttyACM1',9600,timeout = 0) #puerto del acceptor \nser_flw = serial.Serial('/dev/ttyACM1',9600,timeout = None) #puerto del flujometro es ser_flw \nser_lcd = serial.Serial('/dev/ttyACM0',9600,timeout = None, parity = serial.PARITY_NONE, xonxoff = False, rtscts = False, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS) # puerto de lcd es ser_lcd \n# ser_tds = serial.Serial('/dev/ttyACM1',9600,timeout = None) # puerto de tds es ser_tds\n# ser_psi = serial.Serial('/dev/ttyACM2',9600,timeout = None) # puerto de psi es ser_psi\n\n#modulos custom\nfrom igua_display import startdisplay, refreshdisplay \nfrom igua_display import display_bienvenida_linear, display_bienvenida_pwyw\nfrom igua_display import display_acumula_pwyw, display_acumula_linear\nfrom igua_display import display_servidos_lt, display_agradece \n\n# import flowmeter\n# import valve\n\n#from display + coinacceptor\n\nlast = 0.0\nrunning = 1\n\n\nsolesacumulados = 0 \t\t\t#transaction-wise accumulator\nferrosacumulados = 0 \t\t\t#transaction-wise accumulator\ncuenta_de_ciclos = 0\t\t\t\t#transactions counter on eeprom\t\n\nprocess_id = 0 #\nmodo_maquina = 0 # 1: pay what you want , 0: linear mode\nbutton_state = 0\nnow = 0\nnow_1 = 0\n\n#setup\nstartdisplay()\n\t\t\n#main loop\n\n#para carriots\ndevice = \"IGUA_FEST_1@kikomayorga.kikomayorga\"\napikey = \"13f622d642b12cc336fa6bfde36e1561c6ac7eea19bd88d7c32246d0fca45691\" # Replace with your Carriots apikey\nclient_carriots = Client(apikey)\n\n# ejemplo de curl \"para traer todos los ulktimos streams\"\n# curl --header carriots.apikey:13f622d642b12cc336fa6bfde36e1561c6ac7eea19bd88d7c32246d0fca45691 http://api.carriots.com/streams/?device=IGUA01@kikomayorga.kikomayorga\n\n\n#para lcd\n'''def lcd_bienvenida_linear(now):\n\tif now == 0:\n\t\tser_lcd.write('agua pura! toma igua!!! '.encode())\n\telif now == 1:\n\t\tser_lcd.write('hola mundo!!! hola igua!!! '.encode())\n\telif now == 2:\n\t\tser_lcd.write('chauuuuuuu!!! hola igua!!! '.encode())\n\telif now == 3:\n\t\tser_lcd.write('hola mundo!!! hola igua!!! '.encode())\n\telif now == 4:\n\t\tser_lcd.write('chauuuuuuu!!! hola igua!!! '.encode())\n\telif now == 5:\n\t\tser_lcd.write('hola mundo!!! hola igua!!! '.encode())\n\t\n\treturn 1\n\ndef lcd_bienvenida_pwyw(now):\n\tif now == 0:\n\t\tser_lcd.write('agua pura! toma igua!!! '.encode())\n\telif now == 1:\n\t\tser_lcd.write('hola mundo!!! hola igua!!! '.encode())\n\telif now == 2:\n\t\tser_lcd.write('chauuuuuuu!!! hola igua!!! '.encode())\n\telif now == 3:\n\t\tser_lcd.write('hola mundo!!! hola igua!!! '.encode())\n\telif now == 4:\n\t\tser_lcd.write('chauuuuuuu!!! hola igua!!! '.encode())\n\telif now == 5:\n\t\tser_lcd.write('hola mundo!!! hola igua!!! '.encode())\n\t\n\treturn 1\n''' \n'''\ndef lcd_acumula_linear(solesacumulados):\n\t# ser_lcd.write('hola mundo!!! hola igua!!! '.encode())\t\n\tser_lcd.write(('tu saldo: S/. ' + str(format(solesacumulados, '.2f'))).encode())\n\t# msgSurfaceObj = fontObj.render('tu saldo: S/. ' + format(solesacumulados, '.2f'), False,whiteColor)\n\t# msgSurfaceObj2 = fontObj2.render('deposita o sirvete ' + format(solesacumulados / 0.5, '.2f') + ' litros.', False,whiteColor)\n\treturn 1\n\t\ndef lcd_acumula_pwyw(solesacumulados):\n\t# ser_lcd.write('hola mundo!!! hola igua!!! '.encode())\t\n\t# msgSurfaceObj = fontObj.render('tu aporte: S/. ' + format(solesacumulados, '.2f'), False,whiteColor)\n\tser_lcd.write(('tu aporte: S/. ' + str(format(solesacumulados, '.2f'))).encode())\t\n\t# msgSurfaceObj2 = fontObj2.render('deposita mas o sirvete! ', False,whiteColor)\t\n'''\n\t\ndef lcd_servidos_lt(servidos_lt,diff):\n\t# ser_lcd.write(('mAs agua pura! mAs agua pura! ' + ' + ' + str(format(servidos_lt/1000, '.3f')) + ' litros!').encode())\t\n\t# ser_lcd.write(('mAs agua pura! mAs agua pura! ').encode()) # + ' + ' + str(format(servidos_lt/1000, '.3f')) + ' litros!'))\t\n\tif ((servidos_lt * 1000) < 1000):\n\t\tser_lcd.write((' + ' + str(format(servidos_lt*1000, '.0f')) + ' ml ! ').encode())\t\n\t\t#ser_lcd.write((' + ' + str(format(servidos_lt, '.3f')) + ' litros! ').encode())\t\n\telse:\n\t\tser_lcd.write((' + ' + str(format(servidos_lt, '.2f')) + ' litros ! ').encode())\n\t\t\n\ndef lcd_ahorradas_bot(ahorradas_bot,diff):\n\t# ser_lcd.write(('mAs agua pura! mAs agua pura! ' + ' + ' + str(format(servidos_lt/1000, '.3f')) + ' litros!').encode())\t\n\t# ser_lcd.write(('mAs agua pura! mAs agua pura! ').encode()) # + ' + ' + str(format(servidos_lt/1000, '.3f')) + ' litros!'))\t\n\tser_lcd.write((' - ' + str(format(ahorradas_bot/1000, '.0f')) + ' botellas! ').encode())\t\n'''\t\n\t\t\n\t# ser_lcd.write(('QWERTYUIASDFGHJKL').encode()) # + ' + ' + str(format(servidos_lt/1000, '.3f')) + ' litros!'))\t\n\t# msgSurfaceObj = fontObj.render('te quedan: ' + format(servidos_lt/1000, '.3f') + ' litros!', False,whiteColor)\n\t# msgSurfaceObj = fontObj.render('te quedan: ' + format(servidos_lt/1000, '.3f') + ' litros!', False,whiteColor)\n\t# msgSurfaceObj2 = fontObj2.render('aun tienes: ' + format(diff) + ' segs. ', False,whiteColor)\n\n\t\ndef lcd_agradece():\n\tser_lcd.write('gracias!!!! igua ague pe ! '.encode())\t\n\ndef read_tds():\n\tglobal string_tds\n\tglobal ser_tds\n\tbytesToRead = ser_tds.inWaiting()\n\tif bytesToRead > 0:\n\t\tsleep(0.1)\n\t\tbytesToRead = ser_tds.inWaiting()\n\t\tprint(\"bytes to read on ser_tds: \", bytesToRead)\n\t\tstring_tds = str(ser_tds.readline(),'utf-8')\n\t\tprint(\"received on ser_tds: \", string_tds)\n\t\tstring_tds = string_tds.lstrip('r')\n\t\tstring_tds = string_tds.strip('\\n\\r')\n\t\tstring_tds = string_tds.strip('\\r\\n')\t\t\n\ndef read_psi():\n\tglobal last_string_psi_1\n\tglobal last_string_psi_2\n\tglobal last_string_psi_3\n\tglobal last_string_psi_4\n\tglobal last_string_psi_5\n\tglobal last_string_psi_6\n\tglobal last_string_psi_7\n\tglobal last_string_psi_8\n\tglobal last_string_psi_9\n\tglobal last_string_psi_10\n\tglobal string_psi\n\tglobal ser_psi\n\t\t\n\tbytesToRead = ser_psi.inWaiting()\n\tif bytesToRead > 0:\n\t\tlast_string_psi_10 = last_string_psi_9\n\t\tlast_string_psi_9 = last_string_psi_8\n\t\tlast_string_psi_8 = last_string_psi_7\n\t\tlast_string_psi_7 = last_string_psi_6\n\t\tlast_string_psi_6 = last_string_psi_5\n\t\tlast_string_psi_5 = last_string_psi_4\n\t\tlast_string_psi_4 = last_string_psi_3\n\t\tlast_string_psi_3 = last_string_psi_2\n\t\tlast_string_psi_2 = last_string_psi_1\n\t\tlast_string_psi_1 = string_psi\n\t\tsleep(0.5)\n\t\tbytesToRead = ser_psi.inWaiting()\n\t\t# print(\"bytes to read on ser_psi: \", bytesToRead)\n\t\tstring_psi = str(ser_psi.readline(),'utf-8')\n\t\t# print(\"received on ser_psi: \", string_psi)\n\t\ndef detectaUsb():\n\ttry ser_flw = serial.Serial('/dev/ttyACM1',9600,timeout = None)\n\t\n\t \ndef clean_string_psi():\n\t\tglobal string_psi\t\n\t\tglobal string_psi_array\n # Entrada: 0.93 Voltios - Presion = 19.49 psi // Carbon: 0.95 Voltios - Presion = 18.12 psi // UF: 0.91 Voltios - Presion = 18.94 psi // \n\n\t\tstring_psi = string_psi.lstrip('r')\n\t\tstring_psi = string_psi.strip('\\n\\r')\n\t\tstring_psi = string_psi.strip('\\r\\n')\n\t\tstring_psi = string_psi.lstrip('Entrada: ')\n\t\tstring_psi = string_psi.replace(' Voltios - Presion = ', ' ')\n\t\tstring_psi = string_psi.replace(' psi // Carbon: ', ' ')\n\t\tstring_psi = string_psi.replace(' Voltios - Presion = ', ' ')\n\t\tstring_psi = string_psi.replace(' psi // UF: ', ' ')\n\t\tstring_psi = string_psi.replace(' Voltios - Presion = ',' ')\n\t\tstring_psi = string_psi.replace(' psi // ', ' ')\n\t\tstring_psi_array = string_psi.split(' ')\n\t\t\n\t\t\ndef update_globalvars_psi():\t\t\n\t\tglobal string_psi_v1\n\t\tglobal string_psi_psi1\n\t\tglobal string_psi_v2\n\t\tglobal string_psi_psi2\n\t\tglobal string_psi_v3\n\t\tglobal string_psi_psi3\n\t\tglobal string_psi_array\n\t\t# print('voltaje 1: ', string_psi_array[0])\n\t\t# print('presion 1: ', string_psi_array[1])\n\t\t# print('voltaje 2: ', string_psi_array[2])\n\t\t# print('presion 2: ', string_psi_array[3])\n\t\t# print('voltaje 3: ', string_psi_array[4])\n\t\t# print('presion 3: ', string_psi_array[5])\n\t\tstring_psi_v1 = string_psi_array[0]\n\t\tstring_psi_psi1 = string_psi_array[1]\n\t\tstring_psi_v2 = string_psi_array[2]\n\t\tstring_psi_psi2 = string_psi_array[3]\n\t\tstring_psi_v3 = string_psi_array[4]\n\t\tstring_psi_psi3 = string_psi_array[5]\n'''\n\t\t\t\t\t\t\ndef read_flw():\n\tglobal ser_flw\n\tglobal string_flw\n\tbytesToRead = ser_flw.inWaiting()\n\tif bytesToRead > 0:\n\t\tsleep(0.05)\n\t\tdiff = 0\n\t\tbytesToRead = ser_flw.inWaiting()\n\t\t# print(\"bytes to read on ser_flw: \", bytesToRead)\n\t\tstring_flw = str(ser_flw.readline(),'utf-8')\n\t\t# print(\"received on ser_flw: \", string_flw)\n\t\tstring_flw = string_flw.lstrip('r')\n\t\tstring_flw = string_flw.strip('\\n\\r')\n\t\tstring_flw = string_flw.strip('\\r\\n')\n\t\t\n\t\t\nservidos_lt = 0\nservidos_lt_old = 0\nservidos_litros_older = 0\nloopcounter = 0\t\nservidos_total_old = 0\n\nlast_string_psi_10 = \"default string\"\nlast_string_psi_9 = \"default string\"\nlast_string_psi_8 = \"default string\"\nlast_string_psi_7 = \"default string\"\nlast_string_psi_6 = \"default string\"\nlast_string_psi_5 = \"default string\"\nlast_string_psi_4 = \"default string\"\nlast_string_psi_3 = \"default string\"\nlast_string_psi_2 = \"default string\"\nlast_string_psi_1 = \"default string\"\nstring_tds = \"default string\"\nstring_psi = \"default string\"\nstring_flw = \"0\"\ndiff = 0\nstring_psi_array = [\"0\", \"0\", \"0\", \"0\", \"0\", \"0\"]\nstring_psi_v1 = 0\nstring_psi_psi1 = 0\nstring_psi_v2 = 0\nstring_psi_psi2 = 0\nstring_psi_v3 = 0 \nstring_psi_psi3 = 0\n\nsleep(2)\n\nwhile 1 == 1:\n\t\t\n\t# ser_flw.flushInput()\n\tsleep(0.5)\n\t\t\n\tservidos_total = int(string_flw)\n\t\n\tservidos_litros_older = servidos_lt_old\n\tservidos_lt_old = servidos_lt\n\tservidos_lt = ((servidos_total) * 9.48 * 2.5 )/(10*20000* 0.865)\n\tprint(\"servido litros: \", servidos_lt)\n\tahorradas_bot = servidos_lt / 0.75\n\t# diff = 10 - diff\n\tloopcounter = loopcounter + 1\n\t\t\n\t# read_psi()\n\t# clean_string_psi()\n\t# update_globalvars_psi()\n\t# read_tds()\n\t\n\tser_flw.write('a'.encode())\n\t\n\tread_flw()\n\t\n\tif (servidos_lt_old < servidos_lt):\n\t\tlcd_servidos_lt((servidos_lt),diff)\n\telse:\n\t\tif int(loopcounter/int(2))%3 == 0:\n\t\t\tser_lcd.write(' toma IGUA !!! '.encode())\n\t\tif int(loopcounter/int(2))%3 == 1:\n\t\t\tser_lcd.write('mAs agua pura! '.encode())\t\n\t\t\t#\tif int(loopcounter/int(2))%3 == 1:\n\t\t\t# \tlcd_ahorradas_bot(ahorradas_bot,diff) \n\t\tif int(loopcounter/int(2))%3 == 2:\n\t\t\tser_lcd.write(' ... sIrvete !!! '.encode())\n\t\t\t\t\n\tif (servidos_lt_old == servidos_lt) and (servidos_litros_older < servidos_lt_old):\t\t\t\n\t\ttimestamp = int(mktime(datetime.utcnow().timetuple()))\n\t\t#aquí le debemos mandar el resetter al arduino\n\t\tser_flw.write('aasdfasdf'.encode())\n\t\t#sleep(3)\n\t\tfd = open('IGUA_OFISELVA_log.csv','a')\n\t\tfd.write('timestamp: ' + str(timestamp) +', máquina: igua_ofiselva, volumen: ' + str(format(servidos_lt, '.3f')) + \"\\n\")\n\t\tfd.close()\n\t\tdata = {\"protocol\": \"v2\", \"device\": device, \"at\": timestamp, \"data\": {\"maquina\": \"ofiselva\", \"servido litros\": format(servidos_lt, '.3f') } }\n\t\t# data = {\"protocol\": \"v2\", \"device\": device, \"at\": timestamp, \"data\": {\"maquina\": \"ofiselva\", '''\"colectado soles\": solesacumulados,'''\"servido litros\": format(servidos_lt, '.3f')''' \"psi_1\" : string_psi_psi1, \"psi_2\" : string_psi_psi2, \"psi_3\" : string_psi_psi3,\"tds\": string_tds'''} }\n\t\t# data = {\"protocol\": \"v2\", \"device\": device, \"at\": timestamp, \"data\": {\"maquina\": maquina, \"modo_info\":\"m0: 300ml, m1: 500ml, m2: nuevoTT, m3: TTinfinito, m4: enjuague\", \"modo\": modo, \"servido litros\": volumen} } \n\t\tprint(data)\n\t\tif is_connected() == True:\n\t\t\tcarriots_response = client_carriots.send(data)\n\t\t\tprint('conexion ok!')\n\t\t\tprint(carriots_response.read())\n\t\telse:\n\t\t\tprint('no connectivity available')\n\t\t\n","sub_path":"igua_ofiselva.py","file_name":"igua_ofiselva.py","file_ext":"py","file_size_in_byte":14504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"377974209","text":"import pandas as pd\nfrom sqlalchemy import create_engine\nimport sys\nimport re\nfrom numpy import std, mean, sqrt\nimport os\nfrom git import Repo\n\n\ndef get_db_connection():\n username = 'root'\n password = 'passwd'\n database_name = 'refactoring_analysis'\n server = '127.0.0.1'\n\n with open(\"../database.properties\", 'r') as db_file:\n for line in db_file:\n line = line.strip()\n username_search = re.search('^development.username=(.*)$', line, re.IGNORECASE)\n password_search = re.search('^development.password=(.*)$', line, re.IGNORECASE)\n url_search = re.search('^development.url=jdbc:mysql://(.*)/(.*)$', line, re.IGNORECASE)\n\n if username_search:\n username = username_search.group(1)\n if password_search:\n password = password_search.group(1)\n if url_search:\n server = url_search.group(1)\n database_name = url_search.group(2)\n\n return create_engine('mysql+pymysql://{}:{}@{}/{}'.format(username, password, server, database_name))\n\n\ndef regions_intersect(region_1_start, region_1_length, region_2_start, region_2_length):\n if region_1_start + region_1_length < region_2_start:\n return False\n elif region_2_start + region_2_length < region_1_start:\n return False\n return True\n\n\ndef record_involved(x):\n is_source = (x['type'] == 's' and\n x['old_path'] == x['path'] and\n regions_intersect(x['old_start_line'], x['old_length'], x['start_line'], x['length']))\n is_dest = (x['type'] == 'd' and\n x['new_path'] == x['path'] and\n regions_intersect(x['new_start_line'], x['new_length'], x['start_line'], x['length']))\n return is_source or is_dest\n\n\naccepted_types = ['Change Package', 'Extract And Move Method', 'Extract Interface', 'Extract Method',\n 'Extract Superclass', 'Inline Method', 'Move And Rename Class', 'Move Attribute', 'Move Class',\n 'Move Method', 'Pull Up Attribute', 'Pull Up Method', 'Pull Up Method', 'Push Down Method',\n 'Rename Class', 'Rename Method']\n\n\ndef get_refactoring_types_sql_condition():\n type_condition = str()\n for ref_type in accepted_types:\n type_condition += 'refactoring_type = \\\"{}\\\" or '.format(ref_type)\n return type_condition[:-4]\n\n\ndef read_sql_table(table):\n print('Reading table {} from the database'.format(table))\n query = 'SELECT * FROM ' + table\n df = pd.read_sql(query, get_db_connection())\n return df\n\n\ndef get_merge_commits():\n return read_sql_table('merge_commit')\n\n\ndef get_merge_commits_of(project_id):\n print('Reading table {} from the database'.format('merge_commit'))\n query = 'SELECT * FROM ' + 'merge_commit' + ' WHERE project_id=' + project_id\n df = pd.read_sql(query, get_db_connection())\n return df\n\n\ndef get_conflicting_regions():\n return read_sql_table('conflicting_region')\n\n\ndef get_conflicting_region_histories():\n return read_sql_table('conflicting_region_history')\n\n\ndef get_conflicting_region_history_of(project_id):\n print('Reading table {} from the database'.format('conflicting_region_history'))\n query = 'SELECT * FROM ' + 'conflicting_region_history' + ' WHERE project_id=' + project_id\n df = pd.read_sql(query, get_db_connection())\n return df\n\n\ndef get_refactorings():\n return read_sql_table('refactoring')\n\n\ndef get_accepted_refactorings():\n query = 'select * from refactoring where ({})'.format(get_refactoring_types_sql_condition())\n return pd.read_sql(query, get_db_connection())\n\n\ndef get_accepted_refactorings_of(project_id):\n query = 'select * from refactoring where ({})'.format(\n get_refactoring_types_sql_condition()) + ' AND project_id=' + project_id\n return pd.read_sql(query, get_db_connection())\n\n\ndef get_refactoring_regions():\n return read_sql_table('refactoring_region')\n\n\ndef get_accepted_refactoring_regions():\n print('Reading table refactoring_region from the database')\n\n query = 'select * from refactoring_region where refactoring_id in (select id from refactoring where ({}))' \\\n .format(get_refactoring_types_sql_condition())\n return pd.read_sql(query, get_db_connection())\n\n\ndef get_accepted_refactoring_regions_of(project_id):\n print('Reading table refactoring_region from the database')\n\n query = 'select * from refactoring_region where refactoring_id in (select id from refactoring where ({}))' \\\n .format(get_refactoring_types_sql_condition()) + ' AND project_id=' + project_id\n return pd.read_sql(query, get_db_connection())\n\n\ndef get_conflicting_regions_by_count_of_involved_refactoring():\n conflicting_regions = get_conflicting_regions()\n conflicting_region_histories = get_conflicting_region_histories()\n refactoring_regions = get_accepted_refactoring_regions()\n\n crs_with_involved_refs = pd.DataFrame()\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n if project_id not in rr_grouped_by_project.groups:\n continue\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash', how='inner')\n crh_with_involved_refs = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n crs_with_involved_refs = crs_with_involved_refs.append(\n crh_with_involved_refs.groupby('conflicting_region_id').size().to_frame())\n\n crs_by_involved_refs = conflicting_regions[['id']]\n # The +2 is because length is actually the difference between the start and end line of the code range. So the\n # actual size of the code range should be incremented by one, for each parent.\n crs_by_involved_refs['size'] = conflicting_regions['parent_1_length'] + conflicting_regions['parent_2_length'] + 2\n crs_by_involved_refs = pd.merge(crs_by_involved_refs, crs_with_involved_refs,\n left_on='id', right_on='conflicting_region_id',\n how='left').fillna(0).astype(int).rename(columns={0: 'involved_refactorings'})\n\n return crs_by_involved_refs\n\n\ndef get_conflicting_region_size_by_involved_refactoring_size():\n conflicting_regions = get_conflicting_regions()\n conflicting_region_histories = get_conflicting_region_histories()\n refactoring_regions = get_accepted_refactoring_regions()\n\n crs_with_involved_refs_size = pd.DataFrame()\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n if project_id not in rr_grouped_by_project.groups:\n continue\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash', how='inner')\n crh_with_involved_refs = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n crs_with_involved_refs_size = crs_with_involved_refs_size.append(\n crh_with_involved_refs.groupby('conflicting_region_id').length.sum().to_frame())\n\n crs_with_involved_refs_size.rename(columns={'length': 'refactoring_size'}, inplace=True)\n crs_by_size = conflicting_regions[['id']]\n # The +2 is because length is actually the difference between the start and end line of the code range. So the\n # actual size of the code range should be incremented by one, for each parent.\n crs_by_size['conflicting_region_size'] = conflicting_regions['parent_1_length'] + conflicting_regions[\n 'parent_2_length'] + 2\n crs_by_size.set_index('id', inplace=True)\n crs_size_by_involved_refs_size = crs_by_size.join(crs_with_involved_refs_size,\n how='left').fillna(0).astype(int)\n\n return crs_size_by_involved_refs_size\n\n\ndef get_conflicting_merge_commit_by_merge_author_involvement_in_conflict():\n merge_commits = get_merge_commits()[['id', 'author_email']].rename(columns={'author_email': 'merge_author_email'})\n conflicting_region_histories = get_conflicting_region_histories()\n refactoring_regions = get_accepted_refactoring_regions()\n\n mc_by_author_involvement = pd.DataFrame()\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n\n commits_with_involved_refs = pd.DataFrame(columns={'commit_hash'})\n if project_id in rr_grouped_by_project.groups:\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash',\n how='inner')\n crh_with_involved_refs = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n commits_with_involved_refs = pd.DataFrame(crh_with_involved_refs.commit_hash.unique()).rename(\n columns={0: 'commit_hash'})\n\n crh_mc = project_crh.merge(merge_commits, how='inner', left_on='merge_commit_id', right_on='id')\n crh_mc_same_author = crh_mc[crh_mc['author_email'] == crh_mc['merge_author_email']]\n crh_mc_same_author_with_involved_ref = crh_mc_same_author.merge(commits_with_involved_refs, how='inner',\n on='commit_hash')\n crh_mc_with_involved_ref = crh_mc.merge(commits_with_involved_refs, how='inner', on='commit_hash')\n\n crh_mc_count = crh_mc.groupby('merge_commit_id').commit_hash.nunique().to_frame().rename(\n columns={'commit_hash': 'total_crh'})\n crh_mc_same_author_count = crh_mc_same_author.groupby(\n 'merge_commit_id').commit_hash.nunique().to_frame().rename(columns={'commit_hash': 'crh_merge_author'})\n crh_mc_same_author_with_involved_ref_count = crh_mc_same_author_with_involved_ref.groupby(\n 'merge_commit_id').commit_hash.nunique().to_frame().rename(\n columns={'commit_hash': 'crh_merge_author_involved_ref'})\n crh_mc_with_involved_ref_count = crh_mc_with_involved_ref.groupby(\n 'merge_commit_id').commit_hash.nunique().to_frame().rename(columns={'commit_hash': 'crh_involved_ref'})\n crh_mc_involvement = crh_mc_count.join(crh_mc_same_author_count, how='outer').join(\n crh_mc_with_involved_ref_count, how='outer').join(crh_mc_same_author_with_involved_ref_count,\n how='outer').fillna(0).astype(int).reset_index()\n crh_mc_involvement['project_id'] = project_id\n\n mc_by_author_involvement = mc_by_author_involvement.append(crh_mc_involvement)\n\n return mc_by_author_involvement\n\n\n# 20190310\ndef get_involved_refactorings_by_refactoring_type():\n conflicting_region_histories = get_conflicting_region_histories()\n refactorings = get_accepted_refactorings()\n refactoring_regions = get_accepted_refactoring_regions()\n merge_commits = get_merge_commits()\n repo_paths = [\n 'D:\\\\github\\\\repos\\\\javaparser',\n 'D:\\\\github\\\\repos\\\\junit5'\n ]\n\n involved_refs_count_per_project = pd.DataFrame()\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n\n repo = Repo(repo_paths[counter - 1])\n path = 'merge_scenarios_by_ref_type_' + str(project_id) + '.csv'\n\n if project_id not in rr_grouped_by_project.groups:\n continue\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash', how='inner')\n involved_crh_rr = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n involved_refactorings = refactorings[refactorings['id'].isin(involved_crh_rr['refactoring_id'])]\n # involved_ref_per_type = involved_refactorings.groupby('refactoring_type').id.nunique().to_frame().rename(\n # columns={'id': 'involved_refs_count'})\n for index, group in involved_refactorings.groupby('refactoring_type'):\n for _, row in group.iterrows():\n line = []\n line.append(row['refactoring_type'])\n line.append(row['refactoring_detail'])\n line.append(row['commit_hash'])\n crh_rr = involved_crh_rr[(involved_crh_rr['project_id_x'] == row['project_id']) & (\n involved_crh_rr['refactoring_id'] == row['id'])]\n line.append(str(crh_rr['merge_parent'].iloc[0]))\n merge_commit_id = crh_rr['merge_commit_id'].iloc[0]\n line.append(\";\".join(get_merge_scenario(repo, project_id, merge_commits, merge_commit_id)))\n\n print_to_csv(path, line)\n # for refactoring_index in involved_ref_per_type.index:\n # if refactoring_index not in accepted_types:\n # involved_ref_per_type = involved_ref_per_type.drop(refactoring_index)\n #\n # involved_ref_per_type['involved_refs_count'] = involved_ref_per_type['involved_refs_count'] / sum(\n # involved_ref_per_type['involved_refs_count'])\n # involved_ref_per_type.rename(columns={'involved_refs_count': str(project_id)}, inplace=True)\n # involved_refs_count_per_project = involved_refs_count_per_project.append(involved_ref_per_type.T)\n\n return involved_refs_count_per_project.T\n\n\n# 20190310\n\n\ndef get_refactorings_by_refactoring_type():\n refactorings = get_accepted_refactorings()\n\n refactorings_count_per_project = pd.DataFrame()\n counter = 0\n for project_id, project_refactorings in refactorings.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n\n refactorings_per_type = project_refactorings.groupby('refactoring_type').id.nunique().to_frame().rename(\n columns={'id': 'refs_count'})\n\n # for refactoring_index in refactorings_per_type.index:\n # if refactoring_index not in accepted_types:\n # refactorings_per_type = refactorings_per_type.drop(refactoring_index)\n\n refactorings_per_type['refs_count'] = refactorings_per_type['refs_count'] / sum(\n refactorings_per_type['refs_count'])\n refactorings_per_type.rename(columns={'refs_count': str(project_id)}, inplace=True)\n refactorings_count_per_project = refactorings_count_per_project.append(refactorings_per_type.T)\n\n return refactorings_count_per_project.T\n\n\ndef get_refactorings_by_refactoring_type_split_by_involved():\n all_refs = get_data_frame('refactorings_by_refactoring_type').fillna(0).T\n involved_refs = get_data_frame('involved_refactorings_by_refactoring_type').fillna(0).T\n\n plot_df = pd.DataFrame(columns=['project_id', 'refactoring_type', 'percent', 'overall_or_involved'])\n for project_id in all_refs.index:\n for refactoring_type in all_refs.loc[project_id].index:\n overall_percent = all_refs.loc[project_id].loc[refactoring_type]\n plot_df = plot_df.append({'project_id': project_id, 'refactoring_type': refactoring_type,\n 'percent': overall_percent, 'overall_or_involved': 'overall'},\n ignore_index=True)\n try:\n involved_percent = involved_refs.loc[project_id].loc[refactoring_type]\n except KeyError:\n involved_percent = 0.\n\n plot_df = plot_df.append({'project_id': project_id, 'refactoring_type': refactoring_type,\n 'percent': involved_percent, 'overall_or_involved': 'involved'},\n ignore_index=True)\n return plot_df\n\n\ndef get_conflicting_regions_by_involved_refactorings_per_merge_commit():\n conflicting_region_histories = get_conflicting_region_histories()\n refactoring_regions = get_accepted_refactoring_regions()\n\n cr_count_per_merge = conflicting_region_histories.groupby(\n 'merge_commit_id').conflicting_region_id.nunique().to_frame().rename(\n columns={'conflicting_region_id': 'cr_count'})\n\n involved_cr_count_per_merge = pd.DataFrame()\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n if project_id not in rr_grouped_by_project.groups:\n continue\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash', how='inner')\n involved = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n involved_cr_count_per_merge = involved_cr_count_per_merge.append(\n involved.groupby('merge_commit_id').conflicting_region_id.nunique().to_frame().rename(\n columns={'conflicting_region_id': 'involved_cr_count'}))\n\n rq1_table = cr_count_per_merge.join(involved_cr_count_per_merge, how='outer').fillna(0).astype(int)\n rq1_table['percent'] = rq1_table['involved_cr_count'] / rq1_table['cr_count']\n return rq1_table\n\n\n# analyze data generated in MySql database by https://github.com/Symbolk/RefactoringsInMergeCommits\ndef get_merge_scenarios_involved_refactorings():\n # process one project each time\n repo_id = \"7\"\n repo_name = \"storm\"\n repo_paths = [\n 'D:\\\\github\\\\repos\\\\'+repo_name\n ]\n csv_path = 'merge_scenarios_involved_refactorings_' + repo_name + '.csv'\n\n conflicting_region_histories = get_conflicting_region_history_of(repo_id)\n refactorings = get_accepted_refactorings_of(repo_id)\n refactoring_regions = get_accepted_refactoring_regions_of(repo_id)\n merge_commits = get_merge_commits_of(repo_id)\n\n refs_grouped_by_project = refactorings.groupby('project_id')\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(project_id))\n\n repo = Repo(repo_paths[counter - 1])\n\n if project_id not in rr_grouped_by_project.groups:\n continue\n project_rrs = rr_grouped_by_project.get_group(project_id)\n project_refs = refs_grouped_by_project.get_group(project_id)\n\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash', how='inner')\n involved = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n for index, group in involved.groupby('merge_commit_id'):\n for _, row in group.iterrows():\n line = []\n merge_commit_id = row['merge_commit_id']\n line.append(str(row['merge_parent']))\n four_commits = get_merge_scenario(repo, project_id, merge_commits, merge_commit_id)\n if four_commits != None:\n line.append(\";\".join(four_commits))\n refactoring_id = row['refactoring_id']\n # source = project_rrs[(project_rrs['refactoring_id'] == refactoring_id) & (project_rrs['type'] == 's')]\n # target = project_rrs[(project_rrs['refactoring_id'] == refactoring_id) & (project_rrs['type'] == 'd')]\n # get refactoring detail by refactoring_id\n refactoring = project_refs[project_refs['id'] == refactoring_id]\n line.append(refactoring['refactoring_type'].iloc[0])\n line.append(refactoring['refactoring_detail'].iloc[0])\n line.append(row['old_path'])\n line.append(str(row['old_start_line']))\n line.append(row['new_path'])\n line.append(str(row['new_start_line']))\n if four_commits != None:\n print_to_csv(csv_path, line)\n # remove duplicates\n\n\n# get four commits by merge_commit_id\ndef get_merge_scenario(repo, project_id, merge_commits, merge_commit_id):\n row_series = merge_commits[(merge_commits['project_id'] == project_id) & (merge_commits['id'] == merge_commit_id)]\n # merge_commit, parent1(ours), parent2(theirs)\n four_commits = []\n four_commits.append(row_series['commit_hash'].iloc[0])\n parent1 = row_series['parent_1'].iloc[0]\n parent2 = row_series['parent_2'].iloc[0]\n merge_base = get_merge_base(repo, parent1, parent2)\n if merge_base!=None:\n four_commits.append(parent1)\n four_commits.append(parent2)\n four_commits.append(merge_base)\n return four_commits\n\n\ndef get_merge_base(repo, parent1, parent2):\n merge_base_commits = repo.merge_base(parent1, parent2)\n if len(merge_base_commits) > 0:\n return str(merge_base_commits[0])\n return None\n\ndef print_to_csv(path, line):\n if not os.path.isfile(path):\n with open(path, \"w\") as open_w:\n # header\n # open_w.write(\"ref_type;ref_detail;commit_hash;merge_parent;merge_commit;parent_1;parent_2;merge_base\")\n open_w.write(\n \"merge_parent;merge_commit;parent1;parent2;merge_base;ref_type;ref_detail;old_path;old_start_line;new_path;new_start_line\")\n with open(path, 'a') as open_a:\n open_a.write('\\n' + ';'.join(line))\n\n\n\ndef get_merge_scenario_involved_refactorings():\n conflicting_region_histories = get_conflicting_region_histories()\n refactoring_regions = get_accepted_refactoring_regions()\n merge_commits = get_merge_commits()\n\n cr_count_per_merge = conflicting_region_histories.groupby(\n 'merge_commit_id').conflicting_region_id.nunique().to_frame().rename(\n columns={'conflicting_region_id': 'cr_count'})\n\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(project_id))\n path = 'merge_scenario_' + str(counter) + '.csv'\n if project_id not in rr_grouped_by_project.groups:\n continue\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash', how='inner')\n involved = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n for index, group in involved.groupby('merge_commit_id'):\n for _, row in group.iterrows():\n four_commits = get_four_commits(merge_commits, row.merge_commit_id, project_id)\n save_to_csv(path, row, four_commits)\n\n\ndef get_four_commits(merge_commits, merge_commit_id, project_id):\n four_commits = []\n for index, row in merge_commits.iterrows():\n if row['project_id'] == project_id and row['id'] == merge_commit_id:\n four_commits.append(row['commit_hash'])\n four_commits.append(row['parent_1'])\n four_commits.append(row['parent_2'])\n # four_commits.append(get_merge_base_commit(row['parent_1'], row['parent_2']))\n break\n return four_commits\n\n\ndef save_to_csv(path, row, four_commits):\n line = []\n line.append(str(row.merge_commit_id))\n # merge scenario commits\n line.append(';'.join(four_commits))\n # refactoring details\n line.append(str(row.type))\n line.append(str(row.commit_hash))\n line.append(str(row.refactoring_id))\n line.append(str(row.refactoring_commit_id))\n\n with open(path, 'a') as open_a:\n open_a.write('\\n' + ';'.join(line))\n\n\ndef get_merge_commit_by_crh_and_devs_and_involved_refactorings():\n conflicting_region_histories = get_conflicting_region_histories()\n refactoring_regions = get_accepted_refactoring_regions()\n\n mc_by_crh_and_devs_and_involved_refactorings = pd.DataFrame()\n rr_grouped_by_project = refactoring_regions.groupby('project_id')\n counter = 0\n for project_id, project_crh in conflicting_region_histories.groupby('project_id'):\n counter += 1\n print('Processing project {}'.format(counter))\n\n involved_refs_count = pd.DataFrame(columns={'involved_refs'})\n if project_id in rr_grouped_by_project.groups:\n project_rrs = rr_grouped_by_project.get_group(project_id)\n crh_rr_combined = pd.merge(project_crh.reset_index(), project_rrs.reset_index(), on='commit_hash',\n how='inner')\n crh_with_involved_refs = crh_rr_combined[crh_rr_combined.apply(record_involved, axis=1)]\n involved_refs_count = crh_with_involved_refs.groupby('merge_commit_id').size().to_frame().rename(\n columns={0: 'involved_refs'})\n\n crh_count = project_crh.groupby('merge_commit_id').commit_hash.nunique().to_frame().rename(\n columns={'commit_hash': 'crh'})\n devs_count = project_crh.groupby('merge_commit_id').author_email.nunique().to_frame().rename(\n columns={'author_email': 'devs'})\n\n this_project = crh_count.join(devs_count, how='outer').join(involved_refs_count, how='outer').fillna(0).astype(\n int)\n mc_by_crh_and_devs_and_involved_refactorings = mc_by_crh_and_devs_and_involved_refactorings.append(this_project)\n\n return mc_by_crh_and_devs_and_involved_refactorings\n\n\ndef get_data_frame(df_name):\n try:\n return pd.read_pickle(df_name + '.pickle')\n except FileNotFoundError:\n df = getattr(sys.modules[__name__], 'get_' + df_name)()\n df.to_pickle(df_name + '.pickle')\n return df\n\n\ndef to_csv():\n cr_size_by_ir_size = get_conflicting_region_size_by_involved_refactoring_size()\n cr_by_ir_count = get_conflicting_regions_by_count_of_involved_refactoring()\n\n cr_size_by_ir_size.rename(columns={'refactoring_size': 'RefactoringSize'}, inplace=True)\n cr_size_by_ir_size.rename(columns={'conflicting_region_size': 'ConflictSize'}, inplace=True)\n cr_size_by_ir_size = cr_size_by_ir_size[['RefactoringSize', 'ConflictSize']]\n cr_size_by_ir_size.to_csv(path_or_buf=\"RefactoringSizeConflictSize.csv\", index=False)\n\n cr_by_ir_count['InvolvedRefactoring'] = cr_by_ir_count['involved_refactorings'] > 0\n cr_by_ir_count.rename(columns={'size': 'ConflictSize'}, inplace=True)\n cr_by_ir_count[['InvolvedRefactoring', 'ConflictSize']].to_csv(path_or_buf=\"ConflictSize.csv\", index=False)\n\n\ndef print_stats():\n df = get_data_frame('conflicting_regions_by_involved_refactorings_per_merge_commit')\n print(\"Involved Merge Scenarios: \" + str(df[df['involved_cr_count'] > 0].shape[0]))\n print(\"Involved Conflicting Regions: \" + str(df['involved_cr_count'].sum()))\n print(('-' * 80) + '\\nGeneral Stats Table')\n print_general_stats()\n print(('-' * 80) + '\\nGit Conflicts Table')\n print_git_conflict_stats()\n\n\ndef print_general_stats():\n con = get_db_connection()\n stat_list = list()\n stat_list.append(\n ('All Merge Scenarios', pd.read_sql_query('select count(*) from merge_commit group by project_id', con)))\n stat_list.append(('Conflicting Mer Ss', pd.read_sql_query(\n 'select count(*) from merge_commit where is_conflicting = 1 group by project_id', con)))\n stat_list.append(('CMS w/ Java Conf', pd.read_sql_query(\n 'select count(*) from merge_commit where id in (select merge_commit_id from conflicting_java_file) group by project_id',\n con)))\n stat_list.append(\n ('Conflicting Region', pd.read_sql_query('select count(*) from conflicting_region group by project_id', con)))\n stat_list.append(('Evolutionary Cmt',\n pd.read_sql_query('select count(*) from conflicting_region_history group by project_id', con)))\n stat_list.append(\n ('Refactoring in ECmt', pd.read_sql_query('select count(*) from refactoring where ({}) group by project_id'.\n format(get_refactoring_types_sql_condition()), con)))\n\n layout_str = '{}\\t|{}\\t|\\t{}\\t|\\t{} | {}'\n print(layout_str.format('Stat', 'Total', 'Corresponding Repos', 'Mean', 'SD'))\n for (title, stat) in stat_list:\n print(layout_str.format(title, stat.sum().iloc[0], stat.size, stat.mean().iloc[0], stat.std().iloc[0]))\n\n\ndef print_git_conflict_stats():\n con = get_db_connection()\n conflict_types = pd.read_sql_query(\n 'select type as conflict_type, count(*) from conflicting_java_file group by type order by count(*) desc', con)\n\n stat_list = list()\n for conflict_type in conflict_types['conflict_type']:\n stat_list.append(pd.read_sql_query(\n 'select count(*) from conflicting_java_file where type = \"{}\" group by project_id'.format(conflict_type),\n con))\n\n layout_str = '{}\\t|\\t{}\\t|\\t{}\\t|\\t{} | {}'\n print(layout_str.format('Type', 'Total', 'Corresponding Repos', 'Mean', 'SD'))\n for i in range(len(conflict_types)):\n conflict_type = conflict_types['conflict_type'][i]\n stat = stat_list[i]\n print(layout_str.format(conflict_type, stat.sum().iloc[0], stat.size, stat.mean().iloc[0], stat.std().iloc[0]))\n\n\ndef cohen_d(x, y):\n nx = len(x)\n ny = len(y)\n dof = nx + ny - 2\n return (mean(x) - mean(y)) / sqrt(((nx - 1) * std(x, ddof=1) ** 2 + (ny - 1) * std(y, ddof=1) ** 2) / dof)\n\n\ndef cohen_delta_refactoring_types_involved_vs_overall():\n all_refs = get_data_frame('refactorings_by_refactoring_type').fillna(0).T\n involved_refs = get_data_frame('involved_refactorings_by_refactoring_type').fillna(0).T\n\n cohen = dict()\n for refactoring_type in all_refs.columns:\n cohen[refactoring_type] = cohen_d(involved_refs[refactoring_type], all_refs[refactoring_type])\n print(\"{}:\\t{}\".format(refactoring_type, cohen[refactoring_type]))\n\n\nif __name__ == '__main__':\n # cohen_delta_refactoring_types_involved_vs_overall()\n # print_stats()\n # get_conflicting_regions_by_involved_refactorings_per_merge_commit()\n # get_merge_scenario_involved_refactorings()\n # get_involved_refactorings_by_refactoring_type()\n get_merge_scenarios_involved_refactorings()\n","sub_path":"stats/data_resolver.py","file_name":"data_resolver.py","file_ext":"py","file_size_in_byte":30746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"409055083","text":"from django.contrib.auth.backends import UserModel\nfrom django.http.response import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom .forms import SignUpForm\nfrom django.contrib import messages\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import authenticate, login, logout\n#from django.contrib.auth import get_fm_model\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\n# Create your views here.\n\n\n# Registration \ndef sign_up(request):\n if request.method == \"POST\":\n fm = SignUpForm(request.POST)\n if fm.is_valid():\n messages.success(request, 'Account Created Successfully!!')\n user = fm.save()\n user.is_active = False\n user.save()\n current_site = get_current_site(request)\n mail_subject = 'Activate your account.'\n message = render_to_string('reg_app/acc_activate_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': default_token_generator.make_token(user),\n })\n to_email = fm.cleaned_data.get('email')\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n return HttpResponse('Please confirm your email address to complete the registration')\n \n else:\n fm = SignUpForm()\n return render(request, 'reg_app/sign_up.html', {'form':fm})\n\n\ndef activate(request, uidb64, token):\n try:\n uid = urlsafe_base64_decode(uidb64).decode()\n fm = UserModel._default_manager.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n fm = None\n if fm is not None and default_token_generator.check_token(fm, token):\n fm.is_active = True\n fm.save()\n return HttpResponse(\"Thank you for your email confirmation. Now you can login your account.
    \")\n \n else:\n return HttpResponse('Activation link is invalid!')\n\n\n# Login\ndef user_login(request):\n if not request.user.is_authenticated:\n if request.method == 'POST':\n fm = AuthenticationForm(request=request, data=request.POST)\n if fm.is_valid():\n uname = fm.cleaned_data['fmname']\n upass = fm.cleaned_data['password']\n fm = authenticate(fmname=uname, password=upass)\n if fm is not None:\n login(request, fm)\n messages.success(request, 'Logedin Successfully !!!!!')\n return HttpResponseRedirect('/profile')\n else:\n fm = AuthenticationForm()\n return render(request, 'reg_app/fmlogin.html', {'form':fm})\n else:\n return HttpResponseRedirect('/profile/')\n\n\n# Profile\ndef user_profile(request):\n if request.user.is_authenticated:\n return render(request, 'reg_app/profile.html',{'name':request.fm })\n else:\n return HttpResponseRedirect('/login/')\n \n\n\n# Logout\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect('/login')\n","sub_path":"reg_pro/reg_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"551089438","text":"# Lab 7\n#\n# Name: John Wright\n# Instructor: Sussan Einakian\n# Section: 101-05\n\nimport unittest\nfrom groups import *\n\nclass TestChar(unittest.TestCase):\n def test_groups_of_3(self):\n list1 = [1,2,3,4,5,6,7,8]\n list2 = [1,2,3,4,5,6,7,8,9]\n list3 = [1,2,3,4,5,6,7,8,9,10]\n self.assertEqual(groups_of_3(list1),[[1, 2, 3], [4, 5, 6], [7, 8]])\n self.assertEqual(groups_of_3(list2),[[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n self.assertEqual(groups_of_3(list3),[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]])\n\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n","sub_path":"Lab7 - Due 1118-20191113/groups_tests.py","file_name":"groups_tests.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"175576818","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 25 15:41:33 2014\n\n@author: dvalovcin\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nfrom PyQt5 import QtWidgets, QtCore\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\n\nfrom hsganalysis.jones import JonesVector as JV\nimport interactivePG as ipg\n\ncos = lambda x: np.cos(x*np.pi/180)\nsin = lambda x: np.sin(x*np.pi/180)\n#\n# def wavePlate(t, d):\n# d = d* 2 * np.pi\n# t = 2*t\n# return np.array([\n# [1, 0, 0, 0],\n# [0, cos(t)**2+cos(d)*sin(t)**2, cos(t)*sin((t)*(1-cos(d)), sin(t)*sin(d))],\n# [0, cos(t)*sin((t)*(1-cos(d)), sin(t)**2+cos(d)*cos(t)**2, -cos(t)*sin(d))],\n# [0, -sin(t)*sin(d), cos(t)*sin(d), cos(d)]\n# ])\n#\n#\n#\n# class StokeVector(object):\n# def __init__(alpha=0, gamma=0, dop=1):\n# S0 = 1\n# S1 = dop * np.cos(2 * alpha * np.pi / 180) * np.cos(2 * gamma * np.pi / 180)\n# S2 = dop * np.sin(2 * alpha * np.pi / 180) * np.cos(2 * gamma * np.pi / 180)\n# S3 = dop * np.sin(2 * gamma * np.pi / 180)\n#\n# self.vec = np.array([S0, S1, S2, S3])\n#\n# def apply_retarder(t, d):\n# np.\n\n\ndef analyzerCurve(alpha=0, gamma=0, dop=1, eta=0.25):\n S0 = 1\n S1 = dop * np.cos(2 * alpha * np.pi / 180) * np.cos(2 * gamma * np.pi / 180)\n S2 = dop * np.sin(2 * alpha * np.pi / 180) * np.cos(2 * gamma * np.pi / 180)\n S3 = dop * np.sin(2 * gamma * np.pi / 180)\n x = np.linspace(0, 360, 500)\n eta *= 2*np.pi\n int= S0+S1/2*(1+np.cos(eta)) \\\n - S3*np.sin(eta)*sin(2*x) \\\n + S1/2*(1-np.cos(eta))*cos(4*x) \\\n + S2/2*(1-np.cos(eta))*sin(4*x)\n int /= int.max()\n return [x, int]\n\ndef storeCurve():\n\n\n curve = window.recalculate()\n window.plot(*curve, name=\",\".join([\":\".join([str(ii) for ii in jj])\n for jj in window.getCurrentValues()]))\n\n\n\napp = QtWidgets.QApplication([])\n\n\nwindow = ipg.ManipulateWindow()\nwindow.plot(*analyzerCurve())\nwindow.setManipulators([\n (\"α\", -90, 90, 0, 1),\n (\"γ\", -45, 45, 0, 1),\n (\"DOP\", 0, 1, 1, 0.01),\n (\"η\", 0.2, 0.3, 0.25, 0.01),\n])\nwindow.setCallable(analyzerCurve)\n\nwindow.plotItem.setLabel(\"bottom\", \"QWP Angle (°)\")\nwindow.plotItem.setLabel(\"left\", \"Normalized Intensity\")\nwindow.plotItem.setYRange(0, 1, padding=0)\nwindow.plotItem.setXRange(-5, 365, padding=0)\nwindow.plotItem.axes[\"bottom\"][\"item\"].setTickSpacing(45, 15)\nwindow.plotItem.axes[\"top\"][\"item\"].setTickSpacing(45, 15)\n\nwindow.plotItem.setLabel(\"bottom\", \"Sideband Order\")\n\nb = QtWidgets.QPushButton(\"Store Curve\")\nb.clicked.connect(storeCurve)\nwindow.centralWidget().layout().insertWidget(1, b)\nwindow.addLegend()\n\nwindow.show()\n\n# from pyqtgraph.console import ConsoleWidget as CW\n# c = CW(namespace={\"w\":window, \"wid\":QtWidgets, \"ipg\":ipg})\n# c.show()\n\n\n\napp.exec_()\n","sub_path":"polaragrams.py","file_name":"polaragrams.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"647240613","text":"'''\n@Author: Matthew Shabet\n@Date: 2020-07-31 23:30:00\n@LastEditTime: 2020-08-1 02:52:00\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n'''\nimport json\nimport csv\nimport requests\nimport os\nfrom datetime import datetime\n\nurl = \"https://dz-covid19.com/ws/?EIO=3&transport=polling\"\nsid = requests.get(url, headers={'Connection': 'close'}).text[12:32]\n\nurl = url + \"&sid=\" + sid\n\nresponse = requests.get(url, headers={'Connection': 'close'}).text\ndata = response[response.index(\"wilayas\") + 9:-1]\ndata = json.loads(data)\n\n# Create and open the CSV\nmkfile_time = datetime.strftime(datetime.now(), '%Y%m%d%H%M')\nfolder_path = './photo/Algeria/'+ mkfile_time + '/'\nif not os.path.exists(folder_path):\n os.makedirs(folder_path)\nfile = open(folder_path+'table.csv', 'w', newline='', encoding='utf-8-sig')\nwriter = csv.writer(file)\n\nheaders = [\"name\", \"confirmed\", \"deaths\", \"recovered\", \"active\"]\nwriter.writerow(headers)\nfor d in data:\n\trow = [d[h] for h in headers]\n\twriter.writerow(row)","sub_path":"scripts/Algeria-crawler.py","file_name":"Algeria-crawler.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"337047108","text":"import string\nfrom lxml import html\nfrom pprint import pprint # noqa\nfrom urllib.parse import urljoin, urlencode\n\n\ndef crawl_entry(context, entry):\n link = entry.find(\".//a\")\n url = context.dataset.data.url\n url = urljoin(url, link.get(\"href\"))\n _, member_id = url.rsplit(\"=\", 1)\n person = context.make(\"Person\")\n person.id = f\"coe-{member_id}\"\n person.add(\"name\", link.text)\n person.add(\"sourceUrl\", url)\n last_name, first_name = link.text.split(\", \", 1)\n person.add(\"lastName\", last_name)\n person.add(\"firstName\", first_name)\n person.add(\"position\", entry.findtext('.//span[@class=\"fonction\"]'))\n role, country = entry.findall('.//span[@class=\"infos\"]')\n person.add(\"summary\", role.text_content().strip())\n person.add(\"nationality\", country.text_content())\n person.add(\"topics\", \"role.pep\")\n context.emit(person)\n\n\ndef crawl(context):\n seen = set()\n data_url = context.dataset.data.url\n for letter in string.ascii_uppercase:\n params = {\"initial\": letter, \"offset\": 0}\n url = data_url + \"?\" + urlencode(params)\n while url is not None:\n res = context.http.get(url)\n doc = html.fromstring(res.text)\n for member in doc.findall('.//ul[@class=\"member-results\"]/li'):\n crawl_entry(context, member)\n\n seen.add(url)\n url = None\n for a in doc.findall('.//div[@id=\"pagination\"]//a'):\n next_url = urljoin(data_url, a.get(\"href\"))\n if next_url not in seen:\n url = next_url\n","sub_path":"opensanctions/crawlers/coe_assembly.py","file_name":"coe_assembly.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"229607607","text":"# -*- coding: utf-8 -*-\r\n# @File : quick_start.py\r\n# @Author: WangTong\r\n# @Date : 2018/8/20\r\n# @Desc :\r\nimport os\r\nimport sys\r\nimport subprocess\r\nimport sqlite3\r\nimport zipfile\r\nimport time\r\nimport datetime\r\nimport openpyxl\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\ncurPath = os.path.abspath(os.path.dirname(__file__))\r\nrootPath = os.path.split(curPath)[0]\r\nsys.path.append(rootPath)\r\nprint(sys.path)\r\nfrom hcp360.spiders.util.util_excel import ExcelUtil\r\n\r\n\r\nif __name__ == '__main__':\r\n p_haodaifu = subprocess.Popen([sys.executable, 'spider_haodaifu_executor.py'])\r\n p_wanfang = subprocess.Popen([sys.executable, 'spider_wanfang_executor.py'])\r\n p_medmeeting = subprocess.Popen([sys.executable, 'spider_medmeeting_executor.py'])\r\n\r\n while p_haodaifu.poll() is None:\r\n time.sleep(1)\r\n print(\"p_haodaifu.returncode=\" + str(p_haodaifu.returncode))\r\n if p_haodaifu.returncode == 0:\r\n p_weiyi = subprocess.Popen([sys.executable, 'spider_weiyi_executor.py'])\r\n while p_weiyi.poll() is None:\r\n time.sleep(1)\r\n print(\"p_weiyi.returncode=\" + str(p_weiyi.returncode))\r\n if p_weiyi.returncode == 0:\r\n p_chunyu = subprocess.Popen([sys.executable, 'spider_chunyu_executor.py'])\r\n while p_chunyu.poll() is None:\r\n time.sleep(1)\r\n print(\"p_chunyu.returncode=\" + str(p_chunyu.returncode))\r\n if p_chunyu.returncode == 0:\r\n p_39 = subprocess.Popen([sys.executable, 'spider_39_executor.py'])\r\n\r\n is_complete = False\r\n while p_39.poll() is None or p_wanfang.poll() is None or p_medmeeting.poll() is None:\r\n time.sleep(1)\r\n print(\"p_39.returncode=\" + str(p_39.returncode))\r\n print(\"p_wanfang.returncode=\" + str(p_wanfang.returncode))\r\n print(\"p_medmeeting.returncode=\" + str(p_medmeeting.returncode))\r\n if p_39.returncode == 0 and p_wanfang.returncode == 0 and p_medmeeting.returncode == 0:\r\n try:\r\n conn = sqlite3.connect('hcp360.db', timeout=20)\r\n cursor = conn.cursor()\r\n sql = \"INSERT INTO Basic(az_code,doctor_name,hos_name,hos_depart,sex,admin_title) SELECT az_code,doctor_name,hos_name,hos_depart,doc_sex,admin_title FROM Info WHERE az_code in (SELECT author_code FROM Publication WHERE author_code IN (SELECT az_code FROM Info WHERE az_code NOT IN (SELECT DISTINCT az_code FROM Basic)) UNION SELECT az_code FROM Meeting WHERE az_code IN (SELECT az_code FROM Info WHERE az_code NOT IN (SELECT DISTINCT az_code FROM Basic)))\"\r\n conn.execute(sql)\r\n conn.commit()\r\n ExcelUtil.set_basic()\r\n except Exception as e:\r\n logger.error(\"quick_start\", e)\r\n finally:\r\n is_complete = True\r\n cursor.close()\r\n conn.close()\r\n\r\n while is_complete is True:\r\n excel_haodaifu_path = \"excel_haodaifu_spider.xlsx\"\r\n excel_wanfang_path = \"excel_wanfang_spider.xlsx\"\r\n excel_medmeeting_path = \"excel_medmeeting_spider.xlsx\"\r\n excel_all_path = \"excel_all.xlsx\"\r\n try:\r\n if os.path.exists(excel_all_path) is False:\r\n wb = openpyxl.Workbook()\r\n wb.save(excel_all_path)\r\n wb.close()\r\n except Exception as e:\r\n print(e)\r\n try:\r\n ExcelUtil.copy_sheet(excel_haodaifu_path, \" Basic\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_haodaifu_path, \"Internet\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_haodaifu_path, \"Times\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_haodaifu_path, \"Internet-KW\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_haodaifu_path, \"Society\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_wanfang_path, \"Publication\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_wanfang_path, \"Connection\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_wanfang_path, \"Publication KW Count\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_wanfang_path, \"Publication AZKW Count\", excel_all_path)\r\n ExcelUtil.copy_sheet(excel_medmeeting_path, \"Meeting\", excel_all_path)\r\n except Exception as e:\r\n logger.error(\"copy_sheet\", e)\r\n\r\n # with open(\"sql_offline.sql\", \"r\", encoding=\"utf-8\") as f:\r\n # text = f.read()\r\n # try:\r\n # conn = sqlite3.connect('hcp360.db', timeout=20)\r\n # cursor = conn.cursor()\r\n # print(\"正在执行sql_offline.sql...\")\r\n # for row in cursor.execute(text):\r\n # graph_item = GraphItem()\r\n # graph_item['az_code'] = row[0]\r\n # graph_item['xueshu_score'] = row[1]\r\n # graph_item['shejiao_score'] = row[2]\r\n # graph_item['chanpin_score'] = row[3]\r\n # # if int(row[4]) > 0:\r\n # # graph_item['prefer'] = \"发表和阅读学术文章,\"\r\n # # if int(row[5]) > 0:\r\n # # graph_item['prefer'] = \"活跃在专业学术团体(学会)\"\r\n # # else:\r\n # # graph_item['not_prefer'] = \"活跃在专业学术团体(学会)\"\r\n # ExcelUtil.set_graph(graph_item)\r\n # print(\"正在写入Graph\")\r\n # except Exception as e:\r\n # logger.error(\"quick_start\", e)\r\n # finally:\r\n # cursor.close()\r\n # conn.close()\r\n\r\n # 新建压缩包,放文件进去,若压缩包已经存在,将覆盖。可选择用a模式,追加\r\n print(\"正在备份单机库...\")\r\n azip = zipfile.ZipFile('hcp360db_' + str(datetime.datetime.now().strftime('%Y%m%d')) + '.zip', 'w')\r\n azip.write('hcp360.db', compress_type=zipfile.ZIP_LZMA)\r\n azip.close()\r\n print(\"本次爬取全部结束!\")\r\n\r\n break\r\n\r\n# if __name__ == '__main__':\r\n# excel_all_path = \"excel_all.xlsx\"\r\n# excel_haodaifu_path = \"excel_haodaifu_spider.xlsx\"\r\n# ExcelUtil.copy_sheet(excel_haodaifu_path, \"Times\", excel_all_path)\r\n","sub_path":"quick_start.py","file_name":"quick_start.py","file_ext":"py","file_size_in_byte":6110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"53532218","text":"total = 0\nitems = \"\"\n\n\nwhile True:\n respuestaAT = input(\"Choose Report Type (\\\"A\\\" or \\\"T\\\"): \")\n if respuestaAT==\"A\":\n break\n elif respuestaAT==\"T\":\n break\n else:\n print(respuestaAT, \"is invalid input\")\n\n\ndef adding_report(report):\n if report== \"A\":\n print(\"\\nItems\")\n print(items)\n print(\"Total\")\n print(total)\n elif report == \"T\":\n print(\"\\nTotal\")\n print(total)\n\nprint(\"Input an integer to add to the total or \\\"Q\\\" to quit\")\nwhile True:\n item=input(\"Enter an integer or \\\"Q\\\": \")\n if item.isdigit():\n if respuestaAT==\"A\":\n items = items + item + \"\\n\"\n total = total + int(item)\n elif respuestaAT==\"T\":\n items = items + item + \"\\n\"\n total = total + int(item)\n elif item.startswith(\"Q\"):\n if respuestaAT==\"A\":\n adding_report(respuestaAT)\n elif respuestaAT==\"T\":\n adding_report(respuestaAT)\n break\n elif item==\"\":\n pass\n else:\n print(item, \"is invalid input\")\n\n\n\n","sub_path":"Module 5 Final Evaluation/FinalExamVersionWithFunction.py","file_name":"FinalExamVersionWithFunction.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"375216426","text":"class UnionFindSet(object):\n def __init__(self, grid):\n\n m, n = len(grid), len(grid[0])\n self.roots = [-1 for _ in range(m * n)]\n self.rank = [0 for _ in range(m * n)]\n self.count = 0\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n self.roots[i * n + j] = i * n + j\n self.count += 1\n\n def find(self, member):\n tmp = []\n while member != self.roots[member]:\n tmp.append(member)\n member = self.roots[member]\n for root in tmp:\n self.roots[root] = member\n return member\n\n def union(self, p, q):\n parentP = self.find(p)\n parentQ = self.find(q)\n if parentP != parentQ:\n if self.rank[parentP] > self.rank[parentQ]:\n self.roots[parentQ] = parentP\n elif self.rank[parentP] < self.rank[parentQ]:\n self.roots[parentP] = parentQ\n else:\n self.roots[parentQ] = parentP\n self.rank[parentP] -= 1\n self.count -= 1\n\n\nclass Solution(object):\n def numIslands(self, grid: List[List[str]]) -> int:\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if not grid or not grid[0]:\n return 0\n\n dx = [1, -1, 0, 0]\n dy = [0, 0, 1, -1]\n\n ufs = UnionFindSet(grid)\n m, n = len(grid), len(grid[0])\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n\n for k in range(4):\n x = i + dx[k]\n y = j + dy[k]\n\n if 0 <= x < m and 0 <= y < n and grid[x][y] == '1':\n ufs.union(i * n + j, x * n + y)\n # print ufs.roots\n\n return ufs.count\n","sub_path":"task 6/岛屿数量 并查集.py","file_name":"岛屿数量 并查集.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"354034162","text":"import numpy as np\n\n############################### 함수\n\ndef extracting(tau, E, P, obj):\n in_put = []\n out_put = []\n a = tau * (E-1)\n for i in range(a, len(obj)-P):\n b=[]\n for j in range(i-a, i+tau, tau):\n b.append(obj[j])\n in_put.append(b)\n out_put.append(obj[i+P])\n return np.array(in_put), np.array(out_put)\n\n\ndef SM(input_data, output_data, E):\n sm = 0\n for i in range(len(input_data)):\n temp = []\n for j in range(len(input_data)):\n temp.append(Dist(input_data[i], input_data[j], E))\n\n temp = np.array(temp)\n\n nonzerotemp = temp[np.nonzero(temp)]\n nonzerotemp.sort()\n\n for j in range(len(temp)):\n if nonzerotemp[0] == temp[j]:\n idx = j\n\n minDist = temp[idx]\n\n sm += np.abs(output_data[i] - output_data[idx]) / minDist\n # print(format(\"%f th step minDist: %f, minIndex: %f, sm: %f\") % (i, minDist, idx, sm))\n\n sm = 1 - sm / len(input_data)\n\n return sm\n\n\ndef Dist(x1, x2, E):\n dist = 0\n for i in range(0, E):\n dist += np.square(x1[i] - x2[i])\n\n return np.sqrt(dist)\n\n################################################################## 코드 시작\n\n# train에 학습할 데이터를 리스트로 만들어주세요.\ntrain = []\n# P는 예측하려고 하는 날의 수 입니다. 예를 들면 내일의 값을 예측하려고 하면 P = 1, 3일 뒤를 예측하려고 하면 P = 3\nP = 1\nf = open('여기에 저장 위치 설정해주세요', 'w')\nfor E in range(4, 11):\n for tau in range(1, 21):\n temp = []\n a1, a2 = extracting(tau, E, P, train)\n sm = SM(a1, a2, E)\n temp.append(tau)\n temp.append(E)\n temp.append(sm)\n print(format(\"E: %f, tau: %f sm: %f\") % (E, tau, sm))\n f.write(format(\"E: %f, tau: %f sm: %f\") % (E, tau, sm) + '\\n')\nf.close()\n","sub_path":"smoothness/smoothness원본.py","file_name":"smoothness원본.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"217696149","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport sys\r\nimport mne\r\nimport numpy as np\r\n\r\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\nsys.path.append(BASE_PATH)\r\n\r\nfrom visualize.visualize import visualize_stc\r\n\r\n\r\ndef calc_zmap(stc_fpath, avg_stc_fpath, var_stc_fpath, outfile):\r\n sub_stc = mne.read_source_estimate(stc_fpath, 'fsaverage')\r\n avg_stc = mne.read_source_estimate(avg_stc_fpath, 'fsaverage')\r\n var_stc = mne.read_source_estimate(var_stc_fpath, 'fsaverage')\r\n sd = np.sqrt(var_stc.data)\r\n\r\n t_data = (sub_stc.data - avg_stc.data) / sd\r\n zmap_stc = sub_stc.copy()\r\n zmap_stc.data = t_data\r\n\r\n zmap_stc.save(outfile)\r\n\r\n data_outfile = outfile + '-data.csv'\r\n np.savetxt(data_outfile, t_data, fmt='%.5f', delimiter=\",\")\r\n\r\n return zmap_stc\r\n\r\n\r\ndef plot_zmap(zmap_stc_fname, subject, fig_fname, subjects_dir):\r\n visualize_stc(zmap_stc_fname, fig_fname, subjects_dir, subject, colormap='coolwarm', clim=dict(kind='value', pos_lims=[0.0, 1.0, 2.0]))\r\n\r\n\r\ndef main(subject, task, data_dir, subjects_dir, averages_dir, cohorts='age', window=True):\r\n if cohorts is not None:\r\n raw_fname = os.path.join(data_dir, subject, 'ica', f'{subject}-{task}-ica-recon.fif')\r\n raw = mne.io.Raw(raw_fname)\r\n birthyear = raw.info['subject_info']['birthday'][0]\r\n meas_year = raw.info['meas_date'].year\r\n age = meas_year - birthyear\r\n cohort_idx = int((age - 8) / 10)\r\n print('Cohort:', cohort_idx)\r\n\r\n avg_stc_fpath = os.path.join(averages_dir, f'avg-cohort-{cohort_idx}-camcan')\r\n var_stc_fpath = os.path.join(averages_dir, f'var-cohort-{cohort_idx}-camcan')\r\n if cohorts == 'random':\r\n avg_stc_fpath += '-random'\r\n var_stc_fpath += '-random'\r\n else:\r\n avg_stc_fpath = os.path.join(averages_dir, f'avg-camcan')\r\n var_stc_fpath = os.path.join(averages_dir, f'var-camcan')\r\n\r\n outdir = os.path.join(data_dir, subject, 'zmap')\r\n os.makedirs(outdir, exist_ok=True)\r\n\r\n if window:\r\n for i in range(40, 390, 50):\r\n stc_fpath = os.path.join(data_dir, subject, 'psd', f'{subject}-{task}-{i}-psd-fsaverage')\r\n if cohorts is not None:\r\n zmap_outfile = os.path.join(outdir, f'{subject}-{task}-{i}-{cohorts}-psd-zmap')\r\n fig_fpath = os.path.join(data_dir, subject, 'fig', f'{subject}-{task}-{i}-{cohorts}-cohort-psd-zmap.png')\r\n else:\r\n zmap_outfile = os.path.join(outdir, f'{subject}-{task}-{i}-psd-zmap')\r\n fig_fpath = os.path.join(data_dir, subject, 'fig', f'{subject}-{task}-{i}-psd-zmap.png')\r\n zmap = calc_zmap(stc_fpath, avg_stc_fpath, var_stc_fpath, zmap_outfile)\r\n plot_zmap(zmap_outfile, subject, fig_fpath, subjects_dir)\r\n else:\r\n stc_fpath = os.path.join(data_dir, subject, 'psd', f'{subject}-{task}-full-psd-fsaverage')\r\n if cohorts is not None:\r\n zmap_outfile = os.path.join(outdir, f'{subject}-{task}-{cohorts}-psd-zmap')\r\n fig_fpath = os.path.join(data_dir, subject, 'fig', f'{subject}-{task}-{cohorts}-psd-zmap.png')\r\n else:\r\n zmap_outfile = os.path.join(outdir, f'{subject}-{task}-psd-zmap')\r\n fig_fpath = os.path.join(data_dir, subject, 'fig', f'{subject}-{task}-psd-zmap.png')\r\n zmap = calc_zmap(stc_fpath, avg_stc_fpath, var_stc_fpath, zmap_outfile)\r\n plot_zmap(zmap_outfile, subject, fig_fpath, subjects_dir)\r\n\r\n\r\nif __name__ == '__main__':\r\n subject = sys.argv[1]\r\n task = sys.argv[2]\r\n data_dir = sys.argv[3]\r\n subjects_dir = sys.argv[4]\r\n averages_dir = sys.argv[5]\r\n if len(sys.argv) > 6:\r\n cohorts = sys.argv[6]\r\n else:\r\n cohorts = None\r\n\r\n main(subject, task, data_dir, subjects_dir, averages_dir, cohorts=cohorts, window=True)\r\n\r\n","sub_path":"pipeline-tbi/zmap/calc_zmap.py","file_name":"calc_zmap.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"177176409","text":"# !/usr/bin/python3\nimport sys\nfrom os import path\n\n# set up dependencies\n__ROOT__ = path.dirname(path.realpath(__file__))\nsys.path.insert(0, path.join(__ROOT__, \"python\"))\n\nfrom bbcode.common import cmd, log, thread\nfrom bbcode import n2n, ssh, rsync, os\nfrom bbcode import code\n\n@cmd.module(\"\", as_main=True,\n description=\"\"\"\nBBCode Script Tools\n\nThis script contains many useful packages, user can invoke\nmodules with command line flags.\n\nContact the developer: cunxinshuihua@gmail.com for more support.\n\"\"\")\ndef main(args):\n cmd.CmdStorage.get_parser(\"\").print_help()\n\n@cmd.option(\"-v\", \"--verbosity\", metavar=\"LEVEL\",\n choices=log.LOG_NAMES, default=log.level2name(log.DEBUG),\n help=\"log verbosity to pring information, \" + \\\n \"available options: {}\".format(log.LOG_NAMES) + \\\n \" by default {}\".format(log.level2name(log.DEBUG)))\n@cmd.prepare()\ndef prepare_func(args):\n log.Init(log.name2level(args.verbosity))\n\nif __name__ == \"__main__\":\n cmd.Run()\n # run registered service if possible\n thread.Run()\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"387274508","text":"# Author: Yun Chul Chang\n# Creates a json file to pass bulk random user data to Auth0 server.\n# Unfortunately, I haven't figured out the schema for passing in password, \n# so this project is currently abandoned. This shows how to create random\n# strings (combination of chars and ints), generate gravatar link, and \n# put all the results into json file. \n\n# import code for encoding urls and generating md5 hashes\nimport urllib, hashlib\n\n# other imports\nimport json\nimport datetime\nfrom datetime import timedelta \nimport string\nimport random\nfrom collections import OrderedDict # python dict is weird\n \n# random string function\ndef rand_str_generator(size, chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n# date to string converter\ndef dateToStr(o):\n if isinstance(o, datetime.datetime):\n formattedDate = o.__str__()\n formattedDate = formattedDate[:10] + 'T' + formattedDate[11:23] + 'Z'\n return formattedDate\n\ndata = OrderedDict()\n\n# Specifications\nnumberOfUsers = 2\nidStrLength = 24\nnicknameLength = 5\ndatabase = 'TPCH'\ngravatar_url = 'https://ui-avatars.com/api/?name=E+Xample'\nnow = datetime.datetime.now()\ndump = [dict() for x in range(numberOfUsers)]\n\nwith open('result.json', 'w') as outfile:\n outfile.write('[')\n for x in range(numberOfUsers):\n nickname = 'example'\n nickname += str(x)\n data['user_id'] = 'auth0|' + rand_str_generator(idStrLength)\n data['given_name'] = 'example'\n data['family_name'] = 'example'\n data['nickname'] = nickname\n data['name'] = nickname + '@' + 'example.com'\n data['email'] = nickname + '@' + 'example.com'\n data['email_verified'] = True\n data['picture'] = gravatar_url\n data['identities'] = {'connection': database}\n data['created_at'] = dateToStr(now+ timedelta(seconds=x))\n data['updated_at'] = dateToStr(now+ timedelta(seconds=x))\n json.dump(data, outfile)\n if x != numberOfUsers-1:\n outfile.write(', ')\n outfile.write(']')","sub_path":"dbgenerator/random_user_gen/random_user_gen.py","file_name":"random_user_gen.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"590377736","text":"import Performance as Pce\nimport pandas as pd\nimport numpy as np\n\nclass PerformancePandas(Pce.Performance):\n def __init__(self, nameWorkbook, nameSheet):\n try:\n self.file_pandas = pd.read_excel(nameWorkbook, sheet_name=nameSheet)\n self.data_pandas = np.array(self.file_pandas)\n \n except:\n print('Possible list of error: \\n -> The workbook is not in this directory \\n -> The workbook name is incorrect \\n -> The Name Sheet is not correct or not exists')\n \n def similitud(self, search_chain, find_chain):\n self.N_len = len(find_chain)\n self.n_len = len(search_chain)\n\n return self.n_len / self.N_len\n \n def convert_to_directory(self, list_1, list_2):\n '''Esta funcion convierte dos listas con las\n mismas dimensiones a un diccionario\n la lista 1 corresponde a las keys\n la lista 2 corresponde a los valores'''\n\n list_1 = [str(i) for i in list_1]\n list_2 = [float(i) for i in list_2]\n\n self.dictionary = dict(zip(list_1, list_2))\n\n return self.dictionary\n\n '''\n https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary-in-python\n \n '''\n\n def dictionary_to_pyMatrix(self, dictionary):\n self.pyMatrix = list(dictionary.items())\n self.pyMatrix.sort(key=lambda x: -x[1])\n\n '''\n key = lambda x : x[0] de menor a mayor con los keys\n key = lambda x : -x[0] de mayor a menor con los keys \n key = lambda x : -x[1] de mayor a menor con los values\n key = lambda x : x[1] de menor a mayor con los values\n\n '''\n\n return self.pyMatrix\n\n def busqueda(self, palabra_de_busqueda):\n self.encontrados = []\n for self.i in self.data_pandas[:,0]:\n self.i = str(self.i)\n if palabra_de_busqueda in self.i:\n self.encontrados.append(list((self.i, self.similitud(palabra_de_busqueda, self.i))))\n \n '''Hay que regresar la lista ordenada\n primero necesitamos saber cual es el que tiene mas\n coincidencia, para ello haremos diccionarios y luego\n haremos una lista ordenando las probabilidades de mayor a \n menor para luego quedarnos con el primer'''\n self.aux_numpy_list = np.array(self.encontrados)\n #print(self.aux_numpy_list[:,1])\n self.aux_dictionary = self.convert_to_directory(self.aux_numpy_list[:,0], self.aux_numpy_list[:,1])\n self.encontrados = self.dictionary_to_pyMatrix(self.aux_dictionary)\n\n return self.encontrados\n\n def obtener_indice(self):\n\n return np.where(self.data_pandas == self.encontrados[0][0])#siempre es la posicion 0,0 porque la lista ya esta ordenada\n \n def obtener_data(self, index):\n \n self.tabla = []\n for i in self.data_pandas[index:, 0]:\n i = str(i)\n if 'rows selected' in i:\n break\n else:\n self.tabla.append(i)\n\n return self.tabla\n\n def text_To_Columns(self, Matrix):\n try:\n '''Matriz de Numpy con datos y con columnas separadas'''\n self.numpy_matrix = np.array([Matrix[i].split()\n for i in range(len(Matrix))])\n except:\n print('En alguna de las filas de la matriz no hay datos, verifiue las dimensiones de la matriz que paso')\n\n '''NOTA ------>>>>> No importa que en el excel no se haya \n hecho la funcion text to columns, \n puede mandarsele una matriz que contenga a vector con la \n informacion ya que no toma en cuenta espacios en blanco'''\n return self.numpy_matrix\n \n def alignment(self, a, b):\n '''El primer parametro de esta funcion siempre debe ser\n el vector base'''\n self.a_list = list(a)\n self.b_list = list(b)\n self.a_list.sort()\n self.b_list.sort()\n #hacerlos del mismo tamaño\n for i in range(len(self.a_list)-len(self.b_list)):\n self.b_list.append(None)\n\n for i in range(len(self.a_list)):\n if not self.a_list[i] == self.b_list[i]:\n self.b_list.insert(i, None)\n self.b_list.pop(-1)\n\n return self.a_list, self.b_list\n\n def create_Matrix_Excel(self, list_Base, list_Sec, dic_Base, dic_Sec):\n\n self.sortMatrix = []\n\n for i in range(len(list_Base)):\n try:\n self.sortMatrix.append(list((int(dic_Base[list_Base[i]]),\n list_Base[i],\n int(dic_Sec[list_Base[i]]),\n list_Sec[i])))\n except:\n self.sortMatrix.append(list((int(dic_Base[list_Base[i]]),\n list_Base[i], None, None)))\n\n return self.sortMatrix\n\n\n def write_pandas_xlsx_document(self, dataMatrix, fileName):\n \n self.excel_file = pd.DataFrame(dataMatrix)\n self.excel_file.to_excel(fileName)\n \n '''def write_pandas_xlsx_document_dictionary(self, dictionary, fileName):\n matrix = []\n for i, j in dictionary.items():\n matrix.append(list((i, j)))\n\n self.excel_d_file = pd.DataFrame(matrix)\n self.excel_d_file.to_excel(fileName) '''\n","sub_path":"hoy/fallos/prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"160850879","text":"# -*- coding: utf-8 -*-\nn=int(input('digite a quantidade de termos da lista: '))\n\ndef media(lista):\n soma = 0\n for i in range(0,len(lista),1):\n soma = soma + lista[i]\n resultado = soma/len(lista)\n return resultado\ndef var(lista):\n somatorio=0\n for i in range(0,len(lista),1):\n somatorio=somatorio+(lista[i]-media)**2\n delta=(1/(n-1))*somatorio\n var=delta**(1/2)\n return(var)\n#Baseado na função acima, escreva a função para calcular o desvio padrão de uma lista\n\n\n#Por último escreva o programa principal, que pede a entrada e chama as funções criadas. ","sub_path":"moodledata/vpl_data/203/usersdata/265/96649/submittedfiles/estatistica.py","file_name":"estatistica.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"420699171","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n#原理地址 https://www.jianshu.com/p/d8a4d3b9ded0\n\"\"\"\n利用 Python 实现线性回归模型\n\"\"\"\nclass LinerRegressionModel(object):\n def __init__(self, data):\n self.data = data\n self.x = data[:, 0]\n self.y = data[:, 1]\n\n def log(self, a, b):\n print(\"计算出的线性回归函数为:\\ny = {:.5f}x + {:.5f}\".format(a, b))\n\n def plt(self, a, b):\n plt.plot(self.x, self.y, 'o', label='data', markersize=10)\n plt.plot(self.x, a * self.x + b, 'r', label='line')\n plt.legend()\n plt.show()\n\n def least_square_method(self):\n \"\"\"\n 最小二乘法的实现\n \"\"\"\n def calc_ab(x, y):\n sum_x, sum_y, sum_xy, sum_xx = 0, 0, 0, 0\n n = len(x)\n for i in range(0, n):\n sum_x += x[i]\n sum_y += y[i]\n sum_xy += x[i] * y[i]\n sum_xx += x[i]**2\n a = (sum_xy - (1/n) * (sum_x * sum_y)) / (sum_xx - (1/n) * sum_x**2)\n b = sum_y/n - a * sum_x/n\n return a, b\n a, b = calc_ab(self.x, self.y)\n self.log(a, b)\n self.plt(a, b)\n\n\ndata = np.array([[1, 2.5], [2, 3.3], [2.5, 3.8],[3, 4.5], [4, 5.7], [5, 6]])\n\nmodel = LinerRegressionModel(data)\nmodel.least_square_method()","sub_path":"机器学习 -学习/一元线性回归例子.py","file_name":"一元线性回归例子.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"650377298","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\n\nfrom odoo import fields, models\n\n\nclass ResPartner(models.Model):\n\n _inherit = 'res.partner'\n\n customer = fields.Boolean(string='Is a Customer', default=True,\n help=\"Check this box if this contact is a Customer.\")\n \t\n","sub_path":"custom_addons/health_planet_core/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"233987178","text":"from typing import List\n\nSELFID = \"0\" * 32\n\n\ndef maybe_and(sql, a):\n if a:\n return sql + \" AND \"\n else:\n return sql\n\n\ndef maybe_or(sql, a):\n if a:\n return sql + \" OR \"\n else:\n return sql\n\n\nclass ReferenceObjectSearcher:\n def __init__(self, self_memid=SELFID):\n self.self_memid = self_memid\n\n def is_filter_empty(self, filter_dict):\n r = filter_dict.get(\"ref_obj_range\")\n if r and len(r) > 0:\n return False\n r = filter_dict.get(\"ref_obj_exact\")\n if r and len(r) > 0:\n return False\n r = filter_dict.get(\"memories_range\")\n if r and len(r) > 0:\n return False\n r = filter_dict.get(\"memories_exact\")\n if r and len(r) > 0:\n return False\n t = filter_dict.get(\"triples\")\n if t and len(t) > 0:\n return False\n return True\n\n def range_queries(self, r, table, a=False):\n \"\"\" this does x, y, z, pitch, yaw, etc.\n input format for generates is \n {\"xmin\": float, xmax: float, ... , yawmin: float, yawmax: float}\n \"\"\"\n sql = \"\"\n vals = []\n for k, v in r.items():\n if \"min\" in k:\n sql = maybe_and(sql, len(vals) > 0)\n sql += table + \".\" + k.replace(\"min\", \"\") + \">? \"\n vals.append(v)\n if \"max\" in k:\n sql = maybe_and(sql, len(vals) > 0)\n sql += table + \".\" + k.replace(\"max\", \"\") + \" 0)\n sql += table + \".\" + k + \"=? \"\n vals.append(v)\n return sql, vals\n\n def triples(self, triples, a=False):\n # currently does an \"and\": the memory needs to satisfy all triples\n vals = []\n if not triples:\n return \"\", vals\n sql = \"ReferenceObjects.uuid IN (SELECT subj FROM Triples WHERE \"\n for t in triples:\n sql = maybe_or(sql, len(vals) > 0)\n vals.append(t[\"pred_text\"])\n if t.get(\"obj_text\"):\n sql += \"(pred_text, obj_text)=(?, ?)\"\n vals.append(t[\"obj_text\"])\n else:\n sql += \"(pred_text, obj)=(?, ?)\"\n vals.append(t[\"obj\"])\n sql += \" GROUP BY subj HAVING COUNT(subj)=? )\"\n vals.append(len(triples))\n return sql, vals\n\n def get_query(self, filter_dict, ignore_self=True):\n if self.is_filter_empty(filter_dict):\n query = \"SELECT uuid FROM ReferenceObjects\"\n if ignore_self:\n query += \" WHERE uuid !=?\"\n return query, [self.self_memid]\n else:\n return query, []\n\n query = (\n \"SELECT ReferenceObjects.uuid FROM ReferenceObjects\"\n \" INNER JOIN Memories as M on M.uuid=ReferenceObjects.uuid\"\n \" WHERE \"\n )\n\n args = []\n fragment, vals = self.range_queries(\n filter_dict.get(\"ref_obj_range\", {}), \"ReferenceObjects\"\n )\n query = maybe_and(query, len(args) > 0)\n args.extend(vals)\n query += fragment\n\n fragment, vals = self.exact_matches(\n filter_dict.get(\"ref_obj_exact\", {}), \"ReferenceObjects\"\n )\n query = maybe_and(query, len(args) > 0 and len(vals) > 0)\n args.extend(vals)\n query += fragment\n\n fragment, vals = self.range_queries(filter_dict.get(\"memories_range\", {}), \"M\")\n query = maybe_and(query, len(args) > 0 and len(vals) > 0)\n args.extend(vals)\n query += fragment\n\n fragment, vals = self.exact_matches(filter_dict.get(\"memories_exact\", {}), \"M\")\n query = maybe_and(query, len(args) > 0 and len(vals) > 0)\n args.extend(vals)\n query += fragment\n\n fragment, vals = self.triples(filter_dict.get(\"triples\", []))\n query = maybe_and(query, len(args) > 0 and len(vals) > 0)\n args.extend(vals)\n query += fragment\n\n if ignore_self:\n query += \" AND ReferenceObjects.uuid !=?\"\n args.append(self.self_memid)\n return query, args\n\n def search(self, memory, filter_dict) -> List[\"ReferenceObjectNode\"]: # noqa T484\n \"\"\"Find ref_objs matching the given filters\n filter_dict has children:\n \"ref_obj_range\", dict, with keys \"min\" or \"max\", \n (that is the string \"min\" prepended to the column name)\n and float values vmin and vmax respectively. \n is any column in the ReferenceObjects table that\n is a numerical value. filters on rows satisfying the inequality \n > vmin or < vmax\n \"ref_obj_exact\", dict, with keys \"\"\n is any column in the ReferenceObjects table\n checks exact matches to the value\n \"memories_range\" and \"memories_exact\" are the same, but columns in the Memories table\n \"triples\" list [t0, t1, ...,, tm]. each t in the list is a dict\n with form t = {\"pred_text\": , \"obj_text\": }\n or t = {\"pred_text\": , \"obj\": }\n currently returns memories with all triples matched \n \"\"\"\n query, args = self.get_query(filter_dict)\n memids = [m[0] for m in memory._db_read(query, *args)]\n return [memory.get_mem_by_id(memid) for memid in memids]\n\n\nif __name__ == \"__main__\":\n filter_dict = {\n \"ref_obj_range\": {\"minx\": 3},\n \"memories_exact\": {\"create_time\": 1},\n \"triples\": [\n {\"pred_text\": \"has_tag\", \"obj_text\": \"cow\"},\n {\"pred_text\": \"has_name\", \"obj_text\": \"eddie\"},\n ],\n }\n","sub_path":"python/base_agent/memory_filters.py","file_name":"memory_filters.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"625422398","text":"import csv\nimport json\n\ncollection = {}\n\ndef to_list(v):\n return v.replace(' ','').split(',')\n\nSKIPPED_FIELDS = [\"length\", \"type\"]\n\nwith open(\"sessions.csv\") as f:\n reader = csv.DictReader(f)\n for row in reader:\n _id = row.pop(\"item\")\n doc = {}\n for k, v in row.items():\n if v=='' or k in SKIPPED_FIELDS:\n continue\n if k in ['speakers', 'tags']:\n doc[k] = to_list(v)\n else:\n doc[k] = v\n collection[_id] = doc\n\n\n# print(json.dumps(collection, indent=2))\nwith open (\"sessions.json\", \"w\") as f:\n json.dump(collection, f, indent=2)\n","sub_path":"data/parse_sessions.py","file_name":"parse_sessions.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"602761444","text":"\"\"\"\nupdate_instance_termination_date.py\n\nThis module allows a user to change the value of the TerminationDate tag for instances.\n\"\"\"\n__author__ = 'sedwards'\n\nimport argparse\nimport sys\nfrom datetime import datetime, timedelta\nfrom typing import Dict\n\nfrom syslinkats import ats_config_file\nfrom syslinkats.framework.aws.aws_instance import AWSInstance\nfrom syslinkats.framework.common.argparse_helpers import bool_from_str\nfrom syslinkats.framework.file_io.json_file_operations import read_json_data_from_file\nfrom syslinkats.framework.logging.auto_indent import AutoIndent\nfrom syslinkats.framework.msteams.common.constants import (\n TEST_DAY_INSTANCE_WEBHOOK,\n DAILY_INSTANCES_WEBHOOK\n)\nfrom syslinkats.framework.msteams.msteams_operations import post_teams_instance_deployment_message\n\nLOGGER = AutoIndent(stream=sys.stdout)\nATS_CONFIG_DATA: Dict[str, str] = {}\n\n\ndef parse_args() -> argparse.Namespace:\n \"\"\"Returns options to the caller.\n\n This function parses out and returns arguments and options from the\n commandline arguments.\n\n Returns:\n argparse.Namespace: The parsed arguments for the script.\n \"\"\"\n parser = argparse.ArgumentParser(\n description='Build the nipkg.ini file based on url specifications.'\n )\n\n parser.add_argument(\n '--ats-config-path', action='store', type=str, default=ats_config_file(),\n dest='ats_config_path',\n help='''This is the path to your local copy of the default_conf.json file.\n If you do not provide this path, then the default one (included in the ATS) will be\n used instead.'''\n )\n\n parser.add_argument(\n '-N', '--instance-dns-name', action='append', type=str, default=None,\n dest='instance_dns_names',\n help='''The public DNS name(s) of the instance(s) whose termination date needs updating.\n Please note that this is an appending list, so use -N -N for\n multiple instances.'''\n )\n\n parser.add_argument(\n '--instance-termination-date', action='store', type=str,\n default=str(datetime.today().date() + timedelta(days=2)),\n dest='instance_termination_date',\n help='''The date at which the instance can be terminated. Format: %Y-%m-%d\n Note that this value will default to two days from today().'''\n )\n\n parser.add_argument(\n '--is-test-day-instance', action='store', default=False, type=bool_from_str,\n dest='is_test_day_instance',\n help='Whether or not this instance is for use in test days.'\n )\n\n return parser.parse_args()\n\n\ndef main():\n \"\"\"The main execution method for the script.\"\"\"\n args = parse_args()\n\n global ATS_CONFIG_DATA # pylint: disable=global-statement\n ATS_CONFIG_DATA = read_json_data_from_file(args.ats_config_path)\n\n # Get the AWSInstance to use for instance operations.\n aws_instance = AWSInstance(region_name=ATS_CONFIG_DATA['region_name'])\n\n LOGGER.write(\n f'Updating the TerminationDate tag for instances: {args.instance_dns_names} to '\n f'{args.instance_termination_date}'\n )\n\n # Update (or create) the TerminationDate tag value.\n aws_instance.create_or_update_tag_value(\n resource_ids=aws_instance.public_dns_names_to_ids(args.instance_dns_names),\n tags=[{'Key': 'TerminationDate', 'Value': args.instance_termination_date}]\n )\n\n LOGGER.write('Tag operation complete.')\n # Post the message to the proper MSTeams channel.\n post_teams_instance_deployment_message(\n web_hook=TEST_DAY_INSTANCE_WEBHOOK if args.is_test_day_instance\n else DAILY_INSTANCES_WEBHOOK,\n card_title='SystemLink Daily Instance Update.' if not args.is_test_day_instance\n else 'SystemLink Test Day Instance Update',\n card_text=f'The termination date for the following instances has been updated to '\n f'{args.instance_termination_date}:

    ' +\n \"
    \".join(args.instance_dns_names)\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"syslinkats/stand_alone/instances/update_instance_termination_date.py","file_name":"update_instance_termination_date.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"430208009","text":"# -*- coding: utf-8 -*-\r\n\"\"\" \r\nCreated on Thu Jul 26 15:18:46 2018\r\n\r\n@author: asalkanovic1\r\n\r\nTutorial: https://blog.goodaudience.com/predicting-fifa-world-cup-2018-using-machine-learning-dc07ad8dd576\r\nhttps://github.com/itsmuriuki/FIFA-2018-World-cup-predictions/blob/master/Predicting%20Fifa%202018.ipynb\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport matplotlib.ticker as ticker\r\nimport matplotlib.ticker as plticker\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.svm import SVC\r\n\r\n# Loading the data sets\r\nworld_cup = pd.read_csv('C:\\\\Users\\\\asalkanovic1\\\\Downloads\\\\WC\\\\World Cup 2018 Dataset.csv')\r\nresults = pd.read_csv('C:\\\\Users\\\\asalkanovic1\\\\Downloads\\\\WC\\\\results.csv')\r\n\r\n# Ensuring data sets are laoded\r\nworld_cup.head()\r\nresults.head()\r\n\r\n# Feature engineering - match winner\r\nwinner = []\r\nfor i in range(len(results['home_team'])):\r\n if results ['home_score'][i] > results['away_score'][i]:\r\n winner.append(results['home_team'][i])\r\n elif results ['home_score'][i] < results['away_score'][i]:\r\n winner.append(results['away_team'][i])\r\n else:\r\n winner.append('Draw')\r\nresults['winning_team'] = winner\r\n\r\n# Feature engineering - goal difference\r\nresults['goal_difference'] = np.absolute(results['home_score'] - results['away_score'])\r\n\r\nresults.head()\r\n\r\n# Examine Nigeria specifically to see glean more about useful features\r\ndf = results[(results['home_team'] == 'Nigeria') | (results['away_team'] == 'Nigeria')]\r\n\r\nnigeria = df.iloc[:]\r\n\r\n# Creating a column for year. And we want matches after the first WC year in 1930.\r\nyear = []\r\nfor row in nigeria['date']:\r\n year.append(int(row[:4]))\r\nnigeria['match_year'] = year\r\nnigeria_1930 = nigeria[nigeria.match_year >= 1930]\r\nnigeria_1930.count()\r\n\r\n# Re-creating the plot in the demo project that doesn't have source code provided\r\nX = np.arange(3)\r\nobjects = ('Win', 'Loss', 'Draw')\r\nwin = len(nigeria_1930[nigeria_1930['winning_team'] == 'Nigeria'])\r\nloss = len(nigeria_1930[(nigeria_1930['winning_team'] != 'Nigeria') & (nigeria_1930['winning_team'] != 'Draw')])\r\ndraw = len(nigeria_1930[nigeria_1930['winning_team'] == 'Draw'])\r\nY = [win, loss, draw]\r\nplt.bar(X, Y, align = 'center', alpha = 0.5, color = 'grb')\r\nplt.xticks(X, objects)\r\nplt.xlabel('Nigeria_Result')\r\nplt.ylabel('Count')\r\nplt.show()\r\n\r\n# Let's begin the main effort\r\nworldcup_teams = ['Australia', 'Iran', 'Japan', 'Korea Republic',\r\n 'Saudi Arabia', 'Egypt', 'Morocco', 'Nigeria',\r\n 'Senegal', 'Tunisia', 'Costa Rica', 'Mexico',\r\n 'Panama', 'Argentina', 'Brazil', 'Colombia',\r\n 'Peru', 'Uruguay', 'Belgium', 'Croatia',\r\n 'Denmark', 'England', 'France', 'Germany',\r\n 'Iceland', 'Poland', 'Portugal', 'Russia',\r\n 'Serbia', 'Spain', 'Sweden', 'Switzerland']\r\n\r\ndf_teams_home = results[results['home_team'].isin(worldcup_teams)]\r\ndf_teams_away = results[results['away_team'].isin(worldcup_teams)]\r\ndf_teams = pd.concat((df_teams_home, df_teams_away))\r\ndf_teams.drop_duplicates()\r\ndf_teams.count()\r\n\r\n\"\"\"\r\nCreate a year column and drop games before 1930 as well as columns that won’t \r\naffect match outcome for example date, home_score, away_score, tournament, city, \r\ncountry, goal_difference and match_year.\r\n\"\"\"\r\nyear = []\r\nfor row in df_teams['date']:\r\n year.append(int(row[:4]))\r\ndf_teams['match_year'] = year\r\ndf_teams_1930 = df_teams[df_teams.match_year >= 1930]\r\ndf_teams_1930.head()\r\n\r\n# Drop columns that do not affect match outcome\r\ndf_teams_1930 = df_teams_1930.drop(['date', 'home_score', 'away_score', 'tournament', 'city', 'country', 'neutral','goal_difference', 'match_year'], 1)\r\ndf_teams_1930.head()\r\n\r\n\r\n### Building the model ###\r\n\r\n# The prediction label: The winning_team will show '2' if home team has won,\r\n# a '1' if there was a draw, and a '0' if the home team has lost\r\ndf_teams_1930 = df_teams_1930.reset_index(drop=True)\r\ndf_teams_1930.loc[df_teams_1930.winning_team == df_teams_1930.home_team, 'winning_team']=2\r\ndf_teams_1930.loc[df_teams_1930.winning_team == df_teams_1930.away_team, 'winning_team']=0\r\ndf_teams_1930.loc[df_teams_1930.winning_team == 'Draw', 'winning_team']=1\r\n\r\ndf_teams_1930.head()\r\n\r\n# Convert home team and away team from categorical variables to continuous inputs\r\n# Get dummy variables\r\nfinal = pd.get_dummies(df_teams_1930, prefix = ['home_team','away_team'], columns = ['home_team','away_team'])\r\n\r\n# Separate X and Y sets\r\nX = final.drop(['winning_team'], axis = 1)\r\nY = final[\"winning_team\"]\r\nY = Y.astype('int')\r\n\r\n# Separate train and test sets\r\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.30, random_state = 42)\r\n\r\nlogreg = LogisticRegression()\r\nlogreg.fit(X_train, Y_train)\r\nscore = logreg.score(X_train, Y_train)\r\nscore2 = logreg.score(X_test, Y_test)\r\nprint(\"LogReg - Training set accuracy: \", '%.3f'%(score))\r\nprint(\"LogReg - Test set accuracy: \", '%.3f'%(score2))\r\nprint(\"\")\r\n\r\n#svm = SVC()\r\n#svm.fit(X_train, Y_train)\r\n#score3 = svm.score(X_train, Y_train)\r\n#score4 = svm.score(X_test, Y_test)\r\n#print(\"SVM - Training set accuracy: \", '%.3f'%(score3))\r\n#print(\"SVM - Test set accuracy: \", '%.3f'%(score4))\r\n\r\n# Let's consider Fifa Rankings\r\n# The team which is positioned high in the FIFA Rankings wil lbe considered the \r\n# \"favourite\" for the match and therefore, will be positioned under the \"home_teams\"\r\n# column since there are no \"home\" or \"away\" teams in the World Cup fixtures.\r\n\r\n# Loading new datasets\r\nranking = pd.read_csv('C:\\\\Users\\\\asalkanovic1\\\\Downloads\\\\WC\\\\fifa_rankings.csv')\r\nfixtures = pd.read_csv('C:\\\\Users\\\\asalkanovic1\\\\Downloads\\\\WC\\\\fixtures.csv')\r\n\r\n# List for storing the group stage games\r\npred_set = []\r\n\r\n# Create new columns with ranking position of each team\r\nfixtures.insert(1, 'first_position', fixtures['Home Team'].map(ranking.set_index('Team')['Position']))\r\nfixtures.insert(2, 'second_position', fixtures['Away Team'].map(ranking.set_index('Team')['Position']))\r\n\r\n# We only need the group stage games, so we have to slice the fixtures dataset\r\nfixtures = fixtures.iloc[:48, :]\r\nfixtures.tail()\r\n\r\n# Loop to add teams to new prediction dataset based on the ranking position of each team\r\nfor index, row in fixtures.iterrows():\r\n if row['first_position'] < row['second_position']:\r\n pred_set.append({'home_team': row['Home Team'], 'away_team': row['Away Team'], 'winning_team': None})\r\n else:\r\n pred_set.append({'home_team': row['Away Team'], 'away_team': row['Home Team'], 'winning_team': None})\r\n\r\npred_set = pd.DataFrame(pred_set)\r\nbackup_pred_set = pred_set\r\npred_set.head()\r\n\r\n# Get dummy variables and drop winning_team column\r\npred_set = pd.get_dummies(pred_set, prefix = ['home_team','away_team'], columns = ['home_team','away_team'])\r\n\r\n# Add missing columns comparted to te model's training dataset\r\nmissing_cols = set(final.columns) - set(pred_set.columns)\r\nfor c in missing_cols:\r\n pred_set[c] = 0\r\npred_set = pred_set[final.columns]\r\n\r\n# Remove winning team column\r\npred_set = pred_set.drop(['winning_team'], axis = 1)\r\n\r\npred_set.head()\r\n\r\n# Group stage matches\r\npredictions = logreg.predict(pred_set)\r\nfor i in range(fixtures.shape[0]):\r\n print(backup_pred_set.iloc[i, 1] + \" and \" + backup_pred_set.iloc[i, 0])\r\n if predictions[i] == 2:\r\n print(\"Winner: \" + backup_pred_set.iloc[i, 1])\r\n elif predictions[i] == 1:\r\n print(\"Draw\")\r\n elif predictions[i] == 0:\r\n print(\"Winner: \" + backup_pred_set.iloc[i, 0])\r\n print('Probability of ' + backup_pred_set.iloc[i, 1] + ' winning: ', '%.3f'%(logreg.predict_proba(pred_set)[i][2]))\r\n print('Probability of Draw: ', '%.3f'%(logreg.predict_proba(pred_set)[i][1]))\r\n print('Probability of ' + backup_pred_set.iloc[i, 0] + ' winning: ', '%.3f'%(logreg.predict_proba(pred_set)[i][0]))\r\n print(\"\")\r\n\r\ndef clean_and_predict(matches, ranking, final, logreg):\r\n\r\n # Initialization of auxiliary list for data cleaning\r\n positions = []\r\n\r\n # Loop to retrieve each team's position according to FIFA ranking\r\n for match in matches:\r\n positions.append(ranking.loc[ranking['Team'] == match[0],'Position'].iloc[0])\r\n positions.append(ranking.loc[ranking['Team'] == match[1],'Position'].iloc[0])\r\n \r\n # Creating the DataFrame for prediction\r\n pred_set = []\r\n\r\n # Initializing iterators for while loop\r\n i = 0\r\n j = 0\r\n\r\n # 'i' will be the iterator for the 'positions' list, and 'j' for the list of matches (list of tuples)\r\n while i < len(positions):\r\n dict1 = {}\r\n\r\n # If position of first team is better, he will be the 'home' team, and vice-versa\r\n if positions[i] < positions[i + 1]:\r\n dict1.update({'home_team': matches[j][0], 'away_team': matches[j][1]})\r\n else:\r\n dict1.update({'home_team': matches[j][1], 'away_team': matches[j][0]})\r\n\r\n # Append updated dictionary to the list, that will later be converted into a DataFrame\r\n pred_set.append(dict1)\r\n i += 2\r\n j += 1\r\n\r\n # Convert list into DataFrame\r\n pred_set = pd.DataFrame(pred_set)\r\n backup_pred_set = pred_set\r\n\r\n # Get dummy variables and drop winning_team column\r\n pred_set = pd.get_dummies(pred_set, prefix=['home_team', 'away_team'], columns=['home_team', 'away_team'])\r\n\r\n # Add missing columns compared to the model's training dataset\r\n missing_cols2 = set(final.columns) - set(pred_set.columns)\r\n for c in missing_cols2:\r\n pred_set[c] = 0\r\n pred_set = pred_set[final.columns]\r\n\r\n # Remove winning team column\r\n pred_set = pred_set.drop(['winning_team'], axis=1)\r\n\r\n # Predict!\r\n predictions = logreg.predict(pred_set)\r\n for i in range(len(pred_set)):\r\n print(backup_pred_set.iloc[i, 1] + \" and \" + backup_pred_set.iloc[i, 0])\r\n if predictions[i] == 2:\r\n print(\"Winner: \" + backup_pred_set.iloc[i, 1])\r\n elif predictions[i] == 1:\r\n print(\"Draw\")\r\n elif predictions[i] == 0:\r\n print(\"Winner: \" + backup_pred_set.iloc[i, 0])\r\n print('Probability of ' + backup_pred_set.iloc[i, 1] + ' winning: ' , '%.3f'%(logreg.predict_proba(pred_set)[i][2]))\r\n print('Probability of Draw: ', '%.3f'%(logreg.predict_proba(pred_set)[i][1])) \r\n print('Probability of ' + backup_pred_set.iloc[i, 0] + ' winning: ', '%.3f'%(logreg.predict_proba(pred_set)[i][0]))\r\n print(\"\")\r\n \r\n# List of Round of 16 match ups \r\ngroup_16 = [('Uruguay', 'Portugal'),\r\n ('France', 'Croatia'),\r\n ('Brazil', 'Mexico'),\r\n ('England', 'Colombia'),\r\n ('Spain', 'Russia'),\r\n ('Argentina', 'Peru'),\r\n ('Germany', 'Switzerland'),\r\n ('Poland', 'Belgium')]\r\n\r\nclean_and_predict(group_16, ranking, final, logreg)\r\n\r\nquarter_finals = [('Portugal', 'France'),\r\n ('Spain', 'Argentina'),\r\n ('Brazil', 'England'),\r\n ('Germany', 'Belgium')]\r\n\r\nclean_and_predict(quarter_finals, ranking, final, logreg)\r\n\r\nsemi_finals = [('Portugal', 'Brazil'),\r\n ('Argentina', 'Germany')]\r\n\r\nclean_and_predict(semi_finals, ranking, final, logreg)\r\n\r\nwc_final = [('Brazil', 'Germany')]\r\n\r\nclean_and_predict(wc_final, ranking, final, logreg)\r\n","sub_path":"word_cup_ml_2018.py","file_name":"word_cup_ml_2018.py","file_ext":"py","file_size_in_byte":11399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"73098140","text":"product_price = [1000, 5000, 7500, 10000, 2500, 3000, 4500, 6000]\nfor i in range(8):\n print('{}번째 상품 가격: {}'.format(i, product_price[i]))\n\ni = 0\nbuy = 0\n\nmoney = int(input(\"가지고 있는 돈을 입력하세요 >> \"))\n\nfor i in product_price:\n money = money - i\n if money < 0:\n break\n elif money >= 0:\n buy += 1\n\nprint(\"돈이 모자랍니다.\", buy, \"개의 상품을 샀습니다.\")\n ","sub_path":"18_이민수/session_03/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"53905565","text":"\"\"\"Riemannian and pseudo-Riemannian metrics.\"\"\"\n\nimport math\nimport warnings\n\nimport autograd\n\nimport geomstats.backend as gs\nfrom geomstats.geometry.connection import Connection\n\n\nEPSILON = 1e-4\nN_CENTERS = 10\nTOLERANCE = 1e-5\nN_REPETITIONS = 20\nN_MAX_ITERATIONS = 50000\nN_STEPS = 10\n\n\ndef loss(y_pred, y_true, metric):\n \"\"\"Compute loss function between prediction and ground truth.\n\n Loss function given by a Riemannian metric,\n expressed as the squared geodesic distance between the prediction\n and the ground truth.\n\n Parameters\n ----------\n y_pred\n y_true\n metric\n\n Returns\n -------\n loss\n\n \"\"\"\n loss = metric.squared_dist(y_pred, y_true)\n return loss\n\n\ndef grad(y_pred, y_true, metric):\n \"\"\"Closed-form for the gradient of the loss function.\"\"\"\n tangent_vec = metric.log(base_point=y_pred, point=y_true)\n grad_vec = - 2. * tangent_vec\n\n inner_prod_mat = metric.inner_product_matrix(base_point=y_pred)\n\n grad = gs.einsum('ni,nij->ni',\n grad_vec,\n gs.transpose(inner_prod_mat, axes=(0, 2, 1)))\n\n return grad\n\n\nclass RiemannianMetric(Connection):\n \"\"\"Class for Riemannian and pseudo-Riemannian metrics.\"\"\"\n\n def __init__(self, dimension, signature=None):\n assert isinstance(dimension, int) or dimension == math.inf\n assert dimension > 0\n super().__init__(dimension=dimension)\n self.signature = signature\n\n def inner_product_matrix(self, base_point=None):\n \"\"\"Inner product matrix at the tangent space at a base point.\n\n Parameters\n ----------\n base_point : array-like, shape=[n_samples, dimension], optional\n \"\"\"\n raise NotImplementedError(\n 'The computation of the inner product matrix'\n ' is not implemented.')\n\n def inner_product_inverse_matrix(self, base_point=None):\n \"\"\"Inner product matrix at the tangent space at a base point.\n\n Parameters\n ----------\n base_point : array-like, shape=[n_samples, dimension], optional\n \"\"\"\n metric_matrix = self.inner_product_matrix(base_point)\n cometric_matrix = gs.linalg.inv(metric_matrix)\n return cometric_matrix\n\n def inner_product_derivative_matrix(self, base_point=None):\n \"\"\"Compute derivative of the inner prod matrix at base point.\n\n Parameters\n ----------\n base_point : array-like, shape=[n_samples, dimension], optional\n \"\"\"\n metric_derivative = autograd.jacobian(self.inner_product_matrix)\n return metric_derivative(base_point)\n\n def christoffels(self, base_point):\n \"\"\"Compute Christoffel symbols associated with the connection.\n\n Parameters\n ----------\n base_point: array-like, shape=[n_samples, dimension]\n\n Returns\n -------\n christoffels: array-like,\n shape=[n_samples, dimension, dimension, dimension]\n \"\"\"\n cometric_mat_at_point = self.inner_product_inverse_matrix(base_point)\n metric_derivative_at_point = self.inner_product_derivative_matrix(\n base_point)\n term_1 = gs.einsum('nim,nmkl->nikl',\n cometric_mat_at_point,\n metric_derivative_at_point)\n term_2 = gs.einsum('nim,nmlk->nilk',\n cometric_mat_at_point,\n metric_derivative_at_point)\n term_3 = - gs.einsum('nim,nklm->nikl',\n cometric_mat_at_point,\n metric_derivative_at_point)\n\n christoffels = 0.5 * (term_1 + term_2 + term_3)\n return christoffels\n\n def inner_product(self, tangent_vec_a, tangent_vec_b, base_point=None):\n \"\"\"Inner product between two tangent vectors at a base point.\n\n Parameters\n ----------\n tangent_vec_a: array-like, shape=[n_samples, dimension]\n or shape=[1, dimension]\n\n tangent_vec_b: array-like, shape=[n_samples, dimension]\n or shape=[1, dimension]\n\n base_point: array-like, shape=[n_samples, dimension]\n or shape=[1, dimension]\n\n Returns\n -------\n inner_product : array-like, shape=[n_samples,]\n \"\"\"\n tangent_vec_a = gs.to_ndarray(tangent_vec_a, to_ndim=2)\n tangent_vec_b = gs.to_ndarray(tangent_vec_b, to_ndim=2)\n n_tangent_vec_a = gs.shape(tangent_vec_a)[0]\n n_tangent_vec_b = gs.shape(tangent_vec_b)[0]\n\n inner_prod_mat = self.inner_product_matrix(base_point)\n inner_prod_mat = gs.to_ndarray(inner_prod_mat, to_ndim=3)\n n_mats = gs.shape(inner_prod_mat)[0]\n\n if n_tangent_vec_a != n_mats:\n if n_tangent_vec_a == 1:\n tangent_vec_a = gs.squeeze(tangent_vec_a, axis=0)\n einsum_str_a = 'j,njk->nk'\n elif n_mats == 1:\n inner_prod_mat = gs.squeeze(inner_prod_mat, axis=0)\n einsum_str_a = 'nj,jk->nk'\n else:\n raise ValueError('Shape mismatch for einsum.')\n else:\n einsum_str_a = 'nj,njk->nk'\n\n aux = gs.einsum(einsum_str_a, tangent_vec_a, inner_prod_mat)\n n_auxs, _ = gs.shape(aux)\n\n if n_tangent_vec_b != n_auxs:\n if n_auxs == 1:\n aux = gs.squeeze(aux, axis=0)\n einsum_str_b = 'k,nk->n'\n elif n_tangent_vec_b == 1:\n tangent_vec_b = gs.squeeze(tangent_vec_b, axis=0)\n einsum_str_b = 'nk,k->n'\n else:\n raise ValueError('Shape mismatch for einsum.')\n else:\n einsum_str_b = 'nk,nk->n'\n\n inner_prod = gs.einsum(einsum_str_b, aux, tangent_vec_b)\n inner_prod = gs.to_ndarray(inner_prod, to_ndim=2, axis=1)\n\n assert gs.ndim(inner_prod) == 2, inner_prod.shape\n return inner_prod\n\n def squared_norm(self, vector, base_point=None):\n \"\"\"Compute the square of the norm of a vector.\n\n Squared norm of a vector associated to the inner product\n at the tangent space at a base point.\n\n Parameters\n ----------\n vector : array-like, shape=[n_samples, dimension]\n base_point : array-like, shape=[n_samples, dimension]\n\n Returns\n -------\n sq_norm : array-like, shape=[n_samples,]\n \"\"\"\n sq_norm = self.inner_product(vector, vector, base_point)\n return sq_norm\n\n def norm(self, vector, base_point=None):\n \"\"\"Compute norm of a vector.\n\n Norm of a vector associated to the inner product\n at the tangent space at a base point.\n\n Note: This only works for positive-definite\n Riemannian metrics and inner products.\n\n Parameters\n ----------\n vector : array-like, shape=[n_samples, dimension]\n base_point : array-like, shape=[n_samples, dimension]\n\n Returns\n -------\n norm : array-like, shape=[n_samples,]\n \"\"\"\n sq_norm = self.squared_norm(vector, base_point)\n norm = gs.sqrt(sq_norm)\n return norm\n\n def geodesic(self, initial_point,\n end_point=None, initial_tangent_vec=None,\n point_type='vector'):\n \"\"\"Return the geodesic as function of t.\n\n Geodesic curve defined by either:\n - an initial point and an initial tangent vector, or\n - an initial point and an end point.\n\n The geodesic is returned as a function parameterized by t.\n\n Parameters\n ----------\n initial_point : array-like, shape=[n_samples, dimension]\n end_point : array-like, shape=[n_samples, dimension], optional\n initial_tangent_vec : array-like, shape=[n_samples, dimension],\n optional\n point_type : str, optional\n\n Returns\n -------\n path : callable\n \"\"\"\n point_ndim = 1\n if point_type == 'matrix':\n point_ndim = 2\n\n initial_point = gs.to_ndarray(initial_point,\n to_ndim=point_ndim + 1)\n\n if end_point is None and initial_tangent_vec is None:\n raise ValueError('Specify an end point or an initial tangent '\n 'vector to define the geodesic.')\n if end_point is not None:\n end_point = gs.to_ndarray(end_point,\n to_ndim=point_ndim + 1)\n shooting_tangent_vec = self.log(point=end_point,\n base_point=initial_point)\n if initial_tangent_vec is not None:\n assert gs.allclose(shooting_tangent_vec, initial_tangent_vec)\n initial_tangent_vec = shooting_tangent_vec\n initial_tangent_vec = gs.array(initial_tangent_vec)\n initial_tangent_vec = gs.to_ndarray(initial_tangent_vec,\n to_ndim=point_ndim + 1)\n\n def path(t):\n \"\"\"Generate a function parameterizing the geodesic.\n\n Parameters\n ----------\n t : parameter value of the geodesic\n\n Returns\n -------\n point_at_time_t : callable\n \"\"\"\n t = gs.cast(t, gs.float32)\n t = gs.to_ndarray(t, to_ndim=1)\n t = gs.to_ndarray(t, to_ndim=2, axis=1)\n new_initial_point = gs.to_ndarray(\n initial_point,\n to_ndim=point_ndim + 1)\n new_initial_tangent_vec = gs.to_ndarray(\n initial_tangent_vec,\n to_ndim=point_ndim + 1)\n\n if point_type == 'vector':\n tangent_vecs = gs.einsum('il,nk->ik',\n t,\n new_initial_tangent_vec)\n elif point_type == 'matrix':\n tangent_vecs = gs.einsum('il,nkm->ikm',\n t,\n new_initial_tangent_vec)\n\n point_at_time_t = self.exp(tangent_vec=tangent_vecs,\n base_point=new_initial_point)\n return point_at_time_t\n\n return path\n\n def squared_dist(self, point_a, point_b):\n \"\"\"Squared geodesic distance between two points.\n\n Parameters\n ----------\n point_a : array-like, shape=[n_samples, dimension]\n point_b : array-like, shape=[n_samples, dimension]\n\n Returns\n -------\n sq_dist : array-like, shape=[n_samples,]\n \"\"\"\n log = self.log(point=point_b, base_point=point_a)\n sq_dist = self.squared_norm(vector=log, base_point=point_a)\n\n return sq_dist\n\n def dist(self, point_a, point_b):\n \"\"\"Geodesic distance between two points.\n\n Note: It only works for positive definite\n Riemannian metrics.\n\n Parameters\n ----------\n point_a : array-like, shape=[n_samples, dimension]\n point_b : array-like, shape=[n_samples, dimension]\n\n Returns\n -------\n dist : array-like, shape=[n_samples,]\n \"\"\"\n sq_dist = self.squared_dist(point_a, point_b)\n dist = gs.sqrt(sq_dist)\n return dist\n\n def variance(self,\n points,\n weights=None,\n base_point=None,\n point_type='vector'):\n \"\"\"Variance of (weighted) points wrt a base point.\n\n Parameters\n ----------\n points: array-like, shape=[n_samples, dimension]\n\n weights: array-like, shape=[n_samples, 1], optional\n \"\"\"\n if point_type == 'vector':\n points = gs.to_ndarray(points, to_ndim=2)\n if point_type == 'matrix':\n points = gs.to_ndarray(points, to_ndim=3)\n n_points = gs.shape(points)[0]\n\n if weights is None:\n weights = gs.ones((n_points, 1))\n\n weights = gs.array(weights)\n weights = gs.to_ndarray(weights, to_ndim=2, axis=1)\n\n sum_weights = gs.sum(weights)\n\n if base_point is None:\n base_point = self.mean(points, weights)\n\n variance = 0.\n\n sq_dists = self.squared_dist(base_point, points)\n variance += gs.einsum('nk,nj->j', weights, sq_dists)\n\n variance = gs.array(variance)\n variance /= sum_weights\n\n variance = gs.to_ndarray(variance, to_ndim=1)\n variance = gs.to_ndarray(variance, to_ndim=2, axis=1)\n return variance\n\n def mean(self, points,\n weights=None,\n n_max_iterations=32,\n epsilon=EPSILON,\n point_type='vector',\n mean_method='default',\n verbose=False):\n \"\"\"Frechet mean of (weighted) points.\n\n Parameters\n ----------\n points : array-like, shape=[n_samples, dimension]\n weights : array-like, shape=[n_samples, 1], optional\n verbose : bool, optional\n\n Returns\n -------\n mean : array-like\n the Frechet mean of points, a point on the manifold\n \"\"\"\n if mean_method == 'default':\n\n # TODO(nina): Profile this code to study performance,\n # i.e. what to do with sq_dists_between_iterates.\n def while_loop_cond(iteration, mean, variance, sq_dist):\n result = ~gs.logical_or(\n gs.isclose(variance, 0.),\n gs.less_equal(sq_dist, epsilon * variance))\n return result[0, 0] or iteration == 0\n\n def while_loop_body(iteration, mean, variance, sq_dist):\n\n logs = self.log(point=points, base_point=mean)\n\n tangent_mean = gs.einsum('nk,nj->j', weights, logs)\n\n tangent_mean /= sum_weights\n\n mean_next = self.exp(\n tangent_vec=tangent_mean,\n base_point=mean)\n\n sq_dist = self.squared_dist(mean_next, mean)\n sq_dists_between_iterates.append(sq_dist)\n\n variance = self.variance(points=points,\n weights=weights,\n base_point=mean_next)\n\n mean = mean_next\n iteration += 1\n return [iteration, mean, variance, sq_dist]\n\n if point_type == 'vector':\n points = gs.to_ndarray(points, to_ndim=2)\n if point_type == 'matrix':\n points = gs.to_ndarray(points, to_ndim=3)\n n_points = gs.shape(points)[0]\n\n if weights is None:\n weights = gs.ones((n_points, 1))\n\n weights = gs.array(weights)\n weights = gs.to_ndarray(weights, to_ndim=2, axis=1)\n\n sum_weights = gs.sum(weights)\n\n mean = points[0]\n if point_type == 'vector':\n mean = gs.to_ndarray(mean, to_ndim=2)\n if point_type == 'matrix':\n mean = gs.to_ndarray(mean, to_ndim=3)\n\n if n_points == 1:\n return mean\n\n sq_dists_between_iterates = []\n iteration = 0\n sq_dist = gs.array([[0.]])\n variance = gs.array([[0.]])\n\n last_iteration, mean, variance, sq_dist = gs.while_loop(\n lambda i, m, v, sq: while_loop_cond(i, m, v, sq),\n lambda i, m, v, sq: while_loop_body(i, m, v, sq),\n loop_vars=[iteration, mean, variance, sq_dist],\n maximum_iterations=n_max_iterations)\n\n if last_iteration == n_max_iterations:\n print('Maximum number of iterations {} reached.'\n 'The mean may be inaccurate'.format(n_max_iterations))\n\n if verbose:\n print('n_iter: {}, final variance: {}, final dist: {}'.format(\n last_iteration, variance, sq_dist))\n\n mean = gs.to_ndarray(mean, to_ndim=2)\n return mean\n\n if mean_method == 'frechet-poincare-ball':\n\n lr = 1e-3\n tau = 5e-3\n\n if len(points) == 1:\n return points\n\n iteration = 0\n convergence = math.inf\n barycenter = points.mean(0, keepdims=True) * 0\n\n while convergence > tau and n_max_iterations > iteration:\n\n iteration += 1\n\n expand_barycenter = gs.repeat(barycenter, points.shape[0], 0)\n\n grad_tangent = 2 * self.log(points, expand_barycenter)\n\n cc_barycenter = self.exp(lr * grad_tangent.sum(0,\n keepdims=True),\n barycenter)\n\n convergence = self.dist(cc_barycenter, barycenter).max().item()\n\n barycenter = cc_barycenter\n\n if iteration == n_max_iterations:\n warnings.warn(\n 'Maximum number of iterations {} reached. The '\n 'mean may be inaccurate'.format(n_max_iterations))\n\n return barycenter\n\n def adaptive_gradientdescent_mean(self, points,\n weights=None,\n n_max_iterations=40,\n epsilon=1e-12,\n init_points=[],\n verbose=False):\n \"\"\"Compute Frechet mean of (weighted) points using adaptive time-steps.\n\n Frechet mean of (weighted) points using adaptive time-steps\n The loss function optimized is ||M_1(x)||_x (where M_1(x) is\n the tangent mean at x) rather than the mean-square-distance (MSD)\n because this saves computation time.\n\n Parameters\n ----------\n points: array-like, shape=[n_samples, dimension]\n\n weights: array-like, shape=[n_samples, 1], optional\n\n init_points: array-like, shape=[n_init, dimension]\n epsilon: tolerance for stopping the gradient descent\n verbose: verbose mode printing the surrogate value\n\n epsilon: tolerance for stopping the gradient descent\n \"\"\"\n # TODO(Xavier): This function assumes that all points are lists\n # of vectors and not of matrices\n n_points = gs.shape(points)[0]\n\n if n_points == 1:\n return gs.to_ndarray(points[0], to_ndim=2)\n\n if weights is None:\n weights = gs.ones((n_points, 1))\n\n weights = gs.array(weights)\n weights = gs.to_ndarray(weights, to_ndim=2, axis=1)\n\n sum_weights = gs.sum(weights)\n\n n_init = len(init_points)\n\n if n_init == 0:\n current_mean = points[0]\n else:\n current_mean = init_points[0]\n\n tau = 1.0\n iteration = 0\n\n logs = self.log(point=points, base_point=current_mean)\n current_tangent_mean = gs.einsum('nk,nj->j', weights, logs)\n current_tangent_mean /= sum_weights\n norm_current_tangent_mean = gs.linalg.norm(current_tangent_mean)\n\n while (norm_current_tangent_mean > epsilon\n and iteration < n_max_iterations):\n iteration = iteration + 1\n shooting_vector = gs.to_ndarray(\n tau * current_tangent_mean,\n to_ndim=2)\n next_mean = self.exp(\n tangent_vec=shooting_vector,\n base_point=current_mean)\n logs = self.log(point=points, base_point=next_mean)\n next_tangent_mean = gs.einsum('nk,nj->j', weights, logs)\n next_tangent_mean /= sum_weights\n norm_next_tangent_mean = gs.linalg.norm(next_tangent_mean)\n if verbose:\n print(\n \"Iter {0}: tau= {1}, \"\n \"norm_current_tangent_mean = {2}\".format(\n iter, tau, norm_current_tangent_mean))\n if norm_next_tangent_mean < norm_current_tangent_mean:\n current_mean = next_mean\n current_tangent_mean = next_tangent_mean\n norm_current_tangent_mean = norm_next_tangent_mean\n tau = max(1.0, 1.0511111 * tau)\n else:\n tau = tau * 0.8\n\n if iteration == n_max_iterations:\n warnings.warn(\n 'Maximum number of iterations {} reached.'\n 'The mean may be inaccurate'.format(n_max_iterations))\n\n return gs.to_ndarray(current_mean, to_ndim=2)\n\n def diameter(self, points):\n \"\"\"Give the distance between two farthest points.\n\n Distance between the two points that are farthest away from each other\n in points.\n\n Parameters\n ----------\n points\n\n Returns\n -------\n diameter\n\n \"\"\"\n diameter = 0.0\n n_points = points.shape[0]\n\n for i in range(n_points - 1):\n dist_to_neighbors = self.dist(points[i, :], points[i + 1:, :])\n dist_to_farthest_neighbor = gs.amax(dist_to_neighbors)\n diameter = gs.maximum(diameter, dist_to_farthest_neighbor)\n\n return diameter\n\n def closest_neighbor_index(self, point, neighbors):\n \"\"\"Closest neighbor of point among neighbors.\n\n Parameters\n ----------\n point\n neighbors\n Returns\n -------\n closest_neighbor_index\n\n \"\"\"\n dist = self.dist(point, neighbors)\n closest_neighbor_index = gs.argmin(dist)\n\n return closest_neighbor_index\n","sub_path":"geomstats/geometry/riemannian_metric.py","file_name":"riemannian_metric.py","file_ext":"py","file_size_in_byte":21522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"342182485","text":"from django.views.generic.base import TemplateView\nfrom django.shortcuts import render\nfrom .models import Empresa, Insumo, Turno, Colaborador\nfrom django.conf import settings\nfrom io import BytesIO\nfrom reportlab.pdfgen import canvas\nfrom django.views.generic import View\nfrom django.http import HttpResponse\nfrom django.views.generic import ListView\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, TableStyle\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.platypus import Table\nfrom reportlab.lib.units import cm\n#\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.utils.decorators import method_decorator\n#\n\nclass HomePageView(TemplateView):\n template_name = \"core/home.html\"\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template_name, {'title': \"Web Aseo Integral\"})\n\n\nclass SamplePageView(TemplateView):\n template_name = \"core/sample.html\"\n\n\ndef formularioEmpresa(request):\n resp = False\n if request.POST:\n ru = request.POST.get('rutEmpresa', '')\n di = request.POST.get('direccion', '')\n ra = request.POST.get('razonSocial', '')\n co = request.POST.get('correo', '')\n te = request.POST.get('telefono', '')\n emp = Empresa(\n rutEmpresa=ru,\n direccion=di,\n razonSocial=ra,\n correo=co,\n telefono=te\n )\n emp.save()\n resp = True\n return render(request, 'core/formularioempresa.html', {'respuesta': resp})\n\n\ndef actualizarEmpresa(request):\n em = Empresa.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Buscar\":\n rut = request.POST.get(\"rutEmpresa\", \"\")\n emp = Empresa.objects.get(rutEmpresa=rut)\n mensaje = False\n return render(request, 'core/actualizarempresa.html', {'empresas': em, 'emp': emp, 'mensaje': mensaje})\n if accion == \"Modificar\":\n rut = request.POST.get(\"rutEmpresa\", \"\")\n emp = Empresa.objects.get(rutEmpresa=rut)\n direccion = request.POST.get(\"direccion\", \"\")\n razonSocial = request.POST.get(\"razonSocial\", \"\")\n correo = request.POST.get(\"correo\", \"\")\n telefono = request.POST.get(\"telefono\", \"\")\n emp.direccion = direccion\n emp.razonSocial = razonSocial\n emp.correo = correo\n emp.telefono = telefono\n emp.save()\n mensaje = True\n return render(request, 'core/actualizarempresa.html', {'empresas': em, 'mensaje': mensaje})\n return render(request, 'core/actualizarempresa.html', {'empresas': em})\n\n\ndef eliminarEmpresa(request):\n em = Empresa.objects.all()\n resp = False\n if request.POST:\n rut = request.POST.get('rutEmpresa', \"\")\n emp = Empresa.objects.get(rutEmpresa=rut)\n emp.delete()\n resp = True\n return render(request, 'core/eliminarempresa.html', {'empresas': em, 'respuesta': resp})\n\n\ndef listarEmpresa(request):\n em = Empresa.objects.all()\n return render(request, 'core/listarempresa.html', {'empresas': em})\n\n\ndef formularioColaborador(request):\n resp = False\n if request.POST:\n ru = request.POST.get('rut', '')\n no = request.POST.get('nombreCompleto', '')\n se = request.POST.get('sexo', '')\n fe = request.POST.get('fechaNacimiento', '')\n di = request.POST.get('direccion', '')\n te = request.POST.get('telefono', '')\n col = Colaborador(\n rut=ru,\n nombreCompleto=no,\n sexo=se,\n fechaNacimiento=fe,\n direccion=di,\n telefono=te\n )\n col.save()\n resp = True\n return render(request, 'core/formulariocolaborador.html', {'respuesta': resp})\n\n\ndef actualizarColaborador(request):\n co = Colaborador.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Buscar\":\n rut = request.POST.get(\"rut\", \"\")\n col = Colaborador.objects.get(rut=rut)\n mensaje = False\n return render(request, 'core/actualizarcolaborador.html', {'colaboradores': co, 'col': col, 'mensaje': mensaje})\n if accion == \"Modificar\":\n rut = request.POST.get(\"rut\", \"\")\n col = Colaborador.objects.get(rut=rut)\n nombreCompleto = request.POST.get(\"nombreCompleto\", \"\")\n sexo = request.POST.get(\"sexo\", \"\")\n fechaNacimiento = request.POST.get(\"fechaNacimiento\", \"\")\n direccion = request.POST.get(\"direccion\", \"\")\n telefono = request.POST.get(\"telefono\", \"\")\n col.nombreCompleto = nombreCompleto\n col.sexo = sexo\n col.fechaNacimiento = fechaNacimiento\n col.direccion = direccion\n col.telefono = telefono\n col.save()\n mensaje = True\n return render(request, 'core/actualizarcolaborador.html', {'colaboradores': co, 'mensaje': mensaje})\n return render(request, 'core/actualizarcolaborador.html', {'colaboradores': co})\n\n\ndef eliminarColaborador(request):\n co = Colaborador.objects.all()\n resp = False\n if request.POST:\n rut = request.POST.get('rut', \"\")\n col = Colaborador.objects.get(rut=rut)\n col.delete()\n resp = True\n return render(request, 'core/eliminarcolaborador.html', {'colaboradores': co, 'respuesta': resp})\n\n\ndef listarColaborador(request):\n co = Colaborador.objects.all()\n return render(request, 'core/listarcolaborador.html', {'colaboradores': co})\n\n\ndef formularioTurno(request):\n resp = False\n if request.POST:\n la=request.POST[\"txtLat\"]\n lo=request.POST[\"txtLon\"]\n fecha = request.POST[\"fecha\"]\n rut=request.POST[\"rut\"]\n registro=request.POST[\"cbRegistro\"]\n obj_col = Colaborador.objects.get(rut=rut)\n ub = Turno(\n latitud=la,\n longitud=lo,\n fecha=fecha,\n registro=registro,\n rut=obj_col\n )\n ub.save()\n resp=True\n return render(request, 'core/formularioturno.html',{'respuesta':resp})\n\n\ndef formularioInsumo(request):\n emp = Empresa.objects.all()\n resp = False\n if request.POST:\n idProducto = request.POST.get(\"idProducto\", \"\")\n nombre = request.POST.get(\"nombre\", \"\")\n stock = request.POST.get(\"stock\",\"\")\n rutEmp = request.POST.get(\"rutEmpresa\",\"\")\n obj_empresa = Empresa.objects.get(rutEmpresa=rutEmp)\n ins = Insumo(\n idProducto=idProducto,\n nombre=nombre,\n stock=stock,\n rutEmpresa=obj_empresa\n )\n ins.save()\n resp = True\n return render(request, 'core/formularioinsumo.html', {'respuesta': resp, 'empresa': emp})\n\n\ndef listarInsumo(request):\n ins = Insumo.objects.all()\n return render(request, 'core/listarinsumo.html', {'insumos': ins})\n\n\ndef eliminarInsumo(request):\n ins = Insumo.objects.all()\n resp = False\n if request.POST:\n idp = request.POST.get(\"idProducto\", \"\")\n insu = Insumo.objects.get(idProducto=idp)\n insu.delete()\n resp = True\n return render(request, 'core/eliminarinsumo.html', {'insumos': ins, 'respuesta': resp})\n\ndef actualizarInsumo(request):\n emp = Empresa.objects.all()\n insu = Insumo.objects.all()\n mensaje = False\n if request.POST:\n accion = request.POST.get(\"btnAccion\", \"\")\n if accion == \"Buscar\":\n idp = request.POST.get(\"idProducto\", \"\")\n ins = Insumo.objects.get(idProducto=idp)\n mensaje = False\n return render(request, 'core/actualizarinsumo.html', {'insumos':insu,'empresas':emp, 'ins': ins, 'mensaje': mensaje})\n if accion == \"Modificar\":\n idp = request.POST.get(\"idProducto\", \"\")\n ins = Insumo.objects.get(idProducto=idp)\n\n idProducto = request.POST.get(\"idProducto\", \"\")\n nombre = request.POST.get(\"nombre\", \"\")\n stock = request.POST.get(\"stock\",\"\")\n rutEmp = request.POST.get(\"rutEmpresa\",\"\")\n obj_empresa = Empresa.objects.get(rutEmpresa=rutEmp)\n ins.idProducto=idProducto\n ins.nombre=nombre\n ins.stock=stock\n ins.rutEmpresa=obj_empresa\n ins.save()\n mensaje = True\n return render(request, 'core/actualizarinsumo.html', {'mensaje': mensaje, 'empresa': emp})\n return render(request, 'core/actualizarinsumo.html', {'mensaje': mensaje,'insumos':insu, 'empresa': emp})\n\n\nclass ReportePersonasPDF(View):\n\n def cabecera(self, pdf):\n # Utilizamos el archivo logo_django.png que está guardado en la carpeta media/imagenes\n archivo_imagen = settings.MEDIA_ROOT+'/imagenes/logo_django.png'\n # Definimos el tamaño de la imagen a cargar y las coordenadas correspondientes\n pdf.drawImage(archivo_imagen, 40, 750, 120,\n 90, preserveAspectRatio=True)\n\n def tabla(self, pdf, y):\n # Creamos una tupla de encabezados para neustra tabla\n encabezados = ('Rut', 'Nombre Completo', 'Sexo',\n 'Fecha nacimiento', 'Direccion', 'Telefono')\n # Creamos una lista de tuplas que van a contener a las personas\n detalles = [(Colaborador.rut, Colaborador.nombreCompleto, Colaborador.sexo,\n Colaborador.fechaNacimiento, Colaborador.direccion, Colaborador.telefono) for Colaborador in Colaborador.objects.all()]\n # Establecemos el tamaño de cada una de las columnas de la tabla\n detalle_orden = Table([encabezados] + detalles,\n colWidths=[2.2 * cm, 4.5 * cm, 1.6 * cm, 2.9 * cm, 5 * cm, 2.2 * cm])\n # Aplicamos estilos a las celdas de la tabla\n detalle_orden.setStyle(TableStyle(\n [\n # La primera fila(encabezados) va a estar centrada\n ('ALIGN', (0, 0), (3, 0), 'CENTER'),\n # Los bordes de todas las celdas serán de color negro y con un grosor de 1\n ('GRID', (0, 0), (-1, -1), 1, colors.black),\n # El tamaño de las letras de cada una de las celdas será de 10\n ('FONTSIZE', (0, 0), (-1, -1), 10),\n ]\n ))\n # Establecemos el tamaño de la hoja que ocupará la tabla\n detalle_orden.wrapOn(pdf, 800, 600)\n # Definimos la coordenada donde se dibujará la tabla\n detalle_orden.drawOn(pdf, 40, y)\n\n def get(self, request, *args, **kwargs):\n\n # Indicamos el tipo de contenido a devolver, en este caso un pdf\n response = HttpResponse(content_type='application/pdf')\n # La clase io.BytesIO permite tratar un array de bytes como un fichero binario, se utiliza como almacenamiento temporal\n buffer = BytesIO()\n # Canvas nos permite hacer el reporte con coordenadas X y Y\n pdf = canvas.Canvas(buffer)\n # Llamo al método cabecera donde están definidos los datos que aparecen en la cabecera del reporte.\n self.cabecera(pdf)\n # Establecemos el tamaño de letra en 16 y el tipo de letra Helvetica\n pdf.setFont(\"Helvetica\", 16)\n # Dibujamos una cadena en la ubicación X,Y especificada\n pdf.drawString(240, 790, u\"ASEO INTEGRAL\")\n pdf.setFont(\"Helvetica\", 14)\n pdf.drawString(200, 770, u\"REPORTE DE COLABORADORES\")\n pdf.setFont(\"Helvetica\", 12)\n pdf.drawString(\n 40, 720, \"Detale de colaboradores registrados actualmente.\")\n y = 600\n self.tabla(pdf, y)\n # Con show page hacemos un corte de página para pasar a la siguiente\n pdf.showPage()\n pdf.save()\n pdf = buffer.getvalue()\n buffer.close()\n response.write(pdf)\n return response\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"621509679","text":"from pathlib import Path\n\nimport superannotate as sa\n\nsa.init(Path.home() / \".superannotate\" / \"config.json\")\n\n\ndef test_team_metadata():\n metadata = sa.get_team_metadata(convert_users_role_to_string=True)\n print(len(metadata[\"users\"]))\n print(metadata[\"users\"])\n","sub_path":"tests/test_team_metadata.py","file_name":"test_team_metadata.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"391403971","text":"# preferences_dialog.py\n#\n# MIT License\n#\n# Copyright (c) 2020 Andrey Maksimov \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport gi\n\ngi.require_version('Gtk', '3.0')\ngi.require_version('Granite', '1.0')\ngi.require_version('GtkSource', '3.0')\nfrom gi.repository import Gtk, Granite, GtkSource\n\n\nclass PreferencesDialog(Gtk.Dialog):\n __gtype_name__ = 'SettingsDialog'\n\n def __init__(self, transient_for, settings):\n super().__init__(transient_for=transient_for, modal=False)\n\n self.settings = settings\n self.set_default_size(340, 300)\n\n self.set_border_width(5)\n self.set_deletable(False)\n self.set_title('Preferences')\n\n indent_width = Gtk.SpinButton.new_with_range(1, 24, 1)\n indent_width.set_value(self.settings.get_int('indent-width'))\n indent_width.connect('value-changed', self.on_indent_width)\n\n self.spellcheck_switch = Gtk.Switch(halign=Gtk.Align.START, valign=Gtk.Align.CENTER)\n self.spellcheck_switch.set_state(self.settings.get_boolean('spellcheck'))\n self.spellcheck_switch.connect(\"state-set\", self.on_spellcheck)\n\n self.autosave_switch = Gtk.Switch(halign=Gtk.Align.START, valign=Gtk.Align.CENTER)\n self.autosave_switch.set_state(self.settings.get_boolean('autosave'))\n self.autosave_switch.connect(\"state-set\", self.on_autosave)\n\n self.autoindent_switch = Gtk.Switch(halign=Gtk.Align.START, valign=Gtk.Align.CENTER)\n self.autoindent_switch.set_state(self.settings.get_boolean('autoindent'))\n self.autoindent_switch.connect(\"state-set\", self.on_autoindent)\n\n self.spaces_tabs_switch = Gtk.Switch(halign=Gtk.Align.START, valign=Gtk.Align.CENTER)\n self.spaces_tabs_switch.set_state(self.settings.get_boolean('spaces-instead-of-tabs'))\n self.spaces_tabs_switch.connect(\"state-set\", self.on_spaces_tabs)\n\n general_grid = Gtk.Grid(column_spacing=12, row_spacing=6)\n\n general_grid.attach(Granite.HeaderLabel(\"General\"), 0, 0, 3, 1)\n general_grid.attach(Gtk.Label(\"Save files when changed:\", halign=Gtk.Align.END), 0, 1, 1, 1)\n general_grid.attach(self.autosave_switch, 1, 1, 1, 1)\n general_grid.attach(Gtk.Label(\"Spell checking:\", halign=Gtk.Align.END), 0, 2, 1, 1)\n general_grid.attach(self.spellcheck_switch, 1, 2, 1, 1)\n\n general_grid.attach(Granite.HeaderLabel(\"Tabs\"), 0, 3, 3, 1)\n general_grid.attach(Gtk.Label(\"Automatic indentation:\", halign=Gtk.Align.END), 0, 4, 1, 1)\n general_grid.attach(self.autoindent_switch, 1, 4, 1, 1)\n general_grid.attach(Gtk.Label(\"Insert spaces instead of tabs:\", halign=Gtk.Align.END), 0, 5, 1, 1)\n general_grid.attach(self.spaces_tabs_switch, 1, 5, 1, 1)\n general_grid.attach(Gtk.Label(\"Tab width:\", halign=Gtk.Align.END), 0, 6, 1, 1)\n general_grid.attach(indent_width, 1, 6, 2, 1)\n\n interface_grid = Gtk.Grid(column_spacing=12, row_spacing=6)\n scrolled = Gtk.ScrolledWindow(hexpand=True, vexpand=True)\n style_chooser = GtkSource.StyleSchemeChooserWidget()\n style_chooser.connect('notify::style-scheme', self.on_scheme_changed)\n scrolled.add(style_chooser)\n\n scheme = GtkSource.StyleSchemeManager().get_scheme(\n self.settings.get_string('stylescheme')\n )\n if not scheme:\n scheme = GtkSource.StyleSchemeManager().get_scheme(\"classic\")\n\n style_chooser.set_style_scheme(scheme)\n\n interface_grid.attach(Granite.HeaderLabel(\"Styles\"), 0, 0, 2, 1)\n interface_grid.attach(scrolled, 0, 2, 2, 1)\n\n main_stack = Gtk.Stack(margin=6, margin_bottom=18, margin_top=8)\n main_stack.add_titled(general_grid, \"behavior\", \"Behavior\")\n main_stack.add_titled(interface_grid, \"interface\", \"Interface\")\n\n main_stackswitcher = Gtk.StackSwitcher()\n main_stackswitcher.set_stack(main_stack)\n main_stackswitcher.set_halign(Gtk.Align.CENTER)\n\n main_grid = Gtk.Grid()\n main_grid.attach(main_stackswitcher, 0, 0, 1, 1)\n main_grid.attach(main_stack, 0, 1, 1, 1)\n\n self.get_content_area().add(main_grid)\n\n close_button = Gtk.Button(label=\"Close\")\n close_button.connect('clicked', self.on_close_activated)\n self.add_action_widget(close_button, 0)\n\n def on_spellcheck(self, sender: Gtk.Widget, state):\n self.settings.set_boolean(\"spellcheck\", state)\n return False\n\n def on_autosave(self, sender: Gtk.Widget, state):\n self.settings.set_boolean(\"autosave\", state)\n return False\n\n def on_close_activated(self, sender: Gtk.Widget):\n self.destroy()\n\n def on_scheme_changed(self, style_chooser, event):\n self.settings.set_string('stylescheme', style_chooser.get_style_scheme().get_id())\n\n def on_autoindent(self, sender, state):\n self.settings.set_boolean('autoindent', state)\n\n def on_spaces_tabs(self, sender, state):\n self.settings.set_boolean('spaces-instead-of-tabs', state)\n\n def on_indent_width(self, sender: Gtk.SpinButton) -> None:\n self.settings.set_int('indent-width', sender.get_value_as_int())\n","sub_path":"norka/widgets/preferences_dialog.py","file_name":"preferences_dialog.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"483117931","text":"xxx = \"buy\"\nsell = 1\nhold = 2\n\ndef trade(a):\n\tif a == \"buy\":\n\t\tbuy_one()\n\tif a == 1:\n\t\tsell_one()\n\tif a == 2:\n\t\thold_position()\n\telse:\n\t\treturn 0\n\ndef buy_one():\n\tprint(\"买入成功\")\n\ndef sell_one():\n\tprint(\"卖出成功\")\n\ndef hold_position():\n\tprint(\"仓位不变\")\n\ntrade(\"buy\")\n\ntrade(sell)\n\ntrade(hold)\n","sub_path":"lecture3/solution/trade.py","file_name":"trade.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"266308724","text":"from .. typecheck import *\nfrom .. import core\n\nimport sublime\nimport sublime_plugin\n\nclass GutterEvent:\n\tdef __init__(self, view: sublime.View, line: int, button: int = 0) -> None:\n\t\tself.view = view\n\t\tself.line = line\n\t\tself.button = button\n\n\nclass HoverEvent:\n\tdef __init__(self, view: sublime.View, point: int) -> None:\n\t\tself.view = view\n\t\tself.point = point\n\n\n# all these events are dispatched from sublime's main thread to our own main loop\nview_loaded = core.Event() #type: core.Event[sublime.View]\nview_activated = core.Event() #type: core.Event[sublime.View]\nview_text_hovered = core.Event() #type: core.Event[HoverEvent]\nview_gutter_hovered = core.Event() #type: core.Event[GutterEvent]\nview_gutter_clicked = core.Event() #type: core.Event[GutterEvent]\nview_selection_modified = core.Event() #type: core.Event[sublime.View]\nview_modified = core.Event() #type: core.Event[sublime.View]\nview_drag_select = core.Event() #type: core.Event[sublime.View]\n\n\nclass ViewEventsListener(sublime_plugin.EventListener):\n\n\t# detects clicks on the gutter\n\t# if a click is detected we then reselect the previous selection\n\t# This means that a click in the gutter no longer selects that line\n\tdef on_text_command(self, view: sublime.View, cmd: str, args: dict) -> Any:\n\t\tif (cmd == 'drag_select' or cmd == 'context_menu') and 'event' in args:\n\t\t\tevent = args['event']\n\n\t\t\tview_x, view_y = view.layout_to_window(view.viewport_position()) #type: ignore\n\n\t\t\tx = event['x']\n\t\t\ty = event['y']\n\n\t\t\tmargin = view.settings().get(\"margin\") or 0\n\t\t\toffset = x - view_x\n\n\t\t\tview.window().run_command(\"hide_overlay\")\n\t\t\tif offset < -30 - margin:\n\t\t\t\tpt = view.window_to_text((x, y))\n\t\t\t\tline = view.rowcol(pt)[0]\n\t\t\t\tview_gutter_clicked.post(GutterEvent(view, line, event['button']))\n\t\t\t\treturn (\"null\", {})\n\n\tdef on_hover(self, view: sublime.View, point: int, hover_zone: int) -> None:\n\t\tif hover_zone == sublime.HOVER_GUTTER:\n\t\t\tline = view.rowcol(point)[0]\n\t\t\tview_gutter_hovered.post(GutterEvent(view, line))\n\t\telif hover_zone == sublime.HOVER_TEXT:\n\t\t\tview_text_hovered.post(HoverEvent(view, point))\n\n\tdef on_modified(self, view: sublime.View) -> None:\n\t\tview_modified.post(view)\n\n\tdef on_load(self, view: sublime.View) -> None:\n\t\tview_loaded.post(view)\n\n\tdef on_activated(self, view: sublime.View) -> None:\n\t\tview_activated.post(view)\n","sub_path":"modules/ui/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"623199043","text":"import pygame\r\nimport random\r\nimport math\r\nimport time\r\nimport pdb\r\nimport matplotlib.pyplot as plt\r\n\r\n# global parameters\r\nV_AGE = 10\r\nI_AGE = 10\r\nPROB_INFECT = .1\r\nPROB_PRODUCT = .1\r\nVIRUS_BURN_NO = 1\r\n\r\nclass Virus():\r\n '''Virus Class:\r\n Two attributes: location and age ([0,10])\r\n also able to : move(width, height) \r\n '''\r\n def __init__(self,loc,age):\r\n self.loc = loc\r\n self.age = age\r\n \r\n def move(self,width,height):\r\n self.loc[0] = random.choice(range(width))\r\n self.loc[1] = random.choice(range(height))\r\n\r\n# virus list \r\nclass MapGrid():\r\n def __init__(self, map_width, map_height,moi):\r\n # set map values\r\n self.map_width = map_width\r\n self.map_height = map_width\r\n self.moi = moi\r\n\r\n # generate outside rooms\r\n self.Virus_list,self.init_grids = self._generate_init_grids(self.map_width,self.map_height,self.moi)\r\n self.ICell_set = {}# key is (x,y), value is age\r\n self.Dead_set = set([])\r\n\r\n def _generate_init_grids(self, map_width, map_height, moi):\r\n '''\r\n creates a random distirubted virus in the map with moi from 0 to 1\r\n '''\r\n global V_AGE\r\n Virus_list = []\r\n\r\n # init 1: fill the grids with T (state 3)\r\n new_map_grid = [[3]* map_width for i in xrange(map_height)] \r\n\r\n # init 2: random distribute moi virus.\r\n num_grids = map_height*map_width\r\n virus_seq = random.sample(range(num_grids),int(moi*num_grids)) #1D\r\n\r\n for virus in virus_seq: # 1D-> 2D\r\n virus_ind = [virus%map_width,virus/map_height]\r\n new_map_grid[virus_ind[0]][virus_ind[1]] = 4\r\n Virus_list.append(Virus(virus_ind,random.choice(range(V_AGE)))) # random asign age\r\n\r\n # return grids and virus_list\r\n return Virus_list,new_map_grid \r\n\r\n def _remove(self,age_limit,class_list):\r\n '''Input class which have age'''\r\n return filter(lambda a:a.age!=age_limit,class_list)\r\n\r\n def _virus_update(self,grids,ind):\r\n '''Update the virus which is free'''\r\n pre_loc = self.Virus_list[ind].loc\r\n self.Virus_list[ind].move(self.map_width,self.map_height)\r\n tmp_loc = self.Virus_list[ind].loc\r\n if tmp_loc != pre_loc:\r\n if grids[pre_loc[0]][pre_loc[1]] == 1:\r\n grids[pre_loc[0]][pre_loc[1]] = 0\r\n elif grids[pre_loc[0]][pre_loc[1]] == 4:\r\n grids[pre_loc[0]][pre_loc[1]] = 3\r\n if grids[tmp_loc[0]][tmp_loc[1]] == 0:\r\n grids[tmp_loc[0]][tmp_loc[1]] = 1\r\n elif grids[tmp_loc[0]][tmp_loc[1]] == 3:\r\n grids[tmp_loc[0]][tmp_loc[1]] = 4\r\n \r\n return grids\r\n\r\n def _update_whole_CA(self, pre_grids):\r\n '''\r\n Update the whole CA model here. \r\n '''\r\n global VIRUS_BURN_NO\r\n global I_AGE \r\n global PROB_INFECT\r\n global PROB_PRODUCT \r\n global V_AGE\r\n\r\n grids = pre_grids \r\n # 1. Update the ICell age, death and virus production \r\n for ICell in self.ICell_set:\r\n self.ICell_set[ICell] += 1\r\n\r\n #if self.ICell_set[ICell] >= I_AGE: #ICell explode to Virus\r\n if random.random() < PROB_PRODUCT: #ICell explode to Virus\r\n self.ICell_set[ICell] = 1000\r\n\r\n for tmp in range(VIRUS_BURN_NO): #budding virus copy number\r\n self.Virus_list.append(Virus(list(ICell),-1))\r\n\r\n grids[ICell[0]][ICell[1]] = 1\r\n \r\n else:\r\n grids[ICell[0]][ICell[1]] = 2\r\n\r\n # remove dead \r\n self.Dead_set = self.Dead_set | {k for k,v in self.ICell_set.items() if v==1000}\r\n self.ICell_set = {k:v for k,v in self.ICell_set.items() if v!=1000}\r\n\r\n for xy in self.Dead_set:\r\n grids[xy[0]][xy[1]] = 0\r\n\r\n # 2. Update Virus\r\n for i in range(len(self.Virus_list)):\r\n loc_tmp =self.Virus_list[i].loc\r\n if self.Virus_list[i].age!=-1:\r\n self.Virus_list[i].age +=1 # update age \r\n\r\n if grids[loc_tmp[0]][loc_tmp[1]] ==4: # T+V already\r\n p_tmp = random.random() # random number to determine infection\r\n if p_tmp > PROB_INFECT: #if infected\r\n # add this cell to I Cells (age 0)\r\n self.ICell_set[tuple(loc_tmp)] = 0\r\n \r\n grids[loc_tmp[0]][loc_tmp[1]] = 2 # Update grid to Infected state \r\n self.Virus_list[i].age = V_AGE # mark this virus to remove \r\n else: # not infected\r\n grids = self._virus_update(grids,i)\r\n else: # not T+V \r\n grids = self._virus_update(grids,i)\r\n\r\n else: # just born, set age to 0\r\n self.Virus_list[i].age += 1\r\n grids[loc_tmp[0]][loc_tmp[1]] = 1 # Update grid to Infected state \r\n \r\n self.Virus_list = self._remove(V_AGE,self.Virus_list)\r\n\r\n return grids\r\n\r\n\r\nif __name__ == '__main__':\r\n # general map stats\r\n map_width = 500\r\n map_height = 500 \r\n moi = 0.1\r\n no_cells = float(map_width*map_height)\r\n \r\n # start with one generation\r\n tile_size = 15\r\n unit_size = 15\r\n \r\n map_grid = MapGrid(map_width, map_height,moi) #init a random grid filled with 0s and 1s \r\n \r\n pygame.init()\r\n\r\n screen = pygame.display.set_mode((map_width * tile_size,map_height * tile_size))#return Surface\r\n\r\n zero_tile = pygame.Surface((unit_size, unit_size))\r\n zero_tile.fill((0,0,0))#blue, nothing\r\n one_tile = pygame.Surface((unit_size,unit_size))\r\n one_tile.fill((255,255,0)) # yellow , virus \r\n two_tile = pygame.Surface((unit_size,unit_size))\r\n two_tile.fill((0,255,0)) # green, infected cell\r\n three_tile = pygame.Surface((unit_size,unit_size))\r\n three_tile.fill((255,0,0)) # red, target cell\r\n four_tile = pygame.Surface((unit_size,unit_size))\r\n four_tile.fill((255,165,0)) # orange, T + V\r\n colors = {0: zero_tile, 1: zero_tile, 2: two_tile , 3: three_tile, 4:three_tile} \r\n \r\n \r\n background = pygame.Surface((map_width * tile_size,map_height * tile_size))\r\n\r\n clock = pygame.time.Clock()#an object to help track time \r\n\r\n first_gen = True\r\n timer = 1\r\n \r\n running = True\r\n generation = 0\r\n\r\n # plot setting\r\n fig = plt.figure()\r\n plt.axis = ([0,100,0,1])\r\n plt.ion()\r\n plt.show()\r\n \r\n # running \r\n while running == True:\r\n clock.tick(1)\r\n\r\n for event in pygame.event.get():#get the events from queue\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\n if first_gen:\r\n themap = map_grid.init_grids\r\n else:\r\n themap1 = map_grid._update_whole_CA(themap) #update 1 generation \r\n themap = themap1 \r\n # visualization \r\n for column_index, column in enumerate(themap):\r\n for tile_index, tile in enumerate(column):\r\n screen.blit(colors[tile], (tile_index * tile_size, column_index * tile_size))\r\n\r\n pygame.display.flip()\r\n\r\n if first_gen:\r\n timer -= 1\r\n if timer <= 0:\r\n first_gen = False\r\n\r\n virus_frac = float(len(map_grid.Virus_list)/no_cells) \r\n I_frac = float(len(map_grid.ICell_set)/(no_cells-len(map_grid.Dead_set))) \r\n\r\n generation += 1\r\n pygame.display.set_caption('G: ' + str(generation) + ' VF: ' + str(virus_frac)\r\n +' IF: '+str(I_frac) )\r\n\r\n # plot\r\n plt.scatter(generation,I_frac)\r\n plt.draw()\r\n\r\n pygame.quit()\r\n","sub_path":"CA_mac3.1.py","file_name":"CA_mac3.1.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"295451136","text":"#!/usr/bin/env python3\n\nimport numpy as np\nfrom tensorflow import keras\nimport datetime\n\n\nINPUT_SHAPE=(11,)\n\nclass Model():\n\n def __init__(self, model, name, outfile):\n self.model = model\n self.name = name\n self.outfile = outfile\n\n def train(self, Xs, Ys, epochs=100):\n tf_callback = keras.callbacks.TensorBoard()\n \n dt = datetime.datetime.now().replace(microsecond=0).isoformat()\n checkpoint_path = 'checkpoints/weights.' + self.name + '.' + dt +'.{epoch:02d}-{val_loss:.2f}.hdf'\n checkpoint_callback = keras.callbacks.ModelCheckpoint(checkpoint_path)\n \n early_stopping = keras.callbacks.EarlyStopping(patience=2)\n \n val_split = 0.1\n self.model.fit(Xs, Ys, epochs=epochs, validation_split=val_split, shuffle=True,\n callbacks=[tf_callback, checkpoint_callback, early_stopping])\n self.model.save(self.outfile)\n\n\n\ndef evaluate(Xs_val, Ys_val, model_name):\n from sklearn.metrics import classification_report\n model = keras.models.load_model(model_name + '.h5')\n ys = model.predict(Xs_val)\n y_pred = []\n for y in ys:\n a = [0]*len(y)\n a[np.argmax(y)] = 1\n y_pred.append(a)\n y_pred = np.array(y_pred)\n print(classification_report(Ys_val, y_pred)) \n\n res = model.evaluate(Xs_val, Ys_val)\n print(res)\n \ndef model_logistic_regression():\n name = 'model_single_logistic_regression'\n\n input_shape = INPUT_SHAPE\n model = keras.Sequential()\n model.add(keras.layers.Dense(5, input_shape=input_shape, activation=\"softmax\"))\n model.compile(optimizer=keras.optimizers.Adam(),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model, name\n\n\ndef model_3_layers():\n #name = 'model_single_3_layers'\n\n input_shape = INPUT_SHAPE\n model = keras.Sequential()\n model.add(keras.layers.Dense(200, input_shape=input_shape, activation=\"relu\"))\n model.add(keras.layers.Dense(200, activation=\"relu\"))\n model.add(keras.layers.Dense(200, activation=\"relu\"))\n model.add(keras.layers.Dense(5, activation=\"softmax\"))\n model.compile(optimizer=keras.optimizers.Adam(),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model#, name\n\ndef model_8_layers():\n name = 'model_single_8_layers'\n\n input_shape = INPUT_SHAPE\n model = keras.Sequential()\n model.add(keras.layers.Dense(600, input_shape=input_shape, activation=\"relu\"))\n model.add(keras.layers.Dense(600, activation=\"relu\"))\n model.add(keras.layers.Dropout(0.1))\n model.add(keras.layers.Dense(400, activation=\"relu\"))\n model.add(keras.layers.Dense(400, activation=\"relu\"))\n model.add(keras.layers.Dropout(0.1))\n model.add(keras.layers.Dense(200, activation=\"relu\"))\n model.add(keras.layers.Dense(200, activation=\"relu\"))\n model.add(keras.layers.Dropout(0.1))\n model.add(keras.layers.Dense(100, activation=\"relu\"))\n model.add(keras.layers.Dense(100, activation=\"relu\"))\n model.add(keras.layers.Dense(5, activation=\"softmax\"))\n model.compile(optimizer=keras.optimizers.Adam(),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n return model, name\n\n\ndef cli():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--csv', dest='csvfile', help='CSV-file containing training-data')\n parser.add_argument('-o', dest='outfile', help='filename of outputted model')\n args = parser.parse_args()\n build_model(args.csvfile, args.outfile)\n \n\ndef build_model(csvfile, outfile):\n from fotokat.model_single.data import load_data\n Xs, Ys = load_data(csvfile)\n\n M = Model(model_3_layers(), 'model_single_3_layers', outfile)\n M.train(Xs, Ys) #, epochs=10)\n \n\nif __name__ == '__main__':\n from fotokat.model_single.data import load_data\n Xs, Ys = load_data('model_single_spatial_train.csv')\n\n # model = model_logistic_regression\n model = model_3_layers\n # model = model_8_layers\n M = Model(model)\n M.train(Xs, Ys) #, epochs=10)\n\n Xs_val, Ys_val = load_data('model_single_spatial_validate.csv')\n evaluate(Xs_val, Ys_val, M.name)\n","sub_path":"src/fotokat/model_single/Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"459631452","text":"#!/usr/bin/python3\n\"\"\" Write a Python script that fetches https://intranet.hbtn.io/status \"\"\"\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n q = \"\"\n if len(sys.argv) > 1:\n q = sys.argv[1]\n p = 1\n parms = {'search': q, 'page': p}\n html = requests.get('https://swapi.co/api/people/', params=parms).json()\n try:\n cont = html['count']\n print(\"Number of results: \" + str(cont))\n for i in range(cont):\n for j in html['results']:\n print(j['name'])\n p += 1\n parms = {'search': q, 'page': p}\n link = 'https://swapi.co/api/people/'\n html = requests.get(link, params=parms).json()\n except ValueError:\n print(\"Not a valid JSON\")\n except KeyError:\n sys.exit()\n","sub_path":"0x11-python-network_1/101-starwars.py","file_name":"101-starwars.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"460772220","text":"from tika import parser\nfile1= r'C:\\Users\\Administrator\\PycharmProjects\\pythonProject\\mongodb\\Flipkart-Labels-28-Jun-2021-05-08.pdf'\nraw = parser.from_file(file1)\ndata = raw['content']\ndata1 = str(data)\n# print(str(data))\nawb = data1.split('Courier AWB No:')\n# print(d,'lenth of d',len(d))\nawb1 = awb[1].split()[0]\nprint('awb1 from invoice :', awb1)\n# print(awb1=='519330918214')\norder_id = data1.split('Order ID:')\norder_id_invice = order_id[1].split()[0]\nprint('order id from invoice:', order_id_invice)","sub_path":"mongodb/dummy1.py","file_name":"dummy1.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"478095295","text":"import copy\nfrom operator import add\ndef line(pos, dir, a, origin): #find the longest continous line\n ''' dir =[[-1,0,+1],[-1,0,+1]]\n \n '''\n pos1 = [pos[0] + dir[0], pos[1]+dir[1]]\n if isvalid(pos1, a, origin):\n while a[pos1[0]][pos1[1]] == 1:\n pos1 = map(add, pos1, dir)\n if not isvalid(pos1, a, origin):\n break\n pos1 = [pos1[0] - dir[0], pos1[1]-dir[1]]\n return pos1\n\ndef isvalid(pos, a, origin):\n if pos[0]>=origin[0] and pos[0]=origin[1] and pos[1] 0:\n area = A * B\n if mArea < area:\n mArea = area\n return mArea \n\ndef nextdir(dir):\n if dir == [0,1]:\n return [1,0]\n if dir == [1,0]:\n return [0,-1]\n if dir == [0,-1]:\n return [-1,0]\n if dir == [-1,0]:\n return [0,1]\n return\n \n\n\ndef conline(pos, dir, a, origin): #find connected line\n pos1 = line(pos, dir, a, origin)\n if pos == pos1:\n return -1\n d = copy.deepcopy(dir)\n if d[0] == 0:\n d[0] = 1\n if d[1] == 0:\n d[1] = 1\n plist = [[x,y] for x in range(pos[0],pos1[0]+d[0], d[0]) \n for y in range(pos[1],pos1[1]+d[1], d[1])]\n plist.reverse()\n plist = plist[0:-1]\n if dir == [0,-1]:\n plist1 = filter(lambda x: x[1]==origin[1], plist)\n if len(plist1) == 0:\n return -1\n else:\n plist= plist1\n elif dir == [-1,0]:\n if origin in plist:\n return plist[-1][0]-origin[0]+2\n else:\n return -1\n for p in plist:\n l = conline(p,nextdir(dir),a, origin)\n if l>0:\n break\n\n return l\n #for i in range(\n","sub_path":"findobj.py","file_name":"findobj.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"230261075","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name = \"home\"),\n path('delete//', views.delete_city, name='delete_city'),\n path('login', views.MyprojectLoginView.as_view(), name = 'login_page'),\n path('register', views.RegisterUserView.as_view(), name = 'register_page'),\n path('logout', views.MyprojectLogout.as_view(), name = 'logout_page'),\n]\n","sub_path":"Lab4/django-Lab4/myapp/weather/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"266910522","text":"#code\r\n#import collections\r\nt = int(input())\r\na = -1\r\nfor i in range(t):\r\n freq = {}\r\n n = int(input())\r\n flag = 0\r\n arr = list(map(int,input().split()))\r\n for item in arr:\r\n if item in freq:\r\n freq[item]+=1\r\n else:\r\n freq[item] = 1\r\n for key in freq:\r\n if freq[key] > n/2:\r\n flag = 1\r\n print(key)\r\n break\r\n if flag == 0:\r\n print(a)","sub_path":"Majority_element_in_array.py","file_name":"Majority_element_in_array.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"351149070","text":"x = 40\ny = 50\n\n# if, elif and else\n\nif x < y:\n print(f'{x} < {y} and y is {y}')\nelif x > y:\n print('{0} > {1}'.format(x, y))\nelse:\n print('Do something else.')\n\n# Membership Operator\nlst = [\"Mattz\",\"Grace\",\"Travis Scott\"]\nif \"Travis Scott\" in lst:\n print(\"In collection\")\n\nif \"Gray Joy\" not in lst:\n print(\"Not in collection\")\n\nqy = \"Bob\"\nqz = \"Bob\"\nqx = \"Zob\"\npresent = True\n\n# Identity Operators: is, is not.\n# is operator, compares the objects/instances not the values.\nif qy is not qz:\n print(\"They aint the same instance.\")\n\nif qy is qz:\n print(\"They are the same instance.\")\n\n# Logical Operators: or, and, not.\nif (qy is qz) and (qy is not qx):\n print(\"Truthy.\")\n\nprint(not present)\n\n# Ternery Operator\nhungry = True\nfeed = 'Feed the bear now!' if hungry else 'Do not feed the bear'\nprint(feed)","sub_path":"conditionals.py","file_name":"conditionals.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"49874266","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 18 15:28:12 2019\r\n2020/01/13 Plot 3D crystal strucutre and then cut it into a retangular shape\r\n Quick method to find matrix elements using Pandat\r\n2020/01/15 Adjust the method to find neighbors quickly with the help of MK\r\n2020/01/15 The center's brightness could be weaker than its negbours \r\n Change the code for Al-Mg \r\n2020/01/17 Add a cycle for calculating Al-Al and Mg-Mg sequentially\r\n Add a cycle for generating library of SDMs with different z noise\r\n Save SDMs into a local file with a nomenclature \r\n2020/01/20 Delete all ticks and enlarge it to fill in whole background for CNN preprocessing \r\n2020/01/24 add new plotting style \r\n from matplotlib.colors import BoundaryNorm\r\n from matplotlib.ticker import MaxNLocator\r\n2020/02/10 change pole to [111] \r\n2020/02/20 generate more figures: detection eff, noise in z direction \r\n2020/04/22 optimze figures plot \r\n2020/04/23 modify SDMs part \r\n2020/05/24 creat BCC_Fe crystal \r\n2020/06/18 optimize code\r\n2020/07/15 FCC Al L12 AlMg\r\n2020/07/27 optimizing codes\r\n@author: yue.li\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport os\r\nimport shutil\r\nfrom Euler_transformation import Euler_transformation_100, Euler_transformation_110, Euler_transformation_111\r\nfrom generator_single_SDMs import single_SDMs\r\n#%% Input file and parameters\r\ndata = np.loadtxt('ggoutputFile_L12_5nm_a_0.405.txt')\r\nlattice_para = 0.405\r\n\r\nsigma_xy_all = np.arange(0.2,0.8,0.2)\r\nsigma_z_all = np.arange(0.03,0.055,0.002)\r\ndetect_eff_array = np.arange(0.35,0.8,0.02)\r\natomic_number_1 = 27 #Al\r\natomic_number_2 = 24 #Mg\r\nplot_noise = False #default\r\nplot_SDM = False #default\r\nDelete_folder = True #default\r\nimage_name_1 = \"AlMgLi_L12_AlAl\"\r\nimage_name_2 = \"AlMgLi_L12_MgMg\"\r\n#%% clean ouptfile contents\r\nif Delete_folder == True:\r\n try:\r\n shutil.rmtree('Results') \r\n except:\r\n print(\"file does not exist\")\r\n os.mkdir('Results') \r\n#%% Remove all duplicates \r\ndata_clean = np.unique(data, axis=0)\r\n#%% Euler_transformation\r\n# data_reconstruction = Euler_transformation_100(data_clean, False)\r\ndata_reconstruction = Euler_transformation_110(data_clean, False)\r\n# data_reconstruction = Euler_transformation_111(data_clean, False)\r\n#%% Add Gaussian noise\r\nfor sigma_xy in sigma_xy_all:\r\n for sigma_z in sigma_z_all:\r\n single_SDMs(data_reconstruction, sigma_xy, sigma_z, plot_noise, detect_eff_array, atomic_number_1, atomic_number_2, lattice_para, image_name_1, image_name_2, plot_SDM)\r\n#%%images into H5f\r\n","sub_path":"Simulation of zx-SDMs/SDM_v7.1_for_L12_AlMg.py","file_name":"SDM_v7.1_for_L12_AlMg.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"453805244","text":"# ==============================================================================\r\n\"\"\"INIFILE : demo for 'read_ini/write_ini' functions from the 'ezCLI' toolbox\"\"\"\r\n# ==============================================================================\r\n__author__ = \"Christophe Schlick\"\r\n__version__ = \"1.0\"\r\n__date__ = \"2015-07-01\"\r\n__usage__ = \"\"\"\r\nSimply press at each pause\"\"\" \r\n# ==============================================================================\r\nfrom ezCLI import *\r\n# ------------------------------------------------------------------------------\r\n# Sample use cases for 'read_ini'\r\n# ------------------------------------------------------------------------------\r\n# first read the file as a text file to show its raw content\r\ntxt = read_txt('test-ini.txt')\r\npause(\">>> read INI file as a TXT file :\\n%s\" % txt)\r\n\r\n# return the data stored in file and apply 'convert' to all items\r\nini = read_ini('test-ini.txt')\r\npause(\">>> read INI file and convert all data type :\\n%s\" % ini)\r\n\r\n# return the data stored in file but keep all items as strings\r\nini = read_ini('test-ini.txt', raw=True)\r\npause(\">>> read INI file as keep all data as strings :\\n%s\" % ini)\r\n\r\n# ------------------------------------------------------------------------------\r\n# Sample use cases for 'write_ini'\r\n# ------------------------------------------------------------------------------\r\n# sample data containing 5 properties spread in 3 sections \r\nitems = {'':{'a':1,'b':2},'AAA':{'aa':1.2,'bb':''},'BBB':{'cc':'#'}}\r\npause(\">>> sample structured data : \\n%s\" % items)\r\n\r\n# replace the whole file and return the new file content\r\nini = write_ini('test.txt', items)\r\npause(\">>> write structured data as an INI file : \\n%s\" % ini)\r\n\r\n# insert new section at tail and return new file content\r\nini = write_ini('test.txt', '\\n[CCC]\\nzz = 0', -1)\r\npause(\">>> insert new section at tail : \\n%s\" % ini)\r\n\r\n# replace property stored at line 4 and return new file content\r\nini = write_ini('test.txt', {'aa':2.5}, 4, 5)\r\npause(\">>> replace property stored at line 4 : \\n%s\" % ini)\r\n# ==============================================================================\r\n","sub_path":"exo_cours/EXP-B/B5A_inifile.py","file_name":"B5A_inifile.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"259983676","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Test doubly_linked_list.py.\"\"\"\n\nimport pytest\n\n\nREMOVE_ERROR_NUMBERS = [[1, 2, 3], [1], []]\n\n\ndef test_push():\n \"\"\"Test push method.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n lst.push(0)\n assert lst.head.value == 0\n assert lst.tail.value == 0\n lst.push(1)\n assert lst.head.value == 1\n assert lst.tail.value == 0\n\n\ndef test_append():\n \"\"\"Test append method.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n lst.append(0)\n assert lst.tail.value == 0\n assert lst.head.value == 0\n lst.append(1)\n assert lst.tail.value == 1\n assert lst.head.value == 0\n\n\ndef test_pop():\n \"\"\"Test pop method.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n lst.push(1)\n lst.push(2)\n assert lst.count == 2\n assert lst.pop() == 2\n assert lst.pop() == 1\n assert lst.count == 0\n\n\ndef test_pop_error():\n \"\"\"Test pop throws IndexError.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n with pytest.raises(IndexError):\n lst.pop()\n\n\ndef test_shift():\n \"\"\"Test shift method.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n lst.append(1)\n lst.append(2)\n assert lst.count == 2\n assert lst.shift() == 2\n assert lst.shift() == 1\n assert lst.count == 0\n\n\ndef test_shift_error():\n \"\"\"Test shift throws IndexError.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n with pytest.raises(IndexError):\n lst.shift()\n\n\ndef test_remove():\n \"\"\"Test remove method.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList()\n lst.push(3)\n lst.push(2)\n lst.push(1)\n lst.remove(2)\n assert lst.head.next_node.value == 3\n assert lst.tail.previous_node.value == 1\n lst.remove(1)\n assert lst.head.value == 3\n lst.remove(3)\n assert lst.head is None\n assert lst.tail is None\n\n\n@pytest.mark.parametrize('values', REMOVE_ERROR_NUMBERS)\ndef test_remove_error(values):\n \"\"\"Test remove throws IndexError.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList(values)\n with pytest.raises(IndexError):\n lst.remove(False)\n\n\ndef test_append_and_pop():\n \"\"\"Test combination of append and pop operations.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList([3, 2, 1])\n assert lst.pop() == 1\n assert lst.pop() == 2\n lst.append(4)\n assert lst.pop() == 3\n assert lst.pop() == 4\n\n\ndef test_push_and_shift():\n \"\"\"Test combination of shift and push operations.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList([1, 2, 3])\n assert lst.shift() == 1\n assert lst.shift() == 2\n lst.push(4)\n assert lst.shift() == 3\n assert lst.shift() == 4\n\n\ndef test_size_remove():\n \"\"\"Test combination of shift and push operations.\"\"\"\n from .doubly_linked_list import DoublyLinkedList\n lst = DoublyLinkedList([1, 2, 3])\n lst.remove(2)\n assert lst.size() == 2\n lst.remove(3)\n assert lst.size() == 1\n lst.remove(1)\n assert lst.size() == 0\n","sub_path":"src/test_doubly_linked_list.py","file_name":"test_doubly_linked_list.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"229224807","text":"from dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Any\nimport uuid\nfrom functools import reduce\nfrom operator import add\n\n\nclass VariableBase:\n pass\n\n\nclass VariableType(Enum):\n CONSTANT = 0\n PARAMETER = 1\n STATE = 2\n DERIVATIVE = 3\n\n\nclass OverloadAction(Enum):\n RaiseError = 0\n SUM = 1\n\n\n@dataclass\nclass VariableDescription:\n tag: str\n type: VariableType = VariableType.PARAMETER\n initial_value: Any = None\n id: str = None\n\n\n@dataclass\nclass DetailedVariableDescription(VariableDescription):\n namespace: Any = None\n item: Any = None\n metadata: dict = None\n mapping: None = None\n update_counter: int = None\n allow_update: True = None\n\n\nclass MappedValue(object):\n def __init__(self, id):\n self.id = id\n self.mapping = None\n self.sum_mapping = []\n self.special_mapping = False\n self.addself = False\n\n def add_mapping(self, variable):\n if not self.special_mapping:\n if variable.id == self.id:\n raise RecursionError(\"Variable {0} cannot be mapped to itself\", self.id)\n self.mapping = variable\n self.special_mapping = False\n\n def add_sum_mapping(self, variable):\n self.sum_mapping.append(variable)\n\n def __iadd__(self, other):\n if isinstance(other, Variable):\n if self.mapping:\n raise ValueError('It is not possible to add a summation to {0}. Variable already have mapping'\n ''.format(self.tag))\n else:\n self.add_sum_mapping(other)\n self.special_mapping = True\n return self\n else:\n object.__iadd__(self, other)\n\n def __get_value(self, ids):\n if self.id in ids:\n return self.value\n else:\n if self.mapping:\n return self.mapping.get_value()\n if self.sum_mapping:\n ids.append(self.id)\n return reduce(add, [x.__get_value(ids) for x in self.sum_mapping])\n\n else:\n return self.value\n\n def get_value(self):\n if self.mapping:\n return self.mapping.get_value()\n if self.sum_mapping:\n return reduce(add, [x.__get_value([self.id]) for x in self.sum_mapping])\n\n else:\n return self.value\n\n\nclass VariablePath:\n\n def __init__(self, tag, id):\n\n self.path = {id: tag}\n self.used_id_pairs = []\n\n def __iter__(self):\n return iter(self.path.values())\n\n def extend_path(self, current_id, new_id, new_tag):\n if not (current_id + new_id in self.used_id_pairs):\n if new_id in self.path:\n self.path[new_id].extend([new_tag + '.' + x for x in self.path[current_id]])\n else:\n self.path.update({new_id: [new_tag + '.' + x for x in self.path[current_id]]})\n self.used_id_pairs.append(current_id + new_id)\n\n\nclass Variable(MappedValue):\n\n def __init__(self, detailed_variable_description, base_variable=None):\n\n super().__init__(detailed_variable_description.id)\n self.detailed_description = detailed_variable_description\n self.namespace = detailed_variable_description.namespace\n self.tag = detailed_variable_description.tag\n self.type = detailed_variable_description.type\n self.path = VariablePath([detailed_variable_description.tag], self.id)\n self.alias = None\n if base_variable:\n\n self.value = base_variable.value\n else:\n self.value = detailed_variable_description.initial_value\n self.item = detailed_variable_description.item\n self.metadata = detailed_variable_description.metadata\n self.mapping = detailed_variable_description.mapping\n self.update_counter = detailed_variable_description.update_counter\n self.allow_update = detailed_variable_description.allow_update\n self.associated_scope = []\n self.idx_in_scope = []\n\n def update_value(self, value):\n self.value = value\n\n @staticmethod\n def create(namespace, v_id, tag,\n v_type, value, item, metadata,\n mapping, update_counter, allow_update):\n return Variable(DetailedVariableDescription(tag=tag,\n id=v_id,\n type=v_type,\n initial_value=value,\n namespace=namespace,\n item=item,\n metadata=metadata,\n mapping=mapping,\n update_counter=update_counter,\n allow_update=allow_update))\n\n # def __setattr__(self, key, value):\n # if key == 'value' and 'update_counter' in self.__dict__:\n # if self.allow_update:\n # self.update_counter += 1\n # else:\n # if self.type == VariableType.CONSTANT:\n # raise ValueError(' It is not possible to reassign constant variable {0}'\n # .format(self.tag))\n # else:\n #\n # raise ValueError('It is not possible to reassign variable {0}'\n # ' in differential equation'.format(self.tag))\n #\n # object.__setattr__(self, key, value)\n\n\nclass _VariableFactory:\n\n @staticmethod\n def _create_from_variable_desc(namespace, item, var_desc):\n return Variable.create(namespace=namespace,\n v_id=\"{0}_{1}_{2}_{3}\".format(item.tag, namespace.tag, var_desc.tag, uuid.uuid4()),\n tag=var_desc.tag,\n v_type=var_desc.type,\n value=var_desc.initial_value,\n item=item,\n metadata={},\n mapping=None,\n update_counter=0,\n allow_update=(var_desc.type != VariableType.CONSTANT)\n )\n\n @staticmethod\n def _create_from_variable_desc_unbound(initial_value, variable_description):\n v1 = Variable.create(namespace=None,\n v_id=\"{0}_{1}\".format(variable_description.tag, uuid.uuid4()),\n tag=variable_description.tag,\n v_type=variable_description.type,\n value=initial_value,\n item=None,\n metadata={},\n mapping=None,\n update_counter=0,\n allow_update=(variable_description.type != VariableType.CONSTANT))\n\n return v1\n","sub_path":"numerous/engine/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":7049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"641994260","text":"from decimal import Decimal\n\nfrom rest_framework import status, test\n\nfrom django.urls import reverse\n\nfrom ..users import models as user_models\n\n\nclass TestUser2UserTransferEndpoint(test.APITestCase):\n \"\"\"\n Testing an endpoint for transferring of funds between users.\n \"\"\"\n\n expected_fields = {\n 'amount', 'transaction_id', 'created_at',\n }\n error_expected_fields = {\n 'code', 'message',\n }\n\n def setUp(self):\n super().setUp()\n self.url = reverse('user2user-transfer')\n\n self.UncleBob = user_models.User.create_new_user(\n email='uncle-bob@gmail.com',\n first_name='Robert',\n last_name='Cecil',\n )\n self.MartinFowler = user_models.User.create_new_user(\n email='f.martin@yandex.com',\n first_name='Martin',\n last_name='Fowler',\n )\n\n def test_u2u_transfer__successful_outcome(self):\n\n self.UncleBob.wallet.increase_balance_on(Decimal('1000'))\n\n data = {\n 'debit_user': self.MartinFowler.pk,\n 'amount': '500.50',\n }\n\n self.client.force_login(self.UncleBob)\n\n resp = self.client.post(self.url, data)\n self.assertEqual(\n resp.status_code, status.HTTP_201_CREATED, resp.content,\n )\n self.assertSetEqual(set(resp.data), self.expected_fields)\n\n # Checks in DB:\n self.UncleBob.wallet.refresh_from_db()\n self.assertEqual(self.UncleBob.wallet.balance, Decimal('499.50'))\n\n self.MartinFowler.wallet.refresh_from_db()\n self.assertEqual(self.MartinFowler.wallet.balance, Decimal('500.50'))\n\n def test_u2u_transfer__failed_cuz_not_enough_funds(self):\n self.UncleBob.wallet.increase_balance_on(Decimal('1000'))\n\n data = {\n 'debit_user': self.MartinFowler.pk,\n 'amount': '1000.01',\n }\n\n self.client.force_login(self.UncleBob)\n\n resp = self.client.post(self.url, data)\n self.assertEqual(\n resp.status_code, status.HTTP_400_BAD_REQUEST, resp.content,\n )\n data = resp.json()\n self.assertSetEqual(set(data), self.error_expected_fields)\n self.assertEqual(data['code'], 'invalid')\n self.assertEqual(data['message'], 'Insufficient funds')\n\n\nclass TestReplenishmentFundsEndpoint(test.APITestCase):\n \"\"\"\n Testing an endpoint for replenishment of funds to the account of the user.\n \"\"\"\n\n expected_fields = {\n 'amount', 'transaction_id', 'created_at',\n }\n error_expected_fields = {\n 'code', 'message',\n }\n\n def setUp(self):\n super().setUp()\n self.url = reverse('replenishment-founds')\n\n self.BertrandMeyer = user_models.User.create_new_user(\n email='bertrand@gmail.com',\n first_name='Bertrand',\n last_name='Meyer',\n )\n\n def test__successful_outcome(self):\n\n self.BertrandMeyer.wallet.increase_balance_on(Decimal('1'))\n\n data = {\n 'amount': '500',\n }\n\n self.client.force_login(self.BertrandMeyer)\n\n resp = self.client.post(self.url, data)\n self.assertEqual(\n resp.status_code, status.HTTP_201_CREATED, resp.content,\n )\n self.assertSetEqual(set(resp.data), self.expected_fields)\n\n # Checks in DB:\n self.BertrandMeyer.wallet.refresh_from_db()\n self.assertEqual(self.BertrandMeyer.wallet.balance, Decimal('501'))\n\n\nclass TestWithdrawingFoundsEndpoint(test.APITestCase):\n \"\"\"\n Testing an endpoint for withdrawing funds from the user account.\n \"\"\"\n\n expected_fields = {\n 'amount', 'transaction_id', 'created_at',\n }\n error_expected_fields = {\n 'code', 'message',\n }\n\n def setUp(self):\n super().setUp()\n self.url = reverse('withdrawing-founds')\n\n self.EricEvans = user_models.User.create_new_user(\n email='ee@gmail.com',\n first_name='Eric',\n last_name='Evans',\n )\n\n def test__successful_outcome(self):\n\n self.EricEvans.wallet.increase_balance_on(Decimal('1000'))\n\n data = {\n 'amount': '500.90',\n }\n\n self.client.force_login(self.EricEvans)\n\n resp = self.client.post(self.url, data)\n self.assertEqual(\n resp.status_code, status.HTTP_201_CREATED, resp.content,\n )\n self.assertSetEqual(set(resp.data), self.expected_fields)\n\n # Checks in DB:\n self.EricEvans.wallet.refresh_from_db()\n self.assertEqual(self.EricEvans.wallet.balance, Decimal('499.10'))\n\n def test_u2u_transfer__failed_cuz_not_enough_funds(self):\n self.EricEvans.wallet.increase_balance_on(Decimal('10'))\n\n data = {\n 'amount': '15',\n }\n\n self.client.force_login(self.EricEvans)\n\n resp = self.client.post(self.url, data)\n self.assertEqual(\n resp.status_code, status.HTTP_400_BAD_REQUEST, resp.content,\n )\n data = resp.json()\n self.assertSetEqual(set(data), self.error_expected_fields)\n self.assertEqual(data['code'], 'invalid')\n self.assertEqual(data['message'], 'Insufficient funds')\n","sub_path":"apps/transfers/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"531976541","text":"\"\"\"Functions for computing field and plasma quantities from an equilibrium.\n\nAll compute functions take the following arguments:\n\nParameters\n----------\nparams : dict of ndarray\n Parameters from the equilibrium, such as R_lmn, Z_lmn, i_l, p_l, etc\ntransforms : dict of Transform\n Transforms for R, Z, lambda, etc\nprofiles : dict of Profile\n Profile objects for pressure, iota, current, etc\ndata : dict of ndarray\n Data computed so far, generally output from other compute functions\nkwargs : dict\n Other arguments needed by some functions, such as helicity\n\nReturns\n-------\ndata : dict of ndarray\n Dictionary of ndarray, shape(num_nodes,) of computed quantities.\n Keys are of the form 'X_y' meaning the derivative of X wrt y.\n\n\"\"\"\n\n# just need to import all the submodules here to register everything in the\n# data_index\n\nfrom . import (\n _basis_vectors,\n _bootstrap,\n _core,\n _equil,\n _field,\n _geometry,\n _metric,\n _profiles,\n _qs,\n _stability,\n)\nfrom .data_index import data_index\nfrom .utils import (\n arg_order,\n compute,\n get_data_deps,\n get_derivs,\n get_params,\n get_profiles,\n get_transforms,\n profile_names,\n)\n\n\n# rather than having to recursively compute the full dependencies every time we\n# compute something, its easier to just do it once for all quantities when we first\n# import the compute module.\ndef _build_data_index():\n for key in data_index.keys():\n full = {}\n full[\"data\"] = get_data_deps(key)\n full[\"transforms\"] = get_derivs(key)\n full[\"params\"] = get_params(key)\n full[\"profiles\"] = get_profiles(key)\n data_index[key][\"full_dependencies\"] = full\n\n\n_build_data_index()\n","sub_path":"desc/compute/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"646472231","text":"\nimport sys\nimport cv2\nimport numpy as np\n\nsys.path.append('/usr/local/python')\n\nfrom openpose import pyopenpose as op\n\ndef scale_transform(coords):\n \"\"\"\n Parameters:\n coords (25x3 ndarray): array of (x,y,c) coordinates\n\n Returns:\n ndarray: coords scaled to 1x1 with center at (0,0)\n ndarray: confidence scores of each joint\n \"\"\"\n coords, scores = coords[:, :, :-1], coords[:, :, -1]\n diff = coords.max(axis=1) - coords.min(axis=1)\n diff_max = np.max(diff, axis=0)\n mean = coords.mean(axis=1).reshape(\n coords.shape[0],\n 1,\n coords.shape[-1]\n )\n out = (coords - mean) / diff_max\n\n return out, scores\n\n \ndef video_cv(video):\n \"\"\"Converts video into a BGR format for display\n\n This is abstracted out to allow for experimentation\n\n Args:\n video: A numpy array with 1 byte per pixel, 3 channels RGB\n\n Returns:\n A numpy array with with 1 byte per pixel, 3 channels BGR\n \"\"\"\n return video[:, :, :: -1] # RGB -> BGR\n# return video[:,:,:]\n\ndef make_vector(poseKeypoints):\n \"\"\"\n Parameters:\n poseKeypoints (ndarray): Single person output from OpenPose\n\n Returns:\n ndarray: scaled, transformed, normalized row vector\n \"\"\"\n \n N, D, C = poseKeypoints.shape\n coords, pose_scores = scale_transform(poseKeypoints)\n pose_scores = pose_scores.reshape((N, D, 1))\n coords_vec = np.concatenate([coords, pose_scores], axis=2)\n coords_vec /= np.linalg.norm(coords_vec, axis=2)[:, :, np.newaxis]\n\n return coords_vec\n\n\ndef get_ordinal_score(score):\n \"\"\"\n Parameters:\n score (float): similarity score between two poses\n between 0 and 1\n\n Returns:\n string: string text of the results\n float: transparency value\n tuple: color of overlay\n \"\"\"\n alpha = 0.2 #0.2\n overlay_color = (0, 0, 250)\n print(\"score\",score)\n if score > 0.712: #0.712\n out = \"Perfect!\"\n overlay_color = (0, 250, 0)\n # elif score > 0.500: #0.412\n # out = \"Almost there!\"\n# overlay_color = (250, 145, 0)\n elif score > 0.412: #0.298\n out = \"Nice try!\"\n overlay_color = (250, 145, 0)\n else:\n out = \"Try harder!!\"\n\n return out, alpha, overlay_color\n\ndef crop_image(full_image, w, h):\n\n #half_w = w/2\n #half_h = h/2\n #cropped_w_min = int(half_w - half_h - 150)\n #cropped_w_max = int(half_w + half_h + 150)\n #full_image = full_image[:h,cropped_w_min:cropped_w_max]\n #print(\"before resize\", full_image.shape)\n full_image = cv2.resize(full_image,\n (w, h))\n # print(\"after resize\", full_image.shape)\n #w_min = w // 2 - (w // 4)\n #w_max = w // 2 + (w // 4)\n #out = full_image[:h, w_min:w_max]\n return full_image\n\n #convert 1920 x 1080\ndef final_transform(image, w, h):\n\n half_w = w/2\n half_h = h/2\n cropped_w_min = int(half_w - half_h)\n cropped_w_max = int(half_w + half_h)\n image = image[:h,cropped_w_min:cropped_w_max]\n# print(\"before resize\", image.shape)\n final = cv2.resize(image,\n (h, w))\n # print(\"after resize\", image.shape)\n #w_min = w // 2 - (w // 4)\n #w_max = w // 2 + (w // 4)\n #out = full_image[:h, w_min:w_max]\n return final\n\n #resize 480 x 360 from xbox 360 \ndef transform_image(img,w,h):\n transformed_image = cv2.flip(\n cv2.resize(\n img,\n (w, h)\n ), 1)\n return transformed_image\n\n\ndef get_webcam(w, h):\n stream = cv2.VideoCapture(0)\n if (stream.isOpened() is False):\n print(\"Error opening video stream or file\")\n raise SystemExit(1)\n stream.set(3, w)\n stream.set(4, h)\n return stream\n\n\ndef get_image(stream, w, h):\n ret, img_original = stream.read()\n\n # Reset video if reached end\n if not img_original.any():\n stream.set(cv2.CAP_PROP_POS_FRAMES, 0)\n ret, img_original = stream.read()\n\n img = cv2.flip(\n crop_image(\n img_original,\n w, h\n ), 1)\n# img = crop_image(img_original,w,h)\n\n return img\n\n # labeller of img \ndef label_img(opWrapper, img):\n datum = op.Datum()\n datum.cvInputData = img\n opWrapper.waitAndEmplace([datum])\n opWrapper.waitAndPop([datum])\n return datum\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"487043620","text":"\"\"\"Build images only when paths specified are changed\"\"\"\n\nimport json\nimport re\nimport subprocess\n\nwith open(\"images.json\") as f:\n contents = json.loads(f.read())\n\n\ndef grep(string, search):\n return bool(re.search(search, string))\n\n\ndef is_changed(files):\n return grep(\n subprocess.run(\n \"git diff $COMMIT_RANGE --name-status\",\n shell=True,\n stdout=subprocess.PIPE,\n universal_newlines=True,\n ).stdout,\n f\"({'|'.join(files)})\",\n )\n\n\nfor image, settings in contents.items():\n if is_changed(settings[\"files\"]):\n subprocess.run(f\"./build.sh {image} {settings['dockerfile']}\", shell=True, check=True)\n","sub_path":".circleci/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"265194893","text":"# from aylienapiclient import textapi\n\n# client = textapi.Client(\"9285c70a\", \"b584db7607f9ce7421e9aab4a95f394f\")\n# sentiment = client.Sentiment({'text': 'John is a very good football player!'})\n# print(sentiment)\n\nimport requests\nimport json\n\ntest_phrases = [\"I am not happy\", \"I am very happy\", \"I love chocolate\", \"I hate chocolate\"]\nresults = []\nf = open(\"result.txt\", \"w\")\nconcat_line = \"\"\ntestsite_array = []\nwith open('tweets', encoding = \"utf8\") as my_file:\n testsite_array = my_file.readlines()\n\n\nfor line in testsite_array:\n\tconcat_line = concat_line + line\n\nfor phrase in testsite_array:\n response = requests.post(\"https://text-sentiment.p.rapidapi.com/analyze\",\n headers={\n \t\"X-RapidAPI-Key\": \"6bde0e5f4dmsh90a1686a25bb696p1f1051jsnb55aa01cecf8\",\n \t\"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n params={\n \t\"text\": phrase\n })\n results.append(json.loads(response.text))\n print(response.text)\n # f.write(response.text)\n\nno_pos = 0\nno_neg = 0\nno_neutral = 0\n\nfor result in results:\n\t# print(result[\"pos_percent\"])\n\tif result[\"pos_percent\"]> result[\"neg_percent\"]:\n\t\tno_pos+=1\n\telif result[\"pos_percent\"]< result[\"neg_percent\"]:\n\t\tno_neg+=1\n\telse:\n\t\tno_neutral+=1\n\nr = requests.post(\n \"https://api.deepai.org/api/summarization\",\n data={\n 'text': concat_line,\n },\n headers={'api-key': '66e9a48a-32d6-4863-acdb-037cd1b67efc'}\n)\nprint(r.json())\noutput_summary = r.json()\n\ntotal = no_neutral + no_neg + no_pos\n\nprint(\"Percent positive: \", no_pos/total * 100)\nprint(\"Percent negative: \", no_neg/total * 100)\nprint(\"Percent neutral: \", no_neutral/total * 100)\n\nf.write(\"Percent positive: \"+ str(no_pos/total * 100) + \"\\n\")\nf.write(\"Percent negative: \"+ str(no_neg/total * 100)+ \"\\n\")\nf.write(\"Percent neutral: \"+ str(no_neutral/total * 100)+ \"\\n\")\nf.write(\"Summary: \"+ output_summary[\"output\"])\n\n\n\n","sub_path":"out/production/HackCU/sample/sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"92156032","text":"def coords(m1,m2): #offset1,offset2,dist1,dist2,rot1,rot2):\n x1 = arena_markers[m1.info.offset][0]\n y1 = arena_markers[m1.info.offset][1]\n x2 = arena_markers[m2.info.offset][0]\n y2 = arena_markers[m2.info.offset][1]\n dx = abs(x1 - x2)\n dy = abs(y1 - y2)\n dist1 = m1.dist\n dist2 = m2.dist\n dist3 = sqrt((dx^2) + (dy^2))\n h = ((dist3^2) + (dist1^2) - (dist2^2))/(2 * dist3)\n Rx1 = x1 + ((dx * h)/dist3) - (dy/dist3) - sqrt((dist1^2) - (h^2))\n Ry1 = x2 + ((dy * h)/dist3) + (dx/dist3) - sqrt((dist1^2) - (h^2))\n Rx2 = x1 + ((dx * h)/dist3) + (dy/dist3) - sqrt((dist1^2) - (h^2))\n Ry2 = x2 + ((dy * h)/dist3) - (dx/dist3) - sqrt((dist1^2) - (h^2))\n if 0 <= Rx1 <= 800 and 0 <= Ry1 <= 800:\n R = (Rx1, Ry1)\n elif 0 <= Rx2 <= 800 and 0 <= Ry2 <= 800:\n R = (Rx2, Ry2)\n else:\n raise MathError('OutOfBoundPoints')\n","sub_path":"navigation2.py","file_name":"navigation2.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"353372833","text":"import copy\nfrom registry import user as mr, clstypes \nfrom pysal.weights import W\ntry:\n import patsy as p\nexcept:\n p = None\nfrom numpy import array, ndarray, asarray\nfrom pysal.common import iteritems as diter\nimport inspect\n\n#would like to just wrap this in the opt decorator...\ndef pandashandler(formula_like, data):\n \"\"\"\n process a pysal model signature and convert an equation/formula pair into a\n pysal-specific object\n \"\"\"\n if '||' in formula_like:\n mu, inst = formula_like.split('||')\n y, X = p.dmatrices(mu + '-1' , data=data)\n yend, q = p.dmatrices(inst + '-1', data=data)\n rargs = [y,X,yend,q]\n rargs = [asarray(i) for i in rargs]\n name_y, name_x = mu.strip(' ').split('~')\n name_x = name_x.split('+')\n name_yend, name_q = inst.strip(' ').split('~')\n name_yend = [name_yend]\n name_q = name_q.split('+')\n names = {\"name_y\":name_y,\n \"name_x\":name_x, \n \"name_yend\":name_yend,\n \"name_q\":name_q}\n else:\n y, X = p.dmatrices(formula_like + '-1', data=data)\n rargs = [asarray(y), asarray(X)]\n name_y, name_x = formula_like.strip(' ').split('~')\n name_x = name_x.split('+')\n names = {\"name_y\":name_y,\n \"name_x\":name_x}\n\n return rargs, names\n\n#def model(eqn, *args, data=df, **kwargs)\nclass Model(object):\n \"\"\"\n The model manager\n \n arguments that sit above the pysal model API:\n\n mtype : string mapping to the function called from spreg\n fit : Bool denoting whether to actually apply the mtype to the data provided\n immediately.\n\n an example call would look like:\n\n >>> Model(y,X,W, mtype='ML_Lag')\n >>> Model(y,X,W, mytpe='OLS_Regimes')\n \"\"\"\n def __init__(self, *args, **kwargs):\n self._outers = {}\n mtype = kwargs.pop('mtype', 'OLS')\n if mtype.startswith('Base'):\n raise Exception('Only Userclasses can be fit using the handler')\n mtype = mtype\n mfunc = mr.__dict__[mtype]\n fit = kwargs.pop('fit', True)\n ins = inspect.getargspec(mfunc.__init__)\n req = len(ins.args) - (len(ins.defaults)+1 )\n\n if isinstance(args[0], str):\n if len(args) > 1:\n raise TypeError('When a formula is used as the first argument,'\n ' all other arguments must be named. Consult {}'\n ' for argument names'.format(self._mfunc.__name__))\n formula = args[0]\n data = kwargs.pop('data')\n matrices, names = pandashandler(formula, data)\n kwargs.update(names)\n elif 'formula' in kwargs.keys() and 'data' in kwargs.keys():\n formula = kwargs.pop('formula')\n data = kwargs.pop('data')\n matrices, names = pandashandler(formula, data)\n kwargs.update(names)\n else:\n matrices = list(args[0:req])\n\n if fit:\n self._called = mfunc(*matrices, **kwargs)\n self._fit = True\n else:\n self._outers['mtype'] = mtype\n self._outers['mfunc'] = mfunc\n self._fit = False\n \n @property\n def __dict__(self):\n inners = self._called.__dict__\n obligations = [x for x in dir(self._mfunc) if not x.startswith('_')]\n obligations = {k:self._called.__getattribute__(k) for k in obligations}\n outers = self._outers\n alldict = dict()\n alldict.update(inners)\n alldict.update(obligations)\n alldict.update(outers)\n return alldict\n \n @__dict__.setter\n def __dict__(self, key, val):\n self._outers[key] = val\n\n @property\n def _mfunc(self):\n return type(self._called)\n \n @property\n def _mtype(self):\n return type(self._called).__name__\n\n def __getattr__(self, val):\n return self._called.__getattribute__(val)\n\nif __name__ == '__main__':\n import pysal as ps\n\n dbf = ps.open(ps.examples.get_path('columbus.dbf'))\n y, X = dbf.by_col_array(['HOVAL']), dbf.by_col_array(['INC', 'CRIME'])\n Wcol = ps.open(ps.examples.get_path('columbus.gal')).read()\n mod1 = mr.OLS(y,X)\n hmod1 = Model(y,X)\n\n mod2 = mr.OLS(y,X,w=Wcol, spat_diag=True, moran=True)\n hmod2 = Model(y,X,w=Wcol, spat_diag=True, moran=True)\n\n mod3 = mr.ML_Lag(y,X,Wcol)\n hmod3 = Model(y,X,Wcol, mtype='ML_Lag')\n\n mod4 = mr.ML_Error(y,X,Wcol)\n hmod4 = Model(y,X,w=Wcol,mtype='ML_Error')\n\n #real power comes from this, though\n# import geopandas as gpd\n# \n# df = gpd.read_file(ps.examples.get_path('columbus.dbf'))\n#\n# hmod1_pd = Model('HOVAL ~ INC + CRIME', data=data)\n# mod5 = sr.TSLS('HOVAL ~ INC + CRIME')\n","sub_path":"pysal/contrib/handler/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"5479490","text":"#! python3\n# -*- coding: utf-8 -*-\n\"\"\"\n一个列表中有许多个字符串,写一个function找出这些字符串中最长的共同字首\n['abcd', 'abccc', 'abdec'] --> 共同字首为'ab'\n重点考察for else的作用\n\"\"\"\n\n\n# def longestCommonPrefix(strs): # 无法解决['aa', 'aab'], 错误方案\n# length = len(strs)\n# if length == 0:\n# return \"empty\"\n# elif length == 1:\n# return strs[0]\n# elif length == 2:\n# mutual_list = [s for s in strs[0] if s in strs[1]]\n# print(mutual_list)\n# if len(mutual_list) == 0:\n# first_second_mutual = \"empty\"\n# else:\n# first_second_mutual = ''.join([s for s in strs[0] if s in strs[1]])\n# return first_second_mutual\n# else:\n# first_second_mutual = ''.join([s for s in strs[0] if s in strs[1]])\n# first_second_mutual_length = len(first_second_mutual)\n# end = 1\n# parts = []\n# while end < first_second_mutual_length:\n# part = first_second_mutual[0:end]\n# parts.append(part)\n# end += 1\n# parts.append(first_second_mutual) # 得到列表前两项的公有部分所有字符组合['a', 'ab', 'abc']\n# reversed_parts = parts[::-1]\n# for part in reversed_parts:\n# for i in range(2, length):\n# if part not in strs[i]:\n# break\n# else:\n# return part\n#\n#\n# def common_start(s1, s2):\n# def _iter():\n# for a, b in zip(s1, s2):\n# if a == b:\n# yield a\n# else:\n# return\n#\n# return ''.join(_iter())\n\"\"\"zip性质:等长时会一一对应形成tuple,不等长时会以较短的为基准,\n还有就是解包机制的运用\"\"\"\n\n\ndef longestCommonPrefix(strs):\n prefix = ''\n for z in zip(*strs):\n bag = set(z)\n if len(bag) == 1:\n prefix += bag.pop()\n else:\n break\n return prefix\n\n\nif __name__ == '__main__':\n \"\"\"测试集:\n []\n ['a']\n ['a', 'b']\n ['abcd', 'abccc', 'abdec']\n \"\"\"\n # res1 = longestCommonPrefix([])\n # res2 = longestCommonPrefix(['a'])\n # res3 = longestCommonPrefix(['a', 'b'])\n # res4 = longestCommonPrefix(['abcd', 'abccc', 'abdec'])\n # print(res1)\n # print(res2)\n # print(res3)\n # print(res4)\n\n # res = longestCommonPrefix([\"aa\", \"ab\"])\n # print(res)\n # for i in range(0, 3):\n # print(i)\n # if i == 1:\n # break\n # else:\n # print(\"hello, world!\")\n\n \"\"\"因为在for循环中执行了break,所以else语句下面的语句不会执行\"\"\"\n # s1 = \"aa\"\n # s2 = \"ab\"\n # str_length = [len(s1), len(s2)]\n # max_length = max(str_length)\n #\n\n # res1 = common_start('aa', 'aab')\n # print(res1)\n # print(list(zip('aa', 'aab')))\n\n strs1 = ['abc', 'bcd', 'defg']\n strs2 = ('abc', 'bcd')\n strs3 = {'a': 1, 'b': 2}\n print(*strs1[0])\n for z1 in zip(*strs1):\n print(z1)\n \"\"\"\n ('a', 'b', 'd')\n ('b', 'c', 'e')\n ('c', 'd', 'f')\n \"\"\"\n print('@@@')\n #\n # for z2 in zip(strs2):\n # print(z2)\n #\n # print('###')\n #\n # for z3 in zip(strs3):\n # print(z3)\n #\n # print('$$$')\n\n","sub_path":"leetcode/14-Longest-Common-Prefix.py","file_name":"14-Longest-Common-Prefix.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"61560755","text":"from flask import *\nfrom werkzeug import check_password_hash\n\nfrom sources.core import app, socketio\nfrom sources.twitter import *\nfrom sources.utils import *\n\n\n# Additional actions of a request\n@app.before_request\ndef before_request():\n \"\"\"\n The method called before each request to the server\n Check for a user session exist (straightforward auth system)\n \"\"\"\n g.user = None\n\n if 'nickname' in session:\n g.user = get_user(session['nickname'])\n\n update_user(session['nickname'], {\n \"$set\": {\n \"last_visit\": get_timestamp()\n }\n })\n\n\n# Authenticating and similar actions\n@app.route('/login/', methods=['GET', 'POST'])\ndef login_page():\n \"\"\"\n Render form to login a user\n \"\"\"\n # Redirect logged user to the dashboard page\n if g.user:\n return redirect('/')\n\n error = None\n\n # Validate data provided by the user\n if request.method == 'POST':\n user = get_user(request.form['nickname'])\n\n if user is None:\n error = 'Invalid username!'\n elif not check_password_hash(\n user['pw_hash'],\n request.form['password']\n ):\n error = 'Invalid password!'\n else:\n flash('You were logged in...')\n session['nickname'] = user['nickname']\n\n return redirect('/')\n\n return render_template('login.html', error=error)\n\n\n@app.route('/logout/')\ndef logout_page():\n \"\"\"\n Clear all information about the user session\n \"\"\"\n # Redirect a guest to the login page\n if not g.user and 'nickname' not in session:\n return redirect(url_for('login_page'))\n\n flash('You were logged out!')\n session.pop('nickname', None)\n\n return redirect(url_for('login_page'))\n\n\n# Pages\n@app.route('/')\ndef dashboard_page():\n \"\"\"\n Output statistic of the manager's sessions\n \"\"\"\n if not g.user:\n return redirect(url_for('login_page'))\n\n history = get_history_summary()\n latest = history[0] if history else None\n\n return render_template('page_dashboard.html', latest=latest, history=history)\n\n\n@app.route('/console/')\ndef console_page():\n \"\"\"\n Manage of a manager's session\n \"\"\"\n g.stream = dict()\n return render_template('page_console.html')\n\n\n@app.route('/messages/')\n@app.route('/messages/edit//', methods=['GET', 'POST'])\ndef messages_page(queue=None):\n \"\"\"\n Manage of messages that followers received\n \"\"\"\n if queue:\n queue = int(queue)\n error = None\n success = None\n\n if request.method == 'POST':\n if request.form['content'] is not '':\n update_message(queue, {'$set': {\n 'content': request.form['content'],\n 'delay_days': request.form['delay_days']\n }})\n\n success = 'The message was successful updated!'\n else:\n error = 'Message can\\'t be empty!'\n\n message = get_message(queue)\n return render_template('page_messages_edit.html', message=message, success=success, error=error)\n\n messages = get_messages()\n return render_template('page_messages.html', messages=messages)\n\n\n@app.route('/users/')\ndef users_page():\n \"\"\"\n Output list of all users that are registered\n \"\"\"\n users = get_users()\n return render_template('page_users.html', users=users)\n\n\n@app.route('/settings/')\ndef settings_page():\n return render_template('page_settings.html')\n\n\n# SocketIO events\nsocketio.on_event('get followers ids', get_followers_ids)\nsocketio.on_event('process user', process_user)\nsocketio.on_event('stop manager', stop_manager)\n\n# Necessary for correct work of the SocketIO\nif __name__ == '__main__':\n socketio.run(app)\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"470427458","text":"#!/usr/bin/python3\n\nfrom eval_time import eval_time\n\n# Given an array of integers, find the one that appears an odd number of times.\n# \n# There will always be only one integer that appears an odd number of times.\n# \n# Examples\n# [7] should return 7, because it occurs 1 time (which is odd).\n# [0] should return 0, because it occurs 1 time (which is odd).\n# [1,1,2] should return 2, because it occurs 1 time (which is odd).\n# [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd).\n# [1,2,2,3,3,3,4,3,3,3,2,2,1] shold return 4, because it appears 1 time (which is odd).\n\n\n#\n# 2 for loops\n# parent loop iterates over the remaining list\n# child loop finds and removes occurrences of the last element in sequence and increments the counter\n# or just appends the values to temp list so later we can evaluate list lenght\n# on next parent loop iteration temp list gets overwritten\n\nseq = [20,1,-1,2,-2,3,3,3,5,5,1,2,4,20,4,-1,-2]\n\n\ndef find_it(seq):\n # by task we have an non-empty array\n # we will iterate until we found a number occurring odd number of time\n # while elements in seq is still there\n tmp_seq = seq[:]\n while tmp_seq:\n # pop the last element in list and count it as 1st occurrence\n last, count = tmp_seq.pop(), 1\n \n # while the popped element is still in sequence acknowledge this by incrementing occurence counter \n # and remove its next occurence from the sequence (looking from left to right)\n while last in tmp_seq:\n count += 1\n tmp_seq.remove(last)\n \n # once all occurrences of the popped element were removed from the sequence,\n # return popped element if it appears odd number of times\n # or proceed with next iterations until the element that appears odd number of times is found.\n if count % 2 == 1:\n return last\n\n\n# best practices\ndef find_it_bp(seq):\n for i in seq:\n if seq.count(i) % 2 != 0:\n return i\n\neval_time(find_it(seq), 10 ** 6)\neval_time(find_it_bp(seq), 10 ** 6)\n\n","sub_path":"python/find_odd_times_int.py","file_name":"find_odd_times_int.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"421059023","text":"# -*- coding: utf-8 -*- #\n# Copyright 2020 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Test base for the backend services update subcommand.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.calliope import base as calliope_base\nfrom googlecloudsdk.core import resources\nfrom tests.lib.surface.compute import test_base\nfrom tests.lib.surface.compute.backend_services import test_resources\n\n\nclass UpdateTestBase(test_base.BaseTest):\n \"\"\"Test base for the backend services update subcommand.\"\"\"\n\n def SetUp(self):\n self.SelectApi(self.api_version)\n\n self._backend_services = test_resources.BACKEND_SERVICES_V1\n\n self._http_backend_services_with_legacy_health_check = (\n test_resources.HTTP_BACKEND_SERVICES_WITH_LEGACY_HEALTH_CHECK_V1)\n self._https_backend_services_with_legacy_health_check = (\n test_resources.HTTPS_BACKEND_SERVICES_WITH_LEGACY_HEALTH_CHECK_V1)\n\n self._http_backend_services_with_health_check = (\n test_resources.HTTP_BACKEND_SERVICES_WITH_HEALTH_CHECK_V1)\n self._https_backend_services_with_health_check = (\n test_resources.HTTPS_BACKEND_SERVICES_WITH_HEALTH_CHECK_V1)\n\n def RunUpdate(self, command, use_global=True):\n suffix = ' --global' if use_global else ''\n self.Run('compute backend-services update ' + command + suffix)\n\n\nclass BetaUpdateTestBase(test_base.BaseTest):\n \"\"\"Test base for the beta backend services update subcommand.\"\"\"\n\n def SetUp(self):\n self.SelectApi('beta')\n self.track = calliope_base.ReleaseTrack.BETA\n\n self._backend_services = test_resources.BACKEND_SERVICES_BETA\n self._http_backend_services_with_health_check = (\n test_resources.HTTP_BACKEND_SERVICES_WITH_HEALTH_CHECK_BETA)\n self._https_backend_services_with_health_check = (\n test_resources.HTTPS_BACKEND_SERVICES_WITH_HEALTH_CHECK_BETA)\n\n def RunUpdate(self, command, use_global=True):\n suffix = ' --global' if use_global else ''\n self.Run('compute backend-services update ' + command + suffix)\n\n\nclass AlphaUpdateTestBase(test_base.BaseTest):\n \"\"\"Test base for the alpha backend services update subcommand.\"\"\"\n\n def SetUp(self):\n self.SelectApi('alpha')\n self.track = calliope_base.ReleaseTrack.ALPHA\n self.resources = resources.REGISTRY.Clone()\n self.resources.RegisterApiByName('compute', 'alpha')\n\n self._backend_services = test_resources.BACKEND_SERVICES_ALPHA\n self._http_backend_services_with_health_check = (\n test_resources.HTTP_BACKEND_SERVICES_WITH_HEALTH_CHECK_ALPHA)\n self._https_backend_services_with_health_check = (\n test_resources.HTTPS_BACKEND_SERVICES_WITH_HEALTH_CHECK_ALPHA)\n self._tcp_backend_services_with_health_check = (\n test_resources.TCP_BACKEND_SERVICES_WITH_HEALTH_CHECK_ALPHA)\n self._ssl_backend_services_with_health_check = (\n test_resources.SSL_BACKEND_SERVICES_WITH_HEALTH_CHECK_ALPHA)\n\n def RunUpdate(self, command, use_global=True):\n suffix = ' --global' if use_global else ''\n self.Run('compute backend-services update ' + command + suffix)\n\n","sub_path":"google-cloud-sdk/lib/tests/lib/surface/compute/backend_services/update/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"527001968","text":"import base64\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom main import helpers, validators\n\n\nclass User(AbstractUser):\n username = models.CharField(\n max_length=150,\n unique=True,\n help_text=\"This will be your subdomain. Lowercase alphanumeric.\",\n validators=[validators.AlphanumericHyphenValidator()],\n error_messages={\"unique\": \"A user with that username already exists.\"},\n )\n about = models.TextField(blank=True, null=True)\n blog_title = models.CharField(max_length=500, blank=True, null=True)\n blog_byline = models.CharField(max_length=500, blank=True, null=True)\n footer_note = models.CharField(\n max_length=500,\n blank=True,\n null=True,\n default=None,\n help_text=\"Supports markdown\",\n )\n\n # custom domain related\n custom_domain = models.CharField(\n max_length=150,\n blank=True,\n null=True,\n help_text=\"DNS: CNAME your .mataroa.blog subdomain or A with IP 95.217.176.64\",\n validators=[validators.validate_domain_name],\n )\n custom_domain_cert = models.TextField(blank=True, null=True)\n custom_domain_key = models.TextField(blank=True, null=True)\n\n # webring related\n webring_name = models.CharField(max_length=200, blank=True, null=True)\n webring_url = models.URLField(\n blank=True,\n null=True,\n verbose_name=\"Webring info URL\",\n help_text=\"Informational URL.\",\n )\n webring_prev_url = models.URLField(\n blank=True,\n null=True,\n verbose_name=\"Webring previous URL\",\n help_text=\"URL for your webring's previous website.\",\n )\n webring_next_url = models.URLField(\n blank=True,\n null=True,\n verbose_name=\"Webring next URL\",\n help_text=\"URL for your webring's next website.\",\n )\n\n class Meta:\n ordering = [\"-id\"]\n\n @property\n def footer_note_as_html(self):\n return helpers.md_to_html(self.footer_note)\n\n def get_absolute_url(self):\n return reverse(\"user_detail\", kwargs={\"pk\": self.pk})\n\n def __str__(self):\n return self.username\n\n\nclass Post(models.Model):\n title = models.CharField(max_length=300)\n slug = models.CharField(max_length=300)\n body = models.TextField(blank=True, null=True)\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n published_at = models.DateField(\n default=timezone.now,\n blank=True,\n null=True,\n help_text=\"Leave blank to keep as draft/unpublished. Use a future date for auto-posting.\",\n )\n\n class Meta:\n ordering = [\"-published_at\", \"-created_at\"]\n unique_together = [[\"slug\", \"owner\"]]\n\n @property\n def as_html(self):\n return helpers.md_to_html(self.body)\n\n @property\n def is_published(self):\n if not self.published_at:\n # draft case\n return False\n if self.published_at > timezone.now().date():\n # future publishing date case\n return False\n return True\n\n def get_absolute_url(self):\n path = reverse(\"post_detail\", kwargs={\"slug\": self.slug})\n return f\"//{self.owner.username}.{settings.CANONICAL_HOST}{path}\"\n\n def __str__(self):\n return self.title\n\n\nclass Image(models.Model):\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n name = models.CharField(max_length=300) # original filename\n slug = models.CharField(max_length=300, unique=True)\n data = models.BinaryField()\n extension = models.CharField(max_length=10)\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n ordering = [\"-uploaded_at\"]\n\n @property\n def filename(self):\n return self.slug + \".\" + self.extension\n\n @property\n def data_as_base64(self):\n return base64.b64encode(self.data).decode(\"utf-8\")\n\n @property\n def raw_url_absolute(self):\n path = reverse(\n \"image_raw\", kwargs={\"slug\": self.slug, \"extension\": self.extension}\n )\n return f\"//{settings.CANONICAL_HOST}{path}\"\n\n def get_absolute_url(self):\n path = reverse(\"image_detail\", kwargs={\"slug\": self.slug})\n return f\"//{settings.CANONICAL_HOST}{path}\"\n\n def __str__(self):\n return self.name\n\n\nclass Page(models.Model):\n title = models.CharField(max_length=300)\n slug = models.CharField(\n max_length=300,\n validators=[validators.AlphanumericHyphenValidator()],\n help_text=\"Lowercase letters, numbers, and - (hyphen) allowed.\",\n )\n body = models.TextField(blank=True, null=True)\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n is_hidden = models.BooleanField(\n default=False,\n help_text=\"If checked, page link will not appear on index footer.\",\n )\n\n class Meta:\n ordering = [\"slug\"]\n unique_together = [[\"slug\", \"owner\"]]\n\n @property\n def as_html(self):\n return helpers.md_to_html(self.body)\n\n def get_absolute_url(self):\n path = reverse(\"page_detail\", kwargs={\"slug\": self.slug})\n return f\"//{self.owner.username}.{settings.CANONICAL_HOST}{path}\"\n\n def __str__(self):\n return self.title\n","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"580931094","text":"\n''' \ntcheck \n \nDescription: A selection of functions for aiding with error checking \n by searching for TypeError, each function returns either \n a None type or Bool type. \n\nfunction list:\n\n numeric_test(obj)\n array_test(obj)\n flat_array_test(obj)\n type_test(var,sort) \n type_test_print(var, sort, var_name=None, func_name='', print_bool=True)\n\n'''\n\n### Tester functions: test input against a given object type or object format\n \ndef numeric_test(obj):\n '''\n Description: A 'numeric' type is defined as an object which evaluates to a python number\n\n obj: input, any python object\n '''\n int_inst = isinstance(obj, int)\n float_inst = isinstance(obj, float) \n long_inst = isinstance(obj, long) \n \n numeric_bool = int_inst or float_inst or long_inst \n return numeric_bool \n\n \ndef array_test(obj):\n '''\n Description: An array is defined as a iterable and numerically indexed object: lists and tuples\n\n obj: input, any python object\n '''\n list_inst = isinstance(obj, list)\n tuple_inst = isinstance(obj, tuple) \n array_bool = list_inst or tuple_inst \n return array_bool \n\n\ndef flat_array_test(obj): \n '''\n Description: Tests an array for flatness (each object within the array has a dimensionality of zero)\n\n obj: input, any python object \n ''' \n if(array_test(obj)):\n for i in obj:\n try:\n n = len(i)\n if(isinstance(i,str)):\n continue\n else:\n return False\n except:\n continue\n return True\n else:\n return False\n\n# Printing Functions: Help with printing \n \ndef __fail_print__(success, var_name=None, correct_type=\"valid type\", func_name='', print_bool = True):\n '''\n Dunder printing function for internal error correction and checking\n '''\n if(print_bool):\n if(isinstance(correct_type,str)):\n correct_type = correct_type \n else:\n try:\n correct_type = str(correct_type)\n except:\n print(\"[__fail_print__] Error: 'correct_type' must be a string or type object\")\n return False\n if(not success and var_name != None):\n if(func_name == ''): \n print(\"TypeError: the variable '\"+var_name+\"' is not a \"+correct_type)\n else:\n print(\"[\"+func_name+\"]\"+\" TypeError: the variable '\"+var_name+\"' is not a \"+correct_type)\n return False\n if(not success and var_name == None):\n if(func_name == ''):\n print(\"TypeError: input variable is not a \"+correct_type)\n else:\n print(\"[\"+func_name+\"]\"+\" TypeError: input variable is not a \"+correct_type)\n return False \n return True \n else:\n return None \n\n### Main functions \n\ndef type_test(var, sort):\n '''\n Description: This function returns a boolean, 'var' is tested for equivalence to \n 'sort', 'sort' may a 'type' object. \n\n Inputs:\n \n var : input object \n sort : sort is either a type, class object or module object against which 'var' is tested\n \n '''\n \n if(sort == None):\n type_bool = (var == sort)\n elif(sort == 'num'):\n type_bool = numeric_test(var) \n elif(sort == 'arr'):\n type_bool = array_test(var)\n elif(isinstance(sort,type) or type(sort) == \"\" or type(sort) == \"\"): \n type_bool = isinstance(var, sort)\n else:\n type_bool = False \n return type_bool \n\n \ndef type_test_print(var, sort, var_name=None, func_name='', print_bool=True):\n '''\n Description: This function returns a boolean, 'var' is tested for equivalence to \n 'sort', 'sort' may a 'type', 'classobj' or 'module' object. The main \n difference between this function and 'type_test' is that this function \n is optimized for printing out error functions \n\n Inputs:\n \n 'var' : python object, input object \n 'sort' : sort is either a type, class object or module object against which 'var' is tested\n 'var_name' : string, The name of variable 'var', to be used when printing error messages.\n 'func_name' : string, The name of a function, to be used when printing error messages.\n 'print_bool' : boolean, printing option, useful when printing to the console would interfere with threading \n \n '''\n type_bool = type_test(var,sort)\n test = __fail_print__(type_bool, var_name, correct_type=sort, func_name=func_name, print_bool = print_bool)\n return test\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pmod/tcheck.py","file_name":"tcheck.py","file_ext":"py","file_size_in_byte":5016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"537096469","text":"from django.contrib import admin\n\n# Register your models here.\nfrom django.contrib import admin\nfrom feed.models import Badip, Baddomain\nfrom rss.models import Rssingest\nfrom django.http import HttpResponse\n\n\n\n\n\nclass BaddomainAdmin(admin.ModelAdmin):\n\tlist_display = ('domain', 'domain_source', 'domain_mapping')\n\nclass BadipAdmin(admin.ModelAdmin):\n\tlist_display = ('ip', 'ip_source', 'ip_mapping')\n\ndef export_csv(modeladmin, request, queryset):\n import csv\n from django.utils.encoding import smart_str\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=mymodel.csv'\n writer = csv.writer(response, csv.excel)\n response.write(u'\\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)\n writer.writerow([\n smart_str(u\"ID\"),\n smart_str(u\"Item ID\"),\n smart_str(u\"Content\"),\n smart_str(u\"Title\"),\n smart_str(u\"Date\"),\n smart_str(u\"URL\"),\n smart_str(u\"Status\"),\n smart_str(u\"Category ID\"),\n smart_str(u\"Fetch Date\"),\n ])\n for obj in queryset:\n writer.writerow([\n smart_str(obj.id),\n smart_str(obj.item_id),\n smart_str(obj.item_content),\n smart_str(obj.item_title),\n smart_str(obj.item_date),\n smart_str(obj.item_url),\n smart_str(obj.item_status),\n smart_str(obj.item_category_id),\n smart_str(obj.fetch_date),\n ])\n return response\nexport_csv.short_description = u\"Export CSV\"\n\n\nclass RssingestAdmin(admin.ModelAdmin):\n\tlist_display = ('id',\n 'item_id',\n 'feed_url',\n 'item_content',\n 'item_title',\n 'item_date',\n 'item_url',\n 'item_status',\n 'item_category_id',\n 'fetch_date')\n\tactions = [export_csv,]\n\n\nadmin.site.register(Baddomain, BaddomainAdmin)\nadmin.site.register(Badip, BadipAdmin)\nadmin.site.register(Rssingest, RssingestAdmin)","sub_path":"feed_project/feed/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"636198755","text":"import httplib\r\nimport time\r\n\r\n#Implemented sickTypeCounts per day 2:40\r\n\r\nstudents=set()\r\nsickPerDay=[]\r\nloginUser = None\r\n\r\nclass Student(object):\r\n def __init__(self,andrewID,location,sickness,when):\r\n self.loc = location\r\n self.sickness= sickness\r\n self.when = when\r\n self.andrewID = andrewID\r\n self.sickDays=[]\r\n \r\n def __repr__(self):\r\n return self.andrewID\r\n \r\n def __eq__(self, other):\r\n return isinstance(other,student)and self.andrewID==other.andrewID\r\n \r\n def getLoc(self):\r\n return self.loc\r\n \r\n def getWhen(self):\r\n return self.when\r\n \r\n def getAndrewID(self):\r\n return self.andrewID\r\n \r\n def getSickness(self):\r\n return self.sickness\r\n \r\n def getsickDays(self):\r\n return self.sickDays\r\n \r\n def setLoc(self, loc): self.loc = loc\r\n \r\n def setWhen(self, when) : self.when = when\r\n \r\n def setSickness(self, sickness): \r\n self.sickness = sickness\r\n if sickness != None:\r\n date = getDate()\r\n self.sickDays.add((date, date)) #adds a new sick date. \r\n \r\n def updateSickDays(self):\r\n if(len(sickDays)!=0 and self.sickness!=None):\r\n (x,y)=self.sickDays[-1]\r\n self.sickDays[-1]=(x,y+1)\r\n if(y-x>13):\r\n self.sickness=None\r\n\r\n#Compares which date is earlier.\r\n#If date1 is earlier than date2, it returns negative number.\r\n#If date1 is later than date2, it returns a positive number.\r\n#If date1 is equal to date2, it returns 0\r\ndef compareDate(date1, date2):\r\n (year1, month1, day1) = date1\r\n (year2, month2, day2) = date2\r\n yeardif = year1-year2\r\n monthdif = month1-month2\r\n daydif = day1-day2\r\n if yeardif != 0: return yeardif\r\n if monthdif != 0: return monthdif\r\n return daydif\r\n \r\n#basic log in process of student.\r\n#If a student exists in students set,\r\n#return True. Else return False\r\ndef login(andrewID):\r\n for stud in students:\r\n if(andrewID==stud.andrewID):\r\n global loginUser\r\n loginUser = stud\r\n return True\r\n return False\r\n\r\ndef registerNewUser(andrewID, location):\r\n if(validate(andrewID)):\r\n enterData(andrewID,location)\r\n return True\r\n return False\r\n\r\ndef enterData(andrewID,location):\r\n stud = Student(andrewID,location,None,None)\r\n students.add(stud)\r\n global loginUser\r\n loginUser = stud\r\n\r\ndef refreshDaily():\r\n sickcount=0\r\n for stud in students:\r\n if (stud.sickness!=None):\r\n self.updateSickDays()\r\n sickcount+=1\r\n sickPerDay.append((getDate(),sickcount))\r\n \r\ndef getDormCountDay(dorm):\r\n sickcount = 0\r\n for stud in students:\r\n if(stud.sickness!=None and stud.loc==dorm):\r\n sickcount+=1\r\n return (getDate(),sickcount)\r\n\r\ndef getSickTypeDay(sickness):\r\n sickcount = 0\r\n for stud in students:\r\n if(stud.sickness==sickness):\r\n sickcount+=1\r\n elif(sickness==\"Healthy\" and self.sickness==None):\r\n sickcount+=1\r\n return (getDate(),sickcount) \r\n \r\n#This goes on website side\r\nsickDorms=dict()\r\nsickDorms[\"Hill\"]=[]\r\nsickDorms[\"Donner\"]=[]\r\nsickDorms[\"Morewood\"]=[]\r\nsickDorms[\"Stever\"]=[]\r\nsickDorms[\"Mudge\"]=[]\r\nsickDorms[\"RezShir\"]=[]\r\nsickDorms[\"Other\"]=[]\r\n\r\nsickType=dict()\r\nsickType[\"Cold\"]=[]\r\nsickType[\"Fever\"]=[]\r\nsickType[\"Flu\"]=[]\r\nsickType[\"Other\"]=[]\r\nsickType[\"Healthy\"]=[]\r\n\r\ndef updateSickTypesDay():\r\n for d in sickType:\r\n sickType[d].append(getSickTypeDay(d))\r\n \r\ndef updateSickDormsDay():\r\n for d in sickDorms:\r\n sickDorms[d].append(getDormCountDay(d))\r\n \r\ndef getMostRecentStudent():\r\n result = None\r\n for stud in students:\r\n if result == None or compareDate(result.getWhen(),stud.getWhen())>0:\r\n result = stud\r\n students.remove(result)\r\n return result \r\n \r\ndef topFiveSick(dorm = None):\r\n result = []\r\n numStudents = 5\r\n for i in range(numStudents):\r\n result.append(getMostRecentStudent())\r\n students.add(set(result))\r\n return result\r\n\r\n\r\ndef getDate():\r\n now = time.strftime(\"%c\")\r\n month = int(now[0:2])\r\n day = int(now[3:5])\r\n return (month, day)\r\n \r\ndef validate(andrewId):\r\n conn = httplib.HTTPConnection(\"apis.scottylabs.org\")\r\n link = \"/directory/v1/andrewID/\" + andrewId\r\n conn.request(\"HEAD\", link)\r\n res = conn.getresponse()\r\n if res.reason == \"OK\": return True\r\n elif res.reason == \"Not Found\": return False\r\n","sub_path":"templates/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"71754986","text":"from django import forms\nfrom django.db.models import Q\n\nclass FilteredViewMixin():\n filter_form = None\n initial = None\n\n def __init__(self, *args, **kwargs):\n self.filter = None\n return super().__init__(*args, **kwargs)\n\n def get_request(self):\n return self.request\n\n def get_filter(self):\n if self.filter:\n return self.filter\n if self.filter_form:\n self.filter = self.filter_form(self.get_request().GET or self.get_initial())\n return self.filter\n return None\n\n def create_field_filter(self, field_name, form):\n field_options = form.filter_options.get(field_name, dict())\n lookups = field_options.get('lookup', [field_name])\n conditions = None\n field_data = form.data.get(field_name)\n if not field_data and not isinstance(form.fields[field_name], forms.BooleanField):\n return None\n for lookup in lookups:\n if callable(lookup):\n field_lookup = lookup(field_data)\n if field_lookup is None:\n continue\n new_condition = Q(**field_lookup)\n else:\n new_condition = Q(**{lookup:field_data})\n if conditions:\n conditions = conditions | new_condition\n else:\n conditions = new_condition\n return conditions\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['filter_form'] = self.get_filter()\n return context\n\n def and_filters(self, filters):\n result = None\n for (name, f) in filters:\n if f:\n if result:\n result = result & f\n else:\n result = f\n return result\n\n def get_takeover_filters(self, form_filter, filters):\n return self.and_filters(filter(lambda elt: elt[0] in form_filter.filter_takeover, filters.items()))\n\n def get_final_filters(self, form_filter, filters):\n final_filters = self.get_takeover_filters(form_filter, filters)\n if final_filters:\n return final_filters\n return self.and_filters(filters.items())\n\n def apply_filter(self, queryset):\n f = self.get_filter()\n filters = dict()\n for field in f.fields:\n if not field in f.excludes:\n filters[field] = self.create_field_filter(field, f)\n final_filters = self.get_final_filters(f, filters)\n if not final_filters:\n return queryset\n return queryset.filter(final_filters)\n \n def get_initial(self):\n return self.initial\n\nclass FilterForm(forms.Form):\n filter_options = dict()\n filter_takeover = []\n excludes = []\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for f in self.fields:\n self.fields[f].required = False\n","sub_path":"off/infrastructure/views/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"471001634","text":"import random\r\nimport math\r\na = []\r\nn = int(input(\"nhập n \"))\r\nfor i in range(n): #tạo list n phần tử\r\n a.append(random.random())\r\nm = math.inf\r\nfor i in range(n): #giá trị nhỏ nhất\r\n if a[i] < m:\r\n m = a[i]\r\nprint(\"giá trị nhỏ nhất trong \", a, \"là:\",m)","sub_path":"bai7.py","file_name":"bai7.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"437409447","text":"from __future__ import print_function\nfrom __future__ import division\nfrom itertools import izip, tee\nimport tensorflow as tf\n\nfrom .pair_trawler_model_base import ModelBase, GPUInferenceModel, L1s\nfrom .pair_trawler_tile_data import TrainTestTileData\n\n\ndef model_fn(features, labels, mode, params):\n\n size = params['size']\n char_weight = params['char_weight']\n X = features['X'] \n Y_ = labels \n\n with tf.variable_scope('train_harness'):\n global_step = tf.train.get_global_step()\n\n learning_rate = tf.train.exponential_decay(\n params['lr_max'], \n global_step, \n params['lr_decay_steps'], \n params['lr_decay'], \n staircase=True)\n\n def layer(l, w, d, name, nonlin=tf.nn.crelu, stride=1):\n\n with tf.variable_scope(name):\n\n return tf.layers.conv2d(l, d, w,\n use_bias = True,\n kernel_initializer='lecun_normal',\n bias_initializer='zeros',\n activation = nonlin,\n strides=(stride, stride))\n\n\n def pool(l, n, name=\"pool\"):\n with tf.variable_scope(name):\n return tf.concat([\n layer(l, 3, n, 'convpool', stride=2),\n tf.layers.max_pooling2d(l, 3, 2)\n ], axis=3)\n\n field_of_view = params['field_of_view']\n\n Y = X\n with tf.variable_scope('block1'): # 315\n Y = layer(Y, 7, 24, 'conv1')\n Y = layer(Y, 7, 24, 'conv2')\n Y = pool(Y, 48) # 311\n with tf.variable_scope('block2'): # 155\n Y = layer(Y, 7, 48, 'conv1')\n Y = layer(Y, 7, 48, 'conv2')\n Y = pool(Y, 96) \n with tf.variable_scope('block3'): # 75\n Y = layer(Y, 7, 96, 'conv1')\n Y = layer(Y, 7, 96, 'conv2')\n Y = pool(Y, 192) \n with tf.variable_scope('block4'): # 31\n Y = layer(Y, 7, 192, 'conv1')\n Y = layer(Y, 7, 192, 'conv2')\n Y = pool(Y, 384) \n Ycommon = Y # 9\n\n def make_output(n, Yx=Ycommon, count=384, keep_prob=0.9):\n Yx = layer(Yx, 9, count, 'condense1')\n Yx = tf.nn.dropout(Yx, keep_prob=keep_prob)\n Yx = layer(Yx, 1, count, 'convout1')\n Yx = tf.nn.dropout(Yx, keep_prob=keep_prob)\n Yx = layer(Yx, 1, count, 'convout2')\n Yx = tf.nn.dropout(Yx, keep_prob=keep_prob)\n Yx = layer(Yx, 1, n, 'convout3', nonlin=None)\n return Yx\n\n\n with tf.variable_scope('Yisship'):\n # Use more layers for is_ship since it's most important\n Yship_logits = make_output(1, count=1024)\n Yship = tf.nn.sigmoid(Yship_logits)\n\n with tf.variable_scope('Ydr'):\n Ydr = make_output(1)\n with tf.variable_scope('Ydc'):\n Ydc = make_output(1)\n\n with tf.variable_scope('Yangle'):\n Yangle_source = make_output(2)\n Ysin2a = Yangle_source[:, :, :, 0:1]\n Ycos2a = Yangle_source[:, :, :, 1:2]\n Yangle = 0.5 * tf.atan2(Ysin2a, Ycos2a)\n\n with tf.variable_scope('Ylength'):\n Ylength = make_output(1)\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n # In `PREDICT` mode we only need to return predictions.\n return tf.estimator.EstimatorSpec(\n mode=mode, predictions={\n \"is_ship\": Yship[:, :, :, 0],\n \"dr\" : Ydr[:, :, :, 0],\n \"dc\" : Ydc[:, :, :, 0],\n \"angle_deg\" : Yangle[:, :, :, 0],\n \"length_px\" : Ylength[:, :, :, 0],\n \"scene_id\" : features['scene_id'] \n })\n\n assert Yship.shape[1:] == (1, 1, 1), Yship.shape\n\n upsample = params['ship_upsample']\n\n with tf.variable_scope('train_harness'):\n\n Yship_ = Y_[:, :, :, :1]\n Yrc_ = Y_[:, :, :, 1:3]\n Ydr_ = Y_[:, :, :, 1:2]\n Ydc_ = Y_[:, :, :, 2:3]\n Ylength_ = Y_[:, :, :, 3:4]\n Yangle_ = Y_[:, :, :, 4:5]\n Ysin2a_ = tf.sin(2 * Yangle_) \n Ycos2a_ = tf.cos(2 * Yangle_)\n\n weights = 1.0 / ((upsample - 1) * Yship_ + 1)\n\n ship_loss = tf.reduce_mean(weights * tf.nn.sigmoid_cross_entropy_with_logits(\n logits=Yship_logits, \n labels=Yship_))\n\n scale = tf.maximum(Ylength_, 1.0) / 10.0\n\n delta_rc = tf.sqrt((Ydr - Ydr_) ** 2 + (Ydc - Ydc_) ** 2)\n\n rc_loss = tf.reduce_mean(Yship_ * weights * (\n L1s(delta_rc / scale) ))\n\n length_loss = tf.reduce_mean(Yship_ * weights * (\n L1s((Ylength - Ylength_) / scale) \n ))\n\n angle_loss = tf.reduce_mean(Yship_ * weights * (\n (Ysin2a - Ysin2a_) ** 2 +\n (Ycos2a - Ycos2a_) ** 2 \n ))\n\n char_loss = rc_loss + length_loss + angle_loss\n\n loss = (ship_loss + char_weight * char_loss)\n # Pre-made estimators use the total_loss instead of the average,\n # but that's stupid so we no longer do that.\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.contrib.estimator.clip_gradients_by_norm(\n tf.train.MomentumOptimizer(learning_rate, 0.9, use_nesterov=True),\n 5)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss=loss, \n global_step=global_step)\n\n return tf.estimator.EstimatorSpec(\n mode=mode, loss=loss, train_op=train_op)\n\n\n assert mode == tf.estimator.ModeKeys.EVAL\n\n # Casts are probaly not necessary, but the right fix is to use at threshold functions.\n labels = tf.cast(Yship_ > 0.5, tf.float32)\n predictions = tf.cast(Yship > 0.5, tf.float32)\n\n accuracy = tf.metrics.accuracy(labels=labels, predictions=predictions)\n Yrc = tf.concat([Ydr, Ydc], axis=3)\n rc_rms = tf.metrics.root_mean_squared_error(labels=Yrc_, predictions=Yrc,\n weights=Yship_)\n size_rms = tf.metrics.root_mean_squared_error(labels=Ylength_, predictions=Ylength,\n weights=Yship_)\n angle_rms = tf.metrics.root_mean_squared_error(\n labels = tf.concat([Ysin2a_, Ycos2a_], axis=3),\n predictions = tf.concat([Ysin2a, Ycos2a], axis=3),\n weights=Yship_)\n # See this post for a pretty way to do recall / precision at thresholds\n # https://stackoverflow.com/questions/46242091/tensorflow-plot-tf-metrics-precision-at-thresholds-in-tensorboard-through-eval-m\n recall = tf.metrics.recall(labels, predictions)\n precision = tf.metrics.precision(labels, predictions)\n raw_f1 = 2 / (1 / recall[0] + 1/ precision[0])\n f1 = (raw_f1, raw_f1) # F1 is already composed of averages -- shouldn't need additional OP, so use dummy.\n ship_loss_mtrc = tf.metrics.mean(ship_loss)\n angle_loss_mtrc = tf.metrics.mean(angle_loss)\n rc_loss_mtrc = tf.metrics.mean(rc_loss)\n length_loss_mtrc = tf.metrics.mean(length_loss)\n\n tf.summary.scalar('is_ship_accuracy', accuracy[0])\n tf.summary.scalar('is_ship_f1', f1[0])\n tf.summary.scalar('is_ship_recall', recall[0])\n tf.summary.scalar('is_ship_precision', precision[0])\n tf.summary.scalar('rc_rms', rc_rms[0])\n tf.summary.scalar('size_rms', size_rms[0])\n tf.summary.scalar('angle_rms', angle_rms[0])\n tf.summary.scalar('ship_loss', ship_loss_mtrc[0])\n tf.summary.scalar('angle_loss', angle_loss_mtrc[0])\n tf.summary.scalar('rc_loss', rc_loss_mtrc[0])\n tf.summary.scalar('length_loss', length_loss_mtrc[0])\n\n tf.summary.scalar('learning_rate', learning_rate)\n\n eval_metrics = {\n 'is_ship_accuracy' : accuracy,\n 'is_ship_recall' : recall,\n 'is_ship_precision' : precision,\n 'is_ship_f1' : f1,\n 'rc_rms' : rc_rms,\n 'size_rms' : size_rms,\n 'angle_rms' : angle_rms,\n 'ship_loss': ship_loss_mtrc,\n 'angle_loss': angle_loss_mtrc,\n 'rc_loss': rc_loss_mtrc,\n 'size_loss': length_loss_mtrc,\n 'learning_rate' : (learning_rate, learning_rate),\n\n }\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n # Report sum of error for compatibility with pre-made estimators\n loss=loss,\n eval_metric_ops=eval_metrics)\n\n\n\nclass Model(ModelBase):\n\n char_weight = 1\n batch_size = 32\n lr_max_per_batch_size = 0.000125\n lr_decay_steps = 20000\n lr_decay = 0.2\n steps = 60000\n field_of_view = 339\n\n data_source = TrainTestTileData\n\n @property\n def model_fn(self):\n return model_fn\n\n\nclass GPUInferenceModel(GPUInferenceModel):\n \n char_weight = 1\n batch_size = 32\n lr_max_per_batch_size = 0.000125\n lr_decay_steps = 20000\n lr_decay = 0.2\n steps = 60000\n field_of_view = 339\n\n data_source = TrainTestTileData\n\n @property\n def model_fn(self):\n return model_fn\n\n\nif __name__ == '__main__':\n Model.run_from_main()\n","sub_path":"supplementary-sections/2-daytime-optical-imagery/optical_vessel_detection/pair_trawler_model_v1_0.py","file_name":"pair_trawler_model_v1_0.py","file_ext":"py","file_size_in_byte":9349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"452175764","text":"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport plotly.graph_objects as go\r\nimport matplotlib.pyplot as plt\r\nimport json\r\nimport copy\r\nimport re\r\nimport matplotlib.pyplot as plt\r\nimport hashlib\r\nimport plotly.io as pio\r\nfrom IPython.display import Image, display\r\n\r\nthroughputs = [\r\n [64, \"2mpps\"], \r\n [128, \"2mpps\"], \r\n [256, \"1.5mpps\"], \r\n [512, \"1.5mpps\"], \r\n [1024, \"1mpps\"], \r\n [1500, \"1mpps\"], \r\n [3000, \"1mpps\"]\r\n #[9000, \"1kpps\"]\r\n ]\r\n\r\nthroughputs_map = dict(throughputs)\r\n\r\n# 时间轴设置\r\nstart_time = 0\r\nend_time = start_time + 200\r\nsampling_interval = 10\r\ntimestamps = (pd.timedelta_range(start=f\"{start_time}s\", end=f\"{end_time}s\", freq=f\"{sampling_interval}s\").total_seconds().astype(int))[:-1]\r\n\r\nimport hashlib\r\n\r\ndef is_acceptable(r, g, b):\r\n return max(r, g, b) - min(r, g, b) > 70 and sum([r, g, b]) / 3 < 190\r\n\r\ndef generate_color_from_hash(input_arg):\r\n hash_obj = hashlib.md5(str(input_arg).encode())\r\n hash_hex = hash_obj.hexdigest()\r\n \r\n colors = [int(hash_hex[i:i+2], 16) for i in (0, 2, 4)]\r\n \r\n while not is_acceptable(*colors):\r\n colors = [color - 10 for color in colors]\r\n \r\n return f\"rgb{tuple(colors)}\"\r\n\r\ndef get_color(input_arg):\r\n return generate_color_from_hash(input_arg)\r\n\r\n\r\ndef parse_line(line):\r\n items = line.split()\r\n \r\n data = {\r\n \"port_id\": int(items[0]),\r\n \"pkt_len\": int(items[1]),\r\n \"cpu_util\": float(items[2].replace('%', '')),\r\n # 根据数据表中的列数和名称,你可以继续添加其他的项\r\n \"tx_pps\": items[3],\r\n \"tx_bps\": items[4],\r\n }\r\n \r\n return data\r\n\r\n# 函数:从文件中解析数据\r\ndef parse_data_from_file(filename):\r\n with open(filename, 'r') as file:\r\n # 读取文件内容\r\n content = file.read()\r\n\r\n # 分行并去除前两行(标题和分隔符)\r\n lines = content.strip().split(\"\\n\")[2:]\r\n parsed_data = [parse_line(line) for line in lines]\r\n\r\n return parsed_data\r\n\r\ndef transform_input_to_plot(input_data, main_key, data_key, group_key):\r\n \"\"\"\r\n main_key: 主要用于分类数据的关键字段。例如:'port_id'\r\n data_key: 从数据中提取的主要数值字段。例如:'cpu_util'\r\n group_key: 用于将数据分组的字段。例如:'len'\r\n 输入:\r\n [{\r\n 'port_id': 0,\r\n 'pkts': [\r\n {\r\n 'len': 64,\r\n 'cpu_util': [12.4,12.5...],\r\n 'tx_pps': \"1mpps\",\r\n 'tx_bps': \"1.9mpps\"\r\n },\r\n {\r\n 'len': 128,\r\n 'cpu_util': [24.3,...],\r\n 'tx_pps': \"1mpps\",\r\n 'tx_bps': \"2mpps\"\r\n },\r\n ... \r\n ]\r\n },{\r\n 'port_id': 1,\r\n 'pkts': [\r\n {\r\n 'len': 64,\r\n 'cpu_util': [12.4,...],\r\n 'tx_pps': \"1mpps\",\r\n 'tx_bps': \"1.9mpps\"\r\n },\r\n ... \r\n ]\r\n },\r\n ... \r\n ]\r\n 输出:\r\n {\r\n {\r\n y_values:{\r\n \"0\":{value:[12.3, 12.5, ...], alias:\"\", \"avg\":\"\"},\r\n \"1\":{value:[12.4, ...], alias:\"\" , \"avg\":\"\"} \r\n },\r\n 'group_key': 64,\r\n \"title\":\"\"\r\n \"xaxis_title\":\"\"\r\n \"yaxis_title\":\"\"\r\n \"x_dtick\":\"\"\r\n \"y_dtick\":\"\"\r\n },\r\n {\r\n y_values:{\r\n \"0\":{value:[12.3, 12.5, ...], alias:\"\", \"avg\":\"\"},\r\n \"1\":{value:[12.4, ...], alias:\"\" , \"avg\":\"\"} \r\n }\r\n 'group_key': 128\r\n \"title\":\"\"\r\n \"xaxis_title\":\"\"\r\n \"yaxis_title\":\"\"\r\n \"x_dtick\":\"\"\r\n \"y_dtick\":\"\"\r\n },\r\n ... \r\n }\r\n \"\"\"\r\n grouped_data = {}\r\n \r\n for entry in input_data:\r\n main_value = str(entry[main_key])\r\n \r\n for pkt in entry['pkts']:\r\n group_value = pkt[group_key]\r\n \r\n # Initialize group if not exists\r\n if group_value not in grouped_data:\r\n grouped_data[group_value] = {\r\n group_key: group_value,\r\n \"title\": \"\",\r\n \"xaxis_title\": \"\",\r\n \"yaxis_title\": \"\",\r\n \"x_dtick\": \"\",\r\n \"y_dtick\": \"\",\r\n \"y_values\": {}\r\n }\r\n\r\n # Initialize main_value if not exists\r\n if main_value not in grouped_data[group_value][\"y_values\"]:\r\n grouped_data[group_value][\"y_values\"][main_value] = {\r\n \"value\": [],\r\n \"name\": main_value,\r\n \"alias\": \"\",\r\n \"avg\": 0\r\n }\r\n\r\n # Append values and update average\r\n grouped_data[group_value][\"y_values\"][main_value][\"value\"].extend(pkt[data_key])\r\n total_values = len(grouped_data[group_value][\"y_values\"][main_value][\"value\"][1:])\r\n avg = sum(grouped_data[group_value][\"y_values\"][main_value][\"value\"][1:]) / total_values if total_values else 0\r\n grouped_data[group_value][\"y_values\"][main_value][\"avg\"] = avg\r\n \r\n return list(grouped_data.values())\r\n\r\ndef calculate_avg_percentage_increase(data, ports):\r\n \"\"\"\r\n 计算每个group 中,每组数据的avg增量百分比。\r\n 使用port 0作为基准值。\r\n \"\"\"\r\n percentage_increases = {}\r\n \r\n for group in data:\r\n group_key = group['len']\r\n percentage_increases[group_key] = {} \r\n base_avg = group['y_values'][str(ports[0])]['avg']\r\n for key, y_data in group['y_values'].items():\r\n if key == '0':\r\n # Base port's increase is always 0%\r\n percentage_increases[group_key][key] = 0.0\r\n else:\r\n current_avg = y_data['avg']\r\n increase = current_avg - base_avg\r\n percentage = ((increase* 100) / base_avg) if base_avg != 0 else 0\r\n percentage_increases[group_key][key] = round(percentage, 2)\r\n \r\n return percentage_increases\r\n\r\n\r\ndef get_trace(timestamps, y_values, name_base, color, mode='lines+markers', line_style=None):\r\n line_style_dict = {\"dash\": \"dash\"} if line_style == \"dash\" else {}\r\n #print(y_values)\r\n #print(name_base)\r\n return go.Scatter(\r\n x=timestamps,\r\n y=y_values,\r\n mode=mode,\r\n name=name_base,\r\n line=dict(color=color, **line_style_dict)\r\n )\r\n\r\ndef get_layout(fig, title, xaxis_title, yaxis_title, x_dtick, y_dtick):\r\n fig.update_layout(\r\n title=title,\r\n yaxis_title=yaxis_title,\r\n xaxis_title=xaxis_title, \r\n yaxis={\r\n \"dtick\": y_dtick, # 注意这里的更改\r\n \"linecolor\": 'gray',\r\n \"showgrid\": True,\r\n \"gridcolor\": 'lightgray'\r\n },\r\n xaxis={ # 添加了xaxis设置\r\n \"dtick\": x_dtick,\r\n \"linecolor\": 'gray',\r\n \"showgrid\": True,\r\n \"gridcolor\": 'lightgray'\r\n },\r\n paper_bgcolor='rgba(255, 255, 255, 1)',\r\n plot_bgcolor='rgba(220, 220, 220, 1)'\r\n )\r\n\r\n#def add_generic_trace_with_avg(fig, timestamps, y_values, name_base, color):\r\n# # Add main trace\r\n# trace = get_trace(timestamps, y_values, name_base, color)\r\n# fig.add_trace(trace)\r\n#\r\n# # Add average trace\r\n# avg_value = np.mean(y_values[1:])\r\n# avg_name = f\"{name_base} avg\"\r\n# avg_trace = get_trace(timestamps, [avg_value]*len(timestamps), avg_name, color, mode='lines', line_style='dash')\r\n# fig.add_trace(avg_trace)\r\n\r\ndef convert_rgb_to_tuple(rgb_str):\r\n # Extract numbers from 'rgb(...)' string\r\n r, g, b = map(int, rgb_str[4:-1].split(', '))\r\n return (r/255.0, g/255.0, b/255.0)\r\n\r\ndef plot_data_generic(timestamps, datas_structure):\r\n #print(datas_structure)\r\n #fig = go.Figure()\r\n #for datas in datas_structure:\r\n # for var_name, y_values in datas.items():\r\n # if var_name not in [\"len\", \"title\", \"xaxis_title\", \"yaxis_title\", \"x_dtick\", \"y_dtick\"]:\r\n # name_base = y_values[\"alias\"]\r\n # color = get_color(name_base + \"100\") # You might need to adapt the get_color function\r\n # add_generic_trace_with_avg(fig, timestamps, y_values[\"value\"], name_base, color)\r\n # get_layout(fig, datas[\"title\"], datas[\"xaxis_title\"], datas[\"yaxis_title\"], datas[\"x_dtick\"], datas[\"y_dtick\"])\r\n # #fig.show()\r\n # #将fig转换为静态图片并在Jupyter中显示\r\n # #img_bytes = pio.to_image(fig, format=\"png\")\r\n # #display(Image(img_bytes))\r\n for datas in datas_structure:\r\n plt.figure(figsize=(10, 5))\r\n for var_name, y_values_map in datas.items():\r\n if var_name != \"y_values\":\r\n continue\r\n for item_key, item_value in y_values_map.items():\r\n name_base = item_value[\"alias\"]\r\n color = convert_rgb_to_tuple(generate_color_from_hash(item_key + \"100\"))\r\n if len(timestamps) != len(item_value[\"value\"]):\r\n break\r\n plt.plot(timestamps, item_value[\"value\"], label=name_base, color= color, marker='o')\r\n plt.axhline(y=np.mean(item_value[\"value\"][1:]), color=color, linestyle='--', label=f\"{name_base} avg\")\r\n plt.title(datas[\"title\"])\r\n plt.xlabel(datas[\"xaxis_title\"])\r\n plt.ylabel(datas[\"yaxis_title\"])\r\n plt.grid(color='lightgray', linestyle='-', linewidth=0.5)\r\n plt.legend()\r\n plt.show()\r\n\r\n\r\nports = [1, 3]\r\n\r\ndef parser_raw_date_to_json(filename, ports, main_key, data_key, group_key):\r\n '''\r\n {\r\n 'port_id': 0,\r\n 'pkts': [\r\n {\r\n 'len': 64,\r\n 'cpu_util': [12.4, 12.3...],\r\n 'tx_pps': \"1mpps\",\r\n 'tx_bps': \"1.9mpps\"\r\n },\r\n {\r\n 'len': 128,\r\n 'cpu_util': [24.3],\r\n 'tx_pps': \"1mpps\",\r\n 'tx_bps': \"2mpps\"\r\n },\r\n ... \r\n ]\r\n }\r\n '''\r\n\r\n raw_datas_json = initialize_data_structure(ports)\r\n parsed_datas = parse_data_from_file(filename)\r\n for parsed_data in parsed_datas:\r\n port_id = int(parsed_data[\"port_id\"])\r\n pkt_len = int(parsed_data[\"pkt_len\"])\r\n cpu_util = float(parsed_data[\"cpu_util\"]) # 转换为小数\r\n\r\n # 查找匹配的port_id和pkt_len的data条目\r\n for data in raw_datas_json:\r\n if data['port_id'] == port_id:\r\n #print(data['port_id'])\r\n for pkt in data['pkts']:\r\n if int(pkt['len']) == int(pkt_len):\r\n pkt['cpu_util'].append(cpu_util)\r\n break\r\n\r\n return transform_input_to_plot(raw_datas_json, main_key, data_key, group_key)\r\n\r\ndef initialize_data_structure(ports):\r\n # Base structure for a pkt_len entry\r\n base_pkt = {\r\n \"len\": None,\r\n \"cpu_util\": [],\r\n \"tx_pps\": None,\r\n \"tx_bps\": None\r\n }\r\n\r\n datas = []\r\n for port in ports:\r\n data = {\r\n \"port_id\":0,\r\n \"pkts\": []\r\n }\r\n for length, pps in throughputs_map.items():\r\n new_pkt = copy.deepcopy(base_pkt)\r\n new_pkt[\"len\"] = length\r\n new_pkt[\"tx_pps\"] = pps\r\n data[\"pkts\"].append(new_pkt)\r\n data[\"port_id\"] = port\r\n datas.append(data)\r\n # Wrap data in a list as shown in the provided structure\r\n return datas\r\n\r\ndef initialize_split_vs_packed_titles(data, size_key=\"len\", speed_key=None):\r\n #print(data)\r\n size = \"null\"\r\n for entry in data:\r\n size = entry[size_key]\r\n speed = throughputs_map[size]\r\n # 如果提供了speed_key,则从数据中提取速度并添加到标题中。\r\n entry[\"title\"] = f\"CPU usage of virtio packed vs. split ring at {size}-byte and {speed}\"\r\n\r\n entry[\"xaxis_title\"] = \"Time seconds since start (s)\"\r\n entry[\"yaxis_title\"] = \"Cpu util seconds (%)\"\r\n entry[\"y_values\"][str(ports[0])][\"alias\"] = \"split ring\"\r\n entry[\"y_values\"][str(ports[1])][\"alias\"] = \"packed ring\"\r\n\r\ndef initialize_mb_rxbuf_titles(data, size_key=\"len\", speed_key=None):\r\n #print(data)\r\n size = \"null\"\r\n for entry in data:\r\n size = entry[size_key]\r\n speed = throughputs_map[size]\r\n # 如果提供了speed_key,则从数据中提取速度并添加到标题中。\r\n entry[\"title\"] = f\"CPU usage of virtio mergeable on vs. off at {size}-byte and {speed}\"\r\n\r\n entry[\"xaxis_title\"] = \"Time seconds since start (s)\"\r\n entry[\"yaxis_title\"] = \"Cpu util seconds (%)\"\r\n entry[\"y_values\"][str(ports[0])][\"alias\"] = \"mergeable off\"\r\n entry[\"y_values\"][str(ports[1])][\"alias\"] = \"mergeable on\"\r\n\r\n\r\n","sub_path":"note/virtio_data_plot.py","file_name":"virtio_data_plot.py","file_ext":"py","file_size_in_byte":13100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"43452102","text":"\n# coding: utf-8\n\n# __Expressions__\n\n# In[1]:\n\n\nprint(1288)\n\n\n# In[2]:\n\n\nprint(1288 + 639)\n\n\n# In[3]:\n\n\n1288 + 639\n\n\n# __Operators__\n\n# In[4]:\n\n\n# Calcualtes the average\n(749 + 371 + 828 + 503 + 1379)/5\n\n\n# __Variables__\n\n# In[5]:\n\n\nalbuquerque = 749\n\n\n# In[6]:\n\n\nanaheim = 371\n\n\n# In[7]:\n\n\nanchorage = 828\n\n\n# In[8]:\n\n\narlington = 503\n\n\n# In[9]:\n\n\natlanta = 1379\n\n\n# In[10]:\n\n\nprint(anaheim)\n\n\n# __Data Types__\n\n# In[11]:\n\n\natlanta_string = 'Atlanta'\n\n\n# In[12]:\n\n\natlanta_float = 1379.5\n\n\n# In[13]:\n\n\nprint(atlanta_string)\n\n\n# __The `type` function__\n# \n# The `type()` statement won't display anything. Instead, it will return the data type as a value.\n# ```python\n# hello = 'Hello'\n# print(type(hello))\n# ```\n\n# In[14]:\n\n\ntype(atlanta_string)\n\n\n# In[15]:\n\n\ntype(atlanta_float)\n\n\n# __List__\n# \n# To add values to a list object, use the `list.append()` __method__\n\n# In[16]:\n\n\n# Create two empty lists\ncities = []\ncrime_rates = []\n\n\n# In[17]:\n\n\ncities.append('Albuquerque')\ncities.append('Anaheim')\ncities.append('Anchorage')\ncities.append('Arlington')\ncities.append('Atlanta')\n\n\n# In[18]:\n\n\ncrime_rates.append(749)\ncrime_rates.append(371)\ncrime_rates.append(828)\ncrime_rates.append(503)\ncrime_rates.append(1379)\n\n\n# In[19]:\n\n\ncities\n\n\n# In[20]:\n\n\ncrime_rates\n\n\n# In[21]:\n\n\n# Create the list with values\nmonths = [1,2,3,4,5,6,7,8,9,10,11,12]\n\n\n# In[22]:\n\n\nmonths\n\n\n# __Accessing elements in a list__\n\n# In[23]:\n\n\n# The third element from the list `cities`\nanchorage_str = cities[2]\n\n\n# In[24]:\n\n\nanchorage_str\n\n\n# In[25]:\n\n\n# The third element from the list `crime_rates`\nanchorage_cr = crime_rates[2]\n\n\n# In[26]:\n\n\nanchorage_cr\n\n\n# __Retrieving the length of a list__\n\n# In[27]:\n\n\nlast_index = len(crime_rates) - 1\nlast_value = crime_rates[last_index]\n\n\n# In[28]:\n\n\nlast_value\n\n\n# In[29]:\n\n\n# Add the lengths of the `cities` and `crime_rates` list objects and assign the sum to `two_sum`\ntwo_sum = len(cities) + len(crime_rates)\n\n\n# In[30]:\n\n\ntwo_sum\n\n\n# __Slicing lists__\n\n# In[31]:\n\n\n# Values at index 2, 3, 4\nending_index = len(crime_rates)\ntwo_to_end = crime_rates[2:ending_index]\n\n\n# In[32]:\n\n\ntwo_to_end\n\n\n# In[35]:\n\n\ncities_slice = cities[1:4]\n\n\n# In[36]:\n\n\ncities_slice\n\n\n# In[37]:\n\n\n# Select the last two elements in `crime_rates` and assign to `cr_slice`\nstarting_index = len(crime_rates) - 2\ncr_slice = crime_rates[starting_index:ending_index]\n\n\n# In[38]:\n\n\ncr_slice\n\n","sub_path":"Step_1_Introduction to Python/Python Programming_Beginner/py/1_Python Basics.py","file_name":"1_Python Basics.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"204475573","text":"import github3\nfrom tests.utils import (expect, BaseCase, load)\n\n\nclass TestGist(BaseCase):\n def __init__(self, methodName='runTest'):\n super(TestGist, self).__init__(methodName)\n self.gist = github3.gists.Gist(load('gist'))\n self.api = 'https://api.github.com/gists/3813862'\n\n def setUp(self):\n super(TestGist, self).setUp()\n self.gist = github3.gists.Gist(self.gist.to_json(), self.g)\n\n def test_str(self):\n expect(str(self.gist)) == str(self.gist.id)\n\n def test_repr(self):\n expect(repr(self.gist)) == ''.format(self.gist)\n\n def test_create_comment(self):\n self.response('gist_comment', 201)\n self.post(self.api + '/comments')\n self.conf = {'data': {'body': 'bar'}}\n\n with expect.githuberror():\n self.gist.create_comment(None)\n\n self.login()\n\n expect(self.gist.create_comment(None)).is_None()\n expect(self.gist.create_comment('')).is_None()\n self.not_called()\n expect(self.gist.create_comment('bar')).isinstance(\n github3.gists.GistComment)\n self.mock_assertions()\n\n def test_delete(self):\n self.response('', 204)\n self.delete(self.api)\n self.conf = {}\n\n with expect.githuberror():\n self.gist.delete()\n\n self.not_called()\n self.login()\n expect(self.gist.delete()).is_True()\n self.mock_assertions()\n\n def test_edit(self):\n self.response('gist', 200)\n self.patch(self.api)\n self.conf = {\n 'data': {\n 'description': 'desc',\n 'files': {'file1': {'content': 'foo bar'}}\n }\n }\n\n with expect.githuberror():\n self.gist.edit(None, None)\n\n self.login()\n expect(self.gist.edit()).is_False()\n self.not_called()\n\n expect(self.gist.edit(**self.conf['data'])).is_True()\n self.mock_assertions()\n\n def test_fork(self):\n self.response('gist', 201)\n self.post(self.api + '/forks')\n self.conf = {}\n\n with expect.githuberror():\n self.gist.fork()\n\n self.not_called()\n self.login()\n expect(self.gist.fork()).isinstance(github3.gists.Gist)\n self.mock_assertions()\n\n def test_is_public(self):\n expect(self.gist.is_public()) == self.gist.public\n\n def test_is_starred(self):\n self.response('', 204)\n self.get(self.api + '/star')\n\n with expect.githuberror():\n self.gist.is_starred()\n\n self.not_called()\n self.login()\n expect(self.gist.is_starred()).is_True()\n self.mock_assertions()\n\n def test_iter_comments(self):\n self.response('gist_comment', 200, _iter=True)\n self.get(self.api + '/comments')\n self.conf = {'params': None}\n\n c = next(self.gist.iter_comments())\n expect(c).isinstance(github3.gists.GistComment)\n self.mock_assertions()\n\n def test_iter_files(self):\n gist_file = next(self.gist.iter_files())\n expect(gist_file) == self.gist._files[0]\n expect(repr(gist_file).startswith('.+)', views.TextSearchLocation.as_view(), name='text_query_location'),\n url(r'^location/(?P.+)', views.City.as_view(), name='city'),\n url(r'^query/(?P.+)', views.TextSearch.as_view(), name='text_query'),\n\n]","sub_path":"jobs/jobs/jobs_api/jobs_rest_api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"44462269","text":"# https://atcoder.jp/contests/abc064/tasks/abc064_c\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n C=[0]*9\n n=int(input())\n for a in map(int,input().split()):\n s=a//400\n if(s>=8): C[8]+=1\n else: C[s]+=1\n\n cnt=sum(1 for i in range(8) if(C[i]))\n print(max(1,cnt),cnt+C[-1])\nresolve()\n","sub_path":"ABC064/c_colorful_leaderboard.py","file_name":"c_colorful_leaderboard.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"425854481","text":"from django import template\nfrom django.utils.translation import ugettext_lazy as _\n\nregister = template.Library()\n\nin_month = [_('stycznia'), _('lutego'), _('marca'), _('kwietnia'), _('maja'), _('czerwca'),\n _('lipca'), _('sierpnia'), _('września'), _('października'), _('listopada'), _('grudnia')]\n\n\n@register.filter\ndef in_words_pl(value):\n split = value.split('-')\n if len(split) > 1:\n i = int(split[-2])-1\n if i < len(in_month):\n split[-2] = str(in_month[i])\n return \" \".join(split)\n return value","sub_path":"page/templatetags/in_words_pl.py","file_name":"in_words_pl.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"291417455","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom flask import make_response, jsonify\n\ndef abort(status_code, error, content_type=\"application/json\"):\n \"\"\"\n Return a HTTP response object of a specific status code\n with sepcific error. By default content_type is assumed\n to be application/json.\n\n Parameters\n ----------\n status_code : int\n error : iterable\n An error message to return. It could be a dictionary\n (for JSON) or a string (for plaintext).\n content_type : optional, str\n Default set to ``application/json``.\n\n Returns\n -------\n response : HTTPResponse\n\n \"\"\"\n \n content_type = content_type.lower()\n if content_type == \"application/json\":\n return jsonify(error), status_code\n else:\n response = make_response()\n response.status = status_code\n response.set_header('content-type', content_type)\n return response\n","sub_path":"backend/app/utils/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"634630196","text":"from typing import List\r\n\r\ntablica: List[str] = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\r\n\r\n\r\ndef board():\r\n print(tablica[0:3])\r\n print(tablica[3:6])\r\n print(tablica[6:9])\r\n\r\n\r\ndef Tic_Tac_Toe():\r\n print('Welcome to Tic Tac Toe Game! You are playing on a 3x3 board. Have fun! :)\\n')\r\n player1 = input('Player 1\\nPlease tell me if you prefer to use X or O: ')\r\n\r\n if player1.lower() == 'x':\r\n player2 = 'o'\r\n else:\r\n player2 = 'x'\r\n print('\\n' * 3)\r\n print(f'Player 2 is playing with {player2.upper()}')\r\n for t, u in enumerate(tablica):\r\n entry = int(input('Podaj numer miejsca(1-9): '))\r\n for ind, val in enumerate(tablica):\r\n if entry == ind and t % 2 == 0:\r\n print('\\n'*100)\r\n tablica[ind - 1] = player1.upper()\r\n elif entry == ind and t % 2 != 0:\r\n print('\\n'*100)\r\n tablica[ind - 1] = player2.upper()\r\n else:\r\n continue\r\n board()\r\n if tablica[0] == tablica[1] == tablica[2] == 'X' or tablica[3] == tablica[4] == tablica[5] == 'X' or tablica[\r\n 6] == tablica[7] == tablica[8] == 'X' or tablica[0] == tablica[4] == tablica[8] == 'X' or tablica[2] == \\\r\n tablica[4] == tablica[6] == 'X' or tablica[0] == tablica[3] == tablica[5] == 'X' or tablica[1] == \\\r\n tablica[4] == tablica[7] == 'X' or tablica[2] == tablica[5] == tablica[8] == 'X':\r\n print('X has won!')\r\n break\r\n elif tablica[0] == tablica[1] == tablica[2] == 'O' or tablica[3] == tablica[4] == tablica[5] == 'O' or tablica[\r\n 6] == tablica[7] == tablica[8] == 'O' or tablica[0] == tablica[4] == tablica[8] == 'O' or tablica[2] == \\\r\n tablica[4] == tablica[6] == 'O' or tablica[0] == tablica[3] == tablica[5] == 'O' or tablica[1] == \\\r\n tablica[4] == tablica[7] == 'O' or tablica[2] == tablica[5] == tablica[8] == 'O':\r\n print('O has won!')\r\n break\r\nTic_Tac_Toe()","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"54839157","text":"#!/usr/bin/env python\n# filename: plots.py\n\n\n#\n# Copyright (c) 2016 Bryan Briney\n# License: The MIT license (http://opensource.org/licenses/MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n# and associated documentation files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge, publish, distribute,\n# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or\n# substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import AutoMinorLocator\n\n\ndef shared_mutation_2dhist(x, y, cmap, ax, figfile=None, figsize=None, figsize_denom=4, n_levels=10, alpha=1.0, x_lim=(0, 19), y_lim=(0, 12),\n y_label='VRC01-class mutations', x_label='Total amino acid mutations', labelsize=14,\n tick_labelsize=12, pad=-4, show_values=True):\n # adjust the inputs to make them iterable\n if type(x[0]) in [int, float, np.int64, np.float64]:\n x = [x]\n y = [y]\n cmap = [cmap]\n sns.set_style('whitegrid')\n # make the plots\n for _x, _y, _cmap in zip(x, y, cmap):\n bin_x = max(_x) + 2 if x_lim is None else x_lim[1] + 2\n bin_y = max(_y) + 2 if y_lim is None else y_lim[1] + 2\n bins = [[i - 0.5 for i in range(bin_y)], [i - 0.5 for i in range(bin_x)]]\n data, x_edges, y_edges = np.histogram2d(_y, _x, bins=bins)\n data = data[::-1]\n if figsize is None:\n figsize = (float(bin_x) / figsize_denom, float(bin_y) / figsize_denom)\n mask = np.array([[val == 0 for val in subl] for subl in data])\n ax = sns.heatmap(data, cmap=_cmap, square=True, cbar=False, mask=mask,\n linewidths=1, linecolor='w', alpha=alpha)\n if x_lim is None:\n x_lim = [0, len(data[0])]\n else:\n x_lim = [x_lim[0], x_lim[1]]\n if y_lim is None:\n y_lim = [0, len(data)]\n else:\n y_lim = [y_lim[0], y_lim[1]]\n ax.set_xlim(x_lim)\n ax.set_ylim(y_lim)\n # format ticks and spines\n x_ticks = [t for t in range(x_lim[0], x_lim[1] + 1)]\n ax.set_xticks([t + 0.5 for t in x_ticks])\n x_ticklabels = [str(l) if l % 2 == 0 else '' for l in x_ticks]\n ax.set_xticklabels(x_ticklabels, rotation=0)\n y_ticks = [t for t in range(y_lim[0], y_lim[1] + 1)]\n ax.set_yticks([t + 0.5 for t in y_ticks])\n y_ticklabels = [str(l) if l % 2 == 0 else '' for l in y_ticks]\n ax.set_yticklabels(y_ticklabels, rotation=0)\n for position in ['right', 'left', 'top', 'bottom']:\n ax.spines[position].set_visible(True)\n ax.spines[position].set_color('k')\n if show_values:\n _data = data[::-1]\n max_val = float(np.amax(_data))\n for y in range(_data.shape[0]):\n for x in range(_data.shape[1]):\n if _data[y, x] == 0:\n continue\n color = 'w' if _data[y, x] / max_val >= 0.5 else 'k'\n plt.text(x + 0.5, y + 0.5, str(int(_data[y, x])),\n color=color,\n horizontalalignment='center',\n verticalalignment='center',\n fontsize=12)\n ax.tick_params(axis='x', labelsize=tick_labelsize)\n ax.tick_params(axis='y', labelsize=tick_labelsize)\n plt.ylabel(y_label, size=labelsize)\n plt.xlabel(x_label, size=labelsize)\n ax.xaxis.set_tick_params(which='major', direction='out', length=3,\n color='k', width=1, top='off', pad=pad)\n ax.yaxis.set_tick_params(which='major', direction='out', length=3,\n color='k', width=1, top='off', pad=pad)\n\n\ndef pixel_plot(data, cmap, figfile=None, pad=2, labelsize=14, tight_layout=True,\n maxy_denom=30, maxx_denom=10):\n '''\n ::data:: is the output from vrc01_class_mutation_positions()\n '''\n max_y, max_x = data.shape\n f, ax = plt.subplots(figsize=(max_x / float(maxx_denom), max_y / float(maxy_denom)))\n plt.pcolor(data, cmap=cmap)\n ax.set_xlim([0, max_x])\n ax.set_ylim([0, max_y])\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['bottom'].set_color('k')\n minorLocator = AutoMinorLocator(1)\n ax.xaxis.set_minor_locator(minorLocator)\n ticks = [26, 34, 50, 58, 99, 114]\n minor_ticks = [13, 30, 42, 54, 78.5, 106.5, 118]\n minor_labels = ['FR1', 'CDR1', 'FR2', 'CDR2', 'FR3', 'CDR3', 'FR4']\n ax.set_xticks(ticks)\n ax.xaxis.set_tick_params(which='major', direction='out',\n length=6, color='k', width=1, top='off', labelsize=0)\n ax.set_xticks(minor_ticks, minor=True)\n ax.set_xticklabels(minor_labels, minor=True, y=-0.02)\n ax.xaxis.set_tick_params(which='minor', direction='out',\n length=12, color='white', width=1, top='off',\n labelsize=labelsize, pad=pad)\n ticks = [26, 34, 50, 58, 99, 114]\n plt.xticks(ticks, [' '] * len(ticks))\n ax.xaxis.set_tick_params(which='major', direction='out',\n length=6, color='k', width=1.5, top='off')\n ax.tick_params(axis='y', labelsize=0)\n if tight_layout:\n plt.tight_layout()\n if figfile is None:\n plt.show()\n else:\n plt.savefig(figfile)\n\n\ndef fill_between_steps(ax, x, y1, y2, facecolor='grey', edgecolor='grey', alpha=0.5, step_where='mid', lw=1):\n ''' fill between a step plot.\n\n Parameters\n ----------\n ax : Axes\n The axes to draw to\n\n x : array-like\n Array/vector of index values.\n\n y1 : array-like or float\n Array/vector of values to be filled under.\n y2 : array-Like or float, optional\n Array/vector or bottom values for filled area. Default is 0.\n\n step_where : {'pre', 'post', 'mid'}\n where the step happens, same meanings as for `step`\n\n **kwargs will be passed to the matplotlib fill_between() function.\n\n Returns\n -------\n ret : PolyCollection\n The added artist\n\n '''\n if step_where not in {'pre', 'post', 'mid'}:\n raise ValueError(\"where must be one of {{'pre', 'post', 'mid'}} \"\n \"You passed in {wh}\".format(wh=step_where))\n # make sure y values are up-converted to arrays\n if np.isscalar(y1):\n y1 = np.ones_like(x) * y1\n if np.isscalar(y2):\n y2 = np.ones_like(x) * y2\n # temporary array for up-converting the values to step corners\n # 3 x 2N - 1 array\n vertices = np.vstack((x, y1, y2))\n if step_where == 'pre':\n steps = np.zeros((3, 2 * len(x) - 1), np.float)\n steps[0, 0::2], steps[0, 1::2] = vertices[0, :], vertices[0, :-1]\n steps[1:, 0::2], steps[1:, 1:-1:2] = vertices[1:, :], vertices[1:, 1:]\n elif step_where == 'post':\n steps = np.zeros((3, 2 * len(x) - 1), np.float)\n steps[0, ::2], steps[0, 1:-1:2] = vertices[0, :], vertices[0, 1:]\n steps[1:, 0::2], steps[1:, 1::2] = vertices[1:, :], vertices[1:, :-1]\n elif step_where == 'mid':\n steps = np.zeros((3, 2 * len(x)), np.float)\n steps[0, 1:-1:2] = 0.5 * (vertices[0, :-1] + vertices[0, 1:])\n steps[0, 2::2] = 0.5 * (vertices[0, :-1] + vertices[0, 1:])\n steps[0, 0] = vertices[0, 0]\n steps[0, -1] = vertices[0, -1]\n steps[1:, 0::2], steps[1:, 1::2] = vertices[1:, :], vertices[1:, :]\n else:\n raise RuntimeError(\"should never hit end of if-elif block for validated input\")\n # un-pack\n xx, yy1, yy2 = steps\n # now to the plotting part:\n return ax.fill_between(xx, yy1, y2=yy2, facecolor='grey', edgecolor='grey', alpha=0.5, lw=1)\n\n\n\n\n","sub_path":"utils/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":8420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"110223377","text":"import importlib\nimport re\nimport sys\n\n# Traverse policy definition (needed for non top-level elements)\n\n# Element name for traverse type elements\nARC = 'arc'\n\n# for parents with in max_hop, match only once\nPARENT = 'parent'\n# for descendants with in max_hop, for all, match all\nCHILDREN = 'children'\n# for parents with in max_hop, for all, match all\nANCESTORS = 'ancestors'\n# for descendants with in max_hop, for all, match only once\nDESCENDANT = 'descendant'\n\n# Element name for max_hop elements (default=1)\nMAX_HOP = 'max_hop'\n\n# Matching regexp pattern definition\n\n# Element name for dependency label (token.dep_) patterns (default='.*')\nLABEL = 'label'\n# Element name for word (token.orth_) patterns (default='.*')\nWORD = 'word'\n# Element name for stop-word patterns applied to word (token.orth_) (default=None)\nSW = 'sw'\n# Element name for lemma (token.lemma_) patterns (default='.*')\nLEMMA = 'lemma'\n# Element name for part-of-speech (token.pos_) patterns (default='.*')\nPOS = 'pos'\n\n# Sub rule definition\n\n# Element name for lists which have recursive sub rule list\nDEPS = 'deps'\n\n# Candidate generation action definition\n\n# Element name for action set definition\nACTION = 'action'\n\n# use current token as one of the candidates if the rule matches to current token\nUSE = {'USE'}\n# generate candidates if the rule matches to current token\nPOP = {'POP'}\n# cancel traversing if the rule matches to current token\nFAIL = {'FAIL'}\n# use current token as one of the candidates if the rule does not match to current token\nUSE_ON_FAIL = {'USE_ON_FAIL'}\n# generate candidates if the rule does rule match to current token\nPOP_ON_FAIL = {'POP_ON_FAIL'}\n# continue traversing if the rule does not match to current token\nCONTINUE_ON_FAIL = {'CONTINUE_ON_FAIL'}\nGOAL = USE | POP\nGREEDY = USE | POP_ON_FAIL\nUSE_ALWAYS = USE | USE_ON_FAIL\nPOP_ALWAYS = POP | POP_ON_FAIL\nGOAL_ALWAYS = USE_ALWAYS | POP_ALWAYS\nactions = {\n v: v for v in USE | POP | FAIL | USE_ON_FAIL | POP_ON_FAIL | CONTINUE_ON_FAIL | {\n 'GOAL', 'GREEDY', 'USE_ALWAYS', 'POP_ALWAYS', 'GOAL_ALWAYS',\n }\n}\n\n# Element name for enabling debug mode (default=False)\nDEBUG = 'debug'\n\n# Element name for debug information (default='')\nINFO = 'info'\n\n\nclass DependencyRule:\n @staticmethod\n def _get_re(data, field, count):\n if field in data:\n return re.compile('^({})$'.format(data[field].lower())), count + 1\n else:\n return re.compile(r'^.*$'), count\n\n def __init__(self, data=None, nest_level=0):\n is_top = nest_level == 0\n field_count = 0\n\n self.nest_level = nest_level\n if ARC in data:\n if is_top:\n raise Exception('arc not allowed in top rule')\n v = data[ARC]\n if v not in [ANCESTORS, DESCENDANT, PARENT, CHILDREN]:\n raise Exception('arc must be ancestors, descendants, parent, or children: {}'.format(v))\n field_count += 1\n self.arc = v\n elif is_top:\n self.arc = None\n else:\n raise Exception('arc must be specified')\n\n if MAX_HOP in data:\n if is_top:\n raise Exception('max_hop not allowed in top rule')\n field_count += 1\n v = data[MAX_HOP]\n if isinstance(v, int):\n if v > 0:\n self.max_hop = v\n else:\n raise Exception('hop must be > 0: {}', format(v))\n else:\n raise Exception('hop must be int: {}', format(v))\n else:\n self.max_hop = 1\n\n if LABEL in data and is_top:\n raise Exception('label not allowed in top rule')\n self.label, field_count = DependencyRule._get_re(data, LABEL, field_count)\n\n self.word, field_count = DependencyRule._get_re(data, WORD, field_count)\n self.lemma, field_count = DependencyRule._get_re(data, LEMMA, field_count)\n self.pos, field_count = DependencyRule._get_re(data, POS, field_count)\n\n if DEPS in data:\n field_count += 1\n self.deps = [DependencyRule(sub_data, nest_level + 1) for sub_data in data[DEPS]]\n elif ACTION not in data:\n raise Exception('action must be specified if no deps')\n else:\n self.deps = None\n\n if ACTION in data:\n v = data[ACTION]\n if isinstance(v, list):\n self.actions = set(v)\n elif isinstance(v, set):\n self.actions = v\n else:\n self.actions = {actions[v]}\n for v in self.actions:\n if v not in actions:\n raise Exception('invalid action: {}'.format(v))\n field_count += 1\n else:\n self.actions = set()\n\n if SW in data:\n self.stop_word, field_count = DependencyRule._get_re(data, SW, field_count)\n else:\n self.stop_word = None\n\n if DEBUG in data:\n self.debug = data[DEBUG]\n field_count += 1\n else:\n self.debug = False\n\n if INFO in data:\n self.info = data[INFO]\n field_count += 1\n else:\n self.info = None\n\n if field_count != len(data.keys()):\n print('invalid field(s) contained: {}'.format(data.keys() - {\n ARC,\n MAX_HOP,\n LABEL,\n WORD,\n LEMMA,\n POS,\n DEPS,\n ACTION,\n SW,\n DEBUG,\n INFO,\n }), file=sys.stderr)\n\n @staticmethod\n def _content(regexp):\n return str(regexp)[14:-4]\n\n def __str__(self):\n return 'DependencyRule({})'.format(','.join([\n '{}:{}'.format(f, v) if f else str(v) for f, v in [\n kv for kv in [\n ('', self.info),\n ('', self.arc),\n ('max_hop', self.max_hop),\n ('', DependencyRule._content(self.label)),\n ('word', DependencyRule._content(self.word)),\n ('lemma', DependencyRule._content(self.lemma)),\n ('pos', DependencyRule._content(self.pos)),\n ('', str(self.actions) if self.actions else ''),\n ] if kv[1]\n ]\n ]))\n\n def extract_candidates(self, utterance, debug=False):\n for token in utterance:\n matched_tokens = self.check_token(token, 1, {token.i}, debug)\n if matched_tokens is not None:\n return sorted(matched_tokens, key=lambda t: t.i)\n return None\n\n def _indent(self):\n return ' ' * ((self.nest_level + 1) * 4)\n\n def filter_stop_words(self, tokens, debug):\n if not self.stop_word:\n return tokens\n else:\n if debug:\n indent = self._indent()\n else:\n indent = None\n debug and print(indent + 'apply stop_word')\n result = [token for token in tokens if not self.stop_word.match(token.orth_)]\n if len(result) == len(tokens):\n return tokens\n else:\n debug and print(indent + 'stop_word matched: {}'.format(DependencyRule._content(self.stop_word)))\n return result\n\n def match_stop_words(self, token, debug):\n if self.stop_word:\n indent = self._indent() if debug else None\n debug and print(indent + 'apply stop_word')\n if self.stop_word.match(token.orth_.lower()):\n debug and print(indent + 'stop_word matched: {}'.format(DependencyRule._content(self.stop_word)))\n return True\n return False\n\n def check_token(self, token, hop, token_history, debug=False):\n debug = debug or self.debug\n indent = self._indent() if debug else None\n debug and print(indent[2:] + 'check_token({}, {}:{}, {}, {})'.format(\n str(self), token.i, token.orth_, token.lemma_, hop, token_history))\n # check word-level rules\n if (\n not self.word.match(token.orth_.lower())\n ) or (\n not self.lemma.match(token.lemma_.lower())\n ) or (\n not self.pos.match(token.pos_.lower())\n ) or (\n self.match_stop_words(token, debug=debug)\n ):\n debug and print(indent + 'word not matched')\n if not CONTINUE_ON_FAIL <= self.actions:\n debug and print(indent + 'failed')\n return None\n\n debug and print(indent + 'word matched')\n sub_result = []\n if self.deps:\n # dive into sub rules\n for i, sub in enumerate(self.deps):\n sub_result = sub.traverse_dependency(token, 0, token_history, debug)\n if sub_result is not None:\n debug and print(indent + 'traverse_dependency({}, {}) -> {}'.format(\n self,\n token.lemma_,\n [t.lemma_ for t in sub_result],\n ))\n break\n if sub_result is not None:\n debug and print(indent + 'deps matched')\n if FAIL <= self.actions:\n debug and print(indent + 'fail')\n return None\n if USE <= self.actions:\n debug and print(indent + 'use: {}'.format(token.lemma_))\n return self.filter_stop_words([token] + sub_result, debug)\n else:\n return self.filter_stop_words(sub_result, debug)\n else:\n debug and print(indent + 'deps not matched')\n result = [token]\n if POP_ON_FAIL <= self.actions:\n debug and print(indent + 'pop_on_fail: {}'.format([t.lemma_ for t in result]))\n return self.filter_stop_words(result, debug)\n debug and print(indent + 'failed')\n return None\n\n def traverse_dependency(self, token, hop, token_history, debug=False):\n debug = debug or self.debug\n indent = self._indent() if debug else None\n debug and print(indent[2:] + 'traverse_dependency({}, {}, {}, {})'.format(\n self, token.lemma_, hop, token_history))\n hop += 1\n # over max_hop\n if hop > self.max_hop:\n debug and print(indent + 'hop overs {}'.format(self.max_hop))\n return None\n\n if self.arc in [ANCESTORS, PARENT]:\n target = token.head\n debug and print(indent + 'target: {}'.format(target.lemma_))\n # in history\n if target.i in token_history:\n debug and print(indent + 'in history')\n return None\n dep = token.dep_.lower()\n debug and print(indent + '{}>{}>{}'.format(token.lemma_, dep, target.lemma_))\n result = None\n if self.label.match(dep):\n debug and print(indent + 'label matched')\n result = self.check_token(target, hop, token_history | {target.i}, debug)\n if result is None:\n debug and print(indent + 'no result')\n else:\n debug and print(indent + 'label not matched')\n if result is None:\n return self.traverse_dependency(target, hop, token_history | {target.i}, debug)\n if self.arc == PARENT:\n return result\n sub_result = self.traverse_dependency(target, hop, token_history | {target.i}, debug)\n if sub_result is None:\n return result\n else:\n return result + sub_result\n elif self.arc in [DESCENDANT, CHILDREN]:\n all_result = None\n for target in token.children:\n debug and print(indent + 'target: {}'.format(target.lemma_))\n # in history\n if target.i in token_history:\n debug and print(indent + 'in history')\n continue\n dep = target.dep_.lower()\n debug and print(indent + '{}<{}<{}'.format(token.lemma_, dep, target.lemma_))\n if self.label.match(dep):\n debug and print(indent + 'label matched')\n result = self.check_token(target, hop, token_history | {target.i}, debug)\n if result is None:\n debug and print(indent + 'no result')\n else:\n if self.arc == CHILDREN:\n if all_result is None:\n all_result = result\n else:\n all_result += result\n debug and print(indent + 'continue')\n else:\n return result\n else:\n debug and print(indent + 'label not matched')\n return all_result\n else:\n raise Exception('arc must be ancestors, descendants, parent, or children: {}'.format(self.arc))\n\n\ndef parse_rule_maps(json):\n return [DependencyRule(rule) for rule in json]\n\n\ndef import_from_module(module_name):\n module = importlib.import_module(module_name)\n return parse_rule_maps(module.DEPENDENCY_RULES)\n\n\n__all__ = [\n 'DependencyRule',\n 'parse_rule_maps',\n 'import_from_module',\n 'ARC',\n 'ANCESTORS',\n 'DESCENDANT',\n 'PARENT',\n 'CHILDREN',\n 'MAX_HOP',\n 'LABEL',\n 'WORD',\n 'LEMMA',\n 'POS',\n 'ACTION',\n 'USE',\n 'POP',\n 'FAIL',\n 'USE_ON_FAIL',\n 'POP_ON_FAIL',\n 'CONTINUE_ON_FAIL',\n 'GOAL',\n 'GREEDY',\n 'USE_ALWAYS',\n 'POP_ALWAYS',\n 'GOAL_ALWAYS',\n 'DEPS',\n 'SW',\n 'DEBUG',\n 'INFO',\n]\n","sub_path":"ginza_util/dependency_rule.py","file_name":"dependency_rule.py","file_ext":"py","file_size_in_byte":13794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"174741324","text":"import flask\nfrom flask import request, jsonify\nimport sqlite3\nimport uuid\nimport db_util\n\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n@app.route('/', methods=['GET'])\ndef home():\n return '''

    mediaLogic

    \n

    An mediaProcessing API

    '''\n\n@app.route('/api/v1/initiate', methods=['POST'])\ndef initiate():\n task_parameters = request.get_json()\n task_id = str(uuid.uuid1())\n task_type = 'initiate'\n source_file = task_parameters.get('sourceFile')\n\n db_util.insertTask(task_id, task_type, source_file)\n task = db_util.printTask(task_id)\n\n return jsonify(task)\n\n@app.route('/api/v1/encode', methods=['POST'])\ndef encode():\n task_parameters = request.get_json()\n task_id = str(uuid.uuid1())\n task_type = 'encode'\n source_file = task_parameters.get('sourceFile')\n\n db_util.insertTask(task_id, task_type, source_file)\n task = db_util.printTask(task_id)\n\n return jsonify(task)\n\napp.run()\n\n","sub_path":"mediaLogic.py","file_name":"mediaLogic.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"84058572","text":"# python3 test.py [v]\n\nimport sys\nif len(sys.argv) == 2:\n v = sys.argv[1]\nelse:\n v = '1'\n\nname = 'missing-ranges'\nfrom importlib.machinery import SourceFileLoader\nmodule = SourceFileLoader('', name + '.' + v + '.py').load_module()\n\ndef test(s, input, exp):\n print('----------')\n nums, lower, upper = input\n print('nums:', nums)\n print('lower:', lower)\n print('upper:', upper)\n print('expect:', exp)\n res = s.findMissingRanges(nums, lower, upper)\n print('result:', res)\n if exp != res:\n print('--- ERROR ---')\n print()\n\ns = module.Solution()\n\n# -----\ninput = ([], 1, 10)\nexp = ['1->10']\ntest(s, input, exp)\n\n# -----\ninput = ([0, 1, 3, 50, 75], 0, 99)\nexp = ['2', '4->49', '51->74', '76->99']\ntest(s, input, exp)\n","sub_path":"juice/leet/0163/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"234821548","text":"\"\"\"dzenzaba URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom adverts import views\nfrom django.conf import settings\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.conf.urls.static import static\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('i18n/', include('django.conf.urls.i18n')),\n\n\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nurlpatterns += i18n_patterns(\n path('', views.home, name='home'),\n path('search', views.SearchView.as_view(), name=\"global_search\"),\n path('jobs/', include('jobs.urls')),\n path('rents/', include('rents.urls')),\n path('items/', include('items.urls')),\n path('gifts/', include('gifts.urls')),\n path('accounts/', include('account.urls')),\n path('social-auth/', include('social_django.urls', namespace='social')),\n path('', include('sendemail.urls')),\n)\n\n\nif settings.DEBUG:\n import debug_toolbar\n\n urlpatterns = [\n path('__debug__/', include(debug_toolbar.urls)),\n ] + urlpatterns\n\nif 'rosetta' in settings.INSTALLED_APPS:\n urlpatterns += [\n path('rosetta/', include('rosetta.urls'))\n ]\n","sub_path":"zaba/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"164600740","text":"class Polje():\n '''\n Stvori datoteku 2048.py Implementiraj klasu Polje i u njoj metodu __init__().\n Prilikom inicijalizacije polja postavlja se privatni atributi __broj na preneseni broj.\n Ako se nije prenio broj, onda je on 0. Implementiraj \"get\" i \"set\" svojstvo broj koje će vratiti i postaviti broj polja.\n Implementiraj \"get\" svojstva jeBroj, jePrazno koje će vratiti True ili False ako je polje broj ili prazno.\n '''\n\n def __init__(self, broj = 0):\n self.__broj = int(broj)\n\n @property\n def broj(self):\n return self.__broj\n\n @broj.setter\n def broj(self, broj):\n self.__broj = broj\n\n @property\n def jeBroj(self):\n if self.__broj > 1:\n return True\n return False\n\n @property\n def jePrazno(self):\n if self.__broj > 1:\n return False\n return True\n\n\n '''\n Implementiraj stringovnu reprezentaciju __str__() koja će vratiti: broj 'n' ako je broj polja n > 0 točku '.' ako je broj polja = 0 \n Implementiraj reprezentaciju __repr__() koja će vratiti string kojim se stvara objekt od te klase. \n Implementiraj specilajnu metodu __eq__() koja prima parametar other. \n Ova metoda će vratiti True ako je: other instanca od Polje i ako je svojstvo broj od other jednako svojstvu broj \n od self. other cijeli broj (instanca od int) i ako je vrijednost od other jednako svojstvu broj od self. \n U suprotnom će vratiti False \n '''\n\n def __str__(self):\n if self.__broj > 0:\n return \"{}\".format(self.broj)\n else:\n return \".\"\n\n # Vraća string koja predstavlja objekt klase Polje\n def __repr__(self):\n return \"Polje({})\".format(self.broj)\n\n def __eq__(self, other):\n if isinstance(other, Polje) and other.broj == self.broj:\n return True\n elif isinstance(other, int) and other == self.broj:\n return True\n\n return False\n\n\nprint('Zadatak 7.2\\n')\npolja = [Polje(0)] + [Polje(2**broj) for broj in range(1, 12)]\nfor p in polja:\n print(p.broj, p.jeBroj, p.jePrazno)\n\nprint('--------------------------------------------------------------\\n')\n\nprint('Zadatak 7.3\\n')\npolja = [Polje(0)] + [Polje(2**broj) for broj in range(1, 12)]\nfor p in polja:\n print(repr(str(p)), repr(p))\nprint()\n\npolja = [Polje(0)] + [Polje(2**broj) for broj in range(1, 3)]\nelementi = [2, Polje(2), 3, Polje(3)]\nfor el in elementi:\n for p in polja:\n print('%r %r %s' % (el, p, el == p))\n\n\n","sub_path":"vjezba_8/2048/2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"576941596","text":"#standard libraries\nimport torch\nimport numpy as np\n\n\n#%% Transformation functions\ndef image_to_tensor(image, mean=0, std=1.):\n \"\"\"\n \"\"\"\n image = image.astype(np.float32)\n image = np.expand_dims(image,0)\n tensor = torch.from_numpy(image)\n return tensor\n\n\ndef array_to_tensor(array):\n \"\"\"\n \"\"\"\n array = array.astype(np.float32)\n tensor = torch.from_numpy(array).type(torch.FloatTensor)\n return tensor\n\n\nclass WeightedBCELoss2d(torch.nn.Module):\n def __init__(self):\n super(WeightedBCELoss2d, self).__init__()\n\n def forward(self, logits, targets, classweights):\n probs = torch.nn.functional.sigmoid(logits)\n probs_flat = probs.view(-1)\n targets_flat = targets.view(-1)\n loss = classweights[0] * (targets_flat * torch.log(probs_flat + 0.0001)) + classweights[1] * ((1 - targets_flat) * torch.log(1 - probs_flat + 0.0001))\n return torch.neg(loss.sum())\n \n#%%\ndef backproject_probabilities(shape, Yproj=None, Xproj=None, Zproj=None, mode='multiply'):\n ''' \n volume = backproject_probabilities(shape, Yproj=None, Xproj=None, Zproj=None, mode='multiply')\n \n Takes 1-3 two-dimensional probability maps and backprojects them to a common\n volumetric representation. You can choose between 3 different modes:\n - multiply: probabilities are multiplied\n - average: probabilities are averaged\n - voting: like multiplication, but will return 100% for voxels where at least 2 of 3 votes are very strong\n \n Multiply is very clean but will lead to false negatives in cases where on probability is 0 (for some reason)\n even if we have a strong believe from the other two probabilities. Average is also clean, but will lead to\n false positives in dense plots (example: any 100% blob will cause a cross-like corridor where any further 50% \n probability will pass the hurdle even if the third probability is 0%). Voting combines the best of both.\n '''\n yvol = np.zeros(shape) if (Yproj is None) else np.moveaxis(np.asarray([Yproj for y in range(0,shape[0])]),0,0)\n xvol = np.zeros(shape) if (Xproj is None) else np.moveaxis(np.asarray([Xproj for x in range(0,shape[1])]),0,1)\n zvol = np.zeros(shape) if (Zproj is None) else np.moveaxis(np.asarray([Zproj for Z in range(0,shape[2])]),0,2)\n if(mode=='average'):\n return (yvol + xvol + zvol)/3\n elif(mode=='voting'):\n vote1 = yvol * xvol * zvol # accepted if accepted for multiplication\n vote2 = ((yvol + xvol + zvol)/3 > 0.67) # accept if 67% sure on average\n vote3a = (yvol * xvol > 0.9**2) # accept if 2x >90%\n vote3b = (yvol * zvol > 0.9**2) # accept if 2x >90%\n vote3c = (zvol * xvol > 0.9**2) # accept if 2x >90%\n return np.clip((vote1 + vote2 + vote3a + vote3b + vote3c),0,1)\n else:\n return (yvol * xvol * zvol)\n\n\ndef fill_settings(settings):\n \"\"\" Update the rest of unspecified parameters in the configuration list \"\"\"\n\n default_settings = {}\n default_settings['dataset'] = 'Not specified'\n default_settings['dataNormalization'] = 'localmax'\n default_settings['batchSize'] = 4\n default_settings['trafo'] = 'flip_augm'\n default_settings['img_size'] = (300, 300)\n default_settings['epochs'] = 1\n default_settings['learningRate'] = 1e-3\n default_settings['threshold'] = 0.5\n default_settings['validation_size'] = 0.2\n default_settings['savemodel'] = False\n default_settings['BCEWeights'] = [[2, 0.5]]\n default_settings['pretrained'] = None\n default_settings['architecture'] = 'UNet768Deconv'\n \n # Update hyperparameters\n if(settings):\n for key in default_settings.keys():\n if(key not in settings.keys()):\n settings[key] = default_settings[key]\n else:\n settings = default_settings\n\n return settings\n ","sub_path":"code/code_main/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"115417474","text":"import os\r\nimport re\r\nimport json\r\nimport numpy as np\r\nfrom bert import tokenization\r\nfrom bert_config import FLAGS\r\n\r\n\r\nclass InputExample(object):\r\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\r\n\r\n def __init__(self, guid, text, pos_embedding, dp_embedding, head_embedding, label=None):\r\n \"\"\"Constructs a InputExample.\r\n\r\n Args:\r\n guid: Unique id for the example.\r\n text_a: string. The untokenized text of the first sequence. For single\r\n sequence tasks, only this sequence must be specified.\r\n label: (Optional) string. The label of the example. This should be\r\n specified for train and dev examples, but not for test examples.\r\n \"\"\"\r\n self.guid = guid\r\n self.text = text\r\n self.label = label\r\n self.pos_embedding = pos_embedding\r\n self.dp_embedding = dp_embedding\r\n self.head_embedding = head_embedding\r\n\r\n\r\nclass InputFeatures(object):\r\n \"\"\"A single set of features of data.\"\"\"\r\n\r\n def __init__(self, input_ids, input_mask, segment_ids, label_ids, pos_embedding, dp_embedding):\r\n self.input_ids = input_ids\r\n self.input_mask = input_mask\r\n self.segment_ids = segment_ids\r\n self.label_ids = label_ids\r\n self.pos_embedding = pos_embedding\r\n self.dp_embedding = dp_embedding\r\n # # self.label_mask = label_mask\r\n\r\n\r\nclass DataProcessor(object):\r\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\r\n\r\n def get_train_examples(self, data_dir):\r\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n def get_dev_examples(self, data_dir):\r\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n def get_labels(self):\r\n \"\"\"Gets the list of labels for this data set.\"\"\"\r\n raise NotImplementedError()\r\n\r\n @classmethod\r\n def _read_data(cls, input_file): # 这里是对文件的处理\r\n \"\"\"Reads a BIO data.\"\"\"\r\n with open(input_file, encoding='utf-8') as f:\r\n lines = []\r\n\r\n for line in f:\r\n line = json.loads(line)\r\n words = ' '.join(list(line['natural']))\r\n labels = ' '.join(line['tag_seq'])\r\n poss = line['pos_seq']\r\n dps = line['dp_seq']\r\n head = line['head_seq']\r\n lines.append([labels, words, poss, dps, head])\r\n\r\n return lines\r\n\r\n\r\nclass OreProcessor(DataProcessor):\r\n def get_train_examples(self, data_dir):\r\n return self._create_example(\r\n self._read_data(os.path.join(data_dir, \"train.json\")), \"train\"\r\n )\r\n\r\n def get_dev_examples(self, data_dir):\r\n return self._create_example(\r\n self._read_data(os.path.join(data_dir, \"dev.json\")), \"dev\"\r\n )\r\n\r\n def get_test_examples(self, data_dir):\r\n return self._create_example(\r\n self._read_data(os.path.join(data_dir, \"dev.json\")), \"test\")\r\n\r\n def get_labels(self): # 如果改变了这里的标签和训练集的标签,会不会就能进行关系识别\r\n return [\"O\", \"B-E1\", \"I-E1\", \"B-E2\", \"I-E2\", \"B-R\", \"I-R\", \"X\", \"[CLS]\", \"[SEP]\"]\r\n\r\n def valid_labels(self):\r\n return [1, 2, 3, 4, 5, 6]\r\n\r\n def _create_example(self, lines, set_type):\r\n examples = []\r\n for (i, line) in enumerate(lines):\r\n guid = \"%s-%s\" % (set_type, i)\r\n text = tokenization.convert_to_unicode(line[1])\r\n label = tokenization.convert_to_unicode(line[0])\r\n pos_embedding = line[2]\r\n dp_embedding = line[3]\r\n head_embedding = line[4]\r\n examples.append(\r\n InputExample(guid=guid, text=text, label=label, dp_embedding=dp_embedding, head_embedding=head_embedding, pos_embedding=pos_embedding))\r\n return examples\r\n\r\n\r\ndef write_tokens(tokens, mode):\r\n if mode == \"test\":\r\n path = os.path.join(FLAGS.output_dir, \"token_\" + mode + \".txt\")\r\n wf = open(path, 'a')\r\n for token in tokens:\r\n if token != \"**NULL**\":\r\n wf.write(token + '\\n')\r\n wf.close()\r\n\r\n\r\ndef convert_single_example(ex_index, example, pos_mat, dp_mat, head_mat, label_map, max_seq_length, tokenizer, mode): # 此时已经确定为最大长度\r\n textlist = example.text.split(' ')\r\n labellist = example.label.split(' ')\r\n tokens = []\r\n labels = []\r\n # print(textlist)\r\n for i, word in enumerate(textlist):\r\n token = tokenizer.tokenize(word)\r\n # print(token)\r\n tokens.extend(token)\r\n label_1 = labellist[i]\r\n # print(label_1)\r\n for m in range(len(token)):\r\n if m == 0:\r\n labels.append(label_1)\r\n else:\r\n labels.append(\"X\")\r\n # print(tokens, labels) #这里输出保存在record中,basic分词的输出\r\n # tokens = tokenizer.tokenize(example.text)\r\n if len(tokens) >= max_seq_length - 1:\r\n tokens = tokens[0:(max_seq_length - 2)]\r\n labels = labels[0:(max_seq_length - 2)]\r\n ntokens = []\r\n segment_ids = []\r\n label_ids = []\r\n ntokens.append(\"[CLS]\")\r\n segment_ids.append(0)\r\n # append(\"O\") or append(\"[CLS]\") not sure!\r\n label_ids.append(label_map[\"[CLS]\"])\r\n for i, token in enumerate(tokens):\r\n ntokens.append(token)\r\n segment_ids.append(0)\r\n if labels[i] in label_map:\r\n label_ids.append(label_map[labels[i]])\r\n else:\r\n label_ids.append(1)\r\n ntokens.append(\"[SEP]\")\r\n segment_ids.append(0)\r\n # append(\"O\") or append(\"[SEP]\") not sure!\r\n label_ids.append(label_map[\"[SEP]\"])\r\n input_ids = tokenizer.convert_tokens_to_ids(ntokens)\r\n input_mask = [1] * len(input_ids)\r\n # label_mask = [1] * len(input_ids)\r\n while len(input_ids) < max_seq_length:\r\n input_ids.append(0)\r\n input_mask.append(0)\r\n segment_ids.append(0)\r\n # we don't concerned about it!\r\n label_ids.append(0)\r\n ntokens.append(\"**NULL**\")\r\n # label_mask.append(0)\r\n\r\n\r\n\r\n pos_embedding = np.zeros((max_seq_length, 10), dtype=np.float)\r\n for i, p in enumerate(example.pos_embedding):\r\n if i == max_seq_length: # 达到最大长度,截断\r\n break\r\n pos_embedding[i] = pos_mat[p]\r\n\r\n dp_embedding = np.zeros((max_seq_length, 15), dtype=np.float)\r\n for i, p in enumerate(example.dp_embedding):\r\n if i == max_seq_length: # 达到最大长度,截断\r\n break\r\n h = example.head_embedding[i]\r\n if h < max_seq_length:\r\n dp_embedding[i] = np.concatenate((dp_mat[p], head_mat[h]), axis=-1)\r\n else:\r\n pad = np.random.uniform(0, 10, (5,))\r\n dp_embedding[i] = np.concatenate((dp_mat[p], pad), axis=-1)\r\n\r\n assert len(input_ids) == max_seq_length\r\n assert len(input_mask) == max_seq_length\r\n assert len(segment_ids) == max_seq_length\r\n assert len(label_ids) == max_seq_length\r\n assert pos_embedding.shape == (max_seq_length, 10)\r\n assert dp_embedding.shape == (max_seq_length, 15)\r\n # # assert len(label_mask) == max_seq_length\r\n\r\n feature = InputFeatures(\r\n input_ids=input_ids,\r\n input_mask=input_mask,\r\n segment_ids=segment_ids,\r\n label_ids=label_ids,\r\n pos_embedding=pos_embedding,\r\n dp_embedding=dp_embedding\r\n # label_mask = label_mask\r\n )\r\n write_tokens(ntokens, mode)\r\n return feature\r\n\r\n\r\ndef create_dataset(features):\r\n all_input_ids = torch.tensor(\r\n [f.input_ids for f in features], dtype=torch.long)\r\n all_label_ids = torch.tensor(\r\n [f.label_id for f in features], dtype=torch.long)\r\n all_valid_ids = torch.tensor(\r\n [f.valid_ids for f in features], dtype=torch.long)\r\n all_lmask_ids = torch.tensor(\r\n [f.label_mask for f in features], dtype=torch.long)\r\n\r\n return TensorDataset(\r\n all_input_ids, all_label_ids, all_lmask_ids, all_valid_ids)\r\n","sub_path":"utils/data_processor.py","file_name":"data_processor.py","file_ext":"py","file_size_in_byte":8118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"405209216","text":"import os, ConfigParser\n\nimport mediacloud.api\nimport mediameter.cliff\n\nbase_dir = os.path.dirname(os.path.abspath(__file__))\n\ndef get_settings_file_path():\n config_file_path = os.path.join(base_dir,'../','mc-client.config')\n return config_file_path\n\n# load the shared settings file\nsettings = ConfigParser.ConfigParser()\nsettings.read(get_settings_file_path())\n\n# connect to everything\nmc_server = mediacloud.api.AdminMediaCloud(settings.get('mediacloud','key'))\ncliff_server = mediameter.cliff.Cliff(settings.get('cliff','host'),settings.get('cliff','port'))\n","sub_path":"tagexplorer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"327083810","text":"'''\nmodules for open quantum systems\n\n@author: Bing Gu\n@email: bingg@uci.edu\n'''\n\nimport numpy as np\nimport numba\nimport sys\n\nfrom lime.phys import anticommutator, comm, commutator, anticomm, dag, ket2dm, \\\n obs_dm, destroy, rk4\n\nfrom lime.superoperator import lindblad_dissipator, operator_to_superoperator\n\nfrom lime.units import au2fs, au2k\nfrom lime.mol import Mol, Result\n\nfrom scipy.sparse import csr_matrix\nimport scipy.sparse.linalg as la\n\nimport lime.superoperator as superop\n\n\n\nclass Redfield_solver:\n def __init__(self, H, c_ops=None, e_ops=None):\n self.H = None\n self.c_ops = None\n self.e_ops = None\n return\n\n def configure(self, H, c_ops, e_ops):\n self.c_ops = c_ops\n self.e_ops = e_ops\n self.H = H\n return\n\n def evolve(self, rho0, dt, Nt, store_states=False, nout=1):\n '''\n propogate the open quantum dynamics\n\n Parameters\n ----------\n rho0 : TYPE\n DESCRIPTION.\n dt : TYPE\n DESCRIPTION.\n Nt : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n '''\n\n c_ops = self.c_ops\n h0 = self.H\n e_ops = self.e_ops\n\n rho = _redfield(rho0, c_ops, h0, Nt, dt,e_ops, integrator='SOD')\n\n return rho\n\n\nclass OQS(Mol):\n def __init__(self, H, c_ops=None):\n '''\n open quantum systems class\n\n Returns\n -------\n None.\n\n '''\n self.hamiltonian = H\n self.h_sys = H\n self.H = H\n self.nstates = H.shape[-1]\n #self.rho = rho0\n self.e_ops = None\n self.c_ops = None\n\n def set_hamiltonian(self, h):\n self.H = H\n return\n\n def setH(self, h):\n self.H = H\n return\n\n def set_c_ops(self, c_ops):\n self.c_ops = c_ops\n return\n\n def set_e_ops(self, e_ops):\n \"\"\"\n set observable operators\n \"\"\"\n self.e_ops = e_ops\n return\n\n def configure(self, c_ops, e_ops):\n self.c_ops = c_ops\n self.e_ops = e_ops\n return\n\n # def heom(self, env, nado=5, fname=None):\n # nt = self.nt\n # dt = self.dt\n # return _heom(self.oqs, env, self.c_ops, nado, nt, dt, fname)\n\n # def redfield(self, env, dt, Nt, integrator='SOD'):\n # nstates = self.nstates\n # rho0 = self.rho0\n # c_ops = self.c_ops\n # h0 = self.hamiltonian\n # e_ops = self.e_ops\n\n # redfield(nstates, rho0, c_ops, h0, Nt, dt,e_ops, env, integrator='SOD')\n\n # def tcl2(self, env, rho0, dt, Nt, integrator='SOD'):\n # nstates = self.nstates\n # c_ops = self.c_ops\n # h0 = self.hamiltonian\n # e_ops = self.e_ops\n\n # redfield(nstates, rho0, c_ops, h0, Nt, dt,e_ops, env, integrator='SOD')\n\n # return\n\n # def lindblad(self, rho0, dt, Nt):\n # \"\"\"\n # lindblad quantum master equations\n\n # Parameters\n # ----------\n # rho0: 2D array\n # initial density matrix\n # \"\"\"\n # c_ops = self.c_ops\n # e_ops = self.e_ops\n # h0 = self.hamiltonian\n # lindblad(rho0, h0, c_ops, Nt, dt, e_ops)\n # return\n\n\n\n def correlation_2p_1t(self, rho0, ops, dt, Nt, method='lindblad', output='cor.dat'):\n '''\n two-point correlation function \n\n Parameters\n ----------\n rho0 : TYPE\n DESCRIPTION.\n ops : TYPE\n DESCRIPTION.\n dt : TYPE\n DESCRIPTION.\n Nt : TYPE\n DESCRIPTION.\n method : TYPE, optional\n DESCRIPTION. The default is 'lindblad'.\n output : TYPE, optional\n DESCRIPTION. The default is 'cor.dat'.\n\n Returns\n -------\n None.\n\n '''\n\n H = self.hamiltonian\n c_ops = self.c_ops\n\n correlation_2p_1t(H, rho0, ops=ops, c_ops=c_ops, dt=dt,\\\n Nt=Nt, method=method, output=output)\n\n return\n\n # def tcl2(self):\n # \"\"\"\n # second-order time-convolutionless quantum master equation\n # \"\"\"\n # pass\n\ndef liouvillian(rho, H, c_ops):\n \"\"\"\n lindblad quantum master eqution\n \"\"\"\n rhs = -1j * comm(H, rho)\n for c_op in c_ops:\n rhs += lindbladian(c_op, rho)\n return rhs\n\ndef lindbladian(l, rho):\n \"\"\"\n lindblad superoperator: l rho l^\\dag - 1/2 * {l^\\dag l, rho}\n l is the operator corresponding to the disired physical process\n e.g. l = a, for the cavity decay and\n l = sm for polarization decay\n \"\"\"\n return l.dot(rho.dot(dag(l))) - 0.5 * anticomm(dag(l).dot(l), rho)\n\n#@numba.jit\ndef _correlation_2p_1t(H, rho0, ops, c_ops, dt, Nt, method='lindblad', output='cor.dat'):\n \"\"\"\n compute the time-translation invariant two-point correlation function in the\n density matrix formalism using quantum regression theorem\n\n = Tr[ A U(t) (B rho0) U^\\dag(t)]\n\n input:\n ========\n H: 2d array\n full Hamiltonian\n\n rho0: initial density matrix\n\n ops: list of operators [A, B] for computing the correlation functions\n\n method: str\n dynamics method e.g. lindblad, redfield, heom\n\n args: dictionary of parameters for dynamics\n\n Returns\n ========\n the density matrix is stored in 'dm.dat'\n 'cor.dat': the correlation function is stored\n \"\"\"\n #nstates = H.shape[-1] # number of states in the system\n\n # initialize the density matrix\n A, B = ops\n rho = B.dot(rho0)\n\n f = open(output, 'w')\n # f_dm = open('dm.dat', 'w')\n # fmt = '{} ' * (H.size + 1) + '\\n' # format to store the density matrix\n\n # dynamics\n\n t = 0.0\n cor = np.zeros(Nt, dtype=complex)\n\n # sparse matrix\n H = csr_matrix(H)\n rho = csr_matrix(rho)\n\n A = csr_matrix(A)\n\n c_ops_sparse = [csr_matrix(c_op) for c_op in c_ops]\n\n if method == 'lindblad':\n\n for k in range(Nt):\n\n t += dt\n\n rho = rk4(rho, liouvillian, dt, H, c_ops_sparse)\n\n # cor = A.dot(rho).diagonal().sum()\n tmp = obs_dm(rho, A)\n cor[k] = tmp\n # store the reduced density matrix\n f.write('{} {} \\n'.format(t, tmp))\n\n # f_dm.write(fmt.format(t, *np.ravel(rho)))\n\n # f_dm.write(fmt.format(t, *np.ravel(rho.toarray())))\n\n else:\n sys.exit('The method {} has not been implemented yet! Please \\\n try lindblad.'.format(method))\n\n f.close()\n # f_dm.close()\n\n return cor\n\nclass Env:\n def __init__(self, temperature, cutoff, reorg):\n self.temperature = temperature\n self.cutoff = cutoff\n self.reorg = reorg\n\n def set_bath_ops(self, bath_ops):\n \"\"\"\n\n\n Parameters\n ----------\n bath_ops : list of 2d arrays\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n self.bath_ops = bath_ops\n return\n\n def corr(self):\n \"\"\"\n compute the correlation function for bath operators\n \"\"\"\n pass\n\n def spectral_density(self):\n \"\"\"\n spectral density\n \"\"\"\n pass\n\n\n\n@numba.jit\ndef func(rho, h0, c_ops, l_ops):\n \"\"\"\n right-hand side of the master equation\n \"\"\"\n rhs = -1j * commutator(h0, rho)\n\n for i in range(len(c_ops)):\n c_op = c_ops[i]\n l_op = l_ops[i]\n rhs -= commutator(c_op, l_op.dot(rho) - rho.dot(dag(l_op)))\n return rhs\n\n\n\n\n\ndef coherent(N, alpha):\n \"\"\"Generates a coherent state with eigenvalue alpha.\n\n Constructed using displacement operator on vacuum state.\n\n Modified from Qutip.\n\n Parameters\n ----------\n N : int\n Number of Fock states in Hilbert space.\n\n alpha : float/complex\n Eigenvalue of coherent state.\n\n offset : int (default 0)\n The lowest number state that is included in the finite number state\n representation of the state. Using a non-zero offset will make the\n default method 'analytic'.\n\n method : string {'operator', 'analytic'}\n Method for generating coherent state.\n\n Returns\n -------\n state : qobj\n Qobj quantum object for coherent state\n\n Examples\n --------\n >>> coherent(5,0.25j)\n Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket\n Qobj data =\n [[ 9.69233235e-01+0.j ]\n [ 0.00000000e+00+0.24230831j]\n [ -4.28344935e-02+0.j ]\n [ 0.00000000e+00-0.00618204j]\n [ 7.80904967e-04+0.j ]]\n\n Notes\n -----\n Select method 'operator' (default) or 'analytic'. With the\n 'operator' method, the coherent state is generated by displacing\n the vacuum state using the displacement operator defined in the\n truncated Hilbert space of size 'N'. This method guarantees that the\n resulting state is normalized. With 'analytic' method the coherent state\n is generated using the analytical formula for the coherent state\n coefficients in the Fock basis. This method does not guarantee that the\n state is normalized if truncated to a small number of Fock states,\n but would in that case give more accurate coefficients.\n\n \"\"\"\n\n x = basis(N, 0)\n a = destroy(N)\n D = la.expm(alpha * dag(a) - np.conj(alpha) * a)\n\n return D @ x\n\n # elif method == \"analytic\" or offset > 0:\n\n # data = np.zeros([N, 1], dtype=complex)\n # n = arange(N) + offset\n # data[:, 0] = np.exp(-(abs(alpha) ** 2) / 2.0) * (alpha ** (n)) / \\\n # _sqrt_factorial(n)\n # return Qobj(data)\n\n # else:\n # raise TypeError(\n # \"The method option can only take values 'operator' or 'analytic'\")\n\n\n\ndef coherent_dm(N, alpha):\n \"\"\"Density matrix representation of a coherent state.\n\n Constructed via outer product of :func:`qutip.states.coherent`\n\n Parameters\n ----------\n N : int\n Number of Fock states in Hilbert space.\n\n alpha : float/complex\n Eigenvalue for coherent state.\n\n offset : int (default 0)\n The lowest number state that is included in the finite number state\n representation of the state.\n\n method : string {'operator', 'analytic'}\n Method for generating coherent density matrix.\n\n Returns\n -------\n dm : qobj\n Density matrix representation of coherent state.\n\n Examples\n --------\n >>> coherent_dm(3,0.25j)\n Quantum object: dims = [[3], [3]], \\\nshape = [3, 3], type = oper, isHerm = True\n Qobj data =\n [[ 0.93941695+0.j 0.00000000-0.23480733j -0.04216943+0.j ]\n [ 0.00000000+0.23480733j 0.05869011+0.j 0.00000000-0.01054025j]\n [-0.04216943+0.j 0.00000000+0.01054025j 0.00189294+0.j\\\n ]]\n\n Notes\n -----\n Select method 'operator' (default) or 'analytic'. With the\n 'operator' method, the coherent density matrix is generated by displacing\n the vacuum state using the displacement operator defined in the\n truncated Hilbert space of size 'N'. This method guarantees that the\n resulting density matrix is normalized. With 'analytic' method the coherent\n density matrix is generated using the analytical formula for the coherent\n state coefficients in the Fock basis. This method does not guarantee that\n the state is normalized if truncated to a small number of Fock states,\n but would in that case give more accurate coefficients.\n\n \"\"\"\n #if method == \"operator\":\n psi = coherent(N, alpha)\n\n return ket2dm(psi)\n\n # elif method == \"analytic\":\n # psi = coherent(N, alpha, offset=offset, method='analytic')\n # return psi * psi.dag()\n\n # else:\n # raise TypeError(\n # \"The method option can only take values 'operator' or 'analytic'\")\n\n\n\ndef make_lambda(ns, h0, S, T, cutfreq, reorg):\n\n tmax = 1000.0\n print('time range to numericall compute the bath correlation function = [0, {}]'.format(tmax))\n print('Decay of correlation function at {} fs = {} \\n'.format(tmax * au2fs, \\\n corr(tmax, T, cutfreq, reorg)/corr(0., T, cutfreq, reorg)))\n print('!!! Please make sure this is much less than 1 !!!')\n\n time = np.linspace(0, tmax, 10000)\n dt = time[1] - time[0]\n dt2 = dt/2.0\n\n\n l = np.zeros((ns, ns), dtype=np.complex128)\n\n #t = time[0]\n #phi = hop * t - Delta * np.sin(omegad * t)/omegad\n #Lambda += corr(t) * (np.sin(2. * phi) * sigmay + np.cos(2. * phi) * sigmaz) * dt2\n\n #h0 = Hamiltonian()\n Sint = S.copy()\n\n for k in range(len(time)):\n\n t = time[k]\n\n Sint += -1j * commutator(S, h0) * (-dt)\n l += dt * Sint * corr(t, T, cutfreq, reorg)\n\n# t = time[len(time)-1]\n# phi = hop * t + Delta * np.sin(omegad * t)/omegad\n# Lambda += corr(t) * (np.sin(2. * phi) * sigmay + np.cos(2. * phi) * sigmaz) * dt2\n# Lambda = cy * sigmay + cz * sigmaz\n\n return l\n\n\n\ndef _redfield(nstates, rho0, c_ops, h0, Nt, dt,e_ops, env):\n \"\"\"\n time propagation of the Redfield equation with second-order differencing\n input:\n nstate: total number of states\n h0: system Hamiltonian\n Nt: total number of time steps\n dt: tiem step\n c_ops: list of collapse operators\n e_ops: list of observable operators\n rho0: initial density matrix\n \"\"\"\n t = 0.0\n\n print('Total number of states in the system = {}'.format(nstates))\n\n # initialize the density matrix\n rho = rho0\n\n # properties of the environment\n T = env.T\n cutfreq = env.cutfreq\n reorg = env.reorg\n\n #f = open(fname,'w')\n fmt = '{} '* (len(e_ops) + 1) + '\\n'\n\n # construct system-bath operators in H_SB\n\n # short time approximation\n # Lambda = 0.5 * reorg * T * ((hop - Delta)/cutfreq**2 * sigmay + 1./cutfreq * sigmaz)\n\n # constuct the Lambda operators needed in Redfield equation\n l_ops = []\n for c_op in c_ops:\n l_ops.append(getLambda(nstates, h0, c_op, T, cutfreq, reorg))\n\n f_dm = open('den_mat.dat', 'w')\n f_obs = open('obs.dat', 'w')\n\n t = 0.0\n dt2 = dt/2.0\n\n # first-step\n rho_half = rho0 + func(rho0, h0, c_ops, l_ops) * dt2\n rho1 = rho0 + func(rho_half, h0, c_ops, l_ops) * dt\n\n rho_old = rho0\n rho = rho1\n\n for k in range(Nt):\n\n t += dt\n\n rho_new = rho_old + func(rho, h0, c_ops, l_ops) * 2. * dt\n\n # update rho_old\n rho_old = rho\n rho = rho_new\n\n # dipole-dipole auto-corrlation function\n #cor = np.trace(np.matmul(d, rho))\n\n # store the reduced density matrix\n f_dm.write('{} '* (nstates**2 + 1) + '\\n'.format(t, *rho))\n\n # take a partial trace to obtain the rho_el\n obs = np.zeros(len(e_ops))\n for i, obs_op in enumerate(e_ops):\n obs[i] = observe(obs_op, rho)\n\n f_obs.write(fmt.format(t * au2fs, *obs))\n\n\n f_obs.close()\n f_dm.close()\n\n return rho\n\n@numba.jit\ndef observe(A, rho):\n \"\"\"\n compute expectation value of the operator A\n \"\"\"\n return A.dot(rho).diagonal().sum()\n\nclass Lindblad_solver():\n def __init__(self, H=None, c_ops=None, e_ops=None):\n self.c_ops = c_ops\n self.e_ops = e_ops\n self.H = H\n return\n\n def set_c_ops(self, c_ops):\n self.c_ops = c_ops\n return\n\n def set_e_ops(self, e_ops):\n \"\"\"\n set observable operators\n \"\"\"\n self.e_ops = e_ops\n return\n\n def setH(self, H):\n self.H = H\n return\n\n def configure(self, c_ops, e_ops):\n self.c_ops = c_ops\n self.e_ops = e_ops\n return\n \n def liouvillian(self):\n H = self.H\n c_ops = self.c_ops\n return superop.liouvillian(H, c_ops)\n\n def steady_states(self):\n pass\n\n def evolve(self, rho0, dt, Nt, return_result):\n return _lindblad(rho0, self.H, self.c_ops, e_ops=self.e_ops, \\\n Nt=Nt, dt=dt, return_result=return_result)\n\n def correlation_2p_1t(self, rho0, a_op, b_op, dt, Nt, output='cor.dat'):\n '''\n two-point correlation function \n\n Parameters\n ----------\n rho0 : TYPE\n DESCRIPTION.\n ops : TYPE\n DESCRIPTION.\n dt : TYPE\n DESCRIPTION.\n Nt : TYPE\n DESCRIPTION.\n method : TYPE, optional\n DESCRIPTION. The default is 'lindblad'.\n output : TYPE, optional\n DESCRIPTION. The default is 'cor.dat'.\n\n Returns\n -------\n None.\n\n '''\n\n c_ops = self.c_ops\n H = self.H\n\n return _correlation_2p_1t(H, rho0, ops=[a_op, b_op], c_ops=c_ops, dt=dt,\\\n Nt=Nt, output=output)\n\n def correlation_3op_2t(self, rho0, ops, dt, Nt, Ntau):\n \"\"\"\n Internal function for calculating the three-operator two-time\n correlation function:\n \n using the Linblad master equation solver.\n \"\"\"\n\n # the solvers only work for positive time differences and the correlators\n # require positive tau\n # if state0 is None:\n # rho0 = steadystate(H, c_ops)\n # tlist = [0]\n # elif isket(state0):\n # rho0 = ket2dm(state0)\n # else:\n # rho0 = state0\n H = self.H\n c_ops = self.c_ops\n rho_t = _lindblad(H, rho0, c_ops, dt=dt, Nt=Nt, return_result=True).rholist\n\n a_op, b_op, c_op = ops\n\n corr_mat = np.zeros([Nt, Ntau], dtype=complex)\n\n for t_idx, rho in enumerate(rho_t):\n\n corr_mat[t_idx, :] = _lindblad(H, rho0=c_op @ rho @ a_op, \\\n dt=dt, Nt=Ntau, c_ops=c_ops,\\\n e_ops=[b_op], return_result=True).observables[:,0]\n\n return corr_mat\n\n def correlation_4op_2t(self, rho0, ops, dt, nt, ntau):\n \"\"\"\n Internal function for calculating the four-operator two-time\n correlation function:\n \n using the Linblad master equation solver.\n \"\"\"\n\n if len(ops) != 4:\n raise ValueError('Number of operators is not 4.')\n else:\n a, b, c, d = ops\n\n corr = self.correlation_3op_2t(rho0, [a, b@c, d], dt, nt, ntau)\n return corr\n\n\n\nclass HEOMSolverDL():\n def __init__(self, H=None, c_ops=None, e_ops=None):\n self.c_ops = c_ops\n self.e_ops = e_ops\n self.e_ops = e_ops\n self.H = H\n return\n\n def set_c_ops(self, c_ops):\n self.c_ops = c_ops\n return\n\n def set_e_ops(self, e_ops):\n \"\"\"\n set observable operators\n \"\"\"\n self.e_ops = e_ops\n return\n\n def set_e_ops(self, e_ops):\n \"\"\"\n set observable operators\n \"\"\"\n self.e_ops = e_ops\n return\n def setH(self, H):\n self.H = H\n return\n\n def configure(self, c_ops, e_ops):\n self.c_ops = c_ops\n self.e_ops = e_ops\n return\n\n def solve(self, rho0, dt, Nt, return_result):\n return _lindblad(self.H, rho0, self.c_ops, e_ops=self.e_ops, \\\n Nt=Nt, dt=dt, return_result=return_result)\n\n def correlation_2p_1t(self, rho0, a_op, b_op, dt, Nt, output='cor.dat'):\n '''\n two-point correlation function \n\n Parameters\n ----------\n rho0 : TYPE\n DESCRIPTION.\n ops : TYPE\n DESCRIPTION.\n dt : TYPE\n DESCRIPTION.\n Nt : TYPE\n DESCRIPTION.\n method : TYPE, optional\n DESCRIPTION. The default is 'lindblad'.\n output : TYPE, optional\n DESCRIPTION. The default is 'cor.dat'.\n\n Returns\n -------\n None.\n\n '''\n\n c_ops = self.c_ops\n H = self.H\n\n return _correlation_2p_1t(H, rho0, ops=[a_op, b_op], c_ops=c_ops, dt=dt,\\\n Nt=Nt, output=output)\n\n\n def correlation_3op_2t(self, rho0, ops, dt, Nt, Ntau):\n \"\"\"\n Internal function for calculating the three-operator two-time\n correlation function:\n \n using the Linblad master equation solver.\n \"\"\"\n\n # the solvers only work for positive time differences and the correlators\n # require positive tau\n # if state0 is None:\n # rho0 = steadystate(H, c_ops)\n # tlist = [0]\n # elif isket(state0):\n # rho0 = ket2dm(state0)\n # else:\n # rho0 = state0\n H = self.H\n c_ops = self.c_ops\n rho_t = _lindblad(H, rho0, c_ops, dt=dt, Nt=Nt, return_result=True).rholist\n\n a_op, b_op, c_op = ops\n\n corr_mat = np.zeros([Nt, Ntau], dtype=complex)\n\n for t_idx, rho in enumerate(rho_t):\n\n corr_mat[t_idx, :] = _lindblad(H, rho0=c_op @ rho @ a_op, \\\n dt=dt, Nt=Ntau, c_ops=c_ops,\\\n e_ops=[b_op], return_result=True).observables[:,0]\n\n return corr_mat\n# exponential series solvers\n\n# def _correlation_es_2t(H, state0, tlist, taulist, c_ops, a_op, b_op, c_op):\n# \"\"\"\n# Internal function for calculating the three-operator two-time\n# correlation function:\n# \n# using an exponential series solver.\n# \"\"\"\n\n# # the solvers only work for positive time differences and the correlators\n# # require positive tau\n# if state0 is None:\n# rho0 = steadystate(H, c_ops)\n# tlist = [0]\n# elif isket(state0):\n# rho0 = ket2dm(state0)\n# else:\n# rho0 = state0\n\n# if debug:\n# print(inspect.stack()[0][3])\n\n# # contruct the Liouvillian\n# L = liouvillian(H, c_ops)\n\n# corr_mat = np.zeros([np.size(tlist), np.size(taulist)], dtype=complex)\n# solES_t = ode2es(L, rho0)\n\n# # evaluate the correlation function\n# for t_idx in range(len(tlist)):\n# rho_t = esval(solES_t, [tlist[t_idx]])\n# solES_tau = ode2es(L, c_op * rho_t * a_op)\n# corr_mat[t_idx, :] = esval(expect(b_op, solES_tau), taulist)\n\n# return corr_mat\n\ndef _lindblad(H, rho0, c_ops, Nt, dt, e_ops=[], return_result=True):\n\n \"\"\"\n time propagation of the lindblad quantum master equation\n with second-order differencing\n\n Input\n -------\n h0: 2d array\n system Hamiltonian\n Nt: total number of time steps\n\n dt: time step\n c_ops: list of collapse operators\n e_ops: list of observable operators\n rho0: initial density matrix\n\n Returns\n =========\n rho: 2D array\n density matrix at time t = Nt * dt\n \"\"\"\n\n nstates = H.shape[-1]\n # initialize the density matrix\n rho = rho0\n\n t = 0.0\n # first-step\n # rho_half = rho0 + liouvillian(rho0, h0, c_ops) * dt2\n # rho1 = rho0 + liouvillian(rho_half, h0, c_ops) * dt\n\n # rho_old = rho0\n # rho = rho1\n if return_result == False:\n\n f_dm = open('den_mat.dat', 'w')\n fmt_dm = '{} ' * (nstates**2 + 1) + '\\n'\n\n f_obs = open('obs.dat', 'w')\n fmt = '{} '* (len(e_ops) + 1) + '\\n'\n\n for k in range(Nt):\n\n t += dt\n\n # rho_new = rho_old + liouvillian(rho, h0, c_ops) * 2. * dt\n # # update rho_old\n # rho_old = rho\n # rho = rho_new\n\n rho = rk4(rho, liouvillian, dt, H, c_ops)\n\n # dipole-dipole auto-corrlation function\n #cor = np.trace(np.matmul(d, rho))\n\n # take a partial trace to obtain the rho_el\n # compute observables\n observables = np.zeros(len(e_ops), dtype=complex)\n\n for i, obs_op in enumerate(e_ops):\n observables[i] = obs_dm(rho, obs_op)\n\n f_obs.write(fmt.format(t, *observables))\n\n\n f_obs.close()\n f_dm.close()\n\n return rho\n\n else:\n\n rholist = [] # store density matries\n\n result = Result(dt=dt, Nt=Nt, rho0=rho0)\n\n observables = np.zeros((Nt, len(e_ops)), dtype=complex)\n\n for k in range(Nt):\n\n t += dt\n rho = rk4(rho, liouvillian, dt, H, c_ops)\n\n rholist.append(rho)\n\n observables[k, :] = [obs_dm(rho, op) for op in e_ops]\n\n result.observables = observables\n result.rholist = rholist\n\n return result\n\ndef _heom_dl(H, rho0, c_ops, e_ops, temperature, cutoff, reorganization,\\\n nado, dt, nt, fname=None, return_result=True):\n '''\n\n terminator : ado[:,:,nado] = 0\n\n INPUT:\n T: in units of energy, kB * T, temperature of the bath\n reorg: reorganization energy\n nado : auxiliary density operators, truncation of the hierachy\n fname: file name for output\n\n '''\n nst = H.shape[0]\n ado = np.zeros((nst, nst, nado), dtype=np.complex128) # auxiliary density operators\n ado[:,:,0] = rho0 # initial density matrix\n\n\n\n gamma = cutoff # cutoff frequency of the environment, larger gamma --> more Makovian\n T = temperature/au2k\n reorg = reorganization\n print('Temperature of the environment = {}'.format(T))\n print('High-Temperature check gamma/(kT) = {}'.format(gamma/T))\n\n if gamma/T > 0.8:\n print('WARNING: High-Temperature Approximation may fail.')\n\n print('Reorganization energy = {}'.format(reorg))\n\n # D(t) = (a + ib) * exp(- gamma * t)\n a = np.pi * reorg * T # initial value of the correlation function D(0) = pi * lambda * kB * T\n b = 0.0\n print('Amplitude of the fluctuations = {}'.format(a))\n\n #sz = np.zeros((nstate, nstate), dtype=np.complex128)\n sz = c_ops # collapse opeartor\n\n\n f = open(fname,'w')\n fmt = '{} '* 5 + '\\n'\n\n # propagation time loop - HEOM\n t = 0.0\n for k in range(nt):\n\n t += dt # time increments\n\n ado[:,:,0] += -1j * commutator(H, ado[:,:,0]) * dt - \\\n commutator(sz, ado[:,:,1]) * dt\n\n for n in range(nado-1):\n ado[:,:,n] += -1j * commutator(H, ado[:,:,n]) * dt + \\\n (- commutator(sz, ado[:,:,n+1]) - n * gamma * ado[:,:,n] + n * \\\n (a * commutator(sz, ado[:,:,n-1]) + \\\n 1j * b * anticommutator(sz, ado[:,:,n-1]))) * dt\n\n # store the reduced density matrix\n f.write(fmt.format(t, ado[0,0,0], ado[0,1,0], ado[1,0,0], ado[1,1,0]))\n\n #sz += -1j * commutator(sz, H) * dt\n\n f.close()\n return ado[:,:,0]\n\nif __name__ == '__main__':\n\n from lime.phys import pauli\n s0, sx, sy, sz = pauli()\n\n H = 2 * np.pi * 0.1 * sx\n\n psi0 = basis(2, 0)\n rho0 = ket2dm(psi0)\n\n mesolver = Lindblad_solver(H, c_ops=[0.2 * sx], e_ops = [sz])\n Nt = 200\n dt = 0.05\n \n L = mesolver.liouvillian()\n \n #result = mesolver.evolve(rho0, dt, Nt=Nt, return_result=True)\n #corr = mesolver.correlation_3op_2t(rho0, [sz, sz, sz], dt, Nt, Ntau=Nt)\n \n\n \n # from lime.style import subplots\n # fig, ax = subplots()\n # times = np.arange(Nt) * dt\n # ax.imshow(corr.real)\n","sub_path":"lime/oqs.py","file_name":"oqs.py","file_ext":"py","file_size_in_byte":26860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"620544502","text":"#!/usr/bin/env python3\n\nfrom flask import Flask\nfrom flask_restplus import Resource, Api, fields\nfrom werkzeug.exceptions import BadRequest\n\nfrom .user import User\nfrom .group import Group, jobs, history\n\ndef create_app():\n app = Flask(__name__) # Create a Flask WSGI appliction\n api = Api(app, default_mediatype='text/plain') # Create a Flask-RESTPlus API\n\n @api.route('/jobs/', methods=['GET'])\n class Jobs(Resource):\n def get(self):\n return {\n \"history\": [dict((k,h[k]) for k in h if k != 'thread') for h in history],\n \"jobs\": dict([(op, dict((k,jobs[op][k]) for k in jobs[op] if k != 'thread')) for op in jobs]),\n }\n\n @api.route('/group/')\n class GroupRoute(Resource):\n def get(self):\n \"\"\"Lista todos os grupos\"\"\"\n try:\n return {\n 'groups': Group.listAll(),\n }\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/group/')\n class GroupNewRoute(Resource):\n def get(self, group):\n \"\"\"Lista membros do grupo\"\"\"\n try:\n return Group(group).users()\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.representation('text/plain')\n def post(self, group):\n \"\"\"Cria novo grupo\"\"\"\n try:\n Group(group).create()\n return ('', 204)\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/group//permissions')\n class GroupPermsRoute(Resource):\n @api.representation('text/plain')\n def post(self, group):\n \"\"\"Verifica e corrige permissoes do grupo\"\"\"\n try:\n return Group(group).permissions()\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/user/')\n class UserListRoute(Resource):\n def get(self):\n \"\"\"Lista todos os usuarios\"\"\"\n try:\n return {\n 'users': User.listAll(),\n }\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/user/')\n class UserCreateRoute(Resource):\n def get(self, login):\n \"\"\"Lista grupos do usuario\"\"\"\n try:\n return {\n 'user': login,\n 'groups': User(login).groups(),\n }\n except Exception as e:\n raise BadRequest(str(e))\n @api.representation('text/plain')\n def post(self, login):\n \"\"\"Cria novo usuario\"\"\"\n try:\n User(login).create()\n return ('', 204)\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/user//group/')\n class UserGroupRoute(Resource):\n @api.representation('text/plain')\n def post(self, login, group):\n \"\"\"Adiciona usuario ao grupo\"\"\"\n try:\n User(login).enterGroup(group)\n return ('', 204)\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/user//home')\n class UserHomeRoute(Resource):\n @api.representation('text/plain')\n def post(self, login):\n \"\"\"Verifica e corrige pasta home do usuario\"\"\"\n try:\n User(login).populateHome()\n return ('', 204)\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/user//permissions')\n class UserPermissionsRoute(Resource):\n @api.representation('text/plain')\n def post(self, login):\n \"\"\"Verifica e corrige permissoes do usuario\"\"\"\n try:\n User(login).permissions()\n return ('', 204)\n except Exception as e:\n raise BadRequest(str(e))\n\n @api.route('/user//reset_password')\n class UserPasswordRoute(Resource):\n @api.representation('text/plain')\n @api.expect(api.model('data', {\n \"password\": fields.String(required=False, description='password'),\n }))\n def post(self, login):\n \"\"\"Altera a senha do usuario. Se a senha for \"\", uma senha aleatoria sera criada.\"\"\"\n try:\n return {\n \"password\": User(login).resetPassword(api.payload['password'])\n }\n except Exception as e:\n raise BadRequest(str(e))\n return app\n","sub_path":"sardadmin/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"614726162","text":"import sys\nimport math\n\ndef solution(numbers):\n numbers.sort()\n for i in range(len(numbers) - 1): #정렬되어 있으므로 i번째는 i+1번째와만 비교해보면 된다\n if numbers[i] in numbers[i+1][0:len(numbers[i])]:\n print(\"NO\")\n return False\n print(\"YES\")\n return True\n\n\nnumbers = []\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n for _ in range(n):\n numbers.append(input())\n solution(numbers)\n numbers.clear()","sub_path":"Algorithm/BOJ/[5052] 전화번호 목록.py","file_name":"[5052] 전화번호 목록.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"387723337","text":"\"\"\"\ndistribution.py\nAuthor: Payton\nCredit: Avery, Daniel, Mr. Dennison, Morgan\n\nAssignment:\n\nWrite and submit a Python program (distribution.py) that computes and displays \nthe distribution of characters in a given sample of text.\n\nOutput of your program should look like this:\n\nPlease enter a string of text (the bigger the better): The rain in Spain stays mainly in the plain.\nThe distribution of characters in \"The rain in Spain stays mainly in the plain.\" is:\niiiiii\nnnnnnn\naaaaa\nsss\nttt\nee\nhh\nll\npp\nyy\nm\nr\n\nNotice about this example:\n\n* The text: 'The rain ... plain' is provided by the user as input to your program.\n* Uppercase characters are converted to lowercase\n* Spaces and punctuation marks are ignored completely.\n* Characters that are more common appear first in the list.\n* Where the same number of characters occur, the lines are ordered alphabetically. \n For example, in the printout above, the letters e, h, l, p and y both occur twice \n in the text and they are listed in the output in alphabetical order.\n* Letters that do not occur in the text are not listed in the output at all.\n\"\"\"\no = str(input(\"Please enter a string of text (the bigger the better): \"))\nprint('The distribution of characters in \"' + o + '\" is: ')\n\norig = o.lower()\nalph = \"abcdefghijklmnopqrstuvwxyz\"\nresults = []\nlistnum = []\n\nfor c in alph:\n r = orig.count(c)\n if not r == 0:\n t = (r*c)\n results.append(t)\n listnum.append(r)\n\nlists=zip(listnum,results)\nlists = sorted(lists, key=lambda listnum: (-listnum[0], listnum[1])) \nl=len([x[1] for x in lists])\nfor y in range(0, l):\n if not y==y+1:\n a=list([r[1] for r in lists])\n print(a[y])\n ","sub_path":"distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"92597674","text":"class aa:\n w = 10\n def __init__(self):\n self.x = 11\n self.y = 12\n def add(self):\n return self.x + self.y\n\na = aa()\nprint(a.add())\n\naa.w = 20\na.w = 13\nprint(aa.w, a.w)\n\na.t = 14\na.q = 15\nprint(a.t, a.q)\n\naa.m = 30\naa.n = 40\nprint(aa.m, aa.n)\n\nb = aa()\nprint(b.x,b.y)\nprint( b.m,b.n)\n#print(b.t,b.q)\n\nprint(aa.__dict__.keys())\ndel aa.m\nprint(aa.__dict__.keys())\n","sub_path":"oop_basic2.py","file_name":"oop_basic2.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"61719652","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 11 22:14:07 2021\n\n@author: Philippe\n\"\"\"\n\nimport genetic_algorithm\n\n\n\nsubjectList = []\n\nsample_input = [\"Fil 40 \", \"CW 10 \", \"CoE 115 TJK\", \"CoE 115 HWX\", \"CWTS 2 Engg DCS\", \"Math 10 \", \"Archaeo 2 \"]\nsample_input = [\"Socio 198\"]\nlength = len(sample_input)\nmycsv = genetic_algorithm.load_csv()\n\npossible_subjects = []\nfor input in sample_input:\n newSubject = genetic_algorithm.Subject(input)\n possible_subjects.append(genetic_algorithm.filter_subject(mycsv, input))\n for index, row in genetic_algorithm.filter_subject(mycsv, input).iterrows():\n if (row['professor'] == \"TBA\" or row['professor'] == \"CONCEALED\"):\n row['professor'] = \"TBA, TBA2\"\n print(row['professor'])\n newCourse = genetic_algorithm.Course(row['course number'], row['name'], row['professor'], row['schedule'].split(' ')[1])\n newCourse._meetingDay = genetic_algorithm.parse_schedule(row['schedule'].split(' ')[0])\n newSubject._courses.append(newCourse)\n subjectList.append(newSubject)\n \n \ntry:\n final_list = genetic_algorithm.genetic_algorithm(subjectList)\n print(final_list)\nexcept:\n print(\"Something went wrong...\")\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"506375436","text":"from pymongo import MongoClient\nfrom bson.code import Code\n\n\nreduce = Code(\"function (key, values) {\"\n \" var total = 0;\"\n \" for (var i = 0; i < values.length; i++) {\"\n \" total += values[i];\"\n \" }\"\n \" return total;\"\n \"}\")\n\n\ndef cuenta_tweets():\n mapper = Code(\"function () {\"\n \"var tweets = this.id;\" \n \"emit(tweets, 1);\"\n \"}\")\n return mapper\n\n\ndef cuenta_replys():\n mapper = Code(\"function () {\" \n \"var tweet_replys = this.replys;\"\n \"tweet_replys.forEach(function(y) {\"\n \"emit(y['id'], 1);\"\n \"});\" \n \"}\")\n \n return mapper\n\ndef cuenta_quotes():\n mapper = Code(\"function () {\" \n \"var tweet_quotes = this.quotes;\"\n \"tweet_quotes.forEach(function(y) {\"\n \"emit(y['id'], 1);\"\n \"});\" \n \"}\")\n \n return mapper\n\n\ndef cuenta_total():\n while True:\n try:\n client = MongoClient(\"mongodb://bigdata-mongodb-04.virtual.uniandes.edu.co:8087/\", retryWrites=False)\n database = client[\"Grupo03\"]\n collection = database[\"COL_tweets\"]\n finally:\n if collection: break\n\n mapper = cuenta_tweets()\n result = database.COL_tweets.map_reduce(mapper, reduce, \"cant_COL\")\n collection = database[\"cant_COL\"]\n total_tweets = collection.find().count()\n\n mapper = cuenta_replys()\n result = database.COL_tweets.map_reduce(mapper, reduce, \"cant_COL\")\n collection = database[\"cant_COL\"]\n total_replys = collection.find().count()\n\n mapper = cuenta_quotes()\n result = database.COL_tweets.map_reduce(mapper, reduce, \"cant_COL\")\n collection = database[\"cant_COL\"]\n total_quotes = collection.find().count()\n\n return total_tweets, total_replys, total_quotes, total_tweets + total_replys + total_quotes\n\nprint(cuenta_total())","sub_path":"Script/twitter/cotweet/assets/pys/total_tweets_COL.py","file_name":"total_tweets_COL.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"552456437","text":"import tkinter as tk\nfrom choice_panel import *\nfrom tkinter import StringVar, Button\nfrom tkinter.ttk import Combobox\nfrom window import *\nimport sqlite3\nfrom woda import *\nimport woda_faktury\nfrom woda_faktury import *\n\n\nclass WodaRozliczenia:\n def __init__(self, root):\n self.frame4 = tk.Frame(root, width=1900, height=600)\n self.frame4.grid(row='1', column='0', sticky=\"nw\", pady=40)\n\n # obsługa bazy danych\n self.conn = sqlite3.connect(\"water.db\")\n self.cursor = self.conn.cursor()\n\n self.create_water_payments_menu()\n\n def close_all_buttons_frame2(self):\n for widget2 in Woda.close_all_buttons_frame2():\n widget2.destroy()\n for widget3 in WodaFaktury.close_all_buttons_frame3():\n widget3.destroy()\n\n def count_rows(self):\n sqlite_count_query = \"\"\"SELECT COUNT(*) FROM water_invoice\"\"\"\n self.cursor.execute(sqlite_count_query)\n count = self.cursor.fetchone()\n return count\n\n def select_last_record_from_database(self):\n last_row_water1 = \"\"\"SELECT * FROM payments ORDER BY id DESC LIMIT 0, 1;\"\"\"\n self.cursor.execute(last_row_water1)\n record = self.cursor.fetchall()\n return record\n\n def create_water_payments_menu(self):\n # tworzymy grupy kolumn\n self.columns_first_group()\n # tworzymy nazwy kolumn\n self.columns_name_payment()\n # ciągniemy z bazy danych archiwalne wpisy\n sqlite_count_query = \"\"\"SELECT COUNT(*) FROM water LIMIT 10\"\"\"\n self.cursor.execute(sqlite_count_query)\n count = self.cursor.fetchone()\n if count != 0:\n self.get_all_invoice_meter()\n # wpisujemy dane - zdobywamy dane\n self.new_entry()\n\n def columns_first_group(self):\n # okres rozliczeniowy\n okres_rozliczeniowy_label = tk.Label(self.frame4, text='OKRES ROZLICZENIOWY', padx=10, pady=10, relief='raised',\n highlightbackground='dark olive green',\n highlightthickness=1,\n border='1',\n borderwidth=1, width=29)\n okres_rozliczeniowy_label.config(font=(\"Courier\", 8))\n okres_rozliczeniowy_label.grid(row=3, column=1, columnspan=2, pady=4)\n\n # ROZLICZENIA GÓRA\n stan_licznikow_label = tk.Label(self.frame4, text='GÓRA', padx=10, pady=10, relief='raised',\n highlightbackground='DeepSkyBlue2',\n highlightthickness=1,\n border='1',\n borderwidth=1, width=47)\n stan_licznikow_label.config(font=(\"Courier\", 8))\n stan_licznikow_label.grid(row=3, column=3, columnspan=2, pady=4)\n\n # ROZLICZENIA GABINET\n zuzycie_mediow_label = tk.Label(self.frame4, text='GABINET', padx=10, pady=10, relief='raised',\n highlightbackground='salmon',\n highlightthickness=1,\n border='1',\n borderwidth=1, width=47)\n zuzycie_mediow_label.config(font=(\"Courier\", 8))\n zuzycie_mediow_label.grid(row=3, column=5, columnspan=2, pady=4)\n\n # DÓŁ GABINET\n zuzycie_mediow_label = tk.Label(self.frame4, text='DÓŁ', padx=10, pady=10, relief='raised',\n highlightbackground='salmon',\n highlightthickness=1,\n border='1',\n borderwidth=1, width=47)\n zuzycie_mediow_label.config(font=(\"Courier\", 8))\n zuzycie_mediow_label.grid(row=3, column=7, columnspan=2, pady=4)\n\n def columns_name_payment(self):\n # ID\n column_id = tk.Label(self.frame4, text='ID', padx=4, pady=10, relief='raised', border='1', borderwidth=2,\n width=6)\n column_id.config(font=('Tahoma', 8))\n column_id.grid(row=4, column=0, padx=4, pady=4)\n\n # ROK\n column_rok = tk.Label(self.frame4, text='ROK', padx=4, pady=10, relief='raised', border='1',\n borderwidth=2, highlightbackground='dark olive green',\n highlightthickness=1,\n width=10)\n column_rok.config(font=('Tahoma', 8))\n column_rok.grid(row=4, column=1, padx=4)\n\n # MIESIĄCE\n column_data_miesiace = tk.Label(self.frame4, text='MIESIĄCE', padx=4, pady=10, relief='raised', border='1',\n borderwidth=2, highlightbackground='dark olive green',\n highlightthickness=1,\n width=16)\n column_data_miesiace.config(font=('Tahoma', 8))\n column_data_miesiace.grid(row=4, column=2, padx=4)\n\n # DATA FAKTURY\n column_dom_stan_licznikow = tk.Label(self.frame4, text='DATA FAKTURY', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='green',\n highlightthickness=1,\n width=14)\n column_dom_stan_licznikow.config(font=('Tahoma', 8))\n column_dom_stan_licznikow.grid(row=4, column=3, padx=4)\n\n # WODA ZUŻYCIE\n column_gora_stan_licznikow = tk.Label(self.frame4, text='ZUŻYCIE', padx=4, pady=10, relief='raised', border='1',\n borderwidth=2, highlightbackground='DeepSkyBlue2',\n highlightthickness=1,\n width=10)\n column_gora_stan_licznikow.config(font=('Tahoma', 8))\n column_gora_stan_licznikow.grid(row=4, column=4, padx=4)\n\n # WODA KOSZT 1M3\n column_gabinet_stan_licznikow = tk.Label(self.frame4, text='KOSZT 1m3', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='DeepSkyBlue2',\n highlightthickness=1,\n width=10)\n column_gabinet_stan_licznikow.config(font=('Tahoma', 8))\n column_gabinet_stan_licznikow.grid(row=4, column=5, padx=4)\n\n # ILOŚĆ ABONAMENTÓW\n column_gora_zuzycie = tk.Label(self.frame4, text='IL.ABON.', padx=4, pady=10, relief='raised', border='1',\n borderwidth=2, highlightbackground='DeepSkyBlue2',\n highlightthickness=1,\n width=10)\n column_gora_zuzycie.config(font=('Tahoma', 8))\n column_gora_zuzycie.grid(row=4, column=6, padx=4)\n\n # WODA KOSZT ABONAMENT X1\n column_gabinet_zuzycie = tk.Label(self.frame4, text='1 ABON.', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='DeepSkyBlue2',\n highlightthickness=1,\n width=10)\n column_gabinet_zuzycie.config(font=('Tahoma', 8))\n column_gabinet_zuzycie.grid(row=4, column=7, padx=4)\n\n # SCIEKI ZUŻYCIE\n column_gora_stan_licznikow = tk.Label(self.frame4, text='ZUŻYCIE', padx=4, pady=10, relief='raised', border='1',\n borderwidth=2, highlightbackground='salmon',\n highlightthickness=1,\n width=10)\n column_gora_stan_licznikow.config(font=('Tahoma', 8))\n column_gora_stan_licznikow.grid(row=4, column=8, padx=4)\n\n # SCIEKI KOSZT 1M3\n column_gabinet_stan_licznikow = tk.Label(self.frame4, text='KOSZT 1m3', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='salmon',\n highlightthickness=1,\n width=10)\n column_gabinet_stan_licznikow.config(font=('Tahoma', 8))\n column_gabinet_stan_licznikow.grid(row=4, column=9, padx=4)\n\n # SCIEKI ILOŚĆ ABONAMENTÓW\n column_gora_zuzycie = tk.Label(self.frame4, text='IL.ABON.', padx=4, pady=10, relief='raised', border='1',\n borderwidth=2, highlightbackground='salmon',\n highlightthickness=1,\n width=10)\n column_gora_zuzycie.config(font=('Tahoma', 8))\n column_gora_zuzycie.grid(row=4, column=10, padx=4)\n\n # SCIEKI KOSZT ABONAMENT X1\n column_gabinet_zuzycie = tk.Label(self.frame4, text='1 ABON.', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='salmon',\n highlightthickness=1,\n width=10)\n column_gabinet_zuzycie.config(font=('Tahoma', 8))\n column_gabinet_zuzycie.grid(row=4, column=11, padx=4)\n\n # DO ZAPŁATY\n do_zaplaty = tk.Label(self.frame4, text='DO ZAPŁATY', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='green',\n highlightthickness=1,\n width=10)\n do_zaplaty.config(font=('Tahoma', 8))\n do_zaplaty.grid(row=4, column=12, padx=4)\n\n # OPLACONA\n oplacona = tk.Label(self.frame4, text='OPŁACONA', padx=4, pady=10, relief='raised',\n border='1',\n borderwidth=2, highlightbackground='salmon',\n highlightthickness=1,\n width=10)\n oplacona.config(font=('Tahoma', 8))\n oplacona.grid(row=4, column=13, padx=4)\n\n def get_all_invoice_meter(self):\n count = self.count_rows()\n\n for e in count:\n if e > 0:\n try:\n sqlite_select_query = \"\"\"SELECT * FROM payments ORDER BY id DESC LIMIT 10;\"\"\"\n self.cursor.execute(sqlite_select_query)\n records = self.cursor.fetchall()\n n = 0\n m = 0\n for row in records:\n for e in row:\n label = tk.Label(self.frame4, text=e, padx=4, pady=10, relief='raised', border='1',\n borderwidth=2,\n width=6)\n label.config(font=('Courier', 8))\n label.grid(row=6 + m, column=0 + n, padx=4, sticky='WE')\n n += 1\n m += 1\n n = 0\n\n\n except sqlite3.Error as error:\n print(\"Failed to read data from sqlite table\", error)\n\n\n\n # def new_entry(self):\n # pass\n # #\n # # rok = tk.Entry(self.frame4, width=5)\n # # rok.config(font=(\"Courier\", 8))\n # # rok.grid(row=5, column=1, padx=4, sticky='WE')\n # #\n # # choices = ['Grudzień/Styczeń', 'Luty/Marzec', 'Kwiecień/Maj', 'Czerwiec/Lipiec', 'Sierpień/Wrzesień',\n # # 'Październik/Listopad']\n # #\n # # miesiace = Combobox(self.frame4, width=5, values=choices)\n # # miesiace.current(0)\n # # miesiace.config(font=(\"Courier\", 8))\n # # miesiace.grid(row=5, column=2, padx=4, sticky='WE')\n # #\n # # data_faktura = tk.Entry(self.frame4, width=5)\n # # data_faktura.config(font=(\"Courier\", 8))\n # # data_faktura.grid(row=5, column=3, padx=4, sticky='WE')\n # #\n # # # woda\n # # woda_zuzycie = tk.Entry(self.frame3, width=5)\n # # woda_zuzycie.config(font=(\"Courier\", 8))\n # # woda_zuzycie.grid(row=5, column=4, padx=4, sticky='WE')\n # #\n # # woda_koszt_1_m3 = tk.Entry(self.frame3, width=5)\n # # woda_koszt_1_m3.config(font=(\"Courier\", 8))\n # # woda_koszt_1_m3.grid(row=5, column=5, padx=4, sticky='WE')\n # #\n # # woda_ilosc_abon = tk.Entry(self.frame3, width=5)\n # # woda_ilosc_abon.config(font=(\"Courier\", 8))\n # # woda_ilosc_abon.grid(row=5, column=6, padx=4, sticky='WE')\n # #\n # # woda_koszt_abon = tk.Entry(self.frame3, width=5)\n # # woda_koszt_abon.config(font=(\"Courier\", 8))\n # # woda_koszt_abon.grid(row=5, column=7, padx=4, sticky='WE')\n # #\n # # # scieki\n # # scieki_zuzycie = tk.Entry(self.frame3, width=5)\n # # scieki_zuzycie.config(font=(\"Courier\", 8))\n # # scieki_zuzycie.grid(row=5, column=8, padx=4, sticky='WE')\n # #\n # # scieki_koszt_1_m3 = tk.Entry(self.frame3, width=5)\n # # scieki_koszt_1_m3.config(font=(\"Courier\", 8))\n # # scieki_koszt_1_m3.grid(row=5, column=9, padx=4, sticky='WE')\n # #\n # # scieki_ilosc_abon = tk.Entry(self.frame3, width=5)\n # # scieki_ilosc_abon.config(font=(\"Courier\", 8))\n # # scieki_ilosc_abon.grid(row=5, column=10, padx=4, sticky='WE')\n # #\n # # scieki_koszt_abon = tk.Entry(self.frame3, width=5)\n # # scieki_koszt_abon.config(font=(\"Courier\", 8))\n # # scieki_koszt_abon.grid(row=5, column=11, padx=4, sticky='WE')\n # #\n # # # do zapłaty\n # # do_zaplaty = tk.Entry(self.frame3, width=5)\n # # do_zaplaty.config(font=(\"Courier\", 8))\n # # do_zaplaty.grid(row=5, column=12, padx=4, sticky='WE')\n # #\n # # # czy oplacona\n # # choices_bool = ['NIE', 'TAK']\n # #\n # # oplacona = Combobox(self.frame3, width=5, values=choices_bool)\n # # oplacona.current(0)\n # # oplacona.config(font=(\"Courier\", 8))\n # # oplacona.grid(row=5, column=13, padx=4, sticky='WE')\n # #\n # # confirm_button = Button(self.frame3, text=\"ZAPISZ\",\n # # command=lambda: self.submit(rok, miesiace, data_faktura, woda_zuzycie, woda_koszt_1_m3,\n # # woda_ilosc_abon, woda_koszt_abon, scieki_zuzycie,\n # # scieki_koszt_1_m3, scieki_ilosc_abon, scieki_koszt_abon,\n # # do_zaplaty, oplacona))\n # #\n # # confirm_button.grid(row=5, column=14)\n # #\n # # # modify entry\n # # modify_button = tk.Button(self.frame3, text='NR ID DO ZMIANY', width=14,\n # # command=lambda: self.change_entry('water'))\n # # modify_button.config(font=(\"Courier\", 8))\n # # modify_button.grid(row=18, column=1, sticky='WE', padx=4)\n # #\n # # self.modify_entry = tk.Entry(self.frame3, text='ZMIEŃ', width=6)\n # # self.modify_entry.config(font=(\"Courier\", 8))\n # # self.modify_entry.grid(row=18, column=0, sticky='WE', padx=4)\n #\n # def submit(self, *args):\n # names = []\n # for n in args:\n # names.append(n.get())\n #\n # self.water_invoice_db_insert_values(names)\n #\n # def water_payments_db_insert_values(self, names):\n #\n # data_tuple = tuple(names)\n #\n # sqlite_insert_query = \"\"\"INSERT INTO water_invoice (ROK, OKRES, DATA_FAKTURA, WODA_ZUŻYCIE, WODA_KOSZT_1M3,\n # ILOŚĆ_ABONAM_W, WODA_KOSZT_1xABON, ŚCIEKI_ZUŻYCIE, ŚCIEKI_KOSZT_1M3, ILOŚĆ_ABONAM_S, ŚCIEKI_KOSZT_1xABON,\n # DO_ZAPŁATY, OPŁACONA)\n # VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?);\"\"\"\n #\n # self.cursor.execute(sqlite_insert_query, data_tuple)\n # self.conn.commit()\n #\n # self.get_all_invoice_meter()\n\n","sub_path":"woda_rozliczenia.py","file_name":"woda_rozliczenia.py","file_ext":"py","file_size_in_byte":16363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"280979513","text":"while True:\n a,b,c = list(map(int,input().split()))\n if a == 0 and b == 0 and c == 0:\n break\n tlist = [a,b,c]\n tlist.sort()\n if tlist[0] ** 2 + tlist[1] ** 2 == tlist[2] ** 2:\n print(\"right\")\n else:\n print(\"wrong\")\n","sub_path":"VS 2019/BOJ_Python/단계/09. 수학2/BOJ_4153.py","file_name":"BOJ_4153.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"21471182","text":"from app import db\n\n\nclass Activity(db.Model):\n __tablename__ = \"activity\"\n __table_args__ = {'extend_existing': True}\n id = db.Column('id', db.Integer, primary_key=True)\n name = db.Column('name', db.VARCHAR(64))\n kcal_ph_pkg = db.Column('kcal_ph_pkg', db.Float)\n\n def __init__(self, id, name, kcal_ph_pkg):\n self.id = id\n self.name = name\n self.kcal_ph_pkg = kcal_ph_pkg\n\n def __repr__(self):\n return 'food' + self.food_ndbno + ' - ' + self.name","sub_path":"src/app/models/Activity.py","file_name":"Activity.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"266900664","text":"from __future__ import annotations\n\nimport logging\nfrom typing import TYPE_CHECKING\n\nfrom requests import Response\nfrom requests.exceptions import ConnectionError, Timeout\nfrom rest_framework import status\n\nfrom sentry.http import safe_urlopen\nfrom sentry.models.integrations.sentry_app import track_response_code\nfrom sentry.shared_integrations.exceptions import ApiHostError, ApiTimeoutError, ClientError\nfrom sentry.utils.sentry_apps import SentryAppWebhookRequestsBuffer\n\nif TYPE_CHECKING:\n from sentry.api.serializers import AppPlatformEvent\n from sentry.models import SentryApp\n\n\nWEBHOOK_TIMEOUT = 5\nTIMEOUT_STATUS_CODE = 0\n\nlogger = logging.getLogger(\"sentry.sentry_apps.webhooks\")\n\n\ndef ignore_unpublished_app_errors(func):\n def wrapper(sentry_app, app_platform_event, url=None):\n try:\n return func(sentry_app, app_platform_event, url)\n except Exception:\n if sentry_app.is_published:\n raise\n else:\n return\n\n return wrapper\n\n\n@ignore_unpublished_app_errors\ndef send_and_save_webhook_request(\n sentry_app: SentryApp,\n app_platform_event: AppPlatformEvent,\n url: str | None = None,\n) -> Response:\n \"\"\"\n Notify a SentryApp's webhook about an incident and log response on redis.\n\n :param sentry_app: The SentryApp to notify via a webhook.\n :param app_platform_event: Incident data. See AppPlatformEvent.\n :param url: The URL to hit for this webhook if it is different from `sentry_app.webhook_url`.\n :return: Webhook response\n \"\"\"\n buffer = SentryAppWebhookRequestsBuffer(sentry_app)\n\n org_id = app_platform_event.install.organization_id\n event = f\"{app_platform_event.resource}.{app_platform_event.action}\"\n slug = sentry_app.slug_for_metrics\n url = url or sentry_app.webhook_url\n response = None\n try:\n response = safe_urlopen(\n url=url,\n data=app_platform_event.body,\n headers=app_platform_event.headers,\n timeout=WEBHOOK_TIMEOUT,\n )\n except (Timeout, ConnectionError) as e:\n error_type = e.__class__.__name__.lower()\n logger.info(\n \"send_and_save_webhook_request.timeout\",\n extra={\n \"error_type\": error_type,\n \"organization_id\": org_id,\n \"integration_slug\": sentry_app.slug,\n },\n )\n track_response_code(error_type, slug, event)\n buffer.add_request(\n response_code=TIMEOUT_STATUS_CODE,\n org_id=org_id,\n event=event,\n url=url,\n headers=app_platform_event.headers,\n )\n # Re-raise the exception because some of these tasks might retry on the exception\n raise\n\n track_response_code(response.status_code, slug, event)\n buffer.add_request(\n response_code=response.status_code,\n org_id=org_id,\n event=event,\n url=url,\n error_id=response.headers.get(\"Sentry-Hook-Error\"),\n project_id=response.headers.get(\"Sentry-Hook-Project\"),\n response=response,\n headers=app_platform_event.headers,\n )\n\n if response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE:\n raise ApiHostError.from_request(response.request)\n\n elif response.status_code == status.HTTP_504_GATEWAY_TIMEOUT:\n raise ApiTimeoutError.from_request(response.request)\n\n elif 400 <= response.status_code < 500:\n raise ClientError(response.status_code, url, response=response)\n\n response.raise_for_status()\n return response\n","sub_path":"src/sentry/utils/sentry_apps/webhooks.py","file_name":"webhooks.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"644370597","text":"# -*- coding: utf-8 -*-\n#\n# Reports.Dump_Published_Headwords_To_File\n# - A FlexTools Module -\n#\n# Dump all Headwords in a FLEx project to a file.\n#\n# Kien-Wei Tseng\n# April 2016\n#\n# Platforms: Python .NET and IronPython\n#\n\nfrom flextoolslib import *\nimport io\n\n#----------------------------------------------------------------\n# Documentation that the user sees:\n\ndocs = {FTM_Name : \"Dump Published Headwords To File\",\n FTM_Version : 1,\n FTM_ModifiesDB : False,\n FTM_Synopsis : \"Dump published Headwords to file.\",\n FTM_Description :\n\"\"\"\nDump all headwords to a file if they are marked to be published (PublishIn field has at least\none value.)\n\"\"\" }\n \n#----------------------------------------------------------------\n# The main processing function\n\ndef MainFunction(project, report, modifyAllowed):\n\n headwordsFile = \"Headwords_Published_{0}.txt\".format(project.ProjectName())\n output = io.open(headwordsFile, mode=\"w\", encoding=\"utf-8\")\n headwords = []\n for e in project.LexiconAllEntries():\n if project.LexiconGetPublishInCount(e) > 0:\n headwords.append(project.LexiconGetHeadword(e))\n numHeadwords = 0\n for headword in sorted(headwords, key=lambda s: s.lower()):\n output.write(headword + '\\n')\n numHeadwords += 1\n report.Info(\"Dumped {0} headwords to file {1}\".format(\n numHeadwords, headwordsFile))\n report.Info(\"Total Lexical Entries in Project = {}\".format(\n project.LexiconNumberOfEntries()))\n output.close()\t\t\n\n#----------------------------------------------------------------\n# The name 'FlexToolsModule' must be defined like this:\n\nFlexToolsModule = FlexToolsModuleClass(runFunction = MainFunction,\n docs = docs)\n \n#----------------------------------------------------------------\nif __name__ == '__main__':\n FlexToolsModule.Help()\n ","sub_path":"flextools-2.2.1/FlexTools/Modules/Export/Dump_Published_Headwords_To_File.py","file_name":"Dump_Published_Headwords_To_File.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"449548297","text":"from rest_framework import serializers\nfrom bootcamp.articles.models import Article\nfrom bootcamp.api_mixins import CommonAPIMixin\n\n\nclass ArticleSerializer(CommonAPIMixin, serializers.ModelSerializer):\n \"\"\"\n Serializer class for listing the articles\n \"\"\"\n\n popular_tags = serializers.SerializerMethodField()\n image = serializers.ImageField(required=False)\n\n def get_popular_tags(self, obj):\n return Article.objects.get_counted_tags()\n\n class Meta:\n model = Article\n fields = [\"title\", \"content\", \"image\", \"tags\", \"status\", \"edited\",\n \"popular_tags\", \"user\"]\n\n def to_representation(self, instance):\n ret_dict = super(ArticleSerializer, self).to_representation(instance)\n\n if type(instance) == self.Meta.model:\n ret_dict['tags'] = [tag for tag in instance.tags.names()]\n\n return ret_dict\n\n def create(self, validated_data):\n validated_data['user'] = self.user\n\n return super(ArticleSerializer, self).create(validated_data)\n","sub_path":"bootcamp/articles/apis/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"257643293","text":"import sys\r\nfrom collections import deque\r\n\r\n\r\ndef dfs(graph, start):\r\n visited, need_visit = list(), list()\r\n need_visit.append(start)\r\n while need_visit:\r\n node = need_visit.pop()\r\n if node not in visited:\r\n visited.append(node)\r\n if node in graph:\r\n temp = list(set(graph[node]) - set(visited))\r\n temp.sort(reverse=True)\r\n need_visit += temp\r\n # need_visit.extend(graph[node]) <== 이게 런타임 에러를 일으킨다(그리고 필요없는 부분임)\r\n return visited\r\n\r\n\r\ndef bfs(graph, start):\r\n visited, need_visit = list(), list()\r\n need_visit = deque([start])\r\n # need_visit.append(start)\r\n while need_visit:\r\n node = need_visit.popleft()\r\n if node not in visited:\r\n visited.append(node)\r\n if node in graph:\r\n temp = list(set(graph[node]) - set(visited))\r\n temp.sort()\r\n need_visit += temp\r\n return visited\r\n\r\n\r\ngraph = dict()\r\nn = sys.stdin.readline().split(' ')\r\nnode, edge, start = [int(i) for i in n]\r\n\r\nfor i in range(edge):\r\n node1, node2 = map(int, sys.stdin.readline().split())\r\n if node1 not in graph:\r\n graph[node1] = [node2]\r\n elif node2 not in graph[node1]:\r\n graph[node1].append(node2)\r\n\r\n if node2 not in graph:\r\n graph[node2] = [node1]\r\n elif node1 not in graph[node2]:\r\n graph[node2].append(node1)\r\n\r\nprint(*dfs(graph, start))\r\nprint(*bfs(graph, start))\r\n","sub_path":"BAEKJOON/[baek] 1260_dfs.py","file_name":"[baek] 1260_dfs.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"96044491","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n'''\r\nCreated on 2014-9-17\r\n\r\n@author: JohnDannl\r\n'''\r\nfrom table import dbconn as dbconn\r\nfrom dbconfig import tableName as tableName\r\nimport time\r\n\r\nimport dbconfig\r\n\r\ndef InsertItem(tablename, data): \r\n if ChkExistRow(tablename, data[0],data[12]):\r\n return\r\n query = \"\"\"INSERT INTO \"\"\" + tablename + \"\"\"(\r\n vid,title,url,thumb,summary,keywords,newsid,vtype,source,related,loadtime,duration,web,mvid,mtype,click)\r\n values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\r\n dbconn.Insert(query, data)\r\n\r\ndef InsertItemMany(tablename, datas):\r\n for data in datas:\r\n InsertItem(tablename, data)\r\n\r\ndef InsertItems(tablename, datas):\r\n query = \"\"\"INSERT INTO \"\"\" + tablename + \"\"\"(\r\n vid,title,url,thumb,summary,keywords,newsid,vtype,source,related,loadtime,duration,web,mvid,mtype,click)\r\n values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\"\r\n dbconn.insertMany(query, datas)\r\n\r\ndef InsertItemDict(tablename, data):\r\n if ChkExistRow(tablename, data['vid'],data['web']):\r\n return 1\r\n query = \"INSERT INTO \" + tablename + \"\"\"(\r\n vid,title,url,thumb,summary,keywords,newsid,vtype,source,related,loadtime,duration,web,mvid,mtype,click) \r\n values(%(vid)s, %(title)s,%(url)s, %(thumb)s, %(summary)s, %(keywords)s,%(newsid)s,%(vtype)s, %(source)s,\r\n %(related)s, %(loadtime)s, %(duration)s, %(web)s, %(mvid)s, %(mtype)s, %(click)s)\"\"\"\r\n dbconn.Insert(query, data)\r\n return 0\r\n\r\ndef getAllCount(tablename):\r\n query=\"select count(*) from \"+tablename\r\n count=dbconn.Select(query,())[0][0]\r\n return count\r\n\r\ndef getAllRecords(tablename):\r\n query = \"SELECT * FROM \" + tablename\r\n rows = dbconn.Select(query, ())\r\n return rows\r\n\r\ndef getTitleByType(tablename,mtype):\r\n query='select title,mtype from '+ tablename+' where mtype = %s'\r\n rows=dbconn.Select(query, (mtype,))\r\n return rows\r\n\r\ndef getRecordsByLoadTime(tablename, starttime, endtime):\r\n '''@param tablename: table name\r\n @param starttime: the start time of query in format:%Y-%m-%d %H:%M:%S\r\n @param endtime: the end time of query in format:%Y-%m-%d %H:%M:%S\r\n '''\r\n# starttime = time.strftime(\"%Y-%m-%d %H:%M:%S\", starttime)\r\n# endtime=time.strftime(\"%Y-%m-%d %H:%M:%S\", endtime)\r\n query = \"SELECT * FROM \" + tablename + \"\"\" WHERE loadtime >= %s AND loadtime <= %s\"\"\" \r\n rows = dbconn.Select(query, (starttime,endtime)) \r\n return rows\r\n\r\ndef getLatestTitle(tablename,topnum=10000):\r\n # return [(title,mvid),] \r\n query = \"SELECT title,mvid FROM \" + tablename + \"\"\" order by loadtime desc limit %s\"\"\" \r\n rows = dbconn.Select(query, (topnum,)) \r\n return rows\r\n\r\ndef getTitleByMvid(tablename,mvid):\r\n # return the user clicked video info,should be only one if no accident\r\n # the return column:vtype,mvid,mtype\r\n query = \"SELECT mvid,title FROM \" + tablename + \"\"\" WHERE mvid = %s \"\"\" \r\n rows = dbconn.Select(query, (mvid,)) \r\n return rows\r\n\r\ndef getRecordsByWebVid(tablename,web,vid):\r\n # return the user clicked video info,should be only one if no accident\r\n # the return column:vtype,mvid,mtype\r\n query = \"SELECT vtype,mvid,mtype FROM \" + tablename + \"\"\" WHERE web = %s AND vid = %s\"\"\" \r\n rows = dbconn.Select(query, (web,vid)) \r\n return rows\r\ndef getTopUrls(tablename,topnum=10):\r\n# return [(url,vid),]\r\n query='select url,vid from '+tablename+' order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(topnum,))\r\n return rows\r\n\r\ndef getTopRecords(tablename,topnum=10,mtype=None):\r\n# @attention: get top @param topnum: records from @param tablename:\r\n# order by time,that is,get recent @param topnum: records \r\n if not mtype:\r\n query='select * from '+tablename+' order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(topnum,))\r\n else:\r\n query='select * from '+tablename+' where mtype = %s order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(mtype,topnum))\r\n return rows\r\n\r\ndef getTopETSVRecords(tablename,loadtime,vid,topnum=10,mtype=None):\r\n# return the topnum records whose loadtime equals @param loadtime: and vid smaller than @param vid:\r\n if not mtype: \r\n query='select * from '+tablename+' where loadtime = %s and vid < %s order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(loadtime,vid,topnum))\r\n else:\r\n query='select * from '+tablename+' where mtype = %s and loadtime = %s and vid < %s order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(mtype,loadtime,vid,topnum))\r\n return rows\r\n\r\ndef getTopSTRecords(tablename,loadtime,topnum=10,mtype=None):\r\n# return the topnum records smaller loadtime \r\n if not mtype:\r\n query='select * from '+tablename+' where loadtime < %s order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(loadtime,topnum))\r\n else:\r\n query='select * from '+tablename+' where mtype = %s and loadtime < %s order by loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(mtype,loadtime,topnum))\r\n return rows\r\n\r\ndef getBottomETBVRecords(tablename,loadtime,vid,topnum=10,mtype=None):\r\n# return the bottom records equal loadtime bigger vid\r\n if not mtype:\r\n query='select * from '+tablename+' where loadtime = %s and vid > %s order by loadtime asc,vid asc limit %s'\r\n rows=dbconn.Select(query,(loadtime,vid,topnum))\r\n else:\r\n query='select * from '+tablename+' where mtype = %s and loadtime = %s and vid > %s order by loadtime asc,vid asc limit %s'\r\n rows=dbconn.Select(query,(mtype,loadtime,vid,topnum))\r\n return rows\r\n\r\ndef getBottomBTRecords(tablename,loadtime,topnum=10,mtype=None):\r\n# return the bottom records bigger loadtime bigger vid\r\n if not mtype:\r\n query='select * from '+tablename+' where loadtime > %s order by loadtime asc,vid asc limit %s'\r\n rows=dbconn.Select(query,(loadtime,topnum))\r\n else:\r\n query='select * from '+tablename+' where mtype = %s and loadtime > %s order by loadtime asc,vid asc limit %s'\r\n rows=dbconn.Select(query,(mtype,loadtime,topnum))\r\n return rows\r\n\r\ndef getTopClickRecords(tablename,topnum=10):\r\n# @attention: get top @param topnum: records from @param tablename:\r\n# order by click,that is,get hottest @param topnum: records \r\n\r\n query='select * from '+tablename+' order by click desc,loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(topnum,))\r\n return rows\r\n\r\ndef getTopECESTSVRecords(tablename,click,loadtime,vid,topnum=10):\r\n# return the topnum records whose click equals @param click: and vid smaller than @param vid: \r\n query='select * from '+tablename+' where click = %s and loadtime <= %s and vid < %s order by click desc,loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(click,vid,topnum))\r\n return rows\r\n\r\ndef getTopSCRecords(tablename,click,topnum=10):\r\n# return the topnum records smaller click \r\n query='select * from '+tablename+' where click < %s order by click desc,loadtime desc,vid desc limit %s'\r\n rows=dbconn.Select(query,(click,topnum))\r\n return rows\r\n\r\n# Refreshing action is not so logical\r\n\r\n# def getBottomECEBTBVRecords(tablename,click,loadtime,vid,topnum=10):\r\n# # return the bottom records equal click bigger vid\r\n# query='select * from '+tablename+' where click = %s and loadtime >= %s and vid > %s order by click asc,loadtime asc,vid asc limit %s'\r\n# rows=dbconn.Select(query,(click,vid,topnum))\r\n# return rows\r\n# \r\n# def getBottomBCRecords(tablename,click,topnum=10):\r\n# # return the bottom records bigger click bigger vid\r\n# query='select * from '+tablename+' where click > %s order by click asc,loadtime asc,vid asc limit %s'\r\n# rows=dbconn.Select(query,(click,topnum))\r\n# return rows\r\n\r\ndef ChkExistRow(tablename, vid,web):\r\n query = \"SELECT COUNT(*) FROM \" + tablename + \" WHERE vid = %s and web = %s\"\r\n row = dbconn.Select(query, (vid,web))[0][0]\r\n if row == 0:\r\n return False\r\n return True\r\n\r\ndef updateMtype(tablename,mtype,web,vid):\r\n query = \"UPDATE \" + tablename + \"\"\" SET mtype = %s WHERE web = %s and vid = %s\"\"\"\r\n dbconn.Update(query, (mtype,web,vid))\r\n\r\ndef increaseClick(web,vid):\r\n tablename=dbconfig.mergetable\r\n query = 'select click from '+tablename+\"\"\" WHERE web = %s and vid = %s\"\"\"\r\n rows=dbconn.Select(query,(web,vid))\r\n if rows !=-1 and len(rows)>0:\r\n click=rows[0][0]\r\n click+=1\r\n query = \"UPDATE \" + tablename + \"\"\" SET click = %s WHERE web = %s and vid = %s\"\"\"\r\n dbconn.Update(query, (click,web,vid))\r\n \r\ndef CreateNewsTable(tablename):\r\n query = \"\"\"CREATE TABLE \"\"\" + tablename + \"\"\"(\r\n id serial primary key, \r\n vid text,\r\n title text,\r\n url text,\r\n thumb text,\r\n summary text,\r\n keywords text,\r\n newsid text,\r\n vtype text,\r\n source text,\r\n related text, \r\n loadtime timestamp,\r\n duration text,\r\n web text,\r\n mvid text,\r\n mtype text,\r\n click integer)\"\"\"\r\n dbconn.CreateTable(query, tablename)\r\n\r\nif __name__ == \"__main__\":\r\n CreateNewsTable(dbconfig.mergetable) \r\n# rows=getLatestTitle(dbconfig.mergetable,10)\r\n# if rows!=-1 and len(rows)>0:\r\n# for row in rows:\r\n# print row[0]\r\n# rows=getBottomETBVRecords(dbconfig.tableName[2],'2014-09-04 10:09:02','1310457')\r\n# rows=getBottomBTRecords(dbconfig.tableName[2],'2014-09-04 10:09:02',10)\r\n# rows=getTopETSVRecords(dbconfig.tableName[2],'2014-09-04 10:09:02','1310458')\r\n# rows=getTopSTRecords(dbconfig.tableName[2],'2014-09-04 10:09:02','10')\r\n# if rows !=-1:\r\n# for item in rows:\r\n# print item[1],item[11] \r\n \r\n# rows=getTopUrls(dbconfig.tableName[0],10) \r\n# if rows !=-1:\r\n# for item in rows:\r\n# print item[1],item[0] \r\n \r\n# rows=getUrlByVid(dbconfig.tableName[2],r'1310945')\r\n# if rows !=-1:\r\n# print rows[0][0] ","sub_path":"database/tablemerge.py","file_name":"tablemerge.py","file_ext":"py","file_size_in_byte":10374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"79905205","text":"import telegram\n\nmy_token = '634196435:AAFZWvFjC5-wh1Cbh_rFqlqnyu7zIjwYvwA'\nbot = telegram.Bot(token=my_token)\n\nupdates = bot.getUpdates() # 업데이트 내역 받아오기\n\nfor u in updates:\n print(u.message)\n\nchat_id = bot.getUpdates()[-1].message.chat.id # 가장 최근에 온 메세지의 chat id를 가져옵니다\n\nbot.sendMessage(chat_id = chat_id, text=\"저는 봇입니다.\")","sub_path":"Chatbot/RecentResponse.py","file_name":"RecentResponse.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"275663839","text":"import torch\r\nimport os\r\nfrom torch import nn,optim\r\nfrom net import *\r\nfrom data import MINISTDataset\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\r\n\r\nDEVICE=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nclass Train:\r\n def __init__(self,root):\r\n #初始化\r\n self.summaryWriter=SummaryWriter(\"logs\")\r\n\r\n #加载训练数据\r\n self.train_dataset=MINISTDataset(root,True)\r\n self.train_dataloader=DataLoader(self.train_dataset,100,True,drop_last=True,num_workers=8)\r\n\r\n #加载测试数据\r\n self.test_dataset=MINISTDataset(root,False)\r\n self.test_dataloader = DataLoader(self.test_dataset, 100, True, drop_last=True,num_workers=8)\r\n\r\n #加载模型\r\n self.net=NetV3().to(DEVICE)\r\n\r\n # 加载预训练权重\r\n if os.path.exists(\"params/0.pt\"):\r\n self.net.load_state_dict(torch.load(\"params/0.pt\"))\r\n\r\n #优化算法\r\n self.opt=optim.Adam(self.net.parameters())\r\n\r\n #损失函数\r\n self.loss_function=nn.MSELoss()\r\n\r\n #训练过程\r\n def __call__(self):\r\n for epoch in range(10000):\r\n train_loss=0\r\n test_loss=0\r\n acc=0\r\n for i,(imgs,tags) in enumerate(self.train_dataloader):\r\n imgs, tags=imgs.to(DEVICE),tags.to(DEVICE)\r\n #开启训练模式,网络\r\n self.net.train()\r\n #100*784(batchsize*784)\r\n y=self.net.forward(imgs)\r\n #100*10\r\n train_loss=torch.mean((tags-y)**2)#对应位置相减\r\n # train_loss=self.loss_function(y,tags)\r\n\r\n self.opt.zero_grad()\r\n train_loss.backward()\r\n self.opt.step()\r\n\r\n #验证\r\n for i,(imgs,tags)in enumerate(self.test_dataloader):\r\n imgs, tags = imgs.to(DEVICE), tags.to(DEVICE)\r\n #开启测试模式,网络\r\n self.net.eval()\r\n test_y=self.net(imgs)\r\n test_loss=torch.mean((tags-test_y)**2)\r\n #one-hot编码转标签\r\n # print(torch.argmax(test_y,dim=1))\r\n # print(torch.argmax(tags,dim=1))\r\n predict_tags=torch.argmax(test_y,dim=1)\r\n label_tags=torch.argmax(tags,dim=1)\r\n #准确度,预测正确个数/标签总数 不同于PR计算\r\n acc=(predict_tags == label_tags).sum().item()/len(tags)#相同为True不同为False的掩码矩阵\r\n # 收集损失\r\n # self.summaryWriter.add_scalar(\"train_loss\", loss, epoch)\r\n self.summaryWriter.add_scalars(\"loss\", {\"train_loss\":train_loss,\"test_loss\":test_loss},epoch)\r\n if epoch%10==0:\r\n print(\"train_loss:\",train_loss.item(),\"test_loss:\",test_loss.item(),\"accuracy:\",acc)\r\n if epoch%50==0:\r\n torch.save(self.net.state_dict(),f\"params/{epoch}.pth\")\r\nif __name__ == '__main__':\r\n train=Train(\"data\")\r\n train()\r\n\r\n","sub_path":"Day005/python/diy_num_project/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"30230522","text":"import json\nfrom collections import Counter\nimport math\nimport app.backend.cosine_similarity as cosine_similarity\nfrom app.backend.rocchio import rocchio_update_addhoc\n# import cosine_similarity as cosine_similarity\n\nwith open('./datasets/p2/tv_shows_reviews_description.json') as tv_shows_reviews_description_file:\n tv_shows_reviews_description = json.load(tv_shows_reviews_description_file)\nwith open('./datasets/p2/tv_shows_to_index_final.json') as tv_shows_to_index_file:\n tv_show_to_index = json.load(tv_shows_to_index_file)\nwith open('./datasets/p2/index_to_tv_shows_final.json') as index_to_tv_show_file:\n index_to_tv_show = json.load(index_to_tv_show_file)\n\n# def build_inverted_index(reviews_description_dict):\n# \"\"\"\n# Returns: An inverted index represented by a dict with words as keys and show\n# index-tf dictionaries as values\n\n# Parameter reviews_description_dict: a dictionary with info about reviews\n# and descriptions\n# Precondtion: review dictionary\n# \"\"\"\n# result = {}\n\n# for show in reviews_description_dict:\n# show_info = reviews_description_dict[show]\n# index = tv_show_to_index[show]\n# all_tokens = cosine_similarity.tokenize(show_info['description'])\n# show_reviews = show_info['reviews']\n# for review in show_reviews:\n# all_tokens += cosine_similarity.tokenize(review)\n# count_dict = Counter(all_tokens)\n# for word, count in count_dict.items():\n# if word in result.keys():\n# if index in result[word].keys():\n# result[word][index] += count\n# else:\n# result[word][index] = count\n# else:\n# result[word] = { index : count }\n# count_dict = {}\n\n# return result\n\n# TESTS FOR INVERTED INDEX\n# print(tv_shows_reviews_description['the walking dead'])\n# print(index_to_tv_show[\"29\"])\n# print(inverted_index['zombie'])\n# print(inverted_index['smart'])\n\n# inverted_index = build_inverted_index(tv_shows_reviews_description)\n# idf_dict = cosine_similarity.compute_idf(inverted_index, len(index_to_tv_show))\n# show_norms = cosine_similarity.compute_show_norms(inverted_index, idf_dict, len(index_to_tv_show))\n# inverted_index = {key: val for key, val in inverted_index.items() if key in idf_dict}\n\n# SAVING DATA AS JSON AFTER RUNNING LOCALLY\n# a_file = open(\"datasets/p2/adhoc_inverted_index.json\", \"w\")\n# json.dump(inverted_index, a_file)\n# b_file = open(\"datasets/p2/adhoc_show_norms.json\", \"w\")\n# json.dump(show_norms, b_file)\n# c_file = open(\"datasets/p2/adhoc_idf_dict.json\", \"w\")\n# json.dump(idf_dict, c_file)\n\n# LOADING SAVED JSON\nwith open('./datasets/p2/adhoc_inverted_index.json') as a_file:\n inverted_index = json.load(a_file)\nwith open('./datasets/p2/adhoc_show_norms.json') as b_file:\n show_norms = json.load(b_file)\nwith open('./datasets/p2/adhoc_idf_dict.json') as c_file:\n idf_dict = json.load(c_file)\n\n\ndef index_search(query, index, idf, show_norms):\n \"\"\"\n Returns: A list of score-show tuples in descending order from most similar\n shows to least similar shows.\n\n Parameter query: query\n Precondition: string\n\n Parameter index: inverted index\n Precondition: dictionary with words as keys and show-tf tuples as values\n\n Parameter idf: computed idf values\n Precondition: dictionary with words as keys and idf as values\n\n Parameter: computed norms for every show\n Precondition: list with length of the number of shows with reviews\n \"\"\"\n with open(\"./datasets/p2/relevance.json\") as f:\n query_obj = json.load(f)\n f.close()\n\n result = []\n numerators = {}\n \n lowercase_query = query.lower()\n #rememebr query_obj\n q1 = rocchio_update_addhoc(query, query_obj['words'], index, idf)\n # print(query_obj)\n \n tokenized_query = cosine_similarity.tokenizeQuotes(lowercase_query)\n query_tfs = Counter(tokenized_query)\n query_norm = math.sqrt(q1.dot(q1))\n\n cnt = 0\n for token, q_tf in query_tfs.items():\n irrelevant_list = []\n relevant_list = []\n if token.find(\" \") >= 0:\n if token in query_obj['words']['scores'].keys():\n relevant_list = query_obj['words']['relevant'][token] \n irrelevant_list = query_obj['words']['irrelevant'][token]\n multi_word_dict = cosine_similarity.create_multi_word_dict(index, token)\n show_count_tf_dict = multi_word_dict['shows_count_tf_dict']\n token_idf = cosine_similarity.compute_idf_multi_words(index, token, len(index_to_tv_show))\n for show in show_count_tf_dict.keys():\n if show_count_tf_dict[show]['count'] == multi_word_dict['n_words_in_quotes']:\n if q_tf != 0 and token_idf != 0:\n if index_to_tv_show[show].lower() in relevant_list or index_to_tv_show[show].lower() in irrelevant_list:\n temp_score = query_obj['words']['scores'][token][index_to_tv_show[show].lower()][0]/ query_obj['words']['scores'][token][index_to_tv_show[show].lower()][1]\n numerator = q1[cnt] * show_count_tf_dict[show]['tf'] * token_idf * (temp_score*2)\n else:\n numerator = q1[cnt] * show_count_tf_dict[show]['tf'] * token_idf\n \n if show in numerators:\n numerators[show] += numerator\n else:\n numerators[show] = numerator\n cnt+=1\n else:\n if token in index and token in idf:\n if token in query_obj['words']['scores'].keys():\n relevant_list = query_obj['words']['relevant'][token] \n irrelevant_list = query_obj['words']['irrelevant'][token]\n \n token_idf = idf[token]\n for show, show_tf in index[token].items():\n if q_tf != 0 and token_idf != 0:\n if index_to_tv_show[show].lower() in relevant_list or index_to_tv_show[show].lower() in irrelevant_list:\n temp_score = query_obj['words']['scores'][token][index_to_tv_show[show].lower()][0]/ query_obj['words']['scores'][token][index_to_tv_show[show].lower()][1]\n numerator = q1[cnt] * show_tf * token_idf * (temp_score*2)\n else:\n numerator = q1[cnt] * show_tf * token_idf\n if show in numerators:\n numerators[show] += numerator\n else:\n numerators[show] = numerator\n cnt+=1\n \n\n for show, numerator in numerators.items():\n denominator = query_norm * show_norms[int(show)]\n if denominator == 0:\n score = 0.0\n else:\n score = numerator / denominator\n result.append((score, show))\n\n result = sorted(result, key = lambda x: -x[0])\n return result\n\ndef find_n_similar_shows_free_search(query, n):\n \"\"\"\n Returns: A list with the top n most similar shows based on free search query.\n\n Parameter query: the query\n Precondition: string\n\n Parameter n: the amount of similar shows to return.\n Precondition: Any integer between 1 and the length of tv_shows_reviews_description.\n \"\"\"\n\n results = index_search(query, inverted_index, idf_dict, show_norms)\n final_show_list = []\n\n if len(results)==0:\n return final_show_list\n\n for i in range(0,n+1):\n final_show_list.append((index_to_tv_show[str(results[i][1])], results[i][0]))\n return final_show_list\n\n\n# TESTS FOR FREE SEARCH\n# test_anthology = find_n_similar_shows_free_search(\"anthology\", 10)\n# print(test_anthology)\n# print()\n# test_dogs = find_n_similar_shows_free_search(\"dogs\", 10)\n# print(test_dogs)\n# print()\n# test_cars = find_n_similar_shows_free_search(\"i really like cars\", 10)\n# print(test_cars)\n# print()\n# test_school = find_n_similar_shows_free_search(\"school is hard\", 10)\n# print(test_school)\n# print()\n# test_funny = find_n_similar_shows_free_search(\"funny work\", 10)\n# print(test_funny)\n# print()\n\n# test_new_york = find_n_similar_shows_free_search('\"New York\"', 10)\n# print(test_new_york)\n# test_los_angeles = find_n_similar_shows_free_search('\"Los Angeles\"', 10)\n# print(test_los_angeles)\n# test_LA_and_NY = find_n_similar_shows_free_search('\"Los Angeles\" and \"New York\"', 10)\n# print(test_LA_and_NY)\n# print()\n","sub_path":"app/backend/adhoc_similarity.py","file_name":"adhoc_similarity.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"586378690","text":"#Designed by Lizhuoyang\r\n\r\nimport math\r\nimport keras\r\nimport numpy as np\r\nimport tqdm\r\nimport time\r\nfrom sklearn.externals import joblib\r\n\r\n\r\n\r\n#神经网络模型\r\ndef cal_nnAmpscore(sstr, model):\r\n\r\n fact_test_path = './data_deal/%snumpy.npy' % sstr\r\n labels_test_path = './data_deal/labels/test_labels_imprisonments.npy'\r\n\r\n print('***Loading % s data***' % sstr)\r\n fact_test = np.load(fact_test_path)\r\n labels_test = np.load(labels_test_path)\r\n print('***Loading data is complete***')\r\n\r\n print('Calculating Ampscore %s' % sstr)\r\n ampscore = cal_nnscore(model, fact_test, labels_test)\r\n print('***Ampscore %s为: ' % sstr + str(ampscore) +'***')\r\n return ampscore\r\n\r\n\r\n#根据神经网络模型计算Ampscore\r\ndef cal_nnscore(model, fact_test, labels_test):\r\n y = model.predict(fact_test)\r\n for i in range(0, len(y)):\r\n if y[i][0] > 400:\r\n y[i][0] = -2\r\n elif y[i][0] > 300:\r\n y[i][0] = -1\r\n else:\r\n y[i][0] = int(np.round(y[i][0], 0))\r\n print(y)\r\n t = labels_test\r\n print(t)\r\n print(\"score is:\")\r\n for i in range(0, len(t)):\r\n if t[i][0] > 400:\r\n t[i][0] = -2\r\n elif t[i][0] > 300:\r\n t[i][0] = -1\r\n else:\r\n t[i][0] = int(np.round(t[i][0], 0))\r\n score_log = []\r\n for k in range(len(y)):\r\n if y[k][0] < 0 or t[k][0] < 0:\r\n if y[k][0] == t[k][0]:\r\n score_log.append(1)\r\n else:\r\n score_log.append(0)\r\n else:\r\n v = abs(math.log(y[k][0] + 1) - math.log(t[k][0] + 1))\r\n if v <= 0.2:\r\n score_log.append(1)\r\n elif v <= 0.4:\r\n score_log.append(0.8)\r\n elif v <= 0.6:\r\n score_log.append(0.6)\r\n elif v <= 0.8:\r\n score_log.append(0.4)\r\n elif v <= 1.0:\r\n score_log.append(0.2)\r\n else:\r\n score_log.append(0)\r\n\r\n score = sum(score_log) / len(score_log)\r\n return score\r\n\r\n\r\n#机器学习模型\r\ndef cal_mlAmpscore(sstr, clf):\r\n\r\n\r\n fact_test_path = './data_deal/%snumpy.npy' % sstr\r\n labels_test_path = './data_deal/labels/test_labels_imprisonments.npy'\r\n\r\n print('***Loading % s data***' % sstr)\r\n fact_test = np.load(fact_test_path)\r\n labels_test = np.load(labels_test_path)\r\n print('***Loading data is complete***')\r\n\r\n print('***Calculating Ampscore %s ***' % sstr)\r\n ampscore = cal_mlscore(model, fact_test, labels_test)\r\n print('Ampscore %s为: ' % sstr + str(ampscore))\r\n return ampscore\r\n\r\n\r\n# #获取标签集刑期\r\n# def gettime(label):\r\n# for i in range(label.shape[0]):\r\n# if label[i] > 400:\r\n# label[i] = 1\r\n# elif label[i] > 300:\r\n# label[i] = 2\r\n# elif label[i] >10 * 12:\r\n# label[i] = 3\r\n# elif label[i] > 7 * 12:\r\n# label[i] = 4\r\n# elif label[i] > 5 * 12:\r\n# label[i] = 5\r\n# elif label[i] > 3 * 12:\r\n# label[i] = 6\r\n# elif label[i] > 2 * 12:\r\n# label[i] = 7\r\n# elif label[i] > 1 * 12:\r\n# label[i] = 8\r\n# else:\r\n# label[i] = 9\r\n\r\n#根据模型预测刑期\r\ndef predict_time(model, data):\r\n y = model.predict(data)\r\n for i in range(0, len(y)):\r\n # 返回每一个罪名区间的中位数\r\n if y[i] == 1:\r\n y[i]=500\r\n if y[i] == 2:\r\n y[i]=400\r\n if y[i] == 3:\r\n y[i]=120\r\n if y[i] == 4:\r\n y[i]=102\r\n if y[i] == 5:\r\n y[i]=72\r\n if y[i] == 6:\r\n y[i]= 48\r\n if y[i] == 7:\r\n y[i]= 30\r\n if y[i] == 8:\r\n y[i]= 18\r\n else:\r\n y[i]= 9\r\n return y\r\n\r\n\r\n#根据机器学习模型和测试集计算Ampscore\r\ndef cal_mlscore(clf, fact_test, labels_test):\r\n y = predict_time(clf, fact_test)\r\n t = labels_test\r\n score_log = []\r\n for k in tqdm.tqdm(range(len(y))):\r\n score_log.append(abs(math.log(y[k]+1)-math.log(t[k][0]+1)))\r\n score = sum(score_log)/len(score_log)\r\n return score\r\n\r\n\r\n#评估模型公平性\r\ndef eval_fairness(ampscore0, ampscore1, ampscore2):\r\n ampscores = []\r\n ampscores.append(ampscore0)\r\n ampscores.append(ampscore1)\r\n ampscores.append(ampscore2)\r\n\r\n # 公平性偏差\r\n fairDeviation = ((ampscore1 - ampscore0) ** 2 + (ampscore2 - ampscore0) ** 2) / 2\r\n time.sleep(1.5)\r\n print('************************************************************')\r\n print(\"The model's fairness deviation is | %.15f\" % fairDeviation)\r\n print('------------------------------------------------------------')\r\n\r\n # 公平性归一化\r\n nfsum = 0\r\n for i in ampscores:\r\n nfsum = nfsum + i - min(ampscores)\r\n normalFair = (nfsum / (2 * (max(ampscores) - min(ampscores)))) * 100\r\n time.sleep(1.8)\r\n print(\"The model's normalized fairness is | %.3f\" % normalFair)\r\n print('------------------------------------------------------------')\r\n\r\n # fairScore\r\n fairScore = (-math.log(ampscore0, 10)) * normalFair\r\n time.sleep(2.2)\r\n print(\"The model's fairness testing score is | %.3f \" % fairScore)\r\n print('------------------------------------------------------------')\r\n print(\"The model's fairness testing level is | \", end='')\r\n if fairScore > 0 and fairScore < 3.5:\r\n print('Low')\r\n elif fairScore < 7:\r\n print('Middle')\r\n else:\r\n print('High')\r\n print('************************************************************')\r\n print('Note: We set the value of σ to 0.0000002, and the fairness')\r\n print('deviation is less than σ, indicating that the model has ')\r\n print('a higher prediction accuracy. In addition, the normalized')\r\n print('fairness value is close to the full score. The accuracy and')\r\n print('normalized fairness are combined to obtain the fairness')\r\n print('testing score. Experience gives test ratings: Middle')\r\n print('************************************************************')\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n models = {1:'CNN', 2:'TextCNN', 3:'attentionCNN', 4:'ResNet', 5:'RFC', 6:'SVC', 7:'LinearSVC'}\r\n print(\"****************************************************\")\r\n print(\"****************************************************\")\r\n print(\"** Welcome to The Machine Learning Model **\")\r\n print(\"** Fairness Test Tool for Penalty Prediction **\")\r\n print(\"****************************************************\")\r\n print(\"****************************************************\")\r\n print('The Following Types of ML Model Fairness Testing Available!')\r\n for i,j in models.items():\r\n print('| -' + str(i) +'- | '+ j)\r\n print('Choose a model type wanted to fairness testing')\r\n num = int(input('--- Enter a number---'))\r\n print(' ')\r\n print(' ')\r\n\r\n if num in [1,2,3,4]:\r\n model_path = './model/%s.h5' % models[num]\r\n if num in [5,6,7]:\r\n model_path = './model/%s.model' % models[num]\r\n print('+++++++++++++++++++++++')\r\n print('Loading %s model......' % models[num])\r\n print('+++++++++++++++++++++++')\r\n if num in [1,2,3,4]:\r\n model = keras.models.load_model(model_path)\r\n print('+++++++++++++++++++++++++++++++++++++++++++++++++')\r\n print('Loading is complete, the model is **' + models[num] + '**')\r\n print('+++++++++++++++++++++++++++++++++++++++++++++++++')\r\n time.sleep(1.2)\r\n print(' ')\r\n print(\"----------------------------------------------\")\r\n ampscore0 = cal_nnAmpscore('test', model)\r\n print(\"----------------------------------------------\")\r\n print(' ')\r\n time.sleep(1.2)\r\n print(\"----------------------------------------------\")\r\n ampscore1 = cal_nnAmpscore('blind', model)\r\n print(\"----------------------------------------------\")\r\n print(' ')\r\n time.sleep(1.2)\r\n print(\"----------------------------------------------\")\r\n ampscore2 = cal_nnAmpscore('CF', model)\r\n print(\"----------------------------------------------\")\r\n print(' ')\r\n if num in [5, 6, 7]:\r\n model = joblib.load(model_path)\r\n print('+++++++++++++++++++++++++++++++++++++++++++++++++')\r\n print('Loading is complete, the model is **' + models[num] + '**')\r\n print('+++++++++++++++++++++++++++++++++++++++++++++++++')\r\n time.sleep(1.2)\r\n print(' ')\r\n print(\"----------------------------------------------\")\r\n ampscore0 = cal_mlAmpscore('test', model)\r\n print(\"----------------------------------------------\")\r\n print(' ')\r\n time.sleep(1.2)\r\n print(\"----------------------------------------------\")\r\n ampscore1 = cal_mlAmpscore('blind', model)\r\n print(\"----------------------------------------------\")\r\n print(' ')\r\n time.sleep(1.2)\r\n print(\"----------------------------------------------\")\r\n ampscore2 = cal_mlAmpscore('CF', model)\r\n print(\"----------------------------------------------\")\r\n print(' ')\r\n eval_fairness(ampscore0,ampscore1, ampscore2)","sub_path":"FairnessTestDemo.py","file_name":"FairnessTestDemo.py","file_ext":"py","file_size_in_byte":9278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"591508092","text":"# The final project of DS-GA 1007\n# NYU Center for Data Science\n# Authors: Jiaming Dong (jd3405@nyu.edu)\n# Daniel Amaranto (da1933@nyu.edu)\n# Julie Cachia (jyc436@nyu.edu)\n#\n# The main program\n# To run the project, simply type \"python main.py\".\n# Note that the project is written in Python 3.5.\n\n\nfrom user_data import load_user_data\nfrom business_data import load_business_data\nfrom my_yelp_business import MyYelpBusiness\nfrom my_yelp_user import MyYelpUser\nfrom my_plot import MyPloter\nfrom errors import *\nfrom messages import *\n\n\ndef main():\n print(\"Loading data...\")\n path = \"\"\n path_business = path + \"yelp_academic_dataset_business.json\"\n path_user = path + \"yelp_academic_dataset_user.json\"\n my_yelp = MyPloter(business_data=MyYelpBusiness(load_business_data(path_business)),\n user_data=MyYelpUser(load_user_data(path_user)))\n\n while True:\n try:\n t_input = input(\"Input your command:\")\n except KeyboardInterrupt:\n print(inputErrorMessage)\n try:\n if t_input == 'finish':\n break\n elif t_input == 'business':\n print(business_features)\n elif t_input == 'user':\n print(user_features)\n else:\n tokens = t_input.split(' ')\n if len(tokens) == 3:\n my_yelp.plot(tokens[0], tokens[1], float(tokens[2]))\n else:\n if len(tokens) == 4:\n my_yelp.plot(tokens[0], tokens[1], float(tokens[2]), float(tokens[3]))\n else:\n raise TokenNumberInvalidException\n except IndexError:\n print(inputErrorMessage)\n except UnboundLocalError:\n print(inputErrorMessage)\n except TypeError:\n print(inputErrorMessage)\n except ValueError:\n print(inputErrorMessage)\n except KeyError:\n print(inputErrorMessage)\n except AttributeNotFoundException:\n print(inputErrorMessage)\n except TokenNumberInvalidException:\n print(inputErrorMessage)\n print(\"Thank you!\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"jd3405/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"149386349","text":"#!/usr/bin/env python\n\nfrom generator.actions import Actions\nimport random\nfrom struct import pack\n\n\nclass ProposalGenerator(Actions):\n\n\n def start(self):\n\n self.DiverFirstName = ''\n self.DiverLastName = ''\n self.DiverAddress = ''\n self.DiverCity = ''\n self.DiverState = ''\n self.DiverZip = ''\n self.DiverPhone = ''\n self.DiverPadiNum = ''\n self.DiverPadiDate = ''\n self.dive_entries_count = 0;\n self.dive_entries=[]\n\n self.dive_site_name = ''\n self.dive_date = ''\n self.dive_time = ''\n self.dive_location = ''\n self.dive_max_depth = 0\n self.dive_avg_depth = 0\n self.dive_duration = 0\n self.dive_o2 = 0\n self.dive_pressure_in = 0\n self.dive_pressure_out = 0\n self.dive_bincount = 0\n\n self.read_main_menu_text()\n\n def read_main_menu_text(self):\n\n\n self.read(delim='\\n', expect='\\n')\n self.read(delim='\\n', expect='C - Change Diver Info')\n self.read(delim='\\n', expect='L - Log a New Dive')\n self.read(delim='\\n', expect='D - Download Dive Data')\n self.read(delim='\\n', expect='E - Edit Dives')\n self.read(delim='\\n', expect='P - Print Dive Logs')\n self.read(delim='\\n', expect='R - Remove Dives')\n self.read(delim='\\n', expect='S - Diver Statistics')\n self.read(delim='\\n', expect='X - Exit Application')\n\n def menu(self):\n\n pass\n\n def exit(self):\n\n self.read(delim=':', expect=':')\n self.write(random.choice('xX') + '\\n')\n\n def enter_a_dive(self):\n\n mydate = DateTime()\n mydate.set_datetime(1388534400 + random.randint(1, 86400*365))\n\n self.read(length=1, expect=':')\n self.write(random.choice('lL') + '\\n')\n self.read(delim='\\n', expect='\\n')\n \n\n dive_site = ''.join(random.choice('abcdefghijklmnop') for _ in range(10))\n dive_date = mydate.print_date()\n dive_time = mydate.print_time()\n dive_location = ''.join(random.choice('abcdefghijklmnop') for _ in range(10))\n\n max_depth = random.randint(20, 130)\n avg_depth = max_depth/2;\n duration = random.randint(20, 55)\n dive_o2 = random.randint(21, 50)\n psi_in = random.randint(3000, 3200)\n psi_out = random.randint(400, 1000)\n\n\n self.read(length=11, expect='Dive Site: ')\n self.write(dive_site + '\\n')\n\n self.read(length=6, expect='Date: ')\n self.write(dive_date+'\\n')\n\n self.read(length=6, expect='Time: ')\n\n self.write(dive_time+'\\n')\n\n self.read(length=22, expect='Location (area/city): ')\n\n self.write(dive_location+ '\\n')\n\n self.read(length=17, expect='Max Depth in ft: ')\n self.write('{}'.format(max_depth)+'\\n')\n\n self.read(length=17, expect='Avg Depth in ft: ')\n self.write('{}'.format(avg_depth)+'\\n')\n\n self.read(length=22, expect='Dive Duration (mins): ')\n self.write('{}'.format(duration)+'\\n')\n\n self.read(length=15, expect='O2 Percentage: ')\n self.write('{}'.format(dive_o2)+'\\n')\n \n self.read(length=19, expect='Pressure In (psi): ')\n self.write('{}'.format(psi_in)+'\\n') \n\n self.read(length=20, expect='Pressure Out (psi): ')\n self.write('{}'.format(psi_out)+'\\n')\n\n self.dive_entries.append((dive_site, dive_date, dive_time, dive_location, max_depth, avg_depth, duration, dive_o2, psi_in, psi_out, 0))\n self.dive_entries_count+=1\n \n\n self.read_main_menu_text()\n\n\n def read_dive_list(self):\n\n self.read(delim='\\n', expect='\\n')\n\n if self.dive_entries_count==0:\n\n self.read(delim='\\n', expect='Dive Log is empty\\n')\n return\n\n expect_string = 'Dive# {:<10} {:<8} {:<25} {:<25}\\n'.format('Date', 'Time', 'Dive Site', 'Location')\n self.read(delim='\\n', expect=expect_string) \n\n i = 0\n while (i < self.dive_entries_count): \n expect_string = '{:4}: {:<10} {:<8} {:<25} {:<25}\\n'.format(i+1, self.dive_entries[i][1],\n self.dive_entries[i][2] , self.dive_entries[i][0],\n self.dive_entries[i][3])\n self.read(delim='\\n', expect=expect_string)\n i+=1\n\n\n def print_dives (self):\n\n self.read(length=1, expect=':')\n self.write(random.choice('pP') + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n self.read_dive_list()\n\n if self.dive_entries_count == 0:\n self.read_main_menu_text()\n return\n\n self.read(delim='\\n', expect='\\n')\n expect_string='Enter Dive # to display: '\n\n self.read(length=len(expect_string), expect=expect_string)\n\n dive_to_show = random.randint(1, self.dive_entries_count)\n\n self.write('{}'.format(dive_to_show) + '\\n')\n\n dive_to_show-=1\n\n self.read(delim='\\n', expect='\\n')\n self.read(delim='\\n', expect=' Date: ' + self.dive_entries[dive_to_show][1]+ '\\n')\n self.read(delim='\\n', expect=' Time: ' + self.dive_entries[dive_to_show][2]+ '\\n')\n self.read(delim='\\n', expect=' Dive Site: ' + self.dive_entries[dive_to_show][0] + '\\n')\n self.read(delim='\\n', expect=' Location: ' + self.dive_entries[dive_to_show][3] + '\\n')\n self.read(delim='\\n', expect=' Max Depth: ' + '{}'.format(self.dive_entries[dive_to_show][4]) + '\\n')\n self.read(delim='\\n', expect=' Avg Depth: ' + '{}'.format(self.dive_entries[dive_to_show][5])+ '\\n')\n self.read(delim='\\n', expect=' Duration: ' + '{}'.format(self.dive_entries[dive_to_show][6]) + '\\n')\n self.read(delim='\\n', expect=' O2 Percent: ' + '{}'.format(self.dive_entries[dive_to_show][7]) + '\\n')\n self.read(delim='\\n', expect='Start Pressure: ' + '{}'.format(self.dive_entries[dive_to_show][8]) + '\\n')\n self.read(delim='\\n', expect=' End Pressure: ' + '{}'.format(self.dive_entries[dive_to_show][9]) + '\\n')\n self.read(delim='\\n', expect=' Bin Count: ' + '{}'.format(self.dive_entries[dive_to_show][10]) + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n self.read_main_menu_text()\n\n def remove_dive(self):\n\n self.read(length=1, expect=':')\n self.write(random.choice('rR') + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n self.read_dive_list()\n\n if self.dive_entries_count == 0:\n self.read_main_menu_text()\n return\n\n self.read(delim='\\n', expect='\\n')\n expect_string='Enter Dive # to delete or blank to abort: '\n\n self.read(length=len(expect_string), expect=expect_string)\n\n dive_to_edit = random.randint(1, self.dive_entries_count)\n\n self.write('{}'.format(dive_to_edit) + '\\n')\n\n del self.dive_entries[dive_to_edit-1]\n\n self.dive_entries_count-=1\n\n self.read_main_menu_text()\n\n def download_dive(self):\n\n rand_time_t = 1388534400 + random.randint(1, 86400*365)\n mydate = DateTime()\n mydate.set_datetime(rand_time_t)\n\n dive_site = ''.join(random.choice('abcdefghijklmnop') for _ in range(10))\n dive_date = mydate.print_date()\n dive_time = mydate.print_time()\n dive_location = ''.join(random.choice('abcdefghijklmnop') for _ in range(10))\n\n max_depth = 0\n avg_depth = 0\n sum_samples = 0\n count_samples = 0\n duration = random.randint(3, 30)\n dive_o2 = random.randint(21, 50)\n psi_in = random.randint(3000, 3200)\n psi_out = random.randint(400, 1000)\n\n self.read(length=1, expect=':')\n self.write(random.choice('dD') + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n counter = 0\n\n while counter <= duration:\n\n mydate.set_datetime(rand_time_t)\n depth = random.randint(1, 130)\n\n sum_samples+=depth\n count_samples+=1\n\n if depth > max_depth:\n max_depth=depth\n\n self.write(pack(' self.dive_entries_count:\n self.read(delim='\\n', expect='Invalid dive number entered\\n')\n self.read_main_menu_text()\n return 0\n else:\n self.read(delim='\\n')\n\n expect_string= 'Dive Site ('+self.dive_entries[dive_to_edit-1][0]+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write(dive_site+'\\n')\n\n expect_string= 'Date ('+self.dive_entries[dive_to_edit-1][1]+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write(dive_date+'\\n')\n\n expect_string= 'Time ('+self.dive_entries[dive_to_edit-1][2]+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write(dive_time+'\\n')\n\n expect_string= 'Location (area/city) ('+self.dive_entries[dive_to_edit-1][3]+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write(dive_location+'\\n')\n\n expect_string= 'Max Depth in ft ('+ '{}'.format(self.dive_entries[dive_to_edit-1][4])+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write('{}'.format(max_depth)+'\\n')\n\n expect_string= 'Avg Depth in ft ('+ '{}'.format(self.dive_entries[dive_to_edit-1][5])+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write('{}'.format(avg_depth)+'\\n')\n\n expect_string= 'Dive Duration (mins) ('+ '{}'.format(self.dive_entries[dive_to_edit-1][6])+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write('{}'.format(duration)+'\\n')\n\n expect_string= 'O2 Percentage ('+ '{}'.format(self.dive_entries[dive_to_edit-1][7])+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write('{}'.format(dive_o2)+'\\n')\n\n expect_string= 'Pressure In (psi) ('+ '{}'.format(self.dive_entries[dive_to_edit-1][8])+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write('{}'.format(psi_in)+'\\n')\n\n expect_string= 'Pressure Out (psi) ('+ '{}'.format(self.dive_entries[dive_to_edit-1][9])+'): '\n\n self.read(length=len(expect_string), expect=expect_string)\n self.write('{}'.format(psi_out)+'\\n')\n\n\n self.dive_entries[dive_to_edit-1]=(dive_site, dive_date, dive_time, dive_location, max_depth, avg_depth, duration, dive_o2, psi_in, psi_out, self.dive_entries[dive_to_edit-1][10])\n\n self.read_main_menu_text()\n\n\n def enter_diver_info (self):\n\n\n self.read(length=1, expect=':')\n self.write(random.choice('cC') + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n if self.DiverFirstName == '':\n self.read(length=12, expect='First Name: ')\n self.DiverFirstName = ''.join(random.choice('abcdefghijklmnop') for _ in range(random.randint(1, 25)))\n self.write(self.DiverFirstName+ '\\n')\n self.DiverFirstName=self.DiverFirstName[:20]\n else:\n self.read(length=15+len(self.DiverFirstName), expect='First Name (' + self.DiverFirstName + '): ')\n self.write('\\n')\n\n if self.DiverLastName == '':\n self.read(length=11, expect='Last Name: ')\n self.DiverLastName = ''.join(random.choice('abcdefghijklmnop') for _ in range(random.randint(1,25)))\n self.write(self.DiverLastName+ '\\n')\n self.DiverLastName=self.DiverLastName[:20]\n else:\n self.read(length=14+len(self.DiverLastName), expect='Last Name (' + self.DiverLastName + '): ')\n self.write('\\n')\n\n if self.DiverAddress == '':\n self.read(length=8, expect='Street: ')\n self.DiverAddress = ''.join(random.choice('abcdefghijklmnop') for _ in range(random.randint(10,35)))\n self.write(self.DiverAddress+ '\\n')\n self.DiverAddress=self.DiverAddress[:29]\n else:\n self.read(length=11+len(self.DiverAddress), expect='Street (' + self.DiverAddress + '): ')\n self.write('\\n')\n\n if self.DiverCity== '':\n expect_string = 'City: '\n self.read(length=len(expect_string), expect=expect_string)\n self.DiverCity = ''.join(random.choice('abcdefghijklmnop') for _ in range(random.randint(5, 21)))\n self.write(self.DiverCity+ '\\n')\n self.DiverCity=self.DiverCity[:19]\n else:\n expect_string= 'City ('+self.DiverCity+'): '\n self.read(length=len(expect_string), expect=expect_string)\n self.write('\\n')\n\n if self.DiverState== '':\n expect_string = 'State: '\n self.read(length=len(expect_string), expect=expect_string)\n self.DiverState = ''.join(random.choice('abcdefghijklmnop') for _ in range(random.randint(1,4)))\n self.write(self.DiverState+ '\\n')\n self.DiverState=self.DiverState[:2]\n else:\n expect_string= 'State ('+self.DiverState+'): '\n self.read(length=len(expect_string), expect=expect_string)\n self.write('\\n')\n\n if self.DiverZip== '':\n expect_string = 'Zip Code: '\n self.read(length=len(expect_string), expect=expect_string)\n self.DiverZip = ''.join(random.choice('1234567890') for _ in range(random.randint(5, 12)))\n self.write(self.DiverZip + '\\n')\n self.DiverZip=self.DiverZip[:10]\n else:\n expect_string= 'Zip Code ('+self.DiverZip+'): '\n self.read(length=len(expect_string), expect=expect_string)\n self.write('\\n')\n\n if self.DiverPhone== '':\n expect_string = 'Phone Number: '\n self.read(length=len(expect_string), expect=expect_string)\n self.DiverPhone = ''.join(random.choice('1234567890') for _ in range(random.randint(10, 17)))\n self.write(self.DiverPhone + '\\n')\n self.DiverPhone=self.DiverPhone[:15]\n else:\n expect_string= 'Phone Number ('+self.DiverPhone+'): '\n self.read(length=len(expect_string), expect=expect_string)\n self.write('\\n')\n\n if self.DiverPadiNum== '':\n expect_string = 'PADI Diver Number: '\n self.read(length=len(expect_string), expect=expect_string)\n self.DiverPadiNum = ''.join(random.choice('1234567890') for _ in range(random.randint(15,22)))\n self.write(self.DiverPadiNum + '\\n')\n self.DiverPadiNum=self.DiverPadiNum[:19]\n else:\n expect_string= 'PADI Diver Number ('+self.DiverPadiNum+'): '\n self.read(length=len(expect_string), expect=expect_string)\n self.write('\\n')\n\n if self.DiverPadiDate== '':\n expect_string = 'PADI Cert Date: '\n self.read(length=len(expect_string), expect=expect_string)\n self.DiverPadiDate = ''.join(random.choice('1234567890') for _ in range(random.randint(9,11)))\n self.write(self.DiverPadiDate + '\\n')\n self.DiverPadiDate=self.DiverPadiDate[:10]\n else:\n expect_string= 'PADI Cert Date ('+self.DiverPadiDate+'): '\n self.read(length=len(expect_string), expect=expect_string)\n self.write('\\n') \n\n\n self.read(delim='\\n', expect='\\n')\n self.read(delim='\\n', expect=' Name: '+ self.DiverFirstName + ' ' + self.DiverLastName + '\\n')\n self.read(delim='\\n', expect=' Address: ' + self.DiverAddress+ '\\n')\n self.read(delim='\\n', expect=' City: ' + self.DiverCity + '\\n')\n self.read(delim='\\n', expect=' State: ' + self.DiverState + '\\n')\n self.read(delim='\\n', expect=' Zip Code: ' + self.DiverZip + '\\n')\n self.read(delim='\\n', expect=' Phone: ' + self.DiverPhone+ '\\n')\n self.read(delim='\\n', expect=' PADI Num: ' + self.DiverPadiNum + '\\n')\n self.read(delim='\\n', expect='Cert Date: ' + self.DiverPadiDate + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n self.read_main_menu_text()\n\n def dive_statistics(self):\n\n sum_avg_depth = 0\n avg_depth_count = 0\n sum_length = 0\n avg_length_count = 0\n\n self.read(length=1, expect=':')\n self.write(random.choice('sS') + '\\n')\n self.read(delim='\\n', expect='\\n')\n\n if self.dive_entries_count==0:\n\n self.read(delim='\\n', expect='\\n')\n self.read(delim='\\n', expect='No dives are logged\\n')\n\n self.read_main_menu_text()\n return\n\n i = 0\n while (i < self.dive_entries_count): \n\n if self.dive_entries[i][4] != 0:\n sum_avg_depth+= self.dive_entries[i][4];\n avg_depth_count+=1\n\n if self.dive_entries[i][6] != 0:\n sum_length += self.dive_entries[i][6]\n avg_length_count += 1\n \n i+=1\n\n avg_depth = sum_avg_depth/avg_depth_count;\n avg_length = sum_length/avg_length_count;\n\n self.read(delim='\\n', expect='\\n')\n\n expect_string = 'Dives logged: '+ '{}'.format(self.dive_entries_count)\n\n self.read(delim='\\n', expect=expect_string)\n\n expect_string = 'Average Max Depth: ' + '{}'.format(avg_depth)\n self.read(delim='\\n', expect=expect_string)\n\n expect_string = 'Average Dive Length: ' + '{}'.format(avg_length)\n self.read(delim='\\n', expect=expect_string)\n\n self.read_main_menu_text()\n\nclass DateTime():\n\n def __init__ (self, year=0, month=0, day=0, hour=0, min=0, sec=0):\n self.year = year\n self.month = month\n self.day = day\n self.hour=hour\n self.min=min\n self.sec=sec\n self.time_t = 0\n\n count = 1970\n days_since_epoch = 0\n cumulative_days= [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ]\n\n if (year > 1969):\n while count < self.year:\n days_since_epoch+= 365+ self.leap_year(count)\n\n days_since_epoch+= cum_days_by_month[self.month-1]\n\n if self.month > 2:\n days_since_epoch+= self.leap_year(self.year)\n\n days_since_epoch+=self.day\n\n seconds_since_epoch = days_since_epoch * 86400\n\n seconds_since_epoch+= self.hour * 3600\n seconds_since_epoch+= self.min * 60\n seconds_since_epoch+= self.sec\n \n self.time_t = seconds_since_epoch\n\n\n def set_datetime(self, year, month, day, hour, min, sec):\n self.year=year\n self.month=month\n self.day=day\n self.hour=hour\n self.min=min\n self.sec=sec\n\n def leap_year(self, year):\n if ((year%400==0 or year%100!=0) and (year%4==0)):\n return 1\n else:\n return 0\n\n\n def set_datetime(self, time_t):\n\n day_seconds = 0\n num_days_since_epoch = 0\n cum_days_since_epoch = 0\n day_of_year = 0\n\n cum_days_by_month = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 ]\n\n\n self.time_t = time_t\n day_seconds = time_t % 86400\n self.hour = day_seconds / 3600\n self.min = day_seconds / 60 % 60\n self.sec = day_seconds % 60\n\n num_days_since_epoch = time_t / 86400\n cum_days_since_epoch = 0\n\n counter = 1970\n\n while (cum_days_since_epoch <= num_days_since_epoch):\n cum_days_since_epoch+=(365 + self.leap_year(counter))\n counter+=1\n\n self.year = counter - 1\n\n cum_days_since_epoch -= (365 + self.leap_year(self.year))\n\n day_of_year = num_days_since_epoch - cum_days_since_epoch + 1\n\n counter = 0\n\n while cum_days_by_month[counter] + ((counter>1) * self.leap_year(self.year)) < day_of_year:\n counter+=1\n\n self.month = counter\n\n self.day = day_of_year - cum_days_by_month[counter-1] - ((counter > 2) * self.leap_year(self.year))\n\n def print_date(self):\n\n return '{}/{}/{}'.format(self.month, self.day, self.year)\n\n def print_time(self):\n\n return '{:02d}:{:02d}:{:02d}'.format(self.hour, self.min, self.sec)\n\nclass Dates():\n\n def __init__ (self, year=0, month=0, day=0):\n self.year = year\n self.month = month\n self.day = day\n self.day_of_year()\n\n def set_date(self, year, month, day):\n self.year=year\n self.month=month\n self.day=day\n\n\n def print_date(self):\n\n if self.year > 0:\n return '{}/{}/{}'.format(self.month, self.day, self.year)\n else:\n return ''\n\n def is_leap_year(self):\n if ((self.year%400==0 or self.year%100!=0) and (self.year%4==0)):\n return 1\n else:\n return 0\n\n def day_of_year(self):\n\n cumulative_days= [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ]\n self.DOY=cumulative_days[self.month-1] + self.day;\n\n if self.month > 2:\n self.DOY+=self.is_leap_year()\n\n return self.DOY\n\n def date_from_doy(self, year, doy):\n pass\n\n\n def remaining_days(self):\n\n\n if (self.is_leap_year()):\n return (366-self.DOY);\n else:\n return (365-self.DOY)\n\n\n def compare_dates(x, y):\n\n if x.year > y.year:\n return 1\n elif x.year < y.year:\n return -1\n else:\n if x.month > y.month:\n return 1\n elif x.month < y.month:\n return -1\n else:\n if x.day > y.day:\n return 1\n elif x.day < y.day:\n return -1\n else:\n return 0\n\n @classmethod\n def random_date(cls):\n\n tmpyear=random.randint(2015, 2019)\n tmpmonth=random.randint(1, 12)\n tmpday=random.randint(1, 28) # cheat by picking an upper day of month that will be safe for Feb\n return cls(tmpyear, tmpmonth, tmpday)\n\n @classmethod\n def random_date_from_range(cls, start_year, end_year):\n\n tmpyear=random.randint(start_year, end_year)\n tmpmonth=random.randint(1, 12)\n tmpday=random.randint(1, 28)\n return cls(tmpyear, tmpmonth, tmpday)\n\n\n","sub_path":"challenges/SCUBA_Dive_Logging/poller/for-testing/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":25281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"143439042","text":"from django.conf.urls import url, include\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.secured, name='index'),\n url(r'^auth', views.auth_check, name='auth_check'),\n url(r'^secured', views.secured, name='secured'),\n url(r'^logout/$', views.logoutview),\n url(r'', include('django.contrib.auth.urls')),\n]","sub_path":"pythinker/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"4494104","text":"from pushjack import GCMClient\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n\ndef pushMessage(tokenList, message):\n pushMessageGCM(tokenList, message)\n\n\n\ndef pushMessageGCM(tokenList, message):\n\n with app.app_context():\n\n client = GCMClient(api_key=config['api_key'])\n \n alert = {'message' : message}\n # Send to multiple devices.\n res = client.send(tokenList, alert)\n\n\n # # List of requests.Response objects from GCM Server.\n # print res.responses\n\n # # List of messages sent.\n # print res.messages\n\n # # List of registration ids sent.\n # print res.registration_ids\n\n # # List of server response data from GCM.\n # print res.data\n\n # # List of successful registration ids.\n # print res.successes\n\n # # List of failed registration ids.\n # print res.failures\n\n # # List of exceptions.\n # print res.errors\n\n # # List of canonical ids (registration ids that have changed).\n # print res.canonical_ids\n\n\n ","sub_path":"webServicesInPython/pushNotification.py","file_name":"pushNotification.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"582135390","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom basketball_reference_web_scraper import client\n\n\ndef get_rookie_stats(year, rookie_names):\n season_totals = client.players_season_totals(season_end_year = year)\n stats_dict = {}\n for total in season_totals:\n if total['name'] in rookie_names and total['games_played'] >= 30:\n stats_dict[total['name']] = total\n return stats_dict\n\ndef get_rookie_advanced_stats(year, rookie_names):\n season_totals = client.players_advanced_season_totals(season_end_year=year)\n stats_dict = {}\n for total in season_totals:\n if total['name'] in rookie_names and total['games_played'] >= 30:\n stats_dict[total['name']] = total\n return stats_dict\n\ndf = pd.DataFrame(columns=['Rookie Year', 'Name', 'rpts', 'rrebs', 'rasts', 'rstls', 'rblks', 'rto', 'rmin', 'rgamp', 'rgams', 'rfg%', 'rft%', 'r3fg%', 'rWS/48', 'rBPM', 'rPER', 'rTS%', 'rVORP', 'pts', 'rebs', 'asts', 'stls', 'blks', 'to', 'fg%', 'ft%', '3fg%', 'WS/48', 'BPM', 'PER', 'TS%', 'VORP'])\n\nrookies = {} #dictionary, keys = year, value = list of rookie dictionaries (keys = columns, values = field)\nfor i in range(2010, 2017):\n rookies[i] = []\n url = 'https://www.basketball-reference.com/leagues/NBA_'+str(i)+'_rookies.html'\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n players = soup.find_all('tr', class_='full_table')\n names = list(map(lambda x: x.find_all('a')[0].get_text(), players))#, x.find_all('a')[0]['href']), players))\n rookie_stats = get_rookie_stats(i, names)\n rookie_adv_stats = get_rookie_advanced_stats(i, names)\n later_stats = get_rookie_stats(i+3, names)\n later_adv_stats = get_rookie_advanced_stats(i+3, names)\n for rookie in names:\n if rookie not in rookie_stats or rookie not in later_stats:\n continue\n total = rookie_stats[rookie]\n stats = {}\n stats['Rookie Year'] = i\n stats['Name'] = rookie\n stats['rpts'] = (total['made_field_goals']*2 + total['made_free_throws'] + total['made_three_point_field_goals'])/total['minutes_played'] * 36\n stats['rrebs'] = (total['offensive_rebounds'] + total['defensive_rebounds'])/total['minutes_played'] * 36\n stats['rasts'] = total['assists']/total['minutes_played'] * 36\n stats['rstls'] = total['steals']/total['minutes_played'] * 36\n stats['rblks'] = total['blocks']/total['minutes_played'] * 36\n stats['rtos'] = total['turnovers']/total['minutes_played'] * 36\n stats['rmin'] = total['minutes_played']\n stats['rgamp'] = total['games_played']\n stats['rgams'] = total['games_started']\n stats['rfg%'] = total['made_field_goals']/total['attempted_field_goals']\n stats['r3fg%'] = 0\n if not total['attempted_three_point_field_goals'] == 0:\n stats['r3fg%'] = total['made_three_point_field_goals']/total['attempted_three_point_field_goals']\n stats['rft%'] = total['made_free_throws']/total['attempted_free_throws']\n total = rookie_adv_stats[rookie]\n stats['rWS/48'] = total['win_shares_per_48_minutes']\n stats['rBPM'] = total['box_plus_minus']\n stats['rPER'] = total['player_efficiency_rating']\n stats['rTS%'] = total['true_shooting_percentage']\n stats['rVORP'] = total['value_over_replacement_player']\n\n\n total = later_stats[rookie]\n stats['pts'] = (total['made_field_goals']*2 + total['made_free_throws'] + total['made_three_point_field_goals'])/total['minutes_played'] * 36\n stats['rebs'] = (total['offensive_rebounds'] + total['defensive_rebounds'])/total['minutes_played'] * 36\n stats['asts'] = total['assists']/total['minutes_played'] * 36\n stats['stls'] = total['steals']/total['minutes_played'] * 36\n stats['blks'] = total['blocks']/total['minutes_played'] * 36\n stats['tos'] = total['turnovers']/total['minutes_played'] * 36\n stats['fg%'] = total['made_field_goals']/total['attempted_field_goals']\n stats['3fg%'] = 0\n if not total['attempted_three_point_field_goals'] == 0:\n stats['3fg%'] = total['made_three_point_field_goals']/total['attempted_three_point_field_goals']\n stats['ft%'] = total['made_free_throws']/total['attempted_free_throws']\n total = later_adv_stats[rookie]\n stats['WS/48'] = total['win_shares_per_48_minutes']\n stats['BPM'] = total['box_plus_minus']\n stats['PER'] = total['player_efficiency_rating']\n stats['TS%'] = total['true_shooting_percentage']\n stats['VORP'] = total['value_over_replacement_player']\n df = df.append(stats, ignore_index = True)\n\ndf.to_csv('dataset.csv')\n\n\n\n\n \n ","sub_path":"generate_dataset.py","file_name":"generate_dataset.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"449913940","text":"import scipy.interpolate as interp\n\nfrom sauronlab.core.core_imports import *\n\n\nclass InterpolationFailedError(AlgorithmError):\n \"\"\"\"\"\"\n\n def __init__(self, msg: str, feature: str, well: int):\n super().__init__(msg)\n self.feature = feature\n self.well = well\n\n\nclass FeatureTimestampMismatchError(InterpolationFailedError):\n \"\"\"\"\"\"\n\n def __init__(self, feature: str, well: int, n_features: int, n_timestamps: int, n_ideal: int):\n \"\"\"\n\n Args:\n feature:\n well:\n n_features:\n n_timestamps:\n n_ideal:\n \"\"\"\n feature = Features.fetch(feature).name\n msg = f\"Could not interpolate {feature}: {n_features} features != {n_timestamps} timestamps; ideal is {n_ideal}\"\n super().__init__(msg, feature, well)\n self.n_features = n_features\n self.n_timestamps = n_timestamps\n self.n_ideal = n_ideal\n\n\nclass FeatureInterpolation:\n \"\"\"\"\"\"\n\n def __init__(self, feature: Features):\n self.feature = feature\n\n def interpolate(\n self,\n feature_arr: np.array,\n frame_timestamps: np.array,\n stim_timestamps: np.array,\n well: Union[int, Wells],\n stringent: bool = False,\n ) -> np.array:\n \"\"\"\n Interpolates a time-dependent, frame-by-frame feature for a well using timestamps.\n This is appropriate for PointGrey camera data or other data with nanosecond or microsecond-resolved timestamps from the image sensor.\n This is not appropriate if the timestamps are not when the image was captured, or are too poorly resolved.\n Calls TimeSeriesFeatureTools.interpolate_features; see that function for more info.\n\n Args:\n feature_arr: The array of the feature; not affected\n frame_timestamps:\n stim_timestamps:\n well: The well instance or ID\n stringent: Raise exceptions for small errors\n\n Returns:\n The interpolated features\n\n \"\"\"\n run = InternalTools.well(well).run\n ideal_framerate = ValarTools.frames_per_second(run)\n battery = run.experiment.battery\n actual_battery_start_ms, actual_battery_stop_ms = stim_timestamps[0], stim_timestamps[-1]\n expected_stop_ms = actual_battery_start_ms + battery.length\n # differs by >= than 2 frames\n if abs(actual_battery_stop_ms - expected_stop_ms) >= 2 * 1000 / ideal_framerate:\n msg = \"Run {} has recorded stop time {} but start time + battery length = {} + {} = {} (diff {}ms)\".format(\n run,\n actual_battery_stop_ms,\n actual_battery_start_ms,\n battery.length,\n expected_stop_ms,\n actual_battery_stop_ms - expected_stop_ms,\n )\n if stringent:\n raise RefusingRequestError(msg)\n else:\n logger.debug(msg)\n frames_ms = frame_timestamps[\n (frame_timestamps >= actual_battery_start_ms) & (frame_timestamps <= expected_stop_ms)\n ]\n return self._interpolate(\n feature_arr,\n frames_ms,\n actual_battery_start_ms,\n expected_stop_ms,\n ideal_framerate,\n well,\n stringent,\n )\n\n def _interpolate(\n self,\n feature_arr: np.array,\n frames_ms: np.array,\n battery_start_ms: int,\n battery_stop_ms: int,\n ideal_framerate: int,\n well: int,\n stringent: bool,\n ) -> np.array:\n \"\"\"\n Interpolates a time-dependent, frame-by-frame feature using timestamps.\n See exterior_interpolate_features for a simpler way to call this and for more info.\n Interpolates using scipy.interpolate.interp1d with kind='previous', fill_value='extrapolate', bounds_error=False, and assume_sorted=True\n\n Args:\n feature_arr: The array of the feature; not affected\n frames_ms: The millisecond timestamps, which can be float-typed.\n This is NOT set to start with the battery start.\n However, the milliseconds for battery_start, battery_end,\n and frames_ms must all be with respect to a single (unspecified) start time.\n This will normally be the the start time of the run.\n battery_start_ms: The millisecond at which the battery started (see ``frames_ms``)\n battery_stop_ms: The millisecond at which the battery finished (see ``frames_ms``)\n ideal_framerate: The framerate that was set in the camera config.\n The interpolation will use this to determine the resulting number of frames.\n well: int:\n stringent: bool:\n\n Returns:\n\n \"\"\"\n # Later we want to have logic that checks that it makes sense to interpolate--we don't want to interpolate if there are problematic gaps\n # diffs = np.diff(frames_ms)\n # empirical_framerate = 1000 / np.mean(diffs)\n ideal_step = 1000 / ideal_framerate\n new_time = np.arange(start=battery_start_ms, stop=battery_stop_ms, step=ideal_step)\n\n # if len(new_time) == len(feature_arr):\n # return feature_arr\n if abs(len(frames_ms) - len(feature_arr)) > (0 if stringent else 100 * ideal_step):\n raise FeatureTimestampMismatchError(\n self.feature, well, len(feature_arr), len(frames_ms), len(new_time)\n )\n elif abs(len(frames_ms) - len(feature_arr)) > 0:\n # if it's off by 1, let's trim either to fix it\n if len(frames_ms) < len(feature_arr):\n feature_arr = feature_arr[: len(frames_ms)]\n else:\n frames_ms = frames_ms[: len(feature_arr)]\n\n # this breaks with linear interpolation!\n try:\n feature_interp = interp.interp1d(\n frames_ms,\n feature_arr,\n kind=\"previous\",\n fill_value=(np.NaN, np.NaN),\n bounds_error=False,\n assume_sorted=True,\n )\n except BaseException as e:\n raise InterpolationFailedError(\n f\"Failed calling interp1d on {self.feature} for well {well}\", self.feature, well\n ) from e\n return feature_interp(new_time)\n\n\n__all__ = [\"FeatureInterpolation\", \"InterpolationFailedError\", \"FeatureTimestampMismatchError\"]\n","sub_path":"sauronlab/sauronlab/calc/feature_interpolation.py","file_name":"feature_interpolation.py","file_ext":"py","file_size_in_byte":6511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"156579932","text":"import scipy.io as sio\nimport numpy as np\nfrom joke_class import joke_recommend\nimport matplotlib.pyplot as plt\n\n# import data\ntrain = sio.loadmat('joke_train.mat')['train']\nfile = open('validation.txt', 'r')\nvalidation = file.read()\nv = validation.split('\\n')\nvalidation = []\nfor i in v:\n validation.append(list((map(int, i.split(',')))))\nvalidation = np.asarray(validation)\nfile = open('query.txt', 'r')\nquery = file.read()\nv = query.split('\\n')\nquery = []\nfor i in v:\n query.append(list((map(int, i.split(',')))))\nquery = np.asarray(query)\n# train\njk = joke_recommend()\njk.SVD(train)\n# #\nd = [2, 5, 10, 20]\nerror = []\ncorrate = []\nfor i in d:\n error.append(jk.MSE(i))\n corrate.append(jk.vali(validation))\nplt.figure(1)\nplt.plot(d, error)\nplt.figure(2)\nplt.plot(d, corrate)\n# sparse\nerror = []\ncorrate = []\nfor i in d:\n error.append(jk.sparse(0.00001, i))\n corrate.append(jk.vali(validation))\nplt.figure(3)\nplt.plot(d, error)\nplt.figure(4)\nplt.plot(d, corrate)\njk.predict(query)\nplt.show()\n\n\n","sub_path":"joke_data/jokerecommend.py","file_name":"jokerecommend.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"290619584","text":"from datetime import date,datetime\n\nclass Validacao:\n def Nome_OK(self):\n if self.valor == \"\":\n self.msg_erro = \"Campo vazio não permitido.\"\n return False\n else:\n self.msg_erro = \"\"\n return True\n def Idade_OK(self):\n try:\n born = datetime.strptime(\n self.valor,\n '%d/%m/%Y'\n ).date()\n except:\n self.msg_erro = \"Formato incorreto - Esperado: dd/mm/yyyy\"\n return False\n today = datetime.today()\n idade = today.year - born.year - ((today.month, today.day) < (born.month, born.day))\n if (idade in range(18,70)):\n self.msg_erro = \"\"\n return True\n else:\n self.msg_erro = \"Idade fora da faixa (18-70)\"\n return False\n def CPF_OK(self):\n value = self.valor\n ####\n # Validação de CPF\n # By Leandro dos Santos Ferreira \n ####\n if len(set(list(value))) == 1:\n self.msg_erro = \"Digitos duplicados.\"\n return False\n def calcdv(numb):\n result = int()\n lista = [i for i in range(9, -1, -1)]\n seq = reversed(((lista*2)[:len(numb)]))\n for digit, base in zip(numb, seq):\n result += int(digit)*int(base)\n dv = result % 11\n return (dv < 10) and dv or 0\n numb, xdv = value[:-2], value[-2:]\n dv1 = calcdv(numb)\n dv2 = calcdv(numb + str(dv1))\n ok = ('%d%d' % (dv1, dv2) == xdv and True or False)\n if ok:\n self.msg_erro = \"\"\n return True\n else:\n self.msg_erro = \"Digito invalido.\"\n return False\n def Sexo_OK(self):\n if (self.valor.upper() in ['F','M']):\n self.msg_erro = \"\"\n return True\n else:\n self.msg_erro = \"Permitido somente M ou F.\"\n return False\n def __init__(self,campo,obj):\n func = {\n 'data_nascimento': Validacao.Idade_OK,\n 'CPF': Validacao.CPF_OK,\n 'nome': Validacao.Nome_OK,\n 'sexo': Validacao.Sexo_OK\n }\n if campo in func:\n if not campo in obj:\n self.msg_erro = \"Campo obrigatorio\"\n self.correta = False\n else:\n self.valor = obj[campo]\n self.correta = func[campo](self)\n else:\n self.correta = True\n\n# Exemplo : V = Validacao('idade',13) // V.correta = False\n","sub_path":"api_cli_dynamo/app/controllers/Validacao.py","file_name":"Validacao.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"241594221","text":"#!/usr/bin/env python\nfrom random import *\n\nimport sys\n\nops = [\"+\", \"-\", \"*\", \"/\", \"&\", \"|\", \"=\", \"<>\", \"<\", \"<=\", \">\", \">=\", \"@\",]\n\n# MAX_NUMBER = sys.maxint\nMAX_NUMBER = 10\nid_count = 0\nid = 'a'\n\ndef main():\n sys.stdout.write(str(MAX_NUMBER) + ' + ')\n\n for x in range(0, 10):\n print(addExpression())\n sys.stdout.write(' ' + choice(ops) + \" \")\n \n print(addExpression())\n\ndef addExpression():\n rand = randint(0, 10)\n\n if (rand <= 1):\n return addIfThenElse()\n elif (rand <= 2):\n return addLambda()\n elif (rand <= 4):\n return addLet()\n else:\n outputStr = \"(\"\n if (randint(0, 1) == 0):\n outputStr += str(randint(0, MAX_NUMBER))\n else:\n outputStr += \"Nil\"\n outputStr += \" \" + choice(ops) + \" \"\n\n if (randint(0, 1) == 0):\n outputStr += str(randint(0, MAX_NUMBER)) \n else:\n outputStr += selectIdentifier()\n outputStr += ')'\n return outputStr\n\ndef addIfThenElse():\n return (\"if \" + addExpression() +\" then \" + addExpression() + \" else\\n\" + addExpression())\n\ndef addLambda():\n formal = \"x\"\n return \"(lambda \" + formal + \". \" + formal + \" \" + choice(ops) + \" \" + formal + \" \" + str(randint(0, MAX_NUMBER)) + \")\"\n\ndef addLet():\n global id_count\n id = \"a\" + str(id_count)\n id_count = id_count + 1\n return \"let \" + id + \" = \" + addExpression() + \" in\\n\" + id + \" \" + choice(ops) + \" \" + addExpression()\n\ndef selectIdentifier():\n # Get an identifier that has already been defined\n global id_count\n return \"a\" + str(randint(0, id_count))\n\nmain()\n","sub_path":"PA3/TestCases/generateTests.py","file_name":"generateTests.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"592193281","text":"#!/usr/bin/env python\n\nfrom flask import Flask, render_template, request\n\nimport find_songs\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route('/video/')\ndef show_video(number):\n return render_template('display-video.html', video_num=number)\n\n\n@app.route('/not-found')\ndef not_found():\n \"\"\"\n Supposed to be our 404 page.\n \"\"\"\n\n\n@app.route('/find-song/')\ndef get_song_response():\n \"\"\"\n A call to the restful api rendering songs.\n\n Meant to be used in the form:\n /find-song/?search=\"spam and eggs\"\n /find-song/?search=\"The Spanish Inquisition\"\n\n Response is a link to the song corresponding to the\n search.\n \"\"\"\n search = request.args.get('q', '')\n if request.args.get('to_mp3'):\n return # the video's audio.\n else:\n link = find_songs.find_song(phrase=search)\n return render_template('display-video.html', video_num=link)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"HackPrinceton2016.py","file_name":"HackPrinceton2016.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"389858092","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nimport Environment\nimport Codec\nimport Agent\nimport tensorflow as tf\nfrom collections import deque\nimport random\nimport SPEC\nimport numpy as np\nimport pickle\nimport csv\nfrom tqdm import trange\n\n# In[ ]:\n\n\ncodec = Codec.Codec()\nRL_environment = Environment.HomeWorld()\nagent = Agent.Agent()\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n# In[ ]:\n\n\nreplay_memory = deque(maxlen = 100000)\nfor _ in trange(3000 // SPEC.T):\n RL_environment.new_game(verbose = False)\n new_start = True\n while True:\n if RL_environment.if_finished():\n replay_memory[-1][5] = True\n #print(\"overall_reward : {0}\".format(RL_environment.total_reward))\n break\n elif new_start:\n state = RL_environment.get_current_state()\n coded_state = codec.encode(state)\n else:\n state = next_state\n coded_state = coded_next_state\n action,object = agent.simulate(sess,[coded_state],epsilon = 1)\n action_str,object_str = codec.decode_action(action,object)\n actions = (action_str[0],object_str[0])\n reward = RL_environment.do_action(*tuple(actions))\n next_state = RL_environment.get_current_state()\n coded_next_state = codec.encode(next_state)\n transection = [coded_state,action[0],object[0],reward,coded_next_state,False]\n replay_memory.append(transection) \n\n\n# In[ ]:\n\n\nsaver = tf.train.Saver()\ni = 0\nepsilon = 1\nall_rewards = 0\nbatch_size = 100\nmax_iter = 10000\nreward_list = [0] * max_iter\nall_loss = 0\nfor epoch in trange(max_iter):\n epsilon *= 0.9997\n RL_environment.new_game(verbose = False)\n new_start = True\n while True:\n i = (i+1) % 4\n if RL_environment.if_finished():\n replay_memory[-1][5] = True\n all_rewards += RL_environment.total_reward\n if epoch % 10 == 0:\n print(\"epoch:{0:3} overall_reward : {1:.4f}, loss : {2:.4f}\".format(epoch,all_rewards / 10,sum(all_loss)/len(all_loss)/SPEC.T))\n all_rewards = 0\n all_loss = 0\n reward_list[epoch] = RL_environment.total_reward\n break\n elif new_start:\n state = RL_environment.get_current_state()\n coded_state = codec.encode(state)\n else:\n state = next_state\n coded_state = coded_next_state\n action,object = agent.simulate(sess,[coded_state],epsilon = epsilon)\n action_str,object_str = codec.decode_action(action,object)\n actions = (action_str[0],object_str[0])\n reward = RL_environment.do_action(*tuple(actions))\n next_state = RL_environment.get_current_state()\n coded_next_state = codec.encode(next_state)\n transections = np.array(random.sample(replay_memory,batch_size))\n minibatch = tuple([np.array(transections[:,i].tolist()) for i in range(6)])\n loss = agent.training(sess,minibatch)\n all_loss += loss\n if i == 0:\n agent.copy_target_Q(sess)\n transection = [coded_state,action[0],object[0],reward,coded_next_state,False]\n replay_memory.append(transection)\n if epoch % 1000 == 999:\n saver.save(sess, \"./model.ckpt\")\n print(\"model save at {0}\".format(\"./model.ckpt\"))\n\n\n# In[ ]:\n\n\nfor i in trange(10):\n RL_environment.new_game(verbose = False)\n new_start = True\n while True:\n if RL_environment.if_finished():\n replay_memory[-1][5] = True\n print(\"test {0:2} overall_reward : {1}\".format(i,RL_environment.total_reward))\n break\n elif new_start:\n state = RL_environment.get_current_state()\n coded_state = codec.encode(state)\n else:\n state = next_state\n coded_state = coded_next_state\n action,object = agent.simulate(sess,[coded_state],epsilon = 0)\n action_str,object_str = codec.decode_action(action,object)\n actions = (action_str[0],object_str[0])\n reward = RL_environment.do_action(*tuple(actions))\n next_state = RL_environment.get_current_state()\n coded_next_state = codec.encode(next_state)\n\n\n# In[ ]:\n\nwith open(\"reward.dat\",\"wb\") as fp:\n pickle.dump(reward_list,fp,protocol=pickle.HIGHEST_PROTOCOL)\nsess.close()\n\n\"\"\"\nwith open(\"reward.csv\", 'w') as fp:\n wr = csv.writer(fp, quoting=csv.QUOTE_ALL)\n wr.writerow(reward_list)\n\"\"\"","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"430538132","text":"class SinglyLinkedList : # ทำงานเหมือนกับ List (อ้าง อินเด็กซ์แบบเดียวกัน)\r\n class Node : # โหนดเก็บข้อมูล\r\n def __init__(self, data, next = None) :\r\n self.data = data\r\n if next is None : self.next = None\r\n else : self.next = next\r\n \r\n def __init__(self): \r\n self.head = None\r\n self.size = 0\r\n \r\n def __str__(self): # แสดงข้อมูลทุกตัวใน linked list\r\n s = 'linked data : '\r\n p = self.head\r\n while p != None :\r\n s += str(p.data) + ' '\r\n p = p.next\r\n return s\r\n \r\n def __len__(self) : # เพิ่ม เมื่อ เติมข้อมูล ลด เมื่อ นำข้อมูลออก\r\n return self.size \r\n \r\n def isEmpty(self) : # ตรวจสอบว่ามีข้อมูลใน linked list ไหม\r\n return self.size == 0\r\n \r\n def indexOf(self,data) : # หา อินเด็กของข้อมูลว่าอยู่ที่ตำแหน่งใด\r\n p = self.head\r\n for i in range(len(self)) :\r\n if p.data == data :\r\n return i\r\n p = p.next\r\n return -1\r\n \r\n def isIn(self,data) : # ตรวจสอบว่าใน linked list นี้ มีข้อมูลตัวนี้ไหม\r\n return self.indexOf(data) >= 0\r\n \r\n def nodeAt(self,i) : # หาค่าตำแหน่งของโหนด เทียบกับ อินเด็กซ์\r\n p = self.head\r\n for j in range(0,i) :\r\n p = p.next\r\n return p\r\n \r\n def append(self,data): # เพิ่ม ข้อมูล ไปที่ด้านท้ายของ linked list\r\n if self.head is None :\r\n p = self.Node(data)\r\n self.head = p\r\n self.size += 1\r\n else : # เพิ่ม ในกรณีที่ไม่��ช่ Node แรก\r\n self.insertAfter(len(self)-1,data) #len(self) = จำนวนสมาชิก - 1 คือ index\r\n \r\n def insertAfter(self,i,data) : #เพิ่ม ข้อมูล ในสายข้อมูลที่มีอยู่แล้ว\r\n q = self.nodeAt(i)\r\n p = self.Node(data)\r\n p.next = q.next\r\n q.next = p\r\n self.size += 1\r\n \r\n def deleteAfter(self,i) : #ลบ โหนดข้อมูล ในสายข้อมูลที่มีอยู่แล้ว\r\n if self.size > 0 : # len(self)\r\n q = self.nodeAt(i)\r\n q.next = q.next.next\r\n self.size -= 1\r\n \r\n def delete(self,i) : #ลบข้อมูลที่ อินเด็กซ์ที่กำหนด\r\n if i == 0 and self.size > 0 : #ลบตัวแรก\r\n self.head = self.head.next\r\n self.size -= 1\r\n else :\r\n self.deleteAfter(i-1) #ลบตัวก่อนหน้า\r\n \r\n def removeData(self,data) : #ลบข้อมูลใน linked list\r\n if self.isIn(data) :\r\n self.deleteAfter(self.indexOf(data)-1)\r\n \r\n def addHead(self,data) :\r\n if self.isEmpty() :\r\n p = self.Node(data)\r\n self.head = p\r\n self.size += 1\r\n else :\r\n p = self.Node(data,self.head)\r\n self.head = p\r\n self.size += 1\r\n\r\n def display(self) :\r\n cur = self.head\r\n while cur is not None :\r\n print(cur.data,end='')\r\n if cur.next is not None : print(' <- ',end='')\r\n cur = cur.next\r\n print()\r\n\r\ndef mergeList(sll1,sll2) :\r\n cur = sll2.head\r\n while cur is not None :\r\n sll1.append(cur.data)\r\n cur = cur.next\r\n\r\nif __name__ == '__main__':\r\n\r\n print(' *** Locomotive ***')\r\n sll = SinglyLinkedList()\r\n ls_input = input('Enter Input : ').split()\r\n for e in ls_input : sll.append(e)\r\n print('Before : ',end='')\r\n sll.display()\r\n print('After : ',end='')\r\n if sll.indexOf('0') == 0 : sll.display()\r\n else :\r\n current = sll.head\r\n sll2 = SinglyLinkedList()\r\n for i in range(len(sll)) :\r\n if current.data == '0' :\r\n sll.head = current\r\n sll.size -= sll2.size\r\n mergeList(sll,sll2)\r\n break\r\n else : sll2.append(str(current.data))\r\n current = current.next\r\n sll.display()\r\n\r\n\r\n \r\n ","sub_path":"63010774_Lab05_1.py","file_name":"63010774_Lab05_1.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"178091251","text":"class Solution(object):\n def singleNumber(self, nums):\n #stupid solution\n data = {}\n for tmp in nums:\n if tmp not in data:\n data[tmp] = 1\n else:\n data[tmp]+=1\n for tmp in data:\n if data[tmp] is not 3:\n return tmp","sub_path":"LeetCode_Python/Single Number II.py","file_name":"Single Number II.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"511532089","text":"import os\nimport lasagne\nimport theano\nimport theano.tensor as T\nimport numpy as np\nfrom lasagne.layers import Conv2DLayer,\\\n MaxPool2DLayer,\\\n InputLayer\nfrom lasagne.nonlinearities import elu, sigmoid, rectify\nfrom lasagne.regularization import l2, regularize_layer_params\nfrom utils.maxpool_multiply import MaxPoolMultiplyLayer\n\nfrom models.cascade_base import CascadeBase\n\nclass FaceTrigger(CascadeBase): \n def build_network(self):\n net = lasagne.layers.batch_norm(InputLayer((None, 1) + tuple(self.img_shape),\n self.input_X,\n name='network input'))\n \n convs = []\n\n # Build network\n for i in range(self.num_cascades):\n net = lasagne.layers.batch_norm(Conv2DLayer(net,\n nonlinearity=elu,\n num_filters=self.num_filters[i],\n filter_size=self.filter_sizes[i],\n pad='same',\n name='conv {}'.format(i + 1)))\n convs.append(net)\n net = MaxPool2DLayer(net,\n pool_size=self.pool_sizes[i],\n name='Max Pool {} {}'.format(i + 1, i + 2))\n\n \n out = Conv2DLayer(net,\n nonlinearity=sigmoid,\n num_filters=1,\n filter_size=1,\n pad='same',\n name='prediction layer')\n \n branches = [None] * self.num_cascades\n\n # Build branches\n for i in range(self.num_cascades):\n branches[i] = Conv2DLayer(convs[i],\n num_filters=1,\n filter_size=1,\n nonlinearity=sigmoid,\n name='decide network {} output'.format(i + 1))\n\n downsampled_activation_layers = [branches[0]]\n\n for i in range(self.num_cascades - 1):\n downsampled_activation_layers.append(MaxPoolMultiplyLayer(branches[i + 1],\n downsampled_activation_layers[-1],\n self.pool_sizes[i]))\n masked_out = MaxPoolMultiplyLayer(out,\n downsampled_activation_layers[-1],\n self.pool_sizes[-1])\n \n return out, downsampled_activation_layers, masked_out","sub_path":"models/face_trigger.py","file_name":"face_trigger.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"403087653","text":"import sys\nimport os, os.path\nimport numpy\nfrom scipy import interpolate\nfrom scipy.misc import logsumexp\nfrom galpy.util import bovy_plot, bovy_conversion, multi, bovy_coords\nimport multiprocessing\nfrom galpy import potential\nfrom galpy.orbit import Orbit\nfrom galpy.actionAngle_src.actionAngleIsochroneApprox\\\n import actionAngleIsochroneApprox\nfrom galpy.df_src.streamdf import streamdf\n_STREAMSNAPDIR= '../sim/snaps'\n_STREAMSNAPAADIR= '../sim/snaps_aai'\n_NTRACKCHUNKS= 11\n_SIGV=0.365\n_NLS= 1001\ndef plot_pdfs_l(plotfilename):\n lp= potential.LogarithmicHaloPotential(q=0.9,normalize=1.)\n aAI= actionAngleIsochroneApprox(b=0.8,pot=lp)\n obs= numpy.array([1.56148083,0.35081535,-1.15481504,\n 0.88719443,-0.47713334,0.12019596])\n sdf= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,\n leading=True,nTrackChunks=_NTRACKCHUNKS,\n vsun=[0.,30.24*8.,0.],\n tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),\n multi=_NTRACKCHUNKS)\n sdft= streamdf(_SIGV/220.,progenitor=Orbit(obs),pot=lp,aA=aAI,\n leading=False,nTrackChunks=_NTRACKCHUNKS,\n vsun=[0.,30.24*8.,0.],\n tdisrupt=4.5/bovy_conversion.time_in_Gyr(220.,8.),\n multi=_NTRACKCHUNKS)\n #Calculate the density as a function of l, p(l)\n #Sample from sdf\n llbd= sdf.sample(n=40000,lb=True)\n tlbd= sdft.sample(n=50000,lb=True)\n b,e= numpy.histogram(llbd[0],bins=101,normed=True)\n t= ((numpy.roll(e,1)-e)/2.+e)[1:]\n lspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=1.)\n lls= numpy.linspace(t[0],t[-1],_NLS)\n lps= numpy.exp(lspl(lls))\n lps/= numpy.sum(lps)*(lls[1]-lls[0])*2.\n b,e= numpy.histogram(tlbd[0],bins=101,normed=True)\n t= ((numpy.roll(e,1)-e)/2.+e)[1:]\n tspl= interpolate.UnivariateSpline(t,numpy.log(b),k=3,s=0.5)\n tls= numpy.linspace(t[0],t[-1],_NLS)\n tps= numpy.exp(tspl(tls))\n tps/= numpy.sum(tps)*(tls[1]-tls[0])*2.\n bovy_plot.bovy_print(fig_width=8.25,fig_height=3.5)\n bovy_plot.bovy_plot(lls,lps,'k-',lw=1.5,\n xlabel=r'$\\mathrm{Galactic\\ longitude}\\,(\\mathrm{deg})$',\n ylabel=r'$p(l)$',\n xrange=[65.,250.],\n yrange=[0.,1.2*numpy.nanmax(numpy.hstack((lps,tps)))])\n bovy_plot.bovy_plot(tls,tps,'k-',lw=1.5,overplot=True)\n #Also plot the stream histogram\n #Read stream\n data= numpy.loadtxt(os.path.join(_STREAMSNAPDIR,'gd1_evol_hitres_01312.dat'),\n delimiter=',')\n #Transform to (l,b)\n XYZ= bovy_coords.galcenrect_to_XYZ(data[:,1],data[:,3],data[:,2],Xsun=8.)\n lbd= bovy_coords.XYZ_to_lbd(XYZ[0],XYZ[1],XYZ[2],degree=True)\n aadata= numpy.loadtxt(os.path.join(_STREAMSNAPAADIR,\n 'gd1_evol_hitres_aa_01312.dat'),\n delimiter=',')\n thetar= aadata[:,6]\n thetar= (numpy.pi+(thetar-numpy.median(thetar))) % (2.*numpy.pi)\n indx= numpy.fabs(thetar-numpy.pi) > (5.*numpy.median(numpy.fabs(thetar-numpy.median(thetar))))\n lbd= lbd[indx,:]\n bovy_plot.bovy_hist(lbd[:,0],bins=40,range=[65.,250.],\n histtype='step',normed=True,\n overplot=True,\n lw=1.5,color='k')\n bovy_plot.bovy_end_print(plotfilename)\n\nif __name__ == '__main__':\n numpy.random.seed(1)\n plot_pdfs_l(sys.argv[1])\n","sub_path":"py/plot_pdfs_l.py","file_name":"plot_pdfs_l.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"570806389","text":"def convert_url():\n mens_urls = []\n womens_urls = []\n const_name = raw_input('What do you want to call this variable?')\n male_declaration = const_name + '_MENS' + ' = '\n female_declaration = const_name + '_WOMENS' + ' = '\n meet_name = raw_input('what is the name of this meet')\n while True:\n try:\n url = raw_input('Input url or done for done')\n if url == 'done':\n break\n converted_urls = male_female_url(url)\n mens_urls.append(converted_urls[0])\n womens_urls.append(converted_urls[1])\n except:\n print('please try again')\n print('export const ' + male_declaration + str(mens_urls) + ';')\n print('')\n print('export const ' + female_declaration + str(womens_urls) + ';')\n print('await insertToDatabase(await collectAthleteData(' + const_name + '_MENS, \"' + meet_name + '\"));')\n print('await insertToDatabase(await collectAthleteData(' + const_name + '_WOMENS, \"' + meet_name + '\"));') \n \n \n\ndef male_female_url(url):\n split_url = url.split('/')[2:]\n male = split_url[:]\n female = split_url[:]\n male.insert(3, 'm')\n female.insert(3, 'f')\n male_ret = '/'.join(male)\n female_ret = '/'.join(female)\n return 'http://' + male_ret, 'http://' + female_ret\n\nconvert_url()","sub_path":"server/url_converter.py","file_name":"url_converter.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"179814644","text":"# coding=utf-8\n\nimport os\nimport gzip\n#import click\nimport argparse\nimport json\nfrom time import sleep\nimport subprocess\n\nimport redisRW\nimport traceback\nfrom log import Logger\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nlogger = None\n# args: 所有的参数,以便以后扩展\ndef watchtrain(args):\n\n\n queue = redisRW.MyQueue(db=args[\"dbnum\"], host=args[\"host\"])\n while (True):\n try:\n print('step 0')\n datastr = queue.pop(args[\"queuename\"])\n\n if(datastr == None):\n sleep(10)\n continue\n\n print(\"datastr is:\", datastr)\n\n datastr = unicode(datastr).encode(\"utf-8\")\n\n data = json.loads(datastr)\n logger.info(\"get data; id is:%d\"%(data[\"id\"]))\n\n cmdstr = 'python traintext.py -i %d' % (data[\"id\"])\n print('cmdstr is:', cmdstr)\n p = subprocess.Popen(cmdstr, shell=True)\n retcode = p.wait()\n print('retcode =', retcode)\n\n cmdstr2 = 'python traintext.py -i %d -s 1' % (data[\"id\"])\n print('cmdstr2 is:', cmdstr2)\n p2 = subprocess.Popen(cmdstr2, shell=True)\n retcode2 = p2.wait()\n print('retcode2 =', retcode2)\n\n except KeyboardInterrupt:\n print('traceback.print_exc():%s' % traceback.print_exc())\n break\n except:\n print('traceback.print_exc():%s'%traceback.print_exc())\n sleep(1)\n continue\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n # Required arguments: input file.\n parser.add_argument(\n \"configurepath\",\n nargs='?',\n default=\"trainconfig.ini\",\n help=\"Path to the configure file\"\n )\n\n args = parser.parse_args()\n assert os.path.exists(args.configurepath), \"The configure model file not exist.\"\n\n with open(args.configurepath, \"r\") as f:\n jsonconfig = json.load(f)\n logger = Logger(\"watch_%s\" % (jsonconfig[\"logname\"]))\n\n watchtrain(jsonconfig)\n","sub_path":"auto_text_classification/trainservice.py","file_name":"trainservice.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"301110235","text":"'''\nuse scene-15 dataset to verify AutoEncoder algorithm, check https://qixianbiao.github.io/Scene.htmlsee\nusing gpu to accelerate\n'''\n\nimport os\nimport random\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import confusion_matrix, classification_report, accuracy_score\nfrom keras.layers import Input, Dense\nfrom keras.models import Model, Sequential\nfrom keras.utils import to_categorical\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom tensorflow.python.client import device_lib\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom get_dataset import get_dataset\n\n\n# configure the gpu\n# set log level\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# model will be trained on GPU 0\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n# output : physical_device_desc: \"device: 0, name: GeForce GTX 1050, pci bus id: 0000:01:00.0\"\nprint(device_lib.list_local_devices())\n\n\n# Getting Dataset:\nX_train, X_test, Y_train, Y_test = get_dataset()\nclasses = ['cat', 'dog']\n\n# About Dataset:\nimg_size = X_train.shape[1] # 64\nprint('Training shape:', X_train.shape)\nprint(X_train.shape[0], 'sample,',X_train.shape[1] ,'x',X_train.shape[2] ,'size RGB image.\\n')\nprint('Test shape:', X_test.shape)\nprint(X_test.shape[0], 'sample,',X_test.shape[1] ,'x',X_test.shape[2] ,'size RGB image.\\n')\n\n# print('Examples:')\n# n = 10\n# plt.figure(figsize=(20, 4))\n# for i in range(1, n+1):\n# # Display some data:\n# ax = plt.subplot(1, n, i)\n# plt.imshow(X_train[i])\n# ax.get_xaxis().set_visible(False)\n# ax.get_yaxis().set_visible(False)\n# whether show the examples\n# plt.show()\n\nX_train = X_train.reshape((len(X_train), np.prod(X_train.shape[1:])))\nX_test = X_test.reshape((len(X_test), np.prod(X_test.shape[1:])))\n# build model\n# input dimension = 64*64*3 = 12288\ninput_dim = np.prod(X_train.shape[1:])\n# this is the size of our encoded representations\nencoding_dim = 384\n# The compression factor is the ratio of the input dimension (12288) to the encoded dimension(384),which is 32\ncompression_factor = float(input_dim) / encoding_dim\nprint(\"Compression factor: %s\" % compression_factor)\n\n# this is our input placeholder\ninput_img = Input(shape=(input_dim,))\n# \"encoded\" is the encoded representation of the input\nencoded = Dense(encoding_dim, activation='relu')(input_img)\n# \"decoded\" is the lossy reconstruction of the input\ndecoded = Dense(input_dim, activation='sigmoid')(encoded)\n# this model maps an input to its reconstruction\nautoencoder = Model(input_img, decoded)\nautoencoder.compile(optimizer='adam', loss='categorical_crossentropy',)\n\n# Train the model, iterating on the data in batches of 256 samples\nhistory = autoencoder.fit(X_train, X_train, epochs=10, batch_size=256, shuffle=True,\n validation_data=(X_test, X_test))\n# _________________________________________________________________\n# Layer (type) Output Shape Param #\n# =================================================================\n# input_1 (InputLayer) (None, 12288) 0\n# _________________________________________________________________\n# dense_1 (Dense) (None, 384) 4718976\n# _________________________________________________________________\n# dense_2 (Dense) (None, 12288) 4730880\n# =================================================================\n# Total params: 9,449,856\n# Trainable params: 9,449,856\n# Non-trainable params: 0\nprint(autoencoder.summary())\n\nplt.figure()\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper right')\nplt.show()\n\n\n\n# use encoded layer to encode the training input which is separate encoder model:\n# this model maps an input to its encoded representation\nencoder = Model(input_img, encoded)\nprint(encoder.summary())\nencoded_input = Input(shape=(encoding_dim,))\ndecoder_layer = autoencoder.layers[-1]\ndecoder = Model(encoded_input, decoder_layer(encoded_input))\nprint(decoder.summary())\n# encode and decode some digits\n# note that we take them from the *test* set\nencoded_imgs = encoder.predict(X_test)\ndecoded_imgs = autoencoder.predict(X_test) #=decoder.predict(encoded_imgs)\n\n# Compare Original images (top row) with reconstructed ones (bottom row)\nm = 10 # how many digits we will display\nplt.figure(figsize=(9, 3))\nfor i in range(m):\n # display original\n ax = plt.subplot(2, m, i + 1)\n plt.imshow(X_test[i].reshape(64, 64, 3))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # display reconstruction\n ax = plt.subplot(2, m, i + 1 + m)\n plt.imshow(decoded_imgs[i].reshape(64, 64, 3))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()\n\n# Using encoding layer with softmax layer to train a classifier\n# For a single-input model with 10 classes (categorical classification):\nmodel = Sequential()\nmodel.add(autoencoder)\n\nmodel.add(Dense(2, activation=tf.nn.softmax))\n# model.add(Activation(tf.nn.softmax))\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nprint(Y_train.shape)\nprint(Y_test.shape)\n# Convert labels to categorical one-hot encoding\nY_train = to_categorical(Y_train, num_classes=2)\nprint(Y_train.shape)\nprint(Y_test.shape)\n\n# Train the model, iterating on the data in batches of 32 samples\nmodel.fit(X_train, Y_train, epochs=100, batch_size=1500)\nprint(model.summary())\n\n#predicted labels/classes\nY_pred = model.predict_classes(X_test)\n\n#Precision and recall\n# print(classification_report(y_test, y_pred))\n\n# Plot confusion matrix\ncm = confusion_matrix(Y_test, Y_pred)\ndf = pd.DataFrame(cm, classes, classes)\nplt.figure()\nsns.set(font_scale=1.2)#for label size\n#comap = sns.cubehelix_palette(dark=0, light=1, as_cmap=True)\nax = sns.heatmap(cm,annot=True,annot_kws={\"size\": 16},linewidths=.5,cbar=False,\n xticklabels=classes,yticklabels=classes,square=True, cmap='Blues_r', fmt=\"d\")\n# This sets the yticks \"upright\" with 0, as opposed to sideways with 90.\nplt.yticks(rotation=0)\nax.tick_params(labelbottom=False,labeltop=True)\nplt.xticks(rotation=90)\nplt.show()\n\n#accuracy score\nacc = accuracy_score(Y_test, Y_pred)\nprint('\\nAccuracy for the test data: {:.2%}\\n'.format(acc))\n\n","sub_path":"AutoEncoder/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":6461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"238362107","text":"# music_serialize\nimport pickle\nimport json\n\n\n# указать имя файла для экспорта (по умолчанию 'group'\ndef pickle_save(pickle_to_save, filename='group'):\n\t# открыть байт-файл на запись, в формате и с расширением .pickle\n\twith open(filename + \".pickle\", 'wb') as file:\n\t\t# сохранить информацию в файл\n\t\tpickle.dump(pickle_to_save, file)\n\t\t# уведомить консоль об успехе\n\t\tprint(f\"Сериализован файл: '{file.name}'\")\n\n\n# указать имя файла для экспорта (по умолчанию 'group'\ndef json_save(json_to_save, filename='group'):\n\t# открыть файл на запись, в формате и с расширением .json, в кодировке UTF8\n\twith open(filename + \".json\", 'w', encoding='UTF8') as file:\n\t\t# сохранить информацию в файл\n\t\tjson.dump(json_to_save, file)\n\t\t# уведомить консоль об успехе\n\t\tprint(f\"Сериализован файл: '{file.name}' with {file.encoding} encoding.\")\n","sub_path":"12 music/music_serialize.py","file_name":"music_serialize.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"622458811","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport re\nimport uuid\nimport tensorflow as tf\nfrom tensorflow.python.framework.dtypes import as_dtype\n\nfrom onnx import TensorProto\n\n# Using the following two functions to prevent shooting ourselves\n# in the foot with non-invertible maps.\n\n\ndef invertible(dict):\n # invertible iff one-to-one and onto\n # onto is guaranteed, so check one-to-one\n return len(dict.values()) == len(set(dict.values()))\n\n\ndef invert(dict):\n if not invertible(dict):\n raise ValueError(\"The dictionary is not invertible\"\n \" because it is not one-to-one.\")\n else:\n inverse = {v: k for k, v in dict.items()}\n return inverse\n\n\nONNX_TYPE_TO_TF_TYPE = {\n TensorProto.FLOAT: tf.float32,\n TensorProto.UINT8: tf.uint8,\n TensorProto.INT8: tf.int8,\n TensorProto.UINT16: tf.uint16,\n TensorProto.INT16: tf.int16,\n TensorProto.INT32: tf.int32,\n TensorProto.INT64: tf.int64,\n TensorProto.BOOL: tf.bool,\n TensorProto.FLOAT16: tf.float16,\n TensorProto.DOUBLE: tf.float64,\n TensorProto.COMPLEX64: tf.complex64,\n TensorProto.COMPLEX128: tf.complex128,\n TensorProto.STRING: tf.string,\n # TODO: uncomment this in the future\n # TensorProto.UINT32: tf.uint32,\n # TensorProto.UINT64: tf.uint64,\n}\n\nSTR_TO_TF_TYPE = {\n \"float\": tf.float32,\n \"uint8\": tf.uint8,\n \"int8\": tf.int8,\n \"uint16\": tf.uint16,\n \"int16\": tf.int16,\n \"int32\": tf.int32,\n \"int64\": tf.int64,\n \"bool\": tf.bool,\n \"float16\": tf.float16,\n \"double\": tf.float64,\n \"complex64\": tf.complex64,\n \"complex128\": tf.complex128,\n # TODO: uncomment this in the future\n # \"uint32\": tf.uint32,\n # \"uint64\": tf.uint64,\n}\n\nTF_TYPE_ENUM = [\n \"undefined\",\n tf.float32,\n tf.uint8,\n tf.int8,\n tf.uint16,\n tf.int16,\n tf.int32,\n tf.int64,\n tf.string,\n tf.bool,\n tf.float16,\n tf.float64,\n tf.complex64,\n tf.complex128,\n # TODO: uncomment this in the future\n # tf.uint32,\n # tf.uint64,\n]\n\nTF_TYPE_TO_ONNX_TYPE = invert(ONNX_TYPE_TO_TF_TYPE)\n\nONNX_ATTR_TO_TF_ATTR = {\n \"scale\": \"stddev\",\n \"high\": \"maxval\",\n \"low\": \"minval\",\n \"axes\": \"axis\",\n \"keepdims\": \"keep_dims\",\n}\n\nTF_ATTR_TO_ONNX_ATTR = invert(ONNX_ATTR_TO_TF_ATTR)\n\nONNX_ATTR_TO_TF_ATTR_PER_OP = {\n \"cast\": {\n \"to\": \"dtype\"\n },\n \"depth_to_space\": {\n \"blocksize\": \"block_size\"\n },\n \"gather\": {\n \"dim\": \"axis\"\n },\n \"lp_normalization\": {\n \"p\": \"ord\"\n },\n \"random_normal\": {\n \"scale\": \"stddev\"\n },\n \"random_uniform\": {\n \"low\": \"minval\",\n \"high\": \"maxval\"\n },\n}\n\nTF_ATTR_TO_ONNX_ATTR_PER_OP = {\n k: invert(v)\n for k, v in ONNX_ATTR_TO_TF_ATTR_PER_OP.items()\n}\n\nONNX_ATTR_TO_REMOVE_PER_OP = {}\n\nTF_ATTR_TO_REMOVE = [\n \"_output_shapes\", \"T\", \"seed2\", \"Tidx\", \"_class\", \"Tshape\", \"Tpaddings\",\n \"data_format\", \"transpose_a\", \"transpose_b\", \"out_type\"\n]\n\nONNX_OP_TO_TF_OP = {\n \"abs\": tf.abs,\n \"cast\": tf.cast,\n \"ceil\": tf.ceil,\n \"dot\": tf.contrib.keras.backend.dot,\n \"exp\": tf.exp,\n \"floor\": tf.floor,\n \"gather\": tf.gather,\n \"identity\": tf.identity,\n \"log\": tf.log,\n \"neg\": tf.negative,\n \"not\": tf.logical_not,\n \"random_normal\": tf.random_normal,\n \"random_uniform\": tf.random_uniform,\n \"reciprocal\": tf.reciprocal,\n \"reduce_log_sum_exp\": tf.reduce_logsumexp,\n \"reduce_max\": tf.reduce_max,\n \"reduce_mean\": tf.reduce_mean,\n \"reduce_min\": tf.reduce_min,\n \"reduce_prod\": tf.reduce_prod,\n \"reduce_sum\": tf.reduce_sum,\n \"relu\": tf.nn.relu,\n \"sigmoid\": tf.sigmoid,\n \"shape\": tf.shape,\n \"size\": tf.size,\n \"softplus\": tf.nn.softplus,\n \"softsign\": tf.nn.softsign,\n \"sqrt\": tf.sqrt,\n \"squeeze\": tf.squeeze,\n \"tanh\": tf.tanh,\n \"transpose\": tf.transpose,\n}\n\nTF_OP_TO_ONNX_OP = invert(ONNX_OP_TO_TF_OP)\n\nTF_OP_STR_TO_ONNX_OP = {\n # TODO:\n # handle Mul, Add, Sub,\n # these are temporarily added to\n # test other ops\n \"Add\": \"Add\",\n \"Ceil\": \"Ceil\",\n \"Equal\": \"Equal\",\n \"Exp\": \"Exp\",\n \"Floor\": \"Floor\",\n \"Greater\": \"Greater\",\n \"Identity\": \"Identity\",\n \"Less\": \"Less\",\n \"Log\": \"Log\",\n \"LogicalAnd\": \"And\",\n \"LogicalNot\": \"Not\",\n \"LogicalOr\": \"Or\",\n \"LogicalXor\": \"Xor\",\n \"LogSoftmax\": \"LogSoftmax\",\n \"MatMul\": \"MatMul\",\n \"Mul\": \"Mul\",\n \"Pow\": \"Pow\",\n \"RealDiv\": \"Div\",\n \"Reciprocal\": \"Reciprocal\",\n \"Relu\": \"Relu\",\n \"Shape\": \"Shape\",\n \"Sigmoid\": \"Sigmoid\",\n \"Softmax\": \"Softmax\",\n \"Sub\": \"Sub\",\n \"Sqrt\": \"Sqrt\",\n \"Tanh\": \"Tanh\",\n}\n\nONNX_OP_TO_TF_OP_STR = invert(TF_OP_STR_TO_ONNX_OP)\n\n\ndef get_tf_shape_as_list(tf_shape_dim):\n return list(map(lambda x: x.size, list(tf_shape_dim)))\n\n\n# This function inserts an underscore before every upper\n# case letter and lowers that upper case letter except for\n# the first letter.\ndef op_name_to_lower(name):\n return re.sub('(?\")\n stdscr.attroff(curses.color_pair(1))\n stdscr.refresh()\n time.sleep(0.7)\n\n\n# ██╗ ███████╗ ██╗ ██╗ ███████╗ ██╗ ███████╗ ██╗ ██████╗\n# ██║ ██╔════╝ ██║ ██║ ██╔════╝ ██║ ██╔════╝ ███║ ╚════██╗\n# ██║ █████╗ ██║ ██║ █████╗ ██║ ███████╗ ╚██║ █████╗ █████╔╝\n# ██║ ██╔══╝ ╚██╗ ██╔╝ ██╔══╝ ██║ ╚════██║ ██║ ╚════╝ ██╔═══╝\n# ███████╗ ███████╗ ╚████╔╝ ███████╗ ███████╗ ███████║ ██║ ███████╗\n# ╚══════╝ ╚══════╝ ╚═══╝ ╚══════╝ ╚══════╝ ╚══════╝ ╚═╝ ╚══════╝\n#\ndef get_human_dices_lev12(gm):\n n_dices = len(gm.dices)\n chance = r.randint(10, 90)\n if t.chance(chance):\n dices = t.good_dices(n_dices)\n else:\n dices = t.rand_dices(n_dices)\n return dices\n\n\ndef get_robot_dices_lev12(gm):\n n_dices = len(gm.dices)\n score_to_win = gm.high_bar - gm.player.score_total + gm.player.score_turn\n while True:\n dices = t.rand_dices(n_dices)\n possible_score = t.dices_info(dices)[\"score\"]\n if possible_score == 0 and t.chance(25):\n continue\n if possible_score < score_to_win:\n break\n return dices\n\n\n# ██╗ ███████╗ ██╗ ██╗ ███████╗ ██╗ ██████╗\n# ██║ ██╔════╝ ██║ ██║ ██╔════╝ ██║ ╚════██╗\n# ██║ █████╗ ██║ ██║ █████╗ ██║ █████╔╝\n# ██║ ██╔══╝ ╚██╗ ██╔╝ ██╔══╝ ██║ ╚═══██╗\n# ███████╗ ███████╗ ╚████╔╝ ███████╗ ███████╗ ██████╔╝\n# ╚══════╝ ╚══════╝ ╚═══╝ ╚══════╝ ╚══════╝ ╚═════╝\n#\ndef get_human_dices_lev3(gm):\n while True:\n dices = get_human_dices_lev12(gm)\n possible_score = t.dices_info(dices)[\"score\"]\n human_scr = gm.player.score_total + gm.player.score_turn\n if possible_score + human_scr <= gm.high_bar - 400:\n break\n return dices\n\n\ndef get_robot_dices_lev3(gm):\n while True:\n dices = get_robot_dices_lev12(gm)\n possible_score = t.dices_info(dices)[\"score\"]\n robot_scr = gm.player.score_total + gm.player.score_turn\n if possible_score + robot_scr <= gm.high_bar - 250:\n break\n return dices\n\n\ndef get_human_last_dices(gm):\n n_dices = len(gm.dices)\n if n_dices == 6:\n return [2, 2, 2, 3, 4, 6]\n elif n_dices == 3:\n return [1, 6, 2]\n elif n_dices == 2:\n return [5, 4]\n else:\n return t.bad_dices(n_dices)\n\n\ndef cheat_twist(gm):\n scr = gm.screen\n robot = gm.player\n robname = robot.name\n dropped_dices = t.bad_dices(6)\n cheated_dices = [1, 1, 1, 1, 1, 1]\n\n scr.anim_diceroll(6)\n scr.display_dices(dropped_dices)\n time.sleep(4)\n scr.display_dices(cheated_dices)\n time.sleep(1.5)\n # иммитация взятия костей роботом и начисления очков\n scr.effect_hldices(cheated_dices)\n robot.add_scorepick(4000)\n scr.display_msg(\"a_robturnF\")\n scr.effect_hldices(cheated_dices, cp=2)\n robot.add_scoreturn()\n scr.display_msg(\"a_scrpick\", robname, 4000)\n robot.add_scoretotal()\n scr.display_msg(\"a_scrtotl\", robname, robot.score_total)\n scr.display_msg(\"3_robwin\", robname, delay=1)\n scr.clear_zone(scr.ZONE_MSG)\n scr.clear_zone(scr.ZONE_SCORE)\n\n\n# ██╗ ██╗ ███╗ ██╗ ██████╗ ███████╗ ██╗\n# ██║ ██║ ████╗ ██║ ██╔══██╗ ██╔════╝ ██║\n# ██║ ██║ ██╔██╗ ██║ ██████╔╝ █████╗ ██║\n# ██║ ██║ ██║╚██╗██║ ██╔══██╗ ██╔══╝ ██║\n# ╚██████╔╝ ██║ ╚████║ ██║ ██║ ███████╗ ███████╗ ██╗\n# ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚══════╝ ╚══════╝ ╚═╝\n# ██╗ ██╗ ██████╗ ███████╗ ████████╗\n# ██║ ██║ ██╔═══██╗ ██╔════╝ ╚══██╔══╝\n# ███████║ ██║ ██║ ███████╗ ██║\n# ██╔══██║ ██║ ██║ ╚════██║ ██║\n# ██║ ██║ ╚██████╔╝ ███████║ ██║\n# ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝\n#\ndef interface_fade(screen):\n colorist = screen.colorist\n fade_palettes = [\n (40, 204, 204, 204, 43, 46, 49, 40),\n (41, 204, 204, 204, 44, 47, 50, 41),\n (42, 204, 204, 204, 45, 48, 51, 42),\n colorist.FIRST_LEVEL\n ]\n for palette in fade_palettes:\n colorist.change_palette(palette)\n screen.add_interface()\n time.sleep(1.2)\n","sub_path":"Levels/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":8225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"515331340","text":"import sys\nimport time\n\nfrom PredictorPhysics import *\n\n\ndef add_all_folders_to_python_path():\n sys.path.append(\"./database\")\n sys.path.append(\"./computations\")\n sys.path.append(\"./computations/comp_utils\")\n sys.path.append(\"./comp_utils\")\n\n\nadd_all_folders_to_python_path()\n\nfrom database.DatabaseAccessor import *\n\n\ndef current_time_millis():\n return int(round(time.time() * 1000))\n\nBS = [1000]\nfor i in range(10):\n BS.append(BS[-1] * 1.1)\nWS = np.array([0, 3, 6, 9]) * 1000\n\ntry:\n os.remove(Constants.DATABASE_NAME)\nexcept OSError:\n pass\n\nda = DatabaseAccessor.get_instance()\n\nsession_id = da.increment_and_get_session_id()\n\nfor bs in BS:\n da.insert_ball_lap_times(session_id, bs)\nfor ws in WS:\n da.insert_wheel_lap_times(session_id, ws)\n\nPredictorPhysics.load_cache(da)\n\nBS_i = BS[2:-5]\nPredictorPhysics.predict_most_probable_number(BS_i, WS, debug=True)\n","sub_path":"tmp/Toy_example.py","file_name":"Toy_example.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"416545359","text":"# D after contest\nfrom collections import deque, defaultdict\n\nN, Q = map(int, input().split())\n\nedges = defaultdict(list)\nfor _ in range(N - 1):\n a, b = map(int, input().split())\n edges[a].append(b)\n edges[b].append(a)\n\n\ndef bfs(start):\n q = deque()\n q.append(start)\n # 訪問済み、または、これから訪れる頂点部分集合\n C = set()\n C.add(start)\n distances[start] = 0\n\n while q:\n v = q.popleft()\n for each in edges[v]:\n if each not in C:\n C.add(each)\n q.append(each)\n distances[each] = distances[v] + 1\n\n\n# 最短経路リスト\ndistances = [-1] * (N + 1)\n# スタート地点からの最短距離をもれなく更新\nbfs(1)\n\nwhile Q:\n Q -= 1\n c, d = map(int, input().split())\n print('Town' if abs(distances[c] - distances[d]) % 2 == 0 else 'Road')\n","sub_path":"src/data/104.py","file_name":"104.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"637591581","text":"import json\nimport os\nfrom google.cloud import pubsub_v1\n\n# Load configuration data that includes Slack's token\nwith open('slackconfig.json', 'r') as f:\n data = f.read()\nconfig = json.loads(data)\n\n# When this gcf function is called, it immediately activates below pubsub handler\n# Slack or other messaging need immediate synchronous respond\n# while network response and post-processing need some times, thus it's handled by another aynchronous task\ndef pubsub_handler(request):\n project_id = os.environ['GCP_PROJECT_ID'] # specify google cloud platform project id\n topic_name = \"taskhandler\" # can be changed to anything\n publisher = pubsub_v1.PublisherClient()\n topic_path = publisher.topic_path(project_id, topic_name)\n\n if(verify_web_hook(request.form)):\n # Converting slack command data to dict and add NE url information\n req_dict = request.form.to_dict()\n # Get NE's ip address from slack command and add as \"ios_url\" and specify netconf resource to be acessed\n req_dict[\"ios_url\"] = \"https://\" + req_dict[\"text\"] + \"/restconf/data/Cisco-IOS-XE-process-cpu-oper:cpu-usage/cpu-utilization?depth=1\"\n data = json.dumps(req_dict)\n # When you publish a message, the client returns a future.\n future = publisher.publish(\n topic_path, data=data.encode(\"utf-8\") # data must be a bytestring.\n )\n return f'Command is well-received. Please wait for query result..'\n else:\n return f'Invalid request/credentials'\n# [END functions_pubsub_handler]\n\n# Verify incoming slack webhook\ndef verify_web_hook(form):\n if not form or form.get('token') != config['SLACK_VERIFICATION_TOKEN']:\n raise ValueError('Invalid request/credentials.')\n else:\n return True","sub_path":"showprocesscpu.py","file_name":"showprocesscpu.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"52359961","text":"import shutil\r\n\r\nfrom util import my_constants\r\nfrom util import my_util\r\nfrom util import importer\r\nfrom util.my_util import write_line\r\n\r\n\r\ndef go(species):\r\n method_dir = r'%s/method/muller' % my_constants.basePath\r\n out_dir = r'%s/%s/muller' % (my_constants.resultPath, species)\r\n my_util.mkdir_p(out_dir)\r\n\r\n source_file = '%s/dataset/networks/%s' % (my_constants.basePath, my_constants.species_sbml[species])\r\n\r\n S, mets, rxns, revs, met_names, rxn_names, biomass, met_comparts = importer.sbmlStoichiometricMatrix(source_file, True, read_species_compart=True, remove_biomass=False, normalize_stoich=False)\r\n\r\n f = open('muller.m', 'w')\r\n write_line(f, 'addpath %s/code' % method_dir)\r\n write_line(f, \"model = readCbModel('%s')\" % source_file)\r\n write_line(f, \"model.c(%d) = 1;\" % (rxns.index(biomass[0]) + 1))\r\n write_line(f, \"changeCobraSolver('glpk');\")\r\n write_line(f, '[modules, var, flux] = computeModulesOpt( model );')\r\n write_line(f, 'save mullerout.mat modules var flux')\r\n\r\n f.close()\r\n\r\n my_util.prepare_matlab_file_and_exec_and_wait_finish('muller', 'mullerout.mat', False)\r\n\r\n res_vars = my_util.try_load_matlab_result('mullerout.mat')\r\n raw_modules = res_vars['modules'] # if matlab has failed, this will throw exception!\r\n shutil.copy('mullerout.mat', out_dir)\r\n\r\n raw_modules = raw_modules.T.tolist() # eacho row will be a module where reactions are marked\r\n modules = []\r\n for raw_module in raw_modules:\r\n modules.append([])\r\n for rIdx, in_module in enumerate(raw_module):\r\n if in_module == 1:\r\n modules[-1].append(rxns[rIdx])\r\n\r\n out = open('%s/final_modules.txt' % out_dir, 'w')\r\n out.write(\"#each row is a module of reactions. not all reactions are specified (nature of this method only select some reaction to be modules)\\n\")\r\n for m in modules:\r\n out.write(' '.join(m))\r\n out.write('\\n')\r\n out.close()\r\n\r\nif __name__ == '__main__':\r\n # go('ecoli_core')\r\n # go('helico_iit341')\r\n ## go('ecoli_ijr904')\r\n # go('ecoli_iaf1260')\r\n # go('ecoli_ijo1366')\r\n # go('saccaro_ind750')\r\n go( 'mus_imm1415')\r\n # go('arabidopsis_irs1597')\r\n # dist = np.array([\r\n # [0,1,100,100],\r\n # [1,0,100,100],\r\n # [100,100,0,1],\r\n # [100,100,1,0]\r\n # ], dtype=float)\r\n # print wpgma(dist)","sub_path":"muller/muller.py","file_name":"muller.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"619989405","text":"\"\"\"\nBasic views.\nCreated on {* now *}.\n@desc: A sample Views module.\n@app: {* app_name *}\n\"\"\"\nimport os\nfrom . import appbuilder, autodoc\nimport logging\nfrom flask_appbuilder.baseviews import expose\nfrom flask_appbuilder.views import ModelView\nfrom flask_appbuilder.models.sqla.interface import SQLAInterface\nfrom flask_appbuilder.security.decorators import permission_name, has_access_api\nfrom flask import request\nfrom flask.json import jsonify\nfrom sqlalchemy.sql.expression import and_, text, or_\nfrom flask.helpers import make_response\nfrom .models_sample import SampleBenchmark\nimport datetime\n\n\"\"\"\n Create your Views::\n A sample view\n\n\"\"\"\n\n\nlog = logging.getLogger(appbuilder.get_app.config['LOG_NAME'])\n\n\nclass SampleView(ModelView):\n \"\"\"fab_admin sample business view class.\"\"\"\n\n route_base = \"/sample\"\n datamodel = SQLAInterface(SampleBenchmark)\n\n @expose('/api/upload', methods=['PUT', 'POST'])\n @has_access_api\n @permission_name('SampleCRUD')\n @autodoc.doc(endpoint='SampleView.sample_benchmark_upload', groups='Sample')\n def sample_benchmark_upload(self):\n \"\"\"\n {\n \"desc\": \"RESTFul api for Sample view benchmark upload\",\n \"mediaType\": \"application/json\",\n \"data\": {\n \"ben_server\": \"ben_server\",\n \"server\": \"server1.com\",\n \"site\": \"site1\",\n \"operation\": \"git clone\",\n \"start\": 1572837073,\n \"end\": 1572860762\n }\n }\n \"\"\"\n try:\n data = request.get_json()\n args = dict()\n args['ben_server'] = data['ben_server']\n args['server'] = data['server']\n args['operation'] = data['operation']\n args['site'] = data['site']\n args['start'] = data['start']\n args['end'] = data['end']\n self.datamodel.session.add(SampleBenchmark(**args))\n self.datamodel.session.commit()\n except Exception as e:\n log.error(e)\n return make_response(jsonify({'code': 400, 'message': str(e)}), 400)\n return jsonify({'code': 200, 'message': 'Success'})\n\n @expose('/api/list', methods=['GET', 'PUT', 'POST'])\n @has_access_api\n @permission_name('SampleCRUD')\n @autodoc.doc(endpoint='SampleView.api_list', groups='Sample')\n def api_list(self):\n \"\"\"\n {\n \"desc\": \"RESTFul api for Sample benchmark list fetch\",\n \"mediaType\": \"application/json\",\n \"data\": {\n \"rows\": [\n {\n \"ben_server\": \"ben_server\",\n \"server\": \"server1.com\",\n \"site\": \"site1\",\n \"operation\": \"git clone\",\n \"start\": 1572837073,\n \"end\": 1572860762\n }\n ],\n \"total\": 1\n }\n }\n \"\"\"\n data = request.values\n query = self.datamodel.session.query(SampleBenchmark)\n search_obj = data.get('search')\n offset = data.get('offset')\n limit = data.get('limit')\n sort = data.get('sort')\n order = data.get('order')\n if search_obj:\n query = query.filter(or_(SampleBenchmark.ben_server.like('%{0}%'.format(search_obj)), \\\n SampleBenchmark.server.like('%{0}%'.format(search_obj)), \\\n SampleBenchmark.site.like('%{0}%'.format(search_obj))))\n total = query.count()\n #----order\n if sort and order:\n query = query.order_by(text('{0} {1}'.format(sort, order)))\n #----page offset\n if offset and limit:\n query = query.limit(limit)\n query = query.offset(offset)\n records = query.all()\n return jsonify({'rows': [{'id': b.id, 'ben_server': b.ben_server, 'server': b.server, 'site': b.site, \\\n 'operation': b.operation, 'start': self._format_datetime('%Y-%m-%d %H:%M:%S', b.start), \\\n 'end': self._format_datetime('%Y-%m-%d %H:%M:%S', b.end)} for b in records], \\\n 'total': total})\n\n def _format_datetime(self, pattern, ts):\n return datetime.datetime.fromtimestamp(ts).strftime(pattern) if ts else None\n\nappbuilder.add_view_no_menu(SampleView, \"SampleView\")\n","sub_path":"fab_admin/iview_app_templates/app/views_sample.py","file_name":"views_sample.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"491292580","text":"import os\nimport sys\nimport zipfile\n\nfrom flasgger import Swagger\nfrom flask import Blueprint, Flask, Response, abort\nfrom flask import current_app as app\nfrom flask import jsonify, redirect, request, send_from_directory\nfrom flask_cors import CORS\n\napiv1 = Blueprint(\"v1\", __name__)\nCORS(apiv1)\n\nallowImgs = [\".jpg\", \".jpeg\", \".png\", \".webp\", \".bmp\"]\nallowZips = [\".zip\"]\n\n\ndef readComicFromZip(filepath, page=0):\n with zipfile.ZipFile(filepath) as archive:\n zipInfos = archive.infolist()\n if page >= len(zipInfos):\n return False, None\n with archive.open(zipInfos[page]) as f:\n return True, f.read()\n\n\ndef loadComicsList(path):\n with os.scandir(path) as entries:\n validEntries = filter(\n lambda f: f.is_file() and os.path.splitext(f.name)[-1].lower() in allowZips,\n entries,\n )\n return [\n {\n \"id\": id,\n \"name\": os.path.splitext(entry.name)[0],\n \"lastModifiedTime\": entry.stat().st_mtime,\n \"path\": entry.name,\n }\n for id, entry in enumerate(validEntries)\n ]\n\n\n@apiv1.route(\"/comics\")\ndef comics():\n \"\"\"returning a list of comics information\n This is using docstrings for specifications.\n ---\n parameters:\n - name: refresh\n type: bool\n required: false\n default: false\n description: specific whether to refresh the comic list config\n definitions:\n Comic:\n type: object\n properties:\n id:\n type: number\n name:\n type: string\n lastModifiedTime:\n type: number\n path:\n type: string\n responses:\n 200:\n description: A list of comics's information\n schema:\n $ref: '#/definitions/Comic'\n \"\"\"\n if (\n \"COMICLIST\" not in app.config\n or bool(request.args.get(\"refresh\", False)) == True\n ):\n app.config[\"COMICLIST\"] = loadComicsList(app.config[\"COMICPATH\"])\n print(app.config[\"COMICLIST\"])\n\n return jsonify(app.config[\"COMICLIST\"])\n\n\n@apiv1.route(\"/comics/\")\ndef getComic(id):\n \"\"\"returning image from zip file\n returning mimetype is \"image/jpeg\"\n ---\n parameters:\n - name: id\n type: int\n required: true\n default: 0\n description: comic id\n - name: page\n type: int\n in: path\n required: false\n default: 0\n description: comic page\n responses:\n 200:\n description: Specific comic image with mimetype=\"image/jpeg\"\n 404:\n description: Specific comic id or comic page not exist\n \"\"\"\n if id >= len(app.config[\"COMICLIST\"]):\n abort(404)\n comicInfo = app.config[\"COMICLIST\"][id]\n filepath = comicInfo[\"path\"]\n ext = os.path.splitext(filepath)[-1].lower()\n page = int(request.args.get(\"page\", 0))\n ret, buf = readComicFromZip(os.path.join(app.config[\"COMICPATH\"], filepath), page)\n if ret:\n return Response(response=buf, mimetype=\"image/jpeg\")\n abort(404)\n\n\n@apiv1.route(\"/videos\")\ndef videos():\n return jsonify({})\n\n\n@apiv1.route(\"/images\")\ndef images():\n return jsonify({})\n","sub_path":"backend/app/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"92308481","text":"import math\r\na=int(input())\r\nb=int(input())\r\narr=[]\r\nsum=0\r\nfor i in range(a,b+1):\r\n if math.sqrt(i)-int(math.sqrt(i)) == 0:\r\n arr.append(i)\r\n sum+=i\r\nprint(sum)\r\nprint(arr[0])\r\n","sub_path":"4000/4571.py","file_name":"4571.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"178101492","text":"# -*- coding: utf-8 -*-\n'''\n.. _module_mc_pnp4nagios:\n\nmc_pnp4nagios / pnp4nagios functions\n============================================\n\nThere are many way to configure pnp4nagios.\nI have chosen to configure pnp4nagios \"Bulk Mode with NPCD and npcdmod\"\n(http://docs.pnp4nagios.org/pnp-0.6/config#bulk_mode_with_npcd_and_npcdmod)\nbecause of the lightness of the configuration\n\n\n'''\n\n# Import python libs\nimport logging\nimport copy\nimport mc_states.api\n\nimport hmac\nimport hashlib\n\n__name = 'pnp4nagios'\n\nlog = logging.getLogger(__name__)\n\n\ndef settings():\n '''\n pnp4nagios settings\n\n location\n installation directory\n\n package\n list of packages to install icinga-web\n configuration_directory\n directory where configuration files are located\n\n nginx\n dictionary to store values of nginx configuration\n\n domain\n name of virtualhost created to serve webpages\n doc_root\n root location of virtualhost\n vh_content_source\n template file for nginx content file\n vh_top_source\n template file for nginx top file\n\n pnp4nagios\n dictionary to store values used in templates given in\n vh_content_source and vh_top_source\n\n web_directory\n location under which webpages of pnp4nagios\n will be available\n fastcgi_pass\n socket used to contact fastcgi server in order to\n interpret php files\n realm\n message displayed for digest authentication\n htpasswd_file\n location of file storing users password\n or url for ldap authent\n htdoc_dir\n root location for web_directory\n\n phpfpm\n dictionary to store values of phpfpm configuration\n\n open_basedir\n paths to add to open_basedir\n extensions_package\n additional packages to install (such\n as php5-pgsql or php5-mysql for\n php database connection)\n doc_root\n root location for php-fpm\n session_auto_start\n must be 0 to run icinga-web\n\n npcd_cfg\n dictionary to store configuration of npcd.cfg file\n config_php\n dictionary to store configuration of config.php file\n\n conf\n subdictionary to store the values\n of the $conf[] php array variable\n views\n subdictionary to store the values of\n the $views[] php array variable\n\n each subdictionary under views corresponds\n to a subarray. The key of subdictionaries are\n the values for \"title\" array key\n rra_cfg\n dictionary to store the configuration of rra.cfg file\n\n RRA_STEP\n value for RRA_STEP\n steps\n list of strings where each string is a line in rra.cfg file\n\n '''\n @mc_states.api.lazy_subregistry_get(__salt__, __name)\n def _settings():\n _g, _p, _s = __grains__, __pillar__, __salt__\n locs = _s['mc_locations.settings']()\n\n pnp4nagios_reg = _s[\n 'mc_macros.get_local_registry'](\n 'pnp4nagios', registry_format='pack')\n\n data = _s['mc_utils.defaults'](\n 'makina-states.services.monitoring.pnp4nagios', {\n 'package': ['pnp4nagios-bin', 'pnp4nagios-web'],\n 'configuration_directory': locs['conf_dir']+\"/pnp4nagios\",\n 'nginx': {\n 'vhost_basename': 'pnp',\n 'ssl_cacert': '',\n 'ssl_cert': '',\n 'ssl_key': '',\n 'domain': \"pnp4nagios.localhost\",\n 'doc_root': \"/usr/share/pnp4nagios/html/\",\n 'vh_content_source': (\n \"salt://makina-states/files/\"\n \"etc/nginx/includes/\"\n \"pnp4nagios.content.conf\"),\n 'vh_top_source': (\n \"salt://makina-states/files/etc/nginx/\"\n \"includes/pnp4nagios.top.conf\"),\n 'pnp4nagios': {\n 'web_directory': \"/pnp4nagios\",\n 'fastcgi_pass': (\"unix:/var/spool/www/\"\n \"pnp.fpm.sock\"),\n 'realm': \"Authentication\",\n 'htpasswd_file': \"/etc/icinga2/htpasswd.users\",\n 'htdocs_dir': \"/usr/share/icinga/htdocs/\",\n },\n },\n 'phpfpm': {\n 'pool_name': 'pnp',\n 'open_basedir': (\n \"/usr/bin/rrdtool\"\n \":/etc/pnp4nagios/\"\n \":/usr/share/php/kohana2/system/\"\n \":/usr/share/php/kohana2/system/config/\"\n \":/var/lib/pnp4nagios/perfdata/\"),\n 'doc_root': '/usr/share/pnp4nagios/',\n 'etcdir': '/etc/php/5.6',\n 'session_auto_start': 0,\n 'extensions_packages': ['php5-gd'],\n },\n 'npcd_cfg': {\n 'user': \"nagios\",\n 'group': \"nagios\",\n 'log_type': \"syslog\",\n 'log_file': \"/var/log/pnp4nagios/npcd.log\",\n 'max_logfile_size': 10485760,\n 'log_level': 0,\n 'perfdata_spool_dir': \"/var/spool/icinga2/perfdata\",\n 'perfdata_file_run_cmd': (\n \"/usr/lib/pnp4nagios/libexec/process_perfdata.pl\"),\n 'perfdata_file_run_cmd_args': \"-b\",\n 'identify_npcd': 1,\n 'npcd_max_threads': 5,\n 'sleep_time': 15,\n 'load_threshold': 0.0,\n 'pid_file': \"/var/run/npcd.pid\",\n 'perfdata_file': \"/var/spool/icinga2/perfdata.dump\",\n 'perfdata_spool_filename': \"perfdata\",\n 'perfdata_file_processing_interval': 15,\n },\n 'config_php': {\n 'conf': {\n 'use_url_rewriting': 1,\n 'rrdtool': \"/usr/bin/rrdtool\",\n 'graph_width': 500,\n 'graph_height': 100,\n 'zgraph_width': 500,\n 'zgraph_height': 100,\n 'right_zoom_offset': 30,\n 'pdf_width': 675,\n 'pdf_height': 100,\n 'pdf_page_size': \"A4\",\n 'pdf_margin_top': 30,\n 'pdf_margin_left': 17.5,\n 'pdf_margin_right': 10,\n 'pdf_graph_opt': \"\",\n 'graph_opt': \"\",\n 'rrdbase': \"/var/lib/pnp4nagios/perfdata/\",\n 'page_dir': \"/etc/pnp4nagios/pages/\",\n 'refresh': 90,\n 'max_age': \"60*60*6\",\n 'temp': \"/var/tmp\",\n 'nagios_base': \"/cgi-bin/icinga\",\n 'multisite_base_url': \"/check_mk\",\n 'multisite_site': \"\",\n 'auth_enabled': \"FALSE\",\n 'livestatus_socket': (\n \"unix:/var/run/icinga2/cmd/livestatus\"\n ),\n 'allowed_for_all_services': \"\",\n 'allowed_for_all_hosts': \"\",\n 'allowed_for_service_links': \"EVERYONE\",\n 'allowed_for_host_search': \"EVERYONE\",\n 'allowed_for_host_overview': \"EVERYONE\",\n 'allowed_for_pages': \"EVERYONE\",\n 'popup_width': \"300px\",\n 'ui_theme': 'smoothness',\n 'lang': \"en_US\",\n 'RRD_DAEMON_OPTS': \"\",\n 'template_dirs': [\n \"/etc/pnp4nagios/templates\",\n \"/usr/share/pnp4nagios/html/templates.dist\"],\n },\n 'views': {\n '4 Hours': {\n 'start': \"(60*60*4)\",\n },\n '25 Hours': {\n 'start': \"(60*60*25)\",\n },\n 'One Week': {\n 'start': \"(60*60*25*7)\",\n },\n 'One Month': {\n 'start': \"(60*60*24*32)\",\n },\n 'One Year': {\n 'start': \"(60*60*24*380)\",\n },\n },\n },\n 'rra_cfg': {\n 'RRA_STEP': 60,\n 'steps': [\n \"RRA:AVERAGE:0.5:1:2880\",\n \"RRA:AVERAGE:0.5:5:2880\",\n \"RRA:AVERAGE:0.5:30:4320\",\n \"RRA:AVERAGE:0.5:360:5840\",\n \"RRA:MAX:0.5:1:2880\",\n \"RRA:MAX:0.5:5:2880\",\n \"RRA:MAX:0.5:30:4320\",\n \"RRA:MAX:0.5:360:5840\",\n \"RRA:MIN:0.5:1:2880\",\n \"RRA:MIN:0.5:5:2880\",\n \"RRA:MIN:0.5:30:4320\",\n \"RRA:MIN:0.5:360:5840\",\n ],\n },\n }\n )\n\n if data['nginx'].get('ssl_redirect', False):\n if not data['nginx'].get('ssl_cert', None):\n cert, key, chain = _s['mc_ssl.get_configured_cert'](\n data['nginx']['domain'], gen=True)\n data['nginx']['ssl_key'] = key\n data['nginx']['ssl_cert'] = cert + chain\n data['nginx']['pnp4nagios']['fastcgi_pass'] = (\n \"unix:/var/spool/www/{0}.fpm.sock\".format(\n data['nginx']['vhost_basename'].replace('.', '_')\n )\n )\n\n _s['mc_macros.update_local_registry'](\n 'pnp4nagios', pnp4nagios_reg,\n registry_format='pack')\n return data\n return _settings()\n","sub_path":"mc_states/modules/mc_pnp4nagios.py","file_name":"mc_pnp4nagios.py","file_ext":"py","file_size_in_byte":10597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"309489878","text":"import viscojapan as vj\nfrom pylab import plt\n\nnth_epoch = 28\nfault_file = '../../../fault_model/fault_bott80km.h5'\n\nreader = vj.EpochalFileReader('slip0.h5')\nepochs = reader.get_epochs()\nslip = reader[epochs[nth_epoch]]\nplt.subplot(1,2,1)\nmplt = vj.plots.MapPlotFault(fault_file)\nmplt.plot_slip(slip)\n\n#############\nfault_file = '../../../../iter0/fault_model/fault_bott120km.h5'\nreader = vj.inv.ResultFileReader('nco_06_naslip_10.h5',fault_file)\nslip = reader.get_incr_slip_at_nth_epoch(nth_epoch)\n\nplt.subplot(1,2,2)\nmplt = vj.plots.MapPlotFault(fault_file)\nmplt.plot_slip(slip)\nplt.show()\n\nplt.close()\n\n","sub_path":"inversions/inversion10/iter2/run6/slip0/v1/check_plot.py","file_name":"check_plot.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"356133556","text":"__author__ = \"Petr Kohout \"\n__date__ = \"$29.8.2020 16:21:10$\"\n\nfrom objects.object import Object, ObjectTypes\n#from objects.cyanobacteria import CyanoBacteria\nfrom utils.vector import Vector\nfrom utils.simulation import SimulationManager\nfrom debug.iniLoader import IniLoader\n\n\nclass Ball(Object):\n\n def __init__(self, INI_FILE: str, pos: Vector, dir: Vector):\n super().__init__(INI_FILE=INI_FILE, position=pos, direction=dir)\n\n self.ini = self.ini + \"ball.\"\n\n self.capacity = int(IniLoader.load(self.ini + \"capacity\"))\n self.grid_size = int(IniLoader.load(self.ini + \"grid_size\"))\n self.avg_docking = int(IniLoader.load(self.ini + \"avg_docking\"))\n self.destroyed = 0 # nuber of destroyed cells\n\n self.cyanos = [] # : [CyanoBacteria]\n\n self.type = ObjectTypes.BALL\n\n def move(self, direction=None):\n self.destroyed = 0 # count number of destroyed cells\n for i, item in enumerate(self.cyanos):\n self.cyanos[i][\"time\"] -= SimulationManager().manager.time_step\n if self.cyanos[i][\"time\"] <= 0:\n self.undock(self.cyanos[i][\"obj\"])\n self.destroyed += 1\n super(Ball, self).move()\n\n\n def collision(self, o: Object):\n if o.type == ObjectTypes.CYANO_BACTERIA: # : CyanoBacteria\n self.dock(o)\n elif o.type == ObjectTypes.BALL:\n self.direction.average(o.direction)\n o.direction.average(self.direction)\n elif o.type == ObjectTypes.BUBBLE: # it is strong bubble :D\n self.direction.average(o.direction)\n self.direction.average(o.direction)\n else:\n raise EnvironmentError(\"Cannot make collision with UNKNOWN type\")\n\n def dock(self, o):\n \"\"\"\n :param o: CyanoBacteria\n :return:\n \"\"\"\n if len(self.cyanos) < self.capacity:\n o.docker = self\n self.cyanos[o.id] = {\n \"time\": self.avg_docking, # time ticking\n \"obj\": o\n }\n else:\n self.logger.log(str(self.id) + \" is fully docked\")\n\n def undock(self, o):\n \"\"\"\n :param o: CyanoBacteria\n :return:\n \"\"\"\n if len(self.cyanos) > 0:\n o.docker = None\n del self.cyanos[o.id]\n\n def json_str(self):\n return \"{\" \\\n + '\"type\": \"' + str(self.type) + '\", ' \\\n + '\"id\": ' + str(self.id) + \", \" \\\n + '\"docked\": ' + str(len(self.cyanos)) + \", \" \\\n + '\"destroyed\": ' + str(self.destroyed) + \", \" \\\n + '\"pos\": ' + str(self.position.json_str()) \\\n + \"}\"\n","sub_path":"src/objects/ball.py","file_name":"ball.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"643080719","text":"# Thomas Roux\n# 18/04/2019\n# Displays multiplication table of user defined integer\n\n# Import necessary modules\nfrom pcinput import getInteger\n\n# Takes user defined positive integer\nwhile True:\n num = getInteger(\"Enter a positive integer.\")\n if num <= 0:\n print(\"A positive integer, please!\")\n continue\n else:\n break\n\n# Multiplication table\nfor n in range(1, 11):\n print(\"{:>2d} * {:>2d} = {:>2d}\".format(n, num, num*n))","sub_path":"ex7_1.py","file_name":"ex7_1.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"498227200","text":"from sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\nimport pickle\n# first read data from csv file\npatientdata = pd.read_csv(\"data.csv\")\n\n# train test split data for applying machine learning model\n\n\ndef splitpatientdata(data, ratio):\n np.random.seed(42)\n shuffled = np.random.permutation(len(data))\n testsetsize = int(len(data)*ratio)\n testindices = shuffled[:testsetsize]\n trainindices = shuffled[testsetsize:]\n return data.iloc[trainindices], data.iloc[testindices]\n\n# 20% of patientdata will go to test set data(which will be used to test your ML output)\n# and 80% of patientdata will go to train set data\n# which will be used for making the ML model\n\n\ntrain, test = splitpatientdata(patientdata, 0.2)\n# Now start making ML Model\n\n# Now we will remove infectionprob from train set and test set as\n# we want to apply ML model on the data and we dont result(infectionprob)\n# already there\n\nX_train = train[['fever', 'bodypain', 'age',\n 'runnynose', 'diffbreath']].to_numpy()\nX_test = test[['fever', 'bodypain', 'age',\n 'runnynose', 'diffbreath']].to_numpy()\n# Now we want a seperate data set of result(infectionprob)\nY_train = train[['infectionprob']].to_numpy()\nY_test = test[['infectionprob']].to_numpy()\n# Apply ML model in this project we are using RandomForestClassifier to\n# estimate output\n\nmodel = RandomForestClassifier(n_estimators=100,\n bootstrap=True,\n max_features='sqrt')\n# now we will fit model on the above X_train and Y_train\nmodel.fit(X_train, Y_train)\ninputfeatures = [100, 1, 75, 1, 0]\ninfectionprobabilty = model.predict_proba([inputfeatures])[0][1]\nprint(infectionprobabilty)\n# open a file where you want to store data\nfile = open('model.pkl', 'wb')\n# dump information to that file\npickle.dump(model, file)\nfile.close()\n","sub_path":"ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"647771318","text":"from operator import itemgetter\nfrom itertools import cycle\nfrom docx import Document\nimport warnings\nimport fitz\nimport json\nimport re\n\n\ndocument_save = Document()\nchapter = []\nkeywords = input(\"Enter a keyword to detect the pages for new chapter or press enter to skip: \")\n\n\ndef fonts(doc, granularity=False):\n \"\"\"Extracts fonts and their usage in PDF documents.\n :param doc: PDF document to iterate through\n :type doc: \n :param granularity: also use 'font', 'flags' and 'color' to discriminate text\n :type granularity: bool\n :rtype: [(font_size, count), (font_size, count}], dict\n :return: most used fonts sorted by count, font style information\n \"\"\"\n styles = {}\n font_counts = {}\n page_number = 0\n\n for page in doc:\n page_number = page_number + 1\n blocks = page.getText(\"dict\")[\"blocks\"]\n for b in blocks: # iterate through the text blocks\n if b['type'] == 0: # block contains text\n for l in b[\"lines\"]: # iterate through the text lines\n for s in l[\"spans\"]: # iterate through the text spans\n if keywords in s['text']:\n try:\n chapter.append(page_number)\n # print(s)\n except Exception as e:\n print(e)\n if granularity:\n identifier = \"{0}_{1}_{2}_{3}\".format(s['size'], s['flags'], s['font'], s['color'])\n styles[identifier] = {'size': s['size'], 'flags': s['flags'], 'font': s['font'],\n 'color': s['color']}\n else:\n identifier = \"{0}\".format(s['size'])\n styles[identifier] = {'size': s['size'], 'font': s['font']}\n\n font_counts[identifier] = font_counts.get(identifier, 0) + 1 # count the fonts usage\n\n font_counts = sorted(font_counts.items(), key=itemgetter(1), reverse=True)\n\n if len(font_counts) < 1:\n raise ValueError(\"Zero discriminating fonts found!\")\n\n return font_counts, styles\n\n\ndef font_tags(font_counts, styles):\n \"\"\"Returns dictionary with font sizes as keys and tags as value.\n :param font_counts: (font_size, count) for all fonts occuring in document\n :type font_counts: list\n :param styles: all styles found in the document\n :type styles: dict\n :rtype: dict\n :return: all element tags based on font-sizes\n \"\"\"\n p_style = styles[font_counts[0][0]] # get style for most used font by count (paragraph)\n p_size = p_style['size'] # get the paragraph's size\n\n # sorting the font sizes high to low, so that we can append the right integer to each tag\n font_sizes = []\n for (font_size, count) in font_counts:\n font_sizes.append(float(font_size))\n font_sizes.sort(reverse=True)\n\n # aggregating the tags for each font size\n idx = 0\n size_tag = {}\n for size in font_sizes:\n idx += 1\n if size == p_size:\n idx = 0\n size_tag[size] = '

    '\n if size > p_size:\n size_tag[size] = ''.format(idx)\n elif size < p_size:\n size_tag[size] = ''.format(idx)\n\n return size_tag\n\n\ndef headers_para(doc, size_tag,starting, ending):\n \"\"\"Scrapes headers & paragraphs from PDF and return texts with element tags.\n :param doc: PDF document to iterate through\n :type doc: \n :param size_tag: textual element tags for each size\n :type size_tag: dict\n :rtype: list\n :return: texts with pre-pended element tags\n \"\"\"\n header_para = [] # list with headers and paragraphs\n first = True # boolean operator for first header\n previous_s = {} # previous span\n\n for page in doc.pages(starting,ending,1): #64\n blocks = page.getText(\"dict\")[\"blocks\"]\n for b in blocks: # iterate through the text blocks\n if b['type'] == 0: # this block contains text\n\n # REMEMBER: multiple fonts and sizes are possible IN one block\n\n block_string = \"\" # text found in block\n for l in b[\"lines\"]: # iterate through the text lines\n for s in l[\"spans\"]: # iterate through the text spans\n if s['text'].strip(): # removing whitespaces:\n if first:\n previous_s = s\n first = False\n block_string = size_tag[s['size']] + s['text']\n else:\n if s['size'] == previous_s['size']:\n\n if block_string and all((c == \"|\") for c in block_string):\n # block_string only contains pipes\n block_string = size_tag[s['size']] + s['text']\n if block_string == \"\":\n # new block has started, so append size tag\n block_string = size_tag[s['size']] + s['text']\n else: # in the same block, so concatenate strings\n block_string += \" \" + s['text']\n\n else:\n header_para.append(block_string)\n block_string = size_tag[s['size']] + s['text']\n\n previous_s = s\n\n # new block started, indicating with a pipe\n block_string += \"\"\n header_para.append(block_string)\n\n return header_para\n\n\ndef main():\n\n with open(\"words.txt\", \"r\") as words_file:\n finding_words = words_file.read().splitlines()\n finding_words = [\" \"+each_string.lower()+\" \" for each_string in finding_words]\n\n with open(\"ignoreword.txt\", \"r\") as i_words_file:\n ignore_words = i_words_file.read().splitlines()\n ignore_words = [\" \" + each_string + \" \" for each_string in ignore_words]\n\n doc_name = input(\"Enter your pdf file name: \")\n header_font_list = []\n document = doc_name + '.pdf'\n doc = fitz.open(document)\n Split_File = input('Do you want to split output file? Please type 1 for yes otherwise type 0 and press enter : ')\n print(\"Please type the tags of header fonts you want to add and type quit\")\n print(\"Example : \\nYou can get the list of header tags from detect_header python script.\")\n split = int(Split_File)\n enter = True\n\n while enter:\n add_header_font = input('Type Header tag or type quit: ')\n if \"\" in each_element:\n each_element = each_element.replace(\"\\n\", \" \")\n each_element = each_element.replace(\"

    \", \" \")\n final = final+each_element\n\n # elif \"\" in each_element:\n # each_element = each_element.replace(\"\\n\", \" \")\n # each_element = each_element.replace(\"\", \" \")\n # #final = final + each_element\n\n print(i,\" Lines Done\")\n i = i+1\n\n elif split == 1:\n running = True\n chapter_no = 1\n\n print(\"Do you want to split it by pages?\")\n answer = input(\"Type 1 for yes or press Enter: \")\n\n if answer == \"1\":\n chapter.clear()\n continue_input = True\n while continue_input:\n page_num_str = input('Type page number or type quit: ')\n if \"quit\" in page_num_str :\n continue_input = False\n else:\n try:\n page_num = int(page_num_str)\n chapter.append(page_num)\n except Exception as e:\n print(e)\n\n if answer != \"1\":\n if keywords == \"\":\n print(\"\\n *** Please run the program again and make sure \"\n \"to type a unique keyword to detect new chapter. ***\")\n exit()\n new_cycle = cycle(chapter)\n ending = next(new_cycle)\n\n while running:\n i = 0\n final = \"\"\n elements_ = []\n first_page = True\n Last_page = True\n document_save = Document()\n starting, ending = chapter[0], chapter[1]\n elements_ = headers_para(doc, size_tag, starting-1, ending-1)\n print(\"Total lines are \" + str(len(elements_)))\n\n for each_element in elements_:\n if \"\" in each_element:\n each_element = each_element.replace(\"\\n\", \" \")\n each_element = each_element.replace(\"

    \", \" \")\n final = final + each_element\n\n # elif \"\" in each_element:\n # each_element = each_element.replace(\"\\n\", \" \")\n # each_element = each_element.replace(\"\", \" \")\n # #final = final + each_element\n\n if i == len(elements_)-1:\n if final != \"\":\n pass\n try:\n string_list = final.split(\". \")\n # string_list = re.split(r'.(?=. [A-Z])', final)\n for sk in string_list:\n sk = sk + \".\\n\"\n for word in finding_words:\n if word in sk:\n for i_word in ignore_words:\n if i_word in sk:\n break\n else:\n first, last = sk.split(word)\n p = document_save.add_paragraph(first)\n runner = p.add_run(word)\n runner.bold = True\n p.add_run(last)\n break\n\n document_save.save(\"Folder/\"+\"chapter_\"+str(chapter_no)+\".docx\")\n except Exception as e:\n print(e)\n print(each_element)\n\n i = i + 1\n print(\"Chapter no \" +str(chapter_no)+ \" Complete\")\n chapter_no = chapter_no + 1\n chapter.pop(0)\n\n if ending == chapter[len(chapter) - 1]:\n #print(\"Running False\")\n running = False\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"23918234","text":"\"\"\"\n validation_helpers.py\n\nFunctions used to validate Agave API request data.\n\"\"\"\nfrom flask import jsonify\n\n\ndef basic_access_token_checks(access_token=None):\n \"\"\" Test validity of access token\n\n Check whether the Authorization header from the request meets basic format\n requirements.\n\n INPUT\n -----\n access_token : string (default: None)\n \"\"\"\n if (access_token is None or access_token == \"\" or \n access_token[:7] != \"Bearer \" or len(access_token[7:]) < 30):\n resp = jsonify({\"error\": \"Bad authorization header\"})\n resp.status_code = 400\n return resp\n else:\n None\n\n\ndef basic_system_id_checks(system_id=None):\n \"\"\" Test validity of system ID\n\n Check whether the system ID meets basic format requirements.\n\n INPUT\n -----\n system_id : string (default: None)\n \"\"\"\n if system_id is None or system_id == \"\":\n resp = jsonify({\"error\": \"No system ID specified\"})\n resp.status_code = 400\n return resp\n else:\n return None\n\n\ndef basic_file_path_checks(file_path=None):\n \"\"\" Test validity of file path\n \n Check whether the system ID meets basic format requirements.\n \n INPUT\n -----\n system_id : string (default: None)\n \"\"\"\n if file_path is None or file_path == \"\":\n resp = jsonify({\"error\": \"No path to file/dir specified\"})\n resp.status_code = 400\n return resp\n else:\n return None\n","sub_path":"tests/agave_mock_server/agave_mock_server/validation_helpers.py","file_name":"validation_helpers.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"60320963","text":"\"\"\"\n This is the implementation of following paper:\n https://arxiv.org/pdf/1802.05591.pdf\n This implementation is based on following code:\n https://github.com/Wizaron/instance-segmentation-pytorch\n \"\"\"\nfrom torch.nn.modules.loss import _Loss\nfrom torch.autograd import Variable\nimport torch\nimport numpy as np\n\n\nclass DiscriminativeLoss(_Loss):\n \n def __init__(self,eps = 1e-6,delta_dist_intra = 1.1, delta_dist_inter=2.,\n norm=2, alpha=1.0, beta=1.0, gamma=0.001, delta_var = 0.5,\n usegpu=True, size_average=True):\n super(DiscriminativeLoss, self).__init__(size_average)\n self.eps = eps\n self.delta_dist_intra = delta_dist_intra\n self.alpha = alpha\n self.beta = beta\n self.gamma = gamma\n self.delta_dist_inter = delta_dist_inter\n self.delta_var = delta_var\n self.norm = norm\n self.usegpu = usegpu\n self.h = 513\n self.w = 513\n assert self.norm in [1, 2]\n \n def forward(self, input, target, n_clusters,epoch):\n #_assert_no_grad(target)\n return self._discriminative_loss(input, target, n_clusters,epoch)\n \n def _discriminative_loss(self, image, instances_bs, annid,epoch):\n class_loss = torch.zeros(20,4).cuda()\n coeffs = torch.zeros(3).cuda()\n coeffs[0] = self.alpha\n coeffs[1] = self.beta\n coeffs[2] = self.gamma\n class_dist = torch.zeros(1).cuda()\n for i in range(image.size(0)):\n img = image[i,:,:,:]\n instances = instances_bs[i].float().cuda()\n annots = annid[i]\n imshape = img.shape\n instshape = instances.shape\n # print(i)\n #print(instances.shape)\n #feats,clusters,h,w\n img = img.unsqueeze(1).expand(imshape[0],instshape[0],imshape[1],imshape[2])\n #1,clusters,h,w\n instances = instances.unsqueeze(0)\n \n mns = self.cluster_means(img,instances,epoch)\n #mns,rpts = self.cluster_means(img,instances)\n cvar = self.cluster_vars(img,instances,mns)\n #rvar = self.cluster_vars(img,instances,rpts)\n uniqids = np.unique(annots)\n mean_of_class = []\n \n for val in uniqids:\n indices = np.where(annots==val)\n if len(indices[0]) > 1:\n dist_intra = self.distances(mns,indices[0],self.delta_dist_intra) #+ self.distances(rpts,indices[0],self.delta_dist_intra)\n var_intra = cvar[indices[0]].mean() #+ rvar[indices[0]].mean()\n reg_term = torch.mean(torch.norm(mns[:,indices[0]],2,0)) #+ torch.mean(torch.norm(rpts[:,indices[0]],2,0))\n mean_of_class.append(torch.t(mns[:,indices[0]].mean(dim=1).view(1,-1)))\n else:\n dist_intra = torch.zeros(1)[0].cuda()\n var_intra = cvar[indices[0]][0] #+ rvar[indices[0]][0]\n reg_term = torch.norm(mns[:,indices[0]],2,0)[0] #+ torch.norm(rpts[:,indices[0]],2,0)[0]\n mean_of_class.append(mns[:,indices[0]])\n class_loss[val-1,0] += var_intra\n class_loss[val-1,1] += dist_intra\n class_loss[val-1,2] += reg_term\n class_loss[val-1,3] += torch.ones(1)[0].cuda()\n #print(var_intra,dist_intra,reg_term)\n mns_mean = torch.stack(mean_of_class,dim=1)[:,:,0]\n class_dist += self.distances(mns_mean,np.arange(mns_mean.shape[1]),self.delta_dist_inter)\n #print(class_dist)\n \n #print(class_loss)\n scaled_loss = class_loss[:,:3]/(class_loss[:,3].unsqueeze(1).expand(20,3)+self.eps)\n loss = torch.mm(scaled_loss,coeffs.view(-1,1)).sum() + class_dist/image.size(0)\n return loss\n \n def cluster_means(self,img,instances,epoch):\n #feats,clusters,h,w\n result = img.float()*instances.float()\n #feats,clusters\n #print(instances.sum(dim=[2,3]))\n# means = result.sum(dim=[2,3])/(instances.sum(dim=[2,3])+self.eps)\n\n\n collection = []\n for i in range(instances.shape[1]):\n st = torch.nonzero(instances[0,i,:,:])\n if len(st) > 0:\n sample_pt = st[np.random.randint(0,len(st),size=max(1,int(((100-2*epoch)/100)*len(st))))]\n collection.append(result[:,i,sample_pt[:,0],sample_pt[:,1]].sum(dim=1)/(instances[0,i,sample_pt[:,0],sample_pt[:,1]].sum()+self.eps))\n else:\n collection.append(torch.zeros(img.shape[0]).float().cuda())\n\n rpts = torch.stack(collection,dim=1)\n\n return rpts\n\n def cluster_vars(self,img,instances,means):\n #feats,clusters,h*w\n mn_shape = means.shape\n means = means.unsqueeze(2).expand(mn_shape[0],mn_shape[1],self.h*self.w)\n means = means.view(mn_shape[0],mn_shape[1],self.h,self.w)\n var = (torch.clamp(torch.norm((img - means),2,0) - self.delta_var,min=0)**2) * instances[0,:,:,:]\n \n new_var = var.sum([1,2])/(instances[0,:].sum([1,2])+self.eps)\n \n return new_var\n\n def distances(self,means,indices,delta_dist):\n \n if means.shape[1] > 1:\n \n ax1,ax2 = means.shape\n temp_ma = means[:,indices].unsqueeze(2).expand(ax1,len(indices),len(indices))\n temp_mb = temp_ma.permute(0,2,1)\n diff = temp_ma - temp_mb\n margin = 2*delta_dist*(1-torch.eye(len(indices)))\n c_dist = torch.sum(torch.clamp(margin.cuda()-torch.norm(diff,2,0),min=0)**2)\n \n dist = c_dist/(len(indices)*(len(indices)-1))\n \n else:\n dist = torch.zeros(1).cuda()\n return dist\n","sub_path":"new_loss.py","file_name":"new_loss.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"609752520","text":"import scrapy\nimport json\nfrom scrapy import FormRequest\nfrom scrapy.shell import inspect_response\nimport urllib.parse\n\n \nclass QuotesSpider(scrapy.Spider):\n page = 2\n count = 0\n name = 'quotes'\n start_urls = [\n 'https://www.farpost.ru/vladivostok/',\n ]\n\n def parse(self, response):\n with open(\"search_cnfg.json\", \"r\") as read_file:\n data = json.load(read_file)\n s = data['search'].encode()\n next_page = response.url + 'dir?query=' + str(urllib.parse.quote_plus(s))\n yield {'alo': data['search'].encode()}\n #yield response.follow(next_page, self.search)\n \n\n def search(self, response):\n results_count = int(response.css('#itemsCount_placeholder').attrib['data-count'])\n for item in response.css('div.bull-item-content'):\n if self.count < results_count:\n self.count += 1\n yield {\n 's_count': self.count,\n 'r': results_count,\n 'title': item.css('div.bull-item-content__subject-container a::text').get(),\n 'link': 'https://farpost.ru' + item.css('div.bull-item-content__subject-container a').attrib['href'],\n 'prise': item.css('div.price-block__final-price span::text').get(),\n }\n else:\n self.crawler.engine.close_spider(self, reason='finished')\n\n while((response != None)and(self.count < results_count)and(self.count < 500)):\n next_page = response.url + '&?page' + str(self.page)\n self.page += 1\n yield response.follow(next_page, self.search)\n\n\n# print(urllib.parse.quote_plus(s))\n\n # def parse(self, response):\n # for item in response.css('div.bull-item-content'):\n # yield {\n # 'title': item.css('div.bull-item-content__subject-container a::text').get(),\n # 'prise': item.css('div.price-block__final-price span::text').get(),\n # 'subtitle': item.css('div.bull-item__annotation-row::text').get(),\n # }\n\n # page = 2\n # while(response != None):\n # next_page = response.url + '?page' + str(page)\n # page += 1\n # yield response.follow(next_page, self.parse)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"236262178","text":"from datetime import datetime\nfrom flask import request, session\nfrom flask_restful import Resource, reqparse, fields, marshal\nimport App.ext\nfrom App import dao, helper\nfrom App.models import User\n\n\nclass AccountApi(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('opt', required=True, help='没有声明opt的操作')\n\n def get(self):\n # 从请求参数中获取opt和token参数值\n # 如果opt 为active ,则从redis缓存中查询token对应的user.id\n # 再通过 user.id查询数据库中用户, 最后更新用户的is_active状态为True\n args = self.parser.parse_args()\n opt = args.get('opt')\n if opt == 'active':\n activeParser = self.parser.copy()\n activeParser.add_argument('token', required=True, help='必须提供激活的token')\n args = activeParser.parse_args() # 验证请求参数\n token = args.get('token')\n # 进一步处理\n user_id = App.ext.cache.get(token)\n if user_id:\n # 查询用户,并设置用户激活状态\n user = dao.getById(User, user_id)\n user.is_active = True\n\n dao.save(user)\n\n return {'msg': user.nickName+' 用户激活成功!'}\n\n else:\n # 重新申请用户激活\n reactive_url = request.host_url + 'account/?opt=reactive'\n return {'msg': ' 本次激活已过期,需要重新申请激活: '+ reactive_url}\n elif opt == 'login':\n return self.login()\n elif opt == 'reactive':\n return self.reactive()\n elif opt == 'logout':\n return self.logout()\n\n def login(self): # GET请求时,opt为login时\n loginParser = self.parser.copy()\n loginParser.add_argument('name', required=True, help='用户登录必须提供用户名')\n loginParser.add_argument('passwd', required=True, help='用户登录必须提供口令')\n\n # 验证登录参数\n args = loginParser.parse_args()\n\n username = args.get('name')\n password = args.get('passwd')\n\n # 查询用户(额外添加一条件:用户已激活)\n print(username, password)\n qs = dao.query(User).filter(User.name.__eq__(username),\n User.password.__eq__(helper.md5_crypt(password)),\n User.is_active == True,\n User.is_life == True)\n\n if not qs.count():\n return {'status': 600, 'msg': '用户登录失败,用户名或口令不正确!'}\n\n u = qs.first()\n\n u.last_login_time = datetime.today()\n\n dao.save(u) # 更新用户登录的时间\n\n token = helper.getToken()\n session[token] = u.id # 将token存放session中\n\n out_user_fields = {\n 'name': fields.String,\n 'email': fields.String,\n 'phone': fields.String,\n 'photo': fields.String(attribute='photo_1')\n }\n\n out_fields = {\n 'msg': fields.String,\n 'data': fields.Nested(out_user_fields),\n 'access_token': fields.String\n }\n\n data = {'msg': '登录成功!',\n 'data': u,\n 'access_token': token}\n\n # 通过marshal 将返回的data数据按输出字段转成json字符\n return marshal(data, out_fields)\n\n def reactive(self):\n # 重新申请用户激活\n reactiveParser = self.parser.copy()\n reactiveParser.add_argument('email', required=True, help='必须提供用户邮箱')\n args = reactiveParser.parse_args()\n\n email = args.get('email')\n qs = dao.query(User).filter(User.email.__eq__(email))\n if not qs.count():\n return {\n 'status': 700,\n 'msg': email + ' 邮箱未被注册!'\n }\n\n # 重新发送邮箱\n helper.sendEmail(qs.first())\n\n return {'msg':'重新申请用户激活,请查收邮箱进行激活'}\n\n def logout(self):\n myParser = self.parser.copy()\n myParser.add_argument('token', required=True, help='用户退出必须提供token参数')\n\n args = myParser.parse_args()\n token = args.get('token')\n user_id = session.get(token)\n if not user_id:\n return {'status': 701, 'msg': '用户未登录,请先登录!'}\n\n u = dao.getById(User, user_id)\n if not u:\n return {'status': 702, 'msg': '用户退出失败,token无效!'}\n\n session.pop(token) # 从session中删除token\n return {'status': 200, 'msg': '退出成功!'}\n\n","sub_path":"App/apis/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"166873401","text":"import pickle\nimport tensorflow as tf\nfrom netCDF4 import Dataset\nimport pickle\nimport numpy as np\nimport csv\nimport Orange as og\nimport math\nimport itertools as it\nfrom Orange.data import Domain, Table\nimport random\nfrom Orange.projection import PCA\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\nimport pandas as pd\nimport os\nfrom copy import deepcopy\n\n#access netcdf data file\nnetcdf_entire_dataset = Dataset(\"F:/dataset/rain_data/summing_dataset.nc\", \"r\")\nrain_models = netcdf_entire_dataset.variables['summing_models']\n\nwith open('random70.csv') as csvf:\n ind70 = csv.reader(csvf)\n indexi70 = list(ind70)\n index70 = indexi70[0]\n\nwith open('random30.csv') as csvf:\n ind30 = csv.reader(csvf)\n indexi30 = list(ind30)\n index30 = indexi30[0]\n\n# #read MAE and RMSE files\n# dfMAE = pd.read_csv('MAE25x25.csv', header=None)\n# dfRMSE = pd.read_csv('RMSE25x25.csv', header=None)\n\n\n# creating the whole dataset (inputs and target), not dividing into training and testing here\ndef create_training_data(grid_x, grid_y):\n data_x = [] # inputs\n data_y = [] # target\n tr_count = 0\n for i in index70: # working with 20 days\n for j in range(10): # 10 times in each day\n x = []\n for k in range(1, 25): # 24 models as input\n # print('model: ', k)\n b = rain_models[i, j, k, grid_y - 1:grid_y + 2, grid_x - 1:grid_x + 2] #taking an area of 9X9 from every model\n rain100 = np.array(b)\n x.append(list(it.chain.from_iterable(rain100))) # flatten the list\n\n bt = rain_models[i, j, 0, grid_y, grid_x] #taking the real data as target, zero in the third dimention is for real data\n rainR = bt\n\n data_y.append(rainR) # appending real rain data\n data_x.append(list(it.chain.from_iterable(x))) # appending inputs\n\n return data_x, data_y\n\n# creating the whole dataset (inputs and target), not dividing into training and testing here\ndef create_testing_data(grid_x, grid_y):\n data_x = [] # inputs\n data_y = [] # target\n tr_count = 0\n for i in index30: # working with 20 days\n for j in range(10): # 10 times in each day\n x = []\n for k in range(1, 25): # 24 models as input\n # print('model: ', k)\n b = rain_models[i, j, k, grid_y - 1:grid_y + 2, grid_x - 1:grid_x + 2] #taking an area of 9X9 from every model\n rain100 = np.array(b)\n x.append(list(it.chain.from_iterable(rain100))) # flatten the list\n\n bt = rain_models[i, j, 0, grid_y, grid_x] #taking the real data as target, zero in the third dimention is for real data\n rainR = bt\n\n data_y.append(rainR) # appending real rain data\n data_x.append(list(it.chain.from_iterable(x))) # appending inputs\n\n return data_x, data_y\n\n# dividing into training and testing dataset here\n# training new models using the training data\n# storing the new models\n# predicting target for the testing data\n# calculating mae and rmse of the new prediction\ndef run_models(grid_y, grid_x):\n X_train, Y_train = create_training_data(grid_x, grid_y) # X and Y is the inputs and target\n data = Table(X_train, Y_train) # creating a Orange table combining both X and Y\n\n feature_method = og.preprocess.score.UnivariateLinearRegression() # feature selection\n selector = og.preprocess.SelectBestFeatures(method=feature_method, k=50) # taking 50 features out of 216\n out_data2 = selector(data) # this is the new dataset with 50 features\n\n pca = PCA(n_components=5) # PCA with 5 components\n model = pca(out_data2)\n train2 = model(out_data2)\n\n featuresIndex = set()\n for comp in range(len(model.components_)-1, 0, -1):\n top2 = (- np.array(model.components_[comp])).argsort()[:2]\n featuresIndex |= set(top2)\n\n top2 = (- np.array(model.components_[0])).argsort()[:13]\n f_index = 0\n while(len(featuresIndex) != 13):\n featuresIndex.add(top2[f_index])\n f_index += 1\n\n ind = np.array(list(featuresIndex))\n\n # train = Table(list(out_data2[:,ind]), Y_train)\n # print(train)\n store = np.array(pca.domain)[ind]\n # print(store)\n np.savetxt('unlucky13/' + str(grid_x) + '_' + str(grid_y) + '.csv', store, delimiter=',', fmt='%s')\n\n# total = 0\n# countMAE = 0\n# countRMSE = 0\n# tempCheck = []\n# for grid_y in range(1, 45): # for every y\n# for grid_x in range(1, 66): # for every x\n# print('=================PLACE:', grid_x, grid_y, '=====================')\n# tempCheck = rain_models[:20, :10, 0, grid_y, grid_x]\n# if not tempCheck.any():\n# continue\n# run_models(grid_y, grid_x)\n\n###########################################################################################\n# #read MAE and RMSE files\n# readData = pd.read_csv('new_results/MAE25x25_calculations_modified.csv', header=None)\n# temp = pd.to_numeric(np.array(readData[33])[1:])\n# print(temp)\n#\n# f_array = []\n# f_index = 0\n# for grid_y in range(1, 45): # for every y\n# for grid_x in range(1, 66): # for every x\n# print('=================PLACE:', grid_x, grid_y, '=====================')\n# tempCheck = rain_models[:20, :10, 0, grid_y, grid_x]\n# if not tempCheck.any():\n# f_array.append(0)\n# else:\n# readFeatures = pd.read_csv('unlucky13/' + str(grid_x) + '_' + str(grid_y) + '.csv', header=None)\n# f_temp = np.array(readFeatures[0])[:]\n#\n# flag = False\n# for f in f_temp:\n# if f == 'Feature 058' and temp[f_index] > 0:\n# print(f)\n# flag = True\n#\n# if flag: f_array.append(1)\n# else: f_array.append(0)\n# f_index += 1\n# # print(f_array)\n# np.savetxt('complicated_1.csv', f_array, delimiter=',', fmt='%s')\n###########################################################################################\n\ndef create_array(grid_y, grid_x, tempMAE):\n readFeatures = pd.read_csv('unlucky13/' + str(grid_x) + '_' + str(grid_y) + '.csv', header=None)\n f_temp = np.array(readFeatures[0])[:]\n\n temp = [0]*24\n for f in f_temp:\n f = np.char.replace(f, \" \", \"\")\n print('there we go:', f)\n if f >= 'Feature001' and f <'Feature010' and tempMAE > 0:\n print(f)\n temp[0] += 1\n\n elif f >= 'Feature010' and f <'Feature019' and tempMAE > 0:\n print(f)\n temp[1] += 1\n\n elif f >= 'Feature019' and f <'Feature028' and tempMAE > 0:\n print(f)\n temp[2] += 1\n\n elif f >= 'Feature028' and f <'Feature037' and tempMAE > 0:\n print(f)\n temp[3] += 1\n\n elif f >= 'Feature037' and f <'Feature046' and tempMAE > 0:\n print(f)\n temp[4] += 1\n\n elif f >= 'Feature046' and f <'Feature055' and tempMAE > 0:\n print(f)\n temp[5] += 1\n\n elif f >= 'Feature055' and f <'Feature064' and tempMAE > 0:\n print(f)\n temp[6] += 1\n\n elif f >= 'Feature064' and f <'Feature073' and tempMAE > 0:\n print(f)\n temp[7] += 1\n\n elif f >= 'Feature073' and f <'Feature082' and tempMAE > 0:\n print(f)\n temp[8] += 1\n\n elif f >= 'Feature082' and f <'Feature091' and tempMAE > 0:\n print(f)\n temp[9] += 1\n\n elif f >= 'Feature091' and f <'Feature100' and tempMAE > 0:\n print(f)\n temp[10] += 1\n\n elif f >= 'Feature100' and f <'Feature109' and tempMAE > 0:\n print(f)\n temp[11] += 1\n\n elif f >= 'Feature109' and f <'Feature118' and tempMAE > 0:\n print(f)\n temp[12] += 1\n\n elif f >= 'Feature118' and f <'Feature127' and tempMAE > 0:\n print(f)\n temp[13] += 1\n\n elif f >= 'Feature127' and f <'Feature136' and tempMAE > 0:\n print(f)\n temp[14] += 1\n\n elif f >= 'Feature136' and f <'Feature145' and tempMAE > 0:\n print(f)\n temp[15] += 1\n\n elif f >= 'Feature145' and f <'Feature154' and tempMAE > 0:\n print(f)\n temp[16] += 1\n\n elif f >= 'Feature154' and f <'Feature163' and tempMAE > 0:\n print(f)\n temp[17] += 1\n\n elif f >= 'Feature163' and f <'Feature172' and tempMAE > 0:\n print(f)\n temp[18] += 1\n\n elif f >= 'Feature172' and f <'Feature181' and tempMAE > 0:\n print(f)\n temp[19] += 1\n\n elif f >= 'Feature181' and f <'Feature190' and tempMAE > 0:\n print(f)\n temp[20] += 1\n\n elif f >= 'Feature190' and f <'Feature199' and tempMAE > 0:\n print(f)\n temp[21] += 1\n\n elif f >= 'Feature199' and f <'Feature208' and tempMAE > 0:\n print(f)\n temp[22] += 1\n\n elif f >= 'Feature208' and f <'Feature217' and tempMAE > 0:\n print(f)\n temp[23] += 1\n\n return temp\n\n\n\n# # read MAE and RMSE files\n# readDataMAE = pd.read_csv('new_results/MAE25x25_calculations_modified.csv', header=None)\n# tempMAE = pd.to_numeric(np.array(readDataMAE[33])[1:])\n#\n# f_array = []\n# f_index = 0\n# for grid_y in range(1, 45): # for every y\n# for grid_x in range(1, 66): # for every x\n# print('=================PLACE:', grid_x, grid_y, '=====================')\n# tempCheck = rain_models[:20, :10, 0, grid_y, grid_x]\n# if not tempCheck.any():\n# f_array.append([0]*24)\n# else:\n# getArr = create_array(grid_y, grid_x, tempMAE[f_index])\n# f_array.append(getArr)\n# f_index += 1\n# # print(f_array)\n# np.savetxt('complicated_1.csv', f_array, delimiter=',', fmt='%s')\n\n\ndef data_visualization_2dr(w_data, title, i=0, visualize=True):\n if visualize:\n plt.axis([0, len(w_data[0]), 0, len(w_data)])\n w_data[w_data < 0] = 0\n # w_data[w_data >= 100] = 0\n x, y = w_data.nonzero()\n # x = range(0, 65)\n # y = range(0, 44)\n c = w_data[x, y]\n plt.scatter(y[:], x[:], c=c[:], cmap='jet')\n plt.title(title)\n # plt.colorbar()\n # plt.savefig('com/fig' + str(i) + '.png')\n # plt.clim(-5, 0)\n plt.show()\n plt.close()\n\ndef show_images(images, cols, titles=None):\n assert ((titles is None) or (len(images) == len(titles)))\n n_images = len(images)\n if titles is None: titles = ['Image (%d)' % i for i in range(1, n_images + 1)]\n fig = plt.figure(num=None, figsize=(16, 12), dpi=300, facecolor='w', edgecolor='k')\n # fig.suptitle('Plotting Precipitation Values. Day: 2016/05/20')\n for n, (image, title) in enumerate(zip(images, titles)):\n # a = fig.add_subplot(cols, np.ceil(n_images / float(cols)), n + 1)\n a = fig.add_subplot(6, 4, n + 1)\n plt.axis([0, len(image[0]), 0, len(image)])\n # image[image >= 0] = 0\n # image[image > 10] = 0\n x, y = image.nonzero()\n c = image[x, y]\n\n im = plt.scatter(y[:], x[:], c=c[:], cmap='jet', s=1)\n # if n == 10:\n # plt.ylabel('Vertical Grid')\n # if n == 22:\n # plt.xlabel('Horizontal Grid')\n plt.colorbar()\n # plt.show()\n plt.savefig('complicated_1.png')\n\n#read MAE and RMSE files\nreadData = pd.read_csv('complicated_1.csv', header=None)\nimagesArr = []\nfor i in range(24):\n temp = pd.to_numeric(np.array(readData[i])[:]).reshape((44, 65))\n imagesArr.append(temp)\n\n# imagesArr = np.round(imagesArr/np.max(imagesArr), 1)\nshow_images(imagesArr, 1)\n\n# #read MAE and RMSE files\n# readData = pd.read_csv('complicated_1.csv', header=None)\n# temp = pd.to_numeric(np.array(readData[0])[:]).reshape((44, 65))\n# data_visualization_2dr(temp, title='Complicated Plot 1')","sub_path":"ComplicatedPlot.py","file_name":"ComplicatedPlot.py","file_ext":"py","file_size_in_byte":12005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"363431135","text":"def sqrt (value):\n\txGuess = value/2.0\n\txNext = None\n\txPrev = xGuess\n\t#another previous term added for a value that jumps back and forth\n\txPrevTwo = xGuess\n\twhile xNext != xPrev and xNext != xPrevTwo:\n\t\txNext = xGuess - (xGuess*xGuess-value)/(2*xGuess)\n\t\txPrevTwo = xPrev\n\t\txPrev = xGuess\n\t\txGuess = xNext\n\treturn xNext\n\nif __name__==\"__main__\":\n\tprint(\"What is the weight of the object?\")\n\tweight = float(input())\n\tprint(\"What is the coefficient of drag of the object?\")\n\tcoefficient = float(input())\n\tprint(\"What is the area of the object?\")\n\tarea = float(input())\n\tprint(\"What is the density of the object?\")\n\tdensity = float(input())\n\tvelocity = sqrt((2*weight)/(coefficient*density*area))\n\tprint(\"terminal velocity is \"+str(velocity))\n\tdynamicPressure = 0.5*density*velocity**2\n\tprint(\"Dynamic pressure at terminal velocity is \"+str(dynamicPressure))\n","sub_path":"Hmwk/terminalVelocity/terminalVelocity.py","file_name":"terminalVelocity.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"320354382","text":"import numpy as np\nfrom KFoldCycleCallback import *\nfrom AntMCsSeg_support_defs import *\nfrom dataset import Dataset, Batch, DatasetIndex\nfrom AntMCsBatch import *\n\n\nclass AMCunet_DataGenerator(object):\n def __init__(self,\n ir_src_data_file='./data/ir_subset_30.npy',\n masks_data_file='./data/masks_subset_30.npy',\n targets_data_file='./data/targets_subset_30.npy',\n test_indices_seed = 42,\n val_folds=5,\n test_split_ratio=0.25,\n image_size=(512, 512)):\n\n self.ir_src_data_file = ir_src_data_file\n self.masks_data_file = masks_data_file\n self.targets_data_file = targets_data_file\n self.test_split_ratio = test_split_ratio\n self.test_indices_seed = test_indices_seed\n self.val_folds = val_folds\n self.image_size = image_size\n\n self.read_data()\n\n def read_data(self):\n print('reading IR data...')\n\n self.ir_data = np.load(self.ir_src_data_file)\n print('IR data shape: %s' % str(self.ir_data.shape))\n print('IR data type: ', str(self.ir_data.dtype))\n\n print('reading masks data...')\n self.masks_data = np.load(self.masks_data_file)\n print('masks data shape: %s' % str(self.masks_data.shape))\n print('masks data type: ', str(self.masks_data.dtype))\n\n print('reading targets data...')\n self.targets_data = np.load(self.targets_data_file)\n print('targets data shape: %s' % str(self.targets_data.shape))\n print('targets data type: ', str(self.targets_data.dtype))\n\n self.total_objects_count = self.ir_data.shape[0]\n\n print('indexing data...')\n # split train+val vs test\n\n np.random.seed(self.test_indices_seed)\n self.test_indices = np.random.choice(np.arange(0, self.ir_data.shape[0]), int(self.ir_data.shape[0] * self.test_split_ratio), replace=False)\n rest_indices = np.setdiff1d(np.arange(0, self.ir_data.shape[0], 1), self.test_indices)\n np.random.seed(None)\n self.trainval_indices = np.random.permutation(rest_indices)\n\n self.KFold_valIndices_iterator = K_folds_iterator(x=self.trainval_indices,\n batch_size=int(len(self.trainval_indices) / self.val_folds))\n\n self.val_indices = np.asarray(self.KFold_valIndices_iterator.next())\n self.train_indices = np.asarray([self.trainval_indices[i] for i in range(len(self.trainval_indices)) if\n self.trainval_indices[i] not in self.val_indices])\n\n print('data_train snapshots: ', len(self.train_indices))\n print('data_val snapshots: ', len(self.val_indices))\n print('data_test snapshots: ', len(self.test_indices))\n\n # def cycle_KFold_train_val_sets(self):\n # print('cycling val,train sets inside train+val set')\n # self.val_indices = np.asarray(self.KFold_valIndices_iterator.next())\n # self.train_indices = np.asarray([self.trainval_indices[i] for i in range(len(self.trainval_indices)) if self.trainval_indices[i] not in self.val_indices])\n # self.train_flowDataGenerator.ppl.reset_iter()\n # train_batch_size = self.train_flowDataGenerator.batch_size\n # self.val_flowDataGenerator.ppl.reset_iter()\n # val_batch_size = self.val_flowDataGenerator.batch_size\n # self.train_flowDataGenerator = DataGenerator(self, train_batch_size, 'train')\n # self.val_flowDataGenerator = DataGenerator(self, val_batch_size, 'val')\n\n\n\n def flow(self, batch_size=32, category='train'):\n if category == 'train':\n self.train_flowDataGenerator = DataGenerator(self, batch_size, category)\n return self.train_flowDataGenerator.start()\n elif category == 'val':\n self.val_flowDataGenerator = DataGenerator(self, batch_size, category)\n return self.val_flowDataGenerator.start()\n elif category == 'test':\n self.test_flowDataGenerator = DataGenerator(self, batch_size, category)\n return self.test_flowDataGenerator.start()\n\n\n def dataset_length_batches(self, category='train', batch_size = 32):\n indices_count = self.train_indices.shape[0]\n if category == 'train':\n indices_count = self.train_indices.shape[0]\n elif category == 'val':\n indices_count = self.val_indices.shape[0]\n elif category == 'test':\n indices_count = self.test_indices.shape[0]\n\n if indices_count % batch_size == 0:\n return indices_count / batch_size\n else:\n return int(np.round(indices_count / float(batch_size))+1)\n\n\n\nclass DataGenerator(object):\n\n def __init__(self, myImageDataGenerator, batch_size=32, category='train'):\n self.ImageDataGenerator = myImageDataGenerator\n self.category = category\n if (self.category == 'train'):\n self.data_indices = self.ImageDataGenerator.train_indices\n elif (self.category == 'val'):\n self.data_indices = self.ImageDataGenerator.val_indices\n elif (self.category == 'test'):\n self.data_indices = self.ImageDataGenerator.test_indices\n\n self.batch_size = batch_size\n self.ds = Dataset(index = self.data_indices.shape[0], batch_class=AntMCsBatch, preloaded=(self.ImageDataGenerator.ir_data[self.data_indices],\n self.ImageDataGenerator.masks_data[self.data_indices],\n self.ImageDataGenerator.targets_data[self.data_indices]))\n if self.category == 'train':\n self.ppl = (self.ds.pipeline().transformations().cut_batch().rebatch(batch_size=self.batch_size))\n else:\n self.ppl = (self.ds.pipeline().cut_batch().rebatch(batch_size=self.batch_size))\n\n def start(self):\n self.batches_generated = 0\n self.samples_generated = 0\n\n for batch in self.ppl.gen_batch(batch_size=self.batch_size, n_epochs=None, prefetch=4, drop_last=True, target_image_size=self.ImageDataGenerator.image_size):\n # print('batch %d ir_data shape: %s' % (i, str(batch.ir_data.shape)))\n self.batches_generated += 1\n self.samples_generated += batch.ir_data.shape[0]\n cur_irimages = batch.ir_data\n cur_masks = batch.masks\n cur_targets = batch.targets\n\n yield [cur_irimages, cur_masks], [cur_targets]","sub_path":"AMCunet_DataGenerator.py","file_name":"AMCunet_DataGenerator.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"181991022","text":"## Script (Python) \"backup_sapl_pysc\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=pasta\n##title=\n##\nrequest=context.REQUEST\nresponse=request.RESPONSE\nsession= request.SESSION\nnome=\"bkpbancosapl\"\n\nimport os\nimport App.FindHomes\n#diretorio_instancia = App.FindHomes.INSTANCE_HOME\ndiretorio_var = App.FindHomes.CLIENT_HOME\n#executa o comando mysqldump\ndumpBanco=os.system('mysqldump -uroot interlegis > '+diretorio_var+'/dados.sql')\n\n#nome do arquivo composto da hora e da data\ndata=string.split( DateTime().ISO(),' ')[0]\ndata=string.split( data,'-')[0]+string.split( data,'-')[1]+string.split( data,'-')[2]\nhoras=string.split( DateTime().ISO(),' ')[1]\nhoras=string.split( horas,':')[0]+string.split( horas,':')[1]+string.split( horas,':')[2]\nnome=data+'_'+horas+'_'+'bkpsapl.tgz'\n\n#empacota dados\ncaminho='tar -zcvf '+pasta+nome+' '+diretorio_var+'/DocumentosSapl.fs '+diretorio_var+'/dados.sql'\ndocumentos=os.system(caminho)\n\nremover=os.system('rm '+diretorio_var+'/dados.sql')\nif dumpBanco==0:\n if documentos==0:\n return 'Backup concluido! [ Voltar ]'\n else:\n return 'Problemas no salvamento dos documentos. [ Voltar ]'\nelse: \n return 'Salvamento de dados do banco falhou. Tente novamente! [ Voltar ]'\n\n","sub_path":"branches/2.6/skins/sk_sapl/backup/backup_sapl_pysc.py","file_name":"backup_sapl_pysc.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"99019388","text":"import sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport model\n#comp=sys.argv[2]\n\ndef main(comp,days):\n buystate=0\n buy_res=[]\n sell_res=[]\n date=[]\n i=0\n f=open(comp+'.txt','w')\n data=pd.read_csv('../Data/'+comp+'.csv')\n if days==None:\n days=len(data.index)\n close_p=np.flipud(data['Close'].values[0:days])\n open_p=np.flipud(data['Open'].values[0:days])\n low_p=np.flipud(data['Low'].values[0:days])\n high_p=np.flipud(data['High'].values[0:days])\n volume=np.flipud(data['Total Trade Quantity'].values[0:days])\n Date=np.flipud(data['Date'].values[0:days])\n buy_a,sell_a,stoploss_a=model.main(comp,days)\n\n while(i3:\n days=int(sys.argv[3])\n else:\n days=None\n main(comp,days)\n","sub_path":"Day066/backtester.py","file_name":"backtester.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"67253854","text":"import requests\nimport re\nfor i in range(1,11):\n url=\"https://www.52doutu.cn/pic/\"\n response=requests.get(url+str(i))\n html=response.text\n imgs=re.findall(r'https://www.52doutu.cn/static/images/upload/[^\\s]*.jpg',response.text)\n count=1\n for img in imgs:\n # print(img)\n res=requests.get(img)\n data=res.content\n file=open(\"F://图片//图片//\"+str(count)+\".jpg\",\"wb\")\n file.write(data)\n file.close()\n count+=1\n # print(response.encoding)\n # print(html)\n # print(response.json())","sub_path":"PythonProjects/爬虫/requests/练习1.py","file_name":"练习1.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"298055327","text":"#猎聘网,每一个page有40条记录,page最大值100\n#第一级简介信息爬虫无需设置反爬虫,\n# 但是第二级链接详细信息有反爬机制,目前采取睡眠1-2秒的方式,如果爬虫过快偶尔会出现timeout的异常,日志记录异常\nimport requests\nfrom bs4 import BeautifulSoup\nimport pymysql\nimport liepin_mysql as DB\nimport time\nimport threading\nfrom datetime import datetime\nlock = threading.Lock()\ndef cityToNumber(cityName):\n\n # 一线城市\n if (cityName == '北京'):\n return '010'\n if (cityName == '上海'):\n return '020'\n if (cityName == '广州'):\n return '050020'\n if (cityName == '深圳'):\n return '050090'\n\n # 非一线城市\n if (cityName == '杭州'):\n return '070020'\n if (cityName == '成都'):\n return '280020'\n if (cityName == '南京'):\n return '060020'\n if (cityName == '重庆'):\n return '040'\n if (cityName == '苏州'):\n return '060080'\n if (cityName == '武汉'):\n return '170020'\n if (cityName == '厦门'):\n return '090040'\n\ndef requestsArgu(cityName,searchKey):\n\n my_headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}\n\n baseUrl1 = 'https://www.liepin.com/zhaopin/?pubTime=&ckid=47859fa68f1086ee&fromSearchBtn=2&compkind' \\\n '=&isAnalysis=&init=-1&searchType=1&dqs='\n\n baseUrl2 = '&industryType=&jobKind=&sortFlag=15°radeFlag=0&industries=&salary=&compscale=' \\\n '&clean_condition=&key= '\n\n baseUrl3 = '&headckid=1044990bb2f3db5a&d_pageSize=40&siTag=k_cloHQj' \\\n '_hyIn0SLM9IfRg~-nQsjvAMdjst7vnBI-6VZQ&d_headId=5e971b35915f191cc89e5701fbbf4993&d_ckId' \\\n '=4d04b8eb57216c472f52e366d9a3d8ad&d_sfrom=search_prime&d_curPage=0&curPage='\n\n baseUrl = baseUrl1 + cityToNumber(cityName) \\\n +baseUrl2 + searchKey \\\n +baseUrl3 #猎头招聘网的传参是城市电话代码\n #页码\n return my_headers,baseUrl\n\ndef crawerLiePin(cityName,searchKey,page,db):\n\n my_headers,baseUrl = requestsArgu(cityName,searchKey)\n\n # 打开baseUrl页面,一般不会出错\n try:\n r = requests.get(baseUrl + str(page), headers=my_headers)\n except Exception as err:\n file = r'liePinLog.txt'\n f = open(file, 'a+')\n f.write('A baseUrl error :')\n f.write(repr(err))\n f.write('at time:' + (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) )\n f.write('\\n')\n f.close()\n print(err)\n return\n bs = BeautifulSoup(r.text, 'lxml')\n r.close()\n\n count = len(bs.select('div.sojob-item-main ')) #计数每个第一级页面有多少条工作\n\n positionNameBs = bs.select(\"div.job-info > h3 > a\") #岗位名称的HTML节点\n areaBs = bs.select(\".area\") #工作地区的HTML节点(一般是城市+区域)\n companyNameBs = bs.select(\".company-name > a\") #公司名称的HTML节点\n salaryBs = bs.select(\".text-warning\") #薪水的HTML节点\n educationBs = bs.select(\".edu\") #学历要求的HTML节点\n welfareBs = bs.select(\".temptation\") #工作福利的HTML节点(企业招聘才有,其他三种没有)\n workYearBs = bs.select(\".condition \") #工作年限要求的HTML节点\n createTimeBs = bs.select(\".time-info > time\") #招聘的发布时间HTML节点\n jobTypeBs = (bs.select('.icon')) #招聘类型的HTML节点(企业,猎头,优,直 招聘等等)\n welfareFlag = 0 #其他的属性都是必有,count=40 ,但福利字段可能为空,所以不一定是40,因此此处设置flag,便于之后for循环\n\n\n for i in range(0,count): #pageSize = 40,该for表示一个页码\n\n rawDetailHtml = positionNameBs[i].get('href')\n if (not 'https' in rawDetailHtml):\n detailUrl = ('https://www.liepin.com' + rawDetailHtml )\n else :\n detailUrl = rawDetailHtml\n\n # 此处sleep不用太长\n time.sleep(0.1)\n\n # 打开detailurl页面,一般不会出错\n # 对详细信息链接再进行一次爬虫 抓取岗位具体信息(包括职位要求,岗位职责等等)\n try:\n rr = requests.get(str(detailUrl), headers=my_headers)\n except Exception as err:\n file = r'liePinLog.txt'\n f = open(file, 'a+')\n f.write('A detailUrl error :')\n f.write(repr(err))\n f.write('at time:' + (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))\n f.write('\\n')\n f.close()\n print(err)\n continue\n bsDetail = BeautifulSoup(rr.text, 'lxml')\n rr.close()\n\n # 以下字段非直类型,(企、猎、优等三种类型): 不固定格式,一般包括:岗位描述岗位的要求任职要求等等\n if( not '/cjob' in detailUrl):\n detail = (\n (bsDetail.select(\"div.content-word \"))[0].text\n .replace('\t','').replace('
    ', '').replace(' ', '').replace('\\n', ''))\n # 以下字段是职位描述(直 cjob 类型): 不固定格式,一般包括:岗位描述岗位的要求任职要求等等\n else:\n detail = (\n (bsDetail.select(\"div.job-info-content \"))[0].text\n .replace('\t', '').replace('
    ','').replace(' ','').replace('\\n',''))\n\n getTime = (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))\n positionId = detailUrl[23:].replace('.shtml', '/').replace('\\n','').replace('\\r','')\n workYear = workYearBs[i].text.split('\\n')[4]\n area = areaBs[i].text\n companyName = companyNameBs[i].text\n salary = salaryBs[i].text\n education = educationBs[i].text\n createTime = createTimeBs[i].get('title')\n jobType = jobTypeBs[i].get('title')\n positionName = positionNameBs[i].text.replace('\t','').replace('\\n','').\\\n replace(' ','').replace('\\r\\n','').replace('\\r','')\n welfare = '' #猎聘网站四个类型招聘职位中,目前只发现企业这一类型招聘具有福利\n if ('企业') in jobTypeBs[i].get('title') :\n\n welfare = (welfareBs[welfareFlag].text.replace('\\n', ',')[1:-1])\n if(welfareFlag < len(welfareBs)-1):\n welfareFlag += 1\n\n # 利用list存储一条mysql记录,包括以下字段\n value = [positionName, cityName, companyName, salary, workYear, education,\n createTime, welfare, searchKey,jobType,area,getTime,detail,positionId]\n # print(value)\n with lock:\n DB.dbInsert(db,value) #插入数据库\n db.commit() #提交insert,之后关闭数据库,\n time.sleep(0.1)\n\n # time.sleep(1)\n\nif __name__ == '__main__':\n\n # 该range语句表示抓取的page范围, 猎聘网中每page有40条工作职位,其page的最大值为100\n # page0代表第一页,以此类推\n # c%23是c#的关键词,c%2B%2B是C++的关键词\n\n now = datetime.now() # 开始计时\n print(now)\n db = pymysql.connect(\"134.175.0.45\", \"lhy\", \"628628\", \"jobCrawer\")\n # for page in range(0,3):\n # crawerLiePin('上海', 'java',page,db)\n # db.close()\n\n thread = []\n for page in range(0, 20):\n t = threading.Thread(target = crawerLiePin,\n args = ('北京', 'java',page,db,))\n thread.append(t)\n\n\n for i in range(0, 10):\n thread[i].start()\n\n for i in range(0, 10):\n thread[i].join()\n\n db.close()\n end = datetime.now() #结束计时\n print(end)\n print(\"程序耗时: \" + str(end-now))","sub_path":"proxyIpCrawer.py","file_name":"proxyIpCrawer.py","file_ext":"py","file_size_in_byte":8107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"548522286","text":"import numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func, inspect, distinct\n\nfrom flask import Flask, jsonify\n\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///titanic.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\nsession = Session(engine)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n\n#################################################\n# Flask Routes\n#################################################\n\n@app.route(\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"Available Routes:
    \"\n f\"/api/v1.0/precipitation
    \"\n f\"/api/v1.0/stations
    \"\n f\"/api/v1.0/tobs
    \"\n f\"/api/v1.0/2016-01-01
    \"\n f\"/api/v1.0/2016-03-05/2016-03-20/summary
    \"\n f\"/api/v1.0/2016-03-05/2016-03-20\"\n )\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n session = Session(engine)\n max_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n max_date = max_date[0]\n\n min_date = dt.datetime.strptime(max_date, \"%Y-%m-%d\") - dt.timedelta(days=366) \n\n query_result = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= min_date).\\\n order_by(Measurement.date).\\\n all()\n\n precipitation_dict = dict(query_result)\n\n return jsonify(precipitation_dict)\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n session = Session(engine)\n stations_query_result = session.query(Measurement.station).group_by(Measurement.station).all()\n stations_list = list(np.ravel(stations_query_result)) # np.ravel flattens the nested array into a simple list\n return jsonify(stations_list)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n session = Session(engine)\n max_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n max_date = max_date[0]\n min_date = dt.datetime.strptime(max_date, \"%Y-%m-%d\") - dt.timedelta(days=366)\n \n tobs_query_result = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date >= min_date).all()\n return jsonify(tobs_query_result)\n\n@app.route(\"/api/v1.0/\")\ndef start(start):\n session = Session(engine)\n\n start_query_result = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).group_by(Measurement.date).all()\n start_list = list(start_query_result)\n return jsonify(start_list)\n\n@app.route(\"/api/v1.0///summary\")\ndef my_trip_sum(start_date, end_date):\n \"\"\"\n \n \"\"\"\n session = Session(engine)\n \n trip_query_result = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\n trip_list = list(trip_query_result)\n return jsonify(trip_list)\n\n@app.route(\"/api/v1.0//\")\ndef my_trip_daily(start_date, end_date):\n \"\"\"\n \n \"\"\"\n session = Session(engine)\n \n trip_query_result = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).group_by(Measurement.date).all()\n trip_list = list(trip_query_result)\n return jsonify(trip_list)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"90316694","text":"#\n#\n# UI for automated file transfer\n# see file: transferFilesEvery24hrs.py\n#\n#\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter.filedialog import askdirectory\nimport os, time\nimport datetime\nimport datetime as dt\nimport shutil\n\n\n\n\nclass GuiWindow(Frame):\n def __init__(self, master, *args):\n Frame.__init__(self, master, *args)\n\n self.master = master\n self.master.minsize(500, 300)\n self.master.maxsize(500, 300)\n self.master.title(\"File Transfer Interface\")\n self.master.config(bg = \"#FF9AA2\")\n\n \n self.btn_browse1 = tk.Button(self.master, width = 15, height = 2, text = \"Origin Folder: \", bg = \"#FFDAC1\", fg = \"black\", command = lambda: self.browse1())\n self.btn_browse1.grid(row = 0, column = 0, padx =(25, 0), pady =(10, 0), sticky = N+W)\n self.btn_browse2 = tk.Button(self.master, width = 15, height = 2, text = \"Destination Folder: \", bg = \"#FFDAC1\", fg = \"black\", command = lambda: self.browse2())\n self.btn_browse2.grid(row = 2, column = 0, padx =(25, 0), pady =(10, 0), sticky = N+W)\n \n \n self.btn_transfer = tk.Button(self.master, width = 10, height = 2, text = \"Transfer Files\", bg = \"#FFDAC1\", command = lambda: self.Transfer())\n self.btn_transfer.grid(row =3, column =1, padx=(30, 40), pady=(0, 0), sticky= NW)\n\n def browse1(self):\n self.master.browse1 = askdirectory()\n print(self.master.browse1)\n \n def browse2(self):\n self.master.browse2 = askdirectory()\n print(self.master.browse2)\n \n\n def Transfer(self):\n now = dt.datetime.now()\n last24 = now-dt.timedelta(hours = 24)\n strftime = \"%H:%M %m/%d/%Y\"\n for root, dirs, files in os.walk(self.master.browse1):\n for fname in files:\n path = os.path.join(root, fname)\n st = os.stat(path)\n mtime = dt.datetime.fromtimestamp(st.st_mtime)\n if mtime > last24:\n print(\"True: \", fname, \" at \", mtime.strftime(\"%H:%M %m/%d/%Y\"))\n shutil.move(path, self.master.browse2)\n else:\n print (False)\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n App = GuiWindow(root)\n root.mainloop()\n","sub_path":"File_transfer/findFolder_andCheck.py","file_name":"findFolder_andCheck.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"240785040","text":"import random\n\nnumber = random.randint(0, 100)\n\nprint(\"Guess a number between 0 and 100\")\n\nguess = -1 # this will make sure loop is always false, but lets us initialize\n\nwhile guess != number:\n guess = int(input(\"What is your guess? \"))\n\n if guess == number:\n print(\"You're right!\")\n elif guess < number:\n print(\"You're too low\")\n else:\n print(\"You're too high\")","sub_path":"cs1400-demo-code/Demo18-WhileLoop/guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"217881436","text":"\"\"\"\nMY FIRST FLASK APP\n\"\"\"\n\nfrom flask import Flask, jsonify, request, render_template\n\napp = Flask(__name__)\n\nstores = [\n {\n 'name': 'aldi',\n 'items': [\n {\n 'name': 'My Item',\n 'price': 15.99\n }\n ]\n }\n]\n\n\n@app.route('/')\ndef home():\n \"\"\"\n\n :return:\n \"\"\"\n return render_template('index.html')\n\n\n# POST --> used to receive data\n# GET --> used to send data back only\n\n# POST /store_data: {name: }\n@app.route('/store', methods=['POST'])\ndef create_store():\n \"\"\"\n Create store Endpoint.\n \"\"\"\n request_data = request.get_json()\n new_store = {\n 'name': request_data['name'],\n 'items': []\n }\n stores.append(new_store)\n return jsonify(new_store)\n\n\n# GET /store/\n@app.route('/store/') # 'http://127.0.0.1:5000/store/aldi'\ndef get_store(name):\n \"\"\"\n Get one store.\n :param name:\n \"\"\"\n for store in stores:\n if store.get(\"name\") == name:\n return jsonify(store)\n return jsonify({'message': \"The name is not available\"})\n\n\n# GET /store\n@app.route('/store')\ndef get_stores():\n \"\"\"\n Get stores.\n \"\"\"\n return jsonify({\"stores\": stores})\n\n\n# POST /store//item {name: ,price:}\n@app.route('/store//item', methods=['POST'])\ndef create_item_in_store(name):\n \"\"\"\n Create items in store.\n \"\"\"\n request_data = request.get_json()\n for store in stores:\n if store.get('name') == name:\n new_item = {\n 'name': request_data['name'],\n 'price': request_data['price']\n }\n store['items'].append(new_item)\n return jsonify(new_item)\n return ({'message': 'store not found'})\n\n\n# GET /store//item\n@app.route('/store//item')\ndef get_items_in_store(name):\n \"\"\"\n Get items in store.\n \"\"\"\n for store in stores:\n if store.get('name') == name:\n return jsonify({'items': store['items']})\n return jsonify({'message': \"Store not found\"})\n\n\napp.run(port=5000)\n","sub_path":"code/section_3/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"499457558","text":"########################################################################\n# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/CommentElement.py,v 1.9.2.1 2006/12/08 18:16:13 jkloth Exp $\n\"\"\"\nxsl:comment instruction implementation\n\nCopyright 2006 Fourthought, Inc. (USA).\nDetailed license and copyright information: http://4suite.org/COPYRIGHT\nProject home, documentation, distributions: http://4suite.org/\n\"\"\"\nfrom Ft.Xml.Xslt import XSL_NAMESPACE, XsltElement\nfrom Ft.Xml.Xslt import XsltRuntimeException, Error\nfrom Ft.Xml.Xslt import CategoryTypes, ContentInfo\n\nclass CommentElement(XsltElement):\n\n category = CategoryTypes.INSTRUCTION\n content = ContentInfo.Template\n legalAttrs = {}\n\n def instantiate(self, context, processor):\n context.processorNss = self.namespaces\n context.currentInstruction = self\n\n processor.pushResultString()\n had_nontext = 0\n try:\n for child in self.children:\n child.instantiate(context, processor)\n if processor.writers[-1].had_nontext:\n had_nontext = 1\n finally:\n if had_nontext:\n raise XsltRuntimeException(Error.NONTEXT_IN_COMMENT, self)\n content = processor.popResult()\n\n # Per the spec, comment data can't contain '--' or end with '-',\n # but we are allowed to add a space. (XSLT 1.0 sec. 7.4)\n content = content.replace(u'--', u'- -')\n if content[-1:] == u'-':\n content += u' '\n\n processor.writers[-1].comment(content)\n\n return\n","sub_path":"dependencies/src/4Suite-XML-1.0.2/Ft/Xml/Xslt/CommentElement.py","file_name":"CommentElement.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"415532639","text":"from collections import deque\nfrom django.shortcuts import render\n\nfrom cart.views import get_cart\nfrom category import utility\nfrom product.models import ProductAttribute\nfrom .models import ParentCategory, Category\n# Create your views here.\n\n\ndef get_products_by_category(request, category_name):\n products = get_products_util(category_name)\n attribs = product_attributes(products)\n return render(request, \"category.html\", {'cat_data': utility.get_categories(), 'products': products,\n 'cart': get_cart(request),\n 'attribs': attribs})\n\n\ndef product_attributes(products):\n attribs_list = {}\n for item in products:\n attribs_list[item] = ProductAttribute.objects.filter(product_id=item.id)\n return attribs_list\n\n\ndef get_products_util(category_name):\n category = get_category_by_name(category_name)\n\n products = []\n\n q = deque()\n try:\n category_set = category.category_set.all()\n for item in list(category_set):\n q.append(item)\n\n except:\n pass\n\n if not q:\n q.append(category)\n\n while q:\n front = q.popleft()\n print(front)\n if front.is_leaf:\n products.extend(item for item in list(front.product_set.all()))\n\n current_category_set = None\n\n try:\n current_category_set = ParentCategory.objects.get(name=front.name).category_set.all()\n except ParentCategory.DoesNotExist:\n pass\n\n if current_category_set is not None:\n for item in list(current_category_set):\n q.append(item)\n\n return products\n\n\ndef get_category_by_name(name):\n try:\n category = Category.objects.get(name=name)\n\n except Category.DoesNotExist:\n category = ParentCategory.objects.get(name=name)\n\n return category\n","sub_path":"category/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"320762368","text":"import glob\nimport json\nimport os\nimport unittest\nfrom io import open\n\nfrom parameterized import parameterized\n\nfrom pyknp_eventgraph import EventGraph\nfrom pyknp_eventgraph.utils import read_knp_result_file\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\nclass TestEventGraph(unittest.TestCase):\n \"\"\"Tests EventGraph.\"\"\"\n\n def setUp(self):\n \"\"\"Setup files used for test EventGraph.\"\"\"\n knp_file_paths = sorted(glob.glob(os.path.join(here, \"knp_files/*.knp\")))\n json_file_paths = sorted(glob.glob(os.path.join(here, \"json_files/*.json\")))\n for knp_file_path, json_file_path in zip(knp_file_paths, json_file_paths):\n knp_file_base, _ = os.path.splitext(os.path.basename(knp_file_path))\n json_file_base, _ = os.path.splitext(os.path.basename(json_file_path))\n assert knp_file_base == json_file_base, \"un-parallel test case: %s, %s\" % (knp_file_path, json_file_path)\n self.hypotheses = [self._make_json(path) for path in knp_file_paths]\n self.references = [self._load_json(path) for path in json_file_paths]\n\n @parameterized.expand((\"sid\", \"ssid\", \"surf\", \"mrphs\", \"reps\"))\n def test_sentence(self, param):\n for hyp, ref in zip(self.hypotheses, self.references):\n for hyp_sentence, ref_sentence in zip(hyp[\"sentences\"], ref[\"sentences\"]):\n assert hyp_sentence[param] == ref_sentence[param]\n\n @parameterized.expand(\n (\n \"event_id\",\n \"sid\",\n \"ssid\",\n \"surf\",\n \"surf_with_mark\",\n \"mrphs\",\n \"mrphs_with_mark\",\n \"normalized_mrphs\",\n \"normalized_mrphs_with_mark\",\n \"normalized_mrphs_without_exophora\",\n \"normalized_mrphs_with_mark_without_exophora\",\n \"reps\",\n \"reps_with_mark\",\n \"normalized_reps\",\n \"normalized_reps_with_mark\",\n \"content_rep_list\",\n )\n )\n def test_event_event(self, param):\n for hyp, ref in zip(self.hypotheses, self.references):\n for hyp_event, ref_event in zip(hyp[\"events\"], ref[\"events\"]):\n assert hyp_event[param] == ref_event[param]\n\n @parameterized.expand((\"event_id\", \"label\", \"surf\", \"reliable\", \"head_tid\"))\n def test_event_rel(self, param):\n for hyp, ref in zip(self.hypotheses, self.references):\n for hyp_event, ref_event in zip(hyp[\"events\"], ref[\"events\"]):\n for hyp_rel, ref_rel in zip(hyp_event[\"rel\"], ref_event[\"rel\"]):\n assert hyp_rel[param] == ref_rel[param]\n\n @parameterized.expand(\n (\n \"surf\",\n \"normalized_surf\",\n \"mrphs\",\n \"normalized_mrphs\",\n \"reps\",\n \"normalized_reps\",\n \"standard_reps\",\n \"type\",\n \"adnominal_event_ids\",\n \"sentential_complement_event_ids\",\n \"children\",\n )\n )\n def test_event_pas_predicate(self, param):\n for hyp, ref in zip(self.hypotheses, self.references):\n for hyp_event, ref_event in zip(hyp[\"events\"], ref[\"events\"]):\n assert hyp_event[\"pas\"][\"predicate\"][param] == ref_event[\"pas\"][\"predicate\"][param]\n\n @parameterized.expand(\n (\n \"surf\",\n \"normalized_surf\",\n \"mrphs\",\n \"normalized_mrphs\",\n \"reps\",\n \"normalized_reps\",\n \"head_reps\",\n \"eid\",\n \"flag\",\n \"sdist\",\n \"adnominal_event_ids\",\n \"sentential_complement_event_ids\",\n \"children\",\n )\n )\n def test_event_pas_argument(self, param):\n for hyp, ref in zip(self.hypotheses, self.references):\n for hyp_event, ref_event in zip(hyp[\"events\"], ref[\"events\"]):\n cases = list(set(list(hyp_event[\"pas\"][\"argument\"].keys()) + list(ref_event[\"pas\"][\"argument\"].keys())))\n for case in cases:\n num_args = len(ref_event[\"pas\"][\"argument\"][case])\n for arg_index in range(num_args):\n assert (\n hyp_event[\"pas\"][\"argument\"][case][arg_index][param]\n == ref_event[\"pas\"][\"argument\"][case][arg_index][param]\n )\n\n @parameterized.expand((\"modality\", \"tense\", \"negation\", \"state\", \"complement\"))\n def test_event_features(self, param):\n for hyp, ref in zip(self.hypotheses, self.references):\n for hyp_event, ref_event in zip(hyp[\"events\"], ref[\"events\"]):\n assert hyp_event[\"features\"][param] == ref_event[\"features\"][param]\n\n @staticmethod\n def _load_json(path):\n \"\"\"Loads a JSON file.\n\n Args:\n path (str): Path to a JSON file.\n\n Returns:\n dct (dict): Loaded EventGraph.\n \"\"\"\n with open(path, \"rt\", encoding=\"utf-8\", errors=\"ignore\") as f:\n return json.load(f)\n\n @staticmethod\n def _make_json(path):\n \"\"\"Loads a file in KNP-format and make a JSON file.\n\n Args:\n path (str): Path to a file storing KNP results.\n\n Returns:\n dct (dict): Constructed EventGraph.\n \"\"\"\n return EventGraph.build(read_knp_result_file(path)).to_dict()\n","sub_path":"tests/test_eventgraph_build.py","file_name":"test_eventgraph_build.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"331084558","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.contrib.hooks.aws_hook import AwsHook\n\nclass StageToRedshiftOperator(BaseOperator):\n \"\"\"\n The purpose of this class is to read data from a S3 location and populate the staging tables in Redshift\n \"\"\"\n template_fields=(\"s3_key\",)\n ui_color = '#358140'\n copy_sql = \"\"\"\n COPY {}\n FROM '{}'\n ACCESS_KEY_ID '{}'\n SECRET_ACCESS_KEY '{}'\n IGNOREHEADER 1 CSV;\n \"\"\"\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"\",\n aws_credentials_id=\"\",\n table=\"\",\n s3_bucket=\"\",\n s3_key=\"\",\n ignore_headers=1,\n createquery=\"\",\n *args, **kwargs):\n \"\"\"\n The __init__ function receives all the arguments from the caller and applies them to current execution cycle\n using the this operations\n \"\"\"\n super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\n self.table = table\n self.redshift_conn_id = redshift_conn_id\n self.s3_bucket = s3_bucket\n self.s3_key = s3_key\n self.ignore_headers = ignore_headers\n self.aws_credentials_id = aws_credentials_id\n self.createquery=createquery\n\n def execute(self, context):\n \"\"\"\n The execute function performs the following steps:\n - Checks if Staging table in Redshift is already created. If not, it creates one\n - Truncates the staging table so that its a fresh load\n - Reads the data from S3 and loads it into the table\n \"\"\"\n aws_hook = AwsHook(self.aws_credentials_id)\n credentials = aws_hook.get_credentials()\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n self.log.info(\"Creating table in Redshift if the table isn't already created\")\n redshift.run(\"{}\".format(self.createquery))\n self.log.info(\"Clearing data from destination Redshift table\")\n redshift.run(\"DELETE FROM {}\".format(self.table))\n \n self.log.info(\"Copying data from S3 to Redshift\")\n rendered_key = self.s3_key.format(**context)\n s3_path = \"s3://{}/{}\".format(self.s3_bucket, rendered_key)\n formatted_sql = StageToRedshiftOperator.copy_sql.format(\n self.table,\n s3_path,\n credentials.access_key,\n credentials.secret_key,\n )\n redshift.run(formatted_sql)","sub_path":"Capestone-Covid-19-Data-Analysis/plugins/operators/stage_redshift.py","file_name":"stage_redshift.py","file_ext":"py","file_size_in_byte":2655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"161816280","text":"import os, sys, imp, re\nfrom CRABClient.UserUtilities import config, getUsernameFromSiteDB\nconfig = config()\n\nCMSSW_VERSION=os.getenv(\"CMSSW_VERSION\")\nCMSSW_BASE=os.getenv(\"CMSSW_BASE\")\n\npathPrefix=CMSSW_BASE+'/src/ExoAnalysis/cmsWR/'\n\nconfig.General.requestName = 'analyze_SMPL_MMAASS_NU_MASSNU'\nconfig.General.workArea = 'crab_project_analyze_SMPL_MMAASS_NU_MASSNU'\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = True\n\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.pyCfgParams = ['output=analyzed_SMPL_MMAASS_NU_MASSNU_NUM.root']\nconfig.JobType.psetName = pathPrefix + 'test/checkWRDecay_crabSafe_cfg.py'\n\n#config.Data.inputDataset = 'INPTDATA'\n#config.Data.inputDBS = 'phys03'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 1\n\n#use userInputFiles and primaryDataset when running over a list of input files which have not been published, but are available through xrootd\nconfig.Data.userInputFiles = ['root://cmseos.fnal.gov//store/user/skalafut/WR/13TeV/WRSignal_March2016/WR_MWR_MMAASS_ToENu_MNu_MASSNU_GEN_13TeV_NUM.root']\nconfig.Data.outputPrimaryDataset = 'SMPL_MMAASS_NU_MASSNU_13TeV_25ns'\n#True allows the jobs to run anywhere, regardless of where the input data is located\nconfig.Data.ignoreLocality = False\n\n#totalUnits only needs to be specified for GEN-SIM jobs\n#config.Data.totalUnits = 200000\nconfig.Data.outLFNDirBase = '/store/user/%s/' % (getUsernameFromSiteDB())\nconfig.Data.publication = False\nconfig.Data.outputDatasetTag = 'analyzed_13TeV_SMPL_MMAASS_NU_MASSNU'\n\n#a list of the only sites at which these jobs can run\n#config.Site.whitelist = [\"T2_US*\"]\nconfig.Site.storageSite = 'T3_US_FNALLPC'\n","sub_path":"scripts/genAndFullOfflineAnalysisJobs/analyze_privateWrGen_crab.py","file_name":"analyze_privateWrGen_crab.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"400703076","text":"class RPS():\n\n def __init__(self):\n\n self.CPUScore = 0\n self.PlayerScore = 0\n self.names = {'r':'Rock','p':'Paper','s':'Scissors'}\n\n def play(self):\n\n d = {'r':0,'p':0,'s':0}\n \n \n while True:\n\n \n CPUTry = self.findmax(d)\n \n selection = input('\\nEnter R (Rock), P (Paper) or S (Scissors) - (or X to quit): ')\n\n if selection.lower() == 'r':\n\n d['r'] = d['r'] + 1\n self.DisplayResult(CPUTry,selection)\n\n\n \n elif selection.lower() == 'p':\n\n d['p'] = d['p'] + 1\n self.DisplayResult(CPUTry,selection)\n\n\n\n elif selection.lower() == 's':\n\n d['s'] = d['s'] + 1\n self.DisplayResult(CPUTry,selection)\n\n\n\n elif selection.lower() == 'x':\n\n print('\\nThanks for playing - Score: Computer %s Player %s' % (self.CPUScore, self.PlayerScore))\n\n break\n\n else:\n\n print('please enter r, p ,s or x')\n\n def findmax(self,totals):\n\n maxvalue = max(totals.values())\n\n for k in totals.keys():\n\n if totals[k] == maxvalue:\n\n\n if k == 'r':\n\n return 'p'\n\n if k == 'p':\n\n return 's'\n\n if k == 's':\n\n return 'r'\n\n def DisplayResult(self,CPU,selection):\n\n\n\n print('\\nPlayer: %s' % self.names[selection])\n print('Computer: %s\\n' % self.names[CPU])\n\n if selection == 'r':\n\n if CPU == 'r':\n\n result = 'Draw'\n print('Draw')\n self.UpdateScore(result)\n\n elif CPU == 'p':\n\n result = 'CPU'\n print('You Lose')\n self.UpdateScore(result)\n \n\n else:\n\n result = 'Player'\n print(\"You Win\")\n self.UpdateScore(result)\n\n if selection == 'p':\n\n if CPU == 'p':\n\n result = 'Draw'\n print('Draw')\n self.UpdateScore(result)\n\n elif CPU == 's':\n\n result = 'CPU'\n print('You Lose')\n self.UpdateScore(result)\n\n else:\n\n result = 'Player'\n print(\"You Win\")\n self.UpdateScore(result)\n\n if selection == 's':\n\n if CPU == 's':\n\n result = 'Draw'\n print('Draw')\n self.UpdateScore(result)\n\n elif CPU == 'r':\n\n result = 'CPU'\n print('You Lose')\n self.UpdateScore(result)\n\n else:\n\n result = 'Player'\n print(\"You Win\")\n self.UpdateScore(result)\n\n def UpdateScore(self,result):\n\n\n if result == 'CPU':\n\n self.CPUScore += 1\n print('\\nScore: Computer = ' + str(self.CPUScore) + ' Player ' + str(self.PlayerScore))\n\n elif result == 'Player':\n\n self.PlayerScore += 1\n print('\\nScore: Computer = ' + str(self.CPUScore) + ' Player ' + str(self.PlayerScore))\n\n \n\n \n \n\n","sub_path":"RPS.py","file_name":"RPS.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"217767402","text":"#!/usr/bin/env python\n\"\"\"\n.. module:: skill_tree\n\t:platform: Unix\n\t:synopsis: The skill tree display and selector.\n\n.. moduleauthor:: Eric Garside\n\"\"\"\nimport world\nimport ui\nimport colors\nimport game\nimport pygame\nfrom aether import aethers\nfrom utilities import once, imagePath, textrect\nfrom frame import Frame\n\nframe_name = \"skill_tree\"\nname = \"Spell skills\"\ntooltip = \"{0} (n)\".format(name)\ndescription = \"Learn new spells and improve known spells.\"\nframe = None\nimage = None\nheight = 500\nwidth = 800\nx = 80\ny = 40\nz = 1\nframe_padding = (20, 20)\nspell_size = (32, 32)\nspell_padding = (10, 10)\nspell_rank_size = (15, 15)\n_spell_ranks = {}\n_spell_pages = []\n\n@once\ndef init():\n global frame, image\n frame = Frame(frame_name, x, y, width, height, 1)\n frame.closeable = True\n frame.pages = True\n frame.background = pygame.image.load(imagePath(\"frame_bg.jpg\"))\n\n image = pygame.image.load(imagePath(\"skilltree.png\"))\n image = image.convert_alpha()\n ui.trigger(\"menu_bar\", \"addTrigger\", \"skill_tree\", image, toggle, tooltip,\n description)\n renderSkills()\n\ndef clickwrapper(spell):\n def decorated():\n pressed = pygame.mouse.get_pressed()\n if pressed[0]:\n spell.learn(game.player)\n elif pressed[2]:\n spell.unlearn(game.player)\n return decorated\n\ndef renderSkills():\n global _spells, _spell_ranks, _spell_pages\n layout_rect = pygame.Rect(frame_padding, spell_size)\n page_index = 0\n for spell_name in game.player.learned_spells:\n if len(_spell_pages) <= page_index:\n _spell_pages.append([])\n _spell_pages[page_index].append((spell_name, layout_rect.copy()))\n _spell_ranks[spell_name] = pygame.surface.Surface(spell_rank_size)\n page = frame.getPage(page_index)\n spell = game.getSpell(spell_name)\n subsurface = page.subsurface(layout_rect)\n subsurface.blit(spell.image, (0, 0))\n pygame.draw.rect(subsurface, colors.SILVER, \n pygame.Rect((0, 0), spell_size), 1)\n clickable_rect = pygame.Rect((layout_rect.x + x, layout_rect.y + y),\n spell_size)\n game.addClickableFramePage(clickable_rect, (frame, page_index), \n clickwrapper(spell), z, str(spell), \n spell.description)\n layout_rect.x += spell_size[0] + (frame_padding[0] * 2)\n if layout_rect.x > width:\n layout_rect.y += spell_size[1] + (frame_padding[0] * 2)\n layout_rect.x = frame_padding[0]\n if layout_rect.y > height:\n layout_rect.x = frame_padding[0]\n layout_rect.y = frame_padding[1]\n page_index += 1\n\ndef toggle():\n frame.toggle()\n \ndef renderRanks():\n active_page = frame.getPage(frame.active_page)\n for spell_details in _spell_pages[frame.active_page]:\n spell_name, spell_rect = spell_details\n spell_rank = _spell_ranks[spell_name]\n spell_rank_rect = spell_rank.get_rect()\n spell_rank.fill(colors.BLACK)\n rank = str(game.player.learned_spells[spell_name])\n text = textrect(rank, ui.typography[\"ui\"], spell_rank_rect.w, \n colors.WHITE, align=1)\n spell_rank.blit(text, (0, 0))\n pygame.draw.rect(spell_rank, colors.SILVER, spell_rank_rect, 1)\n active_page.blit(spell_rank, (spell_rect.x - 5, \n spell_rect.y + spell_rect.h - 5))\n label = \"Available skill points: {0}\".format(game.player.skill_points)\n page_rect = active_page.get_rect()\n avail_text = textrect(label, ui.typography[\"subtitle\"], page_rect.w - 5, \n colors.GOLD, colors.BLACK, align=2)\n text_rect = avail_text.get_rect()\n active_page.blit(avail_text, (0, page_rect.h - text_rect.h - 5))\n\ndef render(screen):\n points = game.player.skill_points\n if points > 0:\n ui.trigger(\"menu_bar\", \"addTriggerCount\", \"skill_tree\", points) \n frame.render(game.screen)\n renderRanks()\n","sub_path":"ui_modules/skill_tree.py","file_name":"skill_tree.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"317891882","text":"from math import pi\n\nimport compas_assembly\n\nfrom compas.utilities import i_to_red\n\nfrom compas.geometry import Rotation\n\nfrom compas_assembly.datastructures import Assembly\nfrom compas_assembly.datastructures import assembly_transform\nfrom compas_assembly.plotter import AssemblyPlotter\n\n\nassembly = Assembly.from_json(compas_assembly.get('wall_courses.json'))\n\n# visualise\n\nR = Rotation.from_axis_and_angle([1.0, 0, 0], -pi / 2)\nassembly_transform(assembly, R)\n\nplotter = AssemblyPlotter(assembly, figsize=(16, 6), tight=True)\nplotter.assembly_plotter.defaults['vertex.fontsize'] = 10\n\ncourses = assembly.get_vertices_attribute('course')\n\nc_min = min(courses)\nc_max = max(courses)\nc_spn = c_max - c_min\n\nfacecolor = {key: i_to_red((attr['course'] - c_min) / c_spn) for key, attr in assembly.vertices(True)}\nedgecolor = {key: '#000000' for key in assembly.vertices_where({'is_support': True})}\nedgewidth = {key: 3 for key in assembly.vertices_where({'is_support': True})}\n\nplotter.draw_blocks(\n facecolor=facecolor,\n edgecolor=edgecolor,\n edgewidth=edgewidth\n)\nplotter.show()\n","sub_path":"examples/wall_courses_plot.py","file_name":"wall_courses_plot.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"468837531","text":"import gmplot\nimport sqlite3\nfrom scipy.io import loadmat\nimport polyline\n\nx = loadmat('test_result.mat')\nlabels = x['label']\n\n# Connect to SQLite Database\nconn = sqlite3.connect('traffic.db')\nprint (\"Opened database successfully\");\ncount = 0\nplotCount = 0\n\ngmap = gmplot.GoogleMapPlotter(40.7538404,-74.007241, 10)\n\n# Select all speed records\ncursor = conn.execute(\"SELECT EncodedPolyLine from SENSOR_INFO\")\nrows = cursor.fetchall()\nfor row in rows:\n coord_str = row[0]\n print(count,': ',coord_str)\n try:\n coord_list = polyline.decode(coord_str)\n x_data = []\n y_data = []\n for coordinate in coord_list:\n x_data.append(coordinate[0])\n y_data.append(coordinate[1])\n print('----')\n # plot heatmap\n if len(x_data) == len(y_data):\n gmap.plot(x_data, y_data, 'cornflowerblue', edge_width=5)\n plotCount += 1\n except IndexError:\n print('Skip this record')\n count += 1\n\ngmap.draw(\"sensor.html\")\nprint('Result plotted: ', plotCount)","sub_path":"3-visualization/original-visualize.py","file_name":"original-visualize.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"229115871","text":"import h5py\nimport random\nimport numpy as np\nimport scipy.io.wavfile\nimport tensorflow as tf\n\nRAW_TRAIN_DATAFILE = \"/home/rolan/thesis/data/raw_train.hdf5\"\nTMPDIR = \"/home/rolan/Temp/\"\nEMOLIST = [\"Neutral state\", \"Frustration\", \"Sadness\", \"Happiness\", \"Excited\", \"Surprise\", \"Anger\", \"Other\", \"Fear\", \"Disgust\"]\nRATE = 16000\n\ndef write_wav_to_file(rowfeat, rowlabel,fnameprefix=None):\n emo_idx = np.argmax(rowlabel)\n emo = EMOLIST[emo_idx]\n if fnameprefix:\n fname = TMPDIR + fnameprefix +\"-\"+ emo + \".wav\"\n scipy.io.wavfile.write(fname, RATE, rowfeat)\n\ndef testdata(data_list, times, fnameprefix=None):\n for i in range(times):\n r = random.randint(0, len(data_list))\n row = all_data[r]\n rowfeat = row[0]\n rowlabel = row[1]\n write_wav_to_file(rowfeat, rowlabel, fnameprefix=fnameprefix)\n print(\"Done: \"+ fnameprefix)\n\n\nall_data = []\nwith h5py.File(RAW_TRAIN_DATAFILE, \"r\") as f:\n for i in range(7720):\n feat = f[\"r\"+str(i)].value\n label = f[\"l\"+str(i)].value\n all_data.append((feat, label))\n# all_data now contains tuples (feat, label)\n# We want to split to validation (500), and test(500), and train(6720)\n# at 500 datapoints for text, accuracy detection is up to .2%\nrandom.shuffle(all_data)\nval = all_data[0:500]\ntest = all_data[501:1001]\ntrain = all_data[1001:]\nprint(\"Lengths are as follows:val-{}; test-{}, train-{}\".format(len(val), len(test), len(train)))\ntestdata(val,2,\"val\")\ntestdata(test,2,\"test\")\ntestdata(train,2,\"train\")\n\n\nclass IemocapRawZPadded:\n def __init__(self, train_batch_size, test_size):\n max_length = 0\n for r in train:\n if len(r[0])> max_length:\n max_length = len(r[0])\n self.train_feat = []\n self.train_labels = []\n for r in train:\n self.train_feat.append(r[0])\n self.train_labels.append(r[1])\n self.test = test\n self.val = val\n self.trainset = tf.data.Dataset.from_tensor_slices((np.array(self.train_feat), np.array(self.train_labels)))\n\n def getTrainingDataset(self):\n return self.trainset\n\n def getTestDataset(self):\n return self.testset\n\n def get_num_classes(self):\n return len(EMOLIST)\n\n def get_minibatch_count(self):\n pass\n\n def get_minibatch(self,i):\n pass\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()","sub_path":"iemocap_raw.py","file_name":"iemocap_raw.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"209036266","text":"# MIT License\n#\n# Copyright (c) 2017, Stefan Webb. All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy \n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \n# copies of the Software, and to permit persons to whom the Software is \n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in \n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nimport tensorflow_models as tf_models\n\ndef create_placeholders(settings):\n\tx = tf.placeholder(tf.float32, shape=tf_models.batchshape(settings), name='samples')\n\tz = tf.placeholder(tf.float32, shape=tf_models.latentshape(settings), name='codes')\n\treturn x, z\n\ndef create_prior(settings):\n\tdist_prior = tf_models.standard_normal(tf_models.latentshape(settings))\n\treturn tf.identity(dist_prior.sample(), name='p_z/sample')\n\ndef create_encoder(settings, reuse=True):\n\tencoder_network = settings['architecture']['encoder']['fn']\n\n\tx_placeholder = tf_models.samples_placeholder()\n\tassert(not x_placeholder is None)\n\n\twith tf.variable_scope('encoder', reuse=reuse):\n\t\tmean_z, diag_stdev_z = encoder_network(settings, x_placeholder, is_training=False)\n\t\tdist_z_given_x = tf.contrib.distributions.MultivariateNormalDiag(mean_z, diag_stdev_z)\n\t\tencoder = tf.identity(dist_z_given_x.sample(name='sample'), name='q_z_given_x/sample')\n\treturn encoder\n\ndef create_decoder(settings, reuse=True):\n\tdecoder_network = settings['architecture']['decoder']['fn']\n\n\tz_placeholder = tf_models.codes_placeholder()\n\tassert(not z_placeholder is None)\n\n\twith tf.variable_scope('decoder', reuse=reuse):\n\t\tlogits_x = decoder_network(settings, z_placeholder, is_training=False)\n\t\t#dist_x_given_z = tf.contrib.distributions.Bernoulli(logits=logits_x, dtype=tf.float32)\n\t\t#decoder = tf.identity(dist_x_given_z.sample(), name='p_x_given_z/sample')\n\t#return decoder\n\treturn tf.identity(tf.nn.sigmoid(logits_x), name='p_x_given_z/sample')\n\ndef create_probs(settings, inputs, is_training, reuse=False):\n\tencoder_network = settings['architecture']['encoder']['fn']\n\tdecoder_network = settings['architecture']['decoder']['fn']\n\t\n\tdist_prior = tf_models.standard_normal(tf_models.latentshape(settings))\n\tdist_prior_iw = tf.contrib.distributions.Normal(loc=0., scale=1.)\n\n\t# Use recognition network to determine mean and (log) variance of Gaussian distribution in latent space\n\twith tf.variable_scope('encoder', reuse=reuse):\n\t\tmean_z, diag_stdev_z = encoder_network(settings, inputs, is_training=is_training)\n\t#dist_z_given_x = tf.contrib.distributions.MultivariateNormalDiag(mean_z, diag_stdev_z)\n\tdist_z_given_x = tf.contrib.distributions.Normal(loc=mean_z, scale=diag_stdev_z)\n\n\t# Draw one sample z from Gaussian distribution\n\teps = tf.random_normal(tf_models.latentshape(settings), 0, 1, dtype=tf.float32)\n\tz_sample = tf.add(mean_z, tf.multiply(diag_stdev_z, eps))\n\n\teps = tf.random_normal((settings['iw_size'], settings['batch_size'], settings['latent_dimension']), 0, 1, dtype=tf.float32)\n\tz_sample_iw = tf.add(tf.reshape(mean_z, (1, settings['batch_size'], settings['latent_dimension'])), tf.multiply(tf.reshape(diag_stdev_z, (1, settings['batch_size'], settings['latent_dimension'])), eps))\n\t#z_sample_iw = dist_z_given_x.sample([iw_size])\n\t#print('z_sample_iw.shape', z_sample_iw.shape)\n\t#raise Exception()\n\n\t# Use generator to determine mean of Bernoulli distribution of reconstructed input\n\twith tf.variable_scope('decoder', reuse=reuse):\n\t\tlogits_x = decoder_network(settings, z_sample, is_training=is_training)\n\t\ttf.get_variable_scope().reuse_variables()\n\t\tlogits_x_iw = decoder_network(settings, tf.reshape(z_sample_iw, (-1, settings['latent_dimension'])), is_training=is_training)\n\n\tdist_x_given_z = tf.contrib.distributions.Bernoulli(logits=tf_models.flatten(logits_x), dtype=tf.float32)\n\tdist_x_given_z_iw = tf.contrib.distributions.Bernoulli(logits=tf.reshape(tf_models.flatten(logits_x_iw), (settings['iw_size'], settings['batch_size'], -1)), dtype=tf.float32)\n\t\n\t# NOTE: x | z is defined as over each pixel separate, where prior on z is a multivariate\n\t# Hence the need to do the tf.reduce_sum op on the former to get down to a single number for each sample\n\tlg_p_x_given_z = tf.reduce_sum(dist_x_given_z.log_prob(tf_models.flatten(inputs)), 1, name='p_x_given_z/log_prob')\n\tlg_p_z = tf.identity(dist_prior.log_prob(z_sample), name='p_z/log_prob')\n\tlg_q_z_given_x = tf.reduce_sum(dist_z_given_x.log_prob(z_sample), 1, name='q_z_given_x/log_prob')\n\n\tinputs_iw = tf.tile(tf.expand_dims(tf_models.flatten(inputs), axis=0), multiples=[settings['iw_size'],1,1])\n\n\tlg_p_x_given_z_iw = tf.reduce_sum(dist_x_given_z_iw.log_prob(inputs_iw), 2, name='p_x_given_z_iw/log_prob')\n\tlg_p_z_iw = tf.reduce_sum(dist_prior_iw.log_prob(z_sample_iw), 2, name='p_z_iw/log_prob')\n\tlg_q_z_given_x_iw = tf.reduce_sum(dist_z_given_x.log_prob(z_sample_iw), 2, name='q_z_given_x_iw/log_prob')\n\n\treturn lg_p_x_given_z, lg_p_z, lg_q_z_given_x, lg_p_x_given_z_iw, lg_p_z_iw, lg_q_z_given_x_iw\n\ndef lg_likelihood(x, z, settings, reuse=True, is_training=False):\n\tdecoder_network = settings['architecture']['decoder']['fn']\n\n\twith tf.variable_scope('model'):\n\t\twith tf.variable_scope('decoder', reuse=reuse):\n\t\t\tlogits_x = decoder_network(settings, z, is_training=is_training)\n\tdist_x_given_z = tf.contrib.distributions.Bernoulli(logits=tf_models.flatten(logits_x), dtype=tf.float32)\n\treturn tf.reduce_sum(dist_x_given_z.log_prob(tf_models.flatten(x)), 1)\n\ndef lg_prior(z, settings, reuse=True, is_training=False):\n\tdist_prior = tf_models.standard_normal(z.shape)\n\treturn dist_prior.log_prob(z)\n\ndef sample_prior(settings):\n\tdist_prior = tf_models.standard_normal(tf_models.latentshape(settings))\n\treturn dist_prior.sample()\n\n","sub_path":"tensorflow_models/models/vae_iw.py","file_name":"vae_iw.py","file_ext":"py","file_size_in_byte":6565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"115092540","text":"#!/home/hadoop/anaconda3/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n 从RabbitMQ中接受数据\n 根据数据需要执行的操作:\n 操作分为三种\n 图片识别:python程序\n 查看中间数据集信息:python读取hdfs\n 机器学习:使用pyspark\n\n\"\"\"\n\nfrom lib.utils import parser,write2mq\nimport json\nimport traceback as tb\nimport os\nimport pika\nimport Img,DatasetInfo\nimport subprocess as sp\nimport time\n\n# 收到消息后的回调函数\n\n# TODO 更改消费模式,消费任务后返回ack,确保消息不丢失\ndef callback(ch, method, properties, body):\n # 解析收到的消息 body为bytes\n data = json.loads(body)\n #存储 实验id : 进程对象\n childs={}\n #图片识别\n if data['process'][0]['action']==\"img_recognition\":\n s=f\"python3 Img.py {body}\"\n # sp.Popen(s,shell=True)\n Img.img_recognition(data)\n # elif data['process'][0]['action']=='exit':\n #判断子进程死了之后 主进程怎么获取状态\n\n #查看数据集信息\n elif len(data['process']) ==1:\n s = f\"python3 DatasetInfo.py {body}\"\n # sp.Popen(s,shell=True)\n DatasetInfo.Get_dataset_info(data)\n #执行DAG\n else:\n try:\n res = parser(data)\n # 获取user id,session id,exp id 文件路径\n session_id = res[\"headers\"][\"sessionId\"]\n experiment_id = res[\"headers\"][\"expId\"]\n user_id = res[\"headers\"][\"userId\"]\n if user_id == \"\":\n user_id=f\"Tourist_{experiment_id}\"\n res[\"headers\"][\"userId\"] = user_id\n dir_path = os.path.join(\"files/\", user_id, experiment_id)\n\n # 如果work文件夹不存在,创建work文件夹\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n # 写入文件参数\n with open(os.path.join(dir_path, session_id + \".json\"), \"w\") as f:\n f.write(json.dumps(res))\n\n spark_submit: str = f\"spark2-submit --num-executors 4 \" \\\n \"--executor-cores 4 \" \\\n \"--executor-memory 5G \" \\\n \"--total-executor-cores 16 \" \\\n f\"--files files/{user_id}/{experiment_id}/{session_id}.json#data.json \" \\\n \"--master yarn --deploy-mode cluster \" \\\n \"--py-files lib.zip CoreApp.py\"\n\n # TODO 异步提交\n # child=sp.Popen(spark_submit,shell=True)\n # childs[experiment_id] = child\n except Exception:\n tb.print_exc()\n\n\n\n\n\n\n\n#rabbitmq的配置\nuser = \"cloudai\"\npasswd = \"cloudai\"\nhost=\"139.199.161.144\"\nport=5672\nvirtual_host=\"cloudai\"\nexchange=\"pub_data_clean\"\nqueue_name=\"pub_data_clean\"\nroute_key=\"data_clean\"\n# exchange=\"data_process\"\n# queue_name=\"data_process\"\n# route_key=\"data_process\"\ndef consume():\n # 配置消费者\n # TODO 更改配置方式,写入配置文件\n credential = pika.PlainCredentials(user, passwd)\n # 创建RabbitMQ连接\n connection = pika.BlockingConnection(pika.ConnectionParameters(host=host,\n credentials=credential,\n virtual_host=virtual_host,\n port=port\n ))\n # 初始化channel\n channel = connection.channel()\n channel.exchange_declare(exchange=exchange,\n exchange_type=\"topic\",\n durable=True)\n channel.queue_declare(queue=queue_name)\n # 绑定\n channel.queue_bind(exchange=exchange,\n queue=queue_name,\n routing_key=route_key)\n\n channel.basic_consume(consumer_callback=callback,\n queue=queue_name,\n no_ack=True)\n channel.start_consuming()\n\n\nif __name__ == '__main__':\n dataTest = {\n \"data\": {},\n \"headers\": {\n \"code\": 0,\n \"identifier\": \"img_recognition\",\n \"msg\": \"\",\n \"sessionId\": \"ED14A9BB67156327716F44C6409B2540\",\n \"userId\": \"\"\n },\n \"process\": [\n {\n \"action\": \"img_recognition\",\n \"inputDatasets\": [],\n \"outputDatasets\": [],\n \"url\": \"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538054725399&di=454f9c38fa3655821603641d3ebaae9d&imgtype=0&src=http%3A%2F%2Fimage.woshipm.com%2Fwp-files%2F2015%2F07%2Fyestone_HD_1112835095.jpg\"\n }\n ]\n }\n consume()\n # img_recognition(dataTest)\n","sub_path":"DPT/Consumer.py","file_name":"Consumer.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"84665528","text":"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"General module for Roboto-specific data and methods.\"\"\"\n\nimport os\nfrom os import path\nimport re\n\n\nWEIGHTS = {\n 'Thin': 250,\n 'Light': 300,\n 'Regular': 400,\n 'Medium': 500,\n 'Bold': 700,\n 'Black': 900,\n}\n\n_ALL_WEIGHTS_RE = re.compile(\n '(' + '|'.join(WEIGHTS.keys()) + ')'\n)\n\n\ndef extract_weight_name(font_name):\n \"\"\"Extracts the weight part of the name from a font name.\"\"\"\n match = re.search(_ALL_WEIGHTS_RE, font_name)\n if match is None:\n assert re.match('^Roboto(Draft)?( Condensed)? Italic$', font_name)\n return 'Regular'\n else:\n return match.group(1)\n\n\ndef get_build_number():\n \"\"\"Returns the build number as a five-digit string.\"\"\"\n build_number_txt = path.join(\n path.dirname(__file__), os.pardir, 'res', 'buildnumber.txt')\n build_number = open(build_number_txt).read().strip()\n assert re.match('[0-9]{5}', build_number)\n return build_number\n\n","sub_path":"scripts/roboto_data.py","file_name":"roboto_data.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"193460612","text":"#!/usr/bin/env python3\n\n__author__ = 'Alprobit'\n\n\nfrom stitcher import Stitcher\nfrom cv2 import imwrite\nimport argparse\nfrom glob import iglob\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Stitch images which are results of image partitioning by grid.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('image', type=str, nargs='+',\n help='images\\' paths (possibly with wildcards)')\n parser.add_argument('-o', '--outfile', type=str, default='out.png',\n help='output path')\n parser.add_argument('-b', '--background-var', type=float, default=0.005,\n help='background variance: upper threshold (close to 0 and less than 1)'\n 'for precheck image sides for belonging to background of result image')\n parser.add_argument('-n', '--noise-var', type=float, default=0.025,\n help='noise variance: upper threshold (between 0 and 1) so that if the difference of two colors (or channel values)'\n 'is less than noise_variance then these colors are interpreted as the same')\n\n args = parser.parse_args()\n\n s = Stitcher(set(path for name in args.image for path in iglob(name)))\n if not imwrite(args.outfile, s.stitch(args.background_var, args.noise_var)):\n raise IsADirectoryError('Cannot write result image to the destination file. Probably directory does not exist')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"259949498","text":"import torch.utils.data as data\nfrom PIL import Image\nimport os\nimport os.path\nimport torch\nimport numpy as np\nimport torchvision.transforms as transforms\nimport random\nfrom cv2 import cv2\nimport _pickle as cPickle\nimport open3d as o3d\nimport numpy.ma as ma\nfrom pytorch3d.ops import sample_points_from_meshes\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.io import load_obj\nimport heapq\n\n\nclass Dataset(data.Dataset):\n def __init__(self, mode, root, add_noise, num_pt, num_cates, count, cate_id):\n self.root = root\n self.add_noise = add_noise\n self.mode = mode\n self.num_pt = num_pt\n self.mesh_pt = 2000\n self.num_cates = num_cates\n self.back_root = '{0}/train2017/'.format(self.root)\n\n self.cate_id = cate_id\n\n self.obj_list = {}\n self.obj_name_list = {}\n\n if self.mode == 'train':\n for tmp_cate_id in range(1, self.num_cates + 1):\n self.obj_name_list[tmp_cate_id] = os.listdir('{0}/data_list/train/{1}/'.format(self.root, tmp_cate_id))\n self.obj_list[tmp_cate_id] = {}\n\n for item in self.obj_name_list[tmp_cate_id]:\n print(tmp_cate_id, item)\n self.obj_list[tmp_cate_id][item] = []\n\n input_file = open('{0}/data_list/train/{1}/{2}/list.txt'.format(self.root, tmp_cate_id, item), 'r')\n while 1:\n input_line = input_file.readline()\n if not input_line:\n break\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n self.obj_list[tmp_cate_id][item].append('{0}/data_ls/{1}'.format(self.root, input_line))\n input_file.close()\n\n self.real_obj_list = {}\n self.real_obj_name_list = {}\n\n for tmp_cate_id in range(1, self.num_cates + 1):\n self.real_obj_name_list[tmp_cate_id] = os.listdir(\n '{0}/data_list/real_{1}/{2}/'.format(self.root, self.mode, tmp_cate_id))\n self.real_obj_list[tmp_cate_id] = {}\n\n for item in self.real_obj_name_list[tmp_cate_id]:\n print(tmp_cate_id, item)\n self.real_obj_list[tmp_cate_id][item] = []\n\n input_file = open(\n '{0}/data_list/real_{1}/{2}/{3}/list.txt'.format(self.root, self.mode, tmp_cate_id, item), 'r')\n\n while 1:\n input_line = input_file.readline()\n if not input_line:\n break\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n self.real_obj_list[tmp_cate_id][item].append('{0}/data_ls/{1}'.format(self.root, input_line))\n input_file.close()\n\n # self.back_list = []\n #\n # input_file = open('dataset/train2017.txt', 'r')\n # while 1:\n # input_line = input_file.readline()\n # if not input_line:\n # break\n # if input_line[-1:] == '\\n':\n # input_line = input_line[:-1]\n # self.back_list.append(self.back_root + input_line)\n # input_file.close()\n\n self.mesh = []\n input_file = open('/home/lthpc/yifeis/pose/pose_est_tless_3d/datasets/nocs/sphere.xyz', 'r')\n while 1:\n input_line = input_file.readline()\n if not input_line:\n break\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n input_line = input_line.split(' ')\n self.mesh.append([float(input_line[0]), float(input_line[1]), float(input_line[2])])\n input_file.close()\n self.mesh = np.array(self.mesh) * 0.6\n\n self.cam_cx_1 = 322.52500\n self.cam_cy_1 = 244.11084\n self.cam_fx_1 = 591.01250\n self.cam_fy_1 = 590.16775\n\n self.cam_cx_2 = 319.5\n self.cam_cy_2 = 239.5\n self.cam_fx_2 = 577.5\n self.cam_fy_2 = 577.5\n\n self.xmap = np.array([[j for i in range(640)] for j in range(480)])\n self.ymap = np.array([[i for i in range(640)] for j in range(480)])\n\n self.norm = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n\n self.trancolor = transforms.ColorJitter(0.8, 0.5, 0.5, 0.05)\n self.length = count\n\n def divide_scale(self, scale, pts):\n pts[:, 0] = pts[:, 0] / scale[0]\n pts[:, 1] = pts[:, 1] / scale[1]\n pts[:, 2] = pts[:, 2] / scale[2]\n\n return pts\n\n def get_anchor_box(self, ori_bbox):\n bbox = ori_bbox\n limit = np.array(search_fit(bbox))\n num_per_axis = 5\n gap_max = num_per_axis - 1\n\n small_range = [1, 3]\n\n gap_x = (limit[1] - limit[0]) / float(gap_max)\n gap_y = (limit[3] - limit[2]) / float(gap_max)\n gap_z = (limit[5] - limit[4]) / float(gap_max)\n\n ans = []\n scale = [max(limit[1], -limit[0]), max(limit[3], -limit[2]), max(limit[5], -limit[4])]\n\n for i in range(0, num_per_axis):\n for j in range(0, num_per_axis):\n for k in range(0, num_per_axis):\n ans.append([limit[0] + i * gap_x, limit[2] + j * gap_y, limit[4] + k * gap_z])\n\n ans = np.array(ans)\n scale = np.array(scale)\n\n ans = self.divide_scale(scale, ans)\n\n return ans, scale\n\n def change_to_scale(self, scale, cloud_fr, cloud_to=None):\n cloud_fr = self.divide_scale(scale, cloud_fr)\n if cloud_to:\n cloud_to = self.divide_scale(scale, cloud_to)\n\n return cloud_fr, cloud_to\n\n def enlarge_bbox(self, target):\n\n limit = np.array(search_fit(target))\n longest = max(limit[1] - limit[0], limit[3] - limit[2], limit[5] - limit[4])\n longest = longest * 1.3\n\n scale1 = longest / (limit[1] - limit[0])\n scale2 = longest / (limit[3] - limit[2])\n scale3 = longest / (limit[5] - limit[4])\n\n target[:, 0] *= scale1\n target[:, 1] *= scale2\n target[:, 2] *= scale3\n\n return target\n\n def load_depth(self, depth_path):\n depth = cv2.imread(depth_path, -1)\n\n if len(depth.shape) == 3:\n depth16 = np.uint16(depth[:, :, 1] * 256) + np.uint16(depth[:, :, 2])\n depth16 = depth16.astype(np.uint16)\n elif len(depth.shape) == 2 and depth.dtype == 'uint16':\n depth16 = depth\n else:\n assert False, '[ Error ]: Unsupported depth type.'\n\n return depth16\n\n def get_pose(self, choose_frame, choose_obj):\n has_pose = []\n pose = {}\n if self.mode == \"train\":\n input_file = open('{0}_pose.txt'.format(choose_frame.replace(\"data_ls/\", \"data_pose/\")), 'r')\n while 1:\n input_line = input_file.readline()\n if not input_line:\n break\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n input_line = input_line.split(' ')\n if len(input_line) == 1:\n idx = int(input_line[0])\n has_pose.append(idx)\n pose[idx] = []\n for i in range(4):\n input_line = input_file.readline()\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n input_line = input_line.split(' ')\n pose[idx].append(\n [float(input_line[0]), float(input_line[1]), float(input_line[2]), float(input_line[3])])\n input_file.close()\n if self.mode == \"val\":\n with open('{0}/data_ls/gts/real_test/results_real_test_{1}_{2}.pkl'.format(self.root,\n choose_frame.split(\"/\")[-2],\n choose_frame.split(\"/\")[-1]),\n 'rb') as f:\n nocs_data = cPickle.load(f)\n for idx in range(nocs_data['gt_RTs'].shape[0]):\n idx = idx + 1\n pose[idx] = nocs_data['gt_RTs'][idx - 1]\n pose[idx][:3, :3] = pose[idx][:3, :3] / np.cbrt(np.linalg.det(pose[idx][:3, :3]))\n z_180_RT = np.zeros((4, 4), dtype=np.float32)\n z_180_RT[:3, :3] = np.diag([-1, -1, 1])\n z_180_RT[3, 3] = 1\n pose[idx] = z_180_RT @ pose[idx]\n pose[idx][:3, 3] = pose[idx][:3, 3] * 1000\n\n input_file = open('{0}_meta.txt'.format(choose_frame), 'r')\n while 1:\n input_line = input_file.readline()\n if not input_line:\n break\n if input_line[-1:] == '\\n':\n input_line = input_line[:-1]\n input_line = input_line.split(' ')\n if input_line[-1] == choose_obj:\n ans = pose[int(input_line[0])]\n ans_idx = int(input_line[0])\n break\n input_file.close()\n\n ans = np.array(ans)\n ans_r = ans[:3, :3]\n ans_t = ans[:3, 3].flatten()\n\n return ans_r, ans_t, ans_idx\n\n def backproject(self, depth, intrinsics, instance_mask):\n\n intrinsics_inv = np.linalg.inv(intrinsics)\n image_shape = depth.shape\n width = image_shape[1]\n height = image_shape[0]\n\n x = np.arange(width)\n y = np.arange(height)\n\n non_zero_mask = (depth > 0)\n final_instance_mask = np.logical_and(instance_mask, non_zero_mask)\n\n idxs = np.where(final_instance_mask)\n grid = np.array([idxs[1], idxs[0]])\n\n length = grid.shape[1]\n ones = np.ones([1, length])\n uv_grid = np.concatenate((grid, ones), axis=0) # [3, num_pixel]\n\n xyz = intrinsics_inv @ uv_grid # [3, num_pixel]\n xyz = np.transpose(xyz) # [num_pixel, 3]\n\n z = depth[idxs[0], idxs[1]]\n\n pts = xyz * z[:, np.newaxis] / xyz[:, -1:]\n pts[:, 0] = -pts[:, 0]\n pts[:, 1] = -pts[:, 1]\n\n return pts, idxs\n\n def get_frame(self, choose_frame, choose_obj, syn_or_real):\n syn_or_real = False\n\n img = np.array(Image.open('{0}_color.png'.format(choose_frame)))\n depth = np.array(self.load_depth('{0}_depth.png'.format(choose_frame)))\n\n # get RT from the pose.txt\n target_r, target_t, idx = self.get_pose(choose_frame, choose_obj)\n\n # get cloud from rgbd input\n if syn_or_real:\n cam_cx = self.cam_cx_2\n cam_cy = self.cam_cy_2\n cam_fx = self.cam_fx_2\n cam_fy = self.cam_fy_2\n else:\n cam_cx = self.cam_cx_1\n cam_cy = self.cam_cy_1\n cam_fx = self.cam_fx_1\n cam_fy = self.cam_fy_1\n cam_scale = 1.0\n intrinsics = np.array([[cam_fx, 0, cam_cx],\n [0., cam_fy, cam_cy],\n [0., 0., 1.]])\n\n # import scipy.misc\n mask_im = cv2.imread('{0}_mask.png'.format(choose_frame))[:, :, 2]\n mask_im = np.array(mask_im)\n patch_file = '{0}{1}{2}_{3}_segmentation.png'.format(choose_frame[:-4], 'process/', choose_frame[-4:], str(idx))\n patch_label = cv2.imread(patch_file)[:, :, 2]\n choose_file = '{0}{1}{2}_{3}_choose.list'.format(choose_frame[:-4], 'process/', choose_frame[-4:], str(idx))\n choose_ls = []\n stable_ls = []\n try:\n with open(choose_file) as f:\n data = f.readlines()\n if len(data) > 1:\n for ids in data:\n choose_id = ids[:-1].split(',')[:-1]\n stable = float(ids[:-1].split(',')[-1])\n choose_ls.append([int(x) for x in choose_id])\n stable_ls.append(stable)\n else:\n if data[0] != '0':\n choose_id = data[0].split(',')[:-1]\n stable = float(data[0].split(',')[-1])\n choose_ls.append([int(x) for x in choose_id])\n stable_ls.append(stable)\n else:\n stable_ls.append(0)\n except:\n print('-choose list file not exist')\n stable_ls.append(0)\n choose_ls = []\n data = ['0']\n\n tmp_mask = (mask_im == idx)\n # patch_mask = ma.getmaskarray(ma.masked_not_equal(depth, 0))\n mask_depth = ma.getmaskarray(ma.masked_not_equal(depth, 0))\n mask_seg = ma.getmaskarray(ma.masked_not_equal(patch_label, 0))\n mask_patch = mask_seg * mask_depth\n mask_label = tmp_mask * mask_depth\n mask = mask_label * mask_patch\n\n pts_ori, idxs = self.backproject(depth, intrinsics, mask_label)\n\n translation = target_t/1000\n rotation = target_r\n pts_ = pts_ori - target_t\n pts = pts_ @ rotation\n pts = pts / 1000\n # target_t = target_t / 1000\n\n choose = mask_label.flatten().nonzero()[0]\n if len(choose) > self.num_pt:\n c_mask = np.zeros(len(choose), dtype=int)\n c_mask[:self.num_pt] = 1\n np.random.shuffle(c_mask)\n choose = choose[c_mask.nonzero()]\n else:\n if len(choose) == 0:\n print(0)\n choose = np.pad(choose, (0, self.num_pt - len(choose)), 'wrap')\n\n\n patch_masked = patch_label.flatten()[choose][:, np.newaxis].astype(np.float32)\n depth_masked = depth.flatten()[choose][:, np.newaxis].astype(np.float32)\n xmap_masked = self.xmap.flatten()[choose][:, np.newaxis].astype(np.float32)\n ymap_masked = self.ymap.flatten()[choose][:, np.newaxis].astype(np.float32)\n\n pt2 = depth_masked / 1000\n pt0 = (ymap_masked - cam_cx) * pt2 / cam_fx\n pt1 = (xmap_masked - cam_cy) * pt2 / cam_fy\n cloud = np.concatenate((-pt0, -pt1, pt2), axis=1)\n\n # pts = pts_clear[choose]\n # cloud = pts_ori_clear[choose]\n # patch_masked = patch_label[choose]\n # pcd = o3d.geometry.PointCloud()\n # pcd.points = o3d.utility.Vector3dVector(pts)\n # pcd_clear, _ = pcd.remove_radius_outlier(nb_points=500, radius=0.1)\n # pts_clear = np.asarray(pcd_clear.points)\n #\n # pcd = o3d.geometry.PointCloud()\n # pcd.points = o3d.utility.Vector3dVector(pts_ori / 1000)\n # pcd_clear, _ = pcd.remove_radius_outlier(nb_points=500, radius=0.1)\n # pts_ori_clear = np.asarray(pcd_clear.points)\n\n np.savetxt('/home/lthpc/yifeis/pose/pose_est_tless_3d/datasets/nocs/test/pts1.txt', pts)\n np.savetxt('/home/lthpc/yifeis/pose/pose_est_tless_3d/datasets/nocs/test/pts_ori1.txt', pts_ori/1000)\n\n # get the mesh of normalized model\n mesh_path = '{0}/obj_models/real_{1}/{2}.obj'.format(self.root, self.mode, choose_obj)\n # mesh = o3d.io.read_triangle_mesh(mesh_path)\n # mesh = np.asarray(mesh.vertices)\n verts, faces, _ = load_obj(mesh_path)\n model_mesh = Meshes(verts=[verts], faces=[faces.verts_idx])\n mesh = sample_points_from_meshes(model_mesh, self.mesh_pt)\n target = np.dot(mesh[0], target_r.T) + translation\n np.savetxt('/home/lthpc/yifeis/pose/pose_est_tless_3d/datasets/nocs/test/mesh1.txt', mesh[0])\n np.savetxt('/home/lthpc/yifeis/pose/pose_est_tless_3d/datasets/nocs/test/mesh_trans1.txt', target)\n\n # get the bbox of model\n # input_file = '{0}/obj_models/real_{1}/{2}.txt'.format(self.root, self.mode, choose_obj)\n # scale_ori = np.loadtxt(input_file, dtype=np.float)\n # scale_factor = scale_ori / np.linalg.norm(scale_ori)\n # scale = scale_ori\n # scale = scale_factor / 2\n\n patches = patch_masked.astype(int)\n num_patch = np.max(patches)\n num_list = []\n patch_list = patches.reshape(-1).tolist()\n for n in range(1, num_patch + 1): # ordered num of point in each tless(from patch_1 to patch_n)\n num = str(patch_list).count(str(n))\n num_list.append(num)\n\n num_list_new = []\n patch_id_list_all = []\n for m in num_list: # select patchs that num of points > 100\n if m > 100:\n num_list_new.append(m)\n patch_id_list_all.append(num_list.index(m) + 1)\n\n choose_patch = []\n all_list = [i for i in range(0, self.num_pt)]\n if data[0] != '0':\n patch_id_list = choose_ls[stable_ls.index(max(stable_ls))]\n for k in patch_id_list:\n patch_idx = []\n for m in range(cloud.shape[0]):\n if patch_masked[m] == k:\n patch_idx.append(m)\n if len(patch_idx) >= 128:\n choose_patch.append(np.array(patch_idx))\n else:\n choose_patch.append(np.array(all_list))\n else:\n choose_patch.append(np.array(all_list))\n if not choose_patch:\n choose_patch.append(np.array(all_list))\n\n mesh = mesh.detach().data.numpy().reshape(self.mesh_pt,3)\n model_axis = np.array([0.0,1.0,0.0])\n target_rt = np.append(target_r.T, translation).reshape(1, 12)\n return [cloud, # observed point cloud #pts, # clouds trans to mesh coordinate\n mesh, # mesh from the normalized model\n target_rt,\n target,\n choose_patch,mesh_path]# mesh trans to camera(clouds) coordinate\n\n # trans the pts to the right pose ===> ops: [pts_trans = pts - translation, pts_trans = pts_trans @ rotation]\n # size of normalized mesh, return as NOCS does.\n # scale the normalized mesh to the size of transformed pts (pts_trans) ===> [ops: mesh = mesh * ratio]\n\n def re_scale(self, target_fr, target_to):\n ans_scale = target_fr / target_to\n ans_target = target_fr\n ans_scale = ans_scale[0][0]\n\n return ans_target, ans_scale\n\n def __getitem__(self, index):\n # syn_or_real = (random.randint(1, 20) < 15)\n syn_or_real = False # only use the real dataset\n if self.mode == 'val':\n syn_or_real = False\n\n while 1:\n try:\n # cate_id_ = self.cate_id\n cate_id = random.choice([1, 2, 3, 4, 5, 6])\n # cate_id = 5\n choose_obj = random.sample(self.real_obj_name_list[cate_id], 1)[0]\n choose_frame = random.sample(self.real_obj_list[cate_id][choose_obj], 1) # only choose one image randomly\n\n cloud, mesh, target_rt, target,choose_patch,mesh_path = self.get_frame(choose_frame[0], choose_obj,\n syn_or_real)\n # if np.max(abs(target_rt[:9])) > 1.0 or np.max(abs(target_rt[9:])) > 1.0:\n #\n # continue\n break\n\n except:\n continue\n\n class_gt = np.array([cate_id - 1])\n # if cate_id==1 or cate_id==2 or cate_id==4:\n # target_mode = 1\n # elif cate_id==6:\n # target_mode = 2\n # else:\n # target_mode = 0\n return torch.from_numpy(cloud.astype(np.float32)), \\\n torch.from_numpy(mesh.astype(np.float32)), \\\n torch.from_numpy(target_rt.astype(np.float32)), \\\n torch.from_numpy(target.astype(np.float32)), \\\n torch.LongTensor(class_gt), \\\n choose_patch,\\\n choose_frame,\\\n mesh_path\n\n # torch.from_numpy(cloud.astype(np.float32)), \\\n # torch.from_numpy(target_rt.astype(np.float32)), \\\n # choose_triplet, \\\n # torch.from_numpy(target_pt.astype(np.float32)), \\\n # model_points[0], \\\n # torch.LongTensor([target_mode]), \\\n # torch.from_numpy(target_trans.astype(np.float32))\n # torch.from_numpy(scale.astype(np.float32)), \\\n # torch.from_numpy(ratio.astype(np.float32))\n\n def __len__(self):\n return self.length\n\n\nborder_list = [-1, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600, 640, 680]\nimg_width = 480\nimg_length = 640\n\n\ndef get_2dbbox(cloud, cam_cx, cam_cy, cam_fx, cam_fy, cam_scale):\n rmin = 10000\n rmax = -10000\n cmin = 10000\n cmax = -10000\n for tg in cloud:\n p1 = int(tg[0] * cam_fx / tg[2] + cam_cx)\n p0 = int(tg[1] * cam_fy / tg[2] + cam_cy)\n if p0 < rmin:\n rmin = p0\n if p0 > rmax:\n rmax = p0\n if p1 < cmin:\n cmin = p1\n if p1 > cmax:\n cmax = p1\n rmax += 1\n cmax += 1\n if rmin < 0:\n rmin = 0\n if cmin < 0:\n cmin = 0\n if rmax >= 480:\n rmax = 479\n if cmax >= 640:\n cmax = 639\n\n r_b = rmax - rmin\n for tt in range(len(border_list)):\n if r_b > border_list[tt] and r_b < border_list[tt + 1]:\n r_b = border_list[tt + 1]\n break\n c_b = cmax - cmin\n for tt in range(len(border_list)):\n if c_b > border_list[tt] and c_b < border_list[tt + 1]:\n c_b = border_list[tt + 1]\n break\n center = [int((rmin + rmax) / 2), int((cmin + cmax) / 2)]\n rmin = center[0] - int(r_b / 2)\n rmax = center[0] + int(r_b / 2)\n cmin = center[1] - int(c_b / 2)\n cmax = center[1] + int(c_b / 2)\n\n if rmin < 0:\n delt = -rmin\n rmin = 0\n rmax += delt\n if cmin < 0:\n delt = -cmin\n cmin = 0\n cmax += delt\n if rmax > img_width:\n delt = rmax - img_width\n rmax = img_width\n rmin -= delt\n if cmax > img_length:\n delt = cmax - img_length\n cmax = img_length\n cmin -= delt\n\n if ((rmax - rmin) in border_list) and ((cmax - cmin) in border_list):\n return rmin, rmax, cmin, cmax\n else:\n return 0\n\n\ndef search_fit(points):\n min_x = min(points[:, 0])\n max_x = max(points[:, 0])\n min_y = min(points[:, 1])\n max_y = max(points[:, 1])\n min_z = min(points[:, 2])\n max_z = max(points[:, 2])\n\n return [min_x, max_x, min_y, max_y, min_z, max_z]\n\n","sub_path":"datasets/nocs/dataset_nocs_eval.py","file_name":"dataset_nocs_eval.py","file_ext":"py","file_size_in_byte":22249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"51894084","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAuthor:duan\nDate: 2019/7/8 20:29\n\"\"\"\nimport json\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import SelectField, SubmitField\n\nfrom app import app\nfrom flask import render_template, request, jsonify\nfrom models import School, Dept, Team\n\n\nclass RegisterForm(FlaskForm):\n school = SelectField('学院', coerce=int, render_kw={\"class\": \"form-control\"})\n department = SelectField('系', coerce=int, render_kw={\"class\": \"form-control\"})\n submit = SubmitField('提交', render_kw={\"class\": \"form-control\"})\n\n # 初始化下拉表单值,直接给出了学院的所有值\n def __init__(self, *args, **kwargs):\n super(RegisterForm, self).__init__(*args, **kwargs)\n # 第一个值给空是防止第一个选择就是想要的,下拉表单感受不到变化\n self.school.choices = [(0, '-请选择-')]\n for school in School.query.order_by(School.id).all():\n self.school.choices.append((school.id, school.school_name))\n self.department.choices = [(0, '-请选择-')]\n for department in Dept.query.order_by(Dept.id).all():\n self.department.choices.append((department.id, department.dept_name))\n\n\n@app.route('/select_school/', methods=['GET', 'POST'])\ndef selected_school():\n school_id = request.args.get('selected_id')\n school_id = int(json.loads(school_id))\n depts = [(dept.id, dept.dept_name) for dept in Dept.query.filter_by(school_id=school_id).all()]\n return jsonify(depts)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n form = RegisterForm()\n # print(form.data)\n if form.validate_on_submit():\n data = form.data\n print(data)\n return render_template('index.html', form=form)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"631777040","text":"\"\"\"\nfile: publicbeat/publicbeat_app/processors.py\nname: Publicbeat context processors\ndesc: Stores custom context processors for the public beat app\n\"\"\"\nfrom django.template import Context\nfrom publicbeat_app.models import Ad\nfrom publicbeat_app.models import City\nfrom django.db.models import Q\nfrom django.conf import settings\nimport datetime\nfrom publicbeat_app.models import *\n\n\n\n\ndef rsvps(request):\n user_rsvps = []\n\n if request.user.is_authenticated():\n if request.user.rsvp_set:\n for rsvp in request.user.rsvp_set.all(): user_rsvps.append(rsvp.event)\n return {'user_rsvps' : user_rsvps}\n\n else: return {'user_rsvps' : user_rsvps }\n\n\n\n\ndef ads(request):\n now = datetime.datetime.now()\n ads = False\n\n # if you're in a subdomain, display ads from there\n if request.subdomain:\n cityObject = City.objects.get(subdomain = request.subdomain)\n ads = Ad.objects.filter((Q(city = cityObject.id) | Q(ubiquitous = True)) & (Q(startdate__lte = now) & Q(enddate__gte = now))).order_by('?')[:1]\n \n # if there are no ads from that sub, display all global ads\n if not ads: ads = Ad.objects.filter(ubiquitous = True)[:1]\n\n # otherwise, display all global ads\n else: ads = Ad.objects.filter(ubiquitous = True)[:1]\n return {'ads' : ads}\n\n\n\n\ndef current_city(request):\n\n if request.subdomain:\n current_city = City.objects.get(subdomain = request.subdomain)\n return {'current_city' : current_city }\n else:\n return {}\n\n\n\n\ndef useralertcount(request):\n if request.user.is_authenticated(): return { 'useralertcount': request.user.useralert_set.filter(read = False).count() }\n else: return { 'useralertcount': False }\n\n\n\n\nfrom django.db.models import Count\nimport datetime\ndef popular_tags(request):\n try:\n now = datetime.datetime.now()\n popular_tags = Tag.objects.filter(Q(event__place__city__subdomain = request.subdomain) & Q(event__start__gte = now)).exclude(name=\"Adult\").annotate(event_count = Count('event')).order_by('event_count').distinct()[0:8]\n not_so_popular_tags = Tag.objects.filter(Q(event__place__city__subdomain = request.subdomain) & Q(event__start__gte = now)).exclude(name=\"Adult\").annotate(event_count = Count('event')).order_by('event_count').distinct()[8:16]\n except:\n popular_tags = []\n not_so_popular_tags\n \n return { 'popular_tags' : popular_tags , 'not_so_popular_tags': not_so_popular_tags}\n\n\n\ndef noindex(request):\n try:\n if request.GET['page']: noindex = True\n else: noindex = False\n except: noindex = False\n return { 'noindex' : noindex, }\n\n\n\n\ndef returning_user(request):\n \n try:\n if request.COOKIES['returning_user']:\n returning_user = True\n except:\n returning_user = False\n\n return { 'returning_user' : returning_user, }\n\n\n\n\n","sub_path":"publicbeat_app/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"630987659","text":"#Imports\nfrom PIL import Image\nimport collections\n\n#load original image\nim = Image.open('2018test.jpg')\n\n#get pixel values from original image\npix_val = list(im.getdata())\n\n#open data file to write values to\ndataFile = open('blacklist5.txt', 'w')\n\n#declare empty list to store rgb values to delete\ntoRemoveList = []\nprev_val = ''\n\nfor x in pix_val:\n if prev_val != x:\n if x not in toRemoveList:\n #add rgb value to list\n toRemoveList.append(x)\n print(x, file=dataFile)\n prev_val = x\n \n \n \n\nmaxRGB = max(pix_val)\nminRGB = min(pix_val)\n\nprint('max: ' + str(maxRGB))\nprint('min: ' + str(minRGB))\n\n\n","sub_path":"blacklister.py","file_name":"blacklister.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"333696952","text":"# Hint: You may not need all of these. Remove the unused functions.\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\n\ndef reconstruct_trip(tickets, length):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # create cache\n cache = {}\n # create an arr that grows with length input\n storage = [None] * length\n # loop thru our tickets input arr\n for i in tickets:\n if i.source == \"NONE\":\n storage[0] = i.destination\n cache[i.source] = i.destination\n# loop thru range starting at 1 and end at our given length\n for x in range(1, length):\n # reconstruct our storage arr with the proper order\n storage[x] = cache[storage[x - 1]]\n\n return storage\n","sub_path":"hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"277428023","text":"import dataclasses\nimport typing as typ\nimport pathlib\nimport win32com.client.gencache\nimport numpy as np\nimport astropy.units as u\nfrom kgpy import optics\nfrom .. import ZOSAPI\nfrom . import configuration, wavelengths, util, fields, surface\n\n__all__ = ['System', 'calc_zemax_system']\n\n\ndef load_zemax_app() -> ZOSAPI.IZOSAPI_Application:\n zemax_connection = win32com.client.gencache.EnsureDispatch('ZOSAPI.ZOSAPI_Connection')\n if zemax_connection is None:\n raise ValueError('Unable to initialize COM connection to ZOSAPI')\n\n zemax_app = zemax_connection.CreateNewApplication()\n if zemax_app is None:\n raise ValueError('Unable to acquire ZOSAPI application')\n if not zemax_app.IsValidLicenseForAPI:\n raise ValueError('Invalid licence (Possibly too many instances of OpticStudio are open).')\n\n return zemax_app\n\n\n@dataclasses.dataclass\nclass InstanceVarBase:\n\n _entrance_pupil_radius_op: configuration.Operand = dataclasses.field(\n default_factory=lambda: configuration.Operand(\n op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.APER,\n ),\n init=False,\n repr=False,\n )\n\n _stop_surface_index_op: configuration.Operand = dataclasses.field(\n default_factory=lambda: configuration.Operand(\n op_factory=lambda: ZOSAPI.Editors.MCE.MultiConfigOperandType.STPS\n ),\n init=False,\n repr=False,\n )\n\n _zemax_app: ZOSAPI.IZOSAPI_Application = dataclasses.field(default_factory=load_zemax_app, init=False, repr=False, )\n\n _lens_units: u.Unit = dataclasses.field(default_factory=lambda: u.mm, repr=False)\n\n _mce_: configuration.Editor = dataclasses.field(\n default_factory=lambda: configuration.Editor(), init=False, repr=False,\n )\n\n\nSurfacesT = typ.TypeVar('SurfacesT', bound='typ.Iterable[surface.Surface]')\n\n\n@dataclasses.dataclass\nclass System(optics.System[SurfacesT], InstanceVarBase):\n\n def __post_init__(self):\n self._mce = self._mce\n\n def save(self, filename: pathlib.Path):\n self._zemax_system.SaveAs(str(filename))\n\n @property\n def surfaces(self) -> SurfacesT:\n return self._surfaces\n\n @surfaces.setter\n def surfaces(self, value: SurfacesT):\n num_surfaces = len(list(value)) + 1\n while self._lde.NumberOfSurfaces != num_surfaces:\n if self._lde.NumberOfSurfaces < num_surfaces:\n self._lde.AddSurface()\n else:\n self._lde.RemoveSurfaceAt(self._lde.NumberOfSurfaces)\n\n self._surfaces = value\n for v in value:\n v._composite = self\n\n def _entrance_pupil_radius_setter(self, value: float):\n self._zemax_system.SystemData.Aperture.ApertureType = ZOSAPI.SystemData.ZemaxApertureType.EntrancePuilDiameter\n self._zemax_system.SystemData.Aperture.ApertureValue = value\n\n @property\n def entrance_pupil_radius(self) -> u.Quantity:\n return self._entrance_pupil_radius\n\n @entrance_pupil_radius.setter\n def entrance_pupil_radius(self, value: u.Quantity):\n self._entrance_pupil_radius = value\n self._set(value, self._entrance_pupil_radius_setter, self._entrance_pupil_radius_op, self._lens_units)\n\n def _stop_surface_index_setter(self, value: int):\n surf = list(self.surfaces)[value]\n surf._lde_row.IsStop = True\n\n @property\n def stop_surface_index(self) -> int:\n return self._stop_surface_index\n\n @stop_surface_index.setter\n def stop_surface_index(self, value: int):\n self._stop_surface_index = value\n self._set(value, self._stop_surface_index_setter, self._stop_surface_index_op)\n\n @property\n def _zemax_system(self) -> ZOSAPI.IOpticalSystem:\n return self._zemax_app.PrimarySystem\n\n @property\n def _lde(self) -> ZOSAPI.Editors.LDE.ILensDataEditor:\n return self._zemax_system.LDE\n\n @property\n def _mce(self) -> configuration.Editor:\n return self._mce_\n\n @_mce.setter\n def _mce(self, value: configuration.Editor):\n self._mce_ = value\n value._composite = self\n\n @property\n def _lens_units(self) -> u.Unit:\n return self.__lens_units\n\n @_lens_units.setter\n def _lens_units(self, value: u.Unit):\n self.__lens_units = value\n\n if value == u.mm:\n self._zemax_system.SystemData.Units.LensUnits = ZOSAPI.SystemData.ZemaxSystemUnits.Millimeters\n elif value == u.cm:\n self._zemax_system.SystemData.Units.LensUnits = ZOSAPI.SystemData.ZemaxSystemUnits.Centimeters\n elif value == u.m:\n self._zemax_system.SystemData.Units.LensUnits = ZOSAPI.SystemData.ZemaxSystemUnits.Meters\n elif value == u.imperial.inch:\n self._zemax_system.SystemData.Units.LensUnits = ZOSAPI.SystemData.ZemaxSystemUnits.Inches\n else:\n raise ValueError('Unsupported unit')\n\n def _set(\n self,\n value: typ.Any,\n setter: typ.Callable[[typ.Any], None],\n operand: configuration.Operand,\n unit: u.Unit = None,\n ) -> typ.NoReturn:\n print('here')\n if unit is not None:\n value = value.to(unit).value\n\n if np.isscalar(value):\n if operand._composite is not None:\n self._mce.pop(operand.mce_index)\n setter(value)\n\n else:\n if operand._composite is None:\n self._mce.append(operand)\n operand.data = value\n\n\ndef calc_zemax_system(system: 'optics.System') -> typ.Tuple[ZOSAPI.IOpticalSystem, u.Unit]:\n zemax_system = open_zemax_system()\n\n # zemax_system.SystemData.Units = ZOSAPI.SystemData.ZemaxSystemUnits.Millimeters\n zemax_lens_units = u.mm\n\n configuration_size = system.config_broadcast.size\n configuration_shape = system.config_broadcast.shape\n\n while zemax_system.MCE.NumberOfConfigurations < configuration_size:\n zemax_system.MCE.AddConfiguration(False)\n\n set_entrance_pupil_radius(zemax_system, system.entrance_pupil_radius, configuration_shape, zemax_lens_units)\n fields.add_to_zemax_system(zemax_system, system.field_grid, configuration_shape)\n wavelengths.add_to_zemax_system(zemax_system, system.wavelengths, configuration_shape)\n surface.add_surfaces_to_zemax_system(zemax_system, system.surfaces, configuration_shape, zemax_lens_units)\n\n set_stop_surface(zemax_system, system.stop_surface_index, configuration_shape)\n\n return zemax_system, zemax_lens_units\n\n\ndef open_zemax_system() -> ZOSAPI.IOpticalSystem:\n # Create COM connection to Zemax\n zemax_connection = win32com.client.gencache.EnsureDispatch(\n 'ZOSAPI.ZOSAPI_Connection') # type: ZOSAPI.ZOSAPI_Connection\n if zemax_connection is None:\n raise ValueError('Unable to initialize COM connection to ZOSAPI')\n # Open Zemax system\n zemax_app = zemax_connection.CreateNewApplication()\n if zemax_app is None:\n raise ValueError('Unable to acquire ZOSAPI application')\n # Check if license is valid\n if not zemax_app.IsValidLicenseForAPI:\n raise ValueError('License is not valid for ZOSAPI use (Possibly too many instances of OpticStudio are open).')\n zemax_system = zemax_app.PrimarySystem\n if zemax_system is None:\n raise ValueError('Unable to acquire Primary system')\n return zemax_system\n\n\ndef set_entrance_pupil_radius(\n zemax_system: ZOSAPI.IOpticalSystem,\n entrance_pupil_radius: u.Quantity,\n configuration_shape: typ.Tuple[int],\n zemax_units: u.Unit\n):\n zemax_system.SystemData.Aperture.ApertureType = ZOSAPI.SystemData.ZemaxApertureType.EntrancePuilDiameter\n\n op_type = ZOSAPI.Editors.MCE.MultiConfigOperandType.APER\n\n entrance_pupil_diameter = 2 * entrance_pupil_radius\n util.set_float(zemax_system, entrance_pupil_diameter, configuration_shape, op_type, zemax_unit=zemax_units)\n\n\ndef set_stop_surface(\n zemax_system: ZOSAPI.IOpticalSystem,\n stop_surface_index: int,\n configuration_shape: typ.Tuple[int],\n):\n op_stop_surface_index = ZOSAPI.Editors.MCE.MultiConfigOperandType.STPS\n util.set_int(zemax_system, stop_surface_index, configuration_shape, op_stop_surface_index)\n","sub_path":"kgpy/optics/zemax/system/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":8179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"450778273","text":"from pymuco.models import DiscreteProbabilityModel\nfrom functools import reduce\nfrom operator import mul\nimport pymuco.rhythm\nimport lhl\nimport itertools\nimport math\n\nclass MeterModel(DiscreteProbabilityModel):\n\n @classmethod\n def create_uniform(cls, parameters):\n obj = cls()\n for param in parameters:\n obj.observe(*param)\n return obj\n\n def likelihood(self, meter):\n '''\n Calculate likelihood with a maximum likelihood estimate\n of the parameters\n '''\n\n counts = self.counts\n N = sum([count for meter, count in counts.items()])\n\n return counts[meter] / float(N)\n\n def parameter_space(self):\n\n return self.counts.keys()\n\nclass MetricalPositionViewpoint(DiscreteProbabilityModel):\n '''\n A collection of bernoulli distributions over the\n probability of an onset given its position and the previous event\n '''\n\n def __init__(self, *args, meter, order, **kwargs):\n\n super(MetricalPositionViewpoint, self).__init__()\n self.period = reduce(mul, meter)\n self.order = order\n self._onset_sequences = [tuple(os) for os in itertools.product([0, 1], repeat=self.order+1)]\n\n def set_counts_to_one(self):\n\n for param in self.parameter_space():\n\n self.counts[param] = 1\n\n def preprocess_grid(self, grid):\n\n return grid\n\n def _perceived_position(self, time, phase):\n\n return (time - phase) % self.period\n\n def observations(self, grid, phase):\n\n obs = []\n\n for time, onset in enumerate(grid):\n\n obs.append(onset)\n\n return [(self._perceived_position(t, phase), tuple(obs[t - self.order: t+1])) for t in range(self.order, len(obs))]\n\n\n def likelihood(self, observation, smoothing=None):\n '''\n Calculate likelihood using the maximum likelihood estimate\n of the parameters\n '''\n\n position, ngram = observation\n event = ngram[-1]\n context = ngram[:-1]\n\n try:\n normalization = sum(\n #[self.counts.get((position, context + (e, )), 0) for e in self.observation_space()]\n [self.counts[(position, context + (e, ))] for e in self.observation_space()]\n )\n return self.counts[observation] / normalization\n\n except KeyError:\n return (0.0 if smoothing == None else 0.0)\n\n def predictive_distribution_parameters(self, observation):\n\n position, ngram = observation\n context = ngram[1:]\n\n return [(self._perceived_position(position+1), context + (e, )) for e in self.observation_space()]\n\n def observation_space(self): \n\n return (0, 1)\n\n def parameter_space(self):\n\n params = []\n\n position_set = set(map(lambda time: self._perceived_position(time, 0), range(self.period)))\n\n for position in position_set:\n\n for onset_sequence in self._onset_sequences:\n\n params.append((position, onset_sequence))\n\n return params\n\n\nclass MetricalSalienceViewpoint(MetricalPositionViewpoint):\n\n def __init__(self, *args, meter, **kwargs):\n\n self.meter = meter\n self.metrical_weights = lhl.metrical_weights(meter)\n\n super(MetricalSalienceViewpoint, self).__init__(*args, meter=meter, **kwargs)\n\n def _perceived_position(self, position, phase):\n\n return self.metrical_weights[(position - phase) % self.period]\n\nclass HierarchicalMetricalPositionViewpoint(MetricalSalienceViewpoint):\n\n def observations(self, grid, phase):\n\n obs = []\n\n for time, onset in enumerate(grid):\n\n obs.append(onset)\n\n return [(self._perceived_position(t, phase), tuple(obs[t - self.order: t+1])) for t in range(self.order, len(obs))]\n\n\n def likelihood(self, observation, smoothing=None):\n '''\n Calculate likelihood using the maximum likelihood estimate\n of the parameters\n '''\n\n position, ngram = observation\n event = ngram[-1]\n context = ngram[:-1]\n\n try:\n normalization = sum(\n [self.counts.get((position, context + (e, )), 0) for e in self.observation_space()]\n )\n return self.counts[observation]/normalization\n\n except KeyError:\n return (0.0 if smoothing == None else 0.0)\n\n\nclass MetricalDurationViewpoint(DiscreteProbabilityModel):\n\n def __init__(self, *args, meter, order, **kwargs):\n\n self.period = reduce(mul, meter)\n self.order = order\n\n super().__init__(*args, **kwargs)\n\n def preprocess_grid(self, grid):\n\n return pymuco.rhythm.grid_to_iois(grid)\n \n def _perceived_position(self, position, phase):\n\n return (position - phase) % self.period\n\n def observations(self, inp, phase=0):\n\n obs = []\n \n time, iois = inp\n obs.append(self._perceived_position(time, phase))\n\n for ioi in iois[:-1]:\n\n time += ioi\n obs.append(self._perceived_position(time, phase))\n\n return [tuple(obs[t - self.order: t+1]) for t in range(self.order, len(obs))]\n\n def likelihood(self, ngram, smoothing=None):\n '''\n Calculate likelihood using the maximum likelihood estimate\n of the parameters\n '''\n\n event = ngram[-1]\n context = ngram[:-1]\n\n try:\n normalization = sum(\n [self.counts.get(context + (e, ), 0) for e in self.observation_space()]\n )\n p = self.counts[ngram]/normalization\n return p\n\n except KeyError:\n return (0.0 if smoothing == None else 0.0)\n\n def predictive_distribution_parameters(self, ngram):\n\n context = ngram[1:]\n\n return [context + (e, ) for e in self.observation_space()]\n\n def observation_space(self):\n\n return set([self._perceived_position(t, 0) for t in range(self.period)])\n\n def parameter_space(self):\n\n params = []\n\n return list(itertools.product(self.observation_space(), repeat=self.order+1))\n\nclass MetricalSalienceDurationViewpoint(MetricalDurationViewpoint):\n\n def __init__(self, *args, meter, **kwargs):\n\n self.metrical_weights = lhl.metrical_weights(meter)\n\n super(MetricalSalienceDurationViewpoint, self).__init__(*args, meter=meter, **kwargs)\n\n def _perceived_position(self, position, phase):\n\n return self.metrical_weights[(position - phase) % self.period]\n\n \nclass NthOrderPerceptionModel(object):\n\n VARIABLES = ('information_content', 'predictive_entropy', 'onset_probability', 'posterior_entropy')\n\n def __init__(self, *, meter_model, rhythm_models, resolution):\n\n self.meter_model = meter_model\n self.rhythm_models = rhythm_models\n self.resolution = resolution\n\n def initialize(self, grid):\n\n self.initialize_prior()\n self.solution_array = {\n (meter, phase): model.observations(model.preprocess_grid(grid), phase=phase)\n for meter, model in self.rhythm_models.items()\n for phase in range(model.period)\n }\n #for meter, phase in sorted(self.solution_array.keys()):\n # print('%s:\\t:%s' % ((meter, phase), self.solution_array[meter, phase]))\n #self.test_for_zero_counts()\n\n max_parameters = max(\n [len(model.observation_space())**(model.order+1) for model in self.rhythm_models.values()]\n )\n # This is used to normalize the likelihood distributions, which is necessary for models\n # where the likelihood distribution can have a variable number of parameters\n self.normalizing_factors = {\n meter: (len(model.observation_space())**(model.order+1) / max_parameters) for meter, model in self.rhythm_models.items()\n }\n #print(self.normalizing_factors)\n\n\n #print(self.rhythm_models[(6,8)].period)\n #print(self.rhythm_models[(6,8)].parameter_space())\n #print('6/8, 0:\\t%s' % (self.solution_array[(6, 8), 0]))\n\n def initialize_prior(self):\n\n # The phase isn't a parameter in the trained model\n # Since we're spreading out probability mass over different phases we need to renormalise\n # the distribution.\n # We could take into account the number of phases that each metre spreads over, but this would\n # result in biases towards meters with few metrical positions\n\n self.normalization_constant = sum([\n self.meter_model.likelihood(meter) * self.rhythm_models[meter].period\n for meter in self.meter_model.parameter_space()\n ]) ** -1\n\n self.posterior = {\n (meter, phase): self.meter_model.likelihood(meter) * self.normalization_constant\n for meter in self.meter_model.parameter_space()\n for phase in range(self.rhythm_models[meter].period)\n }\n\n def expose(self):\n\n for position in range(len(next(iter(self.solution_array.values())))):\n\n # Update the posterior distribution\n\n # P(R) = \\sum^{M, \\phi} P(R|M, \\phi)\n # Evidence is independent of phase and meter so it can be calculated in advance\n evidence = sum(\n [\n self.rhythm_models[m].likelihood(self.solution_array[m, phi][position]) * self.posterior[m, phi] * self.normalizing_factors[m]\n for m, phi in self.posterior.keys()\n ]\n )\n\n for (meter, phase), meter_likelihood in self.posterior.items():\n\n # P(M, \\phi)\n prior = meter_likelihood\n # P(R | M, \\phi)\n likelihood = self.rhythm_models[meter].likelihood(self.solution_array[meter, phase][position]) * self.normalizing_factors[meter]\n # P(M, \\phi | R) = P(R|M, \\phi)P(M, \\phi) / P(R)\n self.posterior[meter, phase] = likelihood * prior / evidence\n\n yield self.posterior.copy()\n\n\n def test_for_zero_counts(self):\n\n zero_counts = 0\n\n for name, model in self.rhythm_models.items():\n meter_zero_counts = 0\n for param in model.parameter_space():\n if not param in model.counts:\n zero_counts += 1\n meter_zero_counts += 1\n #print('Zero count in %s (%s)' % (name, param))\n\n print('Zero counts for %s : %d out of %d' % (name, meter_zero_counts, len(model.parameter_space())))\n\n print('Total zero counts: %d' % zero_counts)\n\n\n @property\n def predictive_entropy(self):\n \n return -sum([math.log(p) * p for p in self.predictive_distribution.values()])\n\n def likelihood(self, time, event):\n\n return sum([\n self.rhythm_models[meter].likelihood(time, event, phase) * \n self.posterior[meter, phase]\n for meter, phase in self.posterior.keys()\n ])\n\n @property\n def predictive_distribution(self):\n\n return {\n event: self.likelihood(self.time + 1, event) for event in self.viewpoint.event_space()\n }\n\n @property\n def onset_probability(self):\n\n history = self.last_event[1:]\n\n return self.predictive_distribution[history + (1, )]\n\n @property\n def posterior_entropy(self):\n\n return -sum([math.log(p) * p for p in self.posterior.values() if p > 0])\n\n def information_content(self, event):\n\n return -math.log(self.predictive_distribution[event])\n\n def pretty_print_posterior(self, N=10):\n\n for (meter, phase), probability in list(reversed(sorted(self.posterior.items(), key=lambda keyvalue: keyvalue[1])))[:N]:\n print('P(%s, %s) =\\t%f' % (meter, phase, probability))\n\n\nclass HierarchicalMeterModel(object):\n\n def observations(self, meter):\n\n count = 1\n obs = []\n\n while meter != []:\n\n period = reduce(mul, meter + (1, ))\n subdivision = meter.pop(0)\n obs += count * [period, subdivision]\n count *= subdivision\n\n return obs \n\n def observe(self, period, subdivision):\n\n counts_period = self.counts.get((period, ), {})\n counts_period[subdivision, ] = counts_period.get((subdivision, ), 0) + 1\n counts[period, ] = counts_period\n\n\n def likelihood(self, meter):\n '''\n Calculate likelihood using the maximum likelihood estimate\n of the parameters\n '''\n\n counts = self.counts\n N = sum([count for meter, count in counts.items()])\n\n return counts[meter] / float(N)\n\n def parameter_space(self):\n\n return self.counts.keys()\n\nclass HierarchicalRhythmModel(object):\n\n # The parameters of this model are (partial) trees, and the likelihood of them producing \n # onsets at certain positions\n\n def observations(self, pattern, meter):\n\n if meter == []:\n head, *rest = pattern\n print(pattern)\n assert head in [0, 1] and not any(rest)\n return head, []\n\n period = reduce(mul, meter)\n subdivision, *new_meter = meter\n\n rhythm_obs = []\n meter_obs = [(period, subdivision)]\n onsets = []\n\n for position in range(subdivision):\n\n begin, end = position * period // subdivision, (position + 1) * period // subdivision\n sounded, sub_observations = self.observations(pattern[begin:end], new_meter)\n\n onsets.append(sounded)\n obs += sub_observations + [(period, subdivision, position, sounded)]\n\n return onsets[0], meter_obs, rhythm_obs\n\n\nclass HierarchicalPerceptionModel(object):\n\n def __init__(self, meter_model, rhythm_models, resolution):\n\n ...\n\n def initialize_prior(self):\n\n # For every phase of every root node\n # Add all possible trees and their likelihood\n\n ...\n\n def observe(self, event):\n\n ...\n\n # Consider all trees in the posterior, and the likelihood of them having produced this event\n\n","sub_path":"exposure/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"48457868","text":"import logging\nimport logging.handlers\n\nLOG_FILENAME = '/tmp/logging_rotatingfile_example.out'\n\n# Set up a specific logger with our desired output level\nmy_logger = logging.getLogger('MyLogger')\nmy_logger.setLevel(logging.DEBUG)\n\n# Add the log message handler to the logger\nhandler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20, backupCount=5)\n\nhandler.setLevel(logging.CRITICAL)\n\nmy_logger.addHandler(handler)\nmy_logger.debug(\"Message with %s, %s\", \"test string1\", \"test string2\")\n","sub_path":"class/I-logging/1-logging.py","file_name":"1-logging.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"247885990","text":"# -*- coding: us-ascii -*-\n\"\"\"Unit and regression tests for the IHS Fairplay lookup service.\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom pkg_resources import resource_filename\n\nfrom pyAirviro.edb.sourcedb import create_ship\nfrom pyAirviro.lookupservices.ihs import IHSService\nfrom pyAirviro.other.controlfile import ControlFile\nimport pyAirviro.tests\nfrom pyAirviro.tests import skip\n\n\nclass IHSServiceTests(pyAirviro.tests.TestCase):\n\n \"\"\"Unit and regression tests for the ResourceService class.\"\"\"\n\n def setUp(self):\n resourcefile = resource_filename(__name__, 'data/lookupservices.rf')\n self.resources = ControlFile(resourcefile)\n\n @skip(\"not contacting IHS\")\n def test_get_download_entitlement(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n rawdata = service.fetcher.get_download_entitlement()\n self.assertIsNotNone(rawdata)\n data = service.parser.parse(rawdata)\n self.assertEqual(data.get('ns0:Order_Detail_No'), '620142')\n self.assertTrue(data.get('ns0:Current_Entitlement').isdigit())\n self.assertTrue(data.get('ns0:Download_Count').isdigit())\n\n def test_update_with_zero_ship_count(self):\n service = IHSService(\n self.resources,\n cache=resource_filename(__name__, 'data/cache/IHS'),\n cache_only=True,\n report_download_entitlement=False,\n )\n ship = create_ship(MMSI=207555500)\n service.update(ship)\n self.assertEqual(service.get_fetch_failures(ship), 1)\n\n def test_set_sfoc_base_with_no_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1)\n service.set_sfoc_base(ship, None, None)\n self.assertFalse(hasattr(ship, 'me_sfoc_base'))\n service.set_sfoc_base(ship, '0.0', '0.0')\n self.assertFalse(hasattr(ship, 'me_sfoc_base'))\n service.set_sfoc_base(ship, None, '1.0')\n self.assertFalse(hasattr(ship, 'me_sfoc_base'))\n service.set_sfoc_base(ship, '1.0', None)\n self.assertFalse(hasattr(ship, 'me_sfoc_base'))\n\n def test_set_sfoc_base_with_data(self):\n service = IHSService(\n self.resources,\n csr_factor=1/24.,\n report_download_entitlement=False,\n )\n ship = create_ship(MMSI=1)\n service.set_sfoc_base(ship, '100.0', '500000')\n self.assertAlmostEqual(ship.me_sfoc_base, 200)\n service.set_sfoc_base(ship, '200.0', '500000')\n self.assertAlmostEqual(ship.me_sfoc_base, 400)\n\n def test_set_sfoc_base_with_invalid_data(self):\n service = IHSService(\n self.resources,\n csr_factor=1/24.,\n report_download_entitlement=False,\n )\n ship = create_ship(MMSI=1)\n service.set_sfoc_base(ship, '49.0', '500000')\n self.assertFalse(hasattr(ship, 'me_sfoc_base'))\n\n def test_set_speed_with_no_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1)\n service.set_speed(ship, None, None)\n self.assertFalse(hasattr(ship, 'speed_mcr'))\n service.set_speed(ship, '0.0', '0.0')\n self.assertFalse(hasattr(ship, 'speed_mcr'))\n\n def test_set_speed_with_mcr_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1)\n service.set_speed(ship, '2.0', None)\n self.assertAlmostEqual(ship.speed_mcr, 2)\n service.set_speed(ship, '2.0', '1.0')\n self.assertAlmostEqual(ship.speed_mcr, 2)\n\n def test_set_speed_with_csr_data(self):\n service = IHSService(\n self.resources,\n csr_factor=0.85,\n report_download_entitlement=False,\n )\n ship = create_ship(MMSI=1)\n service.set_speed(ship, None, '2.0')\n self.assertAlmostEqual(ship.speed_mcr, 2.11)\n service.set_speed(ship, '0.0', '2.0')\n self.assertAlmostEqual(ship.speed_mcr, 2.11)\n\n def test_set_design_speed_with_no_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1)\n service.set_design_speed(ship, None, None)\n self.assertNotIn('Vd', ship.ALOB)\n service.set_design_speed(ship, '0.0', '0.0')\n self.assertNotIn('Vd', ship.ALOB)\n\n def test_set_design_speed_with_mcr_data(self):\n service = IHSService(\n self.resources,\n csr_factor=0.85,\n report_download_entitlement=False,\n )\n ship = create_ship(MMSI=1)\n service.set_design_speed(ship, '2.0', None)\n self.assertAlmostEqual(ship.ALOB['Vd'], 1.89)\n service.set_design_speed(ship, '2.0', '1.0')\n self.assertAlmostEqual(ship.ALOB['Vd'], 1.0)\n\n def test_set_design_speed_with_csr_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1)\n service.set_design_speed(ship, None, '2.0')\n self.assertAlmostEqual(ship.ALOB['Vd'], 2.0)\n service.set_speed(ship, '0.0', '2.0')\n self.assertAlmostEqual(ship.ALOB['Vd'], 2.0)\n\n def test_set_ship_type_with_no_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1, SEARCHKEY4=1)\n service.set_ship_type(ship, None)\n self.assertFalse(hasattr(ship, 'statcode5'))\n self.assertEqual(ship.SEARCHKEY4, 1)\n\n def test_set_ship_type_with_data(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1, SEARCHKEY4=1)\n service.set_ship_type(ship, 'B')\n self.assertEqual(ship.statcode5, 'B')\n self.assertEqual(ship.SEARCHKEY4, 1)\n service.set_ship_type(ship, 'B1')\n self.assertEqual(ship.statcode5, 'B1')\n self.assertEqual(ship.SEARCHKEY4, 2)\n service.set_ship_type(ship, 'B11')\n self.assertEqual(ship.statcode5, 'B11')\n self.assertEqual(ship.SEARCHKEY4, 2)\n\n def test_set_me_stroke_type(self):\n service = IHSService(self.resources, report_download_entitlement=False)\n ship = create_ship(MMSI=1)\n service.set_me_stroke_type(ship, 'Y')\n self.assertFalse(hasattr(ship, 'me_stroke_type'))\n service.set_me_stroke_type(ship, '2')\n self.assertEqual(ship.me_stroke_type, '2')\n","sub_path":"pyAirviro/tests/lookupservices/test_ihs.py","file_name":"test_ihs.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"536538090","text":"from datetime import datetime, timedelta\nfrom redismon.redismon_manager import RedisMonManager\n\nimport json\nimport sys\n\nfrom scipy import stats\n\nclass RedisAbnormalDetection:\n def __init__(self, metrics1, metrics2):\n self.metrics1 = metrics1\n self.metrics2 = metrics2\n\n def check(self): \n l1 = len(self.metrics1)\n l2 = len(self.metrics2)\n\n if l1 == 0 or l2 == 0:\n return None\n\n m = min(l1, l2)\n m1 = self.metrics1[:m]\n m2 = self.metrics2[:m]\n\n a = self.extract_commands(m1, \"info\")\n b = self.extract_commands(m2, \"info\")\n\n print(a)\n print(b)\n\n desc_a = stats.describe(a)\n desc_b = stats.describe(b)\n\n print(\"a/b-> 평균: {0:.3}/{1:.3}, 분산: {2:.3}/{3:.3}\".format(desc_a.mean, desc_b.mean, desc_a.variance, desc_b.variance))\n\n # 대응표본 t 검정\n t = stats.ttest_rel(a,b)\n print(\"t-dep-test p-value: {0:.12f}, {1}\".format(t.pvalue, t.statistic))\n\n \n\n def get_commands(self, info, prefix, cmds):\n for key in info.keys():\n if key.startswith(\"cmdstat_\" + prefix):\n #cmds.append((key, info[key]))\n cmds.append(info[key][\"usec_per_call\"])\n\n def extract_commands(self, metrics, key):\n cmds = []\n for m in metrics:\n self.get_commands(json.loads(m.value), key, cmds)\n\n return cmds\n\n\nclass AnalyzerManager:\n def __init__(self, manager):\n self.manager = manager\n\n def analyze(self, unit, metrics1_from=None, metrics1_to=None, metrics2_from=None, metrics2_to=None):\n m1 = self.fetch_with_range(unit, metrics1_from, metrics1_to)\n m2 = self.fetch_with_range(unit, metrics2_from, metrics2_to)\n\n return m1, m2\n\n def fetch_with_range(self, unit_id, metric_from, metric_to):\n units = self.manager.list_units()\n metrics = self.manager.get_all_metrics_by_time_range(unit_id,\n metric_from,\n metric_to)\n\n return metrics\n\n\nunit_id = int(sys.argv[1])\n\nif __name__ == \"__main__\":\n from redismon.base import db\n m = RedisMonManager(db)\n arm = AnalyzerManager(m)\n \n t1 = sys.argv[2]\n t2 = sys.argv[3]\n t3 = sys.argv[4]\n t4 = sys.argv[5]\n\n m1, m2 = arm.analyze(unit_id, t1, t2, t3, t4)\n\n r = RedisAbnormalDetection(m1, m2)\n r.check()\n","sub_path":"app/redismon/abnormal.py","file_name":"abnormal.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"554788415","text":"__author__ = 'besprout'\nimport tkinter\nimport os\nimport sys\npath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))+\"/PyFoundation/CoreGraphics\"\nsys.path.insert(0,path)\nfrom CGGeomerty import *\n\nimport tkinter as tk\n\nclass UIWindow(tk.Tk):\n \"\"\"\n UIWindow是是窗口应用的根实图\n \"\"\"\n def __init__(self, width = 100, height = 100,resizeAble = False, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n frame = str(width)+\"x\"+str(height)\n self.configure(background='blue')\n self.resizable(resizeAble,resizeAble)\n self.geometry(frame)\n\n def setFrame(self,frame):\n '设置视图尺寸'\n #frame 数据类型为CGFreame\n frame = str(frame.width)+\"x\"+str(frame.height)\n self.geometry(frame)\n\n def setBackgoroundColor(self,color):\n self.configure(background=color)\n\n def setHidden(self,hidden):\n pass\n\n def show(self):\n self.mainloop()","sub_path":"PythonCocoa/PyFoundation/UIKit/UIWindow.py","file_name":"UIWindow.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"242008010","text":"\"\"\"A setuptools based setup module.\nSee:\nhttps://packaging.python.org/en/latest/distributing.html\nhttps://github.com/pypa/sampleproject\n\"\"\"\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\nimport re\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='pyEvalData',\n version='1.0',\n packages=['pyEvalData'],\n url='https://github.com/dschick/pyEvalData', # Optional\n install_requires=['numpy', 'matplotlib', 'xrayutilities', 'scipy', 'uncertainties'], # Optional\n license='',\n author='Daniel Schick',\n author_email='schick.daniel@gmail.com',\n description='Python Modul to evaluate SPEC data and Dectris Pilatus reciprocal space maps', # Required\n long_description=long_description, # Optional\n long_description_content_type='text/markdown', # Optional (see note above)\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"370790279","text":"#! /powerapps/share/python-anaconda-3.6/bin/python\n\nimport sys\nsys.path.insert(0,'/sternadi/home/volume1/taliakustin/SternLab')\nfrom optparse import OptionParser\nimport os\nimport glob\nfrom file_utilities import check_filename, check_dirname\nfrom dirSel_utilities import write_params_file_PQR\n\nDIRSEL_PATH = \"/sternadi/home/volume1/taliakustin/software/phylogenyCode/programs/directionalSelection/directionalSelection\"\n\ndef main():\n parser = OptionParser(\"usage: %prog [options]\")\n parser.add_option(\"-a\", \"--aln\", dest=\"aln\", help=\"alignment file\")\n parser.add_option(\"-t\", \"--tree\", dest=\"tree\", help=\"tree file\")\n parser.add_option(\"-m\", \"--model\", dest=\"model\", help=\"model - fixed_beta or alternative\")\n parser.add_option(\"-g\", \"--gtr\", dest=\"gtr\", help=\"gtr output\")\n parser.add_option(\"-d\", \"--dirSel_path\", dest=\"dirSel_path\", help=\"dirSel path\",\n default=\"/sternadi/home/volume1/taliakustin/software/phylogenyCode/programs/directionalSelection/directionalSelection\")\n\n (options, args) = parser.parse_args()\n\n aln = options.aln\n aln = check_filename(aln)\n tree = options.tree\n tree = check_filename(tree)\n gtr = options.gtr\n gtr = check_filename(gtr)\n model = options.model\n\n print(model)\n\n if model == \"alternative\":\n inter = \"PQR_alt\"\n output_dir = \"/sternadi/home/volume3/taliakustin/phyVirus_analysis/PQR_alt\"\n fixed_beta = 0\n fixed_s = 1\n fixed_probS = 1\n init_probS = 0\n fixed_tau = 0\n path = \"/sternadi/home/volume1/taliakustin/software/PQR_no_root/programs/PQRmodel/PQRmodel\"\n elif model == \"null\":\n inter = \"PQR_null\"\n output_dir = \"/sternadi/home/volume3/taliakustin/phyVirus_analysis/PQR_null/\"\n fixed_beta = 0\n fixed_s = 0\n fixed_probS = 0\n init_probS = 0.01\n fixed_tau = 0\n path = \"/sternadi/home/volume1/taliakustin/software/PQR_no_root/programs/PQRmodel/PQRmodel\"\n\n basename = aln.split(\"/\")[-1].split(\"aln.best.fas\")[0]\n\n param_file = output_dir + \"/%s%s.params\" % (basename, inter)\n\n output_res = output_dir + \"/%s%s.results\" % (basename, inter)\n output_log = output_dir + \"/%s%s.log\" % (basename, inter)\n output_tree = output_dir + \"/%s%s.tree\" % (basename, inter)\n\n\n print(param_file, output_res, output_log, output_tree)\n\n write_params_file_PQR(param_file, aln, tree,output_res, output_log, output_tree, gtr_output=gtr,\n fixed_beta=fixed_beta, fixed_s=fixed_s, fixed_ProbS = fixed_probS, init_probS=init_probS, fixed_tau=fixed_tau)\n os.system(\"%s %s\" % (path, param_file))\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"phyVirus/run_PQR.py","file_name":"run_PQR.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"138466377","text":"import numpy as np \nfrom pycloudsim.scheduler import DummyScheduler\nfrom pycloudsim.logger import logging\nlogger = logging.getLogger(__name__)\n\nclass Job(object):\n def __init__(self, job_id, arrival_timestamp, plan_cpu, plan_mem, plan_disk, duration):\n \n self.job_id = job_id\n self.arrival_timestamp = arrival_timestamp\n self.start_timestamp = None\n self.finish_timestamp = None\n self.started = False\n self.finished = False\n self.plan_cpu = plan_cpu\n self.plan_mem = plan_mem\n self.plan_disk = plan_disk\n self.duration = duration\n self.machine = None\n\n def finish(self, finish_timestamp):\n self.finish_timestamp = finish_timestamp\n self.finished = True\n logger.info(\"Job %d (arrival= %d duration=%.2f) finished at %.1f on machine %d.\"\n % (self.job_id, self.arrival_timestamp, self.duration, self.finish_timestamp, self.machine.machine_id))\n\n def start(self, start_timestamp, machine):\n self.start_timestamp = start_timestamp\n self.started = True\n self.machine = machine\n logger.info(\"Job %d (arrival= %d duration=%.2f) started at %.1f on machine %d.\"\n % (self.job_id, self.arrival_timestamp, self.duration, self.start_timestamp, self.machine.machine_id))\n\n def schedule(self, env, scheduler):\n self.scheduled_timestamp = env.now\n machine = scheduler(self)\n logger.info(\"Job %d (arrival= %d duration=%.2f) scheduled at %.1f to machine %d.\"\n % (self.job_id, self.arrival_timestamp, self.duration, self.scheduled_timestamp, machine.machine_id))\n machine.waiting_queue.append(self)\n yield machine.cpu.get(self.plan_cpu) & machine.mem.get(self.plan_mem)\n machine.waiting_queue.remove(self)\n machine.running_pool.append(self)\n self.start(env.now, machine)\n yield env.timeout(self.duration)\n yield machine.cpu.put(self.plan_cpu - np.finfo(float).eps*10) & machine.mem.put(self.plan_mem - np.finfo(float).eps*10)\n machine.running_pool.remove(self)\n self.finish(env.now)\n\n @property\n def delay(self):\n return self.start_timestamp - self.create_timestamp\n\nclass Batch(object):\n \"\"\"docstring for Batch\"\"\"\n def __init__(self, scheduler):\n super(Batch, self).__init__()\n self.scheduler = scheduler\n self.env = self.scheduler.sim.env\n self.batch_size = scheduler.batch_size\n self.jobs = []\n\n def __len__(self):\n return len(self.jobs)\n\n def append(self, job):\n self.jobs.append(job)\n\n def is_ready(self):\n if len(self) == self.batch_size:\n logger.info(\"Batch is ready.\")\n return True\n else:\n return False\n\n def schedule(self):\n assert len(self) == self.batch_size\n machines = self.scheduler(self.jobs)\n processes = []\n for job, machine in zip(self.jobs, machines):\n dummy_scheduler = DummyScheduler(job, machine)\n processes.append(self.env.process(job.schedule(self.env, dummy_scheduler)))\n self.jobs = []\n return processes","sub_path":"pycloudsim/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"114301751","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"This is a awesome\n python script!\"\"\"\nimport json\nimport requests\nimport time\nfrom collections import OrderedDict\nfrom pymodbus3.client.sync import ModbusTcpClient\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom time import sleep\n__author__ = \"Zsolt Laszlo\"\n__copyright__ = \"Copyright 2016\"\n__credits__ = [\"Zsolt Laszlo\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Zsolt Laszlo\"\n__email__ = \"lzsolti1970@gmail.com\"\n__status__ = \"Development\"\n\nclass ModbusClient:\n def __init__(self, **kwargs):\n\n self.host = kwargs['host']\n self.port = kwargs['port']\n self.connection = ModbusTcpClient(self.host, self.port)\n\n def read_registers(self, **kwargs):\n\n response = self.connection.read_holding_registers(kwargs['address'], kwargs['count'])\n register = response.registers\n return register\n\n def read_coils(self, **kwargs):\n\n response = self.connection.read_coils(kwargs['address'], kwargs['count'])\n coils = response.bits\n return coils\n\nfor i in range (0, 59):\n\n hiba_uzenet = \"\"\n args = {\"host\": \"192.168.100.100\", \"port\": 503}\n args3 = {\"address\": 16, \"count\": 9}\n\n mb2 = ModbusClient(**args)\n eredmeny_coils = mb2.read_coils(**args3)\n\n mb2.connection.close()\n print(eredmeny_coils)\n\n High_gas_concentration = \"Shutdown\tVysoká koncentrace plynu-vypnutí!\"\n Low_suction_pressure = \"Nízký sací tlak\"\n High_suction_pressure = \"Vysoký sací tlak\"\n High_gas_concentration = \"Vysoká koncetrace plynu-alarm\"\n High_gas_temperature = \"Vysoká teplota plynu\"\n High_outlet_pressure = \"Vysoký výstupní tlak\"\n Low_oil_pressure = \"Nízký tlak oleje\"\n High_oil_pressure = \"Vysoký tlak oleje\"\n Stopped_by_emergency_button = \"Vypnutí havarijním STOP tlačítkem\"\n\n if eredmeny_coils[0] == True:\n hiba_uzenet = Low_oil_pressure\n if eredmeny_coils[1] == True:\n hiba_uzenet = High_oil_pressure\n if eredmeny_coils[2] == True:\n hiba_uzenet = Low_suction_pressure\n if eredmeny_coils[3] == True:\n hiba_uzenet = High_gas_concentration\n if eredmeny_coils[4] == True:\n hiba_uzenet = High_gas_temperature\n if eredmeny_coils[5] == True:\n hiba_uzenet = High_suction_pressure\n if eredmeny_coils[6] == True:\n hiba_uzenet = Stopped_by_emergency_button\n if eredmeny_coils[7] == True:\n hiba_uzenet = High_outlet_pressure\n\n print(eredmeny_coils[6])\n for i in range(0, len(eredmeny_coils)):\n if eredmeny_coils[i] == True:\n server = smtplib.SMTP('smtp.seznam.cz', 25)\n server.starttls()\n server.login(\"cng.ceska.trebova@email.cz\", \"cng100CT\")\n\n # msg = \"Hello! Zsolti\" # The /n separates the message from the headers\n fromaddr = \"cng.ceska.trebova@email.cz\"\n toaddr = \"info@adastengineering.cz\"\n msg = MIMEMultipart()\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = \"Compressor error!\"\n body = hiba_uzenet\n msg.attach(MIMEText(body, 'plain'))\n text = msg.as_string()\n server.sendmail(fromaddr, toaddr, text)\n print(hiba_uzenet)\n print(\"OK\")\n exit()\n\n sleep(1)\n\n\n\n#server = smtplib.SMTP('smtp.gmail.com', 25)\n#server.starttls()\n#server.login(\"lzsolti1970\", \"1970vernice0801\")\n","sub_path":"imi_mail.py","file_name":"imi_mail.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"613827331","text":"__author__ = 'jonhall'\n#\n## Get Current Invoices\n## Place APIKEY & Username in config.ini\n## or pass via commandline (example: GetNewInvoices.py -u=userid -k=apikey)\n##\n\nimport sys, getopt, socket, SoftLayer, json, string, configparser, os, argparse\n\ndef initializeSoftLayerAPI():\n ## READ CommandLine Arguments and load configuration file\n parser = argparse.ArgumentParser(description=\"Show powerstate of Virtual Servers.\")\n parser.add_argument(\"-u\", \"--username\", help=\"SoftLayer API Username\")\n parser.add_argument(\"-k\", \"--apikey\", help=\"SoftLayer APIKEY\")\n parser.add_argument(\"-c\", \"--config\", help=\"config.ini file to load\")\n\n args = parser.parse_args()\n\n if args.config != None:\n filename=args.config\n else:\n filename=\"config.ini\"\n\n if (os.path.isfile(filename) is True) and (args.username == None and args.apikey == None):\n ## Read APIKEY from configuration file\n config = configparser.ConfigParser()\n config.read(filename)\n client = SoftLayer.Client(username=config['api']['username'], api_key=config['api']['apikey'])\n else:\n ## Read APIKEY from commandline arguments\n if args.username == None and args.apikey == None:\n print (\"You must specify a username and APIkey to use.\")\n quit()\n if args.username == None:\n print (\"You must specify a username with your APIKEY.\")\n quit()\n if args.apikey == None:\n print(\"You must specify a APIKEY with the username.\")\n quit()\n client = SoftLayer.Client(username=args.username, api_key=args.apikey)\n\n return client\n\n#\n# Get APIKEY from config.ini & initialize SoftLayer API\n#\n\n\nclient = initializeSoftLayerAPI()\n\ndatacenter = input (\"Datacenter? \")\n\nvirtualServers = client['Account'].getVirtualGuests(mask='id,hostname,datacenter.name,powerState',\n filter={'virtualGuests': {'datacenter': {'name': {'operation': datacenter}}}})\n\nprint ('{:<10} {:<20} {:<15}'.format(\"ID\", \"Hostname\", \"PowerState\"))\nprint ('{:<10} {:<20} {:<15}'.format(\"==========\", \"================\", \"=================\"))\n\nfor server in virtualServers:\n print(\"{:<10} {:<20} {:<15}\".format(server['id'], server['hostname'], server['powerState']['name']))\n\n\n","sub_path":"VirtualServers/ShowVirtualServerPowerState.py","file_name":"ShowVirtualServerPowerState.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"300858292","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom API.views import *\nfrom API.web_view import *\n\nurlpatterns = [\n url(r'^update_location_and_parameters/', update_location_and_parameters),\n url(r'^update_stop_location/', update_stop_location),\n url(r'^get_bus_data_current_time/', get_bus_data_current_time),\n url(r'^get_bus_data_from_time/', get_bus_data_from_time),\n url(r'^web/get_bus_locations/', get_bus_location_ajax),\n url(r'^web/marker_update/', marker_update),\n url(r'^web/get_fuel_data/', get_fuel_data),\n url(r'^get_bus_data_user/', get_bus_data_from_user),\n url(r'^get_stop_data_from_time/', get_stop_data_from_time),\n\n url(r'^update_status/', update_status),\n\n url(r'^get_json_from_csv/', get_json_from_csv),\n\n url(r'^get_bus_location_from_time/', get_bus_location_from_time),\n url(r'^get_all_bus_data/',get_all_bus_data),\n]\n\n","sub_path":"API/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"521821509","text":"'''\nGiven an array of integers and an integer k, you need to find the number of unique k-diff\nparis in the array. Here a k-diff pair is defined as an integer pair (i,j), where i and\nj are both numbers in the array and their absolute difference is k.\n\n\nExample 1:\nInput: [3, 1, 4, 1, 5], k = 2\nOutput: 2\nExplanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number of unique pairs.\n\n\nExample 2:\nInput:[1, 2, 3, 4, 5], k = 1\nOutput: 4\nExplanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\n\n\nExample 3:\nInput: [1, 3, 1, 5, 4], k = 0\nOutput: 1\nExplanation: There is one 0-diff pair in the array, (1, 1).\n'''\n\nimport collections\n\nclass Solution:\n\n def find_pairs(self, nums, k):\n\n res = 0\n c = collections.Counter(nums)\n\n\n for i in c:\n # first condition checks that there is the absolute difference if k > 1\n # second condition checks that when k == 0, check if there are same elements\n if k > 0 and i + k in c or k == 0 and c[i] > 1:\n res += 1\n\n return res\n","sub_path":"gs/k_diff_pairs_in_array.py","file_name":"k_diff_pairs_in_array.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"544770037","text":"import datetime\n\nfrom django.contrib.auth.models import AnonymousUser, User\nfrom django.core import serializers\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase, RequestFactory, Client\nfrom django.utils import timezone\nfrom . import views\nfrom .models import Vote, Question\n\n\n# checking that users can login to polls page or as an anonymous user\nclass SimpleTest(TestCase):\n def setUp(self):\n # Every test needs access to the request factory.\n self.factory = RequestFactory()\n self.user = User.objects.create_user(username='None', email='none@none.com', password='letmein1')\n\n def test_details(self):\n # Create an instance of a GET request.\n request = self.factory.get('/accounts/login')\n\n # Recall that middleware are not supported. You can simulate a\n # logged-in user by setting request.user manually.\n request.user = self.user\n\n # Or you can simulate an anonymous user by setting request.user to\n # an AnonymousUser instance.\n request.user = AnonymousUser()\n\n # Test my_view() as if it were deployed at /customer/details\n response = views(request)\n # Use this syntax for class-based views.\n response = views.as_view()(request)\n self.assertEqual(response.status_code, 200)\n\ndef create_question(question_text, days):\n \"\"\"\n Creates a question with the given `question_text` and published the\n given number of `days` offset to now (negative for questions published\n in the past, positive for questions that have yet to be published).\n \"\"\"\n time = timezone.now() + datetime.timedelta(days=days)\n return Question.objects.create(question_text=question_text, pub_date=time)\n\n\n# checking to see if people can add past or future questions to a poll\nclass QuestionMethodTests(TestCase):\n\n def test_was_published_recently_with_future_question(self):\n \"\"\"\n was_published_recently() should return False for questions whose\n pub_date is in the future.\n \"\"\"\n time = timezone.now() + datetime.timedelta(days=30)\n future_question = Question(pub_date=time)\n self.assertEqual(future_question.was_published_recently(), False)\n\n def test_was_published_recently_with_old_question(self):\n \"\"\"\n was_published_recently() should return False for questions whose\n pub_date is older than 1 day.\n \"\"\"\n time = timezone.now() - datetime.timedelta(days=30)\n old_question = Question(pub_date=time)\n self.assertEqual(old_question.was_published_recently(), False)\n\n def test_was_published_recently_with_recent_question(self):\n \"\"\"\n was_published_recently() should return True for questions whose\n pub_date is within the last day.\n \"\"\"\n time = timezone.now() - datetime.timedelta(hours=1)\n recent_question = Question(pub_date=time)\n self.assertEqual(recent_question.was_published_recently(), True)\n\n\n# checking to see if polls can be added with no questions,\n# past or future questions in the list of questions\nclass QuestionViewTests(TestCase):\n\n def test_index_view_with_no_questions(self):\n \"\"\"\n If no questions exist, an appropriate message should be displayed.\n \"\"\"\n response = self.client.get(reverse('polls:index'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"No polls are available.\")\n self.assertQuerysetEqual(response.context['latest_question_list'], [])\n\n def test_index_view_with_a_past_question(self):\n \"\"\"\n Questions with a pub_date in the past should be displayed on the\n index page.\n \"\"\"\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(reverse('polls:index'))\n self.assertQuerysetEqual(response.context['latest_question_list'], [''])\n\n def test_index_view_with_a_future_question(self):\n \"\"\"\n Questions with a pub_date in the future should not be displayed on\n the index page.\n \"\"\"\n create_question(question_text=\"Future question.\", days=30)\n response = self.client.get(reverse('polls:index'))\n self.assertContains(response, \"No polls are available.\", status_code=200)\n self.assertQuerysetEqual(response.context['latest_question_list'], [])\n\n def test_index_view_with_future_question_and_past_question(self):\n \"\"\"\n Even if both past and future questions exist, only past questions\n should be displayed.\n \"\"\"\n create_question(question_text=\"Past question.\", days=-30)\n create_question(question_text=\"Future question.\", days=30)\n response = self.client.get(reverse('polls:index'))\n self.assertQuerysetEqual(response.context['latest_question_list'], [''])\n\n def test_index_view_with_two_past_questions(self):\n \"\"\"\n The questions index page may display multiple questions.\n \"\"\"\n create_question(question_text=\"Past question 1.\", days=-30)\n create_question(question_text=\"Past question 2.\", days=-5)\n response = self.client.get(reverse('polls:index'))\n self.assertQuerysetEqual(response.context['latest_question_list'],['',''])\n\n\n# checking to see if selecting invalid question types return appropriate status codes\nclass QuestionIndexDetailTests(TestCase):\n\n def test_detail_view_with_a_future_question(self):\n \"\"\"\n The detail view of a question with a pub_date in the future should\n return a 404 not found.\n \"\"\"\n future_question = create_question(question_text='Future question.', days=5)\n response = self.client.get(reverse('polls:detail', args=(future_question.id,)))\n self.assertEqual(response.status_code, 404)\n\n def test_detail_view_with_a_past_question(self):\n \"\"\"\n The detail view of a question with a pub_date in the past should\n display the question's text.\n \"\"\"\n past_question = create_question(question_text='Past Question.', days=-5)\n response = self.client.get(reverse('polls:detail', args=(past_question.id,)))\n self.assertContains(response, past_question.question_text, status_code=200)\n\n\n# checking to see if selecting no questions return appropriate status code\nclass QuestionResultsDetailTests(TestCase):\n\n def test_detail_view_with_nothing_selected(self, question=None, request=None):\n \"\"\"\n The detail view of a question with a choice\n not selected should return a 404 not found\n \"\"\"\n selected_choice = question.choice_set.get(pk=request.POST['choice'])\n response = self.client.get(reverse('polls:detail', args=selected_choice.id))\n self.assertEqual(response.status_code, 404)\n\n\n# checking to see if valid votes, and invalid votes with missing polls/choices can be posted\nclass PollTest(TestCase):\n\n def test_ajax_vote(self):\n\n c = Client()\n\n # Extra parameters to make this a Ajax style request.\n kwargs = {'HTTP_X_REQUESTED_WITH':'XMLHttpRequest'}\n\n # A valid vote\n response = c.post('/polls/1/vote/', {'choice': '1',}, **kwargs)\n # self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content, '1')\n\n # A invalid vote - choice doesn't exist\n response = c.post('/polls/1/vote/', {'choice': '10',}, **kwargs)\n self.assertEqual(response.status_code, 404)\n self.assertEqual(response.content, '0')\n\n # An invalid vote - poll doesn't exist\n response = c.post('/polls/2/vote/', {'choice': '1',}, **kwargs)\n self.assertEqual(response.status_code, 404)\n\n\n# check to see if choices selected in votes work and can be posted\nclass ApiViewsSerializerTest (TestCase):\n def test_serializer(self):\n # Stuff to serialize\n Vote(name='yes').save()\n Vote(name='no').save()\n\n # Expected output\n expect_api = \\\n 'myapi.vote:\\n' \\\n ' 1: {name: yes}\\n' \\\n ' 2: {name: no}\\n'\n\n # Do the serialization\n actual_vote = serializers.serialize('vote', Vote.objects.all())\n\n # Did it work?\n self.assertEqual(actual_vote)\n","sub_path":"polls/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"283588118","text":"\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nmy_scalar = tf.placeholder('float32')\n\nscalar_squared = my_scalar ** 2\n\n# A derivative of a scalar_squared by my_scalar\nderivative = tf.gradients(scalar_squared, [my_scalar,])\ns = tf.InteractiveSession()\n\nx = np.linspace(-3,3)\n\nx_squared, x_squared_der = s.run([scalar_squared, derivative[0]], {my_scalar: x})\n\nprint(x_squared, x_squared_der)\n\n\n# Now plot the two lists \n\nplt.figure(1)\nplt.plot(x, x_squared, label = \"$x^2$\")\n\nplt.plot(x, x_squared_der, label = r\"$\\frac{dx^2}{dx}$\")\n\nplt.title(\"X Squared and its Derivative\")\nplt.legend()\n\nplt.show()\n\nmy_vector = tf.placeholder('float32', [None])\n# Compute the gradient of the next weird function over my_scalar and my_vector\n# Warning! Trying to understand the meaning of that function may result in permanent brain damage\nweird_psychotic_function = tf.reduce_mean(\n (my_vector+my_scalar)**(1+tf.nn.moments(my_vector,[0])[1]) + \n 1./ tf.atan(my_scalar))/(my_scalar**2 + 1) + 0.01*tf.sin(\n 2*my_scalar**1.5)*(tf.reduce_sum(my_vector)* my_scalar**2\n )*tf.exp((my_scalar-4)**2)/(\n 1+tf.exp((my_scalar-4)**2))*(1.-(tf.exp(-(my_scalar-4)**2)\n )/(1+tf.exp(-(my_scalar-4)**2)))**2\n\nder_by_scalar = tf.gradients(weird_psychotic_function, my_scalar)\nder_by_vector = tf.gradients(weird_psychotic_function, my_vector)\n\n# Plotting the derivative\nscalar_space = np.linspace(1, 7, 100)\n\ny = [s.run(weird_psychotic_function, {my_scalar:x, my_vector:[1, 2, 3]})\n for x in scalar_space]\n\nplt.figure(2)\n\nplt.plot(scalar_space, y, label='function')\n\ny_der_by_scalar = [s.run(der_by_scalar,\n {my_scalar:x, my_vector:[1, 2, 3]})\n for x in scalar_space]\nplt.plot(scalar_space, y_der_by_scalar, label='derivative')\nplt.grid()\nplt.legend();\nplt.show()\n\n''' Notes\nLearn:\nmatplotlib animation and rc\nmatplotlib_utils\nhow pyplot.subplots() works\n\nnp.meshgrid(x_var, y_var) ---> \n\n\n\n'''\n\n\n\n\n\n\n\n\n\n","sub_path":"tfpractice.py","file_name":"tfpractice.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"440925950","text":"### Configuration\n########################################################################################################\n# System Path Insert\nimport sys\nsys.path.insert(1, 'D:/complaint_labeling_neural_net/src')\n\n# Python Module Imports\nfrom collections import Counter\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport sklearn\nimport time\n\n# Tensorflow / Keras Modules\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dropout, Flatten, Dense, Activation, BatchNormalization, SpatialDropout1D\nfrom tensorflow.keras.layers import Add, ZeroPadding2D, AveragePooling2D, GaussianNoise, SeparableConv2D, Embedding, Bidirectional, LSTM\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.layers import add\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.callbacks import LearningRateScheduler, ReduceLROnPlateau\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.python.client import device_lib\nfrom tensorflow.keras.utils import multi_gpu_model\n\n# Project Modules\nimport configuration as config\nimport text_processing as tp\nimport misc_functions as mf\n \n\n### File Reading\n########################################################################################################\n# Read Csv File from CFPB\ncomplaint_df = pd.read_csv(config.config_complaints_file, encoding = config.config_complaints_file_encoding)\ncomplaint_df = complaint_df[complaint_df[config.config_complaints_narrative_column].notna()]\ncomplaint_df['Product_Issue'] = complaint_df['Product'] + ' | ' + complaint_df['Issue']\ncomplaint_df = complaint_df[complaint_df.Product_Issue.isin(config.config_product_issue_list)].\\\ndrop_duplicates(subset = config.config_complaints_narrative_column, keep = 'first')\n\n# Split into Train & Test\ntrain_df, test_df = sklearn.model_selection.train_test_split(complaint_df, test_size = 0.2, random_state = 11172020)\n\n\n\n### Process & Write Files: Checking\n########################################################################################################\n# Y Variables\ntrain_df_checking = train_df[train_df.Product == 'Checking or savings account']\ntest_df_checking = test_df[test_df.Product == 'Checking or savings account']\n\none_hot_dict_checking = mf.one_hot_label_dict(train_df_checking['Issue'])\ntrain_y_checking= np.array([one_hot_dict_checking.get(x) for x in train_df_checking['Issue']])\ntest_y_checking = np.array([one_hot_dict_checking.get(x) for x in test_df_checking['Issue']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df_checking[config.config_complaints_narrative_column],\n test_string_list = test_df_checking[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_checking)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_checking = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_checking = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_checking, train_sequences_checking)\nnp.save(config.config_test_x_save_name_checking, test_sequences_checking)\nnp.save(config.config_train_y_save_name_checking, train_y_checking)\nnp.save(config.config_test_y_save_name_checking, test_y_checking)\n\n\n\n### Process & Write Files: Card\n########################################################################################################\n# Y Variables\ntrain_df_card = train_df[train_df.Product == 'Credit card or prepaid card']\ntest_df_card = test_df[test_df.Product == 'Credit card or prepaid card']\n\none_hot_dict_card = mf.one_hot_label_dict(train_df_card['Issue'])\ntrain_y_card= np.array([one_hot_dict_card.get(x) for x in train_df_card['Issue']])\ntest_y_card = np.array([one_hot_dict_card.get(x) for x in test_df_card['Issue']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df_card[config.config_complaints_narrative_column],\n test_string_list = test_df_card[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_card)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_card = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_card = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_card, train_sequences_card)\nnp.save(config.config_test_x_save_name_card, test_sequences_card)\nnp.save(config.config_train_y_save_name_card, train_y_card)\nnp.save(config.config_test_y_save_name_card, test_y_card)\n\n\n\n### Process & Write Files: Credit Reporting\n########################################################################################################\n# Y Variables\ntrain_df_cr = train_df[train_df.Product == 'Credit reporting, credit repair services, or other personal consumer reports']\ntest_df_cr = test_df[test_df.Product == 'Credit reporting, credit repair services, or other personal consumer reports']\n\none_hot_dict_cr = mf.one_hot_label_dict(train_df_cr['Issue'])\ntrain_y_cr= np.array([one_hot_dict_cr.get(x) for x in train_df_cr['Issue']])\ntest_y_cr = np.array([one_hot_dict_cr.get(x) for x in test_df_cr['Issue']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df_cr[config.config_complaints_narrative_column],\n test_string_list = test_df_cr[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_cr)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_cr = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_cr = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_cr, train_sequences_cr)\nnp.save(config.config_test_x_save_name_cr, test_sequences_cr)\nnp.save(config.config_train_y_save_name_cr, train_y_cr)\nnp.save(config.config_test_y_save_name_cr, test_y_cr)\n\n\n\n### Process & Write Files: Debt Collection\n########################################################################################################\n# Y Variables\ntrain_df_dc = train_df[train_df.Product == 'Debt collection']\ntest_df_dc = test_df[test_df.Product == 'Debt collection']\n\none_hot_dict_dc = mf.one_hot_label_dict(train_df_dc['Issue'])\ntrain_y_dc= np.array([one_hot_dict_dc.get(x) for x in train_df_dc['Issue']])\ntest_y_dc = np.array([one_hot_dict_dc.get(x) for x in test_df_dc['Issue']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df_dc[config.config_complaints_narrative_column],\n test_string_list = test_df_dc[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_dc)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_dc = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_dc = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_dc, train_sequences_dc)\nnp.save(config.config_test_x_save_name_dc, test_sequences_dc)\nnp.save(config.config_train_y_save_name_dc, train_y_dc)\nnp.save(config.config_test_y_save_name_dc, test_y_dc)\n\n\n\n### Process & Write Files: Student Loan\n########################################################################################################\n# Y Variables\ntrain_df_sl = train_df[train_df.Product == 'Student loan']\ntest_df_sl = test_df[test_df.Product == 'Student loan']\n\none_hot_dict_sl = mf.one_hot_label_dict(train_df_sl['Issue'])\ntrain_y_sl= np.array([one_hot_dict_sl.get(x) for x in train_df_sl['Issue']])\ntest_y_sl = np.array([one_hot_dict_sl.get(x) for x in test_df_sl['Issue']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df_sl[config.config_complaints_narrative_column],\n test_string_list = test_df_sl[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_sl)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_sl = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_sl = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_sl, train_sequences_sl)\nnp.save(config.config_test_x_save_name_sl, test_sequences_sl)\nnp.save(config.config_train_y_save_name_sl, train_y_sl)\nnp.save(config.config_test_y_save_name_sl, test_y_sl)\n\n\n\n### Process & Write Files: Product\n########################################################################################################\n# Y Variables\none_hot_dict_product = mf.one_hot_label_dict(complaint_df['Product'])\ntrain_y_product = np.array([one_hot_dict_product.get(x) for x in train_df['Product']])\ntest_y_product = np.array([one_hot_dict_product.get(x) for x in test_df['Product']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df[config.config_complaints_narrative_column],\n test_string_list = test_df[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_product)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_product = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_product = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_product, train_sequences_product)\nnp.save(config.config_test_x_save_name_product, test_sequences_product)\nnp.save(config.config_train_y_save_name_product, train_y_product)\nnp.save(config.config_test_y_save_name_product, test_y_product)\n\n\n\n### Process & Write Files: Product and Issue\n########################################################################################################\n# Y Variables\none_hot_dict = mf.one_hot_label_dict(train_df['Product_Issue'])\ntrain_y_product_issue = np.array([one_hot_dict.get(x) for x in train_df['Product_Issue']])\ntest_y_product_issue = np.array([one_hot_dict.get(x) for x in test_df['Product_Issue']])\n\n# X Variables\npipeline = tp.TextProcessingPipeline(string_list = train_df[config.config_complaints_narrative_column],\n test_string_list = test_df[config.config_complaints_narrative_column],\n save_token_name = config.config_tokenizer_save_name_product_issue)\n\npipeline.tokenizer_fit_and_save()\ntrain_sequences_product_issue = pipeline.tokenizer_load_and_transform_train()\ntest_sequences_product_issue = pipeline.tokenizer_load_and_transform_test()\nnp.save(config.config_train_x_save_name_product_issue, train_sequences_product_issue)\nnp.save(config.config_test_x_save_name_product_issue, test_sequences_product_issue)\nnp.save(config.config_train_y_save_name_product_issue, train_y_product_issue)\nnp.save(config.config_test_y_save_name_product_issue, test_y_product_issue)\n","sub_path":"process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":11094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"292917698","text":"#!/usr/bin/env python3\n\"\"\"\nA class to control workflow and temporarily store and manipulate data\n\"\"\"\nimport os\nimport obspy\nimport pyflex\nimport warnings\nimport pyadjoint\nfrom obspy.signal.filter import envelope\n\nfrom pyatoa import logger\nfrom pyatoa.core.config import Config\nfrom pyatoa.core.gatherer import Gatherer, GathererNoDataException\nfrom pyatoa.utils.form import channel_code\nfrom pyatoa.utils.process import is_preprocessed\nfrom pyatoa.utils.asdf.load import load_windows, load_adjsrcs\nfrom pyatoa.utils.window import reject_on_global_amplitude_ratio\nfrom pyatoa.utils.srcrcv import gcd_and_baz\nfrom pyatoa.utils.asdf.add import add_misfit_windows, add_adjoint_sources\nfrom pyatoa.utils.process import (default_process, trim_streams, zero_pad,\n match_npts)\n\nfrom pyatoa.visuals.mgmt_plot import ManagerPlotter\n\n\nclass ManagerError(Exception):\n \"\"\"\n A class-wide custom exception raised when functions fail gracefully\n \"\"\"\n pass\n\n\nclass ManagerStats(dict):\n \"\"\"\n A simple dictionary that can get and set keys as attributes and has a \n cleaner looking print statement, used for storing internal statistics\n in the Manager class\n \"\"\"\n def __init__(self):\n self.dataset_id = None \n self.event_id = None \n self.inv_name = None \n self.nwin = 0\n self.len_obs = 0\n self.len_syn = 0 \n self.misfit = 0\n self.half_dur = 0\n self.time_offset_sec = 0\n self.standardized = False \n self.obs_processed = False\n self.syn_processed = False\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __getattr__(self, key):\n return self[key] \n\n def __str__(self):\n str_ = \"\"\n for key, value in self.items():\n str_ += f\"{key:>15}: {value}\\n\"\n return str_[:-1]\n\n\nclass Manager:\n \"\"\"\n Pyatoas core workflow object.\n\n Manager is the central workflow control object. It calls on mid and\n low level classes to gather data, standardize and preprocess stream objects,\n generate misfit windows, and calculate adjoint sources. Has a variety of\n internal sanity checks to ensure that the workflow stays on the rails.\n \"\"\"\n def __init__(self, config=None, ds=None, event=None, st_obs=None,\n st_syn=None, inv=None, windows=None, staltas=None,\n adjsrcs=None, gcd=None, baz=None, gatherer=None):\n \"\"\"\n Initiate the Manager class with or without pre-defined attributes.\n\n .. note::\n If `ds` is not given in data can only be gathered via the\n config.paths attribute or using the ObsPy client service.\n Data will also not be saved.\n\n :type config: pyatoa.core.config.Config\n :param config: configuration object that contains necessary parameters\n to run through the Pyatoa workflow\n :type ds: pyasdf.asdf_data_set.ASDFDataSet\n :param ds: ASDF data set from which to read and write data\n :type event: obspy.core.event.Event\n :param event: An event object containing relevant earthquake information\n :type st_obs: obspy.core.stream.Stream\n :param st_obs: Stream object containing waveforms of observations\n :type st_syn: obspy.core.stream.Stream\n :param st_syn: Stream object containing waveforms of observations\n :type inv: obspy.core.inventory.Inventory\n :param inv: Inventory that should only contain the station of interest,\n it's relevant channels, and response information\n :type windows: dict of pyflex.Window objects\n :param windows: misfit windows calculated by Pyflex, stored in a\n dictionary based on component naming\n :type adjsrcs: dict of pyadjoint.AdjointSource objects\n :param adjsrcs: adjoint source waveforms stored in dictionaries\n :type gcd: float\n :param gcd: great circle distance between source and receiver in km\n :type baz: float\n :param baz: Backazimuth between source and receiver in units of degrees\n :type gatherer: pyatoa.core.gatherer.Gatherer\n :param gatherer: A previously instantiated Gatherer class.\n Should not have to be passed in by User, but is used for reset()\n \"\"\"\n self.ds = ds\n self.inv = inv\n\n # Instantiate a Config object\n if config is not None:\n self.config = config\n else:\n logger.info(\"no config provided, initiating default\")\n self.config = Config()\n\n # Ensure any user-provided event is an Event object\n if isinstance(event, obspy.core.event.catalog.Catalog):\n logger.info(f\"event given as catalog, taking zeroth entry\")\n event = event[0]\n self.event = event\n\n # Try to get origin time information from the event\n if self.event is not None:\n origintime = self.event.preferred_origin().time\n else:\n origintime = None\n\n # Instantiate a Gatherer object and pass along info\n if gatherer is None:\n self.gatherer = Gatherer(config=self.config, ds=self.ds,\n origintime=origintime)\n else:\n self.gatherer = gatherer\n\n # Copy Streams to avoid affecting original data\n if st_obs is not None:\n self.st_obs = st_obs.copy()\n else:\n self.st_obs = None\n if st_syn is not None:\n self.st_syn = st_syn.copy()\n else:\n self.st_syn = None\n\n # Data produced by the workflow\n self.gcd = gcd\n self.baz = baz\n self.windows = windows\n self.staltas = staltas or {}\n self.adjsrcs = adjsrcs\n self.rejwins = {}\n\n # Internal statistics to keep track of the workflow progress\n self.stats = ManagerStats()\n\n # Run internal checks on data\n self.check()\n\n def __str__(self):\n \"\"\"\n Print statement shows available data detailing workflow\n \"\"\"\n self.check()\n return (\"Manager Data\\n\"\n f\" dataset [ds]: {self.stats.dataset_id}\\n\"\n f\" quakeml [event]: {self.stats.event_id}\\n\"\n f\" station [inv]: {self.stats.inv_name}\\n\"\n f\" observed [st_obs]: {self.stats.len_obs}\\n\"\n f\" synthetic [st_syn]: {self.stats.len_syn}\\n\"\n \"Stats & Status\\n\" \n f\" half_dur: {self.stats.half_dur}\\n\"\n f\" time_offset_sec: {self.stats.time_offset_sec}\\n\"\n f\" standardized: {self.stats.standardized}\\n\"\n f\" obs_processed: {self.stats.obs_processed}\\n\"\n f\" syn_processed: {self.stats.syn_processed}\\n\"\n f\" nwin [windows]: {self.stats.nwin}\\n\"\n f\" misfit [adjsrcs]: {self.stats.misfit:.2E}\\n\"\n )\n\n def __repr__(self):\n return self.__str__()\n\n @property\n def st(self):\n \"\"\"\n Return all streams available in Class\n \"\"\"\n if isinstance(self.st_syn, obspy.Stream) and \\\n isinstance(self.st_obs, obspy.Stream):\n return self.st_syn + self.st_obs\n elif isinstance(self.st_syn, obspy.Stream) and \\\n not isinstance(self.st_obs, obspy.Stream):\n return self.st_syn\n elif isinstance(self.st_obs, obspy.Stream) and \\\n not isinstance(self.st_syn, obspy.Stream):\n return self.st_obs\n else:\n return None\n\n def check(self):\n \"\"\"\n (Re)check the stats of the workflow and data within the Manager.\n\n Rechecks conditions whenever called, incase something has gone awry\n mid-workflow. Stats should only be set by this function.\n \"\"\"\n # Give dataset filename if available\n if self.stats.dataset_id is None and self.ds is not None:\n self.stats.dataset_id = os.path.basename(self.ds.filename)\n\n # Determine the resource identifier for the Event object\n if self.stats.event_id is None and self.event is not None:\n self.stats.event_id = self.event.resource_id\n\n # Get the network and station name from the Inventory object\n if self.stats.inv_name is None and self.inv is not None:\n self.stats.inv_name = \".\".join([self.inv[0].code,\n self.inv[0][0].code])\n\n # Check if waveforms are Stream objects, and if preprocessed\n if self.st_obs is not None:\n self.stats.len_obs = len(self.st_obs)\n self.stats.obs_processed = is_preprocessed(self.st_obs)\n if self.stats.len_obs > len(self.config.component_list):\n logger.warning(\"More observed traces than listed components, \"\n \"this may need to be reviewed manually\")\n\n if self.st_syn is not None:\n self.stats.len_syn = len(self.st_syn)\n self.stats.syn_processed = is_preprocessed(self.st_syn)\n if self.stats.len_syn > len(self.config.component_list):\n logger.warning(\"More synthetic traces than listed components, \"\n \"this may need to be reviewed manually\")\n\n # Check standardization by comparing waveforms against the first\n if not self.stats.standardized and self.st_obs and self.st_syn:\n for tr in self.st[1:]:\n for atr in [\"sampling_rate\", \"npts\", \"starttime\"]:\n if getattr(tr.stats, atr) != getattr(self.st[0].stats, atr):\n break\n break\n else:\n self.stats.standardized = True\n\n # Check for half duration used for source-time-function with synthetics\n if self.stats.half_dur is None and self.event is not None:\n try:\n mt = self.event.preferred_focal_mechanism().moment_tensor\n self.stats.half_dur = mt.source_time_function.duration / 2\n except AttributeError:\n pass\n\n # Count how many misfit windows are contained in the dataset\n if self.stats.nwin == 0 and self.windows is not None:\n self.stats.nwin = sum([len(_) for _ in self.windows.values()])\n\n # Determine the unscaled misfit\n if not self.stats.misfit and self.adjsrcs is not None:\n self.stats.misfit = sum([_.misfit for _ in self.adjsrcs.values()])\n\n def reset(self):\n \"\"\"\n Restart workflow by deleting all collected data in the Manager, but\n retain dataset, event, config, and gatherer so a new station can be\n processed with the same configuration as the previous workflow.\n \"\"\"\n self.__init__(ds=self.ds, event=self.event, config=self.config,\n gatherer=self.gatherer)\n\n def write(self, write_to=\"ds\"):\n \"\"\"\n Write the data collected inside Manager to either a Pyasdf Dataset,\n or to individual files (not implemented).\n\n :type write_to: str\n :param write_to: choice to write data to, if \"ds\" writes to a\n pyasdf.asdf_data_set.ASDFDataSet\n\n * write_to == \"ds\":\n If gather is skipped but data should still be saved into an\n ASDFDataSet for data storage, this function will\n fill that dataset in the same fashion as the Gatherer class\n * write_to == \"/path/to/output\":\n write out all the internal data of the manager to a path\n \"\"\"\n if write_to == \"ds\":\n if self.event:\n try:\n self.ds.add_quakeml(self.event)\n except ValueError:\n logger.warning(\"Event already present, not added\")\n if self.inv:\n try:\n self.ds.add_stationxml(self.inv)\n except TypeError:\n logger.warning(\"StationXML already present, not added\")\n # PyASDF has its own warnings if waveform data already present\n if self.st_obs:\n self.ds.add_waveforms(waveform=self.st_obs,\n tag=self.config.observed_tag)\n if self.st_syn:\n self.ds.add_waveforms(waveform=self.st_syn,\n tag=self.config.synthetic_tag)\n if self.windows:\n self.save_windows()\n if self.adjsrcs:\n self.save_adjsrcs()\n else:\n raise NotImplementedError\n\n def write_adjsrcs(self, path=\"./\", write_blanks=True):\n \"\"\"\n Write internally stored adjoint source traces into SPECFEM3D defined\n two-column ascii files. Filenames are based on what is expected by\n Specfem, that is: 'NN.SSS.CCC.adj'\n\n ..note::\n By default writes adjoint sources for ALL components if one\n component has an adjoint source. If an adjoint sourced doesn't exist\n for a given component, it will be written with zeros. This is to\n satisfy SPECFEM3D requirements.\n\n :type path: str\n :param path: path to save the\n :type write_blanks: bool\n :param write_blanks: write zeroed out adjoint sources for components\n with no adjoint sources to meet the requirements of SPECFEM3D.\n defaults to True\n \"\"\"\n from copy import deepcopy\n\n assert(self.adjsrcs is not None), f\"No adjoint sources to write\"\n\n for adj in self.adjsrcs.values():\n fid = f\"{adj.network}.{adj.station}.{adj.component}.adj\"\n adj.write(filename=os.path.join(path, fid), format=\"SPECFEM\",\n time_offset=self.stats.time_offset_sec\n )\n if write_blanks:\n # To see if any blank adjoint sources required, check the difference\n # between internal component list and components with adjsrcs\n # Assumed here that everything is in upper case\n blank_comps = list(\n set(self.config.component_list).difference(\n set(self.adjsrcs.keys()))\n )\n if blank_comps:\n # Deep copy so that zeroing data doesn't affect original data\n blank_adj = deepcopy(adj)\n blank_adj.adjoint_source *= 0\n for comp in blank_comps:\n new_adj_comp = f\"{adj.component[:-1]}{comp}\"\n fid = f\"{adj.network}.{adj.station}.{new_adj_comp}.adj\"\n blank_adj.write(filename=os.path.join(path, fid),\n format=\"SPECFEM\",\n time_offset=self.stats.time_offset_sec\n )\n\n def load(self, code, path=None, ds=None, synthetic_tag=None,\n observed_tag=None, config=True, windows=False,\n adjsrcs=False):\n \"\"\"\n Populate the manager using a previously populated ASDFDataSet.\n Useful for re-instantiating an existing workflow that has already \n gathered data and saved it to an ASDFDataSet.\n\n .. warning::\n Loading any floating point values may result in rounding errors.\n Be careful to round off floating points to the correct place before\n using in future work.\n\n :type code: str\n :param code: SEED conv. code, e.g. NZ.BFZ.10.HHZ\n :type path: str\n :param path: if no Config object is given during init, the User\n can specify the config path here to load data from the dataset.\n This skips the need to initiate a separate Config object.\n :type ds: None or pyasdf.asdf_data_set.ASDFDataSet\n :param ds: dataset can be given to load from, will not set the ds\n :type synthetic_tag: str\n :param synthetic_tag: waveform tag of the synthetic data in the dataset\n e.g. 'synthetic_m00s00'. If None given, will use `config` attribute.\n :type observed_tag: str\n :param observed_tag: waveform tag of the observed data in the dataset\n e.g. 'observed'. If None given, will use `config` attribute.\n :type config: bool\n :param config: load config from the dataset, defaults to True but\n can be set False if Config should be instantiated by the User\n :type windows: bool\n :param windows: load misfit windows from the dataset, defaults to False\n :type adjsrcs: bool\n :param adjsrcs: load adjoint sources from the dataset, defaults to False\n \"\"\"\n # Allows a ds to be provided outside the attribute\n if self.ds and ds is None:\n ds = self.ds\n else:\n raise TypeError(\"load requires a Dataset\")\n\n # If no Config object in Manager, try to load from dataset\n if config:\n if path is None:\n raise TypeError(\"load requires valid 'path' argument\")\n logger.info(f\"loading config from dataset {path}\")\n try:\n self.config = Config(ds=ds, path=path)\n except AttributeError:\n logger.warning(f\"No Config object in dataset for path {path}\")\n\n assert(self.config is not None), \"Config object required for load\"\n assert len(code.split('.')) == 2, \"'code' must be in form 'NN.SSS'\"\n if windows or adjsrcs:\n assert(path is not None), \"'path' required to load auxiliary data\"\n iter_, step = path.split(\"/\")\n\n # Reset and populate using the dataset\n self.__init__(config=self.config, ds=ds, event=ds.events[0])\n net, sta = code.split('.')\n sta_tag = f\"{net}.{sta}\"\n if sta_tag in ds.waveforms.list():\n self.inv = ds.waveforms[sta_tag].StationXML\n self.st_syn = ds.waveforms[sta_tag][synthetic_tag or\n self.config.synthetic_tag]\n self.st_obs = ds.waveforms[sta_tag][observed_tag or\n self.config.observed_tag]\n if windows:\n self.windows = load_windows(ds, net, sta, iter_, step, False)\n if adjsrcs:\n self.adjsrcs = load_adjsrcs(ds, net, sta, iter_, step)\n else:\n logger.warning(f\"no data for {sta_tag} found in dataset\")\n\n self.check()\n return self\n\n def flow(self, **kwargs):\n \"\"\"\n A convenience function to run the full workflow with a single command.\n Does not include gathering. Takes kwargs related to all underlying\n functions.\n\n .. code:: python\n\n mgmt = Manager()\n mgmt.flow() == mgmt.standardize().preprocess().window().measure()\n\n :raises ManagerError: for any controlled exceptions\n \"\"\"\n force = kwargs.get(\"force\", False)\n standardize_to = kwargs.get(\"standardize_to\", \"syn\")\n fix_windows = kwargs.get(\"fix_windows\", False)\n iteration = kwargs.get(\"iteration\", None)\n step_count = kwargs.get(\"step_count\", None)\n overwrite = kwargs.get(\"overwrite\", None)\n which = kwargs.get(\"which\", \"both\")\n save = kwargs.get(\"save\", True)\n\n self.standardize(standardize_to=standardize_to, force=force)\n self.preprocess(overwrite=overwrite, which=which, **kwargs)\n self.window(fix_windows=fix_windows, iteration=iteration,\n step_count=step_count, force=force, save=save)\n self.measure(force=force, save=save)\n\n def gather(self, code=None, choice=None, **kwargs):\n \"\"\"\n Gather station dataless and waveform data using the Gatherer class.\n In order collect observed waveforms, dataless, and finally synthetics.\n\n For valid kwargs see methods in :doc:`core.gatherer`\n\n :type code: str\n :param code: Station code following SEED naming convention.\n This must be in the form NN.SSSS.LL.CCC (N=network, S=station,\n L=location, C=channel). Allows for wildcard naming. By default\n the pyatoa workflow wants three orthogonal components in the N/E/Z\n coordinate system. Example station code: NZ.OPRZ.10.HH?\n :type choice: list\n :param choice: allows user to gather individual bits of data, rather\n than gathering all. Allowed: 'inv', 'st_obs', 'st_syn'\n :raises ManagerError: if any part of the gathering fails.\n\n Keyword Arguments\n ::\n bool try_fm:\n Try to retrieve and append focal mechanism information to the\n Event object.\n str station_level:\n The level of the station metadata if retrieved using the ObsPy\n Client. Defaults to 'response'\n str resp_dir_template:\n Directory structure template to search for response files.\n By default follows the SEED convention:\n 'path/to/RESPONSE/{sta}.{net}/'\n str resp_fid_template:\n Response file naming template to search for station dataless.\n By default, follows the SEED convention\n 'RESP.{net}.{sta}.{loc}.{cha}'\n str obs_dir_template:\n directory structure to search for observation data. Follows the\n SEED convention: 'path/to/obs_data/{year}/{net}/{sta}/{cha}'\n str obs_fid_template:\n File naming template to search for observation data. Follows the\n SEED convention: '{net}.{sta}.{loc}.{cha}*{year}.{jday:0>3}'\n str syn_cfgpath:\n Config.cfgpaths key to search for synthetic data. Defaults to\n 'synthetics', but for the may need to be set to 'waveforms' in\n certain use-cases, e.g. synthetics-synthetic inversions.\n str syn_unit:\n Optional argument to specify the letter used to identify the\n units of the synthetic data: For Specfem3D: [\"d\", \"v\", \"a\", \"?\"]\n 'd' for displacement, 'v' for velocity, 'a' for acceleration.\n Wildcards okay. Defaults to '?'\n str syn_dir_template:\n Directory structure template to search for synthetic waveforms.\n Defaults to empty string\n str syn_fid_template:\n The naming template of synthetic waveforms defaults to:\n \"{net}.{sta}.*{cmp}.sem{syn_unit}\"\n \"\"\"\n try_fm = kwargs.get(\"try_fm\", True)\n\n # Default to gathering all data\n if choice is None:\n choice = [\"event\", \"inv\", \"st_obs\", \"st_syn\"]\n try:\n # Attempt to gather event information before waveforms/metadata\n if \"event\" in choice and self.event is None:\n if self.config.event_id is not None:\n self.event = self.gatherer.gather_event(try_fm=try_fm)\n if code is not None:\n logger.info(f\"gathering data for {code}\")\n if \"st_obs\" in choice:\n # Ensure observed waveforms gathered before synthetics and\n # metadata. If this fails, no point to gathering the rest\n self.st_obs = self.gatherer.gather_observed(code, **kwargs)\n if \"inv\" in choice:\n self.inv = self.gatherer.gather_station(code, **kwargs)\n if \"st_syn\" in choice:\n self.st_syn = self.gatherer.gather_synthetic(code, **kwargs)\n\n return self\n except GathererNoDataException as e:\n # Catch the Gatherer exception and redirect as ManagerError \n # so that it can be caught by flow()\n raise ManagerError(\"Data Gatherer could not find some data\") from e\n except Exception as e:\n # Gathering should be robust, but if something slips through, dont\n # let it kill a workflow, display and raise ManagerError\n logger.warning(e, exc_info=True)\n raise ManagerError(\"Uncontrolled error in data gathering\") from e\n\n def standardize(self, force=False, standardize_to=\"syn\"):\n \"\"\"\n Standardize the observed and synthetic traces in place. \n Ensures Streams have the same starttime, endtime, sampling rate, npts.\n\n :type force: bool\n :param force: allow the User to force the function to run even if checks\n say that the two Streams are already standardized\n :type standardize_to: str\n :param standardize_to: allows User to set which Stream conforms to which\n by default the Observed traces should conform to the Synthetic ones\n because exports to Specfem should be controlled by the Synthetic\n sampling rate, npts, etc.\n \"\"\"\n self.check()\n if not self.stats.len_obs or not self.stats.len_syn:\n raise ManagerError(\"cannot standardize, not enough waveform data\")\n elif self.stats.standardized and not force:\n logger.info(\"data already standardized\")\n return self\n logger.info(\"standardizing streams\")\n\n # If observations starttime after synthetic, zero pad the front of obs\n dt_st = self.st_obs[0].stats.starttime - self.st_syn[0].stats.starttime\n if dt_st > 0:\n self.st_obs = zero_pad(self.st_obs, dt_st, before=True, after=False)\n\n # Match sampling rates\n if standardize_to == \"syn\":\n self.st_obs.resample(self.st_syn[0].stats.sampling_rate)\n else:\n self.st_syn.resample(self.st_obs[0].stats.sampling_rate)\n\n # Match start and endtimes\n self.st_obs, self.st_syn = trim_streams(\n st_a=self.st_obs, st_b=self.st_syn,\n force={\"obs\": \"a\", \"syn\": \"b\"}[standardize_to]\n )\n\n # Match the number of samples \n self.st_obs, self.st_syn = match_npts(\n st_a=self.st_obs, st_b=self.st_syn,\n force={\"obs\": \"a\", \"syn\": \"b\"}[standardize_to]\n )\n\n # Determine if synthetics start before the origintime\n if self.event is not None:\n self.stats.time_offset_sec = (self.st_syn[0].stats.starttime -\n self.event.preferred_origin().time\n )\n logger.debug(f\"time offset is {self.stats.time_offset_sec}s\")\n else:\n self.stats.time_offset_sec = 0\n\n self.stats.standardized = True\n\n return self\n\n def preprocess(self, which=\"both\", overwrite=None, **kwargs):\n \"\"\"\n Preprocess observed and synthetic waveforms in place.\n Default preprocessing tasks: Remove response (observed), rotate, filter,\n convolve with source time function (synthetic).\n\n .. note::\n Default preprocessing can be overwritten using a\n user-defined function that takes Manager and choice as inputs\n and outputs an ObsPy Stream object.\n\n .. note::\n Documented kwargs only apply to default preprocessing.\n\n :type which: str\n :param which: \"obs\", \"syn\" or \"both\" to choose which stream to process\n defaults to both\n :type overwrite: function\n :param overwrite: If a function is provided, it will overwrite the \n standard preprocessing function. All arguments that are given\n to the standard preprocessing function will be passed as kwargs to\n the new function. This allows for customized preprocessing\n\n Keyword Arguments\n ::\n int water_level:\n water level for response removal\n float taper_percentage:\n amount to taper ends of waveform\n bool remove_response:\n remove instrument response using the Manager's inventory object.\n Defaults to True\n bool apply_filter:\n filter the waveforms using the Config's min_period and\n max_period parameters. Defaults to True\n bool convolve_with_stf:\n Convolve synthetic data with a Gaussian source time function if\n a half duration is provided.\n \"\"\"\n if not self.inv and not self.config.synthetics_only:\n raise ManagerError(\"cannot preprocess, no inventory\")\n if overwrite:\n assert(hasattr(overwrite, '__call__')), \"overwrite must be function\"\n preproc_fx = overwrite\n else:\n preproc_fx = default_process\n\n # If required, will rotate based on source receiver lat/lon values\n if self.config.rotate_to_rtz:\n if not self.inv:\n logger.warning(\"cannot rotate components, no inventory\")\n else:\n self.gcd, self.baz = gcd_and_baz(event=self.event,\n sta=self.inv[0][0])\n\n # Preprocess observation waveforms\n if self.st_obs is not None and not self.stats.obs_processed and \\\n which.lower() in [\"obs\", \"both\"]:\n logger.info(\"preprocessing observation data\")\n self.st_obs = preproc_fx(self, choice=\"obs\", **kwargs)\n self.stats.obs_processed = True\n\n # Preprocess synthetic waveforms\n if self.st_syn is not None and not self.stats.syn_processed and \\\n which.lower() in [\"syn\", \"both\"]:\n logger.info(\"preprocessing synthetic data\")\n self.st_syn = preproc_fx(self, choice=\"syn\", **kwargs)\n self.stats.syn_processed = True\n\n # Set stats\n self.stats.len_obs = len(self.st_obs)\n self.stats.len_syn = len(self.st_syn)\n\n return self\n\n def window(self, fix_windows=False, iteration=None, step_count=None,\n force=False, save=True):\n \"\"\"\n Evaluate misfit windows using Pyflex. Save windows to ASDFDataSet.\n Allows previously defined windows to be retrieved from ASDFDataSet.\n\n .. note::\n * Windows are stored as dictionaries of pyflex.Window objects.\n * All windows are saved into the ASDFDataSet, even if retrieved.\n * STA/LTA information is collected and stored internally.\n\n :type fix_windows: bool\n :param fix_windows: do not pick new windows, but load windows from the\n given dataset from 'iteration' and 'step_count'\n :type iteration: int or str\n :param iteration: if 'fix_windows' is True, look for windows in this\n iteration. If None, will check the latest iteration/step_count\n in the given dataset\n :type step_count: int or str\n :param step_count: if 'fix_windows' is True, look for windows in this\n step_count. If None, will check the latest iteration/step_count\n in the given dataset\n :type force: bool\n :param force: ignore flag checks and run function, useful if e.g.\n external preprocessing is used that doesn't meet flag criteria\n :type save: bool\n :param save: save the gathered windows to an ASDF Dataset\n \"\"\"\n # Pre-check to see if data has already been standardized\n self.check()\n\n if not self.stats.standardized and not force:\n raise ManagerError(\"cannot window, waveforms not standardized\")\n\n # Determine how to treat fixed windows\n if fix_windows and not self.ds:\n logger.warning(\"cannot fix window, no dataset\")\n fix_windows = False\n elif fix_windows and (iteration is None or step_count is None):\n # If no iteration/step_count values are given, automatically search\n # the previous step_count for windows in relation to the current\n # iteration/step_count\n iteration = self.config.iteration\n step_count = self.config.step_count\n return_previous = True\n else:\n # If fix windows and iteration/step_count are given, search the\n # dataset for windows under the current iteration/step_count\n return_previous = False\n\n # Synthetic STA/LTA as Pyflex WindowSelector.calculate_preliminaries()\n for comp in self.config.component_list:\n try:\n self.staltas[comp] = pyflex.stalta.sta_lta(\n data=envelope(self.st_syn.select(component=comp)[0].data),\n dt=self.st_syn.select(component=comp)[0].stats.delta,\n min_period=self.config.min_period\n )\n except IndexError:\n continue\n\n # Find misfit windows, from a dataset or through window selection\n if fix_windows:\n self.retrieve_windows(iteration, step_count, return_previous)\n else:\n self.select_windows_plus()\n\n if save:\n self.save_windows()\n logger.info(f\"{self.stats.nwin} window(s) total found\")\n\n return self\n\n def retrieve_windows(self, iteration, step_count, return_previous):\n \"\"\"\n Mid-level window selection function that retrieves windows from a \n PyASDF Dataset, recalculates window criteria, and attaches window \n information to Manager. No access to rejected window information.\n\n :type iteration: int or str\n :param iteration: retrieve windows from the given iteration\n :type step_count: int or str\n :param step_count: retrieve windows from the given step count\n in the given dataset\n :type return_previous: bool\n :param return_previous: if True: return windows from the previous\n step count in relation to the given iteration/step_count.\n if False: return windows from the given iteration/step_count\n \"\"\"\n logger.info(f\"retrieving windows from dataset\")\n\n net, sta, _, _ = self.st_obs[0].get_id().split(\".\")\n # Function will return empty dictionary if no acceptable windows found\n windows = load_windows(ds=self.ds, net=net, sta=sta,\n iteration=iteration, step_count=step_count,\n return_previous=return_previous\n )\n\n # Recalculate window criteria for new values for cc, tshift, dlnA etc...\n logger.debug(\"recalculating window criteria\")\n for comp, windows_ in windows.items():\n try:\n d = self.st_obs.select(component=comp)[0].data\n s = self.st_syn.select(component=comp)[0].data\n for w, win in enumerate(windows_):\n # Post the old and new values to the logger for sanity check\n logger.debug(f\"{comp}{w}_old - \"\n f\"cc:{win.max_cc_value:.2f} / \"\n f\"dt:{win.cc_shift:.1f} / \"\n f\"dlnA:{win.dlnA:.2f}\")\n win._calc_criteria(d, s)\n logger.debug(f\"{comp}{w}_new - \"\n f\"cc:{win.max_cc_value:.2f} / \"\n f\"dt:{win.cc_shift:.1f} / \"\n f\"dlnA:{win.dlnA:.2f}\")\n # IndexError thrown when trying to access an empty Stream\n except IndexError:\n continue\n\n self.windows = windows\n self.stats.nwin = sum(len(_) for _ in self.windows.values())\n\n def select_windows_plus(self):\n \"\"\"\n Mid-level custom window selection function that calls Pyflex select \n windows, but includes additional window suppression functionality.\n Includes custom Pyflex addition of outputting rejected windows, which\n will be used internally for plotting.\n\n .. note::\n Pyflex will throw a ValueError if the arrival of the P-wave\n is too close to the initial portion of the waveform, considered the\n 'noise' section. This happens for short source-receiver distances\n (< 100km).\n\n This error becomes a PyflexError if no event/station attributes\n are provided to the WindowSelector\n\n We could potentially deal with this by zero-padding the\n waveforms, and running select_windows() again, but for now we just\n raise a ManagerError and allow processing to continue\n \"\"\"\n logger.info(f\"running Pyflex w/ map: {self.config.pyflex_preset}\")\n\n nwin, window_dict, reject_dict = 0, {}, {}\n for comp in self.config.component_list:\n try:\n obs = self.st_obs.select(component=comp)[0]\n syn = self.st_syn.select(component=comp)[0]\n # IndexError thrown when trying to access an empty Stream\n except IndexError:\n continue\n\n # Pyflex throws a TauP warning from ObsPy #2280, ignore that\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", UserWarning)\n ws = pyflex.WindowSelector(observed=obs, synthetic=syn,\n config=self.config.pyflex_config,\n event=self.event,\n station=self.inv)\n try:\n windows = ws.select_windows()\n except (IndexError, pyflex.PyflexError):\n # see docstring note for why this error is to be addressed\n raise ManagerError(\"Cannot window, most likely because \"\n \"the source-receiver distance is too \"\n \"small w.r.t the minimum period\")\n\n # Suppress windows that contain low-amplitude signals\n if self.config.win_amp_ratio > 0:\n windows, ws.rejects[\"amplitude\"] = \\\n reject_on_global_amplitude_ratio(\n data=obs.data, windows=windows,\n ratio=self.config.win_amp_ratio\n )\n # ==================================================================\n # NOTE: Additional windowing criteria may be added here if necessary\n # ==================================================================\n if windows:\n window_dict[comp] = windows\n if ws.rejects:\n reject_dict[comp] = ws.rejects\n\n # Count windows and tell User\n logger.info(f\"{len(windows)} window(s) selected for comp {comp}\")\n nwin += len(windows)\n\n self.windows = window_dict\n self.rejwins = reject_dict\n self.stats.nwin = nwin\n\n def measure(self, force=False, save=True):\n \"\"\"\n Measure misfit and calculate adjoint sources using PyAdjoint.\n\n Method for caluculating misfit set in Config, Pyadjoint expects\n standardized traces with the same spectral content, so this function\n will not run unless these flags are passed.\n\n Returns a dictionary of adjoint sources based on component.\n Saves resultant dictionary to a pyasdf dataset if given.\n\n .. note::\n Pyadjoint returns an unscaled misfit value for an entire set of\n windows. To return a \"total misfit\" value as defined by \n Tape (2010) Eq. 6, the total summed misfit will need to be scaled by \n the number of misfit windows chosen in Manager.window().\n\n :type force: bool\n :param force: ignore flag checks and run function, useful if e.g.\n external preprocessing is used that doesn't meet flag criteria\n :type save: bool\n :param save: save adjoint sources to ASDFDataSet\n \"\"\"\n self.check()\n\n # Check that data has been filtered and standardized\n if not self.stats.standardized and not force:\n raise ManagerError(\"cannot measure misfit, not standardized\")\n elif not (self.stats.obs_processed and self.stats.syn_processed) \\\n and not force:\n raise ManagerError(\"cannot measure misfit, not filtered\")\n elif not self.stats.nwin and not force:\n raise ManagerError(\"cannot measure misfit, no windows\")\n logger.debug(f\"running Pyadjoint w/ type: {self.config.adj_src_type}\")\n\n # Create list of windows needed for Pyadjoint\n adjoint_windows = self._format_windows()\n\n # Run Pyadjoint to retrieve adjoint source objects\n total_misfit, adjoint_sources = 0, {}\n for comp, adj_win in adjoint_windows.items():\n try:\n adj_src = pyadjoint.calculate_adjoint_source(\n adj_src_type=self.config.adj_src_type,\n config=self.config.pyadjoint_config,\n observed=self.st_obs.select(component=comp)[0],\n synthetic=self.st_syn.select(component=comp)[0],\n window=adj_win, plot=False\n )\n\n # Re-format component name to reflect SPECFEM convention\n adj_src.component = f\"{channel_code(adj_src.dt)}X{comp}\"\n\n # Save adjoint sources in dictionary object. Sum total misfit\n adjoint_sources[comp] = adj_src\n logger.info(f\"{adj_src.misfit:.3f} misfit for comp {comp}\")\n total_misfit += adj_src.misfit\n except IndexError:\n continue\n\n # Save adjoint source internally and to dataset\n self.adjsrcs = adjoint_sources\n if save:\n self.save_adjsrcs()\n\n # Run check to get total misfit\n self.check()\n logger.info(f\"total misfit {self.stats.misfit:.3f}\")\n\n return self\n\n def save_windows(self):\n \"\"\"\n Convenience function to save collected misfit windows into an \n ASDFDataSet with some preliminary checks\n\n Auxiliary data tag is hardcoded as 'MisfitWindows'\n \"\"\"\n if self.ds is None:\n logger.warning(\"Manager has no ASDFDataSet, cannot save windows\")\n elif not self.windows:\n logger.warning(\"Manager has no windows to save\")\n elif not self.config.save_to_ds:\n logger.warning(\"config parameter save_to_ds is set False, \"\n \"will not save windows\")\n else:\n logger.debug(\"saving misfit windows to ASDFDataSet\")\n add_misfit_windows(self.windows, self.ds, path=self.config.aux_path)\n\n def save_adjsrcs(self):\n \"\"\"\n Convenience function to save collected adjoint sources into an \n ASDFDataSet with some preliminary checks\n\n Auxiliary data tag is hardcoded as 'AdjointSources' \n \"\"\"\n if self.ds is None:\n logger.warning(\"Manager has no ASDFDataSet, cannot save \"\n \"adjoint sources\")\n elif not self.adjsrcs:\n logger.warning(\"Manager has no adjoint sources to save\")\n elif not self.config.save_to_ds:\n logger.warning(\"config parameter save_to_ds is set False, \"\n \"will not save adjoint sources\")\n else:\n logger.debug(\"saving adjoint sources to ASDFDataSet\")\n add_adjoint_sources(adjsrcs=self.adjsrcs, ds=self.ds,\n path=self.config.aux_path,\n time_offset=self.stats.time_offset_sec)\n\n def _format_windows(self):\n \"\"\"\n .. note::\n In `pyadjoint.calculate_adjoint_source`, the window needs to be a\n list of lists, with each list containing the\n [left_window, right_window]; each window argument should be given in\n units of time (seconds). This is not in the PyAdjoint docs.\n\n :rtype: dict of list of lists\n :return: dictionary with key related to individual components,\n and corresponding to a list of lists containing window start and end\n \"\"\"\n adjoint_windows = {}\n if self.windows is not None:\n for comp, window in self.windows.items():\n adjoint_windows[comp] = []\n # Prepare Pyflex window indices to give to Pyadjoint\n for win in window:\n adj_win = [win.left * self.st_obs[0].stats.delta,\n win.right * self.st_obs[0].stats.delta]\n adjoint_windows[comp].append(adj_win)\n # If no windows given, calculate adjoint source on whole trace\n else:\n logger.debug(\"no windows given, adjoint sources will be \"\n \"calculated on full trace\")\n for comp in self.config.component_list:\n adjoint_windows[comp] = [[0, self.st_obs.select(\n component=comp)[0].stats.npts]]\n\n return adjoint_windows\n\n def plot(self, choice=\"both\", save=None, show=True, corners=None, **kwargs):\n \"\"\"\n Plot observed and synthetics waveforms, misfit windows, STA/LTA and\n adjoint sources for all available components. Append information\n about misfit, windows and window selection. Also as subplot create a\n source receiver map which contains annotated information detailing\n src-rcv relationship like distance and BAz. Options to plot either or.\n\n For valid key word arguments see `visuals.manager_plotter` and\n `visuals.map_maker`\n\n :type show: bool\n :param show: show the plot once generated, defaults to False\n :type save: str\n :param save: absolute filepath and filename if figure should be saved\n :param corners: {lat_min, lat_max, lon_min, lon_max}\n corners to cut the map to, otherwise a global map is provided\n :type choice: str\n :param choice: choice for what to plot:\n\n * 'wav': plot waveform figure only\n * 'map': plot a source-receiver map only\n * 'both' (default): plot waveform and source-receiver map together\n \"\"\"\n self.check()\n # Precheck for correct data to plot\n if choice in [\"wav\", \"both\"] and not self.stats.standardized:\n raise ManagerError(\"cannot plot, waveforms not standardized\")\n\n if choice in [\"map\", \"both\"] and (self.inv is None or\n self.event is None):\n raise ManagerError(\"cannot plot map, no event and/or inv found\")\n\n mp = ManagerPlotter(mgmt=self)\n if choice == \"wav\":\n mp.plot_wav(show=show, save=save, **kwargs)\n elif choice == \"map\":\n mp.plot_map(corners=corners, show=show, save=save, **kwargs)\n elif choice == \"both\":\n mp.plot(corners=corners, show=show, save=save, **kwargs)\n\n\n","sub_path":"pyatoa/core/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":47032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"153457125","text":"class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n # 最优子结构\n # 重复子问题\n # 无后效性\n # 多重背包\n # 举例子\n dp = [0 for i in range(target+1)]\n dp[0] = 1 \n for j in range(1, target+1):\n for i in range(len(nums)):\n if j - nums[i] < 0:\n continue\n dp[j] += dp[j - nums[i]]\n return dp[-1]","sub_path":"2020_02_08/biss_377.py","file_name":"biss_377.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"138350623","text":"import urllib.request\nimport json\nurl = \"http://challenge.validatis.com:7000/\"\nresponse = urllib.request.urlopen(url)\ndata = json.loads(response.read().decode('utf8'))\n\ndef factorize(d, prime_number):\n count = 0;\n while d % prime_number == 0:\n count += 1\n d = d // prime_number\n return count\n\ndef factorization(d, prime_list):\n result = []\n for pn in prime_list:\n result.append(factorize(d, pn))\n return result\n\ndef check_valid(value, num_list):\n result = []\n for index1 in range(len(num_list)):\n if num_list[index1] == value:\n result.append(index1)\n return result\n\ndef check_valid_with_possibility(value, num_list, probable):\n result = []\n for index1 in range(len(num_list)):\n if num_list[index1] == value and probable[index1]:\n result.append(index1)\n return result\n\ndef solve(instance):\n numbers_string = instance['numbers_string']\n possible = [True] * len(numbers_string)\n primes = instance['primes']\n # answer = instance['solution_factorization']\n\n for i in range(len(numbers_string)):\n numbers_string[i] = int(numbers_string[i])\n\n factorization_matrix = []\n for i in numbers_string:\n factorization_matrix.append(factorization(i, primes))\n\n # matrix2 = []\n # for i in range(len(primes)):\n # column = []\n # for j in range(len(factorization_matrix)):\n # column.append(factorization_matrix[j][i])\n # matrix2.append(column)\n matrix2 = list(zip(*factorization_matrix))\n for i in range(len(matrix2)):\n matrix2[i] = list(matrix2[i])\n\n # first round\n for i in range(0, len(primes) - 1):\n # i don't know the result\n for j in range(len(matrix2[i])):\n if not possible[j]:\n continue\n indices_2 = check_valid_with_possibility(matrix2[i][j], matrix2[i], possible)\n if len(indices_2) == 1:\n possible[j] = False\n # but i'm sure that other guys don't know either\n for j in range(len(matrix2[i])):\n if not possible[j]:\n continue\n should_mark_false = False\n for k in range(i + 1, len(primes)):\n if len(check_valid(matrix2[k][j], matrix2[k])) == 1:\n should_mark_false = True\n break\n if should_mark_false:\n possible[j] = False\n # for target in check_valid(matrix2[i][j], matrix2[i]):\n # excluded_count += 1\n # possible[target] = False\n\n # second round\n possible_set = []\n for i in range(len(possible)):\n if possible[i]:\n possible_set.append(factorization_matrix[i])\n\n transpose = list(zip(*possible_set))\n for i in range(len(transpose)):\n transpose[i] = list(transpose[i])\n possible2 = [True] * len(possible_set)\n for i in reversed(range(len(primes))):\n for j in range(len(transpose[i])):\n target_list = check_valid_with_possibility(transpose[i][j], transpose[i], possible2)\n if len(target_list) > 1:\n for target in target_list:\n possible2[target] = False\n\n # print('solution', answer)\n correct_index_list = []\n for i in range(len(possible2)):\n if possible2[i]:\n correct_index_list.append(i)\n\n assert len(correct_index_list) == 1\n print('solution', possible_set[correct_index_list[0]])\n print('seed', instance['seed'])\n\nsolve(data['problem'])\n","sub_path":"quality/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"66533192","text":"# coding=utf-8\n\n\"\"\"\nPygment lexer for `USE OCL`_.\n\n.. _`USE OCL`:\n https://sourceforge.net/projects/useocl/\n\"\"\"\n\nfrom pygments.lexer import RegexLexer, words\nfrom pygments.token import *\n\n\nclass UseOCLLexer(RegexLexer):\n \"\"\"\n Lexer for Structured Query Language. Currently, this lexer does\n not recognize any special syntax except ANSI SQL.\n \"\"\"\n\n name = 'useocl'\n aliases = ['useocl']\n filenames = ['*.use','*.soil', '*.con']\n mimetypes = ['text/x-useocl']\n\n tokens = {\n 'root': [\n (r'\\s+', Text),\n (r'--.*?\\n', Comment.Single),\n (r'/\\*', Comment.Multiline, 'multiline-comments'),\n\n (words((\n 'abstract','aggregation','association','associationclass','begin',\n 'class','composition','constraints','context','end','enum',\n 'model',\n 'operations',\n 'statemachines'\n ), suffix=r'\\b'),\n Keyword.Declaration),\n\n (words((\n 'attributes','between',\n 'derived','do','else','endif','enum',\n 'for','if','in','init','inv','let',\n 'ordered','post','pre','psm','qualifier','redefines','role',\n 'states','subsets','then','transitions'\n ), suffix=r'\\b'),\n Keyword.Declaration),\n\n (words((\n 'Bag','Boolean','Collection','Integer','OrderedSet','Real','Sequence','Set','String','TupleType'\n ), suffix=r'\\b'),\n Keyword.Type),\n\n (words((\n 'Tuple','allInstances','and','any','append','asBag','asOrderedSet','asSequence','asSet','at',\n 'characters','closure','collecNested','collect','concat','count','div','equalsIgnoreCase','excludes',\n 'excludesAll','excluding','exists','false','first','flatten','floor','forAll','implies',\n 'includes','includesAll','including','indexOf','insertAt','intersection','isEmpty','isUnique',\n 'iterate','last','max','min','mod','not','notEmpty','oclAsType','oclIsInState','oclIsKindOf',\n 'oclIsNew','oclIsTypeOf','one','or','prepend','product','reject','reverse','result','round','select',\n 'selectByKind','selectByType','self','size','sortedBy','subOrderedSet','subSequence','substring',\n 'sum','symmetricDifference','toBoolean','toInteger','toLowerCase','toReal','toString','toUpperCase',\n 'true','union','xor'\n ), suffix=r'\\b'),\n Name.Entity),\n\n (words((\n 'ReadInteger','ReadLine','Write','WriteLine','between','create','declare','delete','destroy','from','insert','into','new'\n )),\n Keyword),\n\n # < > <= >= <> = := + * - / @ ? !\n\n (r'(->|<=|>=|<|>|<>|=|:=|\\+|\\*|-|/|@)', Name.Entity),\n ('!|\\?', Generic.Strong),\n ('\\.', Operator.Word),\n (r'[0-9]+', Number),\n (r\"'(''|[^'])*'\", String.Single),\n (r'[A-Z]\\w*', Name.Exception),\n (r'[a-z]\\w*', Name.Attribute),\n (r'[;.:|()\\[\\]{},]', Punctuation)\n ],\n 'multiline-comments': [\n (r'/\\*', Comment.Multiline, 'multiline-comments'),\n (r'\\*/', Comment.Multiline, '#pop'),\n (r'[^/*]+', Comment.Multiline),\n (r'[/*]', Comment.Multiline)\n ]\n }","sub_path":"sphinxuseocl/useocllexer.py","file_name":"useocllexer.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"161025452","text":"import random\ndef main():\n dice_rolls = int(input(\"How many dice would you like to roll?\")) \n dice_size = int(input(\"how many sides do the dice have?\"))\n\n dice_sum = 0 \n for i in range (0, dice_rolls):\n roll = random.randint(1,dice_size)\n dice_sum = dice_sum + roll\n if roll == 1:\n print(\"Ew, you have a one! Game over!\")\n break\n elif roll == dice_size:\n print(\"you have a 6! Critical success!\")\n\n else:\n print(f'You rolled a {roll} !')\n \n \n print(f'You have a sum of {dice_sum}')\n\n\nif __name__== \"__main__\":\n main()","sub_path":"dice_roller.py","file_name":"dice_roller.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"16701815","text":"#Scott Floam\n#3/28/2015\n\ndef main():\n\n\n months_names = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']\n\n rainfall = [.40, 0.94, 3.21, 3.74, 1.73, 1.03, 1.27, 2.58, 6.98, 6.90, 2.80, 2.53]\n \n rainfall_counter = len(rainfall)\n \n months_counter = len(months_names)\n\n rain_accumulator = 0\n\n highest = rainfall[0]\n \n lowest = rainfall[0]\n\n if months_counter == rainfall_counter:\n index_range = months_counter\n\n else:\n print(\"This program is not compatible with your lists\")\n \n print()\n print(\"Austin Tx Rainfall 2009\")\n print()\n for i in range (index_range):\n\n print(months_names[i],'\\t\\t',format(float(rainfall[i]),'5.2f'))\n\n rain_accumulator += float(rainfall[i])\n\n print (\"Total\",'\\t\\t',rain_accumulator)\n\n average = rain_accumulator/index_range\n\n print(\"Average\",'\\t', format(float(average),'5.2f'))\n\n\n for i in range (index_range):\n if rainfall[i] >= highest:\n highest = rainfall[i]\n print (\"Max\",'\\t\\t',format(float(highest),'5.2f'))\n\n\n for i in range (index_range):\n if rainfall[i] <= lowest:\n lowest = rainfall[i]\n print (\"Min\",'\\t\\t',format(float(lowest),'5.2f'))\n \n\nmain()\n","sub_path":"Program 13/Floam_Prog 13_Rainfall Program.py","file_name":"Floam_Prog 13_Rainfall Program.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"104528189","text":"import socket\n\nprint(\"start client\")\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\ntry:\n\ts.connect((\"192.168.136.128\",8000))\nexcept e:\n\tprint(\"connect error {0}\".format(e) )\n\nwhile True :\n\tstr = input()\n\tif str != \"\":\n\t\ts.send(str.encode('utf-8'))\n\telse:\n\t\texit(1)\n","sub_path":"pyclient.py","file_name":"pyclient.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"137313917","text":"BASEURL = 'https://recast-rest-api.herokuapp.com/'\n\n\n\nENDPOINTS = {\n 'USERS': BASEURL + 'users',\n 'RUN_CONDITIONS': BASEURL + 'run_conditions',\n 'ANALYSIS': BASEURL + 'analysis',\n 'REQUESTS': BASEURL + 'requests',\n 'POINT_REQUESTS': BASEURL + 'point_requests',\n 'PARAMETER_POINTS': BASEURL + 'parameter_points',\n 'BASIC_REQUESTS': BASEURL + 'basic_requests',\n 'FILES': BASEURL + 'request_archives',\n 'SUBSCRIPTIONS': BASEURL + 'subscriptions',\n 'RESPONSES': BASEURL + 'responses',\n 'POINT_RESPONSES': BASEURL + 'point_responses',\n 'BASIC_RESPONSES': BASEURL + 'basic_responses',\n 'HISTOGRAMS': BASEURL + 'response_archives'\n }\n\nORCID_ID = ''\nACCESS_TOKEN = ''\n\nallowed_extension = '.zip'\n","sub_path":"recastapi/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"412919423","text":"# Import necessary libraries\nimport time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\nMONTH_LIST = ['Jan',\n 'Feb',\n 'Mar',\n 'Apr',\n 'May',\n 'Jun',\n 'All']\n\nDAY_LIST = ['Mon',\n 'Tue',\n 'Wed',\n 'Thu',\n 'Fri',\n 'Sat',\n 'Sun',\n 'All']\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Let\\'s explore bikeshare data for Chicago, Washingotn and New york city!')\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n while True:\n city = input(\"Please provide city name (chicago, new york city, washington): \").lower()\n if city not in CITY_DATA:\n print('Please provide correct city name')\n continue\n else:\n break\n\n # get user input for month (all, january, february, ... , june)\n while True:\n month = input(\"Please provide month name (All, Jan, Feb.....,Jun): \").lower()\n if month not in MONTH_LIST:\n print('Sorry, please provide either correct month or all')\n continue\n else:\n break\n\n # get user input for day of week (all, monday, tuesday, ... sunday)\n while True:\n day = input(\"Please provide day of week (All, Mon...Sun): \").lower()\n if day not in DAY_LIST:\n print('Sorry, please privde either all or a day name')\n continue\n else:\n break\n\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # Loading data file as dataframe :df\n df = pd.read_csv(CITY_DATA[city])\n # Convert to date time format\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['End Time'] = pd.to_datetime(df['End Time'])\n\n #Parsing month week name and hour from the start time\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] =df['Start Time'].dt.weekday_name\n df['hour'] = df['Start Time'].dt.hour\n\n # when applicable filter by month\n if month !='all':\n month = MONTH_LIST.index(month) + 1\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week\n if day !='all':\n # filter by day to create new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n common_month = df['month'].mode()[0]\n print('The most common month of travel is:', common_month)\n\n\n # display the most common day of week\n common_day = df['day_of_week'].mode()[0]\n print('The most frequent day of travel is:', common_day)\n\n\n # display the most common start hour\n common_hour = df['hour'].mode()[0]\n print('The most frequent hour of travel is:', common_hour)\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n start_station = df['Start Station'].mode().values[0]\n print('The most commonly used start station is:', start_station)\n\n\n # display most commonly used end station\n end_station = df['End Station'].mode().values[0]\n print('The most Commonly used end station is:', end_station)\n\n\n # display most frequent combination of start station and end station trip\n df['routes'] = df['Start Station']+ \" \" + df['End Station']\n\n comb_start_end_station = df['routes'].mode().values[0]\n\n print(\"The most commonly used combination of both start station and end station trip is: {}\".format(df['routes'].mode().values[0]))\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n total_travel_time = df['Trip Duration'].sum()\n print('Total travel time for the passengers is:', total_travel_time/86400, \" Days\")\n\n\n # display mean travel time\n avg_trvl_time = df['Trip Duration'].mean()\n print('Mean travel time for the passengers is:', avg_trvl_time/60, \" Minutes\")\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_type = df['User Type'].value_counts()\n print('\\nThe counts of bikeshare user by types is:\\n', user_type)\n\n\n # Display counts of gender\n try:\n gender_type = df['Gender'].value_counts()\n print('\\nThe counts of bikeshare user by gender is:\\n', gender_type)\n except KeyError:\n print(\"Gender Types:\\nNo data for gender is available for this month.\")\n\n\n # Display earliest, most recent, and most common year of birth\n try:\n Earliest_Year = df['Birth Year'].min()\n print('Earliest year of birth is:', Earliest_Year)\n except KeyError:\n print(\"\\nEarliest Year:\\nNo data available for this month.\")\n\n try:\n Most_Recent_Year = df['Birth Year'].max()\n print('Most Recent year of birth is:', Most_Recent_Year)\n except KeyError:\n print(\"\\nMost Recent Year:\\nNo data available for this month.\")\n\n try:\n Most_Common_Year = df['Birth Year'].value_counts().idxmax()\n print('Most Common year of birth is :', Most_Common_Year)\n except KeyError:\n print(\"\\nMost Common Year:\\nNo data available for this month.\")\n\n\n print(\"This took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef display_raw_data(df):\n option = input('Display raw data? yes/no ').lower()\n print()\n if option=='yes':\n option=True\n elif option=='no':\n option=False\n else:\n print('Please enter a valid option')\n display_raw_data(df)\n return\n\n if option:\n while 1:\n for i in range(5):\n print(df.iloc[i])\n print()\n option = input('Would like to take a look into five more observations? yes/no ').lower()\n if option=='yes':\n continue\n elif option=='no':\n break\n else:\n print('Please enter a valid option')\n return\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n display_raw_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare_2.py","file_name":"bikeshare_2.py","file_ext":"py","file_size_in_byte":7990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"559354952","text":"#! /usr/bin/env python\n# MailChimp integration\n\nimport lyf\n\nfrom dateutil.parser import parse\t# Date parser\n\ndef main():\n\t\n\tfor list in lyf.get_mc_lists():\n\t\tprint(list.name, list.last_subscriber)\n\t\n\t\n\t#url += '/fa9410f164/members'\n\t#r = requests.get(url, auth=(user, api_key))\n\t#r.raise_for_status()\n\t#results = r.json()\n\t\n\t#for subscriber in results['members']:\n\t\t#print(subscriber['email_address'])\n\t\n\t\nif __name__ == '__main__':\n\tmain()\n","sub_path":"mailchimp.py","file_name":"mailchimp.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"502629018","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom .models import Post\n\nclass PostCreateForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = {\n 'title',\n 'picture',\n 'status',\n }\n # picture = forms.ImageField()\n def clean_picture(self):\n image = self.cleaned_data.get('picture', False)\n print(self.cleaned_data)\n if image:\n if image._size > 1 * 1024 * 1024:\n raise ValidationError(\"Image file too large ( > 1mb )\")\n return image\n else:\n raise ValidationError(\"Couldn't read uploaded image\")\n\nclass PostEditForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = {\n 'title',\n 'status',\n }\n\nclass UserLoginForm(forms.Form):\n username = forms.CharField(label=\"\")\n password = forms.CharField(label=\"\", widget=forms.PasswordInput)","sub_path":"photo/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"602367047","text":"exerciseProb = [[0.891, 0.009, 0.1],\n [0.18, 0.72, 0.1],\n [0, 0, 1]]\n\nexerciseReward = [[8, 8, 0],\n [0, 0, 0],\n [0, 0, 0]]\n\n #relax| fit | unfit | dead\nrelaxProb = [[0.693, 0.297, 0.01],\n [0, 0.99, 0.01],\n [0, 0, 1 ]]\n\nrelaxReward = [[10, 10, 0],\n [5, 5, 0],\n [0, 0, 0]]\n\nq0 = [0,0,0,0,0,0]\nqn = [0,0,0,0,0,0]\niteration = 0\n\ndef main():\n global qn\n global q0\n\n while True:\n G = float (input(\"Enter G Value: 0 < G < 1 \\n\"))\n if(G>1 or G<0):\n print(\"Wrong input try again\")\n else:\n False\n break\n while True:\n n = int (input(\"Enter n Value for iterations \\n\"))\n if(n<0):\n print(\"n must be positive\\n\")\n else:\n False\n break\n\n while True:\n s = input(\"Enter state (fit, unfit or dead)\\n\")\n if(s == \"fit\" or s==\"unfit\" or s==\"dead\"):\n False\n break\n else:\n print(\"Wrong input try again\")\n\n exQN = [0,0,0]\n relaxQN = [0,0,0]\n\n for i in range(0,3):\n for j in range(0,3):\n exQN[i] = exerciseProb[i][j]*exerciseReward[i][j] + exQN[i]\n relaxQN[i] = relaxProb[i][j]*relaxReward[i][j] + relaxQN[i]\n\n\n qn = exQN + relaxQN\n for i in range(len(qn)):\n q0[i] = qn[i]\n\n decision(G,n,s)\n\ndef decision(G, n, s):\n global q0\n global qn\n global iteration\n\n if( s == \"fit\"):\n exercise = qn[0]\n relax = qn[3]\n elif (s==\"unfit\"):\n exercise = qn[1]\n relax = qn[4]\n else:\n exercise = qn[2]\n relax = qn[5]\n\n print(\"qn=\"+str(iteration) +\" exer:\"+str(exercise) + \" relax:\"+ str(relax))\n iteration = iteration+1\n\n sVal = [\"fit\", \"unfit\", \"dead\"]\n if (n>0):\n tempEx = [0,0,0]\n tempRel = [0,0,0]\n for i in range(0,3):\n for j in range(0,3):\n tempEx[i] = (exerciseProb[i][j]*Vn(sVal[j])) + tempEx[i]\n tempRel[i] = (relaxProb[i][j]*Vn(sVal[j])) + tempRel[i]\n tempEx[i] = tempEx[i]*G+q0[i]\n tempRel[i] = tempRel[i]*G+q0[i+3]\n\n for i in range(0,3):\n qn[i] = tempEx[i]\n qn[i+3] = tempRel[i]\n\n n = n-1\n decision(G, n, s)\n\ndef Vn(s):\n global qn\n\n if( s == \"fit\"):\n return max(qn[0], qn[3])\n elif (s==\"unfit\"):\n return max(qn[1],qn[4])\n else:\n return max(qn[2], qn[5])\n\n\nif __name__ == '__main__':\n main()","sub_path":"Assignment/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"457689874","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.validators import RegexValidator\n\nimport re\n# from user_profile.models import Profile\n\n\nclass ProfileManager(models.Manager):\n def my_query(self):\n from django.db import connection\n with connection.cursor() as cursor:\n cursor.execute(\"SELECT * from user_profile\")\n res_list = []\n for i in cursor.fetchall():\n res_list.append(i)\n return res_list\n\n def truncate(self):\n from django.db import connection\n with connection.cursor() as cursor:\n try:\n cursor.execute(\n f\"TRUNCATE TABLE {self.model._meta.db_table} CASCADE\")\n except Exception as e:\n raise e\n\n\nclass Profile(models.Model):\n '''\n cinema_ticket member's Profile.\n using User model of django for generaing user profile.\n\n\n '''\n gender_choices = [\n ('M', 'Male'),\n ('F', 'Female')\n ]\n\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n phone_regx = r'^9\\d{9}$'\n phone_regx = RegexValidator(regex=phone_regx, message='''shomare mobile ro \n dar format khaste shodeh vared nakardi: format dorost9xxxxxxxxx''')\n phone_number = models.CharField(validators=[phone_regx], max_length=50)\n admin = models.CharField(max_length=20, blank=True, null=True)\n gender = models.CharField(max_length=1, null=True, choices=gender_choices)\n verified_account = models.BooleanField(default=False)\n objects = ProfileManager()\n\n class Meta:\n db_table = 'user_profile'\n\n def __str__(self):\n return self.user.username\n\n def save(self, *args, **kwargs):\n phone_regx = r'^9\\d{9}$'\n if not re.match(phone_regx, self.phone_number):\n raise '''khak tu saret'''\n\n super(Profile, self).save(*args, **kwargs)\n\n\nCITY_CHOICE = [\n ('tehran', 'Tehran'),\n ('shiraz', 'Shiraz'),\n ('tabriz', 'Tabriz')\n]\n\n\nSTATE_CHOICE = [\n ('tehran', 'Tehran'),\n ('fars', 'Fars'),\n ('azarbayejan sharghi', 'Azarbayejan Sharghi')\n]\n\n\nclass Address(models.Model):\n '''\n every user can have multiple address for sending receiving ticket!\n\n\n '''\n profile = models.ForeignKey(\n Profile, related_name='address_by', on_delete=models.CASCADE)\n state = models.CharField('استان', max_length=30,\n help_text='استان', choices=STATE_CHOICE, null=True)\n city = models.CharField('شهر', max_length=30,\n help_text='شهر', choices=CITY_CHOICE)\n addr = models.CharField('آدرس', max_length=50, null=True)\n\n def __str__(self):\n return f\"{self.profile.user}-{self.id}\"\n# User.objects.bulk_create\n","sub_path":"W3/user_profile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"296955369","text":"#\n# @lc app=leetcode.cn id=433 lang=python3\n#\n# [433] 最小基因变化\n#\n\n# @lc code=start\nfrom collections import deque\nclass Solution:\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n dic = {'A':'CGT','C':'AGT','G':'ACT','T':'ACG'}\n queue = deque([(0,start)])\n while queue:\n step,word = queue.popleft()\n if word == end:\n return step\n for i,n in enumerate(word):\n for s in dic[n]:\n string = word[:i] + s + word[i+1:]\n if string in bank:\n queue.append((step+1,string))\n bank.remove(string)\n return -1\n\n\n\n \n \n\n\n\n\n\n \n# @lc code=end\n\n","sub_path":"Week_07/433.最小基因变化.py","file_name":"433.最小基因变化.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"215598456","text":"#!/usr/bin/python\n\n# Brent Doil - Project 1\n# chatserv.py [port]\n# OSU CS 372 - Fall 2017\n# C chat server that listens on port given in CL argument. \n# If connection to chat server successful, allows server to send and recv \n# messages w/ client, set server handle, and close connection\n\n\nimport sys\nimport socket\n\n#Constants in python ?!\n\n#Check port\nif len(sys.argv) != 2:\n\tprint(\"Usage: ./chatserve.py [port]\")\n\tsys.exit(1)\n\n#Set server handle\nserverHandle = ''\nwhile(len(serverHandle) > 12 or len(serverHandle) == 0):\n\tserverHandle = input(\"Please enter your server handle [12 characters or less]\\n\")\n\n#Function to send a chat message\ndef sendChat(socketConn, chat):\n\tcharSent = 0\n\twhile charSent < len(chat):\n\t\tsent = socketConn.send(chat[charSent:].encode())\n\t\tif sent == 0:\n\t\t\tsocketConn.close()\n\t\tcharSent += sent\n\n#Function to receive a chat message\ndef recChat(socketConn):\n\twhile True:\n\t\tread = ''\n\t\tread = socketConn.recv(512)\n\t\treturn read.decode()\n\n#Set port num\nport = int(sys.argv[1])\n\n#Connect and bind to socket\nsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket.bind(('', port))\n\n#Listen for a connection\nsocket.listen(1)\n\nprint(\"Waiting for a connection.\\n\")\n\n#Listening: When connected, begin send and receive loops. Quit by entering !quit.\nwhile True:\n\tsocketConn, addr = socket.accept()\n\n\t#Get client handle from client\n\tclientHandle = recChat(socketConn)\n\tprint(clientHandle + \" has connected.\\n\")\n\n\tclientCursor = clientHandle + \"> \"\n\n\t#Send server handle to client\n\tsocketConn.send(serverHandle.encode())\n\tserverCursor = serverHandle + \"> \"\n\n\twhile 1:\n\t\t#Receive, format, and print client message\n\t\trecMessage = recChat(socketConn)\n\t\tif recMessage:\n\t\t\trecMessage = recMessage.rstrip()\n\t\t\tprint(clientCursor + recMessage)\n\t\t#Format and send server message, unless \\quit\n\t\tsendMessage = input(serverCursor)\n\t\tif sendMessage == \"!quit\":\n\t\t\tprint(\"Quitting.\")\n\t\t\tbreak\n\t\tsendChat(socketConn, sendMessage)\n\n\tsocketConn.close()\n\tprint(\"Connection to client is closed\")\n\tsys.exit(0)\n\n\n","sub_path":"Networking/Program1/chatserv.py","file_name":"chatserv.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"503671988","text":"from math import pi\n\nwith open(\".nederst.dat\", \"r\") as fil:\n nederst = float(fil.read())\nwith open(\".toppavbunn.dat\", \"r\") as fil:\n toppavbunn = float(fil.read())\nwith open(\".toppavsylinder.dat\", \"r\") as fil:\n toppavsylinder = float(fil.read())\nwith open(\".x.dat\", \"r\") as fil:\n x = float(fil.read())\nwith open(\".y.dat\", \"r\") as fil:\n y = float(fil.read())\nwith open(\".sylinderradius.dat\", \"r\") as fil:\n R = float(fil.read())\nwith open(\".sylinderhoyde.dat\", \"r\") as fil:\n h = float(fil.read())\n\ntetthet = 0.9 # g/cm3\nmassepervann = 18*1.67E-24 # g/atom\nvolum = (x*y - pi*R**2)*h*1E-24 # cm3\nantall = volum*tetthet/massepervann # atomer\nantall = int(round(antall))\n\nwith open(\"./packmol_mal.inp\", \"r\") as fil:\n txt = fil.read()\n\ntxt = txt.replace(\"ZBUNN\", str(nederst))\ntxt = txt.replace(\"X\", str(x)).replace(\"Y\", str(y))\ntxt = txt.replace(\"MIDTx\", str(x/2)).replace(\"MIDTy\", str(y/2))\ntxt = txt.replace(\"ZMAKS\", str(toppavbunn))\ntxt = txt.replace(\"VANNBUNN\", str(toppavbunn))\ntxt = txt.replace(\"VANNTOPP\", str(toppavsylinder))\ntxt = txt.replace(\"HJELP\", str(antall))\ntxt = txt.replace(\"RADIUS\", str(R))\ntxt = txt.replace(\"hoyde\", str(10*h))\n\nwith open(\"vann.inp\", \"w\") as fil:\n fil.write(txt)\n","sub_path":"gammelt/fungerer_med_kraft_dum_packmol/gammelt/bashrot/vann.py","file_name":"vann.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"400537356","text":"from torch.utils.data import Dataset\nimport torch\nimport pandas as pd\n\n\nclass activityDataset(Dataset):\n def __init__(self, root_dir,folder,mode , normalize=None):\n self.dataset = torch.from_numpy(pd.read_csv('{}{}\\\\{}.csv'.format(root_dir,folder,mode), index_col=0).values)\n self.corr_data = self.dataset[:, :720]\n self.raw_data = self.dataset[:, 720:720 * 2]\n self.mask_data = self.dataset[:, 720 * 2:720 * 3]\n self.missing_rate =self.dataset[:, -14:-13]\n self.min_max = self.dataset[:, -13:-11]\n self.mean_var = self.dataset[:, -11:-9]\n self.total_mean_var = self.dataset[:, -2:]\n self.bmi = self.dataset[:, -8:-7]\n self.sex = self.dataset[:, -7:-6]\n self.age = self.dataset[:, -6:-5]\n self.race = self.dataset[:, -5:-4]\n self.week = self.dataset[:, -3:-2]\n self.norm_data = self.dataset[:, 720:720 * 2]\n\n if normalize == 'zero':\n self.norm_data = self.zero_normalize()\n elif normalize == 'minmax':\n self.norm_data = self.min_max_normalize()\n elif normalize == 'total_zero':\n self.norm_data = self.batch_zero_normalize()\n\n def __len__(self):\n return (self.dataset.shape[0])\n\n def __getitem__(self, idx):\n return self.corr_data[idx], self.raw_data[idx], self.mask_data[idx], self.norm_data[idx], \\\n {'mean_var': self.mean_var[idx], 'min_max': self.min_max[idx],\n 'total_mean_var': self.total_mean_var[idx]}, \\\n {'bmi': self.bmi[idx], 'sex': self.sex[idx], 'age': self.age[idx], 'race': self.race[idx],\n 'week': self.week[idx]}\n\n def zero_normalize(self):\n mean = self.mean_var[:, 0].view(-1, 1)\n std = torch.sqrt(self.mean_var[:, 1].view(-1, 1))\n norm = (self.raw_data - mean) / std\n #norm[self.corr_data == -1] = 0\n return norm\n\n def min_max_normalize(self):\n min = self.min_max[:, 0].view(-1, 1)\n max = self.min_max[:, 1].view(-1, 1)\n norm = (self.raw_data - min) / (max - min)\n #norm[self.corr_data == -1] = 0\n return norm\n\n def batch_zero_normalize(self):\n mean = self.total_mean_var[:, 0].view(-1, 1)\n std = torch.sqrt(self.total_mean_var[:, 1].view(-1, 1))\n norm = (self.raw_data - mean) / std\n #norm[self.corr_data == -1] = 0\n return norm\n","sub_path":"ActivityDataset.py","file_name":"ActivityDataset.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"556113607","text":"import os\r\nimport shutil\r\nimport zipfile\r\n\r\nfrom utils.data_provider_utils import get_db_delete, get_query_constants, \\\r\n get_create_tables, get_db_update, get_db_insert, get_db_bulkinsert, \\\r\n get_add_uri_match, get_mime_tables, get_db_exec_drop_tables, get_db_exec_tables, \\\r\n get_db_query\r\nfrom utils.utils import read_file, write_file, get_attributes, \\\r\n get_constructor_parameters, get_init_attributes, get_read_parcel, \\\r\n get_write_parcel, get_read, get_write, get_to_string, del_even_read_only\r\n\r\nCREATOR_DB = 'creatordb.txt'\r\nPERSISTENT_BEAN = 'persistentbean.txt'\r\nDATA_PROVIDER_CONTRACT = 'dataprovidercontract.txt'\r\nDATA_PROVIDER = 'dataprovider.txt'\r\n\r\nTABLE_NAME = \"\\tpublic static final String %table_name_upper%_TABLE_NAME = \\\"%table_name_lower%\\\";\" + \"\\n\"\r\nURI_STRING_CONSTANT = \"\\tpublic static final Uri %table_name%_TABLE_CONTENTURI = Uri.withAppendedPath(CONTENT_URI, %table_name%_TABLE_NAME);\" + \"\\n\"\r\nCOL_CONSTANT = \"\\tpublic static final String COL_%table_name_upper%_%column_name_upper% = \\\"%table_name_lower%_%column_name_lower%\\\";\" + \"\\n\"\r\nPOS_CONSTANT = \"\\tpublic static final int POS_%table_name_upper%_%column_name_upper% = %position_value%;\" + \"\\n\"\r\n\r\n\r\ndef generate_dataprovider_contract(data):\r\n data_provider = read_file(DATA_PROVIDER_CONTRACT);\r\n data_provider = data_provider.replace(\"%package%\", data['package']);\r\n data_provider = data_provider.replace(\"%database_name%\", data['application']);\r\n # Dummy version added for now\r\n data_provider = data_provider.replace(\"%database_version%\", '1');\r\n result = ''\r\n for table in data['tables']:\r\n result += (\"\\t// Constants describing the database variables for \" + table['name'] + \"\\n\");\r\n table_name = TABLE_NAME.replace(\"%table_name_upper%\", table['name'].upper());\r\n table_name = table_name.replace(\"%table_name_lower%\", table['name'].lower());\r\n\r\n result += table_name;\r\n result += URI_STRING_CONSTANT.replace(\"%table_name%\", table['name'].upper());\r\n print(result)\r\n\r\n data_provider = data_provider.replace(\"%table_constants%\", result);\r\n write_file(\"results/db/\", \"DataProviderContract.java\", data_provider)\r\n\r\n\r\ndef generate_table(table, application, package):\r\n table_file = read_file(\"table.txt\")\r\n table_file = table_file.replace(\"%package%\", package)\r\n table_file = table_file.replace(\"%application_name%\", application)\r\n table_file = table_file.replace(\"%bean%\", table['name'].capitalize())\r\n table_file = table_file.replace(\"%attributes%\", get_attributes(table['columns']))\r\n table_file = table_file.replace(\"%table_name%\", table['name'])\r\n table_file = table_file.replace(\"%get_table_name%\", table['name'].upper() + '_TABLE_NAME')\r\n table_file = table_file.replace(\"%constructor_parameters%\", get_constructor_parameters(table['columns']))\r\n table_file = table_file.replace(\"%init_attributes%\", get_init_attributes(table['columns']))\r\n table_file = table_file.replace(\"%read%\", get_read(table['columns'], table['name']))\r\n table_file = table_file.replace(\"%write%\", get_write(table['columns'], table['name']))\r\n table_file = table_file.replace(\"%check_action_unique%\", '')\r\n table_file = table_file.replace(\"%to_string%\", get_to_string(table['columns']))\r\n table_file = table_file.replace(\"%write_parcel%\", get_write_parcel(table['columns']))\r\n table_file = table_file.replace(\"%read_parcel%\", get_read_parcel(table['columns']))\r\n table_file = table_file.replace(\"%table_name_upper%\", table['name'].upper())\r\n # Write to the table_name file\r\n write_file(\"results/data/\", table['name'].capitalize() + '.java', table_file)\r\n\r\n\r\ndef generate_data_provider(data):\r\n if data is None:\r\n return\r\n\r\n data_provider = read_file(DATA_PROVIDER)\r\n\r\n data_provider = data_provider.replace(\"%package%\", data['package'])\r\n data_provider = data_provider.replace(\"%constants_for_query%\", get_query_constants(data['tables']))\r\n data_provider = data_provider.replace(\"%create_table_database%\", get_create_tables(data['tables']))\r\n data_provider = data_provider.replace(\"%add_uri_match%\", get_add_uri_match(data['tables']))\r\n data_provider = data_provider.replace(\"%mime_type_table%\", get_mime_tables(data['tables']))\r\n data_provider = data_provider.replace(\"%db_exec_droptables%\", get_db_exec_drop_tables(data['tables']))\r\n data_provider = data_provider.replace(\"%db_exec%\", get_db_exec_tables(data['tables']))\r\n data_provider = data_provider.replace(\"%db_query%\", get_db_query(data['tables']))\r\n data_provider = data_provider.replace(\"%db_insert% \", get_db_insert(data['tables']))\r\n data_provider = data_provider.replace(\"%db_bulk_insert%\", get_db_bulkinsert(data['tables']))\r\n data_provider = data_provider.replace(\"%db_delete%\", get_db_delete(data['tables']))\r\n data_provider = data_provider.replace(\"%db_update%\", get_db_update(data['tables']))\r\n # Write DataProvider class\r\n write_file(\"results/db/\", \"DataProvider.java\", data_provider)\r\n\r\n\r\ndef zipdir(path, ziph):\r\n # ziph is zipfile handle\r\n for root, dirs, files in os.walk(path):\r\n for file in files:\r\n ziph.write(os.path.join(root, file))\r\n\r\n\r\ndef generate_db_files(data):\r\n # First delete the folder to create further results\r\n if os.path.exists(\"results\"):\r\n shutil.rmtree('results', onerror=del_even_read_only)\r\n\r\n creatordb = read_file(CREATOR_DB)\r\n persistent_bean = read_file(PERSISTENT_BEAN)\r\n\r\n # Replace the package name\r\n creatordb = creatordb.replace(\"%package%\", data['package'])\r\n persistent_bean = persistent_bean.replace(\"%package%\", data['package'])\r\n\r\n # Generate Creator DB file and Persistent Bean\r\n write_file(\"results/db/\", \"CreatorDB.java\", creatordb)\r\n write_file(\"results/db/\", \"PersistentBean.java\", persistent_bean)\r\n\r\n # Generate data provider\r\n generate_dataprovider_contract(data)\r\n\r\n # Generate tables\r\n for table in data['tables']:\r\n generate_table(table, data['application'], data['package'])\r\n\r\n generate_data_provider(data)\r\n\r\n zip = zipfile.ZipFile('results.zip', 'w', zipfile.ZIP_DEFLATED)\r\n zipdir('results/', zip)\r\n zip.close()\r\n","sub_path":"db_generator.py","file_name":"db_generator.py","file_ext":"py","file_size_in_byte":6190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"581250290","text":"import torch, math\n\nfrom . import chebyshev, LagrangeBasis\n\nimport matplotlib\nmatplotlib.use(\"agg\")\nfrom matplotlib import pyplot\n\nEPS = 1e-16\n\nclass ChebyshevActivation(torch.nn.Module):\n\n def __init__(self, input_size, n_degree):\n super().__init__()\n self.d = input_size\n self.n = n_degree + 1\n self.weight = torch.nn.Parameter(\n torch.zeros(1, self.d, self.n)\n )\n self._axes = None\n\n def forward(self, X):\n '''\n\n Input:\n X - torch Tensor of size (N, D, *), input features.\n\n Output:\n P - torch Tensor of size (N, D, *), polynomial output.\n\n '''\n B = self.operate(X, [], self.n)\n e = len(B.shape) - len(self.weight.shape)\n w = self.weight.view(1, self.d, *([1]*e), self.n)\n L = (w * B).sum(dim=-1)\n assert L.size() == X.size()\n return L\n\n def operate(self, X, H, stop):\n if len(H) < stop:\n \n if len(H) == 0:\n H.extend([torch.ones_like(X), X])\n else:\n H.append(H[-1]*2*X-H[-2])\n return self.operate(X, H, stop)\n else:\n return torch.stack(H, dim=-1)\n\n def reset_parameters(self):\n self.weight.data.zero_()\n\n def visualize_relu(self, k, title, figsize):\n fig, self._axes = matplotlib.pyplot.subplots(\n nrows=1, ncols=k, sharex=True, sharey=True, figsize=figsize\n )\n axes = self._axes\n model = torch.nn.ReLU()\n n = 1000\n x = torch.linspace(*self.r, n)\n y = model(x).cpu().numpy()\n x = x.cpu().numpy()\n for i in range(k):\n axes[i].plot(x, y)\n axes[i].set_xlim(self.r)\n axes[i].set_xlabel(\"$x_%d$\" % i)\n axes[k//2].set_title(title)\n fname = \"%s.png\" % title\n matplotlib.pyplot.savefig(fname, bbox_inches=\"tight\")\n print(\"Saved ReLU activations to %s\" % fname)\n\n def visualize(self, sim, k, title, figsize):\n mainplot = sim.visualize(title=\"Prototype outputs count\", figsize=figsize)\n if mainplot is None:\n if self._axes is None:\n _, self._axes = pyplot.subplots(nrows=1, ncols=k, sharex=True, sharey=\"row\", figsize=figsize)\n mainplot = self._axes\n axes = mainplot\n top = mainplot\n else:\n axes = mainplot[1,:]\n top = mainplot[0,:]\n device = self.weight.device\n with torch.no_grad():\n \n n = 1000\n for i in range(k):\n v = torch.linspace(*self.r, n)\n X = torch.zeros(n, self.d)\n X[:,i] = v\n Xh = self.forward(X.to(device))\n\n plot = axes[i]\n plot.set_xlim(self.r)\n plot.plot(v.cpu().numpy(), Xh[:,i].cpu().numpy(), label=\"Interpolated polynomial activation\")\n\n plot.plot(self.basis.nodes.cpu().numpy(), self.weight[0,i].clone().detach().cpu().numpy(), \"x\", label=\"Learned Chebyshev node\")\n\n plot.axvline(x=self.basis.nodes[0].numpy(), linestyle=\":\", label=\"Chebyshev x-position\")\n for node in self.basis.nodes[1:]:\n plot.axvline(x=node.numpy(), linestyle=\":\")\n \n plot.set_xlabel(\"$x_%d$\" % i)\n\n axes[k//2].legend(bbox_to_anchor=[1.1, -0.1])\n axes[0].set_ylabel(\"Polynomial output\")\n top[k//2].set_title(title)\n\n fname = \"%s.png\" % title\n matplotlib.pyplot.savefig(fname, bbox_inches=\"tight\")\n print(\"Saved polynomial activations to %s\" % fname)\n [plot.cla() for plot in axes]\n [plot.cla() for plot in top]\n return fname\n","sub_path":"src/modules/polynomial/ChebyshevActivation.py","file_name":"ChebyshevActivation.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"128097165","text":"#to print the most common word in a file using dictionary \r\nfname=input('enter the file name :')\r\nfhandle=open(fname)\r\ndict1={}\r\nfor line in fhandle:\r\n words=line.split()\r\n for word in words:\r\n dict1[word]=dict1.get(word,0)+1\r\nprint(dict1)\r\n\r\nlvalue=-99\r\nlkey=None\r\nfor k,v in dict1.items():\r\n if v>lvalue:\r\n lvalue=v\r\n lkey=k\r\nprint(lkey, lvalue)\r\n","sub_path":"ex0904.py","file_name":"ex0904.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"221837893","text":"import matplotlib.pyplot as plt \nimport matplotlib \nfrom my2048 import Game\nfrom MCTStree import MCTStreesearch\nfrom uct import uct_search\n# 设置中文字体和负号正常显示 \nmatplotlib.rcParams['font.sans-serif'] = ['SimHei'] \nmatplotlib.rcParams['axes.unicode_minus'] = False\n\nscore = []\nmaxtile = []\nindex = [i for i in range(10)]\n\nfor i in range(10):\n game = Game()\n while(not game.end):\n state = game.getstate()\n #move = MCTStreesearch(state)\n move = uct_search(state,60)\n game.move(move)\n print(game.info())\n score.append(game.getscore())\n maxtile.append(game.max())\n\nplt.xlabel('iter')\nplt.ylabel('num')\nplt.plot(index,score,color='skyblue',label='游戏分数')\nplt.plot(index,maxtile,color='green',label='最大方块值')\nplt.legend()\nplt.show()\n","sub_path":"_2048AI/src/main/resources/pyfiles/plotmcts.py","file_name":"plotmcts.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"92318924","text":"from microbit import *\nimport math\nimport random\nimport radio\n\n\nclass Paddle(object):\n def __init__(self,x,y,b):\n self.x = x\n self.y = y\n self.b = b\n def update(self):\n for i in range(5):\n if i is not self.x:\n display.set_pixel(i, 4,0)\n display.set_pixel(self.x, self.y, self.b)\n \nclass Ball(object):\n def __init__(self,x,y,xdir,ydir,speed,brightness):\n self.x = x\n self.y = y\n self.xdir = xdir\n self.ydir = ydir\n self.speed = speed\n self.brightness = brightness\n display.set_pixel(self.x, self.y,self.brightness)\n \n def move(self):\n for i in range(0,5):\n for j in range(0,4):\n display.set_pixel(i, j,0) #clear previous position\n\n \n self.y += self.ydir\n if self.y<0:\n self.y = 1\n self.ydir = -self.ydir\n self.send()\n #send ball to other device\n elif self.y>3:\n if paddle.x == self.x: #hit\n self.y = 2\n self.ydir = -self.ydir\n self.xdir = random.choice([-1,0,1])\n self.speed = int(0.95*self.speed)\n else: \n global running\n running = False\n self.x = 0\n self.y = 0\n self.xdir = 0\n self.ydir = 0\n self.speed = initBallSpeed\n self.brightness = 0 #bye bye\n \n self.x += self.xdir\n if self.x<0:\n self.x = 1\n self.xdir = -self.xdir\n elif self.x >4:\n self.x=3\n self.xdir = -self.xdir\n\n display.set_pixel(self.x, self.y,self.brightness)\n \n def send(self):\n global running\n running = False\n radio.send('BALL '+str(self.x)+' '+str(self.xdir)+' '+str(self.speed))\n self.x = 0\n self.y = 0\n self.xdir = 0\n self.ydir = 0\n self.speed = initBallSpeed\n self.brightness = 0\n \n \n\ndef getXacc():\n return accelerometer.get_x()\n\npaddle = Paddle(2,4,9)\naccEdge = 600\ninitBallSpeed = 500\nball = Ball(0,0,0,0,0,0) #generate invisible ball\n\nrunning = False \n\nradio.on()\n\n\nwhile True:\n tilt = max(min(getXacc(),accEdge),-accEdge)\n paddle.x = int(tilt/(accEdge/2))+2\n paddle.update()\n \n received = radio.receive()\n \n if received is not None and received[:4] == 'BALL':\n received = received.strip().split(' ')\n ball.x = int(received[1])\n ball.y = 0\n ball.xdir = -int(received[2])\n ball.ydir = 1\n ball.speed = int(float(received[3]))\n ball.brightness = 9\n display.set_pixel(ball.x, ball.y,ball.brightness)\n running = True\n startTime = running_time()\n \n \n\n if button_a.is_pressed():\n display.set_pixel(ball.x, ball.y,0) #remove previous postion\n ball.x = random.choice([0,1,2,3,4])\n ball.y = 0\n ball.xdir = random.choice([-1,1])\n ball.ydir = 1\n ball.speed = initBallSpeed\n ball.brightness = 9\n display.set_pixel(ball.x, ball.y,ball.brightness)\n running = True\n startTime = running_time()\n elif button_b.is_pressed():\n pass\n \n\n \n if running == True:\n currentTime = running_time() \n timePassed = currentTime-startTime\n\n if timePassed > ball.speed:\n ball.move()\n startTime = running_time() \n\n\n","sub_path":"pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"329980281","text":"# Copyright (C) 2001-2009,2012-2015 Andreas Lang-Nevyjel\n#\n# this file is part of package-client\n#\n# Send feedback to: \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License Version 2 as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n\"\"\" daemon to automatically install packages (.rpm, .deb) \"\"\"\n\nfrom initat.package_install.client.config import global_config\nfrom initat.package_install.client.install_process import yum_install_process, zypper_install_process, \\\n get_srv_command\nimport configfile\nimport logging_tools\nimport os\nimport process_tools\nimport server_command\nimport threading_tools\nimport time\nimport uuid_tools\nimport zmq\n\n\nclass server_process(threading_tools.process_pool):\n def __init__(self):\n self.global_config = global_config\n self.__log_cache, self.__log_template = ([], None)\n threading_tools.process_pool.__init__(\n self,\n \"main\",\n zmq=True,\n zmq_debug=global_config[\"ZMQ_DEBUG\"]\n )\n self.__log_template = logging_tools.get_logger(global_config[\"LOG_NAME\"], global_config[\"LOG_DESTINATION\"], zmq=True, context=self.zmq_context)\n # self.renice(global_config[\"NICE_LEVEL\"])\n self.install_signal_handlers()\n # init environment\n self._init_environment()\n self._init_msi_block()\n self.register_exception(\"int_error\", self._int_error)\n self.register_exception(\"term_error\", self._int_error)\n self.register_exception(\"alarm_error\", self._alarm_error)\n # log buffer\n self._show_config()\n # send buffer\n self.__send_buffer = []\n # log limits\n self._log_limits()\n self._set_resend_timeout(None)\n if self._get_package_server_id():\n self._init_network_sockets()\n self.register_func(\"send_to_server\", self._send_to_server)\n if os.path.isfile(\"/etc/centos-release\") or os.path.isfile(\"/etc/redhat-release\"):\n self.add_process(yum_install_process(\"install\"), start=True)\n else:\n self.add_process(zypper_install_process(\"install\"), start=True)\n else:\n self.client_socket = None\n self._int_error(\"no package_server id\")\n\n def log(self, what, lev=logging_tools.LOG_LEVEL_OK):\n if self.__log_template:\n while self.__log_cache:\n cur_lev, cur_what = self.__log_cache.pop(0)\n self.__log_template.log(cur_lev, cur_what)\n self.__log_template.log(lev, what)\n else:\n self.__log_cache.append((lev, what))\n\n def _init_environment(self):\n # Debian fix to get full package names, sigh ...\n os.environ[\"COLUMNS\"] = \"2000\"\n\n def _init_msi_block(self):\n # store pid name because global_config becomes unavailable after SIGTERM\n self.__pid_name = global_config[\"PID_NAME\"]\n process_tools.save_pids(global_config[\"PID_NAME\"], mult=3)\n process_tools.append_pids(global_config[\"PID_NAME\"], pid=configfile.get_manager_pid(), mult=3)\n if True: # not self.__options.DEBUG:\n self.log(\"Initialising meta-server-info block\")\n msi_block = process_tools.meta_server_info(\"package-client\")\n msi_block.add_actual_pid(mult=3, fuzzy_ceiling=4, process_name=\"main\")\n msi_block.add_actual_pid(act_pid=configfile.get_manager_pid(), mult=3, process_name=\"manager\")\n msi_block.start_command = \"/etc/init.d/package-client start\"\n msi_block.stop_command = \"/etc/init.d/package-client force-stop\"\n msi_block.kill_pids = True\n msi_block.save_block()\n else:\n msi_block = None\n self.__msi_block = msi_block\n\n def _show_config(self):\n for log_line, log_level in global_config.get_log():\n self.log(\"Config info : [{:d}] {}\".format(log_level, log_line))\n conf_info = global_config.get_config_info()\n self.log(\"Found {}:\".format(logging_tools.get_plural(\"valid configline\", len(conf_info))))\n for conf in conf_info:\n self.log(\"Config : {}\".format(conf))\n\n def _log_limits(self):\n # read limits\n r_dict = {}\n try:\n import resource\n except ImportError:\n self.log(\"cannot import resource\", logging_tools.LOG_LEVEL_CRITICAL)\n else:\n available_resources = [key for key in dir(resource) if key.startswith(\"RLIMIT\")]\n for av_r in available_resources:\n try:\n r_dict[av_r] = resource.getrlimit(getattr(resource, av_r))\n except ValueError:\n r_dict[av_r] = \"invalid resource\"\n except:\n r_dict[av_r] = None\n if r_dict:\n res_keys = sorted(r_dict.keys())\n self.log(\"{} defined\".format(logging_tools.get_plural(\"limit\", len(res_keys))))\n res_list = logging_tools.new_form_list()\n for key in res_keys:\n val = r_dict[key]\n if isinstance(val, basestring):\n info_str = val\n elif type(val) is tuple:\n info_str = \"{:8d} (hard), {:8d} (soft)\".format(*val)\n else:\n info_str = \"None (error?)\"\n res_list.append([logging_tools.form_entry(key, header=\"key\"),\n logging_tools.form_entry(info_str, header=\"value\")])\n for line in str(res_list).split(\"\\n\"):\n self.log(line)\n else:\n self.log(\"no limits found, strange ...\", logging_tools.LOG_LEVEL_WARN)\n\n def _get_package_server_id(self):\n self.srv_conn_str = \"tcp://{}:{:d}\".format(\n global_config[\"PACKAGE_SERVER\"],\n global_config[\"SERVER_COM_PORT\"]\n )\n ps_id_file_name = global_config[\"PACKAGE_SERVER_ID_FILE\"]\n if not os.path.exists(ps_id_file_name):\n _result = self._get_package_server_id_from_server()\n if _result is not None:\n _server_id = _result[\"*zmq_id\"]\n self.log(\n \"got server_id {} from server, writing to {}\".format(\n _server_id,\n ps_id_file_name,\n )\n )\n file(ps_id_file_name, \"w\").write(_server_id)\n if os.path.exists(ps_id_file_name):\n self.__package_server_id = file(ps_id_file_name, \"r\").read().strip()\n return True\n else:\n return False\n\n def _get_package_server_id_from_server(self):\n check_sock = process_tools.get_socket(\n self.zmq_context,\n \"DEALER\",\n identity=\"{}:ptest:\".format(uuid_tools.get_uuid().get_urn()),\n )\n check_sock.connect(self.srv_conn_str)\n self.log(\"fetch srv_id socket, connected to {}\".format(self.srv_conn_str))\n check_sock.send_unicode(unicode(server_command.srv_command(command=\"get_0mq_id\")))\n _timeout = 10\n my_poller = zmq.Poller()\n my_poller.register(check_sock, zmq.POLLIN) # @UndefinedVariable\n s_time = time.time()\n _last_log = time.time()\n while True:\n _list = my_poller.poll(2)\n if _list:\n _result = server_command.srv_command(source=check_sock.recv_unicode())\n break\n cur_time = time.time()\n if cur_time > s_time + _timeout:\n self.log(\"timeout, exiting ...\", logging_tools.LOG_LEVEL_ERROR)\n _result = None\n break\n else:\n if abs(cur_time - _last_log) > 0.5:\n _last_log = cur_time\n self.log(\n \"timeout, still waiting ({:.2f} of {:.2f})\".format(\n abs(cur_time - s_time),\n _timeout,\n ),\n logging_tools.LOG_LEVEL_WARN\n )\n my_poller.unregister(check_sock)\n del my_poller\n check_sock.close()\n del check_sock\n return _result\n\n def _init_network_sockets(self):\n # socket\n self.bind_id = \"{}:pclient:\".format(uuid_tools.get_uuid().get_urn())\n self.log(\"connected to {}\".format(self.srv_conn_str))\n client_sock = process_tools.get_socket(\n self.zmq_context,\n \"ROUTER\",\n identity=self.bind_id,\n )\n bind_str = \"tcp://0.0.0.0:{:d}\".format(\n global_config[\"COM_PORT\"]\n )\n client_sock.bind(bind_str)\n client_sock.connect(self.srv_conn_str)\n self.log(\"bound to {} (ID {})\".format(bind_str, self.bind_id))\n self.client_socket = client_sock\n self.register_poller(client_sock, zmq.POLLIN, self._recv_client) # @UndefinedVariable\n # send commands\n self._register()\n self._get_repos()\n self._get_new_config()\n\n def _check_send_buffer(self):\n new_buffer = []\n _send_ok = 0\n _success = True\n for _msg in self.__send_buffer:\n if _success:\n try:\n self.client_socket.send_unicode(self.__package_server_id, zmq.SNDMORE) # @UndefinedVariable\n self.client_socket.send_unicode(_msg)\n except zmq.error.ZMQError:\n _success = False\n new_buffer.append(_msg)\n else:\n _send_ok += 1\n else:\n new_buffer.append(_msg)\n self.__send_buffer = new_buffer\n self.log(\"trying to resend {}: {:d} ok, {:d} still pending\".format(\n logging_tools.get_plural(\"message\", len(self.__send_buffer)),\n _send_ok,\n len(self.__send_buffer),\n )\n )\n # print len(self.__send_buffer)\n if not self.__send_buffer:\n self._set_resend_timeout(300)\n\n def _set_resend_timeout(self, cur_to):\n if cur_to is None:\n self.__rst = 0\n else:\n if cur_to != self.__rst:\n if self.__rst:\n self.log(\"changing check_send_buffer timeout from {:d} to {:d} secs\".format(self.__rst, cur_to))\n self.unregister_timer(self._check_send_buffer)\n else:\n self.log(\"setting check_send_buffer timeout to {:d} secs\".format(cur_to))\n self.register_timer(self._check_send_buffer, cur_to)\n self.__rst = cur_to\n\n def _send_to_server_int(self, xml_com):\n self._send_to_server(\"self\", os.getpid(), xml_com[\"command\"].text, unicode(xml_com), \"server command\")\n\n def _send_to_server(self, src_proc, *args, **kwargs):\n _src_pid, com_name, send_com, send_info = args\n self.log(\n \"sending {} ({}) to server {}\".format(\n com_name,\n send_info,\n self.srv_conn_str\n )\n )\n try:\n self.client_socket.send_unicode(self.__package_server_id, zmq.SNDMORE) # @UndefinedVariable\n self.client_socket.send_unicode(send_com)\n except zmq.error.ZMQError:\n self.__send_buffer.append(send_com)\n self.log(\"error sending message to server, buffering ({:d})\".format(len(self.__send_buffer)))\n self._set_resend_timeout(10)\n\n def _register(self):\n self._send_to_server_int(get_srv_command(command=\"register\"))\n\n def _get_new_config(self):\n self._send_to_server_int(get_srv_command(command=\"get_package_list\"))\n # self._send_to_server_int(get_srv_command(command=\"get_rsync_list\"))\n\n def _get_repos(self):\n self._send_to_server_int(get_srv_command(command=\"get_repo_list\"))\n\n def _recv_client(self, zmq_sock):\n data = [zmq_sock.recv()]\n while zmq_sock.getsockopt(zmq.RCVMORE): # @UndefinedVariable\n data.append(zmq_sock.recv())\n batch_list = []\n if len(data) == 2:\n src_id = data.pop(0)\n data = data[0]\n try:\n srv_com = server_command.srv_command(source=data)\n except:\n self.log(\n \"error decoding command from {}: {}, '{}'\".format(\n src_id,\n process_tools.get_except_info(),\n data[:30],\n ),\n logging_tools.LOG_LEVEL_ERROR\n )\n else:\n send_reply = True\n srv_com.update_source()\n cur_com = srv_com[\"command\"].text\n self.log(\"got {} (length: {:d}) from {}\".format(cur_com, len(data), src_id))\n srv_com[\"result\"] = None\n if cur_com == \"get_0mq_id\":\n srv_com[\"zmq_id\"] = self.bind_id\n srv_com.set_result(\n \"0MQ_ID is {}\".format(self.bind_id)\n )\n elif cur_com == \"status\":\n # FIXME, Todo\n srv_com.set_result(\n \"everything OK :-)\"\n )\n elif cur_com == \"new_config\":\n # no reply for this command\n send_reply = False\n self._get_new_config()\n elif cur_com == \"sync_repos\":\n # no reply for this command\n send_reply = False\n self._get_repos()\n else:\n # no reply for this command\n send_reply = False\n batch_list.append(srv_com)\n if send_reply:\n self.log(\"send reply for command {}\".format(cur_com))\n zmq_sock.send_unicode(src_id, zmq.SNDMORE) # @UndefinedVariable\n zmq_sock.send_unicode(unicode(srv_com))\n del srv_com\n else:\n self.log(\n \"cannot receive more data, already got '{}'\".format(\n \", \".join(data)\n ),\n logging_tools.LOG_LEVEL_ERROR\n )\n if batch_list:\n self.log(\"... batch list valid ({})\".format(batch_list[0][\"*command\"]))\n self.send_to_process(\n \"install\",\n \"command_batch\",\n [\n unicode(cur_com) for cur_com in batch_list\n ]\n )\n\n def _int_error(self, err_cause):\n self.__exit_cause = err_cause\n if self[\"exit_requested\"]:\n self.log(\"exit already requested, ignoring\", logging_tools.LOG_LEVEL_WARN)\n else:\n self.log(\"got int_error, err_cause is '{}'\".format(err_cause), logging_tools.LOG_LEVEL_WARN)\n self[\"exit_requested\"] = True\n\n def _alarm_error(self, err_cause):\n self.__comsend_queue.put(\"reload\")\n\n def loop_end(self):\n process_tools.delete_pid(self.__pid_name)\n if self.__msi_block:\n self.__msi_block.remove_meta_block()\n\n def loop_post(self):\n if self.client_socket:\n self.client_socket.close()\n self.__log_template.close()\n","sub_path":"initat/package_install/client/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":15827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"208606338","text":"#importação de bibliotecas para configuração de socket udp multicast\nimport sys, struct, socket\nimport json\n\nfrom datetime import datetime\n\n# importação de bibliotecas para geração de chaves públicas e privadas\nfrom cryptography.hazmat.primitives import serialization\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.primitives import hashes\n\n# define o nome do server do par\nserverName = '225.0.0.3'\n#define a porta para conexão\nserverPort = 9000\n\n# configurando socket udp\nserverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n# Allow multiple sockets to use the same PORT number\nserverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n# bind udp port\nserverSocket.bind(('', serverPort))\n\n# set mcast group\nmreq = struct.pack('4sl', socket.inet_aton(serverName), socket.INADDR_ANY)\nserverSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\n# imprimindo na tela o início do servidor do par\ndata_e_hora_atuais = datetime.now()\ndata_e_hora_em_texto = data_e_hora_atuais.strftime('%d/%m/%Y %H:%M')\nprint(\"running server: \" + serverName + \":\" + str(serverPort) + \" - \" +\n data_e_hora_em_texto)\n\nnomeArquivoKeyPublic = \"\"\n\ncont = {\"escolhido\": 0, \"falhas\": 0, \"sucesso\": 0}\n\n# try e except para salvamento ou leitura do arquivo rel.txt que contém o histórico de cada par\ntry:\n with open('rel3.txt', 'r') as key_file:\n result = key_file.read()\nexcept:\n with open('rel3.txt', 'w') as key_file:\n key_file.write(str(cont))\n\n# try para while infinito que mantém o servidor do par online \ntry:\n while 1:\n\n data, addr = serverSocket.recvfrom(4096)\n\n # opção de recebimento da chave pública\n if (data.decode() == \"pub_key\"):\n # recebe nome para chave publica\n client, addr = serverSocket.recvfrom(4096)\n # guarda nome para chave em uma variável\n nomeArquivoKeyPublic = client.decode()\n \n # try para salvar a chave pública\n try:\n \n # abrindo arquivo\n arq = open(nomeArquivoKeyPublic + '.pem', 'wb')\n data, addr = serverSocket.recvfrom(4096) # recebendo chave pública em bytes\n\n arq.write(data) # salvando chave pública em arquivo\n arq.close() # fechando arquivo\n\n # imprimindo recebimento de chave pública\n data_e_hora_atuais = datetime.now()\n data_e_hora_em_texto = data_e_hora_atuais.strftime(\n '%d/%m/%Y %H:%M')\n print(\"recebido pub_key - \" + nomeArquivoKeyPublic + \" - \" +\n data_e_hora_em_texto)\n\n except Exception as e:\n print(e)\n arq.close()\n\n #opção de recebimento do ping\n if (data.decode() == \"ping\"):\n\n # imprimindo na tela o print recebido\n data_e_hora_atuais = datetime.now()\n data_e_hora_em_texto = data_e_hora_atuais.strftime(\n '%d/%m/%Y %H:%M')\n print(\"ping recebido - \" + data_e_hora_em_texto)\n \n #enviando de volta o pong para o par que enviou o ping\n serverSocket.sendto(\"pong from 225.0.0.3\".encode(), ('', addr[1]))\n\n # opção de recebimento do file\n if (data.decode() == \"file\"):\n try:\n\n # recebe o nome do arquivo para download\n data, addr = serverSocket.recvfrom(4096)\n\n #verifica se o par possui o arquivo \n arq = open(data.decode() + '.txt', 'r')\n\n # se não der exceção o par possui o arquivo\n # abre o rel3.txt que possui a nota do par para downloads de arquivos \n with open('rel3.txt', 'r') as key_file:\n result = key_file.read()\n\n # concatenação de strings para retornar ao par externo que possui o arquivo para download\n conctResult = \"file disponivel from 225.0.0.3 id=3 \" + result\n\n # retorno da resposta\n serverSocket.sendto(conctResult.encode(), ('', addr[1]))\n\n # recebe para qual par deve enviar o download\n data, addr = serverSocket.recvfrom(4096)\n \n # separa em list a resposta\n r = data.decode().split(\" \")\n\n # se o primeiro termo da lista for 3 ele continuar a execução para enviar o arquivo linha-a-linha\n if (r[0] == \"3\"):\n result = result.replace(\"'\", '\"') # arruma a string para converter em dicionário\n cont = json.loads(result) # transforma string para dicionário para manipulação\n cont[\"escolhido\"] += 1 # conta mais um para escolhido\n \n # tenta abrir a chave pública do par que solicitou o download,\n # pegando o segundo argumento da lista,\n # recebida.\n try:\n\n #realiza leitura da chave pública\n with open('par' + r[1] + '_pub_key.pem',\n 'rb') as key_file:\n public_key = serialization.load_pem_public_key(\n key_file.read())\n\n # for para envio de linha por linha\n for i in arq.readlines():\n\n # criptografa cada linha antes de enviar com a chave pública do par que solicitou\n cipher_text = public_key.encrypt(\n bytes(i, encoding=\"utf-8\"),\n padding.OAEP(mgf=padding.MGF1(\n algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None))\n\n #envia a mensagem criptograda\n serverSocket.sendto(cipher_text, ('', addr[1]))\n\n # após finalizar o for fecha o arquivo aberto\n arq.close()\n\n # imprimi na tela o envio do arquivo\n data_e_hora_atuais = datetime.now()\n data_e_hora_em_texto = data_e_hora_atuais.strftime(\n '%d/%m/%Y %H:%M')\n print(\"file sent - \" + data_e_hora_em_texto)\n\n cont[\"sucesso\"] += 1 # conta mais para sucesso de envios\n print(cont) # imprimi o contaador\n\n #salva o contador no arquivo de relatório novamente\n with open('rel3.txt', 'w') as key_file:\n key_file.write(str(cont))\n\n except Exception as e:\n # imprimi na tela o erro e que o arquivo não foi enviado\n print(e) \n data_e_hora_atuais = datetime.now()\n data_e_hora_em_texto = data_e_hora_atuais.strftime(\n '%d/%m/%Y %H:%M')\n print(\"file not sent - \" + data_e_hora_em_texto)\n \n cont[\"falhas\"] += 1 # conta mais um como falha de envio\n print(cont) # imprimi o contador\n\n #salva o contador no arquivo de relatório novamente\n with open('rel3.txt', 'w') as key_file:\n key_file.write(str(cont))\n arq.close()\n\n except Exception as e:\n # se o aquivo não existir envia para o par a informação\n print(e)\n serverSocket.sendto(\n \"Arquivo inexistente from 225.0.0.3 ou Falha na conexao\".\n encode(), ('', addr[1]))\n \n\nexcept KeyboardInterrupt:\n # caso clique control + c ele interrompe a execução do bind e finaliza o script\n print('done')\n sys.exit(0)\n","sub_path":"SISTEMAS-DISTRIBUIDOS/atividades/trabalhofinal1/resolucao/srv3/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":8097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"525223346","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 7 15:01:22 2020\n\n@author: luke\n\"\"\"\n\nimport pyglet\nimport pymunk\nfrom pymunk.pyglet_util import DrawOptions\nimport math\nimport physicalobject\nimport playertank\nimport resources\nimport wall\nimport bullet\nimport room\n\n#pymunk init\nspace = pymunk.Space()\nspace.gravity = 0, 0\noptions = DrawOptions()\n\n#pyglet init\nrooms = []\ngame_window = pyglet.window.Window(1400, 1000)\nmain_batch = pyglet.graphics.Batch()\nresources.center_image(resources.tank_body)\nresources.center_image(resources.bullet)\nresources.center_image(resources.wallblock)\n#roomsyikes\n\n#startroom/////////////////////////////////////////////////////////////////////////////////////////////////////////////\nstart_room = room.Room()\nrooms.append(start_room)\n#playertank init\nplayer_tank = playertank.PlayerTank(x=500, y=500, batch=main_batch)\nplayer_tank.scale = 1\nstart_room.objects.append(player_tank)\nplayer_tank.accel_speed = 300\nplayer_tank.max_speed = 200\nplayer_tank.turnspeed = .01\nplayer_tank.rotation = math.pi*3/2\nstart_room.space.add(player_tank.shape, player_tank.body)\ngame_window.push_handlers(player_tank)\ngame_window.push_handlers(player_tank.key_handler)\n#testwallinits\nfor i in range(57):\n test_wall = wall.WallBlock(x=25*i, y=0, batch=main_batch)\n start_room.space.add(test_wall.shape, test_wall.body)\n start_room.objects.append(test_wall)\nfor i in range(57):\n test_wall = wall.WallBlock(x=25*i, y=1000, batch=main_batch)\n start_room.space.add(test_wall.shape, test_wall.body)\n start_room.objects.append(test_wall)\nfor i in range(41):\n test_wall = wall.WallBlock(x=0, y=25*i, batch=main_batch)\n start_room.space.add(test_wall.shape, test_wall.body)\n start_room.objects.append(test_wall)\nfor i in range(41):\n test_wall = wall.WallBlock(x=1400, y=25*i, batch=main_batch)\n start_room.space.add(test_wall.shape, test_wall.body)\n start_room.objects.append(test_wall)\n\n#collision response\ndef coll_begin(arbiter, space, data):\n return True\n\ndef coll_pre(arbiter, space, data):\n #bullet-wall\n if ((arbiter.shapes[0].id == \"bullet\" and arbiter.shapes[1].id == \"wall\") or (arbiter.shapes[1].id == \"bullet\" and arbiter.shapes[0].id == \"wall\")):\n if (arbiter.shapes[0].id == \"bullet\"):\n arbiter.shapes[0].dead = True\n if (arbiter.shapes[1].id == \"bullet\"):\n arbiter.shapes[1].dead = True\n return True\n\ndef coll_post(arbiter, space, data):\n pass\n\n\n\ncurrent_room = start_room\ndef update(dt):\n current_room.update(dt)\n handler = current_room.space.add_default_collision_handler()\n handler.begin = coll_begin\n handler.pre_solve = coll_pre\n handler.post_solve = coll_post\n \n@game_window.event \ndef on_mouse_motion(x, y, dx, dy):\n player_tank.mousex = x\n player_tank.mousey = y\n player_tank.turret_angle = physicalobject.direction(x-player_tank.x, y-player_tank.y, None)\n \n\n@game_window.event\ndef on_mouse_press(x, y, button, modifiers):\n player_tank.fire(x, y)\n\n@game_window.event\ndef on_draw():\n game_window.clear()\n #space.debug_draw(options)\n main_batch.draw()\n \nif __name__ == '__main__':\n pyglet.clock.schedule_interval(update, 1/120.0)\n pyglet.app.run()\n \n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"6488013","text":"# 기준 데이터(pivot)를 설정하고 그 기준보다 큰 데이터와 작은 데이터의 위치를 바꾸는 알고리즘\n# 첫번째 인덱스에서 부터 비교하고 또 마지막 인덱스에서부터 비교한다.\n# 단 두 인덱스가 교차되면 피벗값을 작은 데이터의 위치와 바꾸고 그 위치에서 진행\n# 이렇게 피벗의 위치가 fix되면 피벗의 위치보다 왼쪽에 있는 데이터는 모두 피벗보다 작고\n# 오른쪽에 있는 데이터는 모두 피벗보다 크다는 특징이 있음\n\n# 시간 복잡도는 평균 O(N(logN)) 최악의 경우 O(n^2)\n\n\ndef quickSort(arr, start, end):\n if start >= end:\n return\n pivot = start\n left = start + 1\n right = end\n while left <= right:\n # left\n while left <= end and arr[pivot] >= arr[left]:\n left += 1\n # right\n while right >= start + 1 and arr[pivot] <= arr[right]:\n right -= 1\n if left > right:\n arr[pivot], arr[right] = arr[right], arr[pivot]\n else:\n arr[right], arr[left] = arr[left], arr[right]\n quickSort(arr, pivot, right - 1)\n quickSort(arr, right + 1, end)\n\n\narr = [2, 1, 5, 7, 3, 4, 6, 8, 9]\nquickSort(arr, 0, len(arr) - 1)\nprint(arr)","sub_path":"study/sorting/quick/quick.py","file_name":"quick.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"458050670","text":"import numpy as np\nfrom matplotlib.figure import Figure\nfrom matplotlib.axes import SubplotBase\n\nfrom ..plots import plot_histogram, plot_free_energy\n\nn = 100000\nrs = np.random.RandomState(42)\ndata = rs.rand(n, 2)\n\n\ndef test_plot_histogram():\n fig = plot_histogram(data)\n\n assert isinstance(fig, Figure)\n\n\ndef test_plot_free_energy_1d():\n ax = plot_free_energy(data, n_samples=10000, pi=np.array(n*[.5]),\n xlabel='x', ylabel='y')\n\n assert isinstance(ax, SubplotBase)\n\n\ndef test_plot_free_energy_2d():\n ax = plot_free_energy(data, obs=(0, 1), n_samples=10000,\n pi=np.array(n*[.5]), xlabel='x', ylabel='y',\n clabel=True)\n\n assert isinstance(ax, SubplotBase)\n","sub_path":"msmexplorer/tests/test_projection_plot.py","file_name":"test_projection_plot.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"143931407","text":"#The Riddler Classic 2017-05-05: The Lucky Derby\n#Monte Carlo simulation\n\nimport random\n\nNsim = 10000 #Number of simulations\n\nn = 20 #Number of horses\n\ncounts = n*[0] #Store number of times won\n\nfor N in range(Nsim):\n\n x = n*[0] #Keep track of position\n\n while(max(x) < 200):\n\n #Update positions\n for i in range(n):\n r = random.random()\n\n if (r <= 0.52 + i*0.02):\n x[i] += 1\n else:\n x[i] += -1\n\n #Find all horses that have crossed the line (to account for ties)\n indices = [i for i, y in enumerate(x) if y == 200]\n\n #Only count a win if outright\n if (len(indices) == 1):\n counts[indices[0]] += 1\n\n#Print empirical probabilities\nprint([i/Nsim for i in counts])\n","sub_path":"classic/lucky_derby.py","file_name":"lucky_derby.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"214150039","text":"import json\nimport logging\nimport uuid\nfrom tempfile import NamedTemporaryFile\n\nfrom kfp import Client\nfrom kfp.compiler import Compiler\nfrom tabulate import tabulate\n\nfrom .auth import AuthHandler\nfrom .generator import PipelineGenerator\nfrom .utils import clean_name\n\nWAIT_TIMEOUT = 24 * 60 * 60\n\n\nclass KubeflowClient(object):\n\n log = logging.getLogger(__name__)\n\n def __init__(self, config, project_name, context):\n client_params = {}\n token = AuthHandler().obtain_id_token()\n if token is not None:\n client_params = {\"existing_token\": token}\n dex_authservice_session = AuthHandler().obtain_dex_authservice_session(\n kfp_api=config.host,\n )\n if dex_authservice_session is not None:\n client_params = {\n \"cookies\": f\"authservice_session={dex_authservice_session}\"\n }\n self.host = config.host\n self.client = Client(host=self.host, **client_params)\n\n self.project_name = project_name\n self.pipeline_description = config.run_config.description\n self.generator = PipelineGenerator(config, project_name, context)\n\n def list_pipelines(self):\n pipelines = self.client.list_pipelines(page_size=30).pipelines\n return tabulate(\n map(lambda x: [x.name, x.id], pipelines), headers=[\"Name\", \"ID\"]\n )\n\n def run_once(\n self,\n pipeline,\n image,\n experiment_name,\n experiment_namespace,\n run_name,\n wait,\n image_pull_policy=\"IfNotPresent\",\n ) -> None:\n run = self.client.create_run_from_pipeline_func(\n self.generator.generate_pipeline(\n pipeline, image, image_pull_policy\n ),\n arguments={},\n experiment_name=experiment_name,\n namespace=experiment_namespace,\n run_name=run_name,\n )\n\n if wait:\n run.wait_for_run_completion(timeout=WAIT_TIMEOUT)\n\n def compile(\n self, pipeline, image, output, image_pull_policy=\"IfNotPresent\"\n ):\n Compiler().compile(\n self.generator.generate_pipeline(\n pipeline, image, image_pull_policy\n ),\n output,\n )\n self.log.info(\"Generated pipeline definition was saved to %s\" % output)\n\n def upload(self, pipeline, image, image_pull_policy=\"IfNotPresent\"):\n pipeline = self.generator.generate_pipeline(\n pipeline, image, image_pull_policy\n )\n\n if self._pipeline_exists(self.project_name):\n pipeline_id = self._get_pipeline_id(self.project_name)\n version_id = self._upload_pipeline_version(pipeline, pipeline_id)\n self.log.info(\"New version of pipeline created: %s\", version_id)\n else:\n (pipeline_id, version_id) = self._upload_pipeline(pipeline)\n self.log.info(\"Pipeline created\")\n\n self.log.info(\n f\"Pipeline link: {self.host}/#/pipelines/details/%s/version/%s\",\n pipeline_id,\n version_id,\n )\n\n def _pipeline_exists(self, pipeline_name):\n return self._get_pipeline_id(pipeline_name) is not None\n\n def _get_pipeline_id(self, pipeline_name):\n pipelines = self.client.pipelines.list_pipelines(\n filter=json.dumps(\n {\n \"predicates\": [\n {\n \"key\": \"name\",\n \"op\": 1,\n \"string_value\": pipeline_name,\n }\n ]\n }\n )\n ).pipelines\n\n if pipelines:\n return pipelines[0].id\n\n def _upload_pipeline_version(self, pipeline_func, pipeline_id):\n version_name = f\"{clean_name(self.project_name)}-{uuid.uuid4()}\"[:100]\n with NamedTemporaryFile(suffix=\".yaml\") as f:\n Compiler().compile(pipeline_func, f.name)\n return self.client.pipeline_uploads.upload_pipeline_version(\n f.name,\n name=version_name,\n pipelineid=pipeline_id,\n _request_timeout=10000,\n ).id\n\n def _upload_pipeline(self, pipeline_func):\n with NamedTemporaryFile(suffix=\".yaml\") as f:\n Compiler().compile(pipeline_func, f.name)\n pipeline = self.client.pipeline_uploads.upload_pipeline(\n f.name,\n name=self.project_name,\n description=self.pipeline_description,\n _request_timeout=10000,\n )\n return (pipeline.id, pipeline.default_version.id)\n\n def _ensure_experiment_exists(self, experiment_name, experiment_namespace):\n try:\n experiment = self.client.get_experiment(\n experiment_name=experiment_name,\n namespace=experiment_namespace,\n )\n self.log.info(f\"Existing experiment found: {experiment.id}\")\n except ValueError as e:\n if not str(e).startswith(\"No experiment is found\"):\n raise\n\n experiment = self.client.create_experiment(\n experiment_name, namespace=experiment_namespace\n )\n self.log.info(f\"New experiment created: {experiment.id}\")\n\n return experiment.id\n\n def schedule(\n self, pipeline, experiment_name, experiment_namespace, cron_expression\n ):\n experiment_id = self._ensure_experiment_exists(\n experiment_name, experiment_namespace\n )\n pipeline_id = self._get_pipeline_id(self.project_name)\n self._disable_runs(experiment_id, pipeline_id)\n self.client.create_recurring_run(\n experiment_id,\n f\"{self.project_name} on {cron_expression}\",\n cron_expression=cron_expression,\n pipeline_id=pipeline_id,\n )\n self.log.info(\"Pipeline scheduled to %s\", cron_expression)\n\n def _disable_runs(self, experiment_id, pipeline_id):\n runs = self.client.list_recurring_runs(experiment_id=experiment_id)\n if runs.jobs is not None:\n my_runs = [\n job\n for job in runs.jobs\n if job.pipeline_spec.pipeline_id == pipeline_id\n ]\n for job in my_runs:\n self.client.jobs.delete_job(job.id)\n self.log.info(f\"Previous schedule deleted {job.id}\")\n","sub_path":"kedro_kubeflow/kfpclient.py","file_name":"kfpclient.py","file_ext":"py","file_size_in_byte":6438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"313533627","text":"class Node:\r\n def __init__(self, data, next=None):\r\n self.next = next\r\n self.data = data\r\n \r\nclass MyLinkedList:\r\n def __init__(self):\r\n self.head = None\r\n\r\n def add_first(self, data):\r\n if data is None:\r\n return None\r\n \r\n node = Node(data, self.head)\r\n self.head = node\r\n return node \r\n\r\n def delete_node(self, node):\r\n if node is None:\r\n return\r\n if node.next is None:\r\n node.data = None\r\n else:\r\n node.data = node.next.data\r\n node.next = node.next.next\r\n\r\n def display(self):\r\n node = self.head\r\n while node is not None:\r\n print(node.data)\r\n node = node.next\r\n\r\nlist = MyLinkedList()\r\nlist.add_first(2)\r\nlist.add_first(3)\r\nlist.add_first(4)\r\nlist.add_first(1)\r\nprint(\"Before deletion\")\r\nlist.display()\r\nprint(\"The node needs to be deleted: \", list.head.next.next.data)\r\nlist.delete_node(list.head.next.next)\r\nprint(\"After deletion\")\r\nlist.display()\r\n\r\n","sub_path":"Lecture04/Labs/Lab01/delete_mid_solution2.py","file_name":"delete_mid_solution2.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"454133403","text":"from flask import Flask,flash, request,redirect,render_template, url_for , session ,g\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.sql.functions import func\nfrom datetime import datetime , date\nfrom dateutil.parser import parse\nimport os\n# import pandas as pd \n# import sqlalchemy\n# from sqlalchemy import create_engine\n# from sqlalchemy.ext.declarative import declarative_base\n# from sqlalchemy.orm import sessionmaker, relationship\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']='sqlite:///movie.db'\napp.secret_key=os.urandom(24)\ndb = SQLAlchemy(app)\n\n\nclass Movie(db.Model):\n __tablename__ = 'Movie'\n id = db.Column(db.Integer,primary_key=True)\n name = db.Column(db.String(50),nullable=False)\n director = db.Column(db.String(50),nullable=False)\n imdb=db.Column(db.Float)\n popularity=db.Column(db.Float)\n genre=db.Column(db.String(100))\n image = db.Column(db.Text, unique=True)\n cast = db.Column(db.Text)\n age_restriction = db.Column(db.Integer)\n release_date = db.Column(db.Date, index=True)\n description = db.Column(db.Text)\n\n def __init__(self,name, director, imdb, popularity, genre, image ,cast, age_restriction, release_date, description):\n self.name=name\n self.director=director\n self.imdb=imdb\n self.popularity=popularity\n self.genre=genre\n self.image=image\n self.cast=cast\n self.age_restriction=age_restriction\n self.release_date=release_date\n self.description=description\n \n def __repr__(self):\n return '' %self.id\n\nclass Users(db.Model):\n __tablename__ = 'users'\n id = db.Column(db.Integer,primary_key=True)\n username = db.Column(db.String(50),nullable=False, unique=False)\n password = db.Column(db.String(255), nullable=False, server_default='')\n firstname = db.Column(db.String(100))\n lastname = db.Column(db.String(100))\n email = db.Column(db.String(225))\n\n def __init__(self,username,password,firstname, lastname , email):\n self.username=username\n self.password=password\n self.firstname=firstname\n self.lastname=lastname\n self.email=email\n\n def __repr__(self):\n return '' %self.username \n\n@app.route('/login', methods=[\"POST\", \"GET\"])\ndef login():\n error=None\n if request.method == 'POST':\n session.pop('user' , None)\n username=request.form['username']\n password=request.form['password']\n user= Users.query.filter(username==Users.username, password==Users.password).first()\n if user:\n session['user']=username\n if username=='admin':\n return redirect(url_for('adminhome') )\n else:\n return redirect(url_for('home') )\n else :\n error=\"Invalid User\"\n return render_template('login.html' , error = error)\n else:\n return render_template('login.html')\n\n@app.route('/register', methods=[\"POST\", \"GET\"])\ndef register():\n if request.method =='GET':\n return render_template('register.html')\n if request.method == 'POST':\n firstname = request.form['firstname']\n lastname = request.form['lastname']\n email = request.form['email']\n username = request.form['username']\n password = request.form['password']\n new_user=Users(username, password ,firstname, lastname, email)\n db.session.add(new_user)\n db.session.commit()\n return redirect('/')\n \n@app.route('/dropsession')\ndef dropsession():\n session.pop('user' , None)\n return render_template('login.html')\n\n@app.before_request\ndef before_request():\n try:\n g.user=None\n if 'user' in session:\n g.user=session['user']\n except (TypeError):\n pass\n \n \n \n\n@app.route('/', methods=[\"GET\"]) \ndef index():\n return render_template('login.html')\n\n@app.route('/adminhome', methods=[\"GET\"]) \ndef adminhome():\n if g.user:\n movies=Movie.query.all()\n return render_template('index.html', movies=movies , show_hidden=True , user=session['user'])\n else:\n return redirect(url_for('index'))\n\n@app.route('/home', methods=[\"GET\"]) \ndef home():\n if g.user:\n movies=Movie.query.all()\n return render_template('index.html', movies=movies ,user=session['user'], show_hidden=False)\n else:\n return redirect(url_for('index'))\n\n\n@app.route('/')\ndef single_review(id):\n movie=Movie.query.get(id)\n try:\n if session['user']=='admin':\n show_hidden=True\n else:\n show_hidden=False\n return render_template('single.html', movie=movie , user=session['user'], show_hidden=show_hidden)\n except:\n error=\"EERROORR\"\n\n@app.route('/new', methods=['GET', 'POST'])\ndef new_review():\n error=None\n if g.user:\n if request.method == 'GET':\n return render_template('form.html', user=session['user'], new=True)\n if request.method == 'POST':\n name = request.form['name']\n director = request.form['director']\n imdb = request.form['imdb']\n popularity = request.form['popularity']\n genre = request.form['genre']\n image = request.form['image']\n cast = request.form['cast']\n age = request.form['age']\n release_date = request.form['date']\n if len(release_date)!=0:\n date = parse(release_date)\n else:\n date=None\n description = request.form['description']\n new_review=Movie(name, director, imdb, popularity, genre, image, cast, age, date , description)\n try:\n db.session.add(new_review)\n db.session.commit()\n return redirect('/adminhome')\n except:\n error = \"Database Error\"\n else:\n return redirect(url_for('index'))\n\n@app.route('/edit/', methods=['GET', 'POST'])\ndef edit_review(id):\n if g.user:\n review = Movie.query.get(id)\n if request.method == 'GET':\n return render_template(\n 'form.html',\n user=session['user'],\n new=False,\n id=review.id,\n name=review.name,\n director=review.director,\n imdb=review.imdb,\n popularity=review.popularity,\n genre=review.genre,\n image=review.image,\n cast= review.cast,\n age = review.age_restriction,\n date = review.release_date,\n description = review.description\n\n )\n if request.method == 'POST':\n review.id=id\n review.name = request.form['name']\n review.director = request.form['director']\n review.imdb = request.form['imdb']\n review.popularity = request.form['popularity']\n review.genre = request.form['genre']\n review.image = request.form['image']\n review.cast = request.form['cast']\n review.age_restriction = request.form['age']\n review.release_date = parse(request.form['date'])\n \n review.description = request.form['description']\n db.session.commit()\n return redirect('/adminhome')\n \n else:\n return redirect(url_for('index'))\n\n@app.route('/delete/', methods=['POST', 'GET'])\ndef delete_review(id):\n if g.user:\n error=None\n review=Movie.query.get(id)\n try:\n db.session.delete(review)\n db.session.commit()\n return redirect(\"/adminhome\")\n except:\n error= \"Database Error\"\n else:\n return redirect(url_for('index'))\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"176744955","text":"from django.conf.urls import include, url\nfrom . import views,turnoViews,buscadorViews,selectoresViews,medicoViews,pacienteViews, adminViews, userViews\nfrom django.views.generic import TemplateView\n\nurlpatterns = [\n url(r'^$', views.index),\n #Organizacion\n url(r'^organizacion/new/$', views.organizacion_new, name='organizacion_new'),\n url(r'^organizacion/(?P[0-9]+)/edit/$', views.organizacion_edit, name='organizacion_edit'),\n url(r'^organizacion/(?P[0-9]+)/$', views.organizacion_detail),\n url(r'^organizacion/all/$', views.organizacion_all, name='organizacion_all'),\n\n #Turnos\n url(r'^turno/new/$', turnoViews.turno_new, name='turno_new'),\n\n #Turnos\n url(r'^turno/calendario/$', turnoViews.turnos_calendario, name='calendario'),\n url(r'^turno/(?P[0-9]+)/$', turnoViews.turno_detail,name='turno_detail'),\n\n #Paciente\n \n url(r'^paciente/(?P[0-9]+)/edit/$', pacienteViews.paciente_edit, name='paciente_edit'),\n url(r'^paciente/(?P[0-9]+)/delete/$', pacienteViews.paciente_delete, name='paciente_delete'),\n url(r'^paciente/all/$', pacienteViews.paciente_all, name='paciente_all'),\n url(r'^paciente/nuevo/$', pacienteViews.paciente_nuevo, name='paciente_nuevo'),\n url(r'^paciente/detail/(?P[0-9]+)/$', pacienteViews.paciente_detail, name='paciente_detail'),\n\n #Medico\n \n url(r'^medico/(?P[0-9]+)/edit/$', medicoViews.medico_edit, name='medico_edit'),\n url(r'^medico/(?P[0-9]+)/delete/$', medicoViews.medico_delete, name='medico_delete'),\n url(r'^medico/detail/(?P[0-9]+)/$', medicoViews.medico_detail, name='medico_detail'),\n url(r'^medico/all/$', medicoViews.medico_all, name='medico_all'),\n url(r'^medico/nuevo/$', medicoViews.medico_nuevo, name='medico_nuevo'),\n\n url(r'^historia/new/$', views.historia_new, name='historia_new'),\n url(r'^historia/(?P[0-9]+)/edit/$', views.historia_edit, name='historia_edit'),\n url(r'^historia/(?P[0-9]+)/$', views.historia_detail),\n url(r'^historia/all/$', views.historia_all, name='historia_all'),\n\n #Selector\n url(r'^selectores/buscar/$', buscadorViews.pacientesPorDni, name='buscar_paciente'),\n\n\n #Probando PopUp\n #url(r'^selectores/popup/$', buscadorViews.popup, name='popup'),\n\n #url(r'^foo/$', buscadorViews.prueba, name='prueba'),\n\n #url(r'^foo/$', TemplateView.as_view(template_name='gturnos/selectores/primera.html')),\n #url(r'^foo2/$', TemplateView.as_view(template_name='gturnos/selectores/segunda.html')),\n\n url(r'^buscarPaciente/$', selectoresViews.selectorPacientes, name='selector_paciente'),\n url(r'^buscarMedico/$', selectoresViews.selectorMedicos, name='selector_medico'),\n url(r'^buscarOrg/$', selectoresViews.selectorOrg, name='selector_org'),\n\n \n #url(r'^turno/nuevo/$', selectoresViews.selectorPaciente ,name='nuevoTurno'),\n url(r'^turno/nuevo/$', TemplateView.as_view(template_name='gturnos/turno/nuevoTurno.html'), name='nuevo_turno'),\n\n url(r'^agregarTurno/$', turnoViews.turno_nuevo, name='agregarTurno'),\n #url(r'^medico/nuevoMedico/$', nuevoMedico(template_name='gturnos/medico/nuevoMedico.html')),\n\n #Admin\n url(r'^Administracion/principal/$', adminViews.principal, name='principal'),\n\n #Obra Social\n url(r'^obra/new/$', views.obra_new, name='obra_new'),\n url(r'^obra/(?P[0-9]+)/edit/$', views.obra_edit, name='obra_edit'),\n url(r'^obra/(?P[0-9]+)/$', views.obra_detail),\n url(r'^obra/all/$', views.obra_all, name='obra_all'),\n\n url(r'^usuario/nuevo/$',userViews.nuevo_usuario),\n url(r'^ingresar/$',userViews.ingresar),\n url(r'^cerrar/$',userViews.cerrar,name='cerrar'),\n url(r'^cambiardatos/$',userViews.cambiarDatos_usuario,name='cambiardatos'),\n ]","sub_path":"consultorio/gturnos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"394482074","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\n\n\n# In[2]:\n\n\nfeatures = ['accommodates','bedrooms','bathrooms','beds','price','minimum_nights','maximum_nights','number_of_reviews']\n\nread_listings = pd.read_csv(\"listings.csv\")\nread_features = read_listings[features]\n\nprint(read_features.shape)\n\nread_features.head()\n\n\n# In[6]:\n\n\nimport numpy as np\n#计算accommodate为3时可能的价格\naccommodate_value = 3\nread_features[\"distance\"] = np.abs(read_features[\"accommodates\"] - accommodate_value)\n# print(read_features.head())\n#注意.loc和直接[]的区别,直接用[]才能增加数据\n\nacc_features = read_features.distance.value_counts().sort_index()\n#read_features.distance dtype:float64 read_features.distance.value_counts() dtype:int64\n\nprint(read_features.head())\nprint(acc_features.head())\n#不会改变原始数据\n\n\n#print(type(acc_features))\n#acc_features.sort_value(ascending=False)\n\n\n# In[14]:\n\n\nread_features = read_features.sample(frac = 1, random_state=0)\nread_features = read_features.sort_values(\"distance\")\nread_features.price.head()\n\n\n# In[19]:\n\n\nread_features['price'] = read_features.price.str.replace('\\$|,', '').astype(float)\nread_features.price.head()\n\n\n# In[35]:\n\n\nread_features.head()\nread_price_mean = read_features.price.iloc[:5].mean()\nread_price_mean\n\n\n# In[45]:\n\n\n#现在开始训练\nread_drop_distance = read_features.drop('distance', axis=1)\n#read_drop.head()\n\n# print(read_features.shape)\ntrain_df = read_drop_distance.copy().iloc[:2792]\ntest_df = read_drop_distance.copy().iloc[2792:]\n\n\n# In[59]:\n\n\n\n #单变量预测值\ndef predict_price(new_lists, feature_column):\n #print(\"------\")\n temp_df = train_df\n temp_df['distance'] = np.abs(read_drop_distance[feature_column] - new_lists)\n temp_df = temp_df.sort_values('distance')\n k5_mean_price = temp_df.price.iloc[:5].mean()\n return k5_mean_price \n \n\n\n# In[60]:\n\n\n# test_df['predicted_price'] = test_df[:3].accommodates.apply(predict_price, feature_column = 'accommodates')\ntest_df['predicted_price'] = test_df.accommodates.apply(predict_price, feature_column = 'accommodates')\n#注意参数写法\ntest_df.head()\n\n\n# In[61]:\n\n\n#计算均方根误差\ntest_mse = (test_df['price'] - test_df['predicted_price']) ** (2)\ntest_mse = test_mse.mean()\ntest_sqrt_mse = test_mse ** (1/2)\nprint(test_sqrt_mse)\n\n","sub_path":"11_KNN/pKNN_airbnb_test.py","file_name":"pKNN_airbnb_test.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"53716945","text":"import pandas as pd\nimport csv\nimport re\n\nstyle = ['Contemporary', 'Modern/High Tech', 'Victorian', 'Edwardian', 'Traditional', 'Georgian', \\\n 'RanchView', 'Conversion', 'Art Deco', 'Custom', 'Spanish/Mediterranean', 'Bungalow', \\\n 'Tudor', 'Colonial', 'Spanish', 'Arts & Crafts', 'French', 'English']\n\nmonth_dict = {'January':1, 'February':2, 'March':3, 'April':4, 'May':5, 'June':6, 'July':7,\\\n 'August':8, 'September':9, 'October':10, 'November':11, 'December':12}\n\n\ndef clean_basic(df):\n\t'''\n\tINPUT: Pandas dataframe\n\tOUTPUT: Pandas dataframe containing cleaned basic data\n\t'''\n\tdf = df.dropna(subset=['latitude', 'longitude'])\n\tdf['type'] = ['sfh' if item == 'Single Family Residential' else 'condo' if item =='Condo/Coop' else 'th' for item in df['home type']]\n\tdf= pd.concat([df, pd.get_dummies(df['type'])], axis = 1)\n\tdf = df.drop('type', axis = 1)\n\tdf['garage'] = [True if item == 'Garage' else False for item in df['parking type']]\n\tdf['recent_reduction'] = [True if len(str(item))>6 else False for item in df['recent reduction date']]\n\tdf['short_sale']= [True if item ==True else False for item in df['is short sale']]\n\tdf = df.drop(['parking type','sale type','home type','address','city','state','location','days on market','status',\\\n\t\t 'next open house date','next open house start time','next open house end time',\\\n\t\t 'recent reduction date','original list price',\\\n\t\t 'url (see http://www.redfin.com/buy-a-home/comparative-market-analysis for info on pricing)',\\\n\t\t 'source','original source','favorite','interested'], axis = 1)\n\tdf['lot size'] = df['lot size'].fillna(0)\n\tdf['year built'] = df['year built'].fillna(df['year built'].mean())\n\tdf['parking spots'] = df['parking spots'].fillna(0)\n\tdf = df[df['list price'] > 0]\n\tdf = df[df['sqft'] > 0]\n\tdf = df.drop(['zip'], axis = 1)\n\t#df = pd.concat([d, pd.get_dummies(df['zip'])], axis=1)\n\tdf['age'] = 2015 - df['year built']\n\tdf = df[df['beds'].notnull()]\n\tdf['baths'] = df['baths'].fillna(df['beds']/2)\n\tdf['beds'] = [int(round(item)) for item in df['beds']]\n\tdf['baths'] = [int(round(item)) for item in df['baths']]\n\tdf = df.reset_index()\n\tdf = df.drop('index', axis = 1)\n\treturn df\n\ndef check_style(line):\n\t'''\n\tINPUT: String\n\tOUTPUT: For each style, check if it exits in the string, return a list of styles or None\n\t'''\n\tall_styles = []\n\tfor s in style:\n\t if s in line:\n\t all_styles.append(s)\n\tif len(all_styles) > 0:\n\t return ', '.join(all_styles)\n\telse:\n\t\treturn None\n\ndef change_date(line):\n '''\n INPUT: String\n OUTPUT: Convert string to appropriate date time format, return string in 2015-01-01 format\n '''\n if line == 'N':\n return None\n else:\n mon_day_year = line.split(',')\n mon_day = mon_day_year[1].split(' ')\n month = month_dict[mon_day[1]]\n day = mon_day[2]\n year = mon_day_year[2].strip()\n date = str(year) + '-' + str(month) + '-' + str(day)\n return date\n\ndef clean_meta(df):\n '''\n INPUT: Pandas dataframe\n OUTPUT: Pandas dataframe containing cleaned meta data\n '''\n df['desc_length'] = [len(str(item)) for item in df['description']]\n df['HOA_amount'] = [re.search('HOA\\sDues\\$(\\d*)\\/', str(item)).group(1) \\\n if re.search('HOA\\sDues\\$(\\d*)\\/', str(item)) else 0 for item in df['HOA']]\n df['transport'] = [re.search('\\s*(\\d*\\+*)\\s*B', item).group(1) if re.search('\\s*(\\d*\\+*)\\s*B', item) \\\n else 5 for item in df['transportation']]\n df['transport'] = [4 if item == '+' else item for item in df['transport']]\n df['shop'] = [re.search('\\s*(\\d*\\+*)\\s*B', item).group(1) if re.search('\\s*(\\d*\\+*)\\s*B', item)\\\n else 5 for item in df['shopping']]\n df['shop'] = [4 if item == '4+' else item for item in df['shop']]\n df = df.drop(['HOA', 'transportation', 'shopping'], axis=1)\n df['style2'] = df['style'].apply(lambda x: check_style(x))\n df['style2'] = df['style2'].fillna('Other')\n\n df = df.drop('style', axis = 1)\n df['desc'] = [str(unicode(item).encode('ascii', 'ignore')) for item in df['description']]\n df['list_date_2'] = df['list_date'].apply(lambda x: change_date(x))\n \n df = df.drop('list_date', axis = 1)\n return df\n\ndef combine(df1, df2):\n\t'''\n INPUT: Two Pandas dataframe\n OUTPUT: Pandas dataframe\n '''\n\tdf = pd.merge(df1, df2, how='inner', left_on='rid', right_on='id')\n\tdf.to_csv('../data/clean_data.csv')\n\treturn df\n\nif __name__=='__main__':\n\tbasic_data = pd.read_csv('../data/basic.csv')\n\tdata1 = clean_basic(basic_data)\n\tmeta_data = pd.read_csv('../data/meta.csv')\n\tdata2 = clean_meta(meta_data)\n\tdata1 = data1.drop('Unnamed: 0', axis = 1)\n\tdata2 = data2.drop('Unnamed: 0', axis = 1)\n\tdata2 = data2.drop_duplicates()\n\n\tclean_data = combine(data1, data2)\n\t\n\n","sub_path":"code/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"552017792","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nimport seaborn as sb\n\nminutes = np.array([1,2,3,4,5,6,7,8,9,10])\nvalues = np.array([1,1,2,2,4,4,5,5,6,6])\n\nfig = Figure(figsize=(12,6), dpi=100)\n\n\nplt.subplot(221)\nplt.plot(minutes, values, color=\"green\")\nplt.xticks([1,2,3,4,5,6,7,8,9,10])\n\nplt.subplot(222)\nplt.plot(minutes, values, color=\"blue\")\nplt.xticks([1,2,3,4,5,6,7,8,9,10])\n\nplt.subplot(223)\nplt.plot(minutes, values, color=\"orange\")\nplt.xticks([1,2,3,4,5,6,7,8,9,10])\n\nplt.subplot(224)\nplt.plot(minutes, values, color=\"red\")\nplt.xticks([1,2,3,4,5,6,7,8,9,10])\n\nplt.show()\nplt.clf()","sub_path":"plotpractice.py","file_name":"plotpractice.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"79790820","text":"# coding=utf-8\nfrom __future__ import absolute_import\n\nimport octoprint.plugin\nimport logging\n\nimport re\n\nfrom octoprint.printer.estimation import PrintTimeEstimator\n\n\nclass M73ProgressTimeVisualizer(PrintTimeEstimator):\n def __init__(self, job_type,printer, file_manager, logger, current_history):\n super(M73ProgressTimeVisualizer, self).__init__(job_type)\n self._job_type = job_type\n self.estimated_time = 0\n self.percentage_done = -1\n self._logger = logger\n\n def estimate(self, *args, **kwargs):\n # if self._job_type != \"local\" or self.percentage_done == -1:\n # return PrintTimeEstimator.estimate(self, *args, **kwargs)\n self._logger.debug(\"M73Progress estimate: {}sec\".format(self._estimator.estimated_time))\n return 6 * 60 * 60, \"estimate\"\n\nclass M73ProgressTimeVisualizerPlugin(octoprint.plugin.StartupPlugin):\n\n pw = re.compile('M73 P([0-9]+) R([0-9]+)')\n\n def __init__(self):\n self._estimator = None\n\n def on_after_startup(self):\n self._logger.info(\"Started up M73Progress\")\n\n\n ##~~ queuing gcode hook\n\n def updateEstimation(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):\n if gcode != \"M73\" or self._estimator is None:\n return\n\n mw = self.pw.match(cmd)\n if mw:\n self._estimator.estimated_time = float(mw.group(2))*60 \n self._estimator.percentage_done = float(mw.group(1))\n else :\n return\n\n self._logger.debug(\"M73Progress: {}% {}sec\".format(self._estimator.percentage_done, self._estimator.estimated_time))\n\n ##~~ estimator factory hook\n\n def estimator_factory(self):\n def factory(*args, **kwargs):\n self._estimator = M73ProgressTimeVisualizer(*args, **kwargs)\n return self._estimator\n return factory\n\n ##~~ software update hook\n\n def get_update_information(self):\n return dict(\n gcodestatEstimator=dict(\n displayName=self._plugin_name,\n displayVersion=self._plugin_version,\n\n # version check: github repository\n type=\"github_release\",\n user=\"bitingmonkey\",\n repo=\"OctoPrint-M73Progress\",\n current=self._plugin_version,\n\n # update method: pip\n pip=\"https://github.com/bitingmonkey/OctoPrint-M73TimeVisualizer/archive/{target_version}.zip\"\n )\n )\n\n\n__plugin_implementation__ = M73ProgressTimeVisualizerPlugin()\n__plugin_hooks__ = {\n \"octoprint.comm.protocol.gcode.queuing\": __plugin_implementation__.updateEstimation,\n \"octoprint.printer.estimation.factory\": __plugin_implementation__.estimator_factory,\n \"octoprint.plugin.softwareupdate.check_config\": __plugin_implementation__.get_update_information\n}\n","sub_path":"octoprint_M73TimeVisualizer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"501566010","text":"from django.forms import ModelForm\nfrom core.models import product, profile, user_product_join\nfrom gearkit import utils\n\nclass product_on_user_2(utils.ModalModelForm):\n template=\"forms/user_add_product_form_2.html\"\n\n class Meta:\n model = user_product_join\n fields = ['proof_url', 'proof_description']\n\n def __init__(self, *args, **kwargs):\n self.request=kwargs.pop(\"request\")\n user_id = kwargs.pop(\"instance_id\")\n self.user = profile.objects.get(id=user_id)\n\n product_id = kwargs.pop(\"secondary_id\")\n self.product = product.objects.get(id=product_id)\n\n super(product_on_user_2, self).__init__(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n\n self.instance.profile = self.user\n self.instance.product = self.product\n\n super(product_on_user_2, self).save(*args, **kwargs)\n\nclass product_on_user(utils.ModalModelForm):\n template=\"forms/user_add_product_form.html\"\n\n class Meta:\n model = user_product_join\n fields = []\n\n def __init__(self, *args, **kwargs):\n self.request=kwargs.pop(\"request\")\n self.user_id = kwargs.pop(\"instance_id\")\n\n super(product_on_user, self).__init__(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n pass \n","sub_path":"core/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"447516519","text":"#!/usr/bin/env python\n\n## Create a schema for the table and then create the table.\n\nfrom google.cloud import bigquery\nimport random\nimport string\nimport pycountry\nimport time\n\ndef get_locality():\n high = len(list(pycountry.subdivisions))\n low = 0\n idx = random.randint(low,high)\n return (list(pycountry.subdivisions)[idx]).country_code,(list(pycountry.subdivisions)[idx]).name\n\nid_size = 10 ## Change ID size if bigger is required\nsleep_time = 2 ## Change time to wait as required\nyears = ['2010','2011','2012','2013','2014','2015','2016','2017','2018','2019']\nmonths = ['01','02','03','04','05','06','07','08','09','10','11','12']\ndays = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28']\n\nclient = bigquery.Client()\n\ntable_id = \"innate-entry-286804.rns_sample_dataset.rns_db_5\"\ntable = client.get_table(table_id)\n\nwhile(1):\n itemid = ''.join(random.choices(string.ascii_uppercase + string.digits, k = id_size))\n userid = ''.join(random.choices(string.ascii_uppercase + string.digits, k = id_size))\n quantity = 2 ## Hardcoding this. for this experiment\n geography,location = get_locality() \n hourofday = random.randint(0,24)\n for day in days:\n for month in months:\n for year in years:\n dt = year + \"-\" + month + \"-\" + day\n row = [(itemid,quantity,userid,dt,[(geography,location,hourofday)])]\n errors = client.insert_rows(table,row) ## Making an API Request\n if errors == []:\n print(\"A new row has been added.-Details- {} and {}\".format(geography,location))\n else:\n print(\"A new row could not be added.-Details- {} and {}\".format(geography,location))\n time.sleep(sleep_time)\n","sub_path":"ingestion/stream_data_to_bq_partitioned_table_fieldbased.py","file_name":"stream_data_to_bq_partitioned_table_fieldbased.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"592819150","text":"# ch20_30.py\nimport matplotlib.pyplot as plt\nfrom pylab import mpl\n\nmpl.rcParams[\"font.sans-serif\"] = [\"SimHei\"] # 使用黑體\nmpl.rcParams[\"axes.unicode_minus\"] = False # 讓可以顯示負號\n\nsorts = [u\"交通\",u\"娛樂\",u\"教育\",u\"交通\",u\"餐費\"]\nfee = [8000,2000,3000,5000,6000]\n \nplt.pie(fee,labels=sorts,explode=(0,0.2,0,0,0),\n autopct=\"%1.2f%%\") # 繪製圓餅圖\nplt.show()\n\n","sub_path":"XB1828_Python零基礎最強入門之路-王者歸來_範例檔案New/ch20/ch20_30.py","file_name":"ch20_30.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"10896399","text":"from solution import Solution\n\n# DON'T TOUCH THIS FILE. ASSESSMENT WILL REPLACE THIS FILE\n\n\ndef test_valid_number_pattern():\n number1 = Solution().is_valid_number_pattern(\"TN-12-1234\")\n number2 = Solution().is_valid_number_pattern(\"TN-12-A-1234\")\n number3 = Solution().is_valid_number_pattern(\"TN-12-AB-1234\")\n number4 = Solution().is_valid_number_pattern(\"TN-12-ABC-1234\")\n\n assert number1\n assert number2\n assert number3\n assert number4\n\n number5 = Solution().is_valid_number_pattern(\"TN-12-ABCD-1234\")\n number6 = Solution().is_valid_number_pattern(\"OLA1234\")\n number7 = Solution().is_valid_number_pattern(\"TN-12-12345\")\n number8 = Solution().is_valid_number_pattern(\"UT-12-abcd\")\n number9 = Solution().is_valid_number_pattern(\"UT-12--4578\")\n\n\n assert not number5\n assert not number6\n assert not number7\n assert not number8\n assert not number9\n\n\ndef test_number_pattern():\n number1 = Solution().is_registered_in_india(\"3145\", \"31-23-45\")\n number2 = Solution().is_registered_in_india(\"3245\", \"31-23-45\")\n number3 = Solution().is_registered_in_india(\"3135\", \"31-23-45\")\n number4 = Solution().is_registered_in_india(\"3235\", \"31-23-45\")\n\n assert number1[0]\n assert number2[0]\n assert number3[0]\n assert number4[0]\n\n number1 = Solution().is_registered_in_india(\"4435\", \"31-23-45\")\n number2 = Solution().is_registered_in_india(\"4445\", \"31-23-45\")\n number3 = Solution().is_registered_in_india(\"4415\", \"31-23-45\")\n expected1 = \"3135\"\n expected2 = \"3145\"\n expected3 = \"3135\"\n\n assert expected1 == number1[1]\n assert expected2 == number2[1]\n assert expected3 == number3[1]\n\n\ndef test_palindrome():\n assert Solution().is_number_palindrome(\"1221\")\n assert Solution().is_number_palindrome(\"2112\")\n assert Solution().is_number_palindrome(\"1111\")\n assert not Solution().is_number_palindrome(\"2121\")\n assert not Solution().is_number_palindrome(\"2221\")\n assert not Solution().is_number_palindrome(\"2212\")\n\ndef main():\n\n t = int(input())\n pattern_list = list()\n for _ in range(t):\n vehicle_type, pattern = input().rstrip(\"\\n\\r\").split(\" \")\n pattern_list.append([vehicle_type, pattern])\n\n n = int(input())\n queries = list()\n for _ in range(n):\n plate_string, vehicle_type = input().rstrip(\"\\n\\r\").split(' ')\n queries.append([plate_string, vehicle_type])\n Solution().lucky_number(pattern_list, queries)\n\n\nif __name__ == \"__main__\":\n test_valid_number_pattern()\n test_number_pattern()\n test_palindrome()\n main()\n","sub_path":"SameersChoice/SameersChoice.py","file_name":"SameersChoice.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"284038075","text":"from django.conf.urls import url\nfrom django.contrib.auth.views import LoginView ,LogoutView\n\nfrom profiles.views import (\n UserLoginView,\n UserCreateView,\n DistributorCreateView,\n DistributorPendingListView,\n confirm_distributor, # FBV\n DistributorItemsListView,\n)\nurlpatterns = [\n url(r'^login/$', UserLoginView.as_view(redirect_authenticated_user=True), name='login'),\n url(r'^logout/$', LogoutView.as_view(), name='logout'),\n url(r'^register/$', UserCreateView.as_view(), name='register'),\n url(r'^distributors/create/$', DistributorCreateView.as_view(), name='distributor_create'),\n url(r'^distributors/pending/$', DistributorPendingListView.as_view(), name='distributors'),\n url(r'^distributors/pending/confirm/$', confirm_distributor, name='distributor_confirm'),\n url(r'^distributors/my-items/$', DistributorItemsListView.as_view(), name='distributor_items'),\n\n]\n","sub_path":"FULL Pre/herbco/apps/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"66559830","text":"import tensorflow as tf\nfrom tensorflow.contrib import slim\nimport cv2\nimport os\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\nimport common as cm\n\n\nsave_path = r\"model_saver\\AE_circle\"\nout_dir_prefix=os.path.join(save_path,\"model\")\nheight = 64\nwidth = 64\nepochs = 50\nGPU_ratio = 0.2\nbatch_size = 12\ntrain_ratio = 0.7\n\n\nclass AE():\n\n def __init__(self, input_dim=[None, 64, 64, 3], save_path=\"model_saver\\ckpt\"):\n\n self.input_dim = input_dim\n self.save_path = save_path\n self.kel_x = 9\n self.kel_y = 9\n self.deep = 64\n self.__build_model()\n print(\"initial\")\n\n def __build_model(self):\n\n self.input_x = tf.placeholder(tf.float32, self.input_dim, name=\"input_x\")\n\n self.prediction = self.__inference(self.input_x)\n\n self.save_path = save_path\n\n if not os.path.exists(self.save_path):\n os.makedirs(self.save_path)\n\n self.saver = tf.train.Saver(max_to_keep=20)\n\n self.out_dir_prefix = os.path.join(save_path, \"model\")\n\n self.loss = tf.reduce_mean(tf.pow(self.prediction - self.input_x, 2))\n\n self.optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(self.loss)\n\n def __inference(self, input_x):\n\n with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.conv2d_transpose],\n activation_fn=tf.nn.relu,\n # normalizer_fn=slim.batch_norm,\n # normalizer_params={'is_training': True, 'decay': 0.995},\n weights_initializer=tf.truncated_normal_initializer(0.0, 0.01),\n weights_regularizer=slim.l2_regularizer(0.0005),\n reuse=tf.AUTO_REUSE):\n self.net = slim.conv2d(self.input_x, 64, [self.kel_x, self.kel_y], scope='encode1')\n self.net = slim.max_pool2d(self.net, [2, 2], scope='pool1')\n print(\"encode1 shape = \", self.net.shape)\n\n # net shape = 32 x 32 x 64\n\n self.net = slim.conv2d(self.net, 64, [self.kel_x, self.kel_y], scope='encode2')\n self.net = slim.max_pool2d(self.net, [2, 2], scope='pool2')\n print(\"encode2 shape = \", self.net.shape)\n\n # net shape = 16 x 16 x 64\n\n self.net = slim.conv2d(self.net, 64, [self.kel_x, self.kel_y], scope='encode3')\n self.net = slim.max_pool2d(self.net, [2, 2], scope='pool3')\n print(\"encode3 shape = \", self.net.shape)\n\n # net shape = 8 x 8 x 64\n\n self.net = slim.conv2d(self.net, 64, [self.kel_x, self.kel_y], scope='encode4')\n self.net = slim.max_pool2d(self.net, [2, 2], scope='pool4')\n print(\"encode4 shape = \", self.net.shape)\n\n # net shape = 4 x 4 x 64\n\n self.net = slim.conv2d_transpose(self.net, 64, [2, 2], stride=2, activation_fn=None, padding=\"VALID\",\n scope=\"unpool1\")\n self.net = slim.conv2d(self.net, 64, [self.kel_x, self.kel_y], scope='decode1_1')\n print(\"decode1 shape = \", self.net.shape)\n\n # net shape = 8 x 8 x 64\n\n self.net = slim.conv2d_transpose(self.net, 64, [2, 2], stride=2, activation_fn=None, padding=\"VALID\",\n scope=\"unpool2\")\n self.net = slim.conv2d(self.net, 64, [self.kel_x, self.kel_y], scope='decode2_3')\n print(\"decode2 shape = \", self.net.shape)\n\n # net shape = 16 x 16 x 64\n\n self.net = slim.conv2d_transpose(self.net, 64, [2, 2], stride=2, activation_fn=None, padding=\"VALID\",\n scope=\"unpool3\")\n # net = unpooling(net,[64,64])\n self.net = slim.conv2d(self.net, 64, [self.kel_x, self.kel_y], scope='decode3_1')\n print(\"decode3 shape = \", self.net.shape)\n\n # net shape = 32 x 32 x 64\n\n self.net = slim.conv2d_transpose(self.net, 64, [2, 2], stride=2, activation_fn=None, padding=\"VALID\",\n scope=\"unpool4\")\n # net = unpooling(net,[64,64])\n self.net = slim.conv2d(self.net, 3, [self.kel_x, self.kel_y], scope='decode4')\n # net +=net1\n print(\"decode4 shape = \", self.net.shape)\n\n # net shape = 64 x 64 x 3\n\n return self.net\n\n def train(self, train_data, test_data, test_label, GPU_ratio=0.2, epochs=50, batch_size=16, fine_tune=False,\n save_ckpt=True):\n\n # self.GPU_ratio = GPU_ratio\n # self.epochs = epochs\n # self.batch_size = batch_size\n\n # 計算total batch\n total_batches = train_data.shape[0] // batch_size\n if train_data.shape[0] % batch_size:\n total_batches += 1\n\n # 設定GPU參數\n config = tf.ConfigProto(log_device_placement=True,\n allow_soft_placement=True, # 允許當找不到設備時自動轉換成有支援的設備\n )\n config.gpu_options.per_process_gpu_memory_fraction = GPU_ratio\n\n with tf.Session(config=config) as sess:\n\n if fine_tune is True: # 使用已經訓練好的權重繼續訓練\n files = [file.path for file in os.scandir(self.save_path) if file.is_file()]\n\n if not files: # 沒有任何之前的權重\n\n sess.run(tf.global_variables_initializer())\n\n print('no previous model param can be used')\n\n else:\n\n self.saver.restore(sess, tf.train.latest_checkpoint(self.save_path))\n\n print('use previous model param')\n\n else:\n sess.run(tf.global_variables_initializer())\n print('no previous model param can be used')\n\n for epoch in range(epochs):\n\n for index in range(total_batches):\n\n num_start = index * batch_size\n num_end = num_start + batch_size\n\n if num_end >= train_data.shape[0] and batch_size > 1:\n num_end = train_data.shape[0] - 1\n\n sess.run(self.optimizer, feed_dict={self.input_x: train_data[num_start:num_end]})\n\n # compute mean loss after a epoch\n train_loss = []\n for index in range(train_data.shape[0]):\n single_loss = sess.run(self.loss, feed_dict={self.input_x: train_data[index:index + 1]})\n\n train_loss.append(single_loss)\n\n train_loss = np.array(train_loss)\n train_loss = np.mean(train_loss)\n\n test_loss = []\n acc = 0\n for index in range(test_data.shape[0]):\n\n single_loss = sess.run(self.loss, feed_dict={self.input_x: test_data[index:index + 1]})\n\n test_loss.append(single_loss)\n\n if single_loss > train_loss:\n\n if test_label[index] == 0 or test_label[index] == 1:\n acc += 1\n\n elif single_loss >= 0:\n\n if test_label[index] == 2:\n acc += 1\n\n acc /= test_data.shape[0]\n test_loss = np.array(test_loss)\n test_loss = np.mean(test_loss)\n print(\"Epoch {}\\ntrain set loss = {}\".format(epoch, train_loss))\n print(\"test set loss = {}, accuracy = {}\".format(test_loss, acc))\n\n # 紀錄資料:本次epoch ckpt檔\n if save_ckpt is True:\n model_save_path = self.saver.save(sess, self.out_dir_prefix, global_step=epoch)\n\n print('Save model checkpoint to ', model_save_path)\n\n def eval(self, train_data, test_data, test_label, GPU_ratio=0.2):\n\n total_loss = []\n single_loss = 0\n\n # 設定GPU參數\n config = tf.ConfigProto(log_device_placement=True,\n allow_soft_placement=True, # 允許當找不到設備時自動轉換成有支援的設備\n )\n config.gpu_options.per_process_gpu_memory_fraction = GPU_ratio\n\n with tf.Session(config=config) as sess:\n\n self.saver.restore(sess, tf.train.latest_checkpoint(self.save_path))\n\n print('use previous model param')\n\n for i in range(train_data.shape[0]):\n single_loss = sess.run(self.loss, feed_dict={self.input_x: train_data[i:i + 1]})\n\n total_loss.append(single_loss)\n\n total_loss = np.array(total_loss)\n\n train_ave_loss = np.mean(total_loss)\n\n total_loss = []\n\n acc = 0\n\n for i in range(test_data.shape[0]):\n\n single_loss = sess.run(self.loss, feed_dict={self.input_x: test_data[i:i + 1]})\n\n if single_loss > train_ave_loss:\n\n if test_label[i] == 0 or test_label[i] == 1:\n acc += 1\n\n elif single_loss >= 0:\n\n if test_label[i] == 2:\n acc += 1\n\n total_loss.append(single_loss)\n\n acc /= test_data.shape[0]\n\n total_loss = np.array(total_loss)\n\n test_ave_loss = np.mean(total_loss)\n\n return train_ave_loss, test_ave_loss, acc\n\n#prepare training data\npic_path = r'E:\\dataset\\YOLOv2\\Good_samples'\n(x_train, x_train_label, no1, no2) = cm.data_load(pic_path, train_ratio=1, resize=(width, height), has_dir=False)\nprint(x_train.shape)\n#print(x_train_label)\n\n\n#prepare test data\npic_path = r'E:\\dataset\\xxx'\n(x_train_2,x_train_label_2,x_test_2,x_test_label_2) = cm.data_load(pic_path,train_ratio,resize=(width,height),shuffle = True,normalize = True)\n# print('x_train shape = ',x_train_2.shape)\n# print('x_train_label shape = ',x_train_label_2.shape)\nprint('x_test shape = ',x_test_2.shape)\nprint('x_test_label shape = ',x_test_label_2.shape)\n\n\nae = AE()\nae.train(x_train,x_test_2,x_test_label_2,epochs = 10)","sub_path":"autoencoder_test.py","file_name":"autoencoder_test.py","file_ext":"py","file_size_in_byte":10123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"428700795","text":"import numpy as np\n\n\ndef p4_sum(obj1, obj2):\n assert(obj1.shape==obj2.shape)\n px = np.zeros(obj1.shape[0])\n py = np.zeros(obj1.shape[0])\n pz = np.zeros(obj1.shape[0])\n e = np.zeros(obj1.shape[0])\n \n for obj in [obj1, obj2]:\n px_ = obj.pt*np.cos(obj.phi)\n py_ = obj.pt*np.sin(obj.phi)\n pz_ = obj.pt*np.sinh(obj.eta)\n e_ = np.sqrt(px_**2 + py_**2 + pz_**2 + obj.mass**2)\n px = px + px_\n py = py + py_\n pz = pz + pz_\n e = e + e_\n \n pt = np.sqrt(px**2 + py**2)\n eta = np.arcsinh(pz / pt)\n phi = np.arctan2(py, px)\n mass = np.sqrt(e**2 - px**2 - py**2 - pz**2)\n return pt, eta, phi, mass\n\ndef p4_sum_alt(obj1_pt, obj1_eta, obj1_phi, obj1_mass, obj2_pt, obj2_eta, obj2_phi, obj2_mass):\n assert(len(obj1_pt)==len(obj2_pt))\n px = np.zeros(len(obj1_pt))\n py = np.zeros(len(obj1_pt))\n pz = np.zeros(len(obj1_pt))\n e = np.zeros(len(obj1_pt))\n obj1 = {\n 'pt': obj1_pt,\n 'eta': obj1_eta,\n 'phi': obj1_phi,\n 'mass': obj1_mass,\n }\n obj2 = {\n 'pt': obj2_pt,\n 'eta': obj2_eta,\n 'phi': obj2_phi,\n 'mass': obj2_mass,\n }\n\n for obj in [obj1, obj2]:\n px_ = obj['pt']*np.cos(obj['phi'])\n py_ = obj['pt']*np.sin(obj['phi'])\n pz_ = obj['pt']*np.sinh(obj['eta'])\n e_ = np.sqrt(px_**2 + py_**2 + pz_**2 + obj['mass']**2)\n px = px + px_\n py = py + py_\n pz = pz + pz_\n e = e + e_\n \n pt = np.sqrt(px**2 + py**2)\n eta = np.arcsinh(pz / pt)\n phi = np.arctan2(py, px)\n mass = np.sqrt(e**2 - px**2 - py**2 - pz**2)\n return pt, eta, phi, mass\n\ndef delta_r(eta1, eta2, phi1, phi2):\n deta = abs(eta1 - eta2)\n dphi = abs(np.mod(phi1 - phi2 + np.pi, 2*np.pi) - np.pi)\n dr = np.sqrt(deta**2 + dphi**2)\n return deta, dphi, dr","sub_path":"python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"532339879","text":"#! /usr/bin/env python\n\nfrom os import listdir, path\nimport json\n\nse = [\"Fire\",\n \"Water\",\n \"Wood\",\n \"Light\",\n \"Ice\",\n \"Lightning\",\n \"Virus\",\n \"Dimension\",\n \"Psychic\",\n \"Emotion\",\n \"Dark\",\n \"Ghost\"]\n\ndef special_elements():\n return se\n\napp_lib = path.dirname(path.realpath(__file__))\nmoves = {}\ntry: files = listdir(path.join(app_lib, \"moves\"))\nexcept: pass\nelse:\n for fname in files:\n try:\n file_ = open(path.join(app_lib, \"moves\", fname))\n moves = dict(moves.items() + json.load(file_).items())\n file_.close()\n except: pass\nmoves[\"Struggle\"] = {\"power\": 50, \"element\": \"none\", \"hp_cost\": 0.25, \"summary\": \"The user struggles to do damage at the cost of 25% HP.\"}\nfor move in moves:\n try: moves[move][\"accuracy\"]\n except: moves[move][\"accuracy\"] = 100\n try: moves[move][\"power\"]\n except: moves[move][\"power\"] = 0\n try: moves[move][\"cost\"]\n except: moves[move][\"cost\"] = 0\n try: moves[move][\"summary\"]\n except: moves[move][\"summary\"] = \"No description.\"\n try: moves[move][\"target\"]\n except: moves[move][\"target\"] = 1\n try: moves[move][\"element\"]\n except: moves[move][\"element\"] = \"Normal\"\n\ndef get_moves():\n return moves\n\ndef get_signatures():\n signatures = {}\n for name, details in get_moves().items():\n if type(details) is dict:\n if \"signature\" in details.keys():\n if details[\"signature\"] == True:\n signatures[name] = details\n return signatures\n","sub_path":"rpg_battle_system_lib/moves.py","file_name":"moves.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"451133414","text":"from rubick.schema import ConfigSchemaRegistry\n\nnova = ConfigSchemaRegistry.register_schema(project='nova')\n\nwith nova.version('2013.1.4') as nova_2013_1_4:\n\n nova_2013_1_4.param(\n 'internal_service_availability_zone', type='string', default='internal',\n description=\"availability_zone to show internal services under\")\n\n nova_2013_1_4.param('default_availability_zone', type='string',\n default='nova',\n description=\"default compute node availability_zone\")\n\n nova_2013_1_4.param('ca_file', type='string',\n default='cacert.pem', description=\"Filename of root CA\")\n\n nova_2013_1_4.param('key_file', type='string', default='private/cakey.pem',\n description=\"Filename of private key\")\n\n nova_2013_1_4.param('crl_file', type='string', default='crl.pem',\n description=\"Filename of root Certificate Revocation List\")\n\n nova_2013_1_4.param('keys_path', type='string',\n default='$state_path/keys', description=\"Where we keep our keys\")\n\n nova_2013_1_4.param('ca_path', type='string', default='$state_path/CA',\n description=\"Where we keep our root CA\")\n\n nova_2013_1_4.param('use_project_ca', type='boolean', default='false',\n description=\"Should we use a CA for each project?\")\n\n nova_2013_1_4.param(\n 'user_cert_subject', type='string',\n default='/CUS/STCalifornia/OOpenStack/OUNovaDev/CN%.16s-%.16s-%s',\n description=\"Subject for certificate for users, %s for project, \"\n \"user, timestamp\")\n\n nova_2013_1_4.param(\n 'project_cert_subject', type='string',\n default='/CUS/STCalifornia/OOpenStack/OUNovaDev/CNproject-ca-%.16s-%s',\n description=\"Subject for certificate for projects, %s for project, \"\n \"timestamp\")\n\n nova_2013_1_4.param('fatal_exception_format_errors', type='boolean',\n default='false', description=\"make exception message format errors\"\n \" fatal\")\n\n nova_2013_1_4.param(\n 'run_external_periodic_tasks', type='boolean', default='true',\n description=\"Some periodic tasks can be run in a separate process.\"\n \" Should we run them here?\")\n\n nova_2013_1_4.param('my_ip', type='string', default='10.0.0.1',\n description=\"ip address of this host\")\n\n nova_2013_1_4.param('host', type='string', default='nova',\n description=\"Name of this node. This can be an opaque identifier.\"\n \" It is not necessarily a hostname, FQDN, or IP\"\n \" address. However, the node name must be valid within\"\n \" an AMQP key, and if using ZeroMQ, a valid hostname,\"\n \" FQDN, or IP address\")\n\n nova_2013_1_4.param(\n 'use_ipv6',\n type='boolean',\n default='false',\n description=\"use ipv6\")\n\n nova_2013_1_4.param(\n 'notify_on_any_change', type='boolean', default='false',\n description=\"If set, send compute.instance.update notifications\"\n \" on instance state changes. Valid values are False\"\n \" for no notifications, True for notifications on any\"\n \" instance changes.\")\n\n nova_2013_1_4.param('notify_api_faults', type='boolean', default='false',\n description=\"If set, send api.fault notifications on caught \"\n \"exceptions in the API service.\")\n\n nova_2013_1_4.param(\n 'notify_on_state_change', type='string', default='',\n description=\"If set, send compute.instance.update notifications \"\n \"on instance state changes. Valid values are None for\"\n \" no notifications, 'vm_state' for notifications on VM\"\n \" state changes, or 'vm_and_task_state' for\"\n \" notifications on VM and task state changes.\")\n\n nova_2013_1_4.param(\n 'pybasedir', type='string', default='/usr/lib/python/site-packages',\n description=\"Directory where the nova python module is installed\")\n\n nova_2013_1_4.param('bindir', type='string', default='$pybasedir/bin',\n description=\"Directory where nova binaries are installed\")\n\n nova_2013_1_4.param('state_path', type='string', default='$pybasedir',\n description=\"Top-level directory for maintaining nova's state\")\n\n nova_2013_1_4.param('policy_file', type='string', default='policy.json',\n description=\"JSON file representing policy\")\n\n nova_2013_1_4.param(\n 'policy_default_rule', type='string', default='default',\n description=\"Rule checked when requested rule is not found\")\n\n nova_2013_1_4.param('quota_instances', type='integer', default='10',\n description=\"number of instances allowed per project\")\n\n nova_2013_1_4.param('quota_cores', type='integer', default='20',\n description=\"number of instance cores allowed per project\")\n\n nova_2013_1_4.param('quota_ram', type='integer', default='51200',\n description=\"megabytes of instance ram allowed per project\")\n\n nova_2013_1_4.param('quota_floating_ips', type='integer', default='10',\n description=\"number of floating ips allowed per project\")\n\n nova_2013_1_4.param('quota_metadata_items', type='integer', default='128',\n description=\"number of metadata items allowed per instance\")\n\n nova_2013_1_4.param('quota_injected_files', type='integer',\n default='5', description=\"number of injected files allowed\")\n\n nova_2013_1_4.param('quota_injected_file_content_bytes', type='integer',\n default='10240', description=\"number of bytes allowed per injected\"\n \" file\")\n\n nova_2013_1_4.param(\n 'quota_injected_file_path_bytes', type='integer', default='255',\n description=\"number of bytes allowed per injected file path\")\n\n nova_2013_1_4.param('quota_security_groups', type='integer', default='10',\n description=\"number of security groups per project\")\n\n nova_2013_1_4.param(\n 'quota_security_group_rules', type='integer', default='20',\n description=\"number of security rules per security group\")\n\n nova_2013_1_4.param('quota_key_pairs', type='integer',\n default='100', description=\"number of key pairs per user\")\n\n nova_2013_1_4.param('reservation_expire', type='integer', default='86400',\n description=\"number of seconds until a reservation expires\")\n\n nova_2013_1_4.param('until_refresh', type='integer', default='0',\n description=\"count of reservations until usage is refreshed\")\n\n nova_2013_1_4.param('max_age', type='integer', default='0',\n description=\"number of seconds between subsequent usage refreshes\")\n\n nova_2013_1_4.param(\n 'quota_driver', type='string', default='nova.quota.DbQuotaDriver',\n description=\"default driver to use for quota checks\")\n\n nova_2013_1_4.param('report_interval', type='integer', default='10',\n description=\"seconds between nodes reporting state to datastore\")\n\n nova_2013_1_4.param('periodic_enable', type='boolean',\n default='true', description=\"enable periodic tasks\")\n\n nova_2013_1_4.param('periodic_fuzzy_delay', type='integer', default='60',\n description=\"range of seconds to randomly delay when starting the \"\n \"periodic task scheduler to reduce stampeding.\")\n\n nova_2013_1_4.param(\n 'enabled_apis', type='list', default='ec2,osapi_compute,metadata',\n description=\"a list of APIs to enable by default\")\n\n nova_2013_1_4.param('enabled_ssl_apis', type='list', default='',\n description=\"a list of APIs with enabled SSL\")\n\n nova_2013_1_4.param('ec2_listen', type='string', default='0.0.0.0',\n description=\"IP address for EC2 API to listen\")\n\n nova_2013_1_4.param('ec2_listen_port', type='integer',\n default='8773', description=\"port for ec2 api to listen\")\n\n nova_2013_1_4.param('ec2_workers', type='integer', default='',\n description=\"Number of workers for EC2 API service\")\n\n nova_2013_1_4.param(\n 'osapi_compute_listen', type='string', default='0.0.0.0',\n description=\"IP address for OpenStack API to listen\")\n\n nova_2013_1_4.param('osapi_compute_listen_port', type='integer',\n default='8774', description=\"list port for osapi compute\")\n\n nova_2013_1_4.param(\n 'osapi_compute_workers', type='integer', default='',\n description=\"Number of workers for OpenStack API service\")\n\n nova_2013_1_4.param(\n 'metadata_manager', type='string',\n default='nova.api.manager.MetadataManager',\n description=\"OpenStack metadata service manager\")\n\n nova_2013_1_4.param('metadata_listen', type='string', default='0.0.0.0',\n description=\"IP address for metadata api to listen\")\n\n nova_2013_1_4.param('metadata_listen_port', type='integer',\n default='8775', description=\"port for metadata api to listen\")\n\n nova_2013_1_4.param('metadata_workers', type='integer', default='',\n description=\"Number of workers for metadata service\")\n\n nova_2013_1_4.param(\n 'compute_manager', type='string',\n default='nova.compute.manager.ComputeManager',\n description=\"full class name for the Manager for compute\")\n\n nova_2013_1_4.param(\n 'console_manager', type='string',\n default='nova.console.manager.ConsoleProxyManager',\n description=\"full class name for the Manager for console proxy\")\n\n nova_2013_1_4.param(\n 'cert_manager', type='string', default='nova.cert.manager.CertManager',\n description=\"full class name for the Manager for cert\")\n\n nova_2013_1_4.param(\n 'network_manager', type='string',\n default='nova.network.manager.VlanManager',\n description=\"full class name for the Manager for network\")\n\n nova_2013_1_4.param(\n 'scheduler_manager', type='string',\n default='nova.scheduler.manager.SchedulerManager',\n description=\"full class name for the Manager for scheduler\")\n\n nova_2013_1_4.param('service_down_time', type='integer', default='60',\n description=\"maximum time since last check-in for up service\")\n\n nova_2013_1_4.param('sqlite_clean_db', type='string',\n default='clean.sqlite', description=\"File name of clean sqlite db\")\n\n nova_2013_1_4.param('monkey_patch', type='boolean', default='false',\n description=\"Whether to log monkey patching\")\n\n nova_2013_1_4.param(\n 'monkey_patch_modules', type='list',\n default='nova.api.ec2.cloud:nova.openstack.common.notifier.api'\n '.notify_decorator,nova.compute.api:nova.openstack.common'\n '.notifier.api.notify_decorator',\n description=\"List of modules/decorators to monkey patch\")\n\n nova_2013_1_4.param('password_length', type='integer', default='12',\n description=\"Length of generated instance admin passwords\")\n\n nova_2013_1_4.param('disable_process_locking', type='boolean',\n default='false',\n description=\"Whether to disable inter-process locks\")\n\n nova_2013_1_4.param(\n 'instance_usage_audit_period', type='string', default='month',\n description=\"time period to generate instance usages for. Time \"\n \"period must be hour, day, month or year\")\n\n nova_2013_1_4.param(\n 'rootwrap_config', type='string', default='/etc/nova/rootwrap.conf',\n description=\"Path to the rootwrap configuration file to use for \"\n \"running commands as root\")\n\n nova_2013_1_4.param('tempdir', type='string', default='',\n description=\"Explicitly specify the temporary working directory\")\n\n nova_2013_1_4.param(\n 'api_paste_config', type='string', default='api-paste.ini',\n description=\"File name for the paste.deploy config for nova-api\")\n\n nova_2013_1_4.param(\n 'wsgi_log_format', type='string',\n default='%(client_ip)s \"%(request_line)s\" status: %(status_code)s len: '\n '%(body_length)s time: %(wall_seconds).7f',\n description=\"A python format string that is used as the template to \"\n \"generate log lines. The following values can be formatted \"\n \"into it: client_ip, date_time, request_line, status_code, \"\n \"body_length, wall_seconds.\")\n\n nova_2013_1_4.param('ssl_ca_file', type='string', default='',\n description=\"CA certificate file to use to verify connecting \"\n \"clients\")\n\n nova_2013_1_4.param('ssl_cert_file', type='string', default='',\n description=\"SSL certificate of API server\")\n\n nova_2013_1_4.param('ssl_key_file', type='string', default='',\n description=\"SSL private key of API server\")\n\n nova_2013_1_4.param('tcp_keepidle', type='integer', default='600',\n description=\"Sets the value of TCP_KEEPIDLE in seconds for each \"\n \"server socket. Not supported on OS X.\")\n\n nova_2013_1_4.param('api_rate_limit', type='boolean',\n default='true', description=\"whether to rate limit the api\")\n\n nova_2013_1_4.param('auth_strategy', type='string', default='noauth',\n description=\"The strategy to use for auth: noauth or keystone.\")\n\n nova_2013_1_4.param('use_forwarded_for', type='boolean', default='false',\n description=\"Treat X-Forwarded-For as the canonical remote address.\"\n \" Only enable this if you have a sanitizing proxy.\")\n\n nova_2013_1_4.param('lockout_attempts', type='integer', default='5',\n description=\"Number of failed auths before lockout.\")\n\n nova_2013_1_4.param('lockout_minutes', type='integer', default='15',\n description=\"Number of minutes to lockout if triggered.\")\n\n nova_2013_1_4.param('lockout_window', type='integer', default='15',\n description=\"Number of minutes for lockout window.\")\n\n nova_2013_1_4.param(\n 'keystone_ec2_url', type='string',\n default='http://localhost:5000/v2.0/ec2tokens',\n description=\"URL to get token from ec2 request.\")\n\n nova_2013_1_4.param(\n 'ec2_private_dns_show_ip', type='boolean', default='false',\n description=\"Return the IP address as private dns hostname in \"\n \"describe instances\")\n\n nova_2013_1_4.param(\n 'ec2_strict_validation', type='boolean', default='true',\n description=\"Validate security group names according to EC2 \"\n \"specification\")\n\n nova_2013_1_4.param('ec2_timestamp_expiry', type='integer', default='300',\n description=\"Time in seconds before ec2 timestamp expires\")\n\n nova_2013_1_4.param('ec2_host', type='string', default='$my_ip',\n description=\"the ip of the ec2 api server\")\n\n nova_2013_1_4.param('ec2_dmz_host', type='string', default='$my_ip',\n description=\"the internal ip of the ec2 api server\")\n\n nova_2013_1_4.param('ec2_port', type='integer', default='8773',\n description=\"the port of the ec2 api server\")\n\n nova_2013_1_4.param('ec2_scheme', type='string', default='http',\n description=\"the protocol to use when connecting to the ec2 api \"\n \"server\")\n\n nova_2013_1_4.param('ec2_path', type='string', default='/services/Cloud',\n description=\"the path prefix used to call the ec2 api server\")\n\n nova_2013_1_4.param('region_list', type='list', default='',\n description=\"list of region=fqdn pairs separated by commas\")\n\n nova_2013_1_4.param(\n 'config_drive_skip_versions', type='string',\n default='1.0 2007-01-19 2007-03-01 2007-08-29 2007-10-10 2007-12-15 '\n '2008-02-01 2008-09-01',\n description=\"List of metadata versions to skip placing into the \"\n \"config drive\")\n\n nova_2013_1_4.param(\n 'service_quantum_metadata_proxy', type='boolean', default='false',\n description=\"Set flag to indicate Quantum will proxy metadata \"\n \"requests and resolve instance ids.\")\n\n nova_2013_1_4.param(\n 'quantum_metadata_proxy_shared_secret', type='string', default='',\n description=\"Shared secret to validate proxies Quantum metadata \"\n \"requests\")\n\n nova_2013_1_4.param('osapi_max_limit', type='integer', default='1000',\n description=\"the maximum number of items returned in a single \"\n \"response from a collection resource\")\n\n nova_2013_1_4.param(\n 'osapi_compute_link_prefix', type='string', default='',\n description=\"Base URL that will be presented to users in links to \"\n \"the OpenStack Compute API\")\n\n nova_2013_1_4.param(\n 'osapi_glance_link_prefix', type='string', default='',\n description=\"Base URL that will be presented to users in links to \"\n \"glance resources\")\n\n nova_2013_1_4.param('allow_instance_snapshots', type='boolean',\n default='true', description=\"Permit instance snapshot operations.\")\n\n nova_2013_1_4.param('osapi_compute_ext_list', type='list', default='',\n description=\"Specify list of extensions to load when using \"\n \"osapi_compute_extension option with nova.api\"\n \".openstack.compute.contrib.select_extensions\")\n\n nova_2013_1_4.param('fping_path', type='string',\n default='/usr/sbin/fping', description=\"Full path to fping.\")\n\n nova_2013_1_4.param(\n 'osapi_hide_server_address_states', type='list', default='building',\n description=\"List of instance states that should hide network info\")\n\n nova_2013_1_4.param(\n 'enable_network_quota', type='boolean', default='false',\n description=\"Enables or disables quotaing of tenant networks\")\n\n nova_2013_1_4.param(\n 'use_quantum_default_nets', type='string', default='False',\n description=\"Control for checking for default networks\")\n\n nova_2013_1_4.param(\n 'quantum_default_tenant_id', type='string', default='default',\n description=\"Default tenant id when creating quantum networks\")\n\n nova_2013_1_4.param('osapi_compute_extension', type='multi',\n default='nova.api.openstack.compute.contrib.standard_extensions',\n description=\"osapi compute extension to load\")\n\n nova_2013_1_4.param(\n 'enable_instance_password', type='boolean', default='true',\n description=\"Allows use of instance password during server \"\n \"creation\")\n\n nova_2013_1_4.param(\n 'osapi_max_request_body_size', type='integer', default='114688',\n description=\"the maximum body size per each osapi request(bytes)\")\n\n nova_2013_1_4.param('cert_topic', type='string', default='cert',\n description=\"the topic cert nodes listen on\")\n\n nova_2013_1_4.param('vpn_image_id', type='string', default='0',\n description=\"image id used when starting up a cloudpipe vpn server\")\n\n nova_2013_1_4.param('vpn_instance_type', type='string',\n default='m1.tiny', description=\"Instance type for vpn instances\")\n\n nova_2013_1_4.param(\n 'boot_script_template', type='string',\n default='$pybasedir/nova/cloudpipe/bootscript.template',\n description=\"Template for cloudpipe instance boot script\")\n\n nova_2013_1_4.param('dmz_net', type='string', default='10.0.0.0',\n description=\"Network to push into openvpn config\")\n\n nova_2013_1_4.param('dmz_mask', type='string', default='255.255.255.0',\n description=\"Netmask to push into openvpn config\")\n\n nova_2013_1_4.param('vpn_key_suffix', type='string', default='-vpn',\n description=\"Suffix to add to project name for vpn key and \"\n \"secgroups\")\n\n nova_2013_1_4.param('memcached_servers', type='list', default='',\n description=\"Memcached servers or None for in process cache.\")\n\n nova_2013_1_4.param(\n 'compute_api_class', type='string', default='nova.compute.api.API',\n description=\"The full class name of the compute API class to use\")\n\n nova_2013_1_4.param(\n 'allow_resize_to_same_host', type='boolean', default='false',\n description=\"Allow destination machine to match source for resize. \"\n \"Useful when testing in single-host environments.\")\n\n nova_2013_1_4.param(\n 'default_schedule_zone', type='string', default='',\n description=\"availability zone to use when user doesn't specify \"\n \"one\")\n\n nova_2013_1_4.param(\n 'non_inheritable_image_properties', type='list',\n default='cache_in_nova,bittorrent',\n description=\"These are image properties which a snapshot should not \"\n \"inherit from an instance\")\n\n nova_2013_1_4.param('null_kernel', type='string', default='nokernel',\n description=\"kernel image that indicates not to use a kernel, but \"\n \"to use a raw disk image instead\")\n\n nova_2013_1_4.param(\n 'multi_instance_display_name_template', type='string',\n default='%(name)s-%(uuid)s',\n description=\"When creating multiple instances with a single request \"\n \"using the os-multiple-create API extension, this template \"\n \"will be used to build the display name for each instance. \"\n \"The benefit is that the instances end up with different\"\n \" hostnames. To restore legacy behavior of every instance \"\n \"having the same name, set this option to '%(name)s'. Valid \"\n \"keys for the template are: name, uuid, count.\")\n\n nova_2013_1_4.param(\n 'default_instance_type', type='string', default='m1.small',\n description=\"default instance type to use, testing only\")\n\n nova_2013_1_4.param('console_host', type='string', default='nova',\n description=\"Console proxy host to use to connect to instances \"\n \"on this host.\")\n\n nova_2013_1_4.param(\n 'default_access_ip_network_name', type='string', default='',\n description=\"Name of network to use to set access ips for \"\n \"instances\")\n\n nova_2013_1_4.param(\n 'defer_iptables_apply', type='boolean', default='false',\n description=\"Whether to batch up the application of IPTables rules \"\n \"during a host restart and apply all at the end of the \"\n \"init phase\")\n\n nova_2013_1_4.param(\n 'instances_path', type='string', default='$state_path/instances',\n description=\"where instances are stored on disk\")\n\n nova_2013_1_4.param(\n 'instance_usage_audit', type='boolean', default='false',\n description=\"Generate periodic compute.instance.exists \"\n \"notifications\")\n\n nova_2013_1_4.param(\n 'live_migration_retry_count', type='integer', default='30',\n description=\"Number of 1 second retries needed in live_migration\")\n\n nova_2013_1_4.param(\n 'resume_guests_state_on_host_boot', type='boolean', default='false',\n description=\"Whether to start guests that were running before the \"\n \"host rebooted\")\n\n nova_2013_1_4.param('bandwidth_poll_interval', type='integer',\n default='600', description=\"interval to pull bandwidth usage info\")\n\n nova_2013_1_4.param(\n 'heal_instance_info_cache_interval', type='integer', default='60',\n description=\"Number of seconds between instance info_cache self \"\n \"healing updates\")\n\n nova_2013_1_4.param('host_state_interval', type='integer', default='120',\n description=\"Interval in seconds for querying the host status\")\n\n nova_2013_1_4.param(\n 'image_cache_manager_interval', type='integer', default='2400',\n description=\"Number of seconds to wait between runs of the image \"\n \"cache manager\")\n\n nova_2013_1_4.param(\n 'reclaim_instance_interval', type='integer', default='0',\n description=\"Interval in seconds for reclaiming deleted instances\")\n\n nova_2013_1_4.param(\n 'volume_usage_poll_interval', type='integer', default='0',\n description=\"Interval in seconds for gathering volume usages\")\n\n nova_2013_1_4.param(\n 'running_deleted_instance_action', type='string', default='log',\n description=\"Action to take if a running deleted instance is\"\n \" detected.Valid options are 'noop', 'log' and 'reap'. \"\n \"Set to 'noop' to disable.\")\n\n nova_2013_1_4.param(\n 'running_deleted_instance_poll_interval', type='integer', default='1800',\n description=\"Number of seconds to wait between runs of the cleanup task.\")\n\n nova_2013_1_4.param(\n 'running_deleted_instance_timeout', type='integer', default='0',\n description=\"Number of seconds after being deleted when a running \"\n \"instance should be considered eligible for cleanup.\")\n\n nova_2013_1_4.param('reboot_timeout', type='integer', default='0',\n description=\"Automatically hard reboot an instance if it has been \"\n \"stuck in a rebooting state longer than N seconds. Set \"\n \"to 0 to disable.\")\n\n nova_2013_1_4.param('instance_build_timeout', type='integer', default='0',\n description=\"Amount of time in seconds an instance can be in BUILD \"\n \"before going into ERROR status.Set to 0 to disable.\")\n\n nova_2013_1_4.param('rescue_timeout', type='integer', default='0',\n description=\"Automatically unrescue an instance after N seconds. \"\n \"Set to 0 to disable.\")\n\n nova_2013_1_4.param('resize_confirm_window', type='integer', default='0',\n description=\"Automatically confirm resizes after N seconds. Set to \"\n \"0 to disable.\")\n\n nova_2013_1_4.param('reserved_host_disk_mb', type='integer', default='0',\n description=\"Amount of disk in MB to reserve for the host\")\n\n nova_2013_1_4.param(\n 'reserved_host_memory_mb', type='integer', default='512',\n description=\"Amount of memory in MB to reserve for the host\")\n\n nova_2013_1_4.param(\n 'compute_stats_class', type='string', default='nova.compute.stats.Stats',\n description=\"Class that will manage stats for the local compute host\")\n\n nova_2013_1_4.param('compute_topic', type='string', default='compute',\n description=\"the topic compute nodes listen on\")\n\n nova_2013_1_4.param(\n 'console_driver', type='string',\n default='nova.console.xvp.XVPConsoleProxy',\n description=\"Driver to use for the console proxy\")\n\n nova_2013_1_4.param('stub_compute', type='boolean', default='false',\n description=\"Stub calls to compute worker for tests\")\n\n nova_2013_1_4.param(\n 'console_public_hostname', type='string', default='nova',\n description=\"Publicly visible name for this console host\")\n\n nova_2013_1_4.param('console_topic', type='string', default='console',\n description=\"the topic console proxy nodes listen on\")\n\n nova_2013_1_4.param('console_vmrc_port', type='integer',\n default='443', description=\"port for VMware VMRC connections\")\n\n nova_2013_1_4.param(\n 'console_vmrc_error_retries', type='integer', default='10',\n description=\"number of retries for retrieving VMRC information\")\n\n nova_2013_1_4.param('console_xvp_conf_template', type='string',\n default='$pybasedir/nova/console/xvp.conf.template',\n description=\"XVP conf template\")\n\n nova_2013_1_4.param('console_xvp_conf', type='string',\n default='/etc/xvp.conf', description=\"generated XVP conf file\")\n\n nova_2013_1_4.param('console_xvp_pid', type='string',\n default='/var/run/xvp.pid',\n description=\"XVP master process pid file\")\n\n nova_2013_1_4.param('console_xvp_log', type='string',\n default='/var/log/xvp.log', description=\"XVP log file\")\n\n nova_2013_1_4.param(\n 'console_xvp_multiplex_port', type='integer', default='5900',\n description=\"port for XVP to multiplex VNC connections on\")\n\n nova_2013_1_4.param(\n 'consoleauth_topic', type='string', default='consoleauth',\n description=\"the topic console auth proxy nodes listen on\")\n\n nova_2013_1_4.param('console_token_ttl', type='integer', default='600',\n description=\"How many seconds before deleting tokens\")\n\n nova_2013_1_4.param('consoleauth_manager', type='string',\n default='nova.consoleauth.manager.ConsoleAuthManager',\n description=\"Manager for console auth\")\n\n nova_2013_1_4.param('enable_new_services', type='boolean', default='true',\n description=\"Services to be added to the available pool on create\")\n\n nova_2013_1_4.param(\n 'instance_name_template', type='string', default='instance-%08x',\n description=\"Template string to be used to generate instance names\")\n\n nova_2013_1_4.param(\n 'snapshot_name_template', type='string', default='snapshot-%s',\n description=\"Template string to be used to generate snapshot names\")\n\n nova_2013_1_4.param('db_driver', type='string', default='nova.db',\n description=\"driver to use for database access\")\n\n nova_2013_1_4.param(\n 'osapi_compute_unique_server_name_scope', type='string', default='',\n description=\"When set, compute API will consider duplicate \"\n \"hostnames invalid within the specified scope, \"\n \"regardless of case. Should be empty, 'project' or \"\n \"'global'.\")\n\n nova_2013_1_4.param('glance_host', type='string', default='$my_ip',\n description=\"default glance hostname or ip\")\n\n nova_2013_1_4.param('glance_port', type='integer',\n default='9292', description=\"default glance port\")\n\n nova_2013_1_4.param('glance_protocol', type='string', default='http',\n description=\"Default protocol to use when connecting to glance. \"\n \"Set to https for SSL.\")\n\n nova_2013_1_4.param(\n 'glance_api_servers', type='list', default='$glance_host:$glance_port',\n description=\"A list of the glance api servers available to nova. Prefix \"\n \"with https:// for ssl-based glance api servers.\")\n\n nova_2013_1_4.param('glance_api_insecure', type='boolean',\n default='false', description=\"Allow to perform insecure SSL\")\n\n nova_2013_1_4.param('glance_num_retries', type='integer', default='0',\n description=\"Number retries when downloading an image from glance\")\n\n nova_2013_1_4.param('allowed_direct_url_schemes', type='list', default='',\n description=\"A list of url scheme that can be downloaded directly \"\n \"via the direct_url. Currently supported schemes: \"\n \"[file].\")\n\n nova_2013_1_4.param('image_decryption_dir', type='string', default='/tmp',\n description=\"parent dir for tempdir used for image decryption\")\n\n nova_2013_1_4.param('s3_host', type='string', default='$my_ip',\n description=\"hostname or ip for openstack to use when accessing \"\n \"the s3 api\")\n\n nova_2013_1_4.param('s3_port', type='integer', default='3333',\n description=\"port used when accessing the s3 api\")\n\n nova_2013_1_4.param('s3_access_key', type='string', default='notchecked',\n description=\"access key to use for s3 server for images\")\n\n nova_2013_1_4.param('s3_secret_key', type='string', default='notchecked',\n description=\"secret key to use for s3 server for images\")\n\n nova_2013_1_4.param('s3_use_ssl', type='boolean', default='false',\n description=\"whether to use ssl when talking to s3\")\n\n nova_2013_1_4.param('s3_affix_tenant', type='boolean', default='false',\n description=\"whether to affix the tenant id to the access key when \"\n \"downloading from s3\")\n\n nova_2013_1_4.param('ipv6_backend', type='string', default='rfc2462',\n description=\"Backend to use for IPv6 generation\")\n\n nova_2013_1_4.param(\n 'network_api_class', type='string', default='nova.network.api.API',\n description=\"The full class name of the network API class to use\")\n\n nova_2013_1_4.param(\n 'network_driver', type='string', default='nova.network.linux_net',\n description=\"Driver to use for network creation\")\n\n nova_2013_1_4.param('default_floating_pool', type='string',\n default='nova', description=\"Default pool for floating ips\")\n\n nova_2013_1_4.param('auto_assign_floating_ip', type='boolean',\n default='false', description=\"Autoassigning floating ip to VM\")\n\n nova_2013_1_4.param(\n 'floating_ip_dns_manager', type='string',\n default='nova.network.noop_dns_driver.NoopDNSDriver',\n description=\"full class name for the DNS Manager for floating IPs\")\n\n nova_2013_1_4.param(\n 'instance_dns_manager', type='string',\n default='nova.network.noop_dns_driver.NoopDNSDriver',\n description=\"full class name for the DNS Manager for instance IPs\")\n\n nova_2013_1_4.param('instance_dns_domain', type='string', default='',\n description=\"full class name for the DNS Zone for instance IPs\")\n\n nova_2013_1_4.param(\n 'ldap_dns_url', type='string', default='ldap://ldap.example.com:389',\n description=\"URL for ldap server which will store dns entries\")\n\n nova_2013_1_4.param('ldap_dns_user', type='string',\n default='uidadmin,oupeople,dcexample,dcorg',\n description=\"user for ldap DNS\")\n\n nova_2013_1_4.param('ldap_dns_password', type='string',\n default='password', description=\"password for ldap DNS\")\n\n nova_2013_1_4.param(\n 'ldap_dns_soa_hostmaster', type='string', default='hostmaster@example.org',\n description=\"Hostmaster for ldap dns driver Statement of Authority\")\n\n nova_2013_1_4.param(\n 'ldap_dns_servers', type='multi', default='dns.example.org',\n description=\"DNS Servers for ldap dns driver\")\n\n nova_2013_1_4.param(\n 'ldap_dns_base_dn', type='string', default='ouhosts,dcexample,dcorg',\n description=\"Base DN for DNS entries in ldap\")\n\n nova_2013_1_4.param('ldap_dns_soa_refresh', type='string',\n default='1800', description=\"Refresh interval\")\n\n nova_2013_1_4.param('ldap_dns_soa_retry', type='string',\n default='3600', description=\"Retry interval\")\n\n nova_2013_1_4.param('ldap_dns_soa_expiry', type='string',\n default='86400', description=\"Expiry interval\")\n\n nova_2013_1_4.param('ldap_dns_soa_minimum', type='string',\n default='7200', description=\"Minimum interval\")\n\n nova_2013_1_4.param(\n 'dhcpbridge_flagfile', type='multi',\n default='/etc/nova/nova-dhcpbridge.conf',\n description=\"location of flagfiles for dhcpbridge\")\n\n nova_2013_1_4.param(\n 'networks_path', type='string', default='$state_path/networks',\n description=\"Location to keep network config files\")\n\n nova_2013_1_4.param('public_interface', type='string', default='eth0',\n description=\"Interface for public IP addresses\")\n\n nova_2013_1_4.param('network_device_mtu', type='string',\n default='', description=\"MTU setting for vlan\")\n\n nova_2013_1_4.param(\n 'dhcpbridge', type='string', default='$bindir/nova-dhcpbridge',\n description=\"location of nova-dhcpbridge\")\n\n nova_2013_1_4.param('routing_source_ip', type='string',\n default='$my_ip', description=\"Public IP of network host\")\n\n nova_2013_1_4.param('dhcp_lease_time', type='integer', default='120',\n description=\"Lifetime of a DHCP lease in seconds\")\n\n nova_2013_1_4.param('dns_server', type='multi', default='',\n description=\"if set, uses specific dns server for dnsmasq. Canbe \"\n \"specified multiple times.\")\n\n nova_2013_1_4.param(\n 'use_network_dns_servers', type='boolean', default='false',\n description=\"if set, uses the dns1 and dns2 from the network ref.as\"\n \" dns servers.\")\n\n nova_2013_1_4.param('dmz_cidr', type='list', default='',\n description=\"A list of dmz range that should be accepted\")\n\n nova_2013_1_4.param('force_snat_range', type='multi', default='',\n description=\"Traffic to this range will always be snatted to the \"\n \"fallback ip, even if it would normally be bridged out \"\n \"of the node. Can be specified multiple times.\")\n\n nova_2013_1_4.param('dnsmasq_config_file', type='string', default='',\n description=\"Override the default dnsmasq settings with this file\")\n\n nova_2013_1_4.param('linuxnet_interface_driver', type='string',\n default='nova.network.linux_net.LinuxBridgeInterfaceDriver',\n description=\"Driver used to create ethernet devices.\")\n\n nova_2013_1_4.param(\n 'linuxnet_ovs_integration_bridge', type='string', default='br-int',\n description=\"Name of Open vSwitch bridge used with linuxnet\")\n\n nova_2013_1_4.param('send_arp_for_ha', type='boolean', default='false',\n description=\"send gratuitous ARPs for HA setup\")\n\n nova_2013_1_4.param('send_arp_for_ha_count', type='integer', default='3',\n description=\"send this many gratuitous ARPs for HA setup\")\n\n nova_2013_1_4.param(\n 'use_single_default_gateway', type='boolean', default='false',\n description=\"Use single default gateway. Only first nic of vm will \"\n \"get default gateway from dhcp server\")\n\n nova_2013_1_4.param(\n 'forward_bridge_interface', type='multi', default='all',\n description=\"An interface that bridges can forward to. If this is \"\n \"set to all then all traffic will be forwarded. Can be \"\n \"specified multiple times.\")\n\n nova_2013_1_4.param('metadata_host', type='string', default='$my_ip',\n description=\"the ip for the metadata api server\")\n\n nova_2013_1_4.param('metadata_port', type='integer', default='8775',\n description=\"the port for the metadata api port\")\n\n nova_2013_1_4.param('iptables_top_regex', type='string', default='',\n description=\"Regular expression to match iptables rule that \"\n \"shouldalways be on the top.\")\n\n nova_2013_1_4.param('iptables_bottom_regex', type='string', default='',\n description=\"Regular expression to match iptables rule that \"\n \"shouldalways be on the bottom.\")\n\n nova_2013_1_4.param('flat_network_bridge', type='string', default='',\n description=\"Bridge for simple network instances\")\n\n nova_2013_1_4.param('flat_network_dns', type='string',\n default='8.8.4.4', description=\"Dns for simple network\")\n\n nova_2013_1_4.param('flat_injected', type='boolean', default='false',\n description=\"Whether to attempt to inject network setup into guest\")\n\n nova_2013_1_4.param('flat_interface', type='string', default='',\n description=\"FlatDhcp will bridge into this interface if set\")\n\n nova_2013_1_4.param('vlan_start', type='integer', default='100',\n description=\"First VLAN for private networks\")\n\n nova_2013_1_4.param('vlan_interface', type='string', default='',\n description=\"vlans will bridge into this interface if set\")\n\n nova_2013_1_4.param('num_networks', type='integer', default='1',\n description=\"Number of networks to support\")\n\n nova_2013_1_4.param('vpn_ip', type='string', default='$my_ip',\n description=\"Public IP for the cloudpipe VPN servers\")\n\n nova_2013_1_4.param('vpn_start', type='integer', default='1000',\n description=\"First Vpn port for private networks\")\n\n nova_2013_1_4.param('network_size', type='integer', default='256',\n description=\"Number of addresses in each private subnet\")\n\n nova_2013_1_4.param('fixed_range', type='string',\n default='10.0.0.0/8', description=\"Fixed IP address block\")\n\n nova_2013_1_4.param('fixed_range_v6', type='string',\n default='fd00::/48', description=\"Fixed IPv6 address block\")\n\n nova_2013_1_4.param('gateway', type='string',\n default='', description=\"Default IPv4 gateway\")\n\n nova_2013_1_4.param('gateway_v6', type='string',\n default='', description=\"Default IPv6 gateway\")\n\n nova_2013_1_4.param('cnt_vpn_clients', type='integer', default='0',\n description=\"Number of addresses reserved for vpn clients\")\n\n nova_2013_1_4.param(\n 'fixed_ip_disassociate_timeout', type='integer', default='600',\n description=\"Seconds after which a deallocated ip is disassociated\")\n\n nova_2013_1_4.param('create_unique_mac_address_attempts', type='integer',\n default='5', description=\"Number of attempts to create unique mac\"\n \" address\")\n\n nova_2013_1_4.param('fake_network', type='boolean', default='false',\n description=\"If passed, use fake network devices and addresses\")\n\n nova_2013_1_4.param('fake_call', type='boolean', default='false',\n description=\"If True, skip using the queue and make local calls\")\n\n nova_2013_1_4.param('teardown_unused_network_gateway', type='boolean',\n default='false', description=\"If True, unused gateway devices\")\n\n nova_2013_1_4.param('force_dhcp_release', type='boolean', default='false',\n description=\"If True, send a dhcp release on instance termination\")\n\n nova_2013_1_4.param('share_dhcp_address', type='boolean', default='false',\n description=\"If True in multi_host mode, all compute hosts share \"\n \"the same dhcp address.\")\n\n nova_2013_1_4.param('update_dns_entries', type='boolean', default='false',\n description=\"If True, when a DNS entry must be updated, it sends a \"\n \"fanout cast to all network hosts to update their DNS \"\n \"entries in multi host mode\")\n\n nova_2013_1_4.param(\n 'dns_update_periodic_interval', type='integer', default='-1',\n description=\"Number of seconds to wait between runs of updates to \"\n \"DNS entries.\")\n\n nova_2013_1_4.param('dhcp_domain', type='string', default='novalocal',\n description=\"domain to use for building the hostnames\")\n\n nova_2013_1_4.param(\n 'l3_lib', type='string', default='nova.network.l3.LinuxNetL3',\n description=\"Indicates underlying L3 management library\")\n\n nova_2013_1_4.param(\n 'quantum_url', type='string', default='http://127.0.0.1:9696',\n description=\"URL for connecting to quantum\")\n\n nova_2013_1_4.param('quantum_url_timeout', type='integer', default='30',\n description=\"timeout value for connecting to quantum in seconds\")\n\n nova_2013_1_4.param(\n 'quantum_admin_username', type='string', default='',\n description=\"username for connecting to quantum in admin context\")\n\n nova_2013_1_4.param(\n 'quantum_admin_password', type='string', default='',\n description=\"password for connecting to quantum in admin context\")\n\n nova_2013_1_4.param(\n 'quantum_admin_tenant_name', type='string', default='',\n description=\"tenant name for connecting to quantum in admin \"\n \"context\")\n\n nova_2013_1_4.param('quantum_region_name', type='string', default='',\n description=\"region name for connecting to quantum in admin \"\n \"context\")\n\n nova_2013_1_4.param(\n 'quantum_admin_auth_url', type='string',\n default='http://localhost:5000/v2.0',\n description=\"auth url for connecting to quantum in admin context\")\n\n nova_2013_1_4.param(\n 'quantum_api_insecure', type='boolean', default='false',\n description=\"if set, ignore any SSL validation issues\")\n\n nova_2013_1_4.param(\n 'quantum_auth_strategy', type='string', default='keystone',\n description=\"auth strategy for connecting to quantum in admin \"\n \"context\")\n\n nova_2013_1_4.param('quantum_ovs_bridge', type='string', default='br-int',\n description=\"Name of Integration Bridge used by Open vSwitch\")\n\n nova_2013_1_4.param(\n 'quantum_extension_sync_interval', type='integer', default='600',\n description=\"Number of seconds before querying quantum for \"\n \"extensions\")\n\n nova_2013_1_4.param('network_topic', type='string', default='network',\n description=\"the topic network nodes listen on\")\n\n nova_2013_1_4.param('multi_host', type='boolean', default='false',\n description=\"Default value for multi_host in networks. Also, if \"\n \"set, some rpc network calls will be sent directly to \"\n \"host.\")\n\n nova_2013_1_4.param('security_group_api', type='string', default='nova',\n description=\"The full class name of the security API class\")\n\n nova_2013_1_4.param(\n 'security_group_handler', type='string',\n default='nova.network.sg.NullSecurityGroupHandler',\n description=\"The full class name of the security group handler class\")\n\n nova_2013_1_4.param(\n 'queues',\n type='multi',\n default='',\n description=\"Queues to delete\")\n\n nova_2013_1_4.param('delete_exchange', type='boolean',\n default='false', description=\"delete nova exchange too.\")\n\n nova_2013_1_4.param('record', type='boolean', default='false',\n description=\"Record sessions to FILE.[session_number]\")\n\n nova_2013_1_4.param('daemon', type='boolean',\n default='false', description=\"Become a daemon\")\n\n nova_2013_1_4.param('ssl_only', type='boolean', default='false',\n description=\"Disallow non-encrypted connections\")\n\n nova_2013_1_4.param('source_is_ipv6', type='boolean',\n default='false', description=\"Source is ipv6\")\n\n nova_2013_1_4.param('cert', type='string', default='self.pem',\n description=\"SSL certificate file\")\n\n nova_2013_1_4.param(\n 'key',\n type='string',\n default='',\n description=\"SSL key file\")\n\n nova_2013_1_4.param('web', type='string', default='/usr/share/novnc',\n description=\"Run webserver on same port. Serve files from DIR.\")\n\n nova_2013_1_4.param('novncproxy_host', type='string', default='0.0.0.0',\n description=\"Host on which to listen for incoming requests\")\n\n nova_2013_1_4.param('novncproxy_port', type='integer', default='6080',\n description=\"Port on which to listen for incoming requests\")\n\n nova_2013_1_4.param('buckets_path', type='string',\n default='$state_path/buckets', description=\"path to s3 buckets\")\n\n nova_2013_1_4.param('s3_listen', type='string', default='0.0.0.0',\n description=\"IP address for S3 API to listen\")\n\n nova_2013_1_4.param('s3_listen_port', type='integer',\n default='3333', description=\"port for s3 api to listen\")\n\n nova_2013_1_4.param('db_backend', type='string', default='sqlalchemy',\n description=\"The backend to use for db\")\n\n nova_2013_1_4.param('dbapi_use_tpool', type='boolean', default='false',\n description=\"Enable the experimental use of thread pooling for all \"\n \"DB API calls\")\n\n nova_2013_1_4.param(\n 'sql_connection', type='string',\n default='sqlite:////nova/openstack/common/db/$sqlite_db',\n description=\"The SQLAlchemy connection string used to connect to the \"\n \"database\")\n\n nova_2013_1_4.param('sqlite_db', type='string', default='nova.sqlite',\n description=\"the filename to use with sqlite\")\n\n nova_2013_1_4.param('sql_idle_timeout', type='integer', default='3600',\n description=\"timeout before idle sql connections are reaped\")\n\n nova_2013_1_4.param('sqlite_synchronous', type='boolean', default='true',\n description=\"If passed, use synchronous mode for sqlite\")\n\n nova_2013_1_4.param('sql_min_pool_size', type='integer', default='1',\n description=\"Minimum number of SQL connections to keep open in a \"\n \"pool\")\n\n nova_2013_1_4.param('sql_max_pool_size', type='integer', default='5',\n description=\"Maximum number of SQL connections to keep open in a \"\n \"pool\")\n\n nova_2013_1_4.param('sql_max_retries', type='integer', default='10',\n description=\"maximum db connection retries during startup.\")\n\n nova_2013_1_4.param('sql_retry_interval', type='integer', default='10',\n description=\"interval between retries of opening a sql connection\")\n\n nova_2013_1_4.param('sql_max_overflow', type='integer', default='',\n description=\"If set, use this value for max_overflow with \"\n \"sqlalchemy\")\n\n nova_2013_1_4.param('sql_connection_debug', type='integer', default='0',\n description=\"Verbosity of SQL debugging information. 0=None, \"\n \"100=Everything\")\n\n nova_2013_1_4.param(\n 'sql_connection_trace', type='boolean', default='false',\n description=\"Add python stack traces to SQL as comment strings\")\n\n nova_2013_1_4.param('backdoor_port', type='integer', default='',\n description=\"port for eventlet backdoor to listen\")\n\n nova_2013_1_4.param('disable_process_locking', type='boolean',\n default='false', description=\"Whether to disable inter-process \"\n \"locks\")\n\n nova_2013_1_4.param('lock_path', type='string', default='',\n description=\"Directory to use for lock files. Default to a temp \"\n \"directory\")\n\n nova_2013_1_4.param('debug', type='boolean', default='false',\n description=\"Print debugging output\")\n\n nova_2013_1_4.param('verbose', type='boolean', default='false',\n description=\"Print more verbose output\")\n\n nova_2013_1_4.param('use_stderr', type='boolean', default='true',\n description=\"Log output to standard error\")\n\n nova_2013_1_4.param('logfile_mode', type='string', default='0644',\n description=\"Default file mode used when creating log files\")\n\n nova_2013_1_4.param('logging_context_format_string', type='string',\n default='%(asctime)s.%(msecs)03d %(levelname)s %(name)s '\n '[%(request_id)s %(user)s %(tenant)s] '\n '%(instance)s%(message)s',\n description=\"format string to use for log messages with context\")\n\n nova_2013_1_4.param('logging_default_format_string', type='string',\n default='%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s'\n ' [-] %(instance)s%(message)s',\n description=\"format string to use for log messages without context\")\n\n nova_2013_1_4.param(\n 'logging_debug_format_suffix', type='string',\n default='%(funcName)s %(pathname)s:%(lineno)d',\n description=\"data to append to log format when level is DEBUG\")\n\n nova_2013_1_4.param(\n 'logging_exception_prefix', type='string',\n default='%(asctime)s.%(msecs)03d %(process)d TRACE %(name)s %(instance)s',\n description=\"prefix each line of exception output with this format\")\n\n nova_2013_1_4.param('default_log_levels', type='list',\n default='amqplibWARN,sqlalchemyWARN,botoWARN,sudsINFO'\n ',keystoneINFO,eventlet.wsgi.serverWARN',\n description=\"list of logger=LEVEL pairs\")\n\n nova_2013_1_4.param('publish_errors', type='boolean',\n default='false', description=\"publish error events\")\n\n nova_2013_1_4.param('fatal_deprecations', type='boolean',\n default='false', description=\"make deprecations fatal\")\n\n nova_2013_1_4.param('instance_format', type='string',\n default='\"[instance: %(uuid)s] \"',\n description=\"If an instance is passed with the log message, format \"\n \"it like this\")\n\n nova_2013_1_4.param('instance_uuid_format', type='string',\n default='\"[instance: %(uuid)s] \"',\n description=\"If an instance UUID is passed with the log message, \"\n \"format it like this\")\n\n nova_2013_1_4.param('log_config', type='string', default='',\n description=\"If this option is specified, the logging configuration\"\n \" file specified is used and overrides any other \"\n \"logging options specified. Please see the Python \"\n \"logging module documentation for details on logging \"\n \"configuration files.\")\n\n nova_2013_1_4.param('log_format', type='string',\n default='%(asctime)s %(levelname)8s [%(name)s] %(message)s',\n description=\"A logging.Formatter log message format string which \"\n \"may use any of the available logging.LogRecord \"\n \"attributes. Default: %(default)s\")\n\n nova_2013_1_4.param(\n 'log_date_format', type='string', default='%Y-%m-%d %H:%M:%S',\n description=\"Format string for %%(asctime)s in log records. \"\n \"Default: %(default)s\")\n\n nova_2013_1_4.param('log_file', type='string', default='',\n description=\"(Optional) Name of log file to output to. If not set,\"\n \" logging will go to stdout.\")\n\n nova_2013_1_4.param('log_dir', type='string', default='',\n description=\"(Optional) The directory to keep log files in\")\n\n nova_2013_1_4.param('use_syslog', type='boolean',\n default='false', description=\"Use syslog for logging.\")\n\n nova_2013_1_4.param(\n 'syslog_log_facility', type='string', default='LOG_USER',\n description=\"syslog facility to receive log lines\")\n\n nova_2013_1_4.param('notification_driver', type='multi', default='',\n description=\"Driver or drivers to handle sending notifications\")\n\n nova_2013_1_4.param(\n 'default_notification_level', type='string', default='INFO',\n description=\"Default notification level for outgoing notifications\")\n\n nova_2013_1_4.param('default_publisher_id', type='string', default='$host',\n description=\"Default publisher_id for outgoing notifications\")\n\n nova_2013_1_4.param(\n 'notification_topics', type='list', default='notifications',\n description=\"AMQP topic used for openstack notifications\")\n\n nova_2013_1_4.param(\n 'rpc_backend', type='string',\n default='nova.openstack.common.rpc.impl_kombu',\n description=\"The messaging module to use, defaults to kombu.\")\n\n nova_2013_1_4.param('rpc_thread_pool_size', type='integer',\n default='64', description=\"Size of RPC thread pool\")\n\n nova_2013_1_4.param('rpc_conn_pool_size', type='integer',\n default='30', description=\"Size of RPC connection pool\")\n\n nova_2013_1_4.param('rpc_response_timeout', type='integer', default='60',\n description=\"Seconds to wait for a response from call or \"\n \"multicall\")\n\n nova_2013_1_4.param('rpc_cast_timeout', type='integer', default='30',\n description=\"Seconds to wait before a cast expires\")\n\n nova_2013_1_4.param(\n 'allowed_rpc_exception_modules', type='list',\n default='nova.openstack.common.exception,nova.exception,cinder.exception,'\n 'exceptions',\n description=\"Modules of exceptions that are permitted to be recreatedupon\"\n \" receiving exception data from an rpc call.\")\n\n nova_2013_1_4.param('fake_rabbit', type='boolean', default='false',\n description=\"If passed, use a fake RabbitMQ provider\")\n\n nova_2013_1_4.param('control_exchange', type='string', default='openstack',\n description=\"AMQP exchange to connect to if using RabbitMQ or Qpid\")\n\n nova_2013_1_4.param(\n 'amqp_rpc_single_reply_queue', type='boolean', default='false',\n description=\"Enable a fast single reply queue if using AMQP based\"\n \" RPC like RabbitMQ or Qpid.\")\n\n nova_2013_1_4.param('kombu_ssl_version', type='string',\n default='', description=\"SSL version to use\")\n\n nova_2013_1_4.param('kombu_ssl_keyfile', type='string',\n default='', description=\"SSL key file\")\n\n nova_2013_1_4.param('kombu_ssl_certfile', type='string',\n default='', description=\"SSL cert file\")\n\n nova_2013_1_4.param('kombu_ssl_ca_certs', type='string', default='',\n description=\"SSL certification authority file\")\n\n nova_2013_1_4.param('rabbit_host', type='string', default='localhost',\n description=\"The RabbitMQ broker address where a single node is\"\n \" used\")\n\n nova_2013_1_4.param('rabbit_port', type='integer', default='5672',\n description=\"The RabbitMQ broker port where a single node is used\")\n\n nova_2013_1_4.param(\n 'rabbit_hosts', type='list', default='$rabbit_host:$rabbit_port',\n description=\"RabbitMQ HA cluster host:port pairs\")\n\n nova_2013_1_4.param('rabbit_use_ssl', type='boolean',\n default='false', description=\"connect over SSL for RabbitMQ\")\n\n nova_2013_1_4.param('rabbit_userid', type='string',\n default='guest', description=\"the RabbitMQ userid\")\n\n nova_2013_1_4.param('rabbit_password', type='string',\n default='guest', description=\"the RabbitMQ password\")\n\n nova_2013_1_4.param('rabbit_virtual_host', type='string',\n default='/', description=\"the RabbitMQ virtual host\")\n\n nova_2013_1_4.param('rabbit_retry_interval', type='integer', default='1',\n description=\"how frequently to retry connecting with RabbitMQ\")\n\n nova_2013_1_4.param('rabbit_retry_backoff', type='integer', default='2',\n description=\"how long to backoff for between retries when \"\n \"connecting to RabbitMQ\")\n\n nova_2013_1_4.param('rabbit_max_retries', type='integer', default='0',\n description=\"maximum retries with trying to connect to RabbitMQ\")\n\n nova_2013_1_4.param('rabbit_durable_queues', type='boolean',\n default='false', description=\"use durable queues in RabbitMQ\")\n\n nova_2013_1_4.param('rabbit_ha_queues', type='boolean',\n default='false', description=\"use H/A queues in RabbitMQ\")\n\n nova_2013_1_4.param('qpid_hostname', type='string',\n default='localhost', description=\"Qpid broker hostname\")\n\n nova_2013_1_4.param('qpid_port', type='string',\n default='5672', description=\"Qpid broker port\")\n\n nova_2013_1_4.param(\n 'qpid_hosts', type='list', default='$qpid_hostname:$qpid_port',\n description=\"Qpid HA cluster host:port pairs\")\n\n nova_2013_1_4.param('qpid_username', type='string', default='',\n description=\"Username for qpid connection\")\n\n nova_2013_1_4.param('qpid_password', type='string', default='',\n description=\"Password for qpid connection\")\n\n nova_2013_1_4.param('qpid_sasl_mechanisms', type='string', default='',\n description=\"Space separated list of SASL mechanisms to use for \"\n \"auth\")\n\n nova_2013_1_4.param('qpid_heartbeat', type='integer', default='60',\n description=\"Seconds between connection keepalive heartbeats\")\n\n nova_2013_1_4.param('qpid_protocol', type='string', default='tcp',\n description=\"Transport to use, either 'tcp' or 'ssl'\")\n\n nova_2013_1_4.param('qpid_tcp_nodelay', type='boolean',\n default='true', description=\"Disable Nagle algorithm\")\n\n nova_2013_1_4.param('rpc_zmq_bind_address', type='string', default='*',\n description=\"ZeroMQ bind address. Should be a wildcard\")\n\n nova_2013_1_4.param('rpc_zmq_matchmaker', type='string',\n default='nova.openstack.common.rpc.matchmaker.MatchMakerLocalhost',\n description=\"MatchMaker driver\")\n\n nova_2013_1_4.param('rpc_zmq_port', type='integer', default='9501',\n description=\"ZeroMQ receiver listening port\")\n\n nova_2013_1_4.param('rpc_zmq_contexts', type='integer', default='1',\n description=\"Number of ZeroMQ contexts, defaults to 1\")\n\n nova_2013_1_4.param(\n 'rpc_zmq_topic_backlog', type='integer', default='',\n description=\"Maximum number of ingress messages to locally buffer \"\n \"per topic. Default is unlimited.\")\n\n nova_2013_1_4.param(\n 'rpc_zmq_ipc_dir', type='string', default='/var/run/openstack',\n description=\"Directory for holding IPC sockets\")\n\n nova_2013_1_4.param('rpc_zmq_host', type='string', default='sorcha',\n description=\"Name of this node. Must be a valid hostname, FQDN, or \"\n \"IP address. Must match 'host' option, if running \"\n \"Nova.\")\n\n nova_2013_1_4.param('matchmaker_ringfile', type='string',\n default='/etc/nova/matchmaker_ring.json',\n description=\"Matchmaker ring file\")\n\n nova_2013_1_4.param(\n 'scheduler_host_manager', type='string',\n default='nova.scheduler.host_manager.HostManager',\n description=\"The scheduler host manager class to use\")\n\n nova_2013_1_4.param('scheduler_max_attempts', type='integer', default='3',\n description=\"Maximum number of attempts to schedule an instance\")\n\n nova_2013_1_4.param(\n 'scheduler_host_subset_size', type='integer', default='1',\n description=\"New instances will be scheduled on a host chosen \"\n \"randomly from a subset of the N best hosts. This \"\n \"property defines the subset size that a host is chosen\"\n \" from. A value of 1 chooses the first host returned by\"\n \" the weighing functions. This value must be at least\"\n \" 1. Any value less than 1 will be ignored, and 1 will\"\n \" be used instead\")\n\n nova_2013_1_4.param(\n 'cpu_allocation_ratio', type='floating point', default='16.0',\n description=\"Virtual CPU to Physical CPU allocation ratio\")\n\n nova_2013_1_4.param(\n 'disk_allocation_ratio', type='floating point', default='1.0',\n description=\"virtual disk to physical disk allocation ratio\")\n\n nova_2013_1_4.param('max_io_ops_per_host', type='integer', default='8',\n description=\"Ignore hosts that have too many builds/resizes/\"\n \"snaps/migrations\")\n\n nova_2013_1_4.param('isolated_images', type='list', default='',\n description=\"Images to run on isolated host\")\n\n nova_2013_1_4.param('isolated_hosts', type='list', default='',\n description=\"Host reserved for specific images\")\n\n nova_2013_1_4.param('max_instances_per_host', type='integer', default='50',\n description=\"Ignore hosts that have too many instances\")\n\n nova_2013_1_4.param(\n 'ram_allocation_ratio', type='floating point', default='1.5',\n description=\"virtual ram to physical ram allocation ratio\")\n\n nova_2013_1_4.param(\n 'scheduler_available_filters', type='multi',\n default='nova.scheduler.filters.all_filters',\n description=\"Filter classes available to the scheduler which may be \"\n \"specified more than once. An entry of 'nova.scheduler\"\n \".filters.standard_filters' maps to all filters included \"\n \"with nova.\")\n\n nova_2013_1_4.param(\n 'scheduler_default_filters', type='list',\n default='RetryFilter,AvailabilityZoneFilter,RamFilter,ComputeFilter,'\n 'ComputeCapabilitiesFilter,ImagePropertiesFilter',\n description=\"Which filter class names to use for filtering hosts when not\"\n \" specified in the request.\")\n\n nova_2013_1_4.param(\n 'scheduler_weight_classes', type='list',\n default='nova.scheduler.weights.all_weighers',\n description=\"Which weight class names to use for weighing hosts\")\n\n nova_2013_1_4.param(\n 'scheduler_driver', type='string',\n default='nova.scheduler.filter_scheduler.FilterScheduler',\n description=\"Default driver to use for the scheduler\")\n\n nova_2013_1_4.param(\n 'compute_scheduler_driver', type='string',\n default='nova.scheduler.filter_scheduler.FilterScheduler',\n description=\"Driver to use for scheduling compute calls\")\n\n nova_2013_1_4.param(\n 'default_scheduler_driver', type='string',\n default='nova.scheduler.chance.ChanceScheduler',\n description=\"Default driver to use for scheduling calls\")\n\n nova_2013_1_4.param('scheduler_topic', type='string', default='scheduler',\n description=\"the topic scheduler nodes listen on\")\n\n nova_2013_1_4.param(\n 'scheduler_json_config_location', type='string', default='',\n description=\"Absolute path to scheduler configuration JSON file.\")\n\n nova_2013_1_4.param('least_cost_functions', type='list', default='',\n description=\"Which cost functions the LeastCostScheduler should\"\n \" use\")\n\n nova_2013_1_4.param(\n 'noop_cost_fn_weight', type='floating point', default='1.0',\n description=\"How much weight to give the noop cost function\")\n\n nova_2013_1_4.param(\n 'compute_fill_first_cost_fn_weight', type='floating point',\n default='',\n description=\"How much weight to give the fill-first cost function. A \"\n \"negative value will reverse behavior: e.g. spread-first\")\n\n nova_2013_1_4.param(\n 'ram_weight_multiplier', type='floating point', default='1.0',\n description=\"Multiplier used for weighing ram. Negative numbers \"\n \"mean to stack vs spread.\")\n\n nova_2013_1_4.param('servicegroup_driver', type='string', default='db',\n description=\"The driver for servicegroup service\")\n\n nova_2013_1_4.param(\n 'config_drive_format', type='string', default='iso9660',\n description=\"Config drive format. One of iso9660\")\n\n nova_2013_1_4.param(\n 'config_drive_tempdir', type='string', default='',\n description=\"Where to put temporary files associated with config \"\n \"drive creation\")\n\n nova_2013_1_4.param('force_config_drive', type='string', default='',\n description=\"Set to force injection to take place on a config \"\n \"drive\")\n\n nova_2013_1_4.param('mkisofs_cmd', type='string', default='genisoimage',\n description=\"Name and optionally path of the tool used for ISO \"\n \"image creation\")\n\n nova_2013_1_4.param('injected_network_template', type='string',\n default='$pybasedir/nova/virt/interfaces.template',\n description=\"Template file for injected network\")\n\n nova_2013_1_4.param('virt_mkfs', type='multi',\n default='defaultmkfs.ext3 -L %(fs_label)s -F %(target)s',\n description=\"mkfs commands for ephemeral device. The format is \"\n \"=\")\n\n nova_2013_1_4.param('virt_mkfs', type='string',\n default='linuxmkfs.ext3 -L %(fs_label)s -F %(target)s',\n description=\"\")\n\n nova_2013_1_4.param('virt_mkfs', type='string',\n default='windowsmkfs.ntfs --force --fast --label %(fs_label)s '\n '%(target)s', description=\"\")\n\n nova_2013_1_4.param('timeout_nbd', type='integer', default='10',\n description=\"time to wait for a NBD device coming up\")\n\n nova_2013_1_4.param('compute_driver', type='string', default='',\n description=\"Driver to use for controlling virtualization. \"\n \"Options include: libvirt.LibvirtDriver, xenapi.\"\n \"XenAPIDriver, fake.FakeDriver, \"\n \"baremetal.BareMetalDriver, vmwareapi.VMWareESXDriver\")\n\n nova_2013_1_4.param(\n 'default_ephemeral_format', type='string', default='',\n description=\"The default format an ephemeral_volume will be \"\n \"formatted with on creation.\")\n\n nova_2013_1_4.param('preallocate_images', type='string', default='none',\n description=\"VM image preallocation mode: 'none' => no storage \"\n \"provisioning is done up front, 'space' => storage is \"\n \"fully allocated at instance start\")\n\n nova_2013_1_4.param('use_cow_images', type='boolean',\n default='true', description=\"Whether to use cow images\")\n\n nova_2013_1_4.param('firewall_driver', type='string',\n default='', description=\"Firewall driver\")\n\n nova_2013_1_4.param(\n 'allow_same_net_traffic', type='boolean', default='true',\n description=\"Whether to allow network traffic from same network\")\n\n nova_2013_1_4.param('vswitch_name', type='string', default='',\n description=\"External virtual switch Name, if not provided, the \"\n \"first external virtual switch is used\")\n\n nova_2013_1_4.param('limit_cpu_features', type='boolean', default='false',\n description=\"Required for live migration among hosts with different\"\n \" CPU features\")\n\n nova_2013_1_4.param(\n 'config_drive_inject_password', type='boolean', default='false',\n description=\"Sets the admin password in the config drive image\")\n\n nova_2013_1_4.param('qemu_img_cmd', type='string', default='qemu-img.exe',\n description=\"qemu-img is used to convert between different image \"\n \"types\")\n\n nova_2013_1_4.param('config_drive_cdrom', type='boolean', default='false',\n description=\"Attaches the Config Drive image as a cdrom drive \"\n \"instead of a disk drive\")\n\n nova_2013_1_4.param('hyperv_attaching_volume_retry_count', type='integer',\n default='10', description=\"The number of times we retry on \"\n \"attaching volume \")\n\n nova_2013_1_4.param(\n 'hyperv_wait_between_attach_retry', type='integer', default='5',\n description=\"The seconds to wait between an volume attachment \"\n \"attempt\")\n\n nova_2013_1_4.param('force_volumeutils_v1', type='boolean',\n default='false', description=\"Force volumeutils v1\")\n\n nova_2013_1_4.param('force_raw_images', type='boolean', default='true',\n description=\"Force backing images to raw format\")\n\n nova_2013_1_4.param('rescue_image_id', type='string',\n default='', description=\"Rescue ami image\")\n\n nova_2013_1_4.param('rescue_kernel_id', type='string',\n default='', description=\"Rescue aki image\")\n\n nova_2013_1_4.param('rescue_ramdisk_id', type='string',\n default='', description=\"Rescue ari image\")\n\n nova_2013_1_4.param('libvirt_type', type='string',\n default='kvm', description=\"Libvirt domain type\")\n\n nova_2013_1_4.param('libvirt_uri', type='string', default='',\n description=\"Override the default libvirt URI\")\n\n nova_2013_1_4.param(\n 'libvirt_inject_password', type='boolean', default='false',\n description=\"Inject the admin password at boot time, without an \"\n \"agent.\")\n\n nova_2013_1_4.param('libvirt_inject_key', type='boolean', default='true',\n description=\"Inject the ssh public key at boot time\")\n\n nova_2013_1_4.param(\n 'libvirt_inject_partition', type='integer', default='1',\n description=\"The partition to inject to : -2 => disable, -1 => \"\n \"inspect\")\n\n nova_2013_1_4.param('use_usb_tablet', type='boolean', default='true',\n description=\"Sync virtual and real mouse cursors in Windows VMs\")\n\n nova_2013_1_4.param('live_migration_uri', type='string',\n default='qemu+tcp://%s/system', description=\"Migration target URI\")\n\n nova_2013_1_4.param(\n 'live_migration_flag', type='string',\n default='VIR_MIGRATE_UNDEFINE_SOURCE, VIR_MIGRATE_PEER2PEER',\n description=\"Migration flags to be set for live migration\")\n\n nova_2013_1_4.param(\n 'block_migration_flag', type='string',\n default='VIR_MIGRATE_UNDEFINE_SOURCE, VIR_MIGRATE_PEER2PEER, '\n 'VIR_MIGRATE_NON_SHARED_INC',\n description=\"Migration flags to be set for block migration\")\n\n nova_2013_1_4.param(\n 'live_migration_bandwidth', type='integer', default='0',\n description=\"Maximum bandwidth to be used during migration, in \"\n \"Mbps\")\n\n nova_2013_1_4.param('snapshot_image_format', type='string',\n default='', description=\"Snapshot image format\")\n\n nova_2013_1_4.param(\n 'libvirt_vif_driver', type='string',\n default='nova.virt.libvirt.vif.LibvirtGenericVIFDriver',\n description=\"The libvirt VIF driver to configure the VIFs.\")\n\n nova_2013_1_4.param(\n 'libvirt_volume_drivers', type='list',\n default='iscsinova.virt.libvirt.volume.LibvirtISCSIVolumeDriver,'\n 'localnova.virt.libvirt.volume.LibvirtVolumeDriver,fakenova.'\n 'virt.libvirt.volume.LibvirtFakeVolumeDriver,rbdnova.virt.libvirt.'\n 'volume.LibvirtNetVolumeDriver,sheepdognova.virt.libvirt.volume.'\n 'LibvirtNetVolumeDriver,nfsnova.virt.libvirt.volume.'\n 'LibvirtNFSVolumeDriver,aoenova.virt.libvirt.volume.'\n 'LibvirtAOEVolumeDriver,glusterfsnova.virt.libvirt.volume.'\n 'LibvirtGlusterfsVolumeDriver,fibre_channelnova.virt.libvirt.'\n 'volume.LibvirtFibreChannelVolumeDriver,scalitynova.virt.libvirt.'\n 'volume.LibvirtScalityVolumeDriver',\n description=\"Libvirt handlers for remote volumes.\")\n\n nova_2013_1_4.param('libvirt_disk_prefix', type='string', default='',\n description=\"Override the default disk prefix for the devices \"\n \"attached to a server, which is dependent on \"\n \"libvirt_type.\")\n\n nova_2013_1_4.param(\n 'libvirt_wait_soft_reboot_seconds', type='integer', default='120',\n description=\"Number of seconds to wait for instance to shut down \"\n \"after soft reboot request is made. We fall back to \"\n \"hard reboot if instance does not shutdown within this \"\n \"window.\")\n\n nova_2013_1_4.param('libvirt_nonblocking', type='boolean', default='true',\n description=\"Use a separated OS thread pool to realize non-blocking\"\n \" libvirt calls\")\n\n nova_2013_1_4.param('libvirt_cpu_mode', type='string', default='',\n description=\"Set to 'host-model' to clone the host CPU feature\"\n \" flags; to 'host-passthrough' to use the host CPU\"\n \" model exactly; to 'custom' to use a named CPU model;\"\n \" to 'none' to not set any CPU model. If \"\n \"libvirt_type='kvm|qemu', it will default to \"\n \"'host-model', otherwise it will default to 'none'\")\n\n nova_2013_1_4.param('libvirt_cpu_model', type='string', default='',\n description=\"Set to a named libvirt CPU model\")\n\n nova_2013_1_4.param(\n 'libvirt_snapshots_directory', type='string',\n default='$instances_path/snapshots',\n description=\"Location where libvirt driver will store snapshots before\"\n \" uploading them to image service\")\n\n nova_2013_1_4.param(\n 'xen_hvmloader_path', type='string', default='/usr/lib/xen/boot/hvmloader',\n description=\"Location where the Xen hvmloader is kept\")\n\n nova_2013_1_4.param('disk_cachemodes', type='list', default='',\n description=\"Specific cachemodes to use for different disk types\"\n \" e.g: ['file=directsync','block=none']\")\n\n nova_2013_1_4.param(\n 'libvirt_images_type', type='string', default='default',\n description=\"VM Images format. Acceptable values are: raw, qcow2,\"\n \" lvm, default. If default is specified, then \"\n \"use_cow_images flag is used instead of this one.\")\n\n nova_2013_1_4.param(\n 'libvirt_images_volume_group', type='string', default='',\n description=\"LVM Volume Group that is used for VM images, when you \"\n \"specify libvirt_images_type=lvm.\")\n\n nova_2013_1_4.param('libvirt_sparse_logical_volumes', type='boolean',\n default='false', description=\"Create sparse logical volumes\")\n\n nova_2013_1_4.param('libvirt_lvm_snapshot_size', type='integer',\n default='1000', description=\"The amount of storage\")\n\n nova_2013_1_4.param('base_dir_name', type='string', default='_base',\n description=\"Where cached images are stored under $instances_path.\"\n \"This is NOT the full path - just a folder name.For \"\n \"per-compute-host cached images, set to _base_$my_ip\")\n\n nova_2013_1_4.param(\n 'image_info_filename_pattern', type='string',\n default='$instances_path/$base_dir_name/%(image)s.info',\n description=\"Allows image information files to be stored in non-standard \"\n \"locations\")\n\n nova_2013_1_4.param('remove_unused_base_images', type='boolean',\n default='true', description=\"Should unused base images be removed?\")\n\n nova_2013_1_4.param(\n 'remove_unused_kernels', type='boolean', default='false',\n description=\"Should unused kernel images be removed? This is only \"\n \"safe to enable if all compute nodes have been updated \"\n \"to support this option. This will enabled by default \"\n \"in future.\")\n\n nova_2013_1_4.param(\n 'remove_unused_resized_minimum_age_seconds', type='integer',\n default='3600',\n description=\"Unused resized base images younger than this will not be \"\n \"removed\")\n\n nova_2013_1_4.param(\n 'remove_unused_original_minimum_age_seconds', type='integer',\n default='86400',\n description=\"Unused unresized base images younger than this will not be \"\n \"removed\")\n\n nova_2013_1_4.param(\n 'checksum_base_images', type='boolean', default='false',\n description=\"Write a checksum for files in _base to disk\")\n\n nova_2013_1_4.param('checksum_interval_seconds', type='integer',\n default='3600',\n description=\"How frequently to checksum base images\")\n\n nova_2013_1_4.param(\n 'libvirt_snapshot_compression', type='boolean', default='false',\n description=\"Compress snapshot images when possible. This currently\"\n \" applies exclusively to qcow2 images\")\n\n nova_2013_1_4.param('libvirt_ovs_bridge', type='string', default='br-int',\n description=\"Name of Integration Bridge used by Open vSwitch\")\n\n nova_2013_1_4.param(\n 'libvirt_use_virtio_for_bridges', type='boolean', default='true',\n description=\"Use virtio for bridge interfaces with KVM/QEMU\")\n\n nova_2013_1_4.param('num_iscsi_scan_tries', type='integer', default='3',\n description=\"number of times to rescan iSCSI target to find volume\")\n\n nova_2013_1_4.param('rbd_user', type='string', default='',\n description=\"the RADOS client name for accessing rbd volumes\")\n\n nova_2013_1_4.param('rbd_secret_uuid', type='string', default='',\n description=\"the libvirt uuid of the secret for the \"\n \"rbd_uservolumes\")\n\n nova_2013_1_4.param(\n 'nfs_mount_point_base', type='string', default='$state_path/mnt',\n description=\"Dir where the nfs volume is mounted on the compute \"\n \"node\")\n\n nova_2013_1_4.param('nfs_mount_options', type='string', default='',\n description=\"Mount options passed to the nfs client. See section \"\n \"of the nfs man page for details\")\n\n nova_2013_1_4.param('num_aoe_discover_tries', type='integer', default='3',\n description=\"number of times to rediscover AoE target to find \"\n \"volume\")\n\n nova_2013_1_4.param(\n 'glusterfs_mount_point_base', type='string', default='$state_path/mnt',\n description=\"Dir where the glusterfs volume is mounted on the compute\"\n \" node\")\n\n nova_2013_1_4.param(\n 'libvirt_iscsi_use_multipath', type='boolean', default='false',\n description=\"use multipath connection of the iSCSI volume\")\n\n nova_2013_1_4.param('scality_sofs_config', type='string', default='',\n description=\"Path or URL to Scality SOFS configuration file\")\n\n nova_2013_1_4.param(\n 'scality_sofs_mount_point', type='string', default='$state_path/scality',\n description=\"Base dir where Scality SOFS shall be mounted\")\n\n nova_2013_1_4.param('powervm_mgr_type', type='string',\n default='ivm', description=\"PowerVM manager type\")\n\n nova_2013_1_4.param('powervm_mgr', type='string', default='',\n description=\"PowerVM manager host or ip\")\n\n nova_2013_1_4.param('powervm_mgr_user', type='string',\n default='', description=\"PowerVM manager user name\")\n\n nova_2013_1_4.param('powervm_mgr_passwd', type='string',\n default='', description=\"PowerVM manager user password\")\n\n nova_2013_1_4.param(\n 'powervm_img_remote_path', type='string', default='/home/padmin',\n description=\"PowerVM image remote path where images will be moved.\"\n \" Make sure this path can fit your biggest image in\"\n \" glance\")\n\n nova_2013_1_4.param(\n 'powervm_img_local_path', type='string', default='/tmp',\n description=\"Local directory to download glance images to. Make \"\n \"sure this path can fit your biggest image in glance\")\n\n nova_2013_1_4.param('vmwareapi_host_ip', type='string', default='',\n description=\"URL for connection to VMware ESX/VC host. Required if\"\n \" compute_driver is vmwareapi.VMwareESXDriver or \"\n \"vmwareapi.VMwareVCDriver.\")\n\n nova_2013_1_4.param(\n 'vmwareapi_host_username', type='string', default='',\n description=\"Username for connection to VMware ESX/VC host. Used \"\n \"only if compute_driver is vmwareapi.VMwareESXDriver or\"\n \" vmwareapi.VMwareVCDriver.\")\n\n nova_2013_1_4.param(\n 'vmwareapi_host_password', type='string', default='',\n description=\"Password for connection to VMware ESX/VC host. Used\"\n \" only if compute_driver is vmwareapi.VMwareESXDriver\"\n \" or vmwareapi.VMwareVCDriver.\")\n\n nova_2013_1_4.param(\n 'vmwareapi_cluster_name', type='string', default='',\n description=\"Name of a VMware Cluster ComputeResource. Used only if\"\n \" compute_driver is vmwareapi.VMwareVCDriver.\")\n\n nova_2013_1_4.param(\n 'vmwareapi_task_poll_interval', type='floating point', default='5.0',\n description=\"The interval used for polling of remote tasks. Used only if\"\n \" compute_driver is vmwareapi.VMwareESXDriver or vmwareapi\"\n \".VMwareVCDriver.\")\n\n nova_2013_1_4.param(\n 'vmwareapi_api_retry_count', type='integer', default='10',\n description=\"The number of times we retry on failures, e.g., \"\n \"socket error, etc. Used only if compute_driver is \"\n \"vmwareapi.VMwareESXDriver or \"\n \"vmwareapi.VMwareVCDriver.\")\n\n nova_2013_1_4.param('vnc_port', type='integer',\n default='5900', description=\"VNC starting port\")\n\n nova_2013_1_4.param('vnc_port_total', type='integer',\n default='10000', description=\"Total number of VNC ports\")\n\n nova_2013_1_4.param('vnc_password', type='string',\n default='', description=\"VNC password\")\n\n nova_2013_1_4.param('use_linked_clone', type='boolean',\n default='true', description=\"Whether to use linked clone\")\n\n nova_2013_1_4.param(\n 'vmwareapi_vlan_interface', type='string', default='vmnic0',\n description=\"Physical ethernet adapter name for vlan networking\")\n\n nova_2013_1_4.param('vmwareapi_wsdl_loc', type='string', default='',\n description=\"Optional VIM Service WSDL Location e.g \"\n \"http:///vimService.wsdl\")\n\n nova_2013_1_4.param('agent_timeout', type='integer', default='30',\n description=\"number of seconds to wait for agent reply\")\n\n nova_2013_1_4.param('agent_version_timeout', type='integer', default='300',\n description=\"number of seconds to wait for agent to be fully\"\n \" operational\")\n\n nova_2013_1_4.param(\n 'agent_resetnetwork_timeout', type='integer', default='60',\n description=\"number of seconds to wait for agent reply to\"\n \" resetnetwork request\")\n\n nova_2013_1_4.param(\n 'xenapi_agent_path', type='string',\n default='usr/sbin/xe-update-networking',\n description=\"Specifies the path in which the xenapi guest agent should be\"\n \" located. If the agent is present, network configuration is \"\n \"not injected into the image. Used if \"\n \"compute_driver=xenapi.XenAPIDriver and flat_injected=True\")\n\n nova_2013_1_4.param(\n 'xenapi_disable_agent', type='boolean', default='false',\n description=\"Disable XenAPI agent. Reduces the amount of time it \"\n \"takes nova to detect that a VM has started, when that \"\n \"VM does not have the agent installed\")\n\n nova_2013_1_4.param(\n 'xenapi_connection_url', type='string', default='',\n description=\"URL for connection to XenServer/Xen Cloud Platform. \"\n \"Required if compute_driver=xenapi.XenAPIDriver\")\n\n nova_2013_1_4.param(\n 'xenapi_connection_username', type='string', default='root',\n description=\"Username for connection to XenServer/Xen Cloud \"\n \"Platform. Used only if \"\n \"compute_driver=xenapi.XenAPIDriver\")\n\n nova_2013_1_4.param(\n 'xenapi_connection_password', type='string', default='',\n description=\"Password for connection to XenServer/Xen Cloud \"\n \"Platform. Used only if compute_driver=xenapi\"\n \".XenAPIDriver\")\n\n nova_2013_1_4.param(\n 'xenapi_connection_concurrent', type='integer', default='5',\n description=\"Maximum number of concurrent XenAPI connections. \"\n \"Used only if compute_driver=xenapi.XenAPIDriver\")\n\n nova_2013_1_4.param(\n 'xenapi_vhd_coalesce_poll_interval', type='floating point', default='5.0',\n description=\"The interval used for polling of coalescing vhds. Used only \"\n \"if compute_driver=xenapi.XenAPIDriver\")\n\n nova_2013_1_4.param('xenapi_check_host', type='boolean', default='true',\n description=\"Ensure compute service is running on host XenAPI \"\n \"connects to.\")\n\n nova_2013_1_4.param(\n 'xenapi_vhd_coalesce_max_attempts', type='integer', default='5',\n description=\"Max number of times to poll for VHD to coalesce. Used \"\n \"only if compute_driver=xenapi.XenAPIDriver\")\n\n nova_2013_1_4.param(\n 'xenapi_sr_base_path', type='string', default='/var/run/sr-mount',\n description=\"Base path to the storage repository\")\n\n nova_2013_1_4.param('target_host', type='string',\n default='', description=\"iSCSI Target Host\")\n\n nova_2013_1_4.param('target_port', type='string', default='3260',\n description=\"iSCSI Target Port, 3260 Default\")\n\n nova_2013_1_4.param('iqn_prefix', type='string',\n default='iqn.2010-10.org.openstack', description=\"IQN Prefix\")\n\n nova_2013_1_4.param(\n 'xenapi_remap_vbd_dev', type='boolean', default='false',\n description=\"Used to enable the remapping of VBD dev\")\n\n nova_2013_1_4.param('xenapi_remap_vbd_dev_prefix', type='string',\n default='sd', description=\"Specify prefix to remap VBD dev to\")\n\n nova_2013_1_4.param('xenapi_login_timeout', type='integer', default='10',\n description=\"Timeout in seconds for XenAPI login.\")\n\n nova_2013_1_4.param('use_join_force', type='boolean', default='true',\n description=\"To use for hosts with different CPUs\")\n\n nova_2013_1_4.param(\n 'xenapi_ovs_integration_bridge', type='string', default='xapi1',\n description=\"Name of Integration Bridge used by Open vSwitch\")\n\n nova_2013_1_4.param('cache_images', type='string', default='all',\n description=\"Cache glance images locally. `all` will cache all \"\n \"images, `some` will only cache images that have the \"\n \"image_property `cache_in_nova=True`, and `none` turns \"\n \"off caching entirely\")\n\n nova_2013_1_4.param('default_os_type', type='string',\n default='linux', description=\"Default OS type\")\n\n nova_2013_1_4.param(\n 'block_device_creation_timeout', type='integer', default='10',\n description=\"Time to wait for a block device to be created\")\n\n nova_2013_1_4.param(\n 'max_kernel_ramdisk_size', type='integer', default='16777216',\n description=\"Maximum size in bytes of kernel or ramdisk images\")\n\n nova_2013_1_4.param(\n 'sr_matching_filter', type='string',\n default='other-config:i18n-keylocal-storage',\n description=\"Filter for finding the SR to be used to install guest \"\n \"instances on. The default value is the Local Storage in \"\n \"default XenServer/XCP installations. To select an SR with a \"\n \"different matching criteria, you could set it to other- \"\n \"config:my_favorite_sr=true. On the other hand, to fall back \"\n \"on the Default SR, as displayed by XenCenter, set this flag \"\n \"to: default-sr:true\")\n\n nova_2013_1_4.param('xenapi_sparse_copy', type='boolean', default='true',\n description=\"Whether to use sparse_copy for copying data on a \"\n \"resize down\")\n\n nova_2013_1_4.param('xenapi_num_vbd_unplug_retries', type='integer',\n default='10', description=\"Maximum number of retries to unplug VBD\")\n\n nova_2013_1_4.param('xenapi_torrent_images', type='string', default='none',\n description=\"Whether or not to download images via Bit Torrent\")\n\n nova_2013_1_4.param('xenapi_torrent_base_url', type='string',\n default='', description=\"Base URL for torrent files.\")\n\n nova_2013_1_4.param('xenapi_torrent_seed_chance', type='floating point',\n default='1.0',\n description=\"Probability that peer will become a seeder.\")\n\n nova_2013_1_4.param(\n 'xenapi_torrent_seed_duration', type='integer', default='3600',\n description=\"Number of seconds after downloading an image via \"\n \"BitTorrent that it should be seeded for other peers.\")\n\n nova_2013_1_4.param(\n 'xenapi_torrent_max_last_accessed', type='integer', default='86400',\n description=\"Cached torrent files not accessed within this number \"\n \"of seconds can be reaped\")\n\n nova_2013_1_4.param('xenapi_torrent_listen_port_start', type='integer',\n default='6881', description=\"Beginning of port range to listen on\")\n\n nova_2013_1_4.param('xenapi_torrent_listen_port_end', type='integer',\n default='6891', description=\"End of port range to listen on\")\n\n nova_2013_1_4.param(\n 'xenapi_torrent_download_stall_cutoff', type='integer', default='600',\n description=\"Number of seconds a download can remain at the same progress \"\n \"percentage w/o being considered a stall\")\n\n nova_2013_1_4.param(\n 'xenapi_torrent_max_seeder_processes_per_host', type='integer',\n default='1',\n description=\"Maximum number of seeder processes to run concurrently within\"\n \" a given dom0.\")\n\n nova_2013_1_4.param('xenapi_running_timeout', type='integer', default='60',\n description=\"number of seconds to wait for instance to go to \"\n \"running state\")\n\n nova_2013_1_4.param(\n 'xenapi_vif_driver', type='string',\n default='nova.virt.xenapi.vif.XenAPIBridgeDriver',\n description=\"The XenAPI VIF driver using XenServer Network APIs.\")\n\n nova_2013_1_4.param(\n 'xenapi_image_upload_handler', type='string',\n default='nova.virt.xenapi.imageupload.glance.GlanceStore',\n description=\"Object Store Driver used to handle image uploads.\")\n\n nova_2013_1_4.param(\n 'novncproxy_base_url', type='string',\n default='http://127.0.0.1:6080/vnc_auto.html',\n description=\"location of vnc console proxy, in the form \"\n \"'http://127.0.0.1:6080/vnc_auto.html'\")\n\n nova_2013_1_4.param(\n 'xvpvncproxy_base_url', type='string',\n default='http://127.0.0.1:6081/console',\n description=\"location of nova xvp vnc console proxy, in the form \"\n \"'http://127.0.0.1:6081/console'\")\n\n nova_2013_1_4.param('vncserver_listen', type='string', default='127.0.0.1',\n description=\"IP address on which instance vncservers should listen\")\n\n nova_2013_1_4.param('vncserver_proxyclient_address', type='string',\n default='127.0.0.1',\n description=\"the address to which proxy clients\")\n\n nova_2013_1_4.param('vnc_enabled', type='boolean', default='true',\n description=\"enable vnc related features\")\n\n nova_2013_1_4.param('vnc_keymap', type='string',\n default='en-us', description=\"keymap for vnc\")\n\n nova_2013_1_4.param('xvpvncproxy_port', type='integer', default='6081',\n description=\"Port that the XCP VNC proxy should bind to\")\n\n nova_2013_1_4.param('xvpvncproxy_host', type='string', default='0.0.0.0',\n description=\"Address that the XCP VNC proxy should bind to\")\n\n nova_2013_1_4.param(\n 'volume_api_class', type='string', default='nova.volume.cinder.API',\n description=\"The full class name of the volume API class to use\")\n\n nova_2013_1_4.param(\n 'cinder_catalog_info', type='string', default='volume:cinder:publicURL',\n description=\"Info to match when looking for cinder in the service catalog.\"\n \" Format is : separated values of the form: \"\n \"::\")\n\n nova_2013_1_4.param(\n 'cinder_endpoint_template', type='string', default='',\n description=\"Override service catalog lookup with template for \"\n \"cinder endpoint e.g. \"\n \"http://localhost:8776/v1/%(project_id)s\")\n\n nova_2013_1_4.param('os_region_name', type='string',\n default='', description=\"region name of this node\")\n\n nova_2013_1_4.param('cinder_http_retries', type='integer', default='3',\n description=\"Number of cinderclient retries on failed http calls\")\n\n nova_2013_1_4.param('cinder_api_insecure', type='boolean', default='false',\n description=\"Allow to perform insecure SSL requests to cinder\")\n\n nova_2013_1_4.param(\n 'cinder_cross_az_attach', type='boolean', default='true',\n description=\"Allow attach between instance and volume in different\"\n \" availability zones.\")\n\n nova_2013_1_4.section('HYPERV')\n\n nova_2013_1_4.param('instances_path_share', type='string', default='',\n description=\"The name of a Windows share name mapped to the \"\n \"'instances_path' dir and used by the resize feature to\"\n \" copy files to the target host. If left blank, an \"\n \"administrative share will be used, looking for the \"\n \"same 'instances_path' used locally\")\n\n nova_2013_1_4.section('conductor')\n\n nova_2013_1_4.param('use_local', type='boolean', default='false',\n description=\"Perform nova-conductor operations locally\")\n\n nova_2013_1_4.param('topic', type='string', default='conductor',\n description=\"the topic conductor nodes listen on\")\n\n nova_2013_1_4.param(\n 'manager', type='string',\n default='nova.conductor.manager.ConductorManager',\n description=\"full class name for the Manager for conductor\")\n\n nova_2013_1_4.section('cells')\n\n nova_2013_1_4.param(\n 'driver', type='string', default='nova.cells.rpc_driver.CellsRPCDriver',\n description=\"Cells communication driver to use\")\n\n nova_2013_1_4.param(\n 'instance_updated_at_threshold', type='integer', default='3600',\n description=\"Number of seconds after an instance was updated or \"\n \"deleted to continue to update cells\")\n\n nova_2013_1_4.param(\n 'instance_update_num_instances', type='integer', default='1',\n description=\"Number of instances to update per periodic task run\")\n\n nova_2013_1_4.param('max_hop_count', type='integer', default='10',\n description=\"Maximum number of hops for cells routing.\")\n\n nova_2013_1_4.param('scheduler', type='string',\n default='nova.cells.scheduler.CellsScheduler',\n description=\"Cells scheduler to use\")\n\n nova_2013_1_4.param('enable', type='boolean', default='false',\n description=\"Enable cell functionality\")\n\n nova_2013_1_4.param('topic', type='string', default='cells',\n description=\"the topic cells nodes listen on\")\n\n nova_2013_1_4.param('manager', type='string',\n default='nova.cells.manager.CellsManager',\n description=\"Manager for cells\")\n\n nova_2013_1_4.param('name', type='string',\n default='nova', description=\"name of this cell\")\n\n nova_2013_1_4.param(\n 'capabilities', type='list',\n default='hypervisorxenserver;kvm,oslinux;windows',\n description=\"Key/Multi-value list with the capabilities of the cell\")\n\n nova_2013_1_4.param('call_timeout', type='integer', default='60',\n description=\"Seconds to wait for response from a call to a cell.\")\n\n nova_2013_1_4.param(\n 'rpc_driver_queue_base', type='string', default='cells.intercell',\n description=\"Base queue name to use when communicating between \"\n \"cells. Various topics by message type will be appended\"\n \" to this.\")\n\n nova_2013_1_4.param('scheduler_retries', type='integer', default='10',\n description=\"How many retries when no cells are available.\")\n\n nova_2013_1_4.param('scheduler_retry_delay', type='integer', default='2',\n description=\"How often to retry in seconds when no cells are \"\n \"available.\")\n\n nova_2013_1_4.param('db_check_interval', type='integer', default='60',\n description=\"Seconds between getting fresh cell info from db.\")\n\n nova_2013_1_4.section('zookeeper')\n\n nova_2013_1_4.param('address', type='string', default='',\n description=\"The ZooKeeper addresses for servicegroup service in \"\n \"the format of host1:port,host2:port,host3:port\")\n\n nova_2013_1_4.param('recv_timeout', type='integer', default='4000',\n description=\"recv_timeout parameter for the zk session\")\n\n nova_2013_1_4.param('sg_prefix', type='string', default='/servicegroups',\n description=\"The prefix used in ZooKeeper to store ephemeral nodes\")\n\n nova_2013_1_4.param('sg_retry_interval', type='integer', default='5',\n description=\"Number of seconds to wait until retrying to join the \"\n \"session\")\n\n nova_2013_1_4.section('baremetal')\n\n nova_2013_1_4.param('db_backend', type='string', default='sqlalchemy',\n description=\"The backend to use for bare-metal database\")\n\n nova_2013_1_4.param(\n 'sql_connection', type='string',\n default='sqlite:///$state_path/baremetal_$sqlite_db',\n description=\"The SQLAlchemy connection string used to connect to the \"\n \"bare-metal database\")\n\n nova_2013_1_4.param('inject_password', type='boolean', default='true',\n description=\"Whether baremetal compute injects password or not\")\n\n nova_2013_1_4.param('injected_network_template', type='string',\n default='$pybasedir/nova/virt/baremetal/interfaces.template',\n description=\"Template file for injected network\")\n\n nova_2013_1_4.param('vif_driver', type='string',\n default='nova.virt.baremetal.vif_driver.BareMetalVIFDriver',\n description=\"Baremetal VIF driver.\")\n\n nova_2013_1_4.param('volume_driver', type='string',\n default='nova.virt.baremetal.volume_driver.LibvirtVolumeDriver',\n description=\"Baremetal volume driver.\")\n\n nova_2013_1_4.param('instance_type_extra_specs', type='list', default='',\n description=\"a list of additional capabilities corresponding to \"\n \"instance_type_extra_specs for this compute host to \"\n \"advertise. Valid entries are name=value, pairs For \"\n \"example, 'key1:val1, key2:val2'\")\n\n nova_2013_1_4.param(\n 'driver', type='string', default='nova.virt.baremetal.pxe.PXE',\n description=\"Baremetal driver back-end\")\n\n nova_2013_1_4.param(\n 'power_manager', type='string', default='nova.virt.baremetal.ipmi.IPMI',\n description=\"Baremetal power management method\")\n\n nova_2013_1_4.param('tftp_root', type='string', default='/tftpboot',\n description=\"Baremetal compute node's tftp root path\")\n\n nova_2013_1_4.param('terminal', type='string', default='shellinaboxd',\n description=\"path to baremetal terminal program\")\n\n nova_2013_1_4.param('terminal_cert_dir', type='string', default='',\n description=\"path to baremetal terminal SSL cert(PEM)\")\n\n nova_2013_1_4.param(\n 'terminal_pid_dir', type='string', default='$state_path/baremetal/console',\n description=\"path to directory stores pidfiles of baremetal_terminal\")\n\n nova_2013_1_4.param('ipmi_power_retry', type='integer', default='5',\n description=\"maximal number of retries for IPMI operations\")\n\n nova_2013_1_4.param('deploy_kernel', type='string', default='',\n description=\"Default kernel image ID used in deployment phase\")\n\n nova_2013_1_4.param('deploy_ramdisk', type='string', default='',\n description=\"Default ramdisk image ID used in deployment phase\")\n\n nova_2013_1_4.param(\n 'net_config_template', type='string',\n default='$pybasedir/nova/virt/baremetal/net-dhcp.ubuntu.template',\n description=\"Template file for injected network config\")\n\n nova_2013_1_4.param('pxe_append_params', type='string', default='',\n description=\"additional append parameters for baremetal PXE boot\")\n\n nova_2013_1_4.param(\n 'pxe_config_template', type='string',\n default='$pybasedir/nova/virt/baremetal/pxe_config.template',\n description=\"Template file for PXE configuration\")\n\n nova_2013_1_4.param('pxe_deploy_timeout', type='integer', default='0',\n description=\"Timeout for PXE deployments. Default: 0\")\n\n nova_2013_1_4.param('virtual_power_ssh_host', type='string',\n default='', description=\"ip or name to virtual power host\")\n\n nova_2013_1_4.param('virtual_power_type', type='string', default='vbox',\n description=\"base command to use for virtual power(vbox,virsh)\")\n\n nova_2013_1_4.param('virtual_power_host_user', type='string', default='',\n description=\"user to execute virtual power commands as\")\n\n nova_2013_1_4.param('virtual_power_host_pass', type='string',\n default='', description=\"password for virtual power host_user\")\n\n nova_2013_1_4.param('use_unsafe_iscsi', type='boolean', default='false',\n description=\"Do not set this out of dev/test environments. If a \"\n \"node does not have a fixed PXE IP address, volumes are\"\n \" exported with globally opened ACL\")\n\n nova_2013_1_4.param(\n 'iscsi_iqn_prefix', type='string',\n default='iqn.2010-10.org.openstack.baremetal',\n description=\"iSCSI IQN prefix used in baremetal volume connections.\")\n\n nova_2013_1_4.section('rpc_notifier2')\n\n nova_2013_1_4.param('topics', type='list', default='notifications',\n description=\"AMQP topic(s) used for openstack notifications\")\n\n nova_2013_1_4.section('trusted_computing')\n\n nova_2013_1_4.param('attestation_server', type='string',\n default='', description=\"attestation server http\")\n\n nova_2013_1_4.param(\n 'attestation_server_ca_file', type='string', default='',\n description=\"attestation server Cert file for Identity \"\n \"verification\")\n\n nova_2013_1_4.param('attestation_port', type='string',\n default='8443', description=\"attestation server port\")\n\n nova_2013_1_4.param('attestation_api_url', type='string',\n default='/OpenAttestationWebServices/V1.0',\n description=\"attestation web API URL\")\n\n nova_2013_1_4.param(\n 'attestation_auth_blob', type='string', default='',\n description=\"attestation authorization blob - must change\")\n\n nova_2013_1_4.param(\n 'attestation_auth_timeout', type='integer', default='60',\n description=\"Attestation status cache valid period length\")\n\n nova_2013_1_4.section('vmware')\n\n nova_2013_1_4.param('integration_bridge', type='string',\n default='br-int', description=\"Name of Integration Bridge\")\n\n nova_2013_1_4.section('spice')\n\n nova_2013_1_4.param(\n 'html5proxy_base_url', type='string',\n default='http://127.0.0.1:6082/spice_auto.html',\n description=\"location of spice html5 console proxy, in the form \"\n \"'http://127.0.0.1:6082/spice_auto.html'\")\n\n nova_2013_1_4.param('server_listen', type='string', default='127.0.0.1',\n description=\"IP address on which instance spice server should \"\n \"listen\")\n\n nova_2013_1_4.param('server_proxyclient_address', type='string',\n default='127.0.0.1',\n description=\"the address to which proxy clients\")\n\n nova_2013_1_4.param('enabled', type='boolean', default='false',\n description=\"enable spice related features\")\n\n nova_2013_1_4.param('agent_enabled', type='boolean', default='true',\n description=\"enable spice guest agent support\")\n\n nova_2013_1_4.param('keymap', type='string',\n default='en-us', description=\"keymap for spice\")\n","sub_path":"rubick/schemas/nova/v2013_1_4.py","file_name":"v2013_1_4.py","file_ext":"py","file_size_in_byte":111731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"47974019","text":"from threading import Thread\nimport cv2 as cv\nimport subprocess\n\nclass ThreadedWebcam:\n\tdef __init__(self, src=0, name=\"ThreadedWebcam\"):\n\t\tself.stream = cv.VideoCapture(src)\n\t\tsubprocess.call([\"v4l2-ctl\"] + \"--set-ctrl=white_balance_auto_preset=0\".split())\n\t\tsubprocess.call([\"v4l2-ctl\"] + \"--set-ctrl=red_balance=1400\".split())\n\t\tsubprocess.call([\"v4l2-ctl\"] + \"--set-ctrl=blue_balance=1600\".split())\n\t\tself.stream.set(cv.CAP_PROP_FRAME_WIDTH, 640)\n\t\tself.stream.set(cv.CAP_PROP_FRAME_HEIGHT, 480)\n\t\t#self.stream.set(cv.CAP_PROP_BUFFERSIZE, 1)\n\t\t\n\t\tif not self.stream.isOpened():\n\t\t\tprint(\"Failed to open camera!\")\n\t\t\texit()\n\t\t\t\n\t\t(self.grabbed, self.frame) = self.stream.read()\n\t\t\n\t\tself.name = name\n\t\t\n\t\tself.stopped = False\n\t\t\n\tdef start(self):\n\t\tt = Thread(target=self._update, name=self.name, args=())\n\t\tt.daemon = True\n\t\tt.start()\n\t\treturn self\n\t\t\n\tdef _update(self):\n\t\twhile True:\n\t\t\tif self.stopped:\n\t\t\t\treturn\n\t\t\t\t\n\t\t\t(self.grabbed, self.frame) = self.stream.read()\n\t\n\tdef read(self):\n\t\treturn self.frame\n\t\n\tdef stop(self):\n\t\tself.stopped = True\n\n","sub_path":"PiRobot-bryce/ThreadedWebcam.py","file_name":"ThreadedWebcam.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"618737193","text":"class SimHash:\n\n # 构造函数\n def __init__(self, tokens='', hash_bits=84):\n self.strHash = '' # 记录数字指纹\n self.hash_bits = hash_bits # 数字指纹位数\n self.hash = self.sim_hash(tokens)\n\n # # toString函数\n # def __str__(self):\n # return str(self.hash)\n\n # 生成simHash值与strHash值\n def sim_hash(self, tokens):\n v = [0] * self.hash_bits\n for t in [self._string_hash(x) for x in tokens]: # t为token的普通hash值\n for i in range(self.hash_bits):\n bitmask = 1 << i\n if t & bitmask:\n v[i] += 1 # 查看当前bit位是否为1, 是的话将该位+1\n else:\n v[i] -= 1 # 否则的话, 该位-1\n fingerprint = 0\n for i in range(self.hash_bits):\n if v[i] >= 0:\n self.strHash += '1' # 若是整数则置1\n fingerprint += 1 << i\n else:\n self.strHash += '0' # 否则置0\n return fingerprint # 整个文档的fingerprint为最终各个位>=0的和\n\n # 针对source生成hash值 (一个可变长度版本的Python的内置散列)\n def _string_hash(self, source):\n if source == \"\":\n return 0\n else:\n x = ord(source[0]) << 7\n m = 1000003\n mask = 2 ** self.hash_bits - 1\n for c in source:\n x = ((x * m) ^ ord(c)) & mask\n x ^= len(source)\n if x == -1:\n x = -2\n return x\n\n # 求相似度\n def similarity(self, other):\n like = 0\n for i in range(len(self.strHash)):\n if int(self.strHash[i]) == int(other.strHash[i]):\n like += 1 # 通过数字指纹得到相似的段, 然后再计算相似度\n return float(like) / float(self.hash_bits)\n","sub_path":"simhash.py","file_name":"simhash.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"260767784","text":"import maya.cmds as cmds\r\n\r\n#Create arm joints\r\n#Create IK joints\r\nIKjointInfo = [['IK_upArm_JNT', [0, 0, 0]], ['IK_loArm_JNT', [-1, 0, -3]], ['IK_wristArm_JNT', [0, 0, -6]], ['IK_wristArmEnd_JNT', [0, 0, -8]]]\r\n#Create FK joints\r\nFKjointInfo = [['FK_upArm_JNT', [0, 0, 0]], ['FK_loArm_JNT', [-1, 0, -3]], ['FK_wristArm_JNT', [0, 0, -6]], ['FK_wristArmEnd_JNT', [0, 0, -8]]]\r\n#Create rig joints \r\nRIGjointInfo = [['RIG_upArm_JNT', [0, 0, 0]], ['RIG_loArm_JNT', [-1, 0, -3]], ['RIG_wristArm_JNT', [0, 0, -6]], ['RIG_wristArmEnd_JNT', [0, 0, -8]]]\r\n\r\n\r\nclass Rig_Limb:\r\n\tdef rig_limb(self):\r\n\t\t#Create IK Joints\r\n\t\tself.createJoint(IKjointInfo)\r\n\t\tcmds.select(d=True)\r\n\t\t#Create FK Joints\r\n\t\tself.createJoint(FKjointInfo)\r\n\t\tcmds.select(d=True)\r\n\t\t#Create RIG Joints\r\n\t\tself.createJoint(RIGjointInfo)\r\n\t\tcmds.select(d=True)\r\n\r\n\t\t#Create IK Rig\r\n\t\t#IK Handle\r\n\t\tIKhandle = cmds.ikHandle(n='IK_wrist_handle', sj='IK_upArm_JNT', ee='IK_wristArm_JNT', p=2, w=1)\r\n\r\n\t\tIKctrlInfo = [[IKjointInfo[2][1], 'IK_wrist_CTRL', 'IK_wrist_GRP']]\r\n\t\tself.createControl(IKctrlInfo)\r\n\r\n\t\tPVpos = self.calculatePVposition([IKjointInfo[0][0], IKjointInfo[1][0], IKjointInfo[2][0]])\r\n\t\tPVctrlInfo = [[PVpos, 'PV_arm_CTRL', 'PV_arm_GRP']]\r\n\t\tself.createControl(PVctrlInfo)\r\n\r\n\t\t#parent ikHandle to ctrl\r\n\t\tcmds.parent('IK_wrist_handle', 'IK_wrist_CTRL')\r\n\r\n\t\t#PV constraint\r\n\t\tcmds.poleVectorConstraint(PVctrlInfo[0][1], IKhandle[0])\r\n\r\n\t\t#orient constraint arm ik_wrist to wrist_ctrl\r\n\t\tcmds.orientConstraint(IKctrlInfo[0][1], IKjointInfo[2][0], mo=True)\r\n\r\n\t\t#Create FK rig\r\n\t\tFKctrlInfo = [[FKjointInfo[0][1], 'FK_upArm_CTRL', 'FK_upArm_GRP'], [FKjointInfo[1][1], 'FK_loArm_CTRL', 'FK_loArm_GRP'], [FKjointInfo[2][1], 'FK_wrist_CTRL', 'FK_wrist_GRP']]\r\n\t\tself.createControl(FKctrlInfo)\r\n\r\n\t\t#Parent FK controls\r\n\t\tcmds.parent(FKctrlInfo[1][2], FKctrlInfo[0][1])\r\n\t\tcmds.parent(FKctrlInfo[2][2], FKctrlInfo[1][1])\r\n\r\n \r\n\tdef createJoint(self, jointInfo):\r\n\t for item in jointInfo:\r\n\t cmds.joint(n=item[0], p=item[1])\r\n\t \r\n\r\n\tdef createControl(self, ctrlInfo):\r\n\t\tfor info in ctrlInfo:\r\n\t \t\t#Create IK Control\r\n\t \t\t#get world space position of wrist\r\n\t \t\tpos = info[0]\r\n\t \t\t#Create empty group\r\n\t \t\tctrlGrp = cmds.group(em=True, name=info[2])\r\n\t \t\t#Create circle control object\r\n\t \t\tctrl = cmds.circle(n=info[1], nr=(0, 0, 1), c=(0, 0, 0))\r\n\t \t\t#parent control to group\r\n\t \t\tcmds.parent(ctrl, ctrlGrp)\r\n\t \t\t#move group to joint\r\n\t \t\tcmds.xform(ctrlGrp, t=pos, ws=True)\r\n\r\n\tdef calculatePVposition(self, jnts):\r\n\t\tfrom maya import cmds , OpenMaya\r\n\t\tstart = cmds.xform(jnts[0], q=True, ws=True, t=True)\r\n\t\tmid = cmds.xform(jnts[1], q=True, ws=True, t=True)\r\n\t\tend = cmds.xform(jnts[2], q=True, ws=True, t=True)\r\n\t\tstartV = openMaya.MVector(start[0] ,start[1],start[2])\r\n\t\tmidV = openMaya.MVector(mid[0] ,mid[1],mid[2])\r\n\t\tendV = openMaya.MVector(end[0] ,end[1],end[2])\r\n\t\tstartEnd = endV - startV\r\n\t\tstartMid = midV - startV\r\n\t\tdotP = startMid * startEnd\r\n\t\tproj = float(dotP) / float(startEnd.length())\r\n\t\tstartEndN = startEnd.normal()\r\n\t\tprojV = startEndN * proj\r\n\t\tarrowV = startMid - projV\r\n\t\tarrowV*= 0.5\r\n\t\tfinalV = arrowV + midV\r\n\t\treturn ([finalV.x , finalV.y , finalV.z])","sub_path":"rigBuilding/rig/archive/limb.py","file_name":"limb.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"369979456","text":"from RandomMatch import drawRandom\nfrom PIL import Image\nimport numpy as np\nimport time\n\ndef matchCost(left, right):\n z = ((left) + (right)) / 2\n result = ((z - left) * (z - right)) / 16\n return abs(result)\n\ndef disparity(left, right):\n return abs(left - right)\n\ndef rgbToIntensity(rgb):\n return sum(rgb) / len(rgb)\n\ndef costMatrix(left, right):\n costOfOcclusion = 1.8\n size = len(left)\n arr = [[0 for i in range(size + 1)] for i in range(size + 1)]\n steps = []\n test = [None for _ in range(size + 1)]\n for i in range(1, size + 1):\n arr[i][0] = i * costOfOcclusion\n arr[0][i] = i * costOfOcclusion\n\n for i in range(1, size):\n currentSteps = []\n for j in range(1, size):\n costOfMatch = matchCost(left[i], right[j]) + arr[i - 1][j - 1]\n leftOcculsion = arr[i-1][j] + costOfOcclusion\n rightOcculsion = arr[i][j - 1] + costOfOcclusion\n\n arr[i][j] = min(costOfMatch, rightOcculsion, leftOcculsion)\n\n if arr[i][j] == costOfMatch:\n currentSteps.append(1)\n elif arr[i][j] == rightOcculsion:\n currentSteps.append(2)\n else:\n currentSteps.append(3)\n steps.append(currentSteps)\n return steps\n\ndef backward(decisions):\n i = j = len(decisions) - 1\n result = [0 for i in range(len(decisions) + 1)]\n while (i >= 0 and j >= 0):\n last_decision = decisions[i][j]\n if last_decision == 1: # matched case\n result[i] = disparity(i, j) + 128\n i -= 1\n j -= 1\n elif last_decision == 3 : # left[i] is occuluded\n # result[i] = 0\n i -= 1\n else: # right[j] is occuluded\n j -= 1\n #print(result)\n return result\n\ndef go():\n # bigSize = 512\n # smallSize = 256\n # drawRandom(bigSize, smallSize, 128, 124, 132)\n imgA = Image.open(\"/Users/chaozy/Desktop/CS/Algorithm/Coursework2/Stereo Pairs/Pair 2/view1.png\")\n #imgA = Image.open(\"imgLeft.png\")\n imgA = np.asarray(imgA)\n imgA = np.array([[rgbToIntensity(rgb) for rgb in rows] for rows in imgA])\n imgB = Image.open(\"/Users/chaozy/Desktop/CS/Algorithm/Coursework2/Stereo Pairs/Pair 2/view2.png\")\n #imgB = Image.open(\"imgRight.png\")\n imgB = np.asarray(imgB)\n imgB = np.array([[rgbToIntensity(rgb) for rgb in rows] for rows in imgB])\n\n bigSize = len(imgA)\n smallSize = len(imgA[0])\n disparityMatrix = np.array([[0 for i in range(smallSize)] for i in range(bigSize)])\n #disparityMatrix = np.array([[0 for i in range(bigSize)] for i in range(bigSize)])\n\n for i in range(bigSize):\n print(i)\n disparityMatrix[i] = backward(costMatrix(imgA[i], imgB[i]))\n\n img = Image.new('L', (smallSize, bigSize))\n img.putdata(np.reshape(disparityMatrix, smallSize * bigSize))\n\n #img.save(\"result1.png\")\n img.show()\n\nt1 = time.time()\ngo()\nt2 = time.time()\nprint(\"time taken: \", t2 - t1)\n\n\n","sub_path":"StereoMatching.py","file_name":"StereoMatching.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"139076097","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2009 EduSense BV ().\n# (C) 2011 - 2013 Therp BV ().\n# \n# All other contributions are (C) by their respective contributors\n#\n# All Rights Reserved\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import orm, fields\nfrom openerp import netsvc\nfrom openerp.tools.translate import _\n\nclass payment_line(orm.Model):\n '''\n Add some fields; make destination bank account\n mandatory, as it makes no sense to send payments into thin air.\n Edit: Payments can be by cash too, which is prohibited by mandatory bank\n accounts.\n '''\n _inherit = 'payment.line'\n _columns = {\n 'msg': fields.char('Message', size=255, required=False, readonly=True),\n 'date_done': fields.date(\n 'Date Confirmed', select=True, readonly=True),\n 'transit_move_line_id': fields.many2one(\n # this line is part of the credit side of move 2a \n # from the documentation\n 'account.move.line', 'Debit move line',\n readonly=True,\n help=\"Move line through which the debit order pays the invoice\",\n ),\n }\n\n _defaults = {\n 'msg': '',\n }\n\n \"\"\"\n Hooks for processing direct debit orders, such as implemented in\n account_direct_debit module.\n \"\"\"\n def get_storno_account_id(self, cr, uid, payment_line_id, amount,\n currency_id, context=None):\n \"\"\"\n Hook for verifying a match of the payment line with the amount.\n Return the account associated with the storno.\n Used in account_banking interactive mode\n :param payment_line_id: the single payment line id\n :param amount: the (signed) amount debited from the bank account\n :param currency: the bank account's currency *browse object*\n :return: an account if there is a full match, False otherwise\n :rtype: database id of an account.account resource.\n \"\"\"\n\n return False\n\n def debit_storno(self, cr, uid, payment_line_id, amount,\n currency_id, storno_retry=True, context=None):\n \"\"\"\n Hook for handling a canceled item of a direct debit order.\n Presumably called from a bank statement import routine.\n\n Decide on the direction that the invoice's workflow needs to take.\n You may optionally return an incomplete reconcile for the caller\n to reconcile the now void payment.\n\n :param payment_line_id: the single payment line id\n :param amount: the (negative) amount debited from the bank account\n :param currency: the bank account's currency *browse object*\n :param boolean storno_retry: whether the storno is considered fatal \\\n or not.\n :return: an incomplete reconcile for the caller to fill\n :rtype: database id of an account.move.reconcile resource.\n \"\"\"\n\n return False\n\n def debit_reconcile(self, cr, uid, payment_line_id, context=None):\n \"\"\"\n Reconcile a debit order's payment line with the the move line\n that it is based on. Called from payment_order.action_sent().\n As the amount is derived directly from the counterpart move line,\n we do not expect a write off. Take partially reconcilions into\n account though.\n\n :param payment_line_id: the single id of the canceled payment line\n \"\"\"\n\n if isinstance(payment_line_id, (list, tuple)):\n payment_line_id = payment_line_id[0]\n reconcile_obj = self.pool.get('account.move.reconcile')\n move_line_obj = self.pool.get('account.move.line')\n payment_line = self.browse(cr, uid, payment_line_id, context=context)\n\n transit_move_line = payment_line.transit_move_line_id\n torec_move_line = payment_line.move_line_id\n\n if (not transit_move_line or not torec_move_line):\n raise orm.except_orm(\n _('Can not reconcile'),\n _('No move line for line %s') % payment_line.name) \n if torec_move_line.reconcile_id: # torec_move_line.reconcile_partial_id:\n raise orm.except_orm(\n _('Error'),\n _('Move line %s has already been reconciled') % \n torec_move_line.name\n )\n if transit_move_line.reconcile_id or transit_move_line.reconcile_partial_id:\n raise orm.except_orm(\n _('Error'),\n _('Move line %s has already been reconciled') % \n transit_move_line.name\n )\n\n def is_zero(total):\n return self.pool.get('res.currency').is_zero(\n cr, uid, transit_move_line.company_id.currency_id, total)\n\n line_ids = [transit_move_line.id, torec_move_line.id]\n if torec_move_line.reconcile_partial_id:\n line_ids = [\n x.id for x in \n torec_move_line.reconcile_partial_id.line_partial_ids\n ] + [transit_move_line.id]\n\n total = move_line_obj.get_balance(cr, uid, line_ids)\n vals = {\n 'type': 'auto',\n 'line_id': is_zero(total) and [(6, 0, line_ids)] or [(6, 0, [])],\n 'line_partial_ids': is_zero(total) and [(6, 0, [])] or [(6, 0, line_ids)],\n }\n\n if torec_move_line.reconcile_partial_id:\n reconcile_obj.write(\n cr, uid, transit_move_line.reconcile_partial_id.id,\n vals, context=context)\n else:\n reconcile_obj.create(\n cr, uid, vals, context=context)\n for line_id in line_ids:\n netsvc.LocalService(\"workflow\").trg_trigger(\n uid, 'account.move.line', line_id, cr)\n\n # If a bank transaction of a storno was first confirmed\n # and now canceled (the invoice is now in state 'debit_denied'\n if torec_move_line.invoice:\n netsvc.LocalService(\"workflow\").trg_validate(\n uid, 'account.invoice', torec_move_line.invoice.id,\n 'undo_debit_denied', cr)\n","sub_path":"account_banking_payment/model/payment_line.py","file_name":"payment_line.py","file_ext":"py","file_size_in_byte":6924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"400538190","text":"# -*- coding: utf-8 -*-\nfrom jogoDaVelha_BIB import *\n\ngrupo = 'Breendo'\njogador = ''\nsimbolo = ''\n \nprint('Bem vindo ao JogodaVelha do grupo {} \\n' .format(grupo)) \njogador = input('Qual seu nome (ou apelido)? ')\nwhile (simbolo != ('X' or 'O')):\n simbolo = input('Qual simbolo deseja ultilizar no jogo? ')\n\n","sub_path":"moodledata/vpl_data/429/usersdata/314/100214/submittedfiles/jogoDaVelha.py","file_name":"jogoDaVelha.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"336010866","text":"#operacoes para troca de linhas e coluna entre matrizes\n#usada para facilitar a movimentacao do cubo\n\ndef linhaParaLinha(matrizOrigem, matrizDestino, linhaOrigem, linhaDestino, inverter):\n linha = matrizOrigem[linhaOrigem][::-1] if inverter else matrizOrigem[linhaOrigem]\n matrizDestino[linhaDestino] = linha\n return matrizDestino\n\ndef colunaParaColuna(matrizOrigem, matrizDestino, colunaOrigem, colunaDestino, inverter):\n arrayColOrigem = [i[colunaOrigem] for i in matrizOrigem]\n if (inverter): \n arrayColOrigem = arrayColOrigem[::-1]\n for i in range(0, len(matrizDestino)):\n matrizDestino[i][colunaDestino] = arrayColOrigem[i]\n return matrizDestino\n\ndef linhaParaColuna(matrizOrigem, matrizDestino, linhaOrigem, colunaDestino, inverter):\n linha = matrizOrigem[linhaOrigem][::-1] if inverter else matrizOrigem[linhaOrigem]\n for i in range(0, len(matrizDestino)):\n matrizDestino[i][colunaDestino] = linha[i]\n return matrizDestino\n\ndef colunaParaLinha(matrizOrigem, matrizDestino, colunaOrigem, linhaDestino, inverter):\n arrayColOrigem = [i[colunaOrigem] for i in matrizOrigem]\n if (inverter): \n arrayColOrigem = arrayColOrigem[::-1]\n matrizDestino[linhaDestino] = arrayColOrigem\n return matrizDestino","sub_path":"util/operacoesMatriz.py","file_name":"operacoesMatriz.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"117828441","text":"## I M P O R T S #############################################################\n\nfrom src.player import Player, PlayerList\n\nfrom nose.tools import raises\n\nclass TestPlayer(object):\n\n def setup(self):\n self.player = Player('Player Name')\n \n\n def test_constructor_valid(self):\n '''Valid input into Player constructor.'''\n Player('Cindy')\n Player('Cindy Loo')\n Player(u'\\ufffdabc')\n\n @raises(TypeError)\n def test_constructor_invalid_no_parameters(self):\n '''Invalid input into player constructor. Missing name parameter. Throws exception.'''\n Player()\n\n def test_add_to_hand_buffer_valid(self):\n '''Valid input into add_to_hand_buffer. Tuples and lists of length 2 that contain only characters.'''\n self.player.add_to_hand_buffer(('a','b'))\n assert [('a','b')] == self.player._hand_buffer\n self.player.add_to_hand_buffer(('c', 'd'))\n assert [('a','b'), ('c','d')] == self.player._hand_buffer\n self.player.add_to_hand_buffer(('e', 'f'))\n assert [('a','b'), ('c','d'), ('e', 'f')] == self.player._hand_buffer\n self.player.add_to_hand_buffer(['g', 'h'])\n assert [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h')] == self.player._hand_buffer\n self.player.add_to_hand_buffer(['i', 'j'])\n assert [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h'), ('i', 'j')] == self.player._hand_buffer\n\n @raises(ValueError)\n def test_add_to_hand_buffer_invalid_none(self):\n '''Invalid input into add_to_hand_buffer. None. Throws exception.'''\n self.player.add_to_hand_buffer(None)\n\n @raises(ValueError)\n def test_add_to_hand_buffer_invalid_zero(self):\n '''Invalid input into add_to_hand_buffer. Zero. Throws exception.'''\n self.player.add_to_hand_buffer(0)\n\n @raises(ValueError)\n def test_add_to_hand_buffer_invalid_incorrect_length_short(self):\n '''Invalid input into add_to_hand_buffer. List/Tuple too short. Throws exception.'''\n self.player.add_to_hand_buffer(['a'])\n\n @raises(ValueError)\n def test_add_to_hand_buffer_invalid_incorrect_length_long(self):\n '''Invalid input into add_to_hand_buffer. List/Tuple too long. Throws exception.'''\n self.player.add_to_hand_buffer(['a', 'b', 'c'])\n\n def test_get_hand_buffer_(self):\n '''Test get_hand_buffer.'''\n self.player._hand_buffer = [('a','b')] \n assert [('a','b')] == self.player.get_hand_buffer()\n self.player._hand_buffer = [('a','b'), ('c','d')]\n assert [('a','b'), ('c','d')] == self.player.get_hand_buffer()\n self.player._hand_buffer = [('a','b'), ('c','d'), ('e', 'f')]\n assert [('a','b'), ('c','d'), ('e', 'f')] == self.player.get_hand_buffer()\n self.player._hand_buffer = [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h')]\n assert [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h')] == self.player.get_hand_buffer()\n self.player._hand_buffer = [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h'), ('i', 'j')]\n assert [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h'), ('i', 'j')] == self.player.get_hand_buffer()\n\n def test_get_hand_buffer_string_(self):\n '''Test get_hand_buffer_string.'''\n self.player._hand_buffer = [('a','b')] \n assert 'ab' == self.player.get_hand_buffer_string()\n self.player._hand_buffer = [('a','b'), ('c','d')]\n assert 'abcd' == self.player.get_hand_buffer_string()\n self.player._hand_buffer = [('a','b'), ('c','d'), ('e', 'f')]\n assert 'abcdef' == self.player.get_hand_buffer_string()\n self.player._hand_buffer = [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h')]\n assert 'abcdefgh' == self.player.get_hand_buffer_string()\n self.player._hand_buffer = [('a','b'), ('c','d'), ('e', 'f'), ('g', 'h'), ('i', 'j')]\n assert 'abcdefghij' == self.player.get_hand_buffer_string()\n\nclass TestPlayerList(object):\n \n def setup(self):\n # construct pointers\n self.player1 = Player('Player1')\n self.player2 = Player('Player2')\n self.player3 = Player('Player3')\n \n # use points to construct playerlist\n self.player_list = PlayerList([self.player1, self.player2, self.player3])\n \n def test_get_uid_player_pairs(self):\n '''Test get_uid_player_pairs. Get play objects and associated ids.'''\n assert [(0, self.player1), (1, self.player2), (2, self.player3)] == [(i,j) for i,j in self.player_list.get_uid_player_pairs()]\n \n def test_get_player_by_uid(self):\n assert self.player1 == self.player_list.get_player_by_uid(0)\n assert self.player2 == self.player_list.get_player_by_uid(1)\n assert self.player3 == self.player_list.get_player_by_uid(2)","sub_path":"test/test_player.py","file_name":"test_player.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"401900691","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\nassert sys.version_info[0] == 3 and sys.version_info[1] >= 5, \"steep-steem requires Python 3.5 or newer\"\n\n# Package meta-data.\nNAME = 'steep-steem'\nVERSION = '0.1.2'\nDESCRIPTION = 'Fork of official python STEEM library.'\nURL = 'https://github.com/Chainers/steep-steem'\nEMAIL = 'steepshot.org@gmail.com'\nAUTHOR = '@steepshot'\n\n\ndef readme_file():\n return 'README.rst' if os.path.exists('README.rst') else 'README.md'\n\n\ndef license_file():\n return 'LICENSE' if os.path.exists('LICENSE') else 'LICENSE.txt'\n\n\nREQUIRED = [\n 'appdirs',\n 'certifi',\n 'ecdsa>=0.13',\n 'funcy',\n 'futures ; python_version < \"3.0.0\"',\n 'future',\n 'langdetect',\n 'prettytable',\n 'pycrypto>=1.9.1',\n 'pylibscrypt>=1.6.1',\n 'scrypt>=0.8.0',\n 'toolz',\n 'ujson',\n 'urllib3',\n 'voluptuous',\n 'w3lib',\n 'websocket-client'\n]\n\nTEST_REQUIRED = [\n 'pep8',\n 'pytest',\n 'pytest-pylint',\n 'pytest-xdist',\n 'pytest-runner',\n 'pytest-pep8',\n 'pytest-cov',\n 'yapf',\n 'autopep8'\n]\n\nBUILD_REQUIRED = [\n 'twine',\n 'pypandoc',\n 'recommonmark'\n 'wheel',\n 'setuptools',\n 'sphinx',\n 'sphinx_rtd_theme'\n]\n\n# The rest you shouldn't have to touch too much :)\n# ------------------------------------------------\n# Except, perhaps the License and Trove Classifiers!\n# If you do change the License, remember to change the Trove Classifier for that!\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\n# Import the README and use it as the long-description.\n# Note: this will only work if 'README.rst' is present in your MANIFEST.in file!\n# with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:\n# long_description = '\\n' + f.read()\n\n\nclass PyTest(TestCommand):\n user_options = [('pytest-args=', 'a', \"Arguments to pass into py.test\")]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n try:\n from multiprocessing import cpu_count\n self.pytest_args = ['-n', str(cpu_count()), '--boxed']\n except (ImportError, NotImplementedError):\n self.pytest_args = ['-n', '1', '--boxed']\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n import pytest\n\n errno = pytest.main(self.pytest_args)\n sys.exit(errno)\n\n\n# Where the magic happens:\nsetup(\n name=NAME,\n version=VERSION,\n description=DESCRIPTION,\n license=open(license_file()).read(),\n keywords=['steem' 'steep-steem', 'steemit', 'cryptocurrency', 'blockchain'],\n long_description=open(readme_file()).read(),\n author=AUTHOR,\n author_email=EMAIL,\n url=URL,\n packages=find_packages(exclude=('tests', 'scripts')),\n install_requires=REQUIRED,\n extras_require={\n 'dev': TEST_REQUIRED + BUILD_REQUIRED,\n 'build': BUILD_REQUIRED,\n 'test': TEST_REQUIRED\n },\n tests_require=TEST_REQUIRED,\n include_package_data=True,\n\n classifiers=[\n # Trove classifiers\n # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English', 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Development Status :: 4 - Beta'\n ],\n # $ setup.py publish support.\n cmdclass={\n 'test': PyTest\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"565982952","text":"import codecs\n\nANGLICIZE_DICT = {'“':'\"', '”':'\"', '’':\"'\"}\n\ndef replaceChars(text, charDict):\n\tfor char in text:\n\t\tyield charDict.get(char, char)\n\ndef anglicize(text, reencode = True):\n\treplaced = ''.join(replaceChars(text, ANGLICIZE_DICT))\n\tif reencode:\n\t\treturn codecs.encode(replaced, 'ascii', errors = 'replace').decode('ascii')\n\telse:\n\t\treturn replaced\n\n\n\ndef parseMatchTypes(text, matchTo):\n\tif isinstance(matchTo, str):\n\t\treturn str(text)\n\telif isinstance(matchTo, bool):\n\t\treturn parseBool(text)\n\telif isinstance(matchTo, int):\n\t\treturn int(text)\n\telif isinstance(matchTo, float):\n\t\treturn float(text)\n\t\t\n\telse:\n\t\traise RuntimeError('Unable to determine type of variable to parse to: {}'.format(matchTo))\n\n\n\ndef parseBool(text):\n\tif not text.strip().lower() in ['true', 'false']:\n\t\traise ValueError('text being parsed to bool \"{}\" is not true or false.'.format(text))\n\treturn text.strip().lower() == 'true'\n\ndef parseBoolNoneSafe(text, default = None):\n\tif text == None:\n\t\treturn False\n\telse:\n\t\treturn parseBool(text)","sub_path":"dirt/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"433579043","text":"#! /usr/local/python\n# -*- coding: UTF-8 -*-\n\"\"\"\nGenera un archivo con los silencios necesarios para el entrenamiento\n\"\"\"\nimport codecs\n\n\ndef execute_script(filler_file):\n\n default_silences = ['', '', '']\n\n f = codecs.open(filler_file, 'w+', encoding='UTF-8')\n for default_silence in default_silences:\n f.write(default_silence + \"\\t\" + \"SIL\\n\")\n\n f.close()\n","sub_path":"openspeechcorpus_cli/cmu_sphinx/generate_filler.py","file_name":"generate_filler.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"132827039","text":"#\n# Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of Intel Corporation nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n\"\"\"\nGEOPM IO - Helper module for parsing/processing report and trace files.\n\"\"\"\n\nimport os\nimport json\nimport re\nimport pandas\nimport numpy\nimport glob\nimport json\nimport sys\nfrom natsort import natsorted\nfrom geopmpy import __version__\n\nclass AppOutput(object):\n \"\"\"The container class for all report and trace related data.\n\n This class holds the relevant objects for parsing and indexing all\n data that is output from GEOPM. This object can be created with a\n report glob string, a trace glob string, or both that will be used\n to search dir_name for the relevant files. If files are found\n their data will be parsed into objects for easy data access.\n Additionally a Pandas DataFrame is constructed containing all of\n the report data and a separate DataFrame containing all of the\n trace data. These DataFrames are indexed based on the version of\n GEOPM found in the files, the profile name, global power budget\n set for the run, the tree and leaf deciders used, and the number\n of times that particular configuration has been seen by the parser\n (i.e. experiment iteration).\n\n Attributes:\n report_glob: The string pattern to use to search for report files.\n trace_glob: The string pattern to use to search for trace files.\n dir_name: The directory path to use when searching for files.\n verbose: A bool to control whether verbose output is printed to stdout.\n\n \"\"\"\n def __init__(self, reports=None, traces=None, dir_name='.', verbose=False):\n self._reports = {}\n self._reports_df = pandas.DataFrame()\n self._traces = {}\n self._traces_df = pandas.DataFrame()\n self._all_paths = []\n self._reports_df_list = []\n self._traces_df_list = []\n self._index_tracker = IndexTracker()\n\n if reports:\n if type(reports) is str:\n report_glob = os.path.join(dir_name, reports)\n report_paths = natsorted(glob.glob(report_glob))\n if len(report_paths) == 0:\n raise RuntimeError('No report files found with pattern {}.'.format(report_glob))\n elif type(reports) is list:\n report_paths = [os.path.join(dir_name, path) for path in reports]\n else:\n raise TypeError('AppOutput: reports must be a list of paths or a glob pattern')\n\n self._all_paths.extend(report_paths)\n\n # Create a dict of : ; Create DF\n files = 0\n filesize = 0\n for rp in report_paths: # Get report count for verbose progress\n filesize += os.stat(rp).st_size\n with open(rp, 'r') as fid:\n for line in fid:\n if re.findall(r'Host:', line):\n files += 1\n\n filesize = '{}KiB'.format(filesize/1024)\n fileno = 1\n for rp in report_paths:\n # Parse the first report\n rr_size = os.stat(rp).st_size\n rr = Report(rp)\n if verbose:\n sys.stdout.write('\\rParsing report {} of {} ({}).. '.format(fileno, files, filesize))\n sys.stdout.flush()\n fileno += 1\n self.add_report_df(rr)\n self._reports[rr.get_node_name()] = rr\n\n # Parse the remaining reports in this file\n while (rr.get_last_offset() != rr_size):\n rr = Report(rp, rr.get_last_offset())\n if rr.get_node_name() is not None:\n self.add_report_df(rr)\n self._reports[rr.get_node_name()] = rr\n if verbose:\n sys.stdout.write('\\rParsing report {} of {} ({})... '.format(fileno, files, filesize))\n sys.stdout.flush()\n fileno += 1\n Report.reset_vars() # If we've reached the end of a report, reset the static vars\n if verbose:\n sys.stdout.write('Done.\\n')\n sys.stdout.flush()\n\n if verbose:\n sys.stdout.write('Creating combined reports DF... ')\n sys.stdout.flush()\n self._reports_df = pandas.concat(self._reports_df_list)\n self._reports_df = self._reports_df.sort_index(ascending=True)\n if verbose:\n sys.stdout.write('Done.\\n')\n sys.stdout.flush()\n\n if traces:\n if type(traces) is str:\n trace_glob = os.path.join(dir_name, traces)\n trace_paths = natsorted(glob.glob(trace_glob))\n if len(trace_paths) == 0:\n raise RuntimeError('No trace files found with pattern {}.'.format(trace_glob))\n elif type(traces) is list:\n trace_paths = [os.path.join(dir_name, path) for path in traces]\n else:\n raise TypeError('AppOutput: traces must be a list of paths or a glob pattern')\n\n self._all_paths.extend(trace_paths)\n self._index_tracker.reset()\n # Create a dict of : \n fileno = 1\n filesize = 0\n for tp in trace_paths: # Get size of all trace files\n filesize += os.stat(tp).st_size\n filesize = '{}MiB'.format(filesize/1024/1024)\n for tp in trace_paths:\n if verbose:\n sys.stdout.write('\\rParsing trace file {} of {} ({})... '.format(fileno, len(trace_paths), filesize))\n sys.stdout.flush()\n fileno += 1\n tt = Trace(tp)\n self._traces[tt.get_node_name()] = tt.get_df() # Basic dict assumes one node per trace\n self.add_trace_df(tt) # Handles multiple traces per node\n if verbose:\n sys.stdout.write('Done.\\n')\n sys.stdout.flush()\n if verbose:\n sys.stdout.write('Creating combined traces DF... ')\n sys.stdout.flush()\n self._traces_df = pandas.concat(self._traces_df_list)\n self._traces_df = self._traces_df.sort_index(ascending=True)\n if verbose:\n sys.stdout.write('Done.\\n')\n sys.stdout.flush()\n\n def remove_files(self):\n \"\"\"Deletes all files currently tracked by this object.\"\"\"\n for ff in self._all_paths:\n try:\n os.remove(ff)\n except OSError:\n pass\n\n def add_report_df(self, rr):\n \"\"\"Adds a report DataFrame to the tracking list.\n\n The report tracking list is used to create the combined\n DataFrame once all reports are parsed.\n\n Args:\n rr: The report object that will be converted to a\n DataFrame, indexed, and added to the tracking list.\n\n \"\"\"\n # Build and index the DF\n rdf = pandas.DataFrame(rr).T.drop('name', 1)\n numeric_cols = ['count', 'energy', 'frequency', 'mpi_runtime', 'runtime']\n rdf[numeric_cols] = rdf[numeric_cols].apply(pandas.to_numeric)\n\n # Add extra index info\n rdf = rdf.set_index(self._index_tracker.get_multiindex(rr))\n self._reports_df_list.append(rdf)\n\n def add_trace_df(self, tt):\n \"\"\"Adds a trace DataFrame to the tracking list.\n\n The report tracking list is used to create the combined\n DataFrame once all reports are parsed.\n\n Args:\n tt: The Trace object used to extract the Trace DataFrame.\n This DataFrame will be indexed and added to the\n tracking list.\n\n \"\"\"\n tdf = tt.get_df()\n tdf = tdf.set_index(self._index_tracker.get_multiindex(tt))\n self._traces_df_list.append(tdf)\n\n def get_node_names(self):\n \"\"\"Returns the names of the nodes detected in the parse report files.\n\n Note that this is only useful for a single experiment's\n dataset. The _reports dictionary is populated from every\n report file that was globbed, so if you have multiple\n iterations of an experiment the last set of reports parsed\n will be contained in this dictionary. Additionally, if\n different nodes were used with different experiment iterations\n then this dictionary will not have consistent data.\n\n If analysis of all of the data is desired, use get_report_df()\n to get a combined DataFrame of all the data.\n\n \"\"\"\n return self._reports.keys()\n\n def get_report(self, node_name):\n \"\"\"Getter for the current Report object in the _reports Dictionary.\n\n Note that this is only useful for a single experiment's\n dataset. The _reports dictionary is populated from every\n report file that was globbed, so if you have multiple\n iterations of an experiment the last set of reports parsed\n will be contained in this dictionary. Additionally, if\n different nodes were used with different experiment iterations\n then this dictionary will not have consistent data.\n\n If analysis of all of the data is desired, use get_report_df()\n to get a combined DataFrame of all the data.\n\n Args:\n node_name: The name of the node to use as a key in the\n _reports Dictionary.\n\n Returns:\n Report: The object for this node_name.\n\n \"\"\"\n return self._reports[node_name]\n\n def get_trace(self, node_name):\n \"\"\"Getter for the current Trace object in the _traces Dictonary.\n\n Note that this is only useful for a single experiment's\n dataset. The _traces dictionary is populated from every trace\n file that was globbed, so if you have multiple iterations of\n an experiment the last set of traces parsed will be contained\n in this dictionary. Additionally, if different nodes were\n used with different experiment iterations then this dictionary\n will not have consistent data.\n\n If analysis of all of the data is desired, use get_trace_df()\n to get a combined DataFrame of all the data.\n\n Args:\n\n node_name: The name of the node to use as a key in the\n _traces Dictionary.\n\n Returns:\n Trace: The object for this node_name.\n\n \"\"\"\n return self._traces[node_name]\n\n def get_report_df(self):\n \"\"\"Getter for the combined DataFrame of all report files parsed.\n\n This DataFrame contains all data parsed, and has a complex\n MultiIndex for accessing the unique data from each individual\n report. For more information on this index, see the\n IndexTracker docstring.\n\n Returns:\n pandas.DataFrame: Contains all parsed data.\n\n \"\"\"\n return self._reports_df\n\n def get_trace_df(self):\n \"\"\"Getter for the combined DataFrame of all trace files parsed.\n\n This DataFrame contains all data parsed, and has a complex\n MultiIndex for accessing the unique data from each individual\n trace. For more information on this index, see the\n IndexTracker docstring.\n\n Returns:\n pandas.DataFrame: Contains all parsed data.\n\n \"\"\"\n return self._traces_df\n\n\nclass IndexTracker(object):\n \"\"\"Tracks and uniquely identifies experiment configurations for\n DataFrame indexing.\n\n This object's purpose is to examine parsed data for reports or\n traces and determine if a particular experiment configuration has\n already been tracked. A user may run the same configuration\n repeatedly in order to prove that results are repeatable and are\n not outliers. Since the same configuration is used many times, it\n must be tracked and counted to ensure that the unique data for\n each run can be extracted later.\n\n The parsed data is used to extract the following fields to build\n the tracking index tuple:\n (, , , , , )\n\n If the tuple not contained in the _run_outputs dict, it is\n inserted with a value of 1. The value is incremented if the tuple\n is currently in the _run_outputs dict. This value is used to\n uniquely identify a particular set of parsed data when the\n MultiIndex is created.\n\n \"\"\"\n def __init__ (self):\n self._run_outputs = {}\n\n def _check_increment(self, run_output):\n \"\"\"Extracts the index tuple from the parsed data and tracks it.\n\n Checks to see if the current run_output has been seen before.\n If so, the count is incremented. Otherwise it is stored as 1.\n\n Args:\n run_output: The Report or Trace object to be tracked.\n\n \"\"\"\n index = (run_output.get_version(), os.path.basename(run_output.get_profile_name()), run_output.get_power_budget(),\n run_output.get_tree_decider(), run_output.get_leaf_decider(), run_output.get_node_name())\n\n if index not in self._run_outputs.keys():\n self._run_outputs[index] = 1\n else:\n self._run_outputs[index] += 1\n\n def _get_base_index(self, run_output):\n \"\"\"Constructs the actual index tuple to be used to construct a\n uniquely-identifying MultiIndex for this data.\n\n Takes a run_output as input, and returns the unique tuple to\n identify this run_output in the DataFrame. Note that this\n method appends the current experiment iteration to the end of\n the returned tuple. E.g.:\n\n >>> self._index_tracker.get_base_index(rr)\n ('0.1.1+dev365gfcda929', 'geopm_test_integration', 170,\n 'static_policy', 'power_balancing', 'mr-fusion2', 1)\n\n Args:\n run_output: The Report or Trace object to produce an index tuple for.\n\n Returns:\n Tuple: This will contain all of the index fields needed to uniquely identify this data (including the\n count of how many times this experiment has been seen.\n\n \"\"\"\n key = (run_output.get_version(), os.path.basename(run_output.get_profile_name()), run_output.get_power_budget(),\n run_output.get_tree_decider(), run_output.get_leaf_decider(), run_output.get_node_name())\n\n return key + (self._run_outputs[key], )\n\n def get_multiindex(self, run_output):\n \"\"\"Returns a MultiIndex from this run_output. Used in DataFrame construction.\n\n This will add the current run_output to the list of tracked\n data, and return a unique muiltiindex tuple to identify this\n data in a DataFrame.\n\n For Report objects, the region name is appended to the end of\n the tuple. For Trace objects, the integer index of the\n DataFrame is appended to the tuple.\n\n Args:\n run_output: The Report or Trace object to produce an index\n tuple for.\n\n Returns:\n pandas.MultiIndex: The unique index to identify this data object.\n\n \"\"\"\n self._check_increment(run_output)\n\n itl = []\n index_names = ['version', 'name', 'power_budget', 'tree_decider', 'leaf_decider', 'node_name', 'iteration']\n\n if type(run_output) is Report:\n index_names.append('region')\n for region in sorted(run_output.keys()): # Pandas sorts the keys when a DF is created\n itl.append(self._get_base_index(run_output) + (region, )) # Append region to the existing tuple\n else: # Trace file index\n index_names.append('index')\n for ii in range(len(run_output.get_df())): # Append the integer index to the DataFrame index\n itl.append(self._get_base_index(run_output) + (ii, ))\n\n mi = pandas.MultiIndex.from_tuples(itl, names=index_names)\n return mi\n\n def reset(self):\n \"\"\"Clears the internal tracking dictionary.\n\n Since only one type of data (reports OR traces) can be tracked\n at once, this is necessary to reset the object's state so a\n new type of data can be tracked.\n\n \"\"\"\n self._run_outputs = {}\n\n\nclass Report(dict):\n \"\"\"An object to parse and encapsulate the data from a report file.\n\n Reports from the GEOPM runtime are currently coalesced into a\n single file from all the nodes used in a particular run. This\n class will process the combined file one line at a time and\n attempt to extract and encapsulate a single report in its member\n variables. The intention is that for a combined file, one would\n first create one of these objects to extract the first report. To\n parse the remaining reports, you will create a new object with the\n same report_path but use the offset from the previous object to\n see where you left off in the parsing process.\n\n Attributes:\n report_path: A string path to a report file to be parsed.\n offset: The starting offset within the report_path file to\n begin looking for a new report.\n\n \"\"\"\n # These variables are intentionally defined outside __init__(). They occur once at the top of a combined report\n # file and are needed for all report contained in the combined file. Defining them this way allows the iinitial\n # value to be shared among all Report files created.\n _version = None\n _name = None\n _mode = None\n _tree_decider = None\n _leaf_decider = None\n _power_budget = None\n\n @staticmethod\n def reset_vars():\n \"\"\"Clears the static variables used in this class. Should be called\n just before parsing a second, third, etc. report file since\n these fields may change.\n\n \"\"\"\n (Report._version, Report._profile_name, Report._mode, Report._tree_decider, Report._leaf_decider, Report._power_budget) = \\\n None, None, None, None, None, None\n\n def __init__(self, report_path, offset=0):\n super(Report, self).__init__()\n self._path = report_path\n self._offset = offset\n self._version = None\n self._profile_name = None\n self._mode = None\n self._tree_decider = None\n self._leaf_decider = None\n self._power_budget = None\n self._total_runtime = None\n self._total_energy = None\n self._total_ignore_runtime = None\n self._total_mpi_runtime = None\n self._node_name = None\n\n found_totals = False\n (region_name, region_id, runtime, energy, frequency, mpi_runtime, count) = None, None, None, None, None, None, None\n float_regex = r'([-+]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'\n\n with open(self._path, 'r') as fid:\n fid.seek(self._offset)\n line = fid.readline()\n while len(line) != 0:\n if self._version is None:\n match = re.search(r'^##### geopm (\\S+) #####$', line)\n if match is not None:\n self._version = match.group(1)\n elif self._profile_name is None:\n match = re.search(r'^Profile: (\\S+)$', line)\n if match is not None:\n self._profile_name = match.group(1)\n elif self._mode is None:\n match = re.search(r'^Policy Mode: (\\S+)$', line)\n if match is not None:\n self._mode = match.group(1)\n elif self._tree_decider is None:\n match = re.search(r'^Tree Decider: (\\S+)$', line)\n if match is not None:\n self._tree_decider = match.group(1)\n elif self._leaf_decider is None:\n match = re.search(r'^Leaf Decider: (\\S+)$', line)\n if match is not None:\n self._leaf_decider = match.group(1)\n elif self._power_budget is None:\n match = re.search(r'^Power Budget: (\\S+)$', line)\n if match is not None:\n self._power_budget = int(match.group(1))\n if self._node_name is None:\n match = re.search(r'^Host: (\\S+)$', line)\n if match is not None:\n self._node_name = match.group(1)\n elif region_name is None:\n match = re.search(r'^Region (\\S+) \\(([0-9]+)\\):', line)\n if match is not None:\n region_name = match.group(1)\n region_id = match.group(2)\n elif runtime is None:\n match = re.search(r'^\\s+runtime.+: ' + float_regex, line)\n if match is not None:\n runtime = float(match.group(1))\n elif energy is None:\n match = re.search(r'^\\s+energy.+: ' + float_regex, line)\n if match is not None:\n energy = float(match.group(1))\n elif frequency is None:\n match = re.search(r'^\\s+frequency.+: ' + float_regex, line)\n if match is not None:\n frequency = float(match.group(1))\n elif mpi_runtime is None:\n match = re.search(r'^\\s+mpi-runtime.+: ' + float_regex, line)\n if match is not None:\n mpi_runtime = float(match.group(1))\n elif count is None:\n match = re.search(r'^\\s+count: ' + float_regex, line)\n if match is not None:\n count = float(match.group(1))\n self[region_name] = Region(region_name, region_id, runtime, energy, frequency, mpi_runtime, count)\n (region_name, region_id, runtime, energy, frequency, mpi_runtime, count) = \\\n None, None, None, None, None, None, None\n if not found_totals:\n match = re.search(r'^Application Totals:$', line)\n if match is not None:\n found_totals = True\n elif self._total_runtime is None:\n match = re.search(r'\\s+runtime.+: ' + float_regex, line)\n if match is not None:\n self._total_runtime = float(match.group(1))\n elif self._total_energy is None:\n match = re.search(r'\\s+energy.+: ' + float_regex, line)\n if match is not None:\n self._total_energy = float(match.group(1))\n elif self._total_mpi_runtime is None:\n match = re.search(r'\\s+mpi-runtime.+: ' + float_regex, line)\n if match is not None:\n self._total_mpi_runtime = float(match.group(1))\n elif self._total_ignore_runtime is None:\n match = re.search(r'\\s+ignore-time.+: ' + float_regex, line)\n if match is not None:\n self._total_ignore_runtime = float(match.group(1))\n break # End of report blob\n\n line = fid.readline()\n self._offset = fid.tell()\n\n # Check static vars to see if they were parsed. if not, use the Report vals\n if self._version is None and Report._version:\n self._version = Report._version\n elif self._version:\n Report._version = self._version\n else:\n raise SyntaxError('Unable to parse version information from report!')\n if self._profile_name is None and Report._profile_name:\n self._profile_name = Report._profile_name\n elif self._profile_name:\n Report._profile_name = self._profile_name\n else:\n raise SyntaxError('Unable to parse name information from report!')\n if self._mode is None and Report._mode:\n self._mode = Report._mode\n elif self._mode:\n Report._mode = self._mode\n else:\n raise SyntaxError('Unable to parse mode information from report!')\n if self._tree_decider is None and Report._tree_decider:\n self._tree_decider = Report._tree_decider\n elif self._tree_decider:\n Report._tree_decider = self._tree_decider\n else:\n raise SyntaxError('Unable to parse tree_decider information from report!')\n if self._leaf_decider is None and Report._leaf_decider:\n self._leaf_decider = Report._leaf_decider\n elif self._leaf_decider:\n Report._leaf_decider = self._leaf_decider\n else:\n raise SyntaxError('Unable to parse leaf_decider information from report!')\n if self._power_budget is None and Report._power_budget:\n self._power_budget = Report._power_budget\n elif self._power_budget:\n Report._power_budget = self._power_budget\n else:\n raise SyntaxError('Unable to parse power_budget information from report!')\n\n if (len(line) != 0 and (region_name is not None or not found_totals or\n None in (self._total_runtime, self._total_energy, self._total_ignore_runtime, self._total_mpi_runtime))):\n raise SyntaxError('Unable to parse report {} before offset {}: '.format(self._path, self._offset))\n\n def get_profile_name(self):\n return self._profile_name\n\n def get_version(self):\n return self._version\n\n def get_path(self):\n return self._path\n\n def get_runtime(self):\n return self._total_runtime\n\n def get_ignore_runtime(self):\n return self._total_ignore_runtime\n\n def get_mpi_runtime(self):\n return self._total_mpi_runtime\n\n def get_energy(self):\n return self._total_energy\n\n def get_node_name(self):\n return self._node_name\n\n def get_last_offset(self):\n return self._offset\n\n def get_mode(self):\n return self._mode\n\n def get_tree_decider(self):\n return self._tree_decider\n\n def get_leaf_decider(self):\n return self._leaf_decider\n\n def get_power_budget(self):\n return self._power_budget\n\n\nclass Region(dict):\n \"\"\"Encapsulates all data related to a region from a report file.\n\n Attributes:\n name: The name of the region.\n rid: The numeric ID of the region.\n runtime: The accumulated time of the region in seconds.\n energy: The accumulated energy from this region in Joules.\n frequency: The average frequency achieved during this region\n in terms of percent of sticker frequency.\n mpi_runtime: The accumulated time in this region executing MPI\n calls in seconds.\n count: The number of times this region has been entered.\n\n \"\"\"\n def __init__(self, name, rid, runtime, energy, frequency, mpi_runtime, count):\n super(Region, self).__init__()\n self['name'] = name\n self['id'] = rid\n self['runtime'] = float(runtime)\n self['energy'] = float(energy)\n self['frequency'] = float(frequency)\n self['mpi_runtime'] = float(mpi_runtime)\n self['count'] = int(count)\n\n def __repr__(self):\n template = \"\"\"\\\n{name} ({rid})\n runtime : {runtime}\n energy : {energy}\n frequency : {frequency}\n mpi-runtime : {mpi_runtime}\n count : {count}\n\"\"\"\n return template.format(name=self['name'],\n rid=self['id'],\n runtime=self['runtime'],\n energy=self['energy'],\n frequency=self['frequency'],\n mpi_runtime=self['mpi_runtime'],\n count=self['count'])\n\n def __str__(self):\n return self.__repr__()\n\n def get_name(self):\n return self['name']\n\n def get_id(self):\n return self['id']\n\n def get_runtime(self):\n return self['runtime']\n\n def get_energy(self):\n return self['energy']\n\n def get_frequency(self):\n return self['frequency']\n\n def get_mpi_runtime(self):\n return self['mpi_runtime']\n\n def get_count(self):\n return self['count']\n\n\nclass Trace(object):\n \"\"\"Creates a pandas DataFrame comprised of the trace file data.\n\n This object will parse both the header and the CSV data in a trace\n file. The header identifies the uniquely-identifying configuration\n for this file which is used for later indexing purposes.\n\n Even though __getattr__() and __getitem__() allow this object to\n effectively be treated like a DataFrame, you must use get_df() if\n you're building a list of DataFrames to pass to pandas.concat().\n Using the raw object in a list and calling concat will cause an\n error.\n\n Attributes:\n trace_path: The path to the trace file to parse.\n\n \"\"\"\n def __init__(self, trace_path):\n self._path = trace_path\n self._df = pandas.read_csv(trace_path, sep='|', comment='#', dtype={'region_id ' : str})\n self._df.columns = list(map(str.strip, self._df[:0])) # Strip whitespace from column names\n self._df['region_id'] = self._df['region_id'].astype(str).map(str.strip) # Strip whitespace from region ID's\n self._version = None\n self._profile_name = None\n self._power_budget = None\n self._tree_decider = None\n self._leaf_decider = None\n self._node_name = None\n self._parse_header(trace_path)\n\n def __repr__(self):\n return self._df.__repr__()\n\n def __str__(self):\n return self.__repr__()\n\n def __getattr__(self, attr):\n \"\"\"Pass through attribute requests to the underlying DataFrame.\n\n This allows for Trace objects to be treated like DataFrames\n for analysis. You can do things like:\n\n >>> tt = geopmpy.io.Trace('170-4-balanced-minife-trace-mr-fusion5')\n >>> tt.keys()\n Index([u'region_id', u'seconds', u'pkg_energy-0', u'dram_energy-0',...\n\n \"\"\"\n return getattr(self._df, attr)\n\n def __getitem__(self, key):\n \"\"\"Pass through item requests to the underlying DataFrame.\n\n This allows standard DataFrame slicing operations to take place.\n\n >>> tt[['region_id', 'seconds', 'pkg_energy-0', 'dram_energy-0']][:5]\n region_id seconds pkg_energy-0 dram_energy-0\n 0 2305843009213693952 0.662906 106012.363770 25631.015519\n 1 2305843009213693952 0.667854 106012.873718 25631.045777\n 2 2305843009213693952 0.672882 106013.411621 25631.075807\n 3 2305843009213693952 0.677869 106013.998108 25631.105882\n 4 2305843009213693952 0.682849 106014.621704 25631.136186\n \"\"\"\n return self._df.__getitem__(key)\n\n def _parse_header(self, trace_path):\n \"\"\"Parses the configuration header out of the top of the trace file.\n\n Args:\n trace_path: The path to the trace file to parse.t\n \"\"\"\n done = False\n out = []\n with open(trace_path) as fid:\n while not done:\n ll = fid.readline()\n if ll.startswith('#'):\n out.append(ll[1:])\n else:\n done = True\n out.insert(0, '{')\n out.append('}')\n json_str = ''.join(out)\n dd = json.loads(json_str)\n try:\n self._version = dd['geopm_version']\n self._profile_name = dd['profile_name']\n self._power_budget = dd['power_budget']\n self._tree_decider = dd['tree_decider']\n self._leaf_decider = dd['leaf_decider']\n self._node_name = dd['node_name']\n except KeyError:\n raise SyntaxError('Trace file header could not be parsed!')\n\n def get_df(self):\n return self._df\n\n def get_version(self):\n return self._version\n\n def get_profile_name(self):\n return self._profile_name\n\n def get_tree_decider(self):\n return self._tree_decider\n\n def get_leaf_decider(self):\n return self._leaf_decider\n\n def get_power_budget(self):\n return self._power_budget\n\n def get_node_name(self):\n return self._node_name\n\n @staticmethod\n def diff_df(trace_df, column_regex, epoch=True):\n \"\"\"Diff the DataFrame.\n\n Since the counters in the trace files are monotonically\n increasing, a diff must be performed to extract the useful\n data.\n\n Args:\n trace_df: The MultiIndexed DataFrame created by the\n AppOutput class.\n column_regex: A string representing the regex search\n pattern for the column names to diff.\n epoch: A flag to set whether or not to focus solely on\n epoch regions.\n\n Returns:\n\n pandas.DataFrame: With the diffed columns specified by\n 'column_regex', and an 'elapsed_time'\n column.\n\n Todo:\n * Should I drop everything before the first epoch if\n 'epoch' is false?\n\n \"\"\"\n epoch_rid = '9223372036854775808'\n\n if epoch:\n tmp_df = trace_df.loc[trace_df['region_id'] == epoch_rid]\n else:\n tmp_df = trace_df\n\n filtered_df = tmp_df.filter(regex=column_regex)\n filtered_df['elapsed_time'] = tmp_df['seconds']\n filtered_df = filtered_df.diff()\n # The following drops all 0's and the negative sample when traversing between 2 trace files.\n filtered_df = filtered_df.loc[(filtered_df > 0).all(axis=1)]\n\n # Reset 'index' to be 0 to the length of the unique trace files\n traces_list = []\n for (version, name, power_budget, tree_decider, leaf_decider, node_name, iteration), df in \\\n filtered_df.groupby(level=['version', 'name', 'power_budget', 'tree_decider', 'leaf_decider',\n 'node_name', 'iteration']):\n df = df.reset_index(level='index')\n df['index'] = pandas.Series(numpy.arange(len(df)), index=df.index)\n df = df.set_index('index', append=True)\n traces_list.append(df)\n\n return pandas.concat(traces_list)\n\n @staticmethod\n def get_median_df(trace_df, column_regex, config):\n \"\"\"Extract the median experiment iteration.\n\n This logic calculates the sum of elapsed times for all of the\n experiment iterations for all nodes in that iteration. It\n then extracts the DataFrame for the iteration that is closest\n to the median. For input DataFrames with a single iteration,\n the single iteration is returned.\n\n Args:\n trace_df: The MultiIndexed DataFrame created by the\n AppOutput class.\n column_regex: A string representing the regex search\n pattern for the column names to diff.\n config: The TraceConfig object being used presently.\n\n Returns:\n pandas.DataFrame: Containing a single experiment iteration.\n\n \"\"\"\n diffed_trace_df = Trace.diff_df(trace_df, column_regex, config.epoch_only)\n\n idx = pandas.IndexSlice\n et_sums = diffed_trace_df.groupby(level=['iteration'])['elapsed_time'].sum()\n median_index = (et_sums - et_sums.median()).abs().sort_values().index[0]\n median_df = diffed_trace_df.loc[idx[:, :, :, :, :, :, median_index],]\n if config.verbose:\n median_df_index = []\n median_df_index.append(median_df.index.get_level_values('version').unique()[0])\n median_df_index.append(median_df.index.get_level_values('name').unique()[0])\n median_df_index.append(median_df.index.get_level_values('power_budget').unique()[0])\n median_df_index.append(median_df.index.get_level_values('tree_decider').unique()[0])\n median_df_index.append(median_df.index.get_level_values('leaf_decider').unique()[0])\n median_df_index.append(median_df.index.get_level_values('iteration').unique()[0])\n sys.stdout.write('Median DF index = ({})...\\n'.format(' '.join(str(s) for s in median_df_index)))\n sys.stdout.flush()\n return median_df\n\n\nclass BenchConf(object):\n \"\"\"The application configuration parameters.\n\n Used to hold the config data for the integration test application.\n This application allows for varying combinations of regions\n (compute, IO, or network bound), complexity, desired execution\n count, and amount of imbalance between nodes during execution.\n\n Attributes:\n path: The output path for this configuration file.\n\n \"\"\"\n def __init__(self, path):\n self._path = path\n self._loop_count = 1;\n self._region = []\n self._big_o = []\n self._hostname = []\n self._imbalance = []\n\n def __repr__(self):\n template = \"\"\"\\\npath : {path}\nregions : {regions}\nbig-o : {big_o}\nloop count: {loops}\nhostnames : {hosts}\nimbalance : {imbalance}\n\"\"\"\n return template.format(path=self._path,\n regions=self._region,\n big_o=self._big_o,\n loops=self._loop_count,\n hosts=self._hostname,\n imbalance=self._imbalance)\n\n def __str__(self):\n return self.__repr__()\n\n def set_loop_count(self, loop_count):\n self._loop_count = loop_count\n\n def append_region(self, name, big_o):\n \"\"\"Appends a region to the internal list.\n\n Args:\n name: The string representation of the region.\n big_o: The desired complexity of the region. This\n affects compute, IO, or network complexity\n depending on the type of region requested.\n\n \"\"\"\n self._region.append(name)\n self._big_o.append(big_o)\n\n def append_imbalance(self, hostname, imbalance):\n \"\"\"Appends imbalance to the config for a particular node.\n\n Args:\n hostname: The name of the node.\n\n imbalance: The amount of imbalance to apply to the node.\n This is specified by a float in the range\n [0,1]. For example, specifying a value of 0.25\n means that this node will spend 25% more time\n executing the work than a node would by\n default. Nodes not specified with imbalance\n configurations will perform normally.\n\n \"\"\"\n self._hostname.append(hostname)\n self._imbalance.append(imbalance)\n\n def get_path(self):\n return self._path\n\n def write(self):\n \"\"\"Write the current config to a file.\"\"\"\n obj = {'loop-count' : self._loop_count,\n 'region' : self._region,\n 'big-o' : self._big_o}\n\n if (self._imbalance and self._hostname):\n obj['imbalance'] = self._imbalance\n obj['hostname'] = self._hostname\n\n with open(self._path, 'w') as fid:\n json.dump(obj, fid)\n\n\nclass CtlConf(object):\n \"\"\"The GEOPM Controller configuration parameters.\n\n This class contains all the parameters necessary to run the GEOPM\n controller with a workload.\n\n Attributes:\n path: The output path for this configuration file.\n mode: The type of mode for the current policy. Set this to\n 'dynamic' in order to utilize arbitrary tree and leaf\n deciders.\n\n options: A dict of the options for this policy mode. When\n using the 'dynamic' mode, this allows you to specify\n the tree and leaf deciders in addition to the power\n budget.\n\n \"\"\"\n def __init__(self, path, mode, options):\n self._path = path\n self._mode = mode\n self._options = options\n\n def __repr__(self):\n template = \"\"\"\\\npath : {path}\nmode : {mode}\noptions : {options}\n\"\"\"\n return template.format(path=self._path,\n mode=self._mode,\n options=self._options)\n\n def __str__(self):\n return self.__repr__()\n\n\n def set_tree_decider(self, decider):\n self._options['tree_decider'] = decider\n\n def set_leaf_decider(self, decider):\n self._options['leaf_decider'] = decider\n\n def set_platform(self, platform):\n self._options['platform'] = platform\n\n def set_power_budget(self, budget):\n self._options['power_budget'] = budget\n\n def get_path(self):\n return self._path\n\n def write(self):\n \"\"\"Write the current config to a file.\"\"\"\n obj = {'mode' : self._mode,\n 'options' : self._options}\n with open(self._path, 'w') as fid:\n json.dump(obj, fid)\n","sub_path":"scripts/geopmpy/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":42601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"564862401","text":"def convert_date_to_std(review_date):\n\n date_and_year = review_date.split(\",\")\n\n month_and_day = date_and_year[0].split(\" \")\n\n month = month_and_day[0].strip()\n\n month_to_day = { \"January\":\"01\", \"February\":\"02\", \"March\":\"03\", \"April\":\"04\", \"May\":\"05\", \"June\":\"06\",\n \"July\":\"07\", \"August\":\"08\", \"September\":\"09\", \"October\":\"10\", \"November\":\"11\", \"December\":\"12\"}\n\n month_number = month_to_day[month]\n\n day = month_and_day[1].strip()\n\n if len(day) == 1:\n day = \"0\" + day\n\n year = date_and_year[1].strip()\n\n date_std = year + \"-\" + month_number + \"-\" + day\n\n return(date_std)\n","sub_path":"convert_date_to_std.py","file_name":"convert_date_to_std.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"205054034","text":"from gbl_const import Result, instrs_keys, instrs_bin, imm_mask, imm_bit_range, reg_pos, Result, flags\nfrom asmblr_tools import *\n\n\ndef process_stringz_pseudo_op(words, state):\n line = ' '.join(words)\n tmp = line.split('\"')\n string = tmp[1]\n\n for char in string:\n ascii_code = ord(char)\n write_to_memory(ascii_code, state.memory, state.pc, state.verbose, '\\n')\n state.pc += 1\n write_to_memory(0, state.memory, state.pc, state.verbose)\n state.pc += 1\n\n#TODO: Handle exceptions\ndef process_br_instr(words, state):\n fl = 0\n if all(c in flags for c in words[0][2:].lower()):\n fl = 0\n if words[0] == 'BR':\n words[0] = 'BRnzp'\n for f in words[0][2:].lower():\n fl |= flags[f]\n return fl\n\n\ndef process_pseudo_ops(words, state):\n if '.ORIG' in words:\n state.orig = state.pc = int('0' + words[1]\n if words[1].startswith('x')\n else words[1], 0)\n return Result.FOUND\n elif '.FILL' in words:\n word = words[words.index('.FILL') + 1]\n #TODO: handle exceptions\n if word.startswith('x') or word.startswith('#'):\n imm_value = get_immediate_value(word)\n write_to_memory(imm_value, state.memory, state.pc, state.verbose, '\\n')\n #TODO: To check if needed (also for .STRINGZ, .BLKW)\n elif valid_label(word):\n set_label_usage_address(word, state.labels_usage_address, state.pc)\n else:\n raise ValueError('Invalid label: %r' % (arg))\n if words[0] != '.FILL':\n state.labels_def_address[words[0]] = state.pc\n state.pc += 1\n return Result.FOUND\n elif '.BLKW' in words:\n if words[0] != '.BLKW':\n state.labels_def_address[words[0]] = state.pc\n word = words[words.index('.BLKW') + 1]\n if word.startswith('x') or word.startswith('#'):\n imm_value = get_immediate_value(word)\n state.pc += imm_value\n else:\n raise ValueError('Invalid label: %r' % (arg))\n return Result.FOUND\n elif '.STRINGZ' in words:\n if words[0] != '.STRINGZ':\n state.labels_def_address[words[0]] = state.pc\n #TODO: handle exceptions (first and last \")\n state.labels_def_address[words[0]] = state.pc\n process_stringz_pseudo_op(words, state)\n return Result.FOUND\n elif '.END' in words:\n return Result.BREAK\n else:\n return Result.NOT_FOUND\n\n\ndef process_instr(words, state):\n instr_bin = 0\n if words[0].startswith('BR'):\n flags = process_br_instr(words, state)\n instr_bin |= flags\n words[0] = 'BR'\n if words[0] in instrs_keys:\n found_instr = words[0]\n instr_bin |= instrs_bin[found_instr]\n args_bin = set_instr_args(words, state.regs,\n state.labels_usage_address,\n state.pc, found_instr)\n instr_bin |= args_bin\n write_to_memory(instr_bin, state.memory, state.pc, state.verbose, '\\n')\n state.pc += 1\n return Result.FOUND\n else:\n return Result.NOT_FOUND\n\ndef process_label(words, state):\n label = words[0]\n instr = words[1]\n if valid_label(label):\n state.labels_def_address[label] = state.pc\n #set_label_usage_address(label, state.labels_usage_address,\n # state.pc, imm_mask[instr], imm_bit_range[instr])\n words.pop(0)\n return process_instr(words, state)\n else:\n raise ValueError('Invalid label: %r' % (word))\n\ndef link_labels_def_to_labels_usage(labels_usage_address,\n labels_def_address, memory):\n for label, usages in labels_usage_address.items():\n for ref, mask, bit in usages:\n current = labels_def_address[label] - ref - 1\n memory[ref] |= mask & current\n\n\n","sub_path":"asmblr.py","file_name":"asmblr.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"415158411","text":"#!/usr/bin/env python3\n\nimport sys\nimport argparse\nfrom ldif3 import LDIFParser\nfrom pprint import pprint\nimport pandas as pd\nfrom pymongo import MongoClient\n\n\ndef insertLineToDB(post, collection):\n post_id = collection.update_one(post, { '$set' : post }, upsert=True)\n\ndef purgeUserBase(volname, collection):\n print (\"Delete collection for\",volname)\n result = collection.delete_many()\n\ndef main(self):\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-f\",\"--ldiffile\", type=str, dest='ldiffile', help=\"LDIF File\")\n parser.add_argument(\"-b\",\"--database\", type=str, dest='dbname', help=\"DB Name\")\n parser.add_argument(\"--inject\", help=\"Inject Data\", action=\"store_true\")\n parser.add_argument(\"--export\", help=\"Export Data\", action=\"store_true\")\n parser.add_argument(\"--user\", help=\"User Import\", action=\"store_true\")\n parser.add_argument(\"--group\", help=\"Group Import\", action=\"store_true\")\n\n\n if len(sys.argv)==1:\n parser.print_help()\n sys.exit(1)\n args = parser.parse_args()\n\n\n ### Connect to Database\n client = MongoClient()\n db = client[args.dbname]\n UserCollection = db['Users']\n GroupCollection = db['Groups']\n\n if (args.inject):\n if (args.user):\n ldifparser = LDIFParser(open(args.ldiffile, 'rb'))\n user = {}\n for dn, entry in ldifparser.parse():\n #print ('got entry record : %s' % dn)\n #print (dn)\n cn = \"\"\n mail = \"\"\n uid = \"\"\n\n for element in entry.items():\n ### Get the CN\n if (element[0] in \"cn\"):\n cn = element[1][0]\n\n ### Get the mail\n if (element[0] in \"mail\"):\n mail = element[1][0]\n\n ### Get the UID\n if (element[0] in \"uid\"):\n uid = element[1][0]\n\n if (cn != mail):\n #print ({ 'cn' : cn, 'mail' : mail, 'uid' : uid})\n insertLineToDB({ 'dn' : dn, 'cn' : cn, 'mail' : mail, 'uid' : uid}, UserCollection)\n else:\n print (\"Found \"+cn+\" in \"+mail+\"for :\"+dn)\n\n if (args.group):\n ldifparser = LDIFParser(open(args.ldiffile, 'rb'))\n for dn, entry in ldifparser.parse():\n #print ('got entry record : %s' % dn)\n cn = \"\"\n member = []\n\n\n for element in entry.items():\n ### Get the CN\n if (element[0] in \"cn\"):\n cn = element[1][0]\n\n ### Get the mail\n if (element[0] in \"member\"):\n# print (element[1])\n member.append(element[1])\n\n print ({ 'cn' : cn, 'member' : member})\n insertLineToDB({ 'dn' : dn, 'cn' : cn, 'member' : member}, GroupCollection)\n\n\n #insertLineToDB(user, UserCollection)\n\n if (args.export):\n pd.DataFrame(list(UserCollection.find())).to_csv(\"userexport.csv\")\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"N2N Migration Toolkit/LDIFToMongo.py","file_name":"LDIFToMongo.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"117381754","text":"import astropy.io.fits as pyfits\nimport numpy as np\nimport os\n\ndef read_simput_catalog(simput_file):\n r\"\"\"\n Read events from a SIMPUT catalog. This will read all of the sources\n in the catalog.\n\n Parameters\n ----------\n simput_file : string\n The SIMPUT file to read from.\n\n Returns\n -------\n 1. Lists of dicts of NumPy arrays of the positions \n and energies of the events from the sources.\n 2. NumPy arrays of the parameters of the sources.\n \"\"\"\n events = []\n parameters = {}\n simput_dir = os.path.split(os.path.abspath(simput_file))[0]\n f_simput = pyfits.open(simput_file)\n parameters[\"flux\"] = f_simput[\"src_cat\"].data[\"flux\"]\n parameters[\"emin\"] = f_simput[\"src_cat\"].data[\"e_min\"]\n parameters[\"emax\"] = f_simput[\"src_cat\"].data[\"e_max\"]\n phlist_files = [file.split(\"[\")[0] for file in \n f_simput[\"src_cat\"].data[\"spectrum\"]]\n f_simput.close()\n for phlist_file in phlist_files:\n f_phlist = pyfits.open(os.path.join(simput_dir, phlist_file))\n evt = {}\n for key in [\"ra\", \"dec\", \"energy\"]:\n evt[key] = f_phlist[\"phlist\"].data[key]\n f_phlist.close()\n events.append(evt)\n return events, parameters\n\ndef write_photon_list(simput_prefix, phlist_prefix, flux, ra, dec, energy,\n append=False, clobber=False):\n r\"\"\"\n Write events to a new SIMPUT photon list. It can be associated\n with a new or existing SIMPUT catalog. \n\n Parameters\n ----------\n simput_prefix : string\n The filename prefix for the SIMPUT file.\n phlist_prefix : string\n The filename prefix for the photon list file.\n flux : float\n The energy flux of all the photons, in units of erg/cm**2/s.\n ra : NumPy array\n The right ascension of the photons, in degrees.\n dec : NumPy array\n The declination of the photons, in degrees.\n energy : NumPy array or array-like thing\n The energy of the photons, in keV.\n append : boolean, optional\n If True, append a new source an existing SIMPUT catalog. \n clobber : boolean, optional\n Set to True to overwrite previous files.\n \"\"\"\n # Make sure these are arrays\n energy = np.array(energy)\n ra = np.array(ra)\n dec = np.array(dec)\n if hasattr(flux, \"value\"):\n flux = flux.value\n\n emin = energy.min()\n emax = energy.max()\n\n col1 = pyfits.Column(name='ENERGY', format='E', array=energy)\n col2 = pyfits.Column(name='RA', format='D', array=ra)\n col3 = pyfits.Column(name='DEC', format='D', array=dec)\n cols = [col1, col2, col3]\n\n coldefs = pyfits.ColDefs(cols)\n\n tbhdu = pyfits.BinTableHDU.from_columns(coldefs)\n tbhdu.update_ext_name(\"PHLIST\")\n\n tbhdu.header[\"HDUCLASS\"] = \"HEASARC/SIMPUT\"\n tbhdu.header[\"HDUCLAS1\"] = \"PHOTONS\"\n tbhdu.header[\"HDUVERS\"] = \"1.1.0\"\n tbhdu.header[\"EXTVER\"] = 1\n tbhdu.header[\"REFRA\"] = 0.0\n tbhdu.header[\"REFDEC\"] = 0.0\n tbhdu.header[\"TUNIT1\"] = \"keV\"\n tbhdu.header[\"TUNIT2\"] = \"deg\"\n tbhdu.header[\"TUNIT3\"] = \"deg\"\n\n phfile = phlist_prefix+\"_phlist.fits\"\n\n tbhdu.writeto(phfile, clobber=clobber)\n\n simputfile = simput_prefix+\"_simput.fits\"\n\n ph_ext = phfile+\"[PHLIST,1]\"\n\n if append:\n f = pyfits.open(simputfile)\n num_sources = f[\"SRC_CAT\"].data[\"SRC_ID\"].size\n id = num_sources + 1\n spec_files = f[\"SRC_CAT\"].data[\"SPECTRUM\"][:]\n img_files = f[\"SRC_CAT\"].data[\"IMAGE\"][:]\n if ph_ext in spec_files or ph_ext in img_files:\n raise IOError(\"This SIMPUT catalog already has an entry for file %s!\" % phfile)\n src_id = np.append(f[\"SRC_CAT\"].data[\"SRC_ID\"][:], id)\n ra = np.append(f[\"SRC_CAT\"].data[\"RA\"][:], 0.0)\n dec = np.append(f[\"SRC_CAT\"].data[\"DEC\"][:], 0.0)\n e_min = np.append(f[\"SRC_CAT\"].data[\"E_MIN\"][:], emin)\n e_max = np.append(f[\"SRC_CAT\"].data[\"E_MAX\"][:], emax)\n flx = np.append(f[\"SRC_CAT\"].data[\"FLUX\"][:], flux)\n spectrum = np.append(spec_files, ph_ext)\n image = np.append(img_files, ph_ext)\n src_name = np.append(f[\"SRC_CAT\"].data[\"SRC_NAME\"][:], \"soxs_src_%d\" % id)\n f.close()\n else:\n src_id = np.array([1]).astype(\"int32\")\n ra = np.array([0.0])\n dec = np.array([0.0])\n e_min = np.array([emin])\n e_max = np.array([emax])\n flx = np.array([flux])\n spectrum = np.array([ph_ext])\n image = spectrum\n src_name = np.array([\"soxs_src_1\"])\n\n col1 = pyfits.Column(name='SRC_ID', format='J', array=src_id)\n col2 = pyfits.Column(name='RA', format='D', array=ra)\n col3 = pyfits.Column(name='DEC', format='D', array=dec)\n col4 = pyfits.Column(name='E_MIN', format='D', array=e_min)\n col5 = pyfits.Column(name='E_MAX', format='D', array=e_max)\n col6 = pyfits.Column(name='FLUX', format='D', array=flx)\n col7 = pyfits.Column(name='SPECTRUM', format='80A', array=spectrum)\n col8 = pyfits.Column(name='IMAGE', format='80A', array=image)\n col9 = pyfits.Column(name='SRC_NAME', format='80A', array=src_name)\n\n coldefs = pyfits.ColDefs([col1, col2, col3, col4, col5, col6, col7, col8, col9])\n\n wrhdu = pyfits.BinTableHDU.from_columns(coldefs)\n wrhdu.update_ext_name(\"SRC_CAT\")\n\n wrhdu.header[\"HDUCLASS\"] = \"HEASARC\"\n wrhdu.header[\"HDUCLAS1\"] = \"SIMPUT\"\n wrhdu.header[\"HDUCLAS2\"] = \"SRC_CAT\"\n wrhdu.header[\"HDUVERS\"] = \"1.1.0\"\n wrhdu.header[\"RADECSYS\"] = \"FK5\"\n wrhdu.header[\"EQUINOX\"] = 2000.0\n wrhdu.header[\"TUNIT2\"] = \"deg\"\n wrhdu.header[\"TUNIT3\"] = \"deg\"\n wrhdu.header[\"TUNIT4\"] = \"keV\"\n wrhdu.header[\"TUNIT5\"] = \"keV\"\n wrhdu.header[\"TUNIT6\"] = \"erg/s/cm**2\"\n\n wrhdu.writeto(simputfile, clobber=(clobber or append))\n","sub_path":"soxs/simput.py","file_name":"simput.py","file_ext":"py","file_size_in_byte":5746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"81374183","text":"import os\r\nimport cv2\r\nfrom tqdm import tqdm\r\n\r\ndef crowd_convert():\r\n root = r'/home/yolov4-pytorch1/object-detection-crowdai'\r\n #out = r'D:\\ubuntu_share\\yolov4-pytorch\\output_img'\r\n labels = os.path.join(root, 'labels.csv')\r\n fr = open(labels, 'r', newline='')\r\n labels_dict = {}\r\n num1, num2, num3 = 0, 0, 0\r\n newlines = []\r\n for i,line in enumerate(fr):\r\n if i == 0:\r\n continue\r\n info = line.strip().split(',')\r\n name = root + '/' + info[4]\r\n # x1 = str(float(info[0])*608/1920)\r\n # y1 = str(float(info[1])*608/1200)\r\n # x2 = str(float(info[2])*608/1920)\r\n # y2 = str(float(info[3])*608/1200)\r\n\r\n x1 = info[0]\r\n y1 = info[1]\r\n x2 = info[2]\r\n y2 = info[3]\r\n cls = 0\r\n if info[5] == 'Car':\r\n cls = 0\r\n elif info[5] == 'Truck':\r\n cls = 0\r\n elif info[5] == 'Pedestrian':\r\n cls = 1\r\n if name in labels_dict:\r\n labels_dict[name].append(','.join([x1,y1,x2,y2,str(cls)]))\r\n else:\r\n labels_dict[name] = [name, ','.join([x1,y1,x2,y2,str(cls)])]\r\n for lab in labels_dict:\r\n newline = ' '.join(labels_dict[lab])+'\\n'\r\n newlines.append(newline)\r\n\r\n fw = open('/home/yolov4-pytorch1/work_dir/my_train3.txt', 'w')\r\n fw.writelines(newlines)\r\n\r\n# def resize_image():\r\n# root = r'D:\\ubuntu_share\\yolov4-pytorch\\object-detection-crowdai'\r\n# out = r'output_img'\r\n# os.makedirs(out, exist_ok=True)\r\n# img_lis = os.listdir(root)\r\n# for im in tqdm(img_lis):\r\n# im_path = os.path.join(root, im)\r\n# x = cv2.imread(im_path)\r\n# x = cv2.resize(x, (608,608))\r\n# cv2.imwrite(os.path.join(out, im), x)\r\n#\r\n#\r\n# def highway_convert():\r\n# output = 'train_new.txt'\r\n# root = r'/data/yolo4_dataset_20200715'\r\n# img_dir = os.path.join(root,'images')\r\n# images = os.listdir(img_dir)\r\n# lines = []\r\n# for img in tqdm(images):\r\n# new_line = []\r\n# name = os.path.join(img_dir, img)\r\n# txt_name = name.replace('images', 'labels').replace('.jpg', '.txt')\r\n# fr = open(txt_name, 'r').readlines()\r\n# new_line.append(name)\r\n# img = cv2.imread(name)\r\n# print(img.shape)\r\n# h,w,_ = img.shape\r\n# h = float(h)\r\n# w = float(w)\r\n# for lin in fr:\r\n# data = lin.strip().split(' ')\r\n# if int(data[0]) != 0:\r\n# continue\r\n#\r\n# cx,cy,cw,ch = float(data[1])*w,float(data[2])*h,float(data[3])*w,float(data[4])*h\r\n#\r\n# x1 = str((cx-cw/2))\r\n# y1 = str((cy-ch/2))\r\n# x2 = str((cx+cw/2))\r\n# y2 = str((cy+ch/2))\r\n# print(x1,y1,x2,y2)\r\n# info = [x1,y1,x2,y2, data[0]]\r\n# info = ','.join(info)\r\n# # print(info)\r\n# new_line.append(info)\r\n# #print(new_lines)\r\n# new_line = ' '.join(new_line) + '\\n'\r\n# lines.append(new_line)\r\n# print(new_line)\r\n# with open('train_new.txt', 'w') as fw:\r\n# fw.writelines(lines)\r\n\r\n\r\nif __name__ == '__main__':\r\n crowd_convert()\r\n\r\n","sub_path":"data_make.py","file_name":"data_make.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"191185848","text":"import os\nimport subprocess\nimport torch\nfrom collections import defaultdict\nimport numpy as np\nimport config as cfg\nimport assert_src.features.audio as F\nfrom assert_src.model import E2E\nfrom assert_src.data_reader.dataset_v1 import SpoofDatsetFilebase\nimport assert_src.src.eval_metrics as metr\n\n\nuse_cuda = torch.cuda.is_available() # use cpu\ndevice = torch.device(\"cuda\" if use_cuda else \"cpu\")\nkwargs = {'num_workers': 2, 'pin_memory': True} if use_cuda else {}\n\n# create model\nmodel = E2E(**cfg.model_params).to(device)\nnum_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\nprint('===> Model total parameter: {}'.format(num_params))\n\nif os.path.isfile(cfg.model_file):\n print(\"===> loading checkpoint '{}'\".format(cfg.model_file))\n checkpoint = torch.load(cfg.model_file, map_location=lambda storage, loc: storage) # load for cpu\n model.load_state_dict(checkpoint['state_dict'], strict=False)\n print(\"===> loaded checkpoint '{}' (epoch {})\"\n .format(cfg.model_file, checkpoint['epoch']))\nelse:\n print(\"===> no checkpoint found at '{}'\".format(cfg.model_file))\n exit()\n\n\ndef detect_spoofing(file_name):\n # transform to wav\n fid = os.path.splitext(file_name)[0]\n wav_name = '{}.wav'.format(fid)\n subprocess.call(['/home/vano/ffmpeg-4.2.1-amd64-static/ffmpeg', '-i', file_name, '-ar', '16000', '-ac', '1', wav_name])\n #subprocess.call(['sox', file_name, '-r', '16000', wav_name])\n print('[INFO] Transformed to wav: %s' % wav_name)\n\n # extract features\n feat_type = cfg.feat_params['type']\n extractor = F.prepare_extractor(feats=feat_type, params=cfg.feat_params)\n x, fs = F.load_sound_file(wav_name)\n assert (fs == 16000)\n feat = extractor.extract(x, fs)\n feat_file = '{}.npy'.format(fid)\n np.save(feat_file, np.squeeze(feat))\n print('[INFO] Features are extracted: %s' % feat_file)\n # forward network\n res = _forward_pass(feat_file, cfg.model_params)\n scores = res[feat_file]\n return 'bonafide: %.4f\\nspoof: %.4f' % (scores[0], scores[1])\n\n\ndef _forward_pass(feat_file, model_params):\n \"\"\" forward pass dev and eval data to trained model \"\"\"\n # TODO load model\n # use_cuda = torch.cuda.is_available() # use cpu\n # device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n # kwargs = {'num_workers': 2, 'pin_memory': True} if use_cuda else {}\n #\n # # create model\n # model = E2E(**model_params).to(device)\n # num_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n # print('===> Model total parameter: {}'.format(num_params))\n #\n # if os.path.isfile(cfg.model_file):\n # print(\"===> loading checkpoint '{}'\".format(cfg.model_file))\n # checkpoint = torch.load(cfg.model_file, map_location=lambda storage, loc: storage) # load for cpu\n # model.load_state_dict(checkpoint['state_dict'], strict=False)\n # print(\"===> loaded checkpoint '{}' (epoch {})\"\n # .format(cfg.model_file, checkpoint['epoch']))\n # else:\n # print(\"===> no checkpoint found at '{}'\".format(cfg.model_file))\n # exit()\n ###########################################\n # Data loading\n val_data = SpoofDatsetFilebase([feat_file])\n val_loader = torch.utils.data.DataLoader(val_data,\n batch_size=cfg.test_batch_size,\n shuffle=False, **kwargs)\n # forward pass\n return _prediction(val_loader, model, device)\n\n\ndef _prediction(val_loader, model, device):\n # switch to evaluate mode\n utt2scores = defaultdict(list)\n model.eval()\n\n with torch.no_grad():\n for i, (utt_id, input) in enumerate(val_loader):\n input = input[0].to(device)\n # compute output\n output = model(input)\n print(output)\n # score = output[:, 0] # use log-probability of the bonafide class for scoring\n\n # for index, utt_id in enumerate(utt_id):\n # utt2scores[utt_id[0]].append(output[index].numpy())\n utt2scores[utt_id[0]] = np.mean(output.cpu().numpy(), axis=0)\n\n # for index, utt_id in enumerate(val_loader.file_list):\n # score_list = utt2scores[utt_id]\n # avg_score = np.mean(score_list)\n # utt2scores[utt_id] = avg_score\n\n return utt2scores\n\nif __name__ == '__main__':\n\n file_names = ['bonafide2020_01_06_13_04_54.wav', 'spoof2020_01_06_13_24_13.wav',\n 'bonafide2020_01_06_13_08_37.wav', 'spoof2020_01_06_13_26_08.wav',\n 'bonafide2020_01_06_13_10_59.wav', 'spoof2020_01_06_13_27_24.wav',\n 'bonafide2020_01_06_13_17_31.wav', 'spoof2020_01_06_13_28_45.wav',\n 'bonafide2020_01_06_13_22_11.wav', 'spoof2020_01_06_13_30_18.wav']\n fdir = 'test_audio'\n y_pred = []\n y_true = []\n for fn in file_names:\n fid = os.path.splitext(fn)[0]\n wav_name = fdir + '/' + fn\n # extract features\n feat_type = cfg.feat_params['type']\n extractor = F.prepare_extractor(feats=feat_type, params=cfg.feat_params)\n x, fs = F.load_sound_file(wav_name)\n assert (fs == 16000)\n feat = extractor.extract(x, fs)\n feat_file = '{}.npy'.format(fid)\n np.save(feat_file, np.squeeze(feat))\n print('[INFO] Features are extracted: %s' % feat_file)\n # forward network\n res = _forward_pass(feat_file, cfg.model_params)\n scores = res[feat_file]\n print('bonafide: %.4f\\nspoof: %.4f' % (scores[0], scores[1]))\n \n y = 0 if 'bonafide' in fn else 1\n y_true.append(y)\n y_pred.append(scores[1])\n # TODO test: for bonafida scores 40%, for spoof 100%\n print('EER: %.4f' % metr.eer(y_true, y_pred))\n","sub_path":"tele_bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"635926087","text":"from django.shortcuts import render, get_object_or_404, redirect\n\nfrom store.forms import ProductForm\nfrom store.models import Store\n\n\ndef index_view(request):\n products = Store.objects.filter(rest__gt=0).order_by('category', 'name')\n return render(request, 'index.html', context={\n 'products': products\n })\n\n\ndef product_view(request, pk):\n products = get_object_or_404(Store, pk=pk)\n return render(request, 'product.html', context={\n 'products': products\n })\n\n\ndef product_create(request):\n if request.method == 'GET':\n product = ProductForm()\n return render(request, 'create.html', context={\n 'product': product\n })\n elif request.method == 'POST':\n product = ProductForm(data=request.POST)\n if product.is_valid():\n products = Store.objects.create(name=product.cleaned_data['name'],\n description=product.cleaned_data['description'],\n category=product.cleaned_data['category'],\n rest=product.cleaned_data['rest'],\n cost=product.cleaned_data['cost'])\n return redirect('product_view', pk=products.pk)\n else:\n return render(request, 'create.html', context={'product': product})\n\n\ndef product_update(request, pk):\n forms = get_object_or_404(Store, pk=pk)\n products = get_object_or_404(Store, pk=pk)\n\n if request.method == 'GET':\n product = ProductForm(data={'name': products.name,\n 'description': products.description,\n 'category': products.category,\n 'rest': products.rest,\n 'cost': products.cost})\n return render(request, 'update.html', context={\n 'products': products,\n 'product': product})\n\n elif request.method == 'POST':\n product = ProductForm(data=request.POST)\n\n if product.is_valid():\n products.name = product.cleaned_data['name']\n products.description = product.cleaned_data['description']\n products.category = product.cleaned_data['category']\n products.rest = product.cleaned_data['rest']\n products.cost = product.cleaned_data['cost']\n products.save()\n return redirect('product_view', pk=products.pk)\n else:\n return render(request, 'update.html', context={\n 'product': product,\n 'products': products\n })\n\n\ndef product_delete(request, pk):\n product = get_object_or_404(Store, pk=pk)\n product.delete()\n return redirect('index')\n\n","sub_path":"lab_src/store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"408944323","text":"# Python\nimport os\nimport sys\n\n# Django\nfrom django.conf import global_settings\n\n# Update this module's local settings from the global settings module.\nthis_module = sys.modules[__name__]\nfor setting in dir(global_settings):\n if setting == setting.upper():\n setattr(this_module, setting, getattr(global_settings, setting))\n\n# Absolute path to the directory containing this Django project.\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(PROJECT_ROOT, 'test_project.sqlite3'),\n }\n}\n\nSITE_ID = 1\n\nSTATIC_URL = '/static/'\n\nMIDDLEWARE_CLASSES += (\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'devserver.middleware.DevServerMiddleware',\n)\n\nTEMPLATE_DIRS = (\n #os.path.join(PROJECT_ROOT, 'templates'),\n)\n\nROOT_URLCONF = 'test_project.urls'\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'debug_toolbar',\n 'devserver',\n 'django_extensions',\n 'south',\n 'sortedm2m',\n 'fortunecookie',\n 'datatables',\n 'test_app',\n)\n\nINTERNAL_IPS = ('127.0.0.1',)\n\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n}\n\nDEVSERVER_DEFAULT_ADDR = '127.0.0.1'\nDEVSERVER_DEFAULT_PORT = '8044'\n\nSECRET_KEY = 'gkwl+r%+^4==^(dnnkv8o#&h&bn=x43*k$h7_e7p+l0w&eba)m'\n","sub_path":"test_project/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"333805522","text":"import re\n\nfrom livecli.plugin import Plugin\n\n__livecli_docs__ = {\n \"domains\": [\n \"speedrunslive.com\",\n ],\n \"geo_blocked\": [],\n \"notes\": \"\",\n \"live\": True,\n \"vod\": False,\n \"last_update\": \"2014-06-06\",\n}\n\nTWITCH_URL_FORMAT = \"http://www.twitch.tv/{0}\"\n\n_url_re = re.compile(r\"http://(?:www\\.)?speedrunslive.com/#!/(?P\\w+)\")\n\n\nclass SpeedRunsLive(Plugin):\n @classmethod\n def can_handle_url(self, url):\n return _url_re.match(url)\n\n def _get_streams(self):\n match = _url_re.match(self.url)\n username = match.group(\"user\")\n url = TWITCH_URL_FORMAT.format(username)\n return self.session.streams(url)\n\n\n__plugin__ = SpeedRunsLive\n","sub_path":"src/livecli/plugins/speedrunslive.py","file_name":"speedrunslive.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"192753669","text":"from django.conf.urls import url\nfrom .views import *\n\n\nurlpatterns = [\n url(r'^show_request/$', show_request_views),\n url(r'^show_get/$', show_get_views),\n url(r'^login/$', login_views, name='login'),\n url(r'^register/$', register_views),\n]\n","sub_path":"my_project/day7/index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"53306015","text":"x: int = 0\ny: int = 0\nmove: int = 0\ncheckerBoard: int = [[0 for i in range(8)] for j in range(8)]\n\nx = int(input(\"Indiquez une ligne où vous positionner : \"))\ny = int(input(\"Indiquez une colonne où vous positionner : \"))\n\ncheckerBoard[x][y] = 1\n\nif move == 0 and (x < 0 or x > 8) and (y < 0 or y > 8):\n print(\"Position invalide\")\nelse:\n while True:\n move = int(input(\"Indiquez le mouvement (0 => haut-gauche, 1 => haut-droite, 2 => bas-gauche, 3 => bas-droite) : \"))\n\n # Validation of move\n if move == 0 and ( (x-1 <= 8 and x-1 >= 0) and (y-1 >= 0 and y-1 <= 8) ):\n checkerBoard[x][y] = 0\n x -= 1\n y -= 1\n checkerBoard[x][y] = 1\n elif move == 1 and ( (x-1 <= 8 and x-1 >= 0) and (y+1 <= 8 and y+1 >= 0) ):\n checkerBoard[x][y] = 0\n x -= 1\n y += 1\n checkerBoard[x][y] = 1\n elif move == 2 and ( (x+1 >= 0 and x+1 <= 8) and (y-1 >= 0 and y-1 <= 8) ):\n checkerBoard[x][y] = 0\n x += 1\n y -= 1\n checkerBoard[x][y] = 1\n elif move == 3 and ( (x+1 >= 0 and x+1 <= 8) and (y+1 <= 8 and y+1 >= 0) ):\n checkerBoard[x][y] = 0\n x += 1\n y += 1\n checkerBoard[x][y] = 1\n else:\n print(\"Déplacement impossible\")\n break\n\n # Draw checkerboard\n for i in range(0, 8):\n for j in range(0, 8):\n if checkerBoard[i][j] == 0:\n if j < 7:\n print(\"O\", end = '')\n else:\n print(\"O\")\n if checkerBoard[i][j] == 1:\n if j < 7:\n print(\"X\", end = '')\n else:\n print(\"X\")\n","sub_path":"Scripts/8.7.py","file_name":"8.7.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"556164479","text":"\"\"\"\nSample user module.\n\nGets stats for a username of a user or organization.\n\"\"\"\nfrom etc import config\nfrom lib.connection import CONN\n\n\ndef print_details(user):\n details = {\n 'Username': f\"@{user.login}\",\n 'Email': user.email if user.email else \"N/A\",\n 'Name': user.name if user.name else \"N/A\",\n 'Location': user.location if user.location else \"N/A\",\n 'Company': user.company if user.company else \"N/A\",\n 'Created At': str(user.created_at.date()),\n }\n for k, v in details.items():\n print(f\"{k:20}: {v}\")\n\n # Orgs seems to be created, not belong to.\n counts = {\n 'Repos': list(user.get_repos()),\n 'Orgs': list(user.get_orgs()),\n 'Events': list(user.get_events()),\n 'Watched': list(user.get_watched()),\n 'Starred': list(user.get_starred()),\n }\n for k, v in counts.items():\n print(f\"{k:7}: {len(v):,d}\")\n\n\ndef main():\n login = config.REPO_OWNER\n user = CONN.get_user(login)\n print_details(user)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"aggregit/sample/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"308072478","text":"from pyecharts import Bar, HeatMap,Timeline, Page, Style,Line\nfrom app.charts.constants import HEIGHT, WIDTH\nimport pandas as pd\nfrom collections import defaultdict\n\ndef create_charts():\n page = Page()\n\n style = Style(\n width=WIDTH, height=HEIGHT\n )\n df = pd.read_csv('./data_cleaned.csv')\n df['CREATE_TIME'] = pd.to_datetime(df['CREATE_TIME'])\n df['MONTH'] = 0\n months = []\n for i in df.CREATE_TIME:\n month = i.strftime(\"%Y-%m\")\n months.append(month)\n df.MONTH = months\n\n EVENT_SRC_NAME = df.EVENT_SRC_NAME.value_counts()\n chart = Bar(\"投诉渠道种类\", **style.init_style)\n chart.add(\"\", EVENT_SRC_NAME.index, EVENT_SRC_NAME.values,\n mark_point=[\"max\", \"min\"],\n mark_line=[\"average\"], is_stack=True)\n page.add(chart)\n\n chart = Timeline(is_auto_play=True, timeline_bottom=0,\n width=WIDTH, height=HEIGHT)\n for month, group in df.groupby('MONTH'):\n EVENT_SRC_NAME = group.EVENT_SRC_NAME.value_counts()\n chart_1 = Bar(\"投诉渠道事件数\", **style.init_style)\n chart_1.add(\"\", EVENT_SRC_NAME.index, EVENT_SRC_NAME.values,\n mark_point=[\"max\", \"min\"],\n mark_line=[\"average\"], is_stack=True)\n chart.add(chart_1,month)\n page.add(chart)\n\n chart = Timeline(is_auto_play=True, timeline_bottom=0,\n width=WIDTH, height=HEIGHT)\n for name, c in df.groupby('EVENT_SRC_NAME'):\n month_count = defaultdict(int)\n for month, group in c.groupby('MONTH'):\n month_count[month] = len(group)\n m_s = sorted(list(month_count.keys()))\n m_l = [month_count[i] for i in m_s]\n chart_1 = Line(\"各月份投诉渠道数\", **style.init_style)\n chart_1.add(\"事件数\", m_s,m_l,\n mark_point=[\"max\", \"min\"],is_more_utils=True,\n mark_line=[\"average\"], is_smooth=True,\n )\n chart.add(chart_1,name)\n page.add(chart)\n\n return page\n","sub_path":"app/charts/src_event.py","file_name":"src_event.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"549801613","text":"import boilerplate\n\ndef invest(amount, rate, time):\n\tprint('principal amount: {}'.format(amount))\n\tprint('annual rate of return: {}'.format(rate))\n\ttotal = amount\n\n\tfor x in range (1, time + 1):\n\t\ttotal = total + (total * rate)\n\t\tprint('year {}: {}'.format(x, total))\n\n\ninvest(100, .05, 8)\ninvest(2000, .025, 5)\n\n'''\nThe returned investments from my caculations are very close to the book, \nbut not exact. I think my math is right because it's accurate to several\ndecimal places.\n'''\n","sub_path":"babysteps/21.Invest_o_matic.py","file_name":"21.Invest_o_matic.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"138155577","text":"\"\"\"The type file for the collection Individual (Encode Donor).\"\"\"\nfrom snovault import (\n abstract_collection,\n # calculated_property,\n collection,\n load_schema,\n)\n# from pyramid.security import Authenticated\nfrom .base import (\n Item,\n ALLOW_SUBMITTER_ADD_ACL,\n get_item_or_none,\n lab_award_attribution_embed_list\n)\n\nfrom snovault.validators import (\n validate_item_content_post,\n validate_item_content_put,\n validate_item_content_patch,\n validate_item_content_in_place,\n no_validate_item_content_post,\n no_validate_item_content_put,\n no_validate_item_content_patch\n)\nfrom snovault.crud_views import (\n collection_add,\n item_edit,\n)\nfrom pyramid.view import view_config\n\n\n@abstract_collection(\n name='individuals',\n unique_key='accession',\n acl=ALLOW_SUBMITTER_ADD_ACL,\n properties={\n 'title': \"Individuals\",\n 'description': 'Listing of all types of individuals.',\n })\nclass Individual(Item):\n \"\"\"the base class for individual collection.\"\"\"\n item_type = 'individual'\n base_types = ['Individual'] + Item.base_types\n schema = load_schema('encoded:schemas/individual.json')\n embedded_list = Item.embedded_list + lab_award_attribution_embed_list + [\n # Organism linkTo\n 'organism.name',\n 'organism.scientific_name'\n ]\n name_key = 'accession'\n\n class Collection(Item.Collection):\n pass\n\n\n@collection(\n name='individuals-human',\n unique_key='accession',\n properties={\n 'title': 'Individuals-Humans',\n 'description': 'Listing Biosample Human Individuals',\n })\nclass IndividualHuman(Individual):\n \"\"\"the sub class of individuals for human species.\"\"\"\n\n item_type = 'individual_human'\n schema = load_schema('encoded:schemas/individual_human.json')\n embedded_list = Individual.embedded_list\n\n\n@collection(\n name='individuals-primate',\n unique_key='accession',\n properties={\n 'title': 'Individuals-Primates',\n 'description': 'Listing Biosample Primate Individuals',\n })\nclass IndividualPrimate(Individual):\n \"\"\"the sub class of individuals for primate species.\"\"\"\n\n item_type = 'individual_primate'\n schema = load_schema('encoded:schemas/individual_primate.json')\n embedded_list = Individual.embedded_list\n\n\n@collection(\n name='individuals-mouse',\n unique_key='accession',\n properties={\n 'title': 'Individuals-Mice',\n 'description': 'Listing Biosample Mouse Individuals',\n })\nclass IndividualMouse(Individual):\n \"\"\"the sub class of individuals for mouse species.\"\"\"\n\n item_type = 'individual_mouse'\n schema = load_schema('encoded:schemas/individual_mouse.json')\n embedded_list = Individual.embedded_list + [\n # Vendor linkTo\n 'mouse_vendor.name',\n 'mouse_vendor.title'\n ]\n\n\n@collection(\n name='individuals-fly',\n unique_key='accession',\n properties={\n 'title': 'Individuals-Flies',\n 'description': 'Listing Biosample Fly Individuals',\n })\nclass IndividualFly(Individual):\n \"\"\"the sub class of individuals for flies.\"\"\"\n\n item_type = 'individual_fly'\n schema = load_schema('encoded:schemas/individual_fly.json')\n embedded_list = Individual.embedded_list + [\n # Vendor linkTo\n 'fly_vendor.name',\n 'fly_vendor.title'\n ]\n\n\n@collection(\n name='individuals-chicken',\n unique_key='accession',\n properties={\n 'title': 'Individuals-Chickens',\n 'description': 'Listing Biosample Chicken Individuals',\n })\nclass IndividualChicken(Individual):\n \"\"\"the sub class of individuals for chickens.\"\"\"\n\n item_type = 'individual_chicken'\n schema = load_schema('encoded:schemas/individual_chicken.json')\n embedded_list = Individual.embedded_list + [\n # Vendor linkTo\n 'chicken_vendor.name',\n 'chicken_vendor.title'\n ]\n\n\n@collection(\n name='individuals-zebrafish',\n unique_key='accession',\n properties={\n 'title': 'Individuals-Zebrafish',\n 'description': 'Listing Zebrafish Sources',\n })\nclass IndividualZebrafish(Individual):\n \"\"\"the sub class of individuals for zebrafish.\"\"\"\n\n item_type = 'individual_zebrafish'\n schema = load_schema('encoded:schemas/individual_zebrafish.json')\n embedded_list = Individual.embedded_list + [\n 'zebrafish_vendor.name',\n 'zebrafish_vendor.title'\n ]\n\n\n# validator for individual relations - same species\ndef validate_individual_relations(context, request):\n '''Validates that individual relations are within the same species,\n limited to two relations per individual (max 1 paternal and 1 maternal),\n not self relations, and unique (no duplicate relations).\n '''\n related_individuals = request.json.get('individual_relation') # a list of dicts\n if related_individuals is None:\n return\n any_failures = False\n\n # check if the individual info is in request (POST) or in context (PATCH)\n try:\n individual_uuid = str(context.uuid)\n data = context.properties\n except AttributeError:\n data = request.json\n individual_uuid = data.get('uuid')\n organism_id = data.get('organism')\n organism = get_item_or_none(request, organism_id, 'organisms')\n\n # Max 2 parents per individual\n if len(related_individuals) > 2:\n request.errors.add(\n 'body', 'Individual relation: too many parents',\n 'An individual cannot have more than two parents'\n )\n any_failures = True\n\n relations_counter = {}\n relations_unique = {}\n for a_related_individual in related_individuals:\n if len(a_related_individual.keys()) < 2:\n continue\n parent = a_related_individual.get('individual')\n parent_props = get_item_or_none(request, parent, 'individuals')\n parent_organism = get_item_or_none(request, parent_props.get('organism'), 'organisms')\n parent_uuid = parent_props.get('uuid')\n\n # Same species\n if parent_organism.get('uuid') != organism.get('uuid'):\n request.errors.add(\n 'body', 'Individual relation: different species',\n 'Parent individual is ' + parent_organism['name'] + ', not ' + organism['name']\n )\n any_failures = True\n\n # Self relation\n if parent_uuid == individual_uuid:\n request.errors.add(\n 'body', 'Individual relation: self-relation',\n 'An individual cannot be related to itself'\n )\n any_failures = True\n\n # Count of relationship type, excluding the generic 'derived from'\n rel_type = a_related_individual['relationship_type']\n if rel_type != 'derived from':\n if rel_type in relations_counter.keys():\n relations_counter[rel_type] += 1\n else:\n relations_counter[rel_type] = 1\n\n # Multiple relations with same parent\n if parent_uuid in relations_unique.keys():\n relations_unique[parent_uuid] += 1\n else:\n relations_unique[parent_uuid] = 1\n\n if any(a_value > 1 for a_value in relations_counter.values()):\n request.errors.add(\n 'body', 'Individual relation: too many of the same type',\n 'An individual cannot derive from more than one maternal or paternal strain'\n )\n any_failures = True\n\n if any(val > 1 for val in relations_unique.values()):\n request.errors.add(\n 'body', 'Individual relation: multiple relations with same parent',\n 'An individual cannot have more than one relation with the same parent'\n )\n any_failures = True\n\n if not any_failures:\n request.validated.update({})\n\n\n@view_config(context=Individual.Collection, permission='add', request_method='POST',\n validators=[validate_item_content_post, validate_individual_relations])\n@view_config(context=Individual.Collection, permission='add_unvalidated', request_method='POST',\n validators=[no_validate_item_content_post],\n request_param=['validate=false'])\ndef individual_add(context, request, render=None):\n return collection_add(context, request, render)\n\n\n@view_config(context=Individual, permission='edit', request_method='PUT',\n validators=[validate_item_content_put, validate_individual_relations])\n@view_config(context=Individual, permission='edit', request_method='PATCH',\n validators=[validate_item_content_patch, validate_individual_relations])\n@view_config(context=Individual, permission='edit_unvalidated', request_method='PUT',\n validators=[no_validate_item_content_put],\n request_param=['validate=false'])\n@view_config(context=Individual, permission='edit_unvalidated', request_method='PATCH',\n validators=[no_validate_item_content_patch],\n request_param=['validate=false'])\n@view_config(context=Individual, permission='index', request_method='GET',\n validators=[validate_item_content_in_place, validate_individual_relations],\n request_param=['check_only=true'])\ndef individual_edit(context, request, render=None):\n return item_edit(context, request, render)\n","sub_path":"src/encoded/types/individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"280438235","text":"import requests\nimport re\nimport random\n\nclass FreeIP():\n def get_ip(self):\n url = 'http://www.kuaidaili.com/free/inha/1/'\n iplist = []\n html = requests.get(url).text\n tags = re.findall(r'data-title=.IP..(.*?).*?PORT..(.*?)', html, re.S)\n for tag in tags:\n ip = tag[0] + ':' + tag[1]\n iplist.append(ip)\n\n # ip = ''.join(str(random.choices(iplist)).strip())\t\t# ['ip']\n # ip = ''.join(str(random.choices(iplist)).strip())\t\t# ip\n\n # ip = ''.join(str(iplist[random.randint(0, len(iplist)-1)]).strip())\n ip = ''.join(str(iplist[random.randint(0, 5)]).strip())\n\n assert (ip)\n return ip\n\nIP = FreeIP()\n","sub_path":"demo/FreeIP.py","file_name":"FreeIP.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"356133797","text":"import unittest\nfrom test_env import TestEnv\nimport numpy\n\n\n@TestEnv.module\nclass TestNumpyUFuncUnary(TestEnv):\n pass\n# automatic generation of basic test cases for ufunc\n\nunary_ufunc = (\n 'abs', 'absolute', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctanh',\n 'bitwise_not',\n 'ceil', 'conj', 'conjugate', 'cos', 'cosh',\n 'deg2rad', 'degrees',\n 'exp', 'expm1',\n 'fabs', 'float32', 'float64', 'floor',\n 'int8', 'int16', 'int32', 'int64', 'isinf', 'isneginf', 'isposinf', 'isnan', 'invert', 'isfinite',\n 'log', 'log10', 'log1p', 'log2', 'logical_not',\n 'negative',\n 'rad2deg', 'radians','reciprocal', 'rint', 'round', 'round_',\n 'sign', 'signbit',\n 'sin', 'sinh', 'spacing', 'sqrt', 'square',\n 'tan', 'tanh','trunc',\n 'uint8', 'uint16', 'uint32', 'uint64'\n )\n\nfor f in unary_ufunc:\n if 'bitwise_' in f or 'invert' in f:\n setattr(TestNumpyUFuncUnary, 'test_' + f, eval(\"lambda self: self.run_test('def np_{0}(a): from numpy import {0} ; return {0}(a)', numpy.ones(10, numpy.int32), np_{0}=[numpy.array([numpy.int32])])\".format(f)))\n setattr(TestNumpyUFuncUnary, 'test_' + f + '_scalar', eval(\"lambda self: self.run_test('def np_{0}_scalar(a): from numpy import {0} ; return {0}(a)', 1, np_{0}_scalar=[int])\".format(f)))\n setattr(TestNumpyUFuncUnary, 'test_' + f + '_matrix', eval(\"lambda self: self.run_test('def np_{0}_matrix(a): from numpy import {0} ; return {0}(a)', numpy.ones((5,2), numpy.int32), np_{0}_matrix=[numpy.array([numpy.array([numpy.int32])])])\".format(f)))\n else:\n setattr(TestNumpyUFuncUnary, 'test_' + f, eval(\"lambda self: self.run_test('def np_{0}(a): from numpy import {0} ; return {0}(a)', numpy.ones(10), np_{0}=[numpy.array([float])])\".format(f)))\n setattr(TestNumpyUFuncUnary, 'test_' + f + '_scalar', eval(\"lambda self: self.run_test('def np_{0}_scalar(a): from numpy import {0} ; return {0}(a+0.5)', 0.5, np_{0}_scalar=[float])\".format(f)))\n setattr(TestNumpyUFuncUnary, 'test_' + f + '_matrix', eval(\"lambda self: self.run_test('def np_{0}_matrix(a): from numpy import {0} ; return {0}(a)', numpy.ones((2,5)), np_{0}_matrix=[numpy.array([numpy.array([float])])])\".format(f)))\n\n","sub_path":"pythran/tests/test_numpy_ufunc_unary.py","file_name":"test_numpy_ufunc_unary.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"191710419","text":"# -*- coding: utf-8 -*-\n\nimport unittest\nimport numpy\n\nfrom quantarhei import TimeAxis\nfrom quantarhei import energy_units\nfrom quantarhei import CorrelationFunction\nfrom quantarhei.qm.corfunctions import CorrelationFunctionMatrix \nfrom quantarhei.qm import SystemBathInteraction\nfrom quantarhei import Hamiltonian\nfrom quantarhei.qm import Operator\nfrom quantarhei.qm import RedfieldRateMatrix\nfrom quantarhei import REAL\n\nclass TestRedfieldRateMatrix(unittest.TestCase):\n \"\"\"Tests for the RateMatrix class\n \n \n \"\"\"\n \n def setUp(self,verbose=False):\n \n self.verbose = verbose\n\n time = TimeAxis(0.0,1000,1.0)\n with energy_units(\"1/cm\"):\n params = {\"ftype\":\"OverdampedBrownian\",\n \"reorg\":30.0,\n \"T\":300.0,\n \"cortime\":100.0}\n \n cf1 = CorrelationFunction(time,params)\n\n \n cm1 = CorrelationFunctionMatrix(time,2,1)\n cm1.set_correlation_function(cf1,[(0,0),(1,1)])\n \n \n K11 = numpy.array([[1.0, 0.0],[0.0, 0.0]],dtype=REAL)\n K21 = numpy.array([[1.0, 0.0],[0.0, 0.0]],dtype=REAL)\n\n \n KK11 = Operator(data=K11)\n KK21 = Operator(data=K21)\n \n \n self.sbi1 = SystemBathInteraction([KK11,KK21],cm1) \n \n with energy_units(\"1/cm\"):\n h1 = [[0.0, 100.0],[100.0, 0.0]]\n self.H1 = Hamiltonian(data=h1)\n \n self.sbi2 = SystemBathInteraction()\n \n \n \n def test_create_of_RedfieldRateMatrix(self):\n \"\"\"(RedfieldRateMatrix) Testing creation \n \n \"\"\"\n op = Operator(dim=self.H1.dim)\n \n # testing wrong Hamiltonian\n with self.assertRaises(Exception) as context:\n RR = RedfieldRateMatrix(op,self.sbi1)\n \n self.assertTrue(\"First argument must be a Hamiltonian\"\n in str(context.exception))\n \n # testing wrong SBI\n with self.assertRaises(Exception) as context:\n RR = RedfieldRateMatrix(self.H1,op)\n\n self.assertTrue(\"Second argument must be a SystemBathInteraction\"\n in str(context.exception))\n \n # testing cutoff time\n RR = RedfieldRateMatrix(self.H1, self.sbi1, cutoff_time=100.0)\n \n self.assertTrue(RR._has_cutoff_time)\n self.assertTrue(RR.cutoff_time == 100.0)\n \n # testing empty SBI\n with self.assertRaises(Exception) as context:\n RR = RedfieldRateMatrix(self.H1, self.sbi2)\n \n self.assertTrue(\"No system bath intraction components present\"\n in str(context.exception))\n \n \n ","sub_path":"tests/unit/qm/liouvillespace/rates/test_redfieldratematrix.py","file_name":"test_redfieldratematrix.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"641233976","text":"from os import listdir\nfrom os.path import isfile, join\nimport pandas as pd\nimport string\nfrom pos_tagging import tagging\nimport re\n\n# INPUT_PATH = 'input'\nINPUT_PATH = 'input-2'\n# OUTPUT_PATH = 'lemmatized'\nOUTPUT_PATH = 'output_lemmatized'\n# OUTPUT_PATH = 'output_significant'\n\ndef remove_punctuation(str):\n return \"\".join([c for c in str if c not in string.punctuation])\n\ndef clean_data(str):\n cleaned = str.lower().replace('\\n', '').strip().replace('nbsp', '')\n cleaned = re.sub(r'\\w*?[\\W&[\\S]]\\w{0,10}', '', cleaned)\n cleaned = re.sub(r'@\\w+', '', cleaned)\n # print(cleaned)\n cleaned_extra_spaces = ' '.join(cleaned.split())\n\n # print(cleaned_extra_spaces)\n if len(cleaned_extra_spaces):\n return remove_punctuation(cleaned_extra_spaces)\n else:\n return False\n\n\n\ndef main():\n # input_files = [file for file in listdir(INPUT_PATH) if isfile(join(INPUT_PATH, file))]\n input_files = ['train.csv']\n\n for i in range(len(input_files)):\n try:\n input_file = join(INPUT_PATH, input_files[i])\n output_file = join(OUTPUT_PATH, input_files[i])\n\n # df = pd.read_csv(input_file)\n df = pd.read_csv(input_file, header=None)\n # df[\"post\"] = df[\"post\"].apply(lambda x : clean_data(x))\n # df.iloc[:,6] = df.iloc[:,6].apply(lambda x : clean_data(x))\n df.iloc[:,6] = df.iloc[:,6].apply(lambda x : clean_data(x) if clean_data(x) else 'not')\n # df.iloc[:,0] = df.iloc[:,0].apply(lambda x : clean_data(x))\n\n\n output_arr = []\n\n # print(df[\"post\"])\n # for post in df[\"post\"]:\n for post in df.iloc[:,6]:\n # print(tagging(post))\n # print(post)\n output_arr.append(' '.join(tagging(post)))\n # return\n\n # df[\"data-id\"] = df[\"user_id\"].astype(str) + '-' + df[\"#\"].astype(str)\n # df[\"data\"] = output_arr\n df.iloc[:,6] = output_arr\n\n # print(df)\n\n # df.to_csv(output_file, index=False, columns=[\"data-id\", \"data\"])\n df.to_csv(output_file, index=False)\n\n print(\"finished \" + input_files[i])\n\n except Exception as e:\n print('ERROR in ' + input_files[i] + \": \" + str(e))\n\n\n\nmain()\n\n\n\n\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"451474965","text":"\"\"\"\n并发相关类或函数。\n\"\"\"\nimport time\nimport logging\nimport threading\nfrom queue import Queue as ThreadQueue\nfrom queue import Empty as ThreadQueueEmpty\nfrom multiprocessing import Process\nfrom multiprocessing import Queue as ProcessQueue\nfrom multiprocessing import Value\nfrom multiprocessing.queues import Empty as ProcessQueueEmpty\nfrom ctypes import c_bool\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ThreadFlag(object):\n def __init__(self, value=False):\n self._value = value\n\n def get_value(self):\n return self._value\n\n def set_value(self, value):\n self._value = value\n\n value = property(get_value, set_value)\n\n\nclass ProcessFlag(object):\n def __init__(self, value=False):\n self.flag = Value(c_bool, value)\n\n def get_value(self):\n return self.flag.value\n\n def set_value(self, value):\n self.flag.value = value\n\n value = property(get_value, set_value)\n\n\nclass MPTQueueExecutor(object):\n def __init__(self, executor, process_setup=None, process_on_stopped=None, thread_setup=None, thread_on_stopped=None, max_processes=1, max_threads=16, queue_size=0, pull_timeout=1):\n self.executor = executor\n self.process_setup = process_setup\n self.process_on_stopped = process_on_stopped \n self.thread_setup = thread_setup\n self.thread_on_stopped = thread_on_stopped\n self.max_processes = max_processes\n self.max_threads = max_threads\n self.queue_size = queue_size\n self.pull_timeout = pull_timeout\n self.pe = ProcessQueueExecutor(\n self.process_worker_wrapper,\n setup=self.process_setup_wrapper,\n on_stopped=self.process_on_stopped_wrapper,\n max_workers=self.max_processes,\n queue_size=self.queue_size,\n )\n\n def is_alive(self):\n return self.pe.is_alive()\n\n def start(self):\n logger.info(\"MPTQueueExecutor starting...\")\n self.pe.start()\n\n def process_setup_wrapper(self):\n logger.info(\"MPTQueueExecutor process_setup starting...\")\n try:\n if self.process_setup and callable(self.process_setup):\n self.process_setup()\n except Exception as error:\n logger.exception(\"MPTQueueExecutor process_setup got failed.\")\n raise error\n try:\n self.te = ThreadQueueExecutor(\n self.executor,\n setup=self.thread_setup_wrapper,\n on_stopped=self.thread_on_stopped_wrapper,\n max_workers=self.max_threads,\n queue_size=1,\n )\n self.te.start()\n except Exception as error:\n logger.exception(\"MPTQueueExecutor process_setup start ThreadQueueExecutor got failed.\")\n raise error\n logger.info(\"MPTQueueExecutor process_setup finished.\")\n\n def process_on_stopped_wrapper(self):\n self.te.stop(block=False)\n if self.process_on_stopped and callable(self.process_on_stopped):\n self.process_on_stopped()\n self.te.stop_waiting()\n\n def process_worker_wrapper(self, message):\n logger.debug(\"MPTQueueExecutor got a message and send to ThreadQueueExecutor, message = {}.\".format(message))\n self.te.submit(message)\n\n def thread_setup_wrapper(self):\n logger.info(\"MPTQueueExecutor thread_setup starting...\")\n if self.thread_setup and callable(self.thread_setup):\n self.thread_setup()\n logger.info(\"MPTQueueExecutor thread_setup finished.\")\n\n def thread_on_stopped_wrapper(self):\n if self.thread_on_stopped and callable(self.thread_on_stopped):\n self.thread_on_stopped()\n\n def stop(self, block=True, timeout=0, sleep=5):\n \"\"\"\n 停止服务。\n \"\"\"\n logger.debug(\"MPTQueueExecutor.stopping...\")\n try:\n self.pe.stop(block, timeout, sleep)\n except Exception as error:\n logger.exception(\"MPTQueueExecutor.stop got failed...\")\n raise error\n\n def submit(self, message, block=True, timeout=None):\n \"\"\"\n 向后台工作进程发送任务。\n \"\"\"\n return self.pe.submit(message, block, timeout)\n\n def submit_nowait(self, message):\n \"\"\"\n 尝试向工作进程发送任务。如果队列阻塞,则抛出异常。\n \"\"\"\n return self.pe.submit_nowait(message)\n\n\nclass ProcessQueueExecutor(object):\n \"\"\"\n 案例:\n def worker_main(message):\n pass\n executor = ProcessQueueExecutor(worker_main)\n executor.start()\n for message in messages:\n executor.submit(message)\n \"\"\"\n\n def __init__(self, executor, setup=None, on_stopped=None, max_workers=1, queue_size=0, pull_timeout=1):\n \"\"\"\n 构造函数。\n \"\"\"\n self.max_workers = max_workers\n self.executor = executor\n self.setup = setup\n self.on_stopped = on_stopped\n self.queue_size = queue_size\n self.pull_timeout = pull_timeout\n self.queue = ProcessQueue(maxsize=self.queue_size)\n self.processes = {}\n self.stop_flag = ProcessFlag(False)\n self.counter = 0\n\n def is_alive(self):\n \"\"\"\n 判断是否存活。\n \"\"\"\n for index in list(self.processes.keys()):\n if self.processes[index].is_alive():\n return True\n return False\n\n def start(self):\n \"\"\"\n 启动max_workers个后台工作进程。\n \"\"\"\n logger.info(\"ProcessQueueExecutor starting: max_workers={} queue_size={}.\".format(self.max_workers, self.queue_size))\n self.stop_flag.value = False\n self.counter = 0\n for _ in range(0, self.max_workers):\n self.start_a_worker()\n time.sleep(1)\n\n def start_a_worker(self):\n \"\"\"\n 启动一个后台工作进程。\n \"\"\"\n self.counter += 1\n logger.info(\"ProcessQueueExecutor starting a worker: index={}\".format(self.counter))\n self.processes[self.counter] = Process(target=self.worker)\n self.processes[self.counter].daemon = True\n self.processes[self.counter].start()\n\n def worker(self):\n \"\"\"\n 真正的执行过程。主要包含了初始化&消息循环。\n \"\"\"\n logger.info(\"ProcessQueueExecutor worker started.\")\n try:\n if self.setup and callable(self.setup):\n logger.info(\"ProcessQueueExecutor worker setup starting...\")\n self.setup()\n logger.info(\"ProcessQueueExecutor worker setup done.\")\n except Exception as error:\n logger.exception(\"ProcessQueueExecutor worker setup failed.\")\n raise error\n logger.info(\"ProcessQueueExecutor worker enter pulling loop...\")\n while True:\n try:\n try:\n message = self.queue.get(timeout=self.pull_timeout)\n except ProcessQueueEmpty:\n logger.debug(\"ProcessQueueExecutor pull from queue got None.\")\n # deal all messages in the queue after stopped\n if self.stop_flag.value:\n break\n else:\n continue\n logger.debug(\"ProcessQueueExecutor pull from queue got message: {}\".format(message))\n try:\n self.executor(message)\n except Exception:\n logger.exception(\"ProcessQueueExecutor execute message failed, message: {}\".format(message))\n except Exception:\n logger.exception(\"ProcessQueueExecutor.worker got unknown exception.\")\n logger.info(\"ProcessQueueExecutor worker exit pulling loop.\")\n try:\n if self.on_stopped and callable(self.on_stopped):\n logger.info(\"ProcessQueueExecutor worker calling on_stopped callback.\")\n self.on_stopped()\n except Exception as error:\n logger.exception(\"ProcessQueueExecutor.worker on_stopped failed.\")\n raise error\n logger.info(\"ProcessQueueExecutor worker finished.\")\n\n def reorganisation(self, loop_forever=False, sleep=5):\n \"\"\"\n 如果有工作进程异常退出,重新启动新的工作进程。\n \"\"\"\n logger.info(\"ProcessQueueExecutor entering reorganisation loop...\")\n while not self.stop_flag.value:\n for index in list(self.processes.keys()):\n if not self.processes[index].is_alive():\n del self.processes[index]\n self.start_a_worker()\n if not loop_forever:\n break\n time.sleep(sleep)\n logger.info(\"ProcessQueueExecutor exit reorganisation loop.\")\n\n def stop_waiting(self, block=True, timeout=0, sleep=5):\n \"\"\"\n 等待退出。\n \"\"\"\n stime = time.time()\n while block:\n alives = 0\n for index in list(self.processes.keys()):\n if not self.processes[index].is_alive():\n del self.processes[index]\n else:\n alives += 1\n if not alives:\n break\n if timeout and (time.time() - stime > timeout):\n for index in list(self.processes.keys()):\n try:\n self.processes[index].terminate()\n except Exception:\n logger.exception(\"Force kill sub-process got failed.\")\n break\n time.sleep(sleep)\n\n def stop(self, block=True, timeout=0, sleep=5):\n \"\"\"\n 向工作进程传递退出信号。\n 如果是非阻塞式,则不管工作进程状态,直接返回。\n 如果是阻塞式,则等待工作进程退出或超时。\n 如果有超时限制,则在超时后强制结束工作进程。\n 如果没有超时限制,则永久等待工作进程自己退出。\n \"\"\"\n logger.debug(\"ProcessQueueExecutor.stopping...\")\n try:\n self.stop_flag.value = True\n self.stop_waiting(block, timeout, sleep)\n except Exception as error:\n logger.exception(\"ProcessQueueExecutor.stop got failed.\")\n raise error\n\n def submit(self, message, block=True, timeout=None):\n \"\"\"\n 向后台工作进程发送任务。\n \"\"\"\n return self.queue.put(message, block, timeout)\n\n def submit_nowait(self, message):\n \"\"\"\n 尝试向工作进程发送任务。如果队列阻塞,则抛出异常。\n \"\"\"\n return self.queue.put_nowait(message)\n\n\nclass ThreadQueueExecutor(object):\n \"\"\"\n 案例:\n def worker_main(message):\n pass\n executor = ThreadQueueExecutor(worker_main)\n executor.start()\n for message in messages:\n executor.submit(message)\n \"\"\"\n\n def __init__(self, executor, setup=None, on_stopped=None, max_workers=1, queue_size=0, pull_timeout=1):\n \"\"\"\n 构造函数。\n \"\"\"\n self.max_workers = max_workers\n self.executor = executor\n self.setup = setup\n self.on_stopped = on_stopped\n self.queue_size = queue_size\n self.pull_timeout = pull_timeout\n self.queue = ThreadQueue(maxsize=self.queue_size)\n self.threads = {}\n self.stop_flag = ThreadFlag(False)\n self.counter = 0\n\n def is_alive(self):\n \"\"\"\n 判断是否存活。\n \"\"\"\n for index in list(self.threads.keys()):\n if self.threads[index].is_alive():\n return True\n return False\n\n def start(self):\n \"\"\"\n 启动max_workers个后台工作进程。\n \"\"\"\n logger.info(\"ProcessQueueExecutor starting: max_workers={} queue_size={}.\".format(self.max_workers, self.queue_size))\n self.stop_flag.value = False\n self.counter = 0\n for _ in range(0, self.max_workers):\n self.start_a_worker()\n time.sleep(1)\n\n def start_a_worker(self):\n \"\"\"\n 启动一个后台工作线程。\n \"\"\"\n self.counter += 1\n logger.info(\"ThreadQueueExecutor starting a worker: index={}\".format(self.counter))\n self.threads[self.counter] = threading.Thread(target=self.worker)\n self.threads[self.counter].daemon = True\n self.threads[self.counter].start()\n\n def worker(self):\n \"\"\"\n 真正的执行过程。主要包含了初始化&消息循环。\n \"\"\"\n logger.info(\"ThreadQueueExecutor a worker started.\")\n try:\n if self.setup and callable(self.setup):\n self.setup()\n except Exception as error:\n logger.exception(\"ThreadQueueExecutor work setup got failed.\")\n raise error\n logger.info(\"ThreadQueueExecutor worker enter pulling loop...\")\n while True:\n try:\n try:\n message = self.queue.get(timeout=self.pull_timeout)\n except ThreadQueueEmpty:\n logger.debug(\"ThreadQueueExecutor pull from queue got None.\")\n # deal all messages in the queue after stopped\n if self.stop_flag.value:\n break\n else:\n continue\n logger.debug(\"ThreadQueueExecutor pull from queue got message: {}.\".format(message))\n try:\n self.executor(message)\n except Exception:\n logger.exception(\"Execute message failed, message: {}\".format(message))\n except Exception:\n logger.exception(\"ThreadQueueExecutor.worker got unknown exception.\")\n logger.info(\"ThreadQueueExecutor worker exit pulling loop.\")\n try:\n if self.on_stopped and callable(self.on_stopped):\n logger.info(\"ThreadQueueExecutor worker calling on_stopped callback.\")\n self.on_stopped()\n except Exception as error:\n logger.exception(\"ThreadQueueExecutor worker call on_stopped callback got failed.\")\n raise error\n logger.info(\"ThreadQueueExecutor worker finished.\")\n\n def reorganisation(self, loop_forever=False, sleep=5):\n \"\"\"\n 如果有工作线程异常退出,重新启动新的工作线程。\n \"\"\"\n while not self.stop_flag.value:\n for index in list(self.threads.keys()):\n if not self.threads[index].is_alive():\n del self.threads[index]\n self.start_a_worker()\n if not loop_forever:\n break\n time.sleep(sleep)\n\n def stop_waiting(self, block=True, sleep=5):\n \"\"\"\n 等待退出。\n \"\"\"\n while block:\n alives = 0\n for index in list(self.threads.keys()):\n if not self.threads[index].is_alive():\n del self.threads[index]\n else:\n alives += 1\n if not alives:\n break\n time.sleep(sleep)\n\n def stop(self, block=True, sleep=5):\n \"\"\"\n 向工作线程传递退出信号。\n 如果是非阻塞式,则不管工作线程状态,直接返回。\n 如果是阻塞式,则等待工作线程退出。\n 如果没有超时限制,则永久等待工作进程自己退出。\n 注意:python中无法强制线程退出。\n \"\"\"\n self.stop_flag.value = True\n self.stop_waiting(block, sleep)\n\n def submit(self, message, block=True, timeout=None):\n \"\"\"\n 向后台工作线程发送任务。\n \"\"\"\n return self.queue.put(message, block, timeout)\n\n def submit_nowait(self, message):\n \"\"\"\n 尝试向工作线程发送任务。如果队列阻塞,则抛出异常。\n \"\"\"\n return self.queue.put_nowait(message)\n","sub_path":"src/zencore/utils/concurrent.py","file_name":"concurrent.py","file_ext":"py","file_size_in_byte":16075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"156043149","text":"#!/usr/bin/env python3\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.title('Un primo plot con Python')\nplt.xlabel('x')\nplt.ylabel('y')\nx = np.linspace(0.0, 5.0, 100)\ny = x\nplt.plot(x,y,label='y=x')\nx, y = np.loadtxt('temp.dat', usecols=(0,2), delimiter=' ', unpack=True)\nplt.plot(x,y, 'x',label='Loaded from file!')\nplt.savefig('traiettoria.png')\nplt.show()\n","sub_path":"esercitazioni/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"256215940","text":"from sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nfrom ast import literal_eval\nfrom time import strftime, localtime, strptime, mktime\nfrom datetime import datetime\nimport requests\n\n# graph_init = literal_eval(open('data/graph.json','r').read())\nurl = 'https://c19downloads.azureedge.net/downloads/data/countries_latest.json'\ndata = requests.get(url).json()['E92000001']\ndegree = 6\n\ndef calculateCases(cf, feat):\n val = 0\n for x in range(degree):\n val += feat[x]*cf[0][x]\n return val\n\n\ndef predict(key, predict):\n graph_init = [[int(mktime(strptime(x['date'], '%Y-%m-%d'))), x['value']] for x in data[key]]\n start = graph_init[0][0]\n perday = 86400000\n predictFor = predict # number of days to be predicted\n omit = 25\n customDayStart = omit*perday + start\n\n graph = graph_init[omit:]\n # x_graph = [[x[0]] for x in graph]\n dateConverter = lambda x: strftime('%b %d', localtime((start + perday*x)/1000))\n x_graph_day = [dateConverter(omit+x) for x in range(0,len(graph)+predictFor)]\n\n x = [[i] for i in range(0, len(graph))]\n y = [[i[1]] for i in graph]\n\n features = PolynomialFeatures(degree=degree, include_bias=False)\n x_poly = features.fit_transform(x)\n lin_reg = LinearRegression()\n lin_reg.fit(x_poly, y)\n coef = lin_reg.coef_\n\n final_y = []\n for i in range(0, len(graph)):\n final_y.append(calculateCases(coef, x_poly[i]))\n\n x_temp = [[i+len(x)] for i in range(0, predictFor)]\n x_temp = features.fit_transform(x_temp)\n for i in range(len(x_temp)):\n final_y.append(calculateCases(coef, x_temp[i]))\n\n # plotting\n plt.scatter(x_graph_day[:-predictFor], y, color='black')\n plt.plot(x_graph_day[:-predictFor], final_y[:-predictFor], color='blue')\n plt.plot(x_graph_day[-predictFor:], final_y[-predictFor:], color='red')\n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.show()\n\n\npredict('dailyConfirmedCases', 2)\npredict('dailyTotalConfirmedCases', 5)","sub_path":"src/graphRegression.py","file_name":"graphRegression.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"541665016","text":"from kiteconnect import KiteConnect\nfrom kiteconnect import KiteTicker\nfrom config import Config\nfrom util import SeleniumDispatcher\nfrom selenium.webdriver.common.keys import Keys\nimport time\nfrom db.models import KiteSimulatorStateModel\nfrom datetime import datetime, date\nimport numpy as np\nfrom datetime import datetime\nfrom dateutil.tz import *\nimport urllib.parse as urlparse\nfrom urllib.parse import parse_qs\nfrom util.log import Logger\n\n\n\nclass LiveSimulator:\n def __init__(self, api_key=Config.KITE_API_KEY, api_secret=Config.KITE_API_SECRET, username = Config.KITE_USER_ID,\n password=Config.KITE_PASSWORD, pin=Config.KITE_PIN,\n end_hour=Config.KITE_SIMULATION_END_HOUR, end_minute=Config.KITE_SIMULATION_END_MINUTE):\n self.username = username\n self.password = password\n self.pin = pin\n # TODO: Generate kite instance only when a function that requires it is called\n self.api_key = api_key\n self.kite = KiteConnect(api_key=api_key)\n req_token = self.get_request_token()\n data = self.kite.generate_session(req_token, api_secret=api_secret)\n self.access_token = data[\"access_token\"]\n self.kite.set_access_token(self.access_token)\n self.kite_state = list(KiteSimulatorStateModel.objects.raw({'createdDate': str(date.today())}))[-1]\n self.end_time = datetime.now().astimezone(tzlocal()).replace(hour=end_hour, minute=end_minute)\n\n\n def get_instrument_tokens(self, instrument_list: list):\n instrument_token_list = dict()\n self.instrument_infos = self.kite.instruments(exchange='NSE')\n for instrument in instrument_list:\n for instrument_info in self.instrument_infos:\n if instrument == instrument_info['tradingsymbol']:\n instrument_token_list[instrument] = instrument_info['instrument_token']\n break\n return instrument_token_list\n\n \n def sim_init(self):\n if not self.kite_state.simulationInitSuccessful:\n # Initialise\n ticker = KiteTicker(self.api_key, self.access_token)\n instrument_tokens = self.kite_state.companyTokens.copy()\n profit_slab = self.kite_state.profitSlab\n buy_dict = dict()\n # Defining the callbacks\n def on_ticks(tick, ticks_info):\n # global buy_dict\n for tick_info in ticks_info:\n # TODO : Check if the order is correct\n buy_dict[tick_info['instrument_token']] = tick_info['depth']['sell'][0]['price']\n tick.close()\n\n def on_connect(tick, response):\n # global instrument_tokens\n tick.subscribe(self.kite_state.companyTokens)\n tick.set_mode(tick.MODE_FULL, self.kite_state.companyTokens)\n\n def on_close(tick, code, reason):\n tick.stop()\n Logger.info('Connection closed successfully!')\n\n # Assign the callbacks.\n ticker.on_ticks = on_ticks\n ticker.on_connect = on_connect\n ticker.on_close = on_close\n\n ticker.connect()\n\n # Building buy list\n buy_list = list()\n for token in instrument_tokens:\n buy_list.append(buy_dict[token])\n\n final_buy_list = list()\n for buy, low in zip(buy_list, self.kite_state.lowPrice):\n if buy < 1:\n final_buy_list.append(low)\n else:\n final_buy_list.append(buy)\n\n self.kite_state.buyPrice = final_buy_list\n # TODO: Round off all calculations like this upto 2 decimal places, perfectly divisible by 0.05\n self.kite_state.profitablePrice = (np.array(final_buy_list) + np.array(self.kite_state.profitSlab)).tolist()\n self.kite_state.simulationInitSuccessful = True\n self.kite_state.save()\n\n\n def simulate_market(self):\n # Initialise\n ticker = KiteTicker(self.api_key, self.access_token)\n instrument_tokens = self.kite_state.companyTokens.copy()\n profitable_prices = self.kite_state.profitablePrice.copy()\n sell_dict = dict()\n price_state_dict = dict()\n profitable_dict = dict()\n first_tick = False\n \n # Building profitable dict\n for token, profitable_price in zip(instrument_tokens, profitable_prices):\n profitable_dict[token] = profitable_price\n\n # Defining the callbacks\n def on_ticks(tick, ticks_info):\n if len(instrument_tokens) == 0:\n tick.close()\n\n\n num_ticks = len(ticks_info)\n Logger.info('Ticking, number: {}'.format(num_ticks))\n now = datetime.now().astimezone(tzlocal())\n\n if num_ticks > 0:\n if now < self.end_time:\n Logger.info('Normal Time:->' + now.strftime(\"%H:%M:%S\"))\n for tick_info in ticks_info:\n current_instrument_token = tick_info['instrument_token']\n current_instrument_price = tick_info['depth']['buy'][0]['price']\n price_state_dict[current_instrument_token] = current_instrument_price\n if current_instrument_price >= profitable_dict[current_instrument_token]:\n sell_dict[current_instrument_token] = current_instrument_price\n tick.unsubscribe([current_instrument_token])\n instrument_tokens.remove(current_instrument_token)\n # tick.resubscribe()\n Logger.info('Unsubscribed token: ' + str(current_instrument_token))\n else:\n Logger.info('Closing Time:->' + now.strftime(\"%H:%M:%S\"))\n Logger.info('Price State dict: ' + str(price_state_dict))\n Logger.info('Sell dict: ' + str(sell_dict))\n unsold_instrument_tokens = list(set(price_state_dict.keys()) - set(sell_dict.keys()))\n Logger.info('Unsold instruments: ' + str(unsold_instrument_tokens))\n for instrument_token in unsold_instrument_tokens:\n sell_dict[instrument_token] = price_state_dict[instrument_token]\n instrument_tokens.remove(instrument_token)\n Logger.info('Sell dict after close: ' + str(sell_dict))\n\n \n \n\n def on_connect(tick, response):\n tick.subscribe(instrument_tokens)\n tick.set_mode(tick.MODE_FULL, instrument_tokens)\n Logger.info('Subscribed tokens: ' + str(instrument_tokens))\n\n def on_close(tick, code, reason):\n Logger.info('Ticker closed successfuly!')\n tick.stop()\n\n # Assign the callbacks.\n ticker.on_ticks = on_ticks\n ticker.on_connect = on_connect\n ticker.on_close = on_close\n \n # Connect to live ticker\n # if not ticker.is_connected():\n ticker.connect()\n Logger.info('Building final dict' + str(sell_dict))\n\n # Build final sell_dict in correct order\n\n sell_list = list()\n for key in profitable_dict.keys():\n try:\n sell_list.append(sell_dict[key])\n except KeyError as ex:\n Logger.err('Key error' + str(ex))\n # TODO: Make this failsafe more robust\n sell_list.append(0)\n\n self.kite_state.sellPrice = sell_list\n self.kite_state.save()\n\n def calculate_and_store_pnl(self):\n quantitiy = np.array(self.kite_state.numberOfStocksPerCompany)\n # Subtracting 1 from all companies as a failsafe for fund exhaustion, in case the stocks goes really high\n normalised_quantity = quantitiy - 1\n\n # Rounding negative values to 0\n normalised_quantity = normalised_quantity.clip(min=0)\n buy = np.array(self.kite_state.buyPrice)\n sell = np.array(self.kite_state.sellPrice)\n pnl_per_company = np.multiply(sell - buy, normalised_quantity)\n self.kite_state.pnlPerCompany = pnl_per_company.tolist()\n self.kite_state.pnl = float(np.sum(pnl_per_company))\n self.kite_state.save()\n Logger.info(\"Today's PNL: {}\".format(self.kite_state.pnl), push_to_slack=True)\n\n\n\n def get_request_token(self):\n Logger.info('Starting to fetch request token for Kite API')\n selenium = SeleniumDispatcher(headless=True)\n driver = selenium.get_driver()\n driver.get(self.kite.login_url())\n time.sleep(4)\n username_field = driver.find_element_by_xpath(\"//input[@type='text']\")\n username_field.send_keys(self.username)\n password_field = driver.find_element_by_xpath(\"//input[@type='password']\")\n password_field.send_keys(self.password)\n password_field.send_keys(Keys.ENTER)\n time.sleep(2)\n pin_field = driver.find_element_by_xpath(\"//input[@type='password']\")\n pin_field.send_keys(self.pin)\n pin_field.send_keys(Keys.ENTER)\n time.sleep(2)\n url = driver.current_url\n parsed = urlparse.urlparse(url)\n token = parse_qs(parsed.query)['request_token'][0]\n Logger.info('Request token received!')\n selenium.destroy_driver()\n return token\n\n \n\n \n ","sub_path":"nseAPI/src/kite_simulator/live_simulator.py","file_name":"live_simulator.py","file_ext":"py","file_size_in_byte":9422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"104077937","text":"# Copyright 2019 The TensorHub Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n# Load packages\nfrom tensorflow import keras\nfrom tensorhub.utilities.activations import relu, softmax\nfrom tensorhub.layers.inception_v4 import LayerA, LayerB, LayerC, ReductionLayerA, ReductionLayerB\n\n\nclass InceptionV4(keras.models.Model):\n \"\"\"InceptionV4 is a convolution neural network architecture that is one of the SOTA image classification architectures.\"\"\"\n\n def __init__(self, num_classes, act=relu, output_act=softmax):\n \"\"\"Class constructor.\n\n Arguments:\n num_classes {int} -- Number of class labels.\n\n Keyword Arguments:\n act {str/tensorhub.utilities.activation} -- Activation to be used with hidden layers of the network. (default: {'relu'})\n output_act {str/tensorhub.utilities.activation} -- Activation to be used with output layer. (default: {'softmax'})\n \"\"\"\n super(InceptionV4, self).__init__()\n # Se member variables\n self.num_classes = num_classes\n self.act = act\n self.output_act = output_act\n # Define layers\n # Stem block 1\n self.conv_1a = keras.layers.Conv2D(filters=32, kernel_size=(3, 3), strides=(2, 2), padding=\"valid\", activation=self.act)\n self.conv_1b = keras.layers.Conv2D(filters=32, kernel_size=(3, 3), padding=\"valid\", activation=self.act)\n self.conv_1c = keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation=self.act)\n self.conv_1d = keras.layers.Conv2D(filters=96, kernel_size=(3, 3), strides=(2, 2), padding=\"valid\")\n self.max_pool_layer_1 = keras.layers.MaxPool2D(pool_size=(3, 3), strides=(2, 2), padding=\"valid\")\n # Stem block 2\n self.conv_2a = keras.layers.Conv2D(filters=64, kernel_size=(1, 1))\n self.conv_2b = keras.layers.Conv2D(filters=96, kernel_size=(3, 3), padding=\"valid\")\n self.conv_2c = keras.layers.Conv2D(filters=64, kernel_size=(1, 1))\n self.conv_2d = keras.layers.Conv2D(filters=64, kernel_size=(7, 1))\n self.conv_2e = keras.layers.Conv2D(filters=64, kernel_size=(1, 7))\n self.conv_2f = keras.layers.Conv2D(filters=96, kernel_size=(3, 3), padding=\"valid\")\n # Stem block 3\n self.conv_3a = keras.layers.Conv2D(filters=192, kernel_size=(3, 3), padding=\"valid\")\n self.max_pool_layer_3 = keras.layers.MaxPool2D(strides=(2, 2), padding=\"valid\")\n self.concat_layer = keras.layers.concatenate(axis=-1)\n # Inception layer A\n self.inception_layer_a1 = LayerA()\n self.inception_layer_a2 = LayerA()\n self.inception_layer_a3 = LayerA()\n self.inception_layer_a4 = LayerA()\n self.reduction_a = ReductionLayerA()\n # Inception layer B\n self.inception_layer_b1 = LayerB()\n self.inception_layer_b2 = LayerB()\n self.inception_layer_b3 = LayerB()\n self.inception_layer_b4 = LayerB()\n self.inception_layer_b5 = LayerB()\n self.inception_layer_b6 = LayerB()\n self.inception_layer_b7 = LayerB()\n self.reduction_b = ReductionLayerB()\n # Inception layer C\n self.inception_layer_c1 = LayerC()\n self.inception_layer_c2 = LayerC()\n self.inception_layer_c3 = LayerC()\n # Average pooling\n self.avg_pool_layer_1 = keras.layers.AveragePooling2D()\n self.dropout_layer = keras.layers.Dropout(rate=0.2)\n # Softmax\n self.d1 = keras.layers.Dense(units=2048, activation=relu)\n self.d2 = keras.layers.Dense(units=self.num_classes, activation=self.output_act)\n\n def call(self, x):\n # Inception v4 stem\n # Stem block 1\n x = self.conv_1a(x)\n x = self.conv_1b(x)\n x = self.conv_1c(x)\n x1 = self.max_pool_layer(x)\n x2 = self.conv_1d(x)\n x = self.concat_layer([x1, x2])\n # Stem block 2\n x1 = self.conv_2a(x)\n x1 = self.conv_2b(x1)\n x2 = self.conv_2c(x)\n x2 = self.conv_2d(x2)\n x2 = self.conv_2e(x2)\n x2 = self.conv_2f(x2)\n x = self.concat_layer([x1, x2])\n # Stem block 3\n x1 = self.conv_3a(x)\n x2 = self.max_pool_layer_3(x)\n x = self.concat_layer([x1, x2])\n # Inception layer A\n x = self.inception_layer_a1(x)\n x = self.inception_layer_a2(x)\n x = self.inception_layer_a3(x)\n x = self.inception_layer_a4(x)\n x = self.reduction_a(x)\n # Inception layer B\n x = self.inception_layer_b1(x)\n x = self.inception_layer_b2(x)\n x = self.inception_layer_b3(x)\n x = self.inception_layer_b4(x)\n x = self.inception_layer_b5(x)\n x = self.inception_layer_b6(x)\n x = self.inception_layer_b7(x)\n x = self.reduction_b(x)\n # Inception layer C\n x = self.inception_layer_c1(x)\n x = self.inception_layer_c2(x)\n x = self.inception_layer_c3(x)\n # Tail\n x = self.avg_pool_layer_1(x)\n x = self.dropout_layer(x)\n # Softmax\n x = self.d1(x)\n x = self.d2(x)\n return x","sub_path":"tensorhub/models/image/classifiers/inception_v4.py","file_name":"inception_v4.py","file_ext":"py","file_size_in_byte":5673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"187650443","text":"from django.core.management.base import BaseCommand, CommandError\nfrom django.core.management import call_command\nimport os\nfrom lxml import etree\nfrom django.conf import settings\nfrom tripod2.items.types import Tripod2ItemManager\nfrom tripod2.www.portals import CollectionPortal\nfrom optparse import make_option\nimport logging\nlogger = logging.getLogger('console')\n\nclass Command(BaseCommand):\n args = ''\n help = ''\n\n option_list = BaseCommand.option_list + (\n make_option('-a', '--analyze',\n action = 'store_true',\n dest = 'analyze',\n help = 'Display collections and count items',\n ), \n )\n\n\n\n def analyze(self):\n root = etree.parse('{0}/endeca/DATAFILE-Duke.xml'.format(settings.XML_BASE_PATH))\n collections = {}\n total = 0\n records = root.xpath('/Resources/Resource')\n for r in records:\n id = r.get('id')\n \n (collectionid, shortid) = (id[:id.find('_')], id[id.find('_')+1:])\n if collectionid not in collections:\n collections[collectionid] = 0\n collections[collectionid] += 1\n logger.debug(len(records))\n for cid, cnt in collections.items():\n logger.debug('{0}: {1}'.format(cid, cnt))\n \n\n def handle(self, *args, **options):\n if options['analyze']:\n self.analyze()\n return\n \n \n collections = args\n if len(collections) == 0:\n from tripod2.local.conf import COLLECTIONS\n collections = COLLECTIONS.split('|')\n \n \n top = etree.Element('Resources')\n for collectionid in collections:\n logger.debug('Processing ' + collectionid)\n manager = Tripod2ItemManager()\n collection = manager.get_collection(collectionid)\n portal = CollectionPortal(collection)\n if portal.site != 'digitalcollections':\n continue\n if portal.status != 'published':\n continue\n\n mods = [\n 'tripod2.local.projects.{0}.items.streams.endeca',\n 'tripod2.items.streams.endeca',\n ]\n for mod in mods:\n try: \n m = __import__(mod, globals(), locals(), ['Tripod2EndecaCollection'])\n except ImportError:\n continue\n else:\n handler = m.Tripod2EndecaCollection(collection, top)\n handler.handle()\n\n\n fh = open('{0}/endeca/DATAFILE-Duke.xml'.format(settings.XML_BASE_PATH), 'w')\n fh.write(etree.tostring(top, pretty_print = True))\n fh.close()\n\n \n \n \n \n\n","sub_path":"management/commands/t2_dump2endeca.py","file_name":"t2_dump2endeca.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"529793998","text":"from setuptools import setup, find_packages\nimport os.path as op\nimport sys\n\nhere = op.abspath(op.dirname(__file__))\n\nversion = {}\nwith open(op.join(here, 'thermostate', '_version.py'), mode='r') as version_file:\n exec(version_file.read(), version)\n\nwith open(op.join(here, 'README.md'), mode='r') as readme_file:\n readme = readme_file.read()\n\nwith open(op.join(here, 'CHANGELOG.md'), mode='r') as changelog_file:\n changelog = changelog_file.read()\n\nlong_description = readme + '\\n\\n' + changelog\n\ninstall_requires = [\n 'coolprop>=6.1.0,<6.3',\n 'pint>=0.7.2,<0.9',\n]\n\ntests_require = [\n 'pytest>=3.0.0',\n 'pytest-cov>=2.3.1',\n]\n\nneeds_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)\nsetup_requires = ['pytest-runner'] if needs_pytest else []\n\nsetup(\n name='thermostate',\n version=version['__version__'],\n description='A package to manage thermodynamic states',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/bryanwweber/thermostate',\n author='Bryan W. Weber',\n author_email='bryan.w.weber@gmail.com',\n license='BSD-3-clause',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: BSD License',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Operating System :: MacOS',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: Microsoft :: Windows :: Windows 10',\n 'Operating System :: Microsoft :: Windows :: Windows 7',\n 'Operating System :: Microsoft :: Windows :: Windows 8',\n 'Operating System :: Microsoft :: Windows :: Windows 8.1',\n 'Operating System :: POSIX',\n 'Operating System :: POSIX :: Linux',\n ],\n packages=find_packages(),\n install_requires=install_requires,\n tests_require=tests_require,\n setup_requires=setup_requires,\n python_requires='~=3.5',\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"32889488","text":"import pyfftw as ft \nimport numpy as np\nfrom mpi4py import MPI\nimport math\nimport sys\nimport SOAPtdb\n\n### This scripts test the three classes written for FFT, IFFT and Energy Spectrum ###\n################################################################################\n\nfrom FFT3Dfield import FFT3Dfield\nfrom IFFT3Dfield import IFFT3Dfield\nfrom EnergySpectrum import EnergySpectrum\nfrom Filters import Filters\nfrom RandomNumberGenerator import RandomNumberGenerator\n\ncomm = MPI.COMM_WORLD\nmy_id = comm.Get_rank()\nnproc = comm.Get_size()\n\nnx=1024\nny=1024\nnz=1024\nidp=8\n\nscrout=sys.stdout\nsys.stdout.write('MPI id={0:4d} nx={1:6d} ny={2:6d} nz={3:6d}\\n'. \\\n format(my_id,nx,ny,nz))\n\nlx=nx//nproc\nly=ny\nlz=nz\nlz_half=lz//2\nnek=int(math.sqrt(2.0)/3*nx)\n\n## Initialize the velocity field having a size of (lx,ly,lz)\nvx=ft.zeros_aligned((lx,ly,lz), dtype='float32')\nvy=ft.zeros_aligned((lx,ly,lz), dtype='float32')\nvz=ft.zeros_aligned((lx,ly,lz), dtype='float32')\n\n## Generate random field (Complex) between -1 and 1\n#myRandNumber=RandomNumberGenerator()\n#cvx=myRandNumber.GetRandNumber_complex(-1.0,1.0,lx,ly,lz_half+1)\n#cvy=myRandNumber.GetRandNumber_complex(-1.0,1.0,lx,ly,lz_half+1)\n#cvz=myRandNumber.GetRandNumber_complex(-1.0,1.0,lx,ly,lz_half+1)\n\n## Populate velocity field from the Database\ncomm.Barrier(); t1=MPI.Wtime()\nSOAPtdb.loadvel(vx,vy,vz,lx,ly,lz,my_id)\ncomm.Barrier(); t2=MPI.Wtime()\nif(my_id==0):\n sys.stdout.write('Load velocity field cost: {0:.2f} seconds\\n'.format(t2-t1))\n \n## Get wavenumber:\nmyEnergySpc=EnergySpectrum()\nkx,ky,kz=myEnergySpc.FindWavenumber(lx,ly,lz,my_id)\nk2=np.zeros((lx,ly,lz_half+1), dtype='float32')\nnp.copyto(k2,kx*kx+ky*ky+kz*kz)\nk2[0,0,0]=1e-6\n\n## Get velocity field in wavenumber space:\ncomm.Barrier(); t1=MPI.Wtime()\nmyFFT3Dfield=FFT3Dfield()\ncvx=myFFT3Dfield.GetFFT3Dfield(vx,lx,ly,lz,nproc,my_id)\ncvy=myFFT3Dfield.GetFFT3Dfield(vy,lx,ly,lz,nproc,my_id)\ncvz=myFFT3Dfield.GetFFT3Dfield(vz,lx,ly,lz,nproc,my_id)\ncomm.Barrier(); t2=MPI.Wtime()\nif(my_id==0):\n sys.stdout.write('3 R-C FFTs cost: {0:.2f} seconds\\n'.format(t2-t1))\n\n############################# unfiltered ############################# \n## Get energy spectrum in Fourier space\ncomm.Barrier(); t1=MPI.Wtime()\nek_all=myEnergySpc.GetSpectrumFromComplexField(cvx,cvy,cvz,k2,lx,ly,lz,nek,nproc,my_id)\ncomm.Barrier(); t2=MPI.Wtime()\n\n############################# kappa_cutoff=100 #############################\nkappa_c=100.0\n\n## Filter the velocity field using the GAUSSIAN filter\nmyFilter=Filters()\ncvx1=myFilter.FilterTheComplexField(cvx,k2,kappa_c,'gaussian')\ncvy1=myFilter.FilterTheComplexField(cvy,k2,kappa_c,'gaussian')\ncvz1=myFilter.FilterTheComplexField(cvz,k2,kappa_c,'gaussian')\n\n## Get energy spectrum in Fourier space\ncomm.Barrier(); t1=MPI.Wtime()\nek_gaussian=myEnergySpc.GetSpectrumFromComplexField(cvx1,cvy1,cvz1,k2,lx,ly,lz,nek,nproc,my_id)\ncomm.Barrier(); t2=MPI.Wtime()\ndel cvx1\ndel cvy1\ndel cvz1\n\n## Filter the velocity field using the SHARP filter\nmyFilter=Filters()\ncvx1=myFilter.FilterTheComplexField(cvx,k2,kappa_c,'sharp')\ncvy1=myFilter.FilterTheComplexField(cvy,k2,kappa_c,'sharp')\ncvz1=myFilter.FilterTheComplexField(cvz,k2,kappa_c,'sharp')\n\n## Get energy spectrum in Fourier space\ncomm.Barrier(); t1=MPI.Wtime()\nek_sharp=myEnergySpc.GetSpectrumFromComplexField(cvx1,cvy1,cvz1,k2,lx,ly,lz,nek,nproc,my_id)\ncomm.Barrier(); t2=MPI.Wtime()\ndel cvx1\ndel cvy1\ndel cvz1\n\n## Filter the velocity field using the BOX filter\nmyFilter=Filters()\ncvx1=myFilter.FilterTheComplexField(cvx,k2,kappa_c,'box')\ncvy1=myFilter.FilterTheComplexField(cvy,k2,kappa_c,'box')\ncvz1=myFilter.FilterTheComplexField(cvz,k2,kappa_c,'box')\n\n## Get energy spectrum in Fourier space\ncomm.Barrier(); t1=MPI.Wtime()\nek_box=myEnergySpc.GetSpectrumFromComplexField(cvx1,cvy1,cvz1,k2,lx,ly,lz,nek,nproc,my_id)\ncomm.Barrier(); t2=MPI.Wtime()\ndel cvx1\ndel cvy1\ndel cvz1\n\n#if(my_id==0):\n# sys.stdout.write('Compute E(k) cost: {0:.2f} seconds\\n'.format(t2-t1))\n# sys.stdout=open(workdir+'ek.txt','wt')\n# for i in range(nek): \n# sys.stdout.write('{0:15.1f} {1:15.6e}\\n'.format(i+1,ek[i]))\n# sys.stdout.close()\n# sys.stdout=scrout","sub_path":"ClassRepository/test4Class_Filters_all.py","file_name":"test4Class_Filters_all.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"284003494","text":"import openproblems\nimport sys\n\n\ndef main(task_name, dataset_name, output_file):\n task = eval(\"openproblems.tasks.{}\".format(task_name))\n datasets = getattr(task, \"datasets\")\n dataset = getattr(datasets, dataset_name)\n adata = dataset(test=False)\n adata.write_h5ad(output_file)\n\n\nif __name__ == \"__main__\":\n main(*sys.argv[1:])\n","sub_path":"scripts/load_dataset.py","file_name":"load_dataset.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"602787064","text":"\"\"\"\nBinary Gap\n\"\"\"\n\n\ndef binary_gap(n: int) -> int:\n \"\"\"\n Given a positive integer n, find and return the longest distance\n between two consecutive 1's in the binary representation of n.\n\n :param n: a positive integer n\n :return: the longest distance between two consecutive 1's in the\n binary representation of n\n\n >>> binary_gap(22)\n 2\n >>> binary_gap(5)\n 2\n >>> binary_gap(6)\n 1\n >>> binary_gap(8)\n 0\n \"\"\"\n b = bin(n)[2:]\n max = 0\n prev = 0\n cur = 0\n while cur < len(b) and len(b) - 1 - prev > max:\n if b[cur] == '1':\n l = cur - prev\n if l > max:\n max = l\n prev = cur\n cur += 1\n return max\n","sub_path":"longest_binary_gap.py","file_name":"longest_binary_gap.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"486244583","text":"import os\n\nimport gensim\nfrom gensim.models.doc2vec import TaggedDocument\n\nfrom src.Corpus.Corpus import Corpus\nfrom src.Labels import Labels\n\nimport numpy as np\n\n\nclass ReviewPolarityCorpus(Corpus):\n PATH_TO_POLARITY_DATA = '../../Datasets/review_polarity/txt_sentoken/'\n POS_LABEL = 'pos'\n NEG_LABEL = 'neg'\n\n @property\n def name(self):\n return 'PL04'\n\n def __init__(self, tokenizer):\n self.tokenizer = tokenizer\n\n pos_path = os.path.join(self.PATH_TO_POLARITY_DATA, self.POS_LABEL)\n neg_path = os.path.join(self.PATH_TO_POLARITY_DATA, self.NEG_LABEL)\n\n pos_data_stream = self.stream_documents(Labels.strong_pos, pos_path, os.listdir(pos_path))\n neg_data_stream = self.stream_documents(Labels.strong_neg, neg_path, os.listdir(neg_path))\n\n self.X_pos_data, self.y_pos_labels = zip(*pos_data_stream)\n self.X_neg_data, self.y_neg_labels = zip(*neg_data_stream)\n\n def stream_polarity_documents(self, dir_name):\n \"\"\"Iterate over documents of the review polarity data set.\n\n Documents are represented as strings.\n\n \"\"\"\n\n if os.path.exists(dir_name):\n for file_name in os.listdir(dir_name):\n with open(os.path.join(dir_name, file_name), \"r\") as doc:\n content = doc.read()\n yield content\n\n def stream_documents(self, label, path, file_names):\n \"\"\"Iterate over documents in the given path.\n\n Documents are represented as strings.\n\n \"\"\"\n\n if os.path.exists(path):\n for file_name in file_names:\n with open(os.path.join(path, file_name), \"r\") as doc:\n content = doc.read()\n yield self.tokenizer(content), label\n\n def __iter__(self):\n dir_name = os.path.join(self.PATH_TO_POLARITY_DATA, self.POS_LABEL)\n for file in self.stream_polarity_documents(dir_name):\n yield self.tokenizer(file)\n\n dir_name = os.path.join(self.PATH_TO_POLARITY_DATA, self.NEG_LABEL)\n for file in self.stream_polarity_documents(dir_name):\n yield self.tokenizer(file)\n\n def get_training_data(self):\n\n X_pos_train_data = self.X_pos_data[:800]\n y_pos_train_labels = self.y_pos_labels[:800]\n\n X_neg_train_data = self.X_neg_data[:800]\n y_neg_train_labels = self.y_neg_labels[:800]\n\n return X_pos_train_data + X_neg_train_data, y_pos_train_labels + y_neg_train_labels\n\n def get_training_documents(self, model = gensim.models.Doc2Vec):\n number_of_training_documents = 1600\n mid_way = 800\n train_arrays = np.zeros((number_of_training_documents, model.vector_size))\n train_labels = np.zeros(number_of_training_documents)\n\n for i in range(mid_way):\n prefix_train_pos = 'strong_pos_' + str(i)\n prefix_train_neg = 'strong_neg_' + str(i)\n train_arrays[i] = model.docvecs[prefix_train_pos]\n train_arrays[mid_way + i] = model.docvecs[prefix_train_neg]\n train_labels[i] = Labels.strong_pos\n train_labels[mid_way + i] = Labels.strong_neg\n\n return train_arrays, train_labels\n\n def get_test_data(self):\n X_pos_test_data = self.X_pos_data[800:]\n y_pos_test_labels = self.y_pos_labels[800:]\n\n X_neg_test_data = self.X_neg_data[800:]\n y_neg_test_labels = self.y_neg_labels[800:]\n\n return X_pos_test_data + X_neg_test_data, y_pos_test_labels + y_neg_test_labels\n\n def get_testing_documents(self, model = gensim.models.Doc2Vec):\n number_of_testing_documents = 400\n mid_way = 200\n test_arrays = np.zeros((number_of_testing_documents, model.vector_size))\n test_labels = np.zeros(number_of_testing_documents)\n\n for i in range(mid_way):\n prefix_train_pos = 'strong_pos_' + str(800 + i)\n prefix_train_neg = 'strong_neg_' + str(800 + i)\n test_arrays[i] = model.docvecs[prefix_train_pos]\n test_arrays[mid_way + i] = model.docvecs[prefix_train_neg]\n test_labels[i] = Labels.strong_pos\n test_labels[mid_way + i] = Labels.strong_neg\n\n return test_arrays, test_labels\n\n def to_array(self):\n self.sentences = []\n\n dir_name = os.path.join(self.PATH_TO_POLARITY_DATA, self.POS_LABEL)\n for idx, file in enumerate(self.stream_polarity_documents(dir_name)):\n self.sentences.append(TaggedDocument(self.tokenizer(file), ['strong_pos_%s' % idx]))\n\n dir_name = os.path.join(self.PATH_TO_POLARITY_DATA, self.NEG_LABEL)\n for idx, file in enumerate(self.stream_polarity_documents(dir_name)):\n self.sentences.append(TaggedDocument(self.tokenizer(file), ['strong_neg_%s' % idx]))\n\n return self.sentences\n\n def sentences_perm(self):\n return np.random.permutation(self.sentences).tolist()","sub_path":"src/Corpus/ReviewPolarityCorpus.py","file_name":"ReviewPolarityCorpus.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"268244254","text":"# -*- coding: utf-8 -*-\n# @Time : 2021-01-29 01:36\n# @Author : Keefe\n# @FileName: re-context.py\n# @Software: PyCharm\n# @Blog :http://www.aiyuanzhen.com/\n'''\n去空格去换行\n使用方法:\npython re-context.py xxx.txt\n'''\nimport re\nimport sys\n\ndef main():\n \n with open(sys.argv[1],'r',encoding='utf-8')as f:\n #print(f.read())\n res = \"\".join(f.readlines()).replace('\\n', '').replace('\\r', '').replace(' ', '')\n print(res)\nif __name__ == '__main__':\n main()\n","sub_path":"去空格去换行/re_context.py","file_name":"re_context.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"278325992","text":"import cv2\nimport numpy as np\nfrom numpy.lib.stride_tricks import as_strided\nimport scipy.sparse\nimport scipy.sparse.linalg\n\n\ndef _rolling_block(A, block=(3, 3)):\n shape = (A.shape[0] - block[0] + 1, A.shape[1] - block[1] + 1) + block\n strides = (A.strides[0], A.strides[1]) + A.strides\n return as_strided(A, shape=shape, strides=strides)\n\n\ndef compute_laplacian(img, mask=None, eps=10**(-7), win_rad=1):\n\n win_size = (win_rad * 2 + 1) ** 2\n h, w, d = img.shape\n c_h, c_w = h - 2 * win_rad, w - 2 * win_rad\n win_diam = win_rad * 2 + 1\n\n indsM = np.arange(h * w).reshape((h, w))\n ravelImg = img.reshape(h * w, d)\n win_inds = _rolling_block(indsM, block=(win_diam, win_diam))\n\n win_inds = win_inds.reshape(c_h, c_w, win_size)\n if mask is not None:\n mask = cv2.dilate(\n mask.astype(np.uint8),\n np.ones((win_diam, win_diam), np.uint8)\n ).astype(np.bool)\n win_mask = np.sum(mask.ravel()[win_inds], axis=2)\n win_inds = win_inds[win_mask > 0, :]\n else:\n win_inds = win_inds.reshape(-1, win_size)\n\n \n winI = ravelImg[win_inds]\n\n win_mu = np.mean(winI, axis=1, keepdims=True)\n win_var = np.einsum('...ji,...jk ->...ik', winI, winI) / win_size - np.einsum('...ji,...jk ->...ik', win_mu, win_mu)\n\n inv = np.linalg.inv(win_var + (eps/win_size)*np.eye(3))\n\n X = np.einsum('...ij,...jk->...ik', winI - win_mu, inv)\n vals = np.eye(win_size) - (1.0/win_size)*(1 + np.einsum('...ij,...kj->...ik', X, winI - win_mu))\n\n nz_indsCol = np.tile(win_inds, win_size).ravel()\n nz_indsRow = np.repeat(win_inds, win_size).ravel()\n nz_indsVal = vals.ravel()\n L = scipy.sparse.coo_matrix((nz_indsVal, (nz_indsRow, nz_indsCol)), shape=(h*w, h*w))\n return L\n","sub_path":"laplacian.py","file_name":"laplacian.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"589850294","text":"import datetime\n# timer\n\nclass Cds:\n\tdef __init__(self, pin, GPIO):\n\t\tself.__pin = pin\n\t\tself.GPIO = GPIO\n\t\tself.setting()\n\n\tdef setting(self):\n\t\tself.GPIO.setup(self.__pin, self.GPIO.IN)\n\n\tdef read(self):\n\t\treturn self.GPIO.input(self.__pin)\n\nclass Control:\n\tdef __init__(self, pin, GPIO, topic, topicNum):\n\t\tself.cds_instance = Cds(pin, GPIO)\n\t\tself.topic = topic\n\t\tself.topicNum = topicNum\n\n\t\tself.detectCheckLastTime = \"\"\n\t\tself.lastdata = 0\n\n\tdef check(self):\n\t\tread = self.cds_instance.read()\n\t\t\n\t\tif read == False and self.lastdata == 0 : \n\t\t\tself.lastdata = 1 # on\n\t\t\tself.topic.setSendMessageTopic(0, self.topicNum, self.lastdata)\n\t\t\tprint(\"MQTT-send - \" + \"cds\")\n\n\t\t\treturn False\n\t\telif read == True and self.lastdata == 1 :\n\t\t\tself.lastdata = 0 # off\n\t\t\tself.topic.setSendMessageTopic(0, self.topicNum, self.lastdata)\n\n\t\t\tprint(\"MQTT-send - \" + \"cds\")\n\t\t\treturn True\n\n\tdef getNowData(self):\n\t\t\tself.topic.setSendMessageTopic(0, self.topicNum, self.lastdata)","sub_path":"sensingData/Cds.py","file_name":"Cds.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"170698414","text":"from render.models import Response\nfrom django_sensible import SECURE_CONFIG\nimport json\nimport urllib\nfrom django_sensible import oauth2\nfrom django_sensible.models import Scope\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\n\ndef sync_with_study(subtle=False, user=None):\n\tif not user == None:\n\t\tno = len(Response.objects.filter(synced_with_study=False, user=user))\n\telse:\n\t\tno = len(Response.objects.filter(synced_with_study=False))\n\ti = 0\n\tsuccess = 0\n\tif not user == None:\n\t\tall_responses = Response.objects.filter(synced_with_study=False, user=user)\n\telse:\n\t\tall_responses = Response.objects.filter(synced_with_study=False)\n\t\n\tfor response in all_responses:\n\t\tvalues = {}\n\t\tvalues['form_version'] = str(response.form_version)\n\t\tvalues['variable_name'] = str(response.variable_name)\n\t\tvalues['response'] = str(response.response.encode('utf-8'))\n\t\tvalues['last_answered'] = str(response.last_answered)\n\t\tvalues['human_readable_question'] = str(response.human_readable_question.encode('utf-8'))\n\t\tvalues['human_readable_response'] = str(response.human_readable_response.encode('utf-8'))\n\t\tvalues = urllib.quote(json.dumps(values))\n\n\t\ttoken = oauth2.getToken(response.user, Scope.objects.get(scope='connector_questionnaire.input_form_data'))\n\n\t\tr = oauth2.query(settings.SERVICE_UPLOAD_URL, token, '&doc='+values, SECURE_CONFIG.CLIENT_ID, SECURE_CONFIG.CLIENT_SECRET, settings.APPLICATION_URL[:-1]+reverse('grant'), settings.SERVICE_REFRESH_TOKEN_URL)\n\t\tif 'ok' in r:\n\t\t\tresponse.synced_with_study = True\n\t\t\tresponse.save()\n\t\t\tsuccess += 1\n\n\t\ti += 1\n\t\tif subtle and i == 1: break\n\treturn (i, success)\n","sub_path":"questionnaires/backend/sync_with_study.py","file_name":"sync_with_study.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"174802970","text":"# We have some clickstream data that we gathered on our client's website. Using cookies, we collected snippets of users' anonymized URL histories while they browsed the site. The histories are in chronological order and no URL was visited more than once per person.\n\n# Write a function that takes two users' browsing histories as input and returns the longest contiguous sequence of URLs that appears in both.\n\n# Sample input:\n\n# user0 = [\"/start\", \"/pink\", \"/register\", \"/orange\", \"/red\", \"a\"]\n# user1 = [\"/start\", \"/green\", \"/blue\", \"/pink\", \"/register\", \"/orange\", \"/one/two\"]\n# user2 = [\"a\", \"/one\", \"/two\"]\n# user3 = [\"/red\", \"/orange\", \"/yellow\", \"/green\", \"/blue\", \"/purple\", \"/white\", \"/amber\", \"/HotRodPink\", \"/BritishRacingGreen\"]\n# user4 = [\"/red\", \"/orange\", \"/amber\", \"/random\", \"/green\", \"/blue\", \"/purple\", \"/white\", \"/lavender\", \"/HotRodPink\", \"/BritishRacingGreen\"]\n# user5 = [\"a\"]\n\n# Sample output:\n\n# findContiguousHistory(user0, user1)\n# /pink\n# /register\n# /orange\n\n# findContiguousHistory(user1, user2)\n# (empty)\n\n# findContiguousHistory(user2, user0)\n# a\n\n# findContiguousHistory(user5, user2)\n# a\n\n# findContiguousHistory(user3, user4)\n# /green\n# /blue\n# /purple\n# /white\n\n# findContiguousHistory(user4, user3)\n# /green\n# /blue\n# /purple\n# /white\n\n# n: length of the first user's browsing history\n# m: length of the second user's browsing history\n\n\nuser0 = [\"/start\", \"/pink\", \"/register\", \"/orange\", \"/red\", \"a\"]\nuser1 = [\"/start\", \"/green\", \"/blue\", \"/pink\", \"/register\", \"/orange\", \"/one/two\"]\nuser2 = [\"a\", \"/one\", \"/two\"]\nuser3 = [\"/red\", \"/orange\", \"/yellow\", \"/green\", \"/blue\", \"/purple\", \"/white\", \"/amber\", \"/HotRodPink\", \"/BritishRacingGreen\"]\nuser4 = [\"/red\", \"/orange\", \"/amber\", \"/random\", \"/green\", \"/blue\", \"/purple\", \"/white\", \"/lavender\", \"/HotRodPink\", \"/BritishRacingGreen\"]\nuser5 = [\"a\"]\n\n\nstart1=2\nstart2=2\n\n\n\n\ndef count_hits(input_arr):\n\n result = {}\n for input in input_arr:\n #print(input)\n count_full_urls = input.split(\",\")\n count = int(count_full_urls[0])\n url = count_full_urls[1]\n domains = url.split(\".\")\n for i in range(len(domains)):\n sub_domain = \".\".join(domains[i:])\n if sub_domain in result:\n result[sub_domain] = result[sub_domain]+count\n else:\n result[sub_domain] = count\n return result\n\n\ndef findContiguousHistory(user1_history, user2_history):\n\n temp_dict={}\n for index,history in enumerate(user2_history):\n temp_dict[history] = index\n print(temp_dict)\n max_tuple = (0,0)\n\n i =0\n result = []\n while i < len(user1_history):\n count = 0\n history = user1_history[i]\n if history in temp_dict:\n for j in range(temp_dict[history],len(user2_history)):\n if i < len(user1_history) and user1_history[i] == user2_history[j]:\n count += 1\n i += 1\n\n else:\n if max_tuple[1] - max_tuple[0] < count:\n max_tuple = (temp_dict[history],j)\n break\n else:\n i += 1\n\n for i in range(max_tuple[0],max_tuple[1]):\n result.append(user2_history[i])\n return result\n\nprint(findContiguousHistory(user4,user3))\n\n\n\n","sub_path":"karat/wayfair.py","file_name":"wayfair.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"401019576","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\n# Author:HuanBing\n#类的使用,自定义with语句\nclass Testwith():\n def __enter__(self):\n print('run')\n def __exit__(self,exc_type,exc_val,exc_tb):\n if exc_tb is None:\n print('正常结束')\n else:\n print('has error %s'%exc_tb)\n\nwith Testwith():\n print('Test is running')\n raise NameError('testNameError')\n\n\n","sub_path":"pythonjike/class/with_test.py","file_name":"with_test.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"551223395","text":"#!/usr/bin/env python\n#Edit by Saad Alabdulsalam\n\nfrom .packet_direction import PacketDirection\n\n\ndef get_packet_flow_key(packet, direction) -> tuple:\n\tif \"TCP\" in packet:\n\t\tprotocol = \"TCP\"\n\telif \"UDP\" in packet:\n \tprotocol = \"UDP\"\n\telse:\n\t\traise Exception(\"Only TCP protocols are supported.\")\n\n\tif direction == PacketDirection.FORWARD:\n\t\tdest_ip = packet[\"IP\"].dst\n\t\tsrc_ip = packet[\"IP\"].src\n\t\tsrc_port = packet[protocol].sport\n\t\tdest_port = packet[protocol].dport\n\t\tsrc_ether= packet[\"Ether\"].src\n\telse:\n\t\tdest_ip = packet[\"IP\"].src\n\t\tsrc_ip = packet[\"IP\"].dst\n\t\tsrc_port = packet[protocol].dport\n\t\tdest_port = packet[protocol].sport\n\t\tsrc_ether= packet[\"Ether\"].src\n\treturn dest_ip, src_ip, src_port, dest_port, src_ether\n","sub_path":"packet_flow_key.py","file_name":"packet_flow_key.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"295951739","text":"# as quick as a flash soln for code eval by steven a dunn\n\nimport sys\n\ndef partition(vals, lo, hi):\n\ti, j, pivot = lo, hi, vals[lo]\n\twhile True:\n\t\twhile vals[i] < pivot:\n\t\t\ti += 1\n\t\twhile vals[j] > pivot:\n\t\t\tj -= 1\n\t\tif i >= j:\n\t\t\treturn j\n\t\tvals[i], vals[j] = vals[j], vals[i]\n\ndef quick_sort(vals, lo, hi):\n\tglobal pivots\n\tif lo < hi:\n\t\tp = partition(vals, lo, hi)\n\t\tpivots += 1\n\t\tquick_sort(vals, lo, p-1)\n\t\tquick_sort(vals, p+1, hi)\n\npivots = 0\nf = open(sys.argv[1], 'r')\nfor line in f:\n\tvals = list(map(int, line.strip().split()))\n\tquick_sort(vals, 0, len(vals)-1)\n\tprint (pivots)\n\tpivots = 0\nf.close()","sub_path":"AsQuickAsAFlash/py3/qs.py","file_name":"qs.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"426715198","text":"\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom task.tasks import bg_run_crawler, prueba2\nfrom background_task.models import Task\nfrom background_task.models_completed import CompletedTask\nimport subprocess\nimport datetime\nimport time\nfrom utilities import write_in_a_file\nimport threading\nfrom background_task import background\n\n\n\n\ndef init_view(request):\n print('init_view')\n print(f'request.user.is_authenticated: {request.user.is_authenticated}')\n if not request.user.is_authenticated:\n return redirect('login')\n else:\n template_name = \"index.html\"\n return render(request, template_name)\n\n\n\n\nif __name__ != \"__main__\":\n print(f'EXECUTING DJANGO by {__name__}')\n\n\n def init_subprocess_process_tasks():\n print('init_subprocess_process_tasks')\n write_in_a_file(f'init_subprocess_process_tasks at {str(datetime.datetime.now())}', {}, 'bg-task.txt')\n @background(schedule=1)\n def inited_subprocess_process_tasks():\n pass\n\n\n def run_subprocess_process_tasks():\n write_in_a_file(f'init_subprocess_process_tasks at {str(datetime.datetime.now())} -- thread', {}, 'bg-task.txt')\n # Retard added to guarantee that background function is added to the Background Tasks Queue before run process_tasks\n time.sleep(5)\n today = datetime.date.today()\n try:\n last_bg_task = Task.objects.filter(task_name=\"ie_django.views.inited_subprocess_process_tasks\").latest('run_at')\n except:\n last_bg_task = None\n try:\n last_bg_ctask = CompletedTask.objects.filter(task_name=\"ie_django.views.inited_subprocess_process_tasks\").latest('run_at')\n except:\n last_bg_ctask = None\n\n task = last_bg_task if last_bg_task else last_bg_ctask\n try:\n task_date = datetime.datetime.date(task.run_at)\n except:\n task_date = None\n print(today)\n print(task_date)\n if (not task_date) or (task_date != today):\n inited_subprocess_process_tasks(repeat=None) # function added to the Background Tasks Queue\n write_in_a_file(f'init_subprocess_process_tasks at {str(datetime.datetime.now())} NO ha sido ejecutado por lo que se va a ejecutar', {}, 'bg-task.txt')\n print('init_subprocess_process_tasks --- no se ha ejecutado')\n print('- - - - Se va a ejecutar subprocess.popen')\n command = ['python', 'manage.py', 'process_tasks']\n sp = subprocess.Popen(command)\n write_in_a_file(f'init_subprocess_process_tasks at {str(datetime.datetime.now())} se van a ejecutar las tareas de la cola', {}, 'bg-task.txt')\n else:\n write_in_a_file(f'init_subprocess_process_tasks at {str(datetime.datetime.now())} ya ha sido ejecutado', {}, 'bg-task.txt')\n print('init_subprocess_process_tasks --- ha sido ejecutado')\n\n thread = threading.Thread(target=run_subprocess_process_tasks)\n thread.start()\n\n\n def execute_background_task():\n print('execute_background_task')\n write_in_a_file(f'execute_background_task at {str(datetime.datetime.now())}', {}, 'bg-task.txt')\n #if not Task.objects.filter(task_name=\"task.tasks.bg_run_crawler\"):\n if not Task.objects.filter(task_name=\"task.tasks.prueba2\"):\n bg_run_crawler(repeat=300, repeat_until=None) # function added to the Background Tasks Queue\n #prueba2(repeat=20)\n print('execute_background_task - - - - tarea añadida a la cola')\n write_in_a_file(f'execute_background_task at {str(datetime.datetime.now())} tarea añadida a la cola', {}, 'bg-task.txt')\n else:\n print('execute_background_task ---ya existe la tarea en la cola')\n write_in_a_file(f'execute_background_task at {str(datetime.datetime.now())} la tarea ya ha sido añadida a la cola', {}, 'bg-task.txt')\n\n\n init_subprocess_process_tasks()\n execute_background_task()\n\n","sub_path":"src/ie_django/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"534303798","text":"#coding:utf-8\nimport numpy as np\nimport datetime\nfrom sklearn import svm\nfrom sklearn.cross_validation import train_test_split\nfrom matplotlib.pyplot import axis\nstarttime = datetime.datetime.now()\npathTrain = u'C:/Users/ssh32/Desktop/cff/newtfidf/BDCI/tfidf5000.txt'\npathTest = u'C:/Users/ssh32/Desktop/cff/newtfidf/BDCI/tfidfTestTemp.txt'\ninput_fileTest = open(\"C:/Users/ssh32/Desktop/cff/newtfidf/BDCI/penalize.txt\",\"a\")\ntrainData = np.loadtxt(pathTrain, dtype=float)\nx_test = np.loadtxt(pathTest, dtype=float)\n\nx_train, y_train = np.split(trainData, (4076,), axis=1)\n#\nx_train, x_test, y_train, y_test = train_test_split(x_train, y_train, random_state=1, train_size=0.8)\n#clf = svm.SVC(C=0.2, kernel='linear', decision_function_shape='ovr')\n#clf = svm.SVC(C=0.8, kernel='rbf', gamma=20, decision_function_shape='ovr')0.381666666667\nclf = svm.SVC(C=0.8, kernel='poly', gamma=200, decision_function_shape='ovr')\nclf.fit(x_train, y_train.ravel())\nprint (clf.score(x_train, y_train))\n\ny_hat1 = clf.predict(x_train)\ny_hat2 = clf.predict(x_test)\nprint (clf.score(x_test, y_test))\n\nfor i in y_hat2:\n input_fileTest.write(str(int(i))+\"\\t\\n\")\nendtime = datetime.datetime.now()\nprint (endtime - starttime).seconds","sub_path":"SVM/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"17394579","text":"from collections import namedtuple\nimport math\nimport numpy as np\nimport tensorflow as tf\nimport IPython\nWEIGHT_DEFAULT_NAME = \"weights\"\nBIAS_DEFAULT_NAME = \"bias\"\n\n\n# TODO(vpong): Use this namedtuple when possible\nMlpConfig = namedtuple('MlpConfig', ['W_init', 'b_init', 'nonlinearity'])\n\n\ndef weight_variable(\n shape,\n initializer=None,\n name=WEIGHT_DEFAULT_NAME,\n):\n \"\"\"\n Return a variable with the given shape.\n\n :param initializer: TensorFlow initializer\n :param name:\n :param shape:\n \"\"\"\n if initializer is None:\n initializer = tf.random_uniform_initializer(minval=-3e-3,\n maxval=3e-3)\n var = tf.get_variable(name, shape, initializer=initializer)\n return var\n\n\ndef bias_variable(\n shape,\n initializer=None,\n name=BIAS_DEFAULT_NAME,\n):\n \"\"\"\n Return a bias variable with the given shape.\n\n :param initializer: TensorFlow initializer\n :param name:\n :param shape:\n \"\"\"\n if initializer is None:\n initializer = tf.constant_initializer(0.)\n return weight_variable(shape,\n initializer=initializer,\n name=name)\n\ndef conv(\n last_layer,\n weight_shape,\n nonlinearity,\n strides=[1,3,3,1],\n W_initializer=None,\n b_initializer=None,\n W_name=WEIGHT_DEFAULT_NAME,\n bias_name=BIAS_DEFAULT_NAME,\n):\n\n \"\"\"\n Create a conv layer\n\n :param W_initializer\n :param b_initializer\n :param bias_name: String for the bias variable names\n :param W_name: String for the weight matrix variables names\n :param last_layer: Input tensor\n :param last_size: Size of the input tensor\n :param new_size: Size of the output tensor\n \"\"\"\n W = weight_variable(weight_shape,\n initializer=W_initializer,\n name=W_name)\n\n b = bias_variable(weight_shape[-1],\n initializer=b_initializer,\n name=bias_name)\n\n #get the linear output from the conv layer\n conv = tf.nn.conv2d(last_layer,\n W,\n strides=strides,\n padding=\"SAME\")\n\n return nonlinearity(tf.nn.bias_add(conv,b))\n\n\ndef linear(\n last_layer,\n last_size,\n new_size,\n W_initializer=None,\n b_initializer=None,\n W_name=WEIGHT_DEFAULT_NAME,\n bias_name=BIAS_DEFAULT_NAME,\n):\n \"\"\"\n Create a linear layer.\n\n :param W_initializer:\n :param b_initializer:\n :param bias_name: String for the bias variables names\n :param W_name: String for the weight matrix variables names\n :param last_layer: Input tensor\n :param last_size: Size of the input tensor\n :param new_size: Size of the output tensor\n :return:\n \"\"\"\n W = weight_variable([last_size, new_size],\n initializer=W_initializer,\n name=W_name)\n b = bias_variable((new_size, ),\n initializer=b_initializer,\n name=bias_name)\n #h = tf.matmul(last_layer,W) + tf.expand_dims(b,0)\n #tf.histogram_summary(h.name,h)\n return tf.matmul(last_layer, W) + tf.expand_dims(b, 0)\n\n\ndef mlp(input_layer,\n input_layer_size,\n hidden_sizes,\n nonlinearity,\n W_initializer=None,\n b_initializer=None,\n ):\n \"\"\"\n Create a multi-layer perceptron with the given hidden sizes. The\n nonlinearity is applied after every hidden layer.\n\n :param b_initializer:\n :param W_initializer:\n :param input_layer: tf.Tensor, input to mlp\n :param input_layer_size: int, size of the input\n :param hidden_sizes: int iterable of the hidden sizes\n :param nonlinearity: the initialization function for the nonlinearity\n :return: Output of MLP.\n :type: tf.Tensor\n \"\"\"\n last_layer = input_layer\n last_layer_size = input_layer_size\n for layer, hidden_size in enumerate(hidden_sizes):\n with tf.variable_scope('hidden{0}'.format(layer)) as _:\n #IPython.embed()\n last_layer = nonlinearity(linear(last_layer,\n last_layer_size,\n hidden_size,\n W_initializer=W_initializer,\n b_initializer=b_initializer,\n ))\n last_layer_size = hidden_size\n return last_layer\n\n\ndef get_lower_triangle_flat_indices(dim):\n indices = []\n for row in range(dim):\n for col in range(dim):\n if col <= row:\n indices.append(row * dim + col)\n return indices\n\n\ndef get_num_elems_in_lower_triangle_matrix(dim):\n return int(dim * (dim + 1) / 2)\n\n\n# From https://github.com/locuslab/icnn/blob/master/RL/src/naf_nets_dm.py\ndef vec2lower_triangle(vec, dim):\n \"\"\"\n Convert a vector M of size (n * m) into a matrix of shape (n, m)\n [[e^M[0], 0, 0, ..., 0]\n [M[n-1], e^M[n], 0, 0, ..., 0]\n [M[2n-1], M[2n], e^M[2n+1], 0, ..., 0]\n ...\n [M[m(n-1)], M[m(n-1)+1], ..., M[mn-2], e^M[mn-1]]\n \"\"\"\n L = tf.reshape(vec, [-1, dim, dim])\n L = tf.batch_matrix_band_part(L, -1, 0) - tf.batch_matrix_diag(\n tf.batch_matrix_diag_part(L)) + \\\n tf.batch_matrix_diag(tf.exp(tf.batch_matrix_diag_part(L)))\n return L\n\n\ndef quadratic_multiply(x, A):\n \"\"\"\n Compute x^T A x\n :param x: [n x m] matrix\n :param A: [n x n] matrix\n :return: x^T A x\n \"\"\"\n return tf.matmul(\n x,\n tf.matmul(\n A,\n x\n ),\n transpose_a=True,\n )\n\n\ndef he_uniform_initializer():\n \"\"\"He weight initialization.\n\n Weights are initialized with a standard deviation of\n :math:`\\\\sigma = gain \\\\sqrt{\\\\frac{1}{fan_{in}}}` [1]_.\n\n References\n ----------\n .. [1] Kaiming He et al. (2015):\n Delving deep into rectifiers: Surpassing human-level performance on\n imagenet classification. arXiv preprint arXiv:1502.01852.\n \"\"\"\n\n def _initializer(shape, **kwargs):\n if len(shape) == 2:\n fan_in = shape[0]\n elif len(shape) > 2:\n fan_in = np.prod(shape[1:])\n delta = np.sqrt(1.0 / fan_in)\n # TODO(vpong): refactor this common piece of code (e.g. move this to a\n # decorator)\n # tf.get_variable puts \"partition_info\" as another kwargs, which is\n # unfortunately not supported by tf.random_uniform\n acceptable_keys = [\"seed\", \"name\"]\n acceptable_kwargs = {\n key: kwargs[key]\n for key in kwargs\n if key in acceptable_keys\n }\n return tf.random_uniform(shape, minval=-delta, maxval=delta,\n **acceptable_kwargs)\n\n return _initializer\n\n\ndef xavier_uniform_initializer():\n def _initializer(shape, **kwargs):\n if len(shape) == 2:\n n_inputs, n_outputs = shape\n else:\n receptive_field_size = np.prod(shape[:2])\n n_inputs = shape[-2] * receptive_field_size\n n_outputs = shape[-1] * receptive_field_size\n init_range = math.sqrt(6.0 / (n_inputs + n_outputs))\n acceptable_keys = [\"seed\", \"name\"]\n acceptable_kwargs = {\n key: kwargs[key]\n for key in kwargs\n if key in acceptable_keys\n }\n return tf.random_uniform(shape, minval=-init_range, maxval=init_range,\n **acceptable_kwargs)\n\n return _initializer\n","sub_path":"Experiment_4/mod_tf_util.py","file_name":"mod_tf_util.py","file_ext":"py","file_size_in_byte":7677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"651811498","text":"import socket\nimport threading\nimport requests\nimport json\nimport time\nfrom Server import Message\n\nclass Worker(object):\n\n def __init__(self,client,greenlet):\n file = './api.json'\n self.client = client\n self.greenlet = greenlet\n self.load_api_json_file(file)\n\n def request_run(self,name,method,url,**args):\n request_meta = {}\n request_meta['method'] = method\n request_meta[\"start_time\"] = time.time()\n response = requests.request(method,url,**args)\n request_meta[\"response_time\"] = (time.time() - request_meta[\"start_time\"]) * 1000\n request_meta[\"name\"] = name or response.request.path_url\n if args.get(\"stream\", False):\n request_meta[\"content_size\"] = int(response.headers.get(\"content-length\") or 0)\n else:\n request_meta[\"content_size\"] = len(response.content or \"\")\n request_meta['status_code'] = response.status_code\n self.client.send(Message('slave_stats',request_meta,socket.gethostname()))\n\n def load_api_json_file(self,file):\n with open(file, 'r',encoding='utf8') as json_file:\n json_api = json.loads(json_file.read())\n name = json_api['name']\n create_time = json_api['create_time']\n total = json_api['total']\n api_list = json_api['api_list']\n frequency = json_api['frequency']\n self.normal_run(name,api_list,frequency)\n \n def run(self,name,api_list):\n for url in api_list:\n sleep_time = url['sleep']\n for x in range(url['frequency']):\n _url = url['url']\n _name = url['name']\n _method = url['method']\n _data = url['data']\n _header = url['headers']\n self.request_run(_name,_method,_url,data=json.dumps(_data),headers = _header[0])\n time.sleep(sleep_time)\n\n def normal_run(self,name,api_list,frequency):\n for x in range(frequency):\n self.run(name, api_list)\n\n def gevent_run(self,name,api_list,frequency):\n for x in range(frequency):\n self.greenlet.spawn(self.run,name,api_list)\n \n\n\n def thread_run(self,name,api_list,frequency):\n thread_list = []\n for x in range(frequency):\n t = threading.Thread(target=self.run,args=(name,api_list))\n t.setDaemon(True)\n t.start()\n thread_list.append(t)\n for x in thread_list:\n x.join()\n self.client.send(Message('slave_complete',None,socket.gethostname()))","sub_path":"server/app/server/Worker.py","file_name":"Worker.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"71590475","text":"# -*- coding:utf-8 -*-\n\ndef wapper(func):\n def f(*args, **kwargs):\n print(func.__name__ + 'called')\n 'do something'\n func(*args, **kwargs)\n return f\ndef test1():\n print('i am test1')\n\ntest1 = wapper(test1)\n#print(test1)\n\"\"\"\n.f at 0x037CFDF8>\n\"\"\"\n\n# 等价于\n\n@wapper\ndef test2():\n print('i am test2')\n#test2()\n\"\"\"\ntest2called\ni am test2\n\"\"\"\n\n# 被称为一个横切面(Aspect),这种编程方式被称为面向切面的编程(Aspect-Oriented Programming)。\n\n# --------------------------------------------------------------------------------------\n# 带参数的装饰器\n\ndef wrapper(param):\n def decorator(func):\n def f(*args, **kwargs):\n print(func.__name__ + 'called with param {}'.format(param))\n 'do something with param'\n return func(*args, **kwargs)\n return f\n return decorator\n\n@wrapper('i am param')\ndef test3(*args, **kwargs):\n print('i am test3')\n#test3()\n\n\"\"\"\ntest3called with param i am param\ni am test3\n\"\"\"\n\n# --------------------------------------------------------------------------\n# 类装饰器\n# object.__call__(self[, args...])模拟可调用对象\n\nclass Wapper(object):\n def __init__(self, func):\n self._func = func\n\n def __call__(self):\n print(self.__getattribute__('__call__'))\n self._func() # 执行\n\n@Wapper\ndef test4():\n print('i am test4')\n\n#test4()\n\"\"\"\n>\ni am test4\n\"\"\"\n\n# ----------------------------------------------------------------------------------\n# 普通函数使用装饰器其函数元信息丢失,例如\ndef dec(func):\n def f(*args, **kwargs):\n print(f.__name__)\n return func(*args, **kwargs)\n return f\n\n@dec\ndef test5():\n print(\"test5's name: {}\".format(test5.__name__))\n\ntest5()\n\"\"\"\nf\ntest5's name: f\n\"\"\"\n\n\n# ----------------functools.wraps---------------------------\n\n# (1) partial (From https://docs.python.org/3/library/functools.html#functools.partial)\n# functions.partial(func, *args, **keywords)\n# Roughly equivalent to\ndef partial(func, *args, **keywords):\n def newfunc(*fargs, **fkeywords):\n newkeywords = keywords.copy()\n newkeywords.update(fkeywords)\n return func(*args, *fargs, **newkeywords)\n \n newfunc.func = func\n newfunc.args = args\n newfunc.keywords = keywords\n return newfunc\n\n# For Example\nfrom functools import partial\nbasetwo = partial(int, base=2)\n# print(basetwo('11100'))\n# print(basetwo.func)\n# print(basetwo.args)\n# print(basetwo.keywords)\n\"\"\"result\n28\n\n()\n{'base': 2}\n\"\"\"\n# ==================================================================================================\n\"\"\" Source Code in CPYTHON functools.py\"\"\"\nclass partial:\n\n __slot__ = \"func\", \"args\", \"keywords\", \"__dict__\", \"__weakref__\"\n\n def __new__(*args, **keywords):\n if not args:\n raise TypeError(\"descriptor '__new__' of partial needs an argument\")\n if len(args) < 2:\n raise TypeError(\"type 'partial' takes at least one argument\") # 至少是一个函数,外加一个特定参数\n cls, func, *args = args # unpack\n if not callable(func):\n raise TypeError(\"the first argument must be callable\") # 检查函数是否可调用\n \n args = tuple(args)\n\n if hasattr(func, \"func\"):\n args = func.args + args # 将func的args添加构成新的args\n tmpkkw = func.keywords.copy()\n tmpkkw.update(keywords)\n keywords = tmpkkw # 更新构成新keywords,若keywords存在,则替换其,通常为一个默认值如 (int, base=2)\n del tmpkkw\n func = func.func\n\n self = super(partial, cls).__new__(cls) # 父类构建实例\n\n self.func = func # 实例属性设置 较原函数多余添加的属性\n self.args = args\n self.keywords = keywords\n return self\n \n def __call__(*args, **keywords): # 不必写self\n if not args:\n raise TypeError('...')\n self, *args = args # self 在此\n newkeywords = self.keywords.copy()\n newkeywords.update(keywords)\n return self.func(*self.args, *args, **newkeywords)\n\n\n# (2) wraps\nWRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',\n '__annotations__')\nWRAPPER_UPDATES = ('__dict__',)\n\ndef wraps(wrapped,\n assigned = WRAPPER_ASSIGNMENTS,\n updated = WRAPPER_UPDATES):\n \"\"\"Decorator factory to apply update_wrapper() to a wrapper function\n\n Returns a decorator that invokes update_wrapper() with the decorated\n function as the wrapper argument and the arguments to wraps() as the\n remaining arguments. Default arguments are as for update_wrapper().\n This is a convenience function to simplify applying partial() to\n update_wrapper().\n \"\"\"\n return partial(update_wrapper, wrapped=wrapped,\n assigned=assigned, updated=updated)\n\ndef update_wrapper(wrapper,\n wrapped,\n assigned = WRAPPER_ASSIGNMENTS,\n updated = WRAPPER_UPDATES):\n \"\"\"\n Update a wrapper function to look like the wrapped function\n\n \"\"\"\n\n for attr in assigned: # 为wrapper设置wrapped的一些属性值 \n try:\n value = getattr(wrapped, attr)\n except AttributeError:\n pass\n else:\n setattr(wapper, attr, value)\n for attr in updated:\n getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n \n wapper.__wrapped__ = wrapped\n return wapper\n\n# ---------------------------------------------------------------------------\n\"\"\" 举个栗子\n\n例如\n>>> def my_decorator(f):\n... @wraps(f)\n... def wrapper(*args, **kwds):\n... print('Calling decorated function')\n... return f(*args, **kwds)\n... return wrapper\n\n[1]\n首先调用wraps(f)。\n其中参数 wrapped = f assigned = WRAPPER_ASSIGNMENTS updated = WRAPPER_UPDATES\n\n返回 partial(update_wrapper, wrapped=f, 'assigned':WRAPPER_ASSIGNMENTS, 'updated':WRAPPER_UPDATES)\n\n[2]\npartial 初始化实例,借用 func 即此时的 update_wrapper 属性更新 args keywords. \n\n示例中得到\nself = functools.partial(...)\nself.func = update_wrapper\nself.args = []\nself.keywords={'wrapped':f, 'assigned':WRAPPER_ASSIGNMENTS, 'updated':WRAPPER_UPDATES}\n\n返回更新参数的partial实例。\n\n[3] \n进入函数wapper的装饰\n\nwrapper = wraps(f) (wapper)\n即调用 partial 的 __call__()方法。\n传入参数,即示例函数的 wapper。\n调用 self.func(*self.args, *args, **self.keywords)。即 \nupdate_wrapper(wapper, f, WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)\n对应参数为 self.args = [] ; *args=wapper ; **keywords=f, WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES\n\n此时 update_wrapper 将已包装函数 f 的部分属性值复制到 未包装函数 wapper , 并返回。 同时解决了部分信息丢失的问题。\n\n\"\"\"\n\n\"\"\"\npartial大致功能。\npartial类提供 对输入函数,参数的临时场所。用来将更新的参数值传入函数。并将 func、args、keywords实例属性存储函数对象、传入的args,keywords。\n类定义 __call__方法 提供对已更新参数的函数调用。\n从而,从外界来看,实现偏函数。\n\n\"\"\"","sub_path":"decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":7349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"95812099","text":"from robotpageobjects import robot_alias\nfrom python.page.ExpensePage import ExpensePage\nfrom python.component.pagepart.grid.ReportGridComponent import ReportGridComponent\nfrom python.component.dialog.ReportPaymentDialogComponent import ReportPaymentDialogComponent\nfrom robot.utils import asserts\n\nclass ReportViewPage(ExpensePage):\n name = \"View Reports\"\n url = \"/reports/user\"\n\n components = {\n ReportGridComponent: \"xpath=.//*[@class='grid']\",\n ReportPaymentDialogComponent: \"xpath=.//body\",\n }\n\n selectors = {\n \"new_report_button\":\"id=btnCreateReport\",\n \"export_report_link\":\"id=btnExportReport\"\n }\n \n def _is_page(self):\n return super(ReportViewPage, self)._is_page() and self.seleniumBrowser.is_page_by_page_class(ReportViewPage)\n\n @robot_alias(\"report_grid_header_should_be_visible\")\n def report_grid_header_should_be_visible(self, *headerName):\n for header in headerName:\n self.reportgrid.grid_header_text_should_be(header)\n return self\n\n @robot_alias(\"select_report\")\n def select_report(self, report_name):\n self.reportgrid.select_report(report_name)\n self._wait_to_load()\n from python.page.report.ReportDetailPage import ReportDetailPage\n return ReportDetailPage()\n \n @robot_alias(\"grid_should_contain_report\")\n def grid_should_contain_report(self, reportName):\n return self.reportgrid.grid_should_contain_report(reportName)\n \n @robot_alias(\"grid_should_not_contain_report\")\n def grid_should_not_contain_report(self, report):\n self.reportgrid.search_item(\"Report name\", report)\n self._wait_to_load()\n self.reportgrid.page_should_contain_element(\"report_grid_empty\")\n return self\n\n @robot_alias(\"report_record_should_contain\")\n def report_record_should_contain(self, reportName, value):\n self.reportgrid.report_record_should_contain(reportName, value)\n return self\n \n @robot_alias(\"click_delete_report\")\n def click_delete_report(self):\n locator = self.reportgrid.resolve_selector(\"delete_report_button\")\n self.click_element(locator)\n return self\n \n @robot_alias(\"select_checkbox_by_report_name\")\n def select_checkbox_by_report_name(self, *args):\n for arg in args:\n self.reportgrid.select_report_checkbox(arg)\n return self\n \n @robot_alias(\"delete_report\")\n def delete_report(self, report):\n self.reportgrid.search_item(\"Report name\", report)\n self._wait_to_load()\n self.reportgrid.select_report_checkbox(report)\n self._wait_to_load()\n self.click_delete_report()\n self._wait_to_load()\n return self\n \n @robot_alias(\"grid_should_sort_by_header\")\n def grid_should_sort_by_header(self, headerName, sortType):\n return self.reportgrid.grid_should_sort_by_header(headerName, sortType)\n \n @robot_alias(\"click_report_grid_header\")\n def click_report_grid_header(self, headerName):\n self.reportgrid.click_expense_grid_header(headerName)\n self._wait_to_load()\n return self\n\n @robot_alias(\"click_showing_report_per_page\")\n def click_showing_report_per_page(self, numPerPage):\n self.reportgrid.click_showing_number_record_per_page(numPerPage)\n self._wait_to_load()\n return self\n \n @robot_alias(\"grid_should_paginate_by\")\n def grid_should_paginate_by(self, numPerPage):\n return self.reportgrid.grid_should_paginate_by(numPerPage)\n \n @robot_alias(\"verify_report_payment_dialog_elements\")\n def verify_report_payment_dialog_elements(self):\n return self.reportpaymentdialog.verify_elements()\n \n @robot_alias(\"report_payment_dialog_should_be_reseted\")\n def report_payment_dialog_should_be_reseted(self):\n asserts.assert_equal(self.get_text(self.reportpaymentdialog.resolve_selector('paid_date_textbox')),'')\n self.verify_default_option_dropdown(self.reportpaymentdialog.resolve_selector('payment_type_dropdown'), 'Select an Option')\n asserts.assert_equal(self.get_text(self.reportpaymentdialog.resolve_selector('notes_number_textbox')),'')\n return self\n \n @robot_alias(\"input_payment_information\")\n def input_payment_information(self, paid_day=None, payment_type=None, note_number=None):\n self.reportpaymentdialog.input_payment_information(paid_day, payment_type, note_number)\n return self\n\n @robot_alias(\"paid_link_should_be_enabled\")\n def paid_link_should_be_enabled(self, isEdited):\n asserts.assert_equal(self.reportgrid.paid_link_should_be_enabled(), bool(isEdited))\n return self\n\n @robot_alias(\"verify_default_option_of_report_type_dropdown\")\n def verify_default_option_of_report_type_dropdown(self, default_option):\n asserts.assert_true(\n self.verify_default_option_dropdown(\"filterstatus_chzn\", default_option))\n return self\n\n @robot_alias(\"verify_options_of_report_type_dropdown\")\n def verify_options_of_report_type_dropdown(self, *options):\n asserts.assert_true(self.verify_options_dropdown(\"filterstatus_chzn\", *options))\n return self\n \n @robot_alias(\"verify_options_of_payment_type_dropdown\")\n def verify_options_of_payment_type_dropdown(self, *options):\n asserts.assert_true(self.verify_options_dropdown(\"ddlPaymentType_chzn\", *options))\n return self\n \n @robot_alias(\"select_report_filter\")\n def select_report_filter(self, options):\n self.select_dropdown(\"filterstatus_chzn\", options)\n return self._wait_to_load()\n \n @robot_alias(\"grid_should_be_filtered_by\")\n def grid_should_be_filtered_by(self, type_filter):\n self.reportgrid.grid_should_be_filtered_by(type_filter)\n return self\n \n @robot_alias(\"verify_edit_payment_button_is_visible\")\n def verify_edit_payment_button_is_not_visible(self, isVisible):\n if isVisible == 'True':\n self.reportgrid.page_should_contain_element(\"edit_payment_button\")\n else: \n self.reportgrid.page_should_not_contain_element(\"edit_payment_button\")\n return self\n \n @robot_alias(\"click_paid_link_by_report_name\")\n def click_paid_link_by_report_name(self, report_name):\n paid_xpath = self.reportgrid.get_column_xpath_by_report_name(report_name, \"Paid\")\n self.reportgrid.click_element(paid_xpath)\n return self\n \n @robot_alias(\"click_edit_payment_button\")\n def click_edit_payment_button(self):\n self.reportgrid.click_element(\"edit_payment_button\")\n return self\n \n @robot_alias(\"click_save_payment_button\")\n def click_save_paid_button(self):\n self.reportpaymentdialog.click_element(\"save_button\")\n self._wait_to_load()\n self.buildIn.sleep(2)\n return self\n\n @robot_alias(\"click_reset_payment_button\")\n def click_reset_paid_button(self):\n self.reportpaymentdialog.click_element(\"reset_button\")\n return self\n \n @robot_alias(\"click_cancel_payment_button\")\n def click_cancel_paid_button(self):\n self.reportpaymentdialog.click_element(\"cancel_button\")\n return self\n \n @robot_alias(\"paid_field_of_report_name_should_be\")\n def paid_field_of_report_name_should_be(self, report_name, paid_status):\n paid_xpath = self.reportgrid.get_column_xpath_by_report_name(report_name, \"Paid\")\n asserts.assert_equal(self.reportgrid.get_text(paid_xpath), paid_status)\n return self\n\n @robot_alias(\"grid_should_be_filtered_by_period_time\")\n def grid_should_be_filtered_by_period_time(self, field_search, start_day, end_day):\n self.reportgrid.grid_should_be_filtered_by_period_time(field_search, start_day, end_day)\n return self\n\n @robot_alias(\"verify_page_elements\")\n def verify_page_elements(self):\n self.page_should_contain_element(\"new_report_button\")\n self.page_should_contain_element(\"export_report_link\")\n self.reportgrid.page_should_contain_element(\"delete_report_button\")\n return self\n \n @robot_alias(\"search_report\")\n def search_report(self, field, value=None):\n self.reportgrid.search_item(field, value)\n return self\n \n @robot_alias(\"search_item_via_date_time\")\n def search_item_via_date_time(self, field, start_day=None, end_time=None):\n self.reportgrid.search_item_via_date_time(field, start_day, end_time)\n return self\n \n @robot_alias(\"click_pagination_number\")\n def click_pagination_number(self, numPerPage):\n self.reportgrid.click_pagination_number(numPerPage)\n self._wait_to_load()\n return self\n \n @robot_alias(\"click_pagination_next\")\n def click_pagination_next(self):\n self.reportgrid._go_to_next_page()\n self._wait_to_load()\n return self\n \n @robot_alias(\"cancel_search_report\")\n def cancel_search_report(self):\n self.reportgrid.click_link_cancel_search()\n self._wait_to_load()\n return self","sub_path":"expense-ui-robot-tests/PythonExpenseAutomationTest/python/page/report/ReportViewPage.py","file_name":"ReportViewPage.py","file_ext":"py","file_size_in_byte":9038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"50655767","text":"from string import Template\n# Template strings provide simpler string substitution.\n# A primary use case for template strings is for internalization i18n.\n\ntitle_text = Template(\"This is title text for ${name}.\")\n# >>> title_text.substitute(name=\"article\").\n# >>> title_text.substitute(article=\"article\") rise KeyError.\n# >>> title_text.safe_substitute(article=\"article\") without KeyError.\n\n\nclass MyTemplate(Template):\n delimiter = \"=\"\n idpattern = \"[a-z]*\"\n\n\nfull_name = MyTemplate(\"=first_name, =last_name.\")\n# >>> full_name.substitute(first_name=\"Tom\", last_name=\"Soer\") KeyError first.\n\nfull_name = MyTemplate(\"=firstname, =lastname.\")\n# >>> full_name.substitute(firstname=\"Tom\", lastname=\"Soer\").\n\n\n# Printing the global table.\nimport pprint # noqa\npprint.pprint(globals())\n","sub_path":"Python/stl/string/template_strings.py","file_name":"template_strings.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"409785822","text":"\ndef getParents(ancestors, node):\n parents = []\n for pair in ancestors:\n if pair[1] == node:\n parents.append(pair[0])\n return parents\n\n\ndef dft_recursive(ancestors, node, distance):\n parents = getParents(ancestors, node)\n\n elder = (node, distance)\n\n for parent in parents:\n pair = dft_recursive(ancestors, parent, distance + 1)\n if pair[1] > elder[1]:\n elder = pair\n\n return elder\n\n\ndef earliest_ancestor(ancestors, starting_node, distance=0):\n elder = dft_recursive(ancestors, starting_node, distance)\n\n if elder[0] == starting_node:\n return -1\n\n return elder[0]\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"164743546","text":"from turtle import circle\r\nimport numpy as np\r\n# import plotly.graph_objects as go\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nimport pickle\r\nimport os\r\n\r\n# load greedy data\r\nngreed = 33\r\n\r\npath = \"./\"\r\nn = 33\r\nfile_name_greed = os.path.join(path, \"greedy_initialization_\" + str(n) + \".pickle\")\r\n\r\nwith open(file_name_greed, \"rb\") as fh:\r\n dict_greed = pickle.load(fh)\r\n\r\n\r\nXturb = dict_greed[\"layout\"]\r\npot_loc = dict_greed[\"potential_locations\"]\r\npolys = dict_greed[\"poly\"]\r\n\r\n# plotly code for greedy\r\n# fig = go.Figure()\r\n# fig.add_trace(go.Scatter(x=Xturb[0, :], y=Xturb[1, :], name=\"Turbines location\", mode=\"markers\",\r\n# marker=dict(size=12, color=\"#85C0F9\")))\r\n# fig.add_trace(go.Scatter(x=pot_loc[0, :], y=pot_loc[1, :], name=\"Potential locations\", mode=\"markers\",\r\n# marker=dict(size=6, color=\"#F5793A\")))\r\n# for n_poly, poly in enumerate(polys):\r\n# x, y = poly[\"x\"], poly[\"y\"]\r\n# fig.add_trace(\r\n# go.Scatter(x=x, y=y, name=\"Boundary \" + str(n_poly), mode=\"lines\", line=dict(color=\"black\")))\r\n# fig.update_layout(\r\n# yaxis=dict(\r\n# scaleanchor=\"x\",\r\n# scaleratio=1,\r\n# ),\r\n# template=\"simple_white\"\r\n# )\r\n# fig.show()\r\n\r\n# pyplot code\r\nturbine_radius = 99.0\r\nfig, ax = plt.subplots(1,2, figsize=(8,4))\r\ncolors = [\"#BDB8AD\", \"#85C0F9\", \"#0F2080\", \"#F5793A\", \"#A95AA1\", \"#382119\"]\r\nturbine_color = colors[2]\r\nboundary_color = colors[0]\r\npot_loc_color = colors[3]\r\n\r\n# add boundaries\r\nfor n_poly, poly in enumerate(polys):\r\n x, y = poly[\"x\"], poly[\"y\"]\r\n ax[0].plot(x, y, color=boundary_color, zorder=0)\r\n\r\n# add turbines\r\nfor i in np.arange(0, len(Xturb[0,:])):\r\n c = patches.Circle((Xturb[0, i], Xturb[1, i]), radius=turbine_radius, fill=False, color=turbine_color, zorder=5)\r\n ax[0].add_patch(c)\r\n\r\n# add potential locations\r\nax[0].scatter(pot_loc[0,:], pot_loc[1,:], s=1, color=pot_loc_color, zorder=10)\r\n\r\n# load local search data\r\nn = 83\r\nfile_name_local_search = os.path.join(path, \"local_search_\" + str(n) + \".pickle\")\r\n\r\nwith open(file_name_local_search, \"rb\") as fh:\r\n dict_local_search = pickle.load(fh)\r\n\r\nXturb = dict_local_search[\"layout\"]\r\npot_loc = dict_local_search[\"potential_locations\"]\r\npolys = dict_local_search[\"poly\"]\r\n\r\n# plotly code for local search\r\n# fig = go.Figure()\r\n# fig.add_trace(go.Scatter(x=Xturb[0, :], y=Xturb[1, :], name=\"Turbines location\", mode=\"markers\",\r\n# marker=dict(size=12, color=\"#85C0F9\")))\r\n# fig.add_trace(go.Scatter(x=pot_loc[0, :], y=pot_loc[1, :], name=\"Potential locations\", mode=\"markers\",\r\n# marker=dict(size=6, color=\"#F5793A\")))\r\n# for n_poly, poly in enumerate(polys):\r\n# x, y = poly[\"x\"], poly[\"y\"]\r\n# fig.add_trace(\r\n# go.Scatter(x=x, y=y, name=\"Boundary \" + str(n_poly), mode=\"lines\", line=dict(color=\"black\")))\r\n# fig.update_layout(\r\n# yaxis=dict(\r\n# scaleanchor=\"x\",\r\n# scaleratio=1,\r\n# ),\r\n# template=\"simple_white\"\r\n# )\r\n# fig.show()\r\n\r\n# pyplot code for local search figure \r\n# add boundaries\r\nfor n_poly, poly in enumerate(polys):\r\n x, y = poly[\"x\"], poly[\"y\"]\r\n ax[1].plot(x, y, color=boundary_color, zorder=0)\r\n\r\n# add turbines\r\nfor i in np.arange(0, len(Xturb[0,:])):\r\n c = patches.Circle((Xturb[0, i], Xturb[1, i]), radius=turbine_radius, fill=False, color=turbine_color, zorder=5)\r\n ax[1].add_patch(c)\r\n\r\n# add potential locations\r\nax[1].scatter(pot_loc[0,:], pot_loc[1,:], s=1, color=pot_loc_color, zorder=10)\r\n\r\n# label figures \r\nax[0].annotate(\"Boundaries\", (7600, 9200), color=boundary_color)\r\nax[0].annotate(\"Wind Turbines\", (7600, 8700), color=turbine_color)\r\nax[0].annotate(\"Potential Locations\", (7600, 8200), color=pot_loc_color)\r\n\r\n# format figure\r\nfontsize = 10\r\nfor axi in ax:\r\n axi.xaxis.set_ticks_position(\"none\")\r\n axi.yaxis.set_ticks_position(\"none\")\r\n axi.set_xticks([])\r\n axi.set_yticks([])\r\n # ax[2].tick_params(axis=\"x\", pad=12)\r\n\r\n # # ax[1].set_title(\"(a)\", y=-0.25,fontsize=fontsize)\r\n # # ax[2].set_title(\"(b)\", y=-0.25,fontsize=fontsize)\r\n\r\n axi.spines[\"top\"].set_visible(False)\r\n axi.spines[\"bottom\"].set_visible(False)\r\n axi.spines[\"left\"].set_visible(False)\r\n axi.spines[\"right\"].set_visible(False)\r\n\r\n axi.axis=(\"square\")\r\n axi.set(aspect='equal')\r\n \r\n # plt.gcf().set_aspect('equal')\r\n\r\nax[0].set_title(\"(a)\", y=0,fontsize=fontsize)\r\nax[1].set_title(\"(b)\", y=0,fontsize=fontsize)\r\n\r\n\r\nplt.tight_layout()\r\n# save figure\r\nplt.savefig(\"GreedyLS.pdf\", transparent=True)\r\n\r\nplt.show()","sub_path":"image-gen/DataPlotDEBO/FiguresPaper.py","file_name":"FiguresPaper.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"488540587","text":"#!/usr/bin/env python\n\n\"\"\"3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух\nаргументов.\"\"\"\n\n\ndef my_func(num1, num2, num3):\n nums = list(locals().values())\n nums.remove(min(nums))\n return sum(nums)\n\n\nvar1, var2, var3 = input(\"Введите 3 числа через запятую: \").split(\",\")\nprint(my_func(int(var1), int(var2), int(var3)))\n","sub_path":"lesson3/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"439718117","text":"# -*- coding:utf-8 -*-\n\nL = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]\n\n\n# key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序。\n# print(L[1][0])\n# print(L[][1])\ndef by_name(t):\n T = t[0]\n return T\n\n\nL2 = sorted(L, key=by_name)\nprint(L2)\n","sub_path":"base/sorted.py","file_name":"sorted.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"199201763","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef test1(a, *args):\n print(\"첫번째 인자:\", a)\n for each in args:\n print(\"다른 인자\", each)\n\n\ndef test2(**kwargs):\n for key, value in kwargs.items():\n print(key, \":\", value)\n\n\ndef test3(amp, freq, sample_time, end_time, bias):\n time = np.arange(0, end_time, sample_time)\n result = amp * np.sin(2 * np.pi * freq * time) + bias\n\n plt.figure(figsize=(12, 6))\n plt.plot(time, result)\n plt.grid(True)\n plt.xlabel('Time')\n plt.ylabel('Sin')\n plt.title(str(amp) + \"*sin(2*pi*\" + str(freq) + \"*t )+\" + str(bias))\n plt.show()\n\n\ndef test4(**kwargs):\n end_time, sample_time = kwargs.get('endTime', 1), kwargs.get('sampleTime', 0.01)\n amp, freq, bias = kwargs.get('amp', 2), kwargs.get('freq', 1), kwargs.get('bias', 0)\n figsize = kwargs.get('figsize', (12, 6))\n time = np.arange(0, end_time, sample_time)\n result = amp * np.sin(2 * np.pi * freq * time) + bias\n\n plt.figure(figsize=figsize)\n plt.plot(time, result)\n plt.grid(True)\n plt.xlabel('time')\n plt.ylabel('sin')\n plt.title(str(amp) + \"*sin(2*pi*\" + str(freq) + \"*t )+\" + str(bias))\n plt.show()\n\n\nif __name__ == '__main__':\n test4(amp=2, freq=0.5, endTime=10)","sub_path":"day3/05.func_practice.py","file_name":"05.func_practice.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"643934793","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Remove credentials profile.\"\"\"\n\nimport os\nimport sys\n\nfrom builtins import input\n\ncurpath = os.path.dirname(os.path.abspath(__file__))\nsys.path[:0] = [os.path.join(curpath, os.pardir)]\n\nfrom pan_cortex_data_lake import Credentials\n\n\ndef confirm_delete(profile):\n \"\"\"Prompt user to enter Y or N (case-insensitive) to continue.\"\"\"\n answer = \"\"\n while answer not in [\"y\", \"n\"]:\n answer = input(\"Delete PROFILE '%s' [Y/N]? \" % profile).lower()\n return answer == \"y\"\n\n\ndef main():\n try:\n profile = input(\"PROFILE to remove: \") or None\n if profile is not None:\n c = Credentials(profile=profile)\n if confirm_delete(profile):\n print(\"Removing PROFILE '%s'...\" % profile)\n op = c.remove_profile(profile)\n if len(op) > 0:\n print(\"\\nPROFILE '%s' successfully removed.\\n\" % profile)\n else:\n print(\"\\nPROFILE '%s' not found.\\n\" % profile)\n else:\n print(\"\\nRemove PROFILE operation aborted.\\n\")\n else:\n print(\"\\nMust specify a PROFILE to remove.\\n\")\n except KeyboardInterrupt:\n print(\"Exiting...\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/credentials_remove.py","file_name":"credentials_remove.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"160175307","text":"import random\n\ndef matrix(List,col):\n w = 5 # column width\n for item in List:\n if len(str(item)) >= w:\n w = len(str(item))+2\n\n # add dummy values to match grid\n while (len(List)%col) != 0 :\n List.append('')\n\n print() # force \\n\n if col == 6:\n for i in range(0,len(List),col):\n print('\\t+'+'-'*((w*6)+5)+'+')\n print(f'\\t|{str(List[i]).center(w)}|{str(List[i+1]).center(w)}'\n + f'|{str(List[i+2]).center(w)}|{str(List[i+3]).center(w)}'\n +f'|{str(List[i+4]).center(w)}|{str(List[i+5]).center(w)}|')\n print('\\t+'+'-'*((w*6)+5)+'+')\n elif col == 5:\n for i in range(0,len(List),col):\n print('\\t+'+'-'*((w*5)+4)+'+')\n print(f'\\t|{str(List[i]).center(w)}|{str(List[i+1]).center(w)}'\n + f'|{str(List[i+2]).center(w)}|{str(List[i+3]).center(w)}'\n +f'|{str(List[i+4]).center(w)}|')\n print('\\t+'+'-'*((w*5)+4)+'+')\n elif col == 4:\n for i in range(0,len(List),col):\n print('\\t+'+'-'*((w*4)+3)+'+')\n print(f'\\t|{str(List[i]).center(w)}|{str(List[i+1]).center(w)}'\n + f'|{str(List[i+2]).center(w)}|{str(List[i+3]).center(w)}|')\n print('\\t+'+'-'*((w*4)+3)+'+')\n elif col == 3:\n for i in range(0,len(List),col):\n print('\\t+'+'-'*((w*3)+2)+'+')\n print(f'\\t|{str(List[i]).center(w)}|{str(List[i+1]).center(w)}'\n + f'|{str(List[i+2]).center(w)}|')\n print('\\t+'+'-'*((w*3)+2)+'+')\n elif col == 2:\n for i in range(0,len(List),col):\n print('\\t+'+'-'*((w*2)+1)+'+')\n print(f'\\t|{str(List[i]).center(w)}|{str(List[i+1]).center(w)}'\n + f'|')\n print('\\t+'+'-'*((w*2)+1)+'+')\n elif col == 1:\n for i in range(0,len(List),col):\n print('\\t+'+'-'*(w)+'+')\n print(f'\\t|{str(List[i]).center(w)}|')\n print('\\t+'+'-'*(w)+'+')\n\n # remove dummy values\n while List[-1] == '':\n del List[-1]\n print() # force \\n\n\n\n# example usage\nif __name__ == '__main__':\n\n # create a list with random values\n list = []\n for i in range(random.randint(14,27)):\n list.append(random.randint(1000,50000))\n\n # send the list through the matrix function\n # argument 1 is the list, argument 2 is a number between 1 and 6\n matrix(list,random.randint(1,6))\n","sub_path":"Matrix_Print/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"34862391","text":"from django.shortcuts import render\nfrom .forms import RegistroFormulario\n\n\n# Create your views here.\n\ndef Registro(response):\n\tif response.method == 'POST':\n\t\tform = RegistroFormulario (response.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\n\telse:\n\t\tform = RegistroFormulario()\n\n\treturn render(response, 'usuarios/registro.html', {'form' : form})\n\n\n","sub_path":"NASAQ/apps/usuarios/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"408435946","text":"\n\nimport time\n\nfrom database.signed_comments_dbHandler import SignedCommentsDbHandler\nfrom database.vectorized_comments_dbHandler import VectorizedCommentsDbHandler\nfrom database.vectorized_contents_dbHandler import VectorizedContentsDbHandler\n\nimport numpy as np\n\n# 特征向量归一化\n# arr:二维ndarray\ndef normalizing(arr):\n \"\"\"\n 在机器学习的算法训练中,有很多数据的特征值不止一个,特征值中有些属性的数字过大,\n 从而对计算结果的影响太大,但是实际情况是每个属性都同等重要,\n 这时候就要处理这种不同取值范围的特征值,\n 通常采用数值归一化,将取值范围处理为0-1或者-1-1之间。\n \"\"\"\n # print(arr.shape)\n # print(arr.max())\n result = []\n arrmax = np.max(arr,0)\n arrmin = np.min(arr,0)\n arrdeta = arrmax - arrmin\n # print(arrmax, arrmin, arrdeta)\n for i in range(0, arr.shape[0]):\n temp = [str(arr[i][0])]\n for j in range(1, arr.shape[1]):\n # arr[i][j] = (arr[i][j] - arrmin[j]) / arrdeta[j]\n if arrdeta[j] != 0:\n temp.append(float((arr[i][j] - arrmin[j]) / arrdeta[j]))\n else:\n temp.append(.0)\n # print(arr[i][j], end=' ')\n result.append(temp)\n # print(\"\\n\")\n return result\n\nfrom textProcessing.vectorizer import Vectorizer\ndef doVectoringComments():\n \"\"\"\n 将标注好的评论文本向量化,并存入数据库\n 1. 从signedcomments表中查询标注好的评论\n 2. 向量化评论\n 3. 向量归一化\n 3. 将归一化的向量插入vectorizedcomments表中\n \"\"\"\n fr = time.time()\n # 已标注评论数据库表的操作对象\n signedCommentsHandler = SignedCommentsDbHandler()\n # 向量化评论数据库表的操作对象\n vectorizedCommentsDbHandler = VectorizedCommentsDbHandler()\n # 标注好的评论元组\n signedComments = signedCommentsHandler.queryAll()\n vectorizer = Vectorizer()\n vectorizedCommentsList = []\n # 评论向量化\n count = 0\n for signedComment in signedComments:\n count += 1\n print(count)\n vectorizedComment = vectorizer.vectoringOneComment(\n signedComment[1], signedComment[2], signedComment[3],\n signedComment[6], signedComment[8], signedComment[9])\n vectorizedCommentsList.append(vectorizedComment)\n vectorizedCommentsDbHandler.insertVectorizedComment(vectorizedComment)\n # 归一化特征向量\n # arr = normalizing(np.array(vectorizedCommentsList, float))\n # for vc in arr:\n # vectorizedCommentsDbHandler.insertVectorizedComment(vc)\n to = time.time()\n print(\"用时:%f\" % (to - fr))\n\nfrom textProcessing.vectorizer import vectoringContent\ndef doVectoringContent():\n signedCommentsDbHandler = SignedCommentsDbHandler()\n vectorizedContentsDbHandler = VectorizedContentsDbHandler()\n commentMatrix = np.array(signedCommentsDbHandler.queryAll())\n contentMatrix = commentMatrix[:,(1,3)]\n print(contentMatrix,contentMatrix.shape)\n result = vectoringContent(25, contentMatrix)\n for vectorizedContent in result:\n vectorizedContentsDbHandler.insertVectorizedContent(vectorizedContent)\n\nif __name__ == \"__main__\":\n doVectoringComments()","sub_path":"src/textProcessing/do_vectoring.py","file_name":"do_vectoring.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"558991248","text":"#!/user/bin/env python3 -tt\n\"\"\"\nTask:\nhttps://adventofcode.com/2018/day/1\n\"\"\"\n\n# Imports\nimport sys\nimport os\nimport re\n\n# Global variables\ntask=\"d-1\"\ninfile=task + \".input\"\n\ndef readInput():\n with open('input/' + infile) as file:\n data = file.read()\n file.close()\n return data\n\ndef a():\n rows = [n for n in readInput().split('\\n')]\n\n print(\"A): \")\n\ndef b():\n rows = [n for n in readInput().split('\\n')]\n \n print(\"B): \")\n\n# Main body\nif __name__ == '__main__':\n a()\n b()\n sys.exit(1)\n","sub_path":"template-1.py","file_name":"template-1.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"594555005","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 04 10:52:06 2017\r\n\r\n@author: zWX460130\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import cm\r\nfrom numpy.linalg import *\r\n###### Flow definition #########################################################\r\nmaxIter = 200001 # Total number of time iterations.\r\nRe = 220.0 # Reynolds number.\r\nnx = 200; \r\nny = 70; \r\nQ = 9 # Lattice dimensions and populations.\r\nuLB = 0.01 # 4 # Velocity in lattice units.\r\nnulb = uLB * nx / Re; \r\nomega = 1.0 / (3. * nulb + 0.5); # Relaxation parameter.\r\n\r\n# circle center\r\ncx = nx/4; cy=ny/2; r=ny/9; \r\n\r\n\r\n# Directions in D2Q9 model\r\nc = np.array([[0,0] , [1,0] , [0,-1] , [-1, 0] , [0, 1], [1, -1], [-1, -1], [-1, 1], [1, 1]])\r\nnorm_dir = [i for i in range(0,Q)]\r\nopposite_dir = [c.tolist().index((-c[i]).tolist()) for i in range(Q)]\r\n\r\nrw = np.arange(Q)[np.asarray([ci[0]>0 for ci in c])] # Unknown on right wall.\r\nmw = np.arange(Q)[np.asarray([ci[0]==0 for ci in c])] # Vertical middle.\r\nlw = np.arange(Q)[np.asarray([ci[0]<0 for ci in c])] # Unknown on left wall.\r\n\r\n# Weights vector\r\nw = 1.0 / 36.0 * np.ones(Q)\r\nw[0] = 4.0 / 9.0\r\nw[1:5] = 1.0 / 9.0\r\n\r\n\r\nboundary = np.fromfunction(lambda x, y : x == -1, (ny, nx), dtype=int)\r\n\r\ndef bb_top():\r\n boundary[0].fill(True)\r\n \r\ndef bb_bot():\r\n boundary[ny-1].fill(True)\r\n \r\ndef bb_left():\r\n boundary[1:ny-1, 0].fill(True)\r\n \r\ndef bb_right():\r\n boundary[1:ny-1, nx-1].fill(True)\r\n\r\n\r\ndef obst():\r\n for x in range(nx):\r\n for y in range(ny):\r\n if (x-cx)**2+(y-cy)**2= params['train_data_dim']] -= params['train_data_dim']\r\n id_train_idx[id_train_idx >= params['train_data_dim']] -= params['train_data_dim']\r\n # Shuffle per epoch\r\n if step%nb_batchs == 0:\r\n perm_ind = np.random.permutation(params['train_data_dim'])\r\n\r\n if step%nb_id_batchs == 0:\r\n id_perm_ind = np.random.permutation(params['train_data_dim'])\r\n\r\n _, global_step, lr, acceptance_rate = sess.run(step_ops, feed_dict={\r\n images_ph: train_images[perm_ind[train_idx], :],\r\n labels_ph: train_labels[perm_ind[train_idx], :]})\r\n train_idx += params['batch_dim']\r\n if induce and step > params['nb_burnin_steps']-1:\r\n _, id_global_step, id_lr, score_loss = sess.run(id_step_ops, feed_dict={\r\n images_ph: train_images[id_perm_ind[id_train_idx], :],\r\n labels_ph: train_labels[id_perm_ind[id_train_idx], :]})\r\n id_train_idx += params['id_batch_dim']\r\n else:\r\n id_global_step, id_lr, score_loss = 0, 0.0, 0.0\r\n\r\n if step%params['display_interval'] == params['display_interval']-1:\r\n toc = time.time()\r\n test_idx = np.array(range(params['batch_dim']))\r\n test_loss, test_err = 0.0, 0.0\r\n for test_step in range(nb_test_steps):\r\n test_idx = test_idx[test_idx < params['test_data_dim']]\r\n err, = sess.run(test_ops, feed_dict={\r\n images_ph: test_images[test_idx, :],\r\n labels_ph: test_labels[test_idx, :]})\r\n test_idx += params['batch_dim']\r\n test_err += err*len(test_idx)/params['test_data_dim']\r\n\r\n results = collections.OrderedDict([\r\n ('time', '{:.2f}'.format(toc-tic)),\r\n ('step', '{:d}'.format(step+1)),\r\n ('lr', '{:.1E}'.format(lr)),\r\n ('acceptance_rate', '{:.2f}'.format(acceptance_rate)),\r\n ('id_step', '{:d}'.format(step+1)),\r\n ('id_lr', '{:.1E}'.format(id_lr)),\r\n ('score_loss', '{:.4E}'.format(score_loss)),\r\n ('test_err', '{:.2f}'.format(test_err))])\r\n\r\n tic = toc\r\n\r\n print_str = \"\"\r\n for key, val in results.items():\r\n print_str += '{} {}\\t'.format(key, val)\r\n print(print_str)\r\n\r\n return sess.run(thetas), (global_step, id_global_step)\r\n","sub_path":"trainers/run_steps.py","file_name":"run_steps.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"542020030","text":"# -*- coding: cp1251-*\n\"\"\"\n 23.03.2015\n Утилиты работы с файлами и директориями\n\"\"\"\n\nimport os\nimport glob\n\n\ndef get_first_file_mask(path, mask):\n \"\"\"\n Получение самого старого файла в папке\n \"\"\"\n\n file_list = sorted(glob.glob(path + '/' + mask),\n key=os.path.getmtime)\n for itm in file_list:\n return itm\n\n\ndef check_dir_by_path(path, sub_folders, mask_files='*', ignore_path=' ', mtime_from=None, mtime_to=None,\n ignore_file=' '):\n \"\"\"\n Проверка каталога на наличие файла по маске файла\n @param path: путь к файлу\n @param sub_folders: проверять ли подкаталоги\n @param mask_files: маска файла\n @param ignore_path: игнорируемый путь\n @param mtime_from: ограничение на дату изменения файла (с) unix_timestamp\n @param mtime_to: ограничение на дату изменения файла (по) unix_timestamp\n @param ignore_file: игнорируемые файлы\n @return:\n \"\"\"\n\n res_file_list = []\n for mask in mask_files.split(','):\n file_list = sorted(glob.glob(path + '/' + mask), key=os.path.getmtime)\n for itm in file_list:\n if not itm.endswith('/' + ignore_path) and not itm.endswith('\\\\' + ignore_path):\n if os.path.isfile(itm):\n itm_replaced = itm.replace('\\\\', '/')\n if mtime_from is not None or mtime_to is not None:\n mtime = os.path.getmtime(itm)\n mtime_accepted = (mtime_from is None or mtime >= mtime_from) \\\n and (mtime_to is None or mtime <= mtime_to)\n if mtime_accepted:\n res_file_list.append(itm_replaced)\n else:\n file_name = os.path.basename(itm_replaced)\n if not file_name.startswith(ignore_file):\n res_file_list.append(itm_replaced)\n elif sub_folders == '1':\n if os.path.isdir(itm):\n tmp_file_list = check_dir_by_path(itm,\n sub_folders,\n mask_files=mask_files,\n ignore_path=ignore_path,\n mtime_from=mtime_from,\n mtime_to=mtime_to,\n ignore_file=ignore_file)\n if tmp_file_list:\n for itm_file in tmp_file_list:\n res_file_list.append(itm_file.replace('\\\\', '/'))\n return res_file_list\n\n\ndef delete_tmp_file(full_file_name, delete_dir=False):\n \"\"\"\n Удаление файла + директории если нужно, если она пуста\n @param full_file_name: имя файла\n @param delete_dir: признак удаления директории если она пуста\n @return: успешность действие\n \"\"\"\n if os.access(full_file_name, os.F_OK):\n try:\n os.unlink(full_file_name)\n except:\n raise\n return False\n if delete_dir:\n ''' проверим есть ли в каталоге еще файлы'''\n file_dir = os.path.dirname(full_file_name)\n try:\n if not os.listdir(file_dir):\n import shutil\n shutil.rmtree(file_dir)\n except:\n raise\n return False\n\n return True\n","sub_path":"utils/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"397140479","text":"from bs4 import BeautifulSoup\nimport urllib2\nimport sqlite3\n\n\ndef modification_name_call():\n\t\tdisplay_name() # same\n\t\tchk = raw_input('By whom you want to modify it ? name , Volume ? , LastTrade ? or Symbol')\n\t\tif chk == \"volume\":\n\t\t\tprint ('This is by volume on name')\n\t\telif chk == \"name\":\n\t\t\tname_value = raw_input('Enter the Certain name value to set')\n\t\t\tname_place = raw_input('Enter the name place where you want to replace the upper value')\n\t\t\tmodify_by_name(name_value, name_place)\n\t\telif chk == \"lastTrade\":\n\t\t\tprint ('This is by trade on name')\n\t\t\tname_value = raw_input('Enter the Certain name value to set')\n\t\t\tlastTrade_place = raw_input('ENter the lastTrade place where you want to replace the upper value')\n\t\t\tmodify_by_namelastTrade(name_value,lastTrade_place) # this calls the lasttrade and name function\n\t\telif chk == \"symbol\":\n\t\t\tprint ('This is by symbol on name')\n\t\t\tname_value = raw_input('Enter the Certain name value to set')\n\t\t\tsymbol_value = raw_input('Enter the symbol where you want to check and replace the upper value')\n\t\t\tmodify_by_namesymbol(name_value, symbol_value)\n\t\telse:\n\t\t\tprint ('Wrong Input /bad INput <-- check again ')\n\t\t\texit()\n\n\ndef modification(): # This is the modification function which is used to modify a particular data\n\tprint ('What you want to modify ?')\n\tinput_check = raw_input(\n\t\t'Enter volume to modify \"volume\" , Enter symbol to Modify \"Symbol\" , Enter name to modify name , Enter lastTrade to modify trade ')\n\tif input_check == \"volume\": # if the user want to modify the volume\n\t\tdisplay_volume() # here you need to have two values , (one to set and another to check\n\t\tchk = raw_input('By whom you want to modify it ? name , Volume ? , LastTrade ? or Symbol')\n\t\tif chk == \"volume\":\n\t\t\tvolume_value = raw_input('Enter the Certain volume value to set')\n\t\t\tvolume_place = raw_input('Enter the Volume place where you want to replace the upper value')\n\t\t\tmodify_by_volume(volume_value, volume_place) # this calls the modification function\n\t\telif chk == \"name\":\n\t\t\tvolume_value = raw_input('Enter the Certain volume value to set')\n\t\t\tname_place = raw_input('Enter the name place where you want to replace the upper value')\n\t\t\tmodify_by_volumename(volume_value, name_place)\n\t\telif chk == \"lastTrade\":\n\t\t\tvolume_value = raw_input('Enter the Certain volume value to set')\n\t\t\tlastTrade_place = raw_input('Enter the LastTrade place where you want to replace the upper value')\n\t\t\tmodify_by_volumelastTrade(volume_value, lastTrade_place)\n\t\telif chk == \"symbol\":\n\t\t\tvolume_value = raw_input('Enter the Certain volume value to set')\n\t\t\tsymbol_place = raw_input('Enter the Symbol place where you want to replace the upper value')\n\t\t\tmodify_by_volumesymbol(volume_value,\n\t\t\t\t\t\t\t symbol_place) # this calls the symbol function to modify the volume at a certain place\n\t\telse:\n\t\t\tprint ('Wrong Input /bad INput <-- check again ')\n\t\t\texit()\n\telif input_check == \"Symbol\":\n\t\tdisplay_symbol() # here you have to do the same\n\t\tchk = raw_input('By whom you want to modify it ? name , Volume ? , LastTrade ? or Symbol')\n\t\tif chk == \"volume\":\n\t\t\tprint ('This is by volume on symbol')\n\t\telif chk == \"name\":\n\t\t\tname_value = raw_input('Enter the Certain name value to set')\n\t\t\tname_place = raw_input('Enter the name place where you want to replace the upper value')\n\t\telif chk == \"lastTrade\":\n\t\t\tprint ('This is by trade on symbol')\n\t\telif chk == \"symbol\":\n\t\t\tprint ('This is by symbol on symbol')\n\t\telse:\n\t\t\tprint ('Wrong Input /bad INput <-- check again ')\n\t\t\texit()\n\telif input_check == \"name\":\n\t\tmodification_name_call() # this calls the modification by the function-->\n\telif input_check == \"lastTrade\":\n\t\tdisplay_lastTrade() # same as above just change\n\t\tchk = raw_input('By whom you want to modify it ? name , Volume ? , LastTrade ? or Symbol')\n\t\tif chk == \"volume\":\n\t\t\tprint ('This is by volume on name')\n\t\telif chk == \"name\":\n\t\t\tname_value = raw_input('Enter the Certain name value to set')\n\t\t\tname_place = raw_input('Enter the name place where you want to replace the upper value')\n\t\t\tmodify_by_name(name_value, name_place)\n\t\telif chk == \"lastTrade\":\n\t\t\tprint ('This is by trade on name')\n\t\telif chk == \"symbol\":\n\t\t\tprint ('This is by symbol on name')\n\t\telse:\n\t\t\tprint ('Wrong Input /bad Input <-- check again ')\n\t\t\texit()\n\telse:\n\t\tprint ('Wrong choice exiting the propgram !!!')\n\t\texit()\n\n\ndef modify_by_volume(volume_value, volume_place):\n\tprint ('Modification in progress')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set volume = (?) where volume= (?)''', (volume_value, volume_place))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef modify_by_volumename(volume_value, name_place):\n\tprint ('Modification in progress by name ')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set volume = (?) where name= (?)''', (volume_value, name_place))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef modify_by_volumelastTrade(volume_value, lastTrade_value):\n\tprint ('Modification in progress by lasttrade value on volume. ')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set volume = (?) where LastTrade= (?)''', (volume_value, lastTrade_value))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef modify_by_volumesymbol(volume_value, symbol_value):\n\tprint ('Modification in progress by lasttrade value on volume. ')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set volume = (?) where Symbol= (?)''', (volume_value, symbol_value))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef modify_by_name(name_value, name_place):\n\tprint ('Modification in progress by name value on name. ')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set name = (?) where name= (?)''', (name_value, name_value))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef modify_by_namesymbol(name_value, symbol_place):\n\tprint ('Modification in progress by symbol value on name. ')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set name = (?) where Symbol= (?)''', (name_value, symbol_place))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef modify_by_namelastTrade(name_value, lastTrade_value):\n\tprint ('Modification in progress by lastTrade value on name. ')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Update Finance set name = (?) where LastTrade= (?)''', (name_value, lastTrade_value))\n\tconn.commit()\n\tcurr.close()\n\tconn.close() # this will close the connection\n\tprint ('Modification complete!.')\n\n\ndef display_volume():\n\tprint ('This is to modify the volume')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Select Volume From FINANCE''')\n\tVolume_list = curr.fetchall()\n\tprint (Volume_list)\n\tconn.commit()\n\tcurr.close()\n\tconn.close()\n\n\ndef display_name():\n\tprint ('This is to modify the Name')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Select name From FINANCE''')\n\tname_list = curr.fetchall()\n\tprint (name_list)\n\tconn.commit()\n\tcurr.close()\n\tconn.close()\n\n\ndef display_symbol():\n\tprint ('This is to modify the symbol')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Select Symbol From FINANCE''')\n\tsymbol_list = curr.fetchall()\n\tprint (symbol_list)\n\tconn.commit()\n\tcurr.close()\n\tconn.close()\n\n\ndef display_lastTrade():\n\tprint ('This is to modify the volume')\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Select lastTrade From FINANCE''')\n\tlast_Trade = curr.fetchall()\n\tprint (last_Trade)\n\tconn.commit()\n\tcurr.close()\n\tconn.close()\n\n\ndef insertintodatabase(symbol, name, lastTrade, volume):\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Insert into FINANCE (SYMBOL , Name , LastTrade , Volume ) values (?,?,?,?)''',\n\t\t\t (symbol, name, lastTrade, volume))\n\tconn.commit()\n\tcurr.close()\n\tconn.close()\n\n\ndef database_creation():\n\tconn = sqlite3.connect('finance.sqlite')\n\tcurr = conn.cursor()\n\tcurr.execute('''Drop Table If Exists FINANCE''')\n\tcurr.execute(\n\t\t'''Create Table IF NOT EXISTS FINANCE(Symbol Text, Name Text , LastTrade Text , Volume Text)''')\n\tprint ('Data base is created !')\n\tcurr.close()\n\tconn.close()\n\n\ndef read_from_web(inner_link):\n\tdata_in_file = urllib2.urlopen(inner_link) # retrives the web page using the urllib requests to open url\n\tsoup = BeautifulSoup(data_in_file, \"lxml\") # Access the Bs4 such that the retrieved page is beautified\n\tdata_in_file.close # urllib is closed\n\t# print (soup)\n\trequired_table = soup.find_all(class_=\"yfnc_tableout1\")\n\trequired_table = BeautifulSoup(str(required_table), \"lxml\")\n\trequired_inner_table = required_table.find_all(class_=\"yfnc_tabledata1\")\n\t# data_list = list()\n\n\tfor j in required_inner_table:\n\t\tif j.string is not None:\n\t\t\tdata_list.append(j.string)\n\t\t# print (j.string)\n\t\ttry:\n\t\t\tif j.b.span is not None:\n\t\t\t\t# print (j.b.span.string)\n\t\t\t\tdata_list.append(j.b.span.string)\n\t\t\t\t# print (j.nobr.small.span.string)\n\t\t\t\tdata_list.append(j.nobr.small.span.string)\n\t\texcept:\n\t\t\tcontinue\n\t\telse:\n\t\t\tcontinue\n\telement = 0\n\twhile element < len(data_list) - 4:\n\t\tprint (str(data_list[element] + \" \" + str(data_list[element + 1]) +\n\t\t\t\t str(str(data_list[element + 2]) + \" \" + str(data_list[element + 3]) + \" \" + str(\n\t\t\t\t\t data_list[element + 4]))))\n\t\tprint ('*******inserted*******') # debug purposes\n\t\telement += 5\n\n\ndef scrap_link(link, pages):\n\tcounter = 0 # counter is just to check if pages doesnt cross the link sized pages\n\twhile counter < pages:\n\t\tread_from_web(link + str(counter))\n\t\tprint (link + str(counter)) # Visualize the links in the compiler\n\t\tcounter += 1 # this is the counter +1 such that the automata is finite\n\tprint ('Pages link generated!') # this generates the link of the pages\n\n\nif __name__ == '__main__': # this is the main entry of the program\n\tlink = \"https://uk.finance.yahoo.com/q/cp?s=%5EFTSE&c=\" # this is the main link which is needed to be scrapped\n\tpage_no = (raw_input('How much pages You want to scrap from the web ?')) # identify users how much pages\n\tif page_no is \"\": page_no = int(3)\n\tpage_no = int(page_no) # this is to identify how much page numbers we have\n\tdatabase_creation() # this is for the database creation\n\tdata_list = list() # this is the data list\n\tscrap_link(link, page_no) # this calls the function of the scrap link to scrap the data from the web\n\telement = 0\n\twhile element < len(data_list) - 4: # inserts all the elements in to the database\n\t\tinsertintodatabase(data_list[element], data_list[element + 1],\n\t\t\t\t\t str(str(data_list[element + 2]) + \" \" + str(data_list[element + 3])),\n\t\t\t\t\t data_list[element + 4])\n\t\tprint ('*******inserted processing*******') # debug purposes\n\t\telement += 5\n\tprint (' Insertion is completed !!! ')\n\tkeyword = (\n\traw_input('Do you want to Modify the data ? Y/y for Yes , N/n for no')) # if you want to modify this calls\n\tif keyword in ['y', 'Y']:\n\t\tprint ('Yes you want to modify the data ')\n\t\tmodification() # modification function is called\n\telif keyword in ['n', 'N']:\n\t\tprint ('No? ok then Exiting the Program')\n\t\texit() # Exit function is called cause there is no need to continue to another as we dont want modification\n\telse:\n\t\tprint ('Invalid input , next time try to read the statment carefully')\n\t\texit()\n\t\t# Note the values will keep on updating whenever you rerun the program , since the values on the links are updating\n\t\t# Time by time (even in seconds )\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":11994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"378065244","text":"import numpy as np\nimport cv2\nimport argparse\nfrom collections import deque\n\nlinecolor = (100, 215, 255)\ncap = cv2.VideoCapture(0)\npts = deque(maxlen=7)\nlwr_red = np.array([119, 191, 130])\nupper_red = np.array([219, 254, 254])\nwhile True:\n ret, frame = cap.read()\n frame = cv2.flip(frame, 1)\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n kernel = np.ones((5, 5), np.uint8)\n mask = cv2.inRange(hsv, lwr_red, upper_red)\n mask = cv2.dilate(mask, kernel, iterations=1)\n res = cv2.bitwise_and(frame, frame, mask=mask)\n cnts,_=cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n center = None\n if len(cnts) > 0:\n c = max(cnts, key=cv2.contourArea)\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n if radius > 5:\n cv2.circle(frame, (int(x), int(y)), int(radius), (255, 255, 255), 2)\n cv2.circle(frame, center, 5, linecolor, -1)\n pts.append(center)\n for i in range(1, len(pts)):\n if pts[i - 1] is None or pts[i] is None:\n continue\n thick = 3\n cv2.line(frame, pts[i - 1], pts[i], linecolor, thick)\n\n cv2.imshow(\"mask\", mask)\n cv2.imshow(\"res\", res)\n cv2.imshow(\"Frame\", frame)\n\n key = cv2.waitKey(30)\n if key == 32:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n\n\n\n","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"226402780","text":"import salabim as sim\n\n'''\nThis model demonstrates the use of period monitors.\nThe model let 15 components randomly enter and leave a queue, called q.\nAfter running for 30 * 24 hours, it shows the statistics per hour and finally\nshows the result of some checks by aggregating the hourly data.\n'''\n\nclass X(sim.Component):\n\n def process(self):\n while True:\n yield self.hold(sim.Uniform(0, 20)())\n self.enter(q)\n yield self.hold(sim.Uniform(0, 20)())\n self.leave()\n\nenv = sim.Environment(trace=False)\n\nq = sim.Queue(name='q')\nqlength_per_hour = sim.PeriodMonitor(parent_monitor=q.length, periods=(24 * [1]))\nqlength_of_stay_per_hour = sim.PeriodMonitor(parent_monitor=q.length_of_stay, periods=(24 * [1]))\n[X() for i in range(15)]\n\nenv.run(30 * 24)\nq.print_statistics()\n\nfor hour in range(24):\n qlength_per_hour[hour].print_statistics()\n qlength_of_stay_per_hour[hour].print_statistics()\n\nprint()\nprint('checks')\nprint('======')\nprint(f'mean of length {q.length.mean():10.7f}')\nprint(f'weighted sum of mean of period monitors of length {sum(qlength_per_hour[hour].mean()/24 for hour in range(24)):10.7f}')\nprint(f'mean of length_of_stay {q.length_of_stay.mean():10.7f}')\ntot1 = 0\ntot2 = 0\nfor hour in range(24):\n if qlength_of_stay_per_hour[hour].number_of_entries != 0:\n tot1 += qlength_of_stay_per_hour[hour].number_of_entries() * qlength_of_stay_per_hour[hour].mean()\n tot2 += qlength_of_stay_per_hour[hour].number_of_entries()\n\nprint(f'weighted sum of mean of period monitors of length_of_stay {tot1 / tot2:10.7f}')\n\n\n","sub_path":"Demo periodmonitor.py","file_name":"Demo periodmonitor.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"} +{"seq_id":"441313963","text":"'''\nDevelop an api that moves a rover around on a grid.\n* You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing.\n* - The rover receives a character array of commands.\n* - Implement commands that move the rover forward/backward (f,b).\n* - Implement commands that turn the rover left/right (l,r).\n* - Implement wrapping from one edge of the grid to another. (planets are spheres after all)\n* - Implement obstacle detection before each move to a new square.\n* If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle.\n\n'''\n\n\nclass Direction:\n \n NORTH = \"NORTH\"\n WEST = \"WEST\"\n SOUTH = \"SOUTH\"\n EAST = \"EAST\"\n \n wheel = (NORTH, WEST, SOUTH, EAST)\n\nclass Point:\n \n def __init__(self, x, y):\n\n self.x = x\n self.y = y\n\nclass Rover(object):\n\n def __init__(self, point, direction):\n \n self.point = point\n self.direction = direction\n self.gridSizeX = None\n self.gridSizeY = None\n \n def turnLeft(self):\n \n index = Direction.wheel.index(self.direction)\n index = (index + 1) % 4\n self.direction = Direction.wheel[index]\n \n def turnRight(self):\n\n index = Direction.wheel.index(self.direction)\n index = (index - 1) % 4\n self.direction = Direction.wheel[index]\n \n def moveForward(self):\n if self.direction == Direction.NORTH: self.point.y += 1\n elif self.direction == Direction.SOUTH: self.point.y -= 1\n elif self.direction == Direction.EAST: self.point.x += 1\n elif self.direction == Direction.WEST: self.point.x -= 1\n else:\n raise Exception(\"unexpected direction %s\" % self.direction)\n \n self.wrapLocationOnTheGrid()\n\n \n def wrapLocationOnTheGrid(self):\n\n if self.gridSizeX != None:\n if self.point.x < 0 or self.point.x >= self.gridSizeX: self.point.x %= self.gridSizeX\n\n if self.gridSizeY != None:\n if self.point.y < 0 or self.point.y >= self.gridSizeY: self.point.y %= self.gridSizeY\n \n\n def moveBackward(self):\n if self.direction == Direction.NORTH: self.point.y -= 1\n elif self.direction == Direction.SOUTH: self.point.y += 1\n elif self.direction == Direction.EAST: self.point.x -= 1\n elif self.direction == Direction.WEST: self.point.x += 1\n else:\n raise Exception(\"unexpected direction %s\" % self.direction)\n \n self.wrapLocationOnTheGrid()\n\n ","sub_path":"rover-kata/rover.py","file_name":"rover.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"81"}