diff --git "a/719.jsonl" "b/719.jsonl" new file mode 100644--- /dev/null +++ "b/719.jsonl" @@ -0,0 +1,1693 @@ +{"seq_id":"70195818496","text":"students = [{'name': 'abha', 'age': '32', 'city': 'indore', 'clas': 'bca'}, {'name': 'arohi', 'age': '28', 'city': 'bhopal', 'clas': 'mca'}, {'name': 'vivek', 'age': '45', 'city': 'puna', 'clas': 'mca'}, {'name': 'kunal', 'age': '22', 'city': 'kargone', 'clas': 'bsc'}]\n\nwhile True:\n comd = input(\"Input 1 for add data, \\n Input 2 for search data by name,\\n enter 3 for all student \\n Input 4 for exit?: \")\n try:\n comd = int(comd)\n except:\n print(\"You enter Wrong value\")\n continue\n\n if comd == 1:\n name = input(\"Name:\")\n age = input(\"Age:\")\n city = input(\"city\")\n clas = input(\"class\")\n student = {'name':name, 'age': age, 'city':city, 'clas':clas}\n students.append(student)\n\n elif comd == 2:\n val = input(\"Enter name for find details:\")\n name=\"Not available\"\n for stu in students:\n if stu['name'] == val:\n name = stu\n break\n print(name)\n\n elif comd==4:\n exit(0)\n\n elif comd==3:\n print(students)\n\n else:\n print (\"You have enter number that not defined\")\n","repo_name":"yogeshdmca/5thfabpythonsession","sub_path":"2nd.py","file_name":"2nd.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"12995349119","text":"import math\nimport random\nimport time\n\nimport numpy as np\nfrom sklearn import svm, feature_selection, preprocessing\nfrom scipy.stats import entropy\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_auc_score, accuracy_score, matthews_corrcoef, precision_recall_curve\nfrom sklearn.model_selection import LeavePOut, LeaveOneOut, KFold, StratifiedKFold\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\n\n\ndef remove_irrelevant_features(features, X, Y):\n model = RandomForestClassifier()\n model.fit(X, Y)\n importance = model.feature_importances_\n importance_max = importance.max()\n importance_map = {f: i for f, i in zip(features, importance)}\n ro_0 = 0.1 * importance_max\n return [f for f, i in zip(features, importance) if i >= ro_0], importance_map\n\n\ndef find_weak_correlation_features(f1, U1, importance, d):\n d_log_d = d / math.log(d)\n dts = {fi: abs(importance[f1] - importance[fi]) for fi in U1}\n ro1 = max(dts.values()) * d_log_d\n return [fi for fi in U1 if dts[fi] <= ro1]\n\n\ndef find_similar_features(f1, U1, importance, df):\n model = RandomForestRegressor()\n model.fit(df[U1], df[f1])\n importance_f1 = model.feature_importances_\n importance_f1 = {f: i for f, i in zip(U1, importance_f1)}\n ret = []\n for f in U1:\n mini = min(importance[f], importance[f1])\n if importance_f1[f] >= mini:\n ret.append(f)\n return ret\n\n\ndef FCFC_clustering(Ft, importance, df):\n clusters = []\n U0 = sorted(Ft, key=lambda x: importance[x])\n d = len(U0)\n while len(U0) > 1:\n f1 = U0[0]\n U1 = U0.copy()[1:]\n c = [f1]\n U1 = find_weak_correlation_features(f1, U1, importance, d)\n c += find_similar_features(f1, U1, importance, df)\n clusters.append(c)\n U0 = [ele for ele in U0 if ele not in c]\n if len(U0) != 0:\n clusters.append(U0)\n return clusters\n\n\ndef init_particles(clusters, importance):\n cvs = [max([importance[f] for f in c]) for c in clusters]\n max_cv = max(cvs)\n pcvs = [cv / max_cv for cv in cvs]\n x = []\n for i in range(len(clusters)):\n xi = []\n for j in range(len(clusters)):\n if random.uniform(0, 1) < pcvs[j]:\n xi.append(random.randint(1, len(clusters[j])))\n else:\n xi.append(0)\n x.append(xi)\n return x\n\n\ndef get_best(x, clusters, df, pbest=None, pbest_scores=None):\n k = 0\n new_pbests = []\n new_pbests_scores = []\n gbest = None\n gbest_score = None\n for xi in x:\n model = svm.SVC()\n fs = [c[xij - 1] for xij, c in zip(xi, clusters) if xij > 0]\n fx = df[fs]\n if fx.empty:\n score = 0\n else:\n y = df['y']\n model.fit(fx, y)\n score = model.score(fx, y)\n if pbest is None or pbest_scores[k] < score:\n new_pbests.append(xi)\n new_pbests_scores.append(score)\n else:\n new_pbests.append(pbest[k])\n new_pbests_scores.append(pbest_scores[k])\n if gbest is None or gbest_score < new_pbests_scores[-1]:\n gbest = new_pbests[-1]\n gbest_score = new_pbests_scores[-1]\n k += 1\n return new_pbests, new_pbests_scores, gbest\n\n\ndef IBPSO(clusters, importance, max_iters, df):\n x = init_particles(clusters, importance)\n pbest, pbest_scores = None, None\n gbest = None\n i = 0\n while gbest is None or max_iters > i:\n pbest, pbest_scores, gbest = get_best(x, clusters, df, pbest, pbest_scores)\n for pb, xi in zip(pbest, x):\n for j in range(len(xi)):\n if random.uniform(0, 1) > 0.5:\n g = random.gauss(0, 1)\n xi[j] = math.ceil((pb[j] + gbest[j]) / 2) + math.ceil(g * abs(pb[j] - gbest[j]))\n if xi[j] < 0:\n xi[j] = 0\n elif xi[j] > len(clusters[j]):\n xi[j] = len(clusters[j])\n else:\n xi[j] = pb[j]\n i += 1\n ft = [c[j - 1] for c, j in zip(clusters, gbest) if j > 0]\n return ft\n\n\ndef New_HFS_C_P(X, Y, max_iters=50):\n df = pd.DataFrame(X)\n df['y'] = Y\n x = pd.DataFrame(X)\n cols = df.columns.to_list()\n features = x.columns.to_list()\n Ft, importance = remove_irrelevant_features(features, x, Y)\n clusters = FCFC_clustering(Ft, importance, df)\n chosen = IBPSO(clusters, importance, max_iters, df)\n ret = []\n for f in features:\n a = 1 if f in chosen else 0\n ret.append(a)\n return ret, None\n\n\ndef get_cv(df):\n n = df.shape[0]\n if n < 50:\n return LeavePOut(2), 'LeavePairOut'\n if n < 100:\n return LeaveOneOut(), 'LeaveOneOut'\n if n < 1000:\n return StratifiedKFold(n_splits=10), '10Folds'\n return StratifiedKFold(n_splits=5), '5Folds'\n\n\ndef run_classification(model, X, y):\n cv, cv_name = get_cv(X)\n print(cv_name)\n fit_times = []\n pred_times = []\n aucs = []\n accs = []\n mccs = []\n praucs = []\n total_folds = cv.get_n_splits(X, y)\n if len(y.value_counts()) > 2:\n mult = 'ovo'\n else:\n mult = 'raise'\n for train_index, test_index in cv.split(X, y):\n X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n y_train, y_test = y[train_index], y[test_index]\n fit_time = time.time()\n model.fit(X_train, y_train)\n fit_times.append(time.time() - fit_time)\n pred_time = time.time()\n probs = model.predict_proba(X_test)\n pred_times.append(time.time() - pred_time)\n preds = model.predict(X_test)\n try:\n aucs.append(roc_auc_score(y_test, probs, multi_class=mult))\n except Exception as e:\n try:\n aucs.append(roc_auc_score(y_test, probs[:, 1], multi_class=mult))\n except Exception as e:\n aucs.append(None)\n accs.append(accuracy_score(y_test, preds))\n mccs.append(matthews_corrcoef(y_test, preds))\n try:\n precision, _, _ = precision_recall_curve(y_test, probs[:, 1], pos_label=y_test.unique()[1,])\n except:\n precision = None\n praucs.append(precision)\n return fit_times, pred_times, aucs, accs, mccs, praucs, total_folds, cv_name\n\n\ndef get_model(model):\n models = {'RandomForest': RandomForestClassifier(), 'LogisticRegression': LogisticRegression(),\n 'svm': SVC(probability=True),\n 'NB': GaussianNB(), 'knn': KNeighborsClassifier()}\n return models[model]\n\n\nif __name__ == \"__main__\":\n ks = [1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 50, 100]\n models = ['svm', 'knn', 'RandomForest', 'NB', 'LogisticRegression']\n # ks = [1, 2]\n names = ['CLL-SUB-111', 'ALLAML', 'BASEHOCK', 'COIL20', 'Carcinom', 'pone.0202167.s016', 'pone.0202167.s017',\n 'bladderbatch', 'ayeastCC', 'breastCancerVDX', 'curatedOvarianData', 'leukemiasEset', 'Lung', 'Lymphoma',\n 'MLL', 'SRBCT', 'CNS', 'pone.0202167.s011', 'pone.0202167.s012', 'pone.0202167.s015']\n for i in [5]:\n print(f'{i} --------------------------------------------------------------------------------------------')\n df1 = pd.read_csv(f'datasets/dataset_{i}.csv').drop(columns=['Unnamed: 0'])\n X = df1.drop(columns=['y'])\n Y = df1['y']\n save = pd.DataFrame(\n columns=['Dataset Name', 'Number of samples', 'Original Number of features', 'Filtering Algorithm',\n 'Learning algorithm', 'Number of features selected (K)', 'CV Method', 'Fold', 'Measure Type',\n 'Measure Value', 'List of Selected Features Names', 'Selected Features scores'])\n for k in ks:\n start = time.time()\n t = feature_selection.SelectKBest(New_HFS_C_P, k=k)\n new_x = t.fit_transform(X, Y)\n feature_selection_time = time.time() - start\n names_f = t.get_feature_names_out()\n ind = [np.where(t.feature_names_in_ == name)[0][0] for name in names_f]\n scores = t.scores_[ind]\n for m in models:\n model = get_model(m)\n fit_times, pred_times, aucs, accs, mccs, praucs, total_folds, cv_name = run_classification(model,\n pd.DataFrame(\n new_x),\n Y)\n row_auc = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds, 'AUC', aucs,\n str(names_f), scores]\n save.loc[len(save)] = row_auc\n row_acc = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds, 'ACC', accs,\n str(names_f), scores]\n save.loc[len(save)] = row_acc\n row_mcc = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds, 'MCC', mccs,\n str(names_f), scores]\n save.loc[len(save)] = row_mcc\n row_prauc = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds, 'PR-AU',\n praucs, str(names_f), scores]\n save.loc[len(save)] = row_prauc\n row_pred_time = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds,\n 'prediction time', pred_times, str(names_f), scores]\n save.loc[len(save)] = row_pred_time\n row_fit_time = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds, 'fit time',\n fit_times, str(names_f), scores]\n save.loc[len(save)] = row_fit_time\n row_selection_time = [names[i], X.shape[0], X.shape[1], 'New_HFS-C-P', m, k, cv_name, total_folds,\n 'feature selection time', feature_selection_time, str(names_f), scores]\n save.loc[len(save)] = row_selection_time\n\n save.to_csv(f'res_{i}_new.csv')\n","repo_name":"maimonin/ML4","sub_path":"New_HFS-C-P.py","file_name":"New_HFS-C-P.py","file_ext":"py","file_size_in_byte":10466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"70347574654","text":"#!/usr/bin/env python\n\nimport sys\nimport unicodedata\n\nif sys.version_info[0] < 3:\n # PYTHON 2.7.8 SOLUTION\n\n text = unicode(raw_input(), 'utf')\n\n # unicode() is enough for anything between UCS-2 and single-code-unit UTF-16\n # characters, but some shenanigans are in order so that double-code-unit\n # UTF-16 characters (i.e. surrogate pairs) behave, otherwise the reversal\n # will reverse each individual code unit, rather than the whole UTF-8 code\n # point.\n newstr = \"\"\n batch = []\n for i in range(len(text)-1, -1, -1):\n uname = unicodedata.name(text[i], '')\n if 'COMBINING' in uname or uname == \"\":\n batch.insert(0, text[i])\n else:\n if len(batch) > 0:\n newstr += \"\".join(batch)\n batch = []\n newstr += text[i]\n\n print(newstr)\nelse:\n # PYTHON 3.4.1 SOLUTION\n\n # raw_input is now input in python 3, and unicode support is built right in\n # (even handles surrogate pairs! Glorious!)\n print(input()[::-1])\n # Easy!\n","repo_name":"hlissner/practice","sub_path":"other/text/reverse_string/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"79"} +{"seq_id":"35044811135","text":"\"\"\"\n Prim:\n - Appending the most small edge among seen nodes\n - Using heapq\n Kruskal:\n - Checking all edges in ascending order and appending edge if it connects to new node\n - Using Union-Find Tree\n O(ElogV)\n\"\"\"\nimport heapq\nfrom src import UnionFind\n\ndef prim(edges, num_nodes):\n # edges: adjacent list\n heap = []\n visited = [False for i in range(num_nodes)]\n heapq.heappush(heap, [0, 0])\n cost = 0\n connection = 0\n while heap:\n w, nx = heapq.heappop(heap)\n if visited[nx]:\n continue\n cost += w\n connection += 1\n visited[nx] = True\n for edge in edges[nx]:\n heapq.heappush(heap, [edge[1], edge[0]])\n if connection == num_nodes:\n break\n return cost\n\n\ndef kruskal(edges, num_nodes):\n # edges: simple edge list such as (from, to, cost)\n uf = UnionFind(num_nodes)\n edges = [(w, n1, n2) for (n1, n2, w) in edges]\n edges.sort()\n cost = 0\n for edge in edges:\n w, n1, n2 = edge\n if uf.issame(n1, n2):\n continue\n uf.unite(n1, n2)\n cost += w\n return cost\n","repo_name":"meguruin/pratice_algo_and_data","sub_path":"src/minimum_spanning_tree.py","file_name":"minimum_spanning_tree.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"74224798015","text":"import json\n\nfrom . models import *\n\ndef cookieCart(request):\n try:\n cart = json.loads(request.COOKIES['cart'])\n except:\n cart = {}\n print('Cart:', cart)\n items = []\n orders = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False}\n cartItems = orders['get_cart_items']\n\n for i in cart:\n try:\n cartItems += cart[i][\"quantity\"]\n\n product = Product.objects.get(id=i)\n total = (product.pro_price * cart[i]['quantity'])\n\n orders['get_cart_total'] += total\n orders['get_cart_items'] += cart[i]['quantity']\n\n item = {\n 'products': {\n 'id': product.id,\n 'pro_price': product.pro_price,\n 'pro_name': product.pro_name,\n 'pro_image': product.pro_image,\n },\n 'quantity': cart[i][\"quantity\"],\n 'get_total': total\n }\n\n items.append(item)\n\n if product.digital == False:\n order['shipping'] = True\n except:\n pass\n\n return {'orders': orders,\n 'items':items,\n 'cartItems': cartItems}\n\ndef cartData(request):\n if request.user.is_authenticated:\n costumer = request.user.customer\n orders, created = order.objects.get_or_create(customer=costumer, complete=False)\n items = orders.orderitem_set.all()\n cartItems = orders.get_cart_items\n\n else:\n cookieData = cookieCart(request)\n cartItems = cookieData['cartItems']\n orders = cookieData['orders']\n items = cookieData['items']\n\n return {'items': items,'orders': orders, 'cartItems': cartItems }\n\ndef guestOrder(request, data):\n print('user is not login')\n print('Data', request.body)\n print('COOKIES:', request.COOKIES)\n name = data['form']['name']\n email = data['form']['email']\n\n cookieData = cookieCart(request)\n items = cookieData['items']\n\n customer, create = Customer.objects.get_or_creat(\n email=email,\n\n )\n customer.name = name\n customer.save()\n\n orders = order.objects.create(\n customer=customer,\n complete=False\n )\n for item in items:\n product = Product.objects.get(id=item['products']['id'])\n\n orderItems = orderitem.objects.create(\n product=product,\n order=order,\n quantity=item['quantity']\n\n )\n\n\n return customer, orders\n","repo_name":"Jimuel1920/Final_lunaxxCafe","sub_path":"main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"72536750016","text":"def getPrimeList(num):\n global primes\n primes = []\n\n if num < 2:\n return primes\n for i in range(2, num+1):\n isPrime = True\n for j in primes:\n if i % j == 0:\n isPrime = False\n break\n elif j > i**0.5:\n break\n if isPrime:\n primes.append(i)\n return primes\n\na, b = map(int, input().split())\nnum = b - a + 1\ngetPrimeList(b)\n\nfor i in primes:\n num -= b // i ** 2\n\nprint(num)","repo_name":"ghyeon0/bojsolve","sub_path":"boj1016.py","file_name":"boj1016.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"35714599449","text":"from tools import *\nfrom statistics import mode\n\n\ndef nn(test_img, A, norm, reduced=False):\n z = []\n for img in A:\n if norm == 'cos':\n cos = np.dot(test_img, img) / (np.linalg.norm(test_img) * np.linalg.norm(img))\n z.append(1 - cos)\n else:\n z.append(np.linalg.norm(img - test_img, norm))\n x = np.argmin(z)\n if reduced:\n return x + 1\n else:\n return find_person(x)\n\n\ndef knn(test_img, A, norm, k=5):\n z = []\n for img in A:\n if norm == 'cos':\n cos = np.dot(test_img, img) / (np.linalg.norm(test_img) * np.linalg.norm(img))\n z.append(1-cos)\n else:\n z.append(np.linalg.norm(img - test_img, norm))\n indices_sort = np.argsort(z)\n persons = []\n for i in range(0, k):\n persons.append(find_person(indices_sort[i]))\n return mode(persons)\n\n","repo_name":"prodangp/acs-project","sub_path":"src/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"34540947158","text":"import logging\nfrom jsonformatter import JsonFormatter\nimport os\nimport torch\nfrom transformers import AutoTokenizer\nimport onnxruntime as ort\nfrom pydantic import BaseModel\n\n#\n# Models for predict requests\n#\n\nclass PredictInput(BaseModel):\n text: str\n\nclass PredictResponse(BaseModel):\n text: str = None\n label: str = None\n status: str\n\n#\n# Helper classes and functions\n#\n\nformat = '''{\n \"level\": \"levelname\",\n \"logger_name\": \"%(name)s.%(funcName)s\",\n \"timestamp\": \"asctime\",\n \"message\": \"message\"\n}'''\n\ndef get_logger(name: str, level: int = logging.INFO):\n logger = logging.getLogger(name)\n logger.setLevel(level)\n formatter = JsonFormatter(format)\n\n logHandler = logging.StreamHandler()\n logHandler.setFormatter(formatter)\n logHandler.setLevel(level)\n\n logger.addHandler(logHandler)\n return logger\n\nclass SKLearnWrapper:\n def __init__(self, tokenizer=None, st_model=None, clf=None):\n self.tokenizer = tokenizer\n self.st_model = st_model\n self.clf = clf\n \n def mean_pooling(self, model_output, attention_mask):\n token_embeddings = torch.from_numpy(model_output)\n attention_mask = torch.from_numpy(attention_mask)\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\n sum_embeddings = torch.sum(token_embeddings * input_mask_expanded, 1)\n sum_mask = torch.clamp(input_mask_expanded.sum(1), min=1e-9)\n return sum_embeddings / sum_mask\n \n def encode(self, tokenized_sentences):\n \"\"\"\n 'tokenized_sentences' is of type transformers.tokenization_utils_base.BatchEncoding\n but onnxruntime expects a python dict obtained by 'tokenized_sentences.data'\n \"\"\"\n embeddings = self.st_model.run(None, tokenized_sentences.data)\n pooled_embeddings = self.mean_pooling(embeddings[0], tokenized_sentences[\"attention_mask\"])\n return pooled_embeddings\n \n def predict_head(self, embeddings):\n \"\"\"\n Predict class with skl2onnx scikit-learn model\n \"\"\"\n input_name = self.clf.get_inputs()[0].name\n label_name = self.clf.get_outputs()[0].name\n predicted_classes = self.clf.run([label_name], {input_name: embeddings.numpy()})[0]\n return predicted_classes\n\n def predict(self, sentences):\n \"\"\"\n Full prediction pipeline\n \"\"\"\n inputs = self.tokenizer(sentences, padding=True, truncation=True, return_tensors='np')\n embeddings = self.encode(inputs)\n return self.predict_head(embeddings)\n\n def load(self, path):\n self.tokenizer = AutoTokenizer.from_pretrained(path)\n self.st_model = ort.InferenceSession(os.path.join(path, \"model.onnx\"), providers=['CPUExecutionProvider'])\n self.clf = ort.InferenceSession(os.path.join(path, \"model_head.onnx\"))\n\nclass SetFitPipeline:\n def __init__(self, model_name_or_path) -> None:\n base_model = SKLearnWrapper()\n base_model.load(model_name_or_path)\n self.model = base_model\n\n def __call__(self, inputs, *args, **kwargs):\n model_outputs = self.model.predict(inputs)\n return model_outputs\n","repo_name":"OmdenaAI/latam-chapters-news-validator","sub_path":"src/tasks/task-3-plugin/model_api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"79"} +{"seq_id":"6700689849","text":"position = {1:7, 2:5}\nscore = {1:0, 2:0}\n\ndef play_one_round(n):\n \n die = [3*n-2, 3*n-1, 3*n]\n\n die = [(x-1)%100 + 1 for x in die]\n\n player = (n-1)%2 + 1\n\n space = (position[player] + sum(die) -1)%10 + 1\n position[player] = space\n score[player] += space\n\n\ndef play():\n\n n = 1\n\n while True:\n play_one_round(n)\n #print(n, position, score)\n if max(score.values()) >= 1000:\n return min(score.values())*n*3\n n += 1\n\n\n\nprint(play())\n\n\n","repo_name":"DavidBartram/advent-of-code","sub_path":"2021/day21-1.py","file_name":"day21-1.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"1816018466","text":"from django.conf.urls import url\n\nfrom . import views\n\n\napp_name = 'photos'\n\nurlpatterns = [\n url(r'^new/$', views.create_post, name='new'),\n url(r'^(?P[0-9]+)/$', views.view_post, name='view'),\n url(r'^$', views.list_posts, name='list'),\n url(r'^comments/(?P[0-9]+)/delete/$', views.delete_comment, name='delete_comment')\n]\n","repo_name":"nam2582/pystagram","sub_path":"photos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"42052336449","text":"import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport os\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nthis_path = os.path.dirname(os.path.realpath(__file__))\n\nbase_dir = os.path.join(this_path, '../data/')\ntrain_csv = os.path.join(base_dir, 'train.csv')\n\ndef split(df, test_ratio=0.3):\n target_dir = os.path.join(base_dir, str(dt.date.today()))\n if os.path.exists(target_dir):\n raise Exception('{} already exists'.format(target_dir))\n else:\n os.system('mkdir -p {}'.format(target_dir))\n test_size = int(df.shape[0] * test_ratio)\n sss = StratifiedShuffleSplit(n_splits=1, test_size=test_size)\n indices = sss.split(X=df, y=df.target).next()\n df_train = df.iloc[indices[0]]\n df_test = df.iloc[indices[1]]\n df_train.to_csv(os.path.join(target_dir, 'train.csv'), index=False)\n df_test.target.to_csv(os.path.join(target_dir, '.test_target.csv'), index=False)\n del df_test['target']\n df_test.to_csv(os.path.join(target_dir, 'test.csv'), index=False)\n return None\n\n\nif __name__ == '__main__':\n df = pd.read_csv(train_csv)\n split(df)\n","repo_name":"changyaochen/Porto_Seguro","sub_path":"py/split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"28614632371","text":"\"\"\"Swiss Rotors Barcode scanner interface\nProgram scans barcodes, looks for data in file and send it via EGD protocol to Fanuc industrial robot.\n\nAuthor: Piotr Smarzyński\n\"\"\"\nfrom barcode_parsing import parseBCR\nfrom scanner_api import scanBCR, serialPorts\nimport socket\nfrom udp_communication import get_ip, parse_ip, send_data\nfrom data_packing import pack_data, pack_data_egd\nfrom file_handling import searchLineFromBCR, checkFile\nfrom threads import parse_and_send_loop, scanning_loop, gui_queue\nfrom thread_print import s_print\nfrom gui import gui\n\nimport argparse\nfrom threading import Thread\nfrom queue import Queue\nfrom time import sleep\nimport serial\nimport sys\nfrom colorama import Fore, init\n\ndef main():\n init() #colorama\n parser = argparse.ArgumentParser()\n parser.add_argument('-pipe' ,'--pipeline', type=int, default=8, help='Pipeline no. Defaults to 8.')\n parser.add_argument('-pipe2' ,'--pipeline2', type=int, default=7, help='Pipeline no. Defaults to 7.')\n parser.add_argument('-ip', '--ip_address', type=str, default='192.168.0.12', help='IP address of 1st receiver. Defaults to 192.168.0.10')\n parser.add_argument('-ip2', '--ip_address2', type=str, default='192.168.0.11', help='IP address of 2nd receiver. Defaults to 192.168.0.11')\n parser.add_argument('-s', '--station', type=int, default=0, help='Station no. Defaults to 0')\n parser.add_argument('-s2', '--station2', type=int, default=1, help='Station no. Defaults to 1')\n parser.add_argument('-c', '--com_port', type=str, help='COM port of 1st scanner')\n parser.add_argument('-c2', '--com_port2', type=str, help='COM port of 2nd scanner')\n parser.add_argument('-p', '--period', type=float, default=0.05, help='Time period to send data over EGD protocol. Defaults to 0.05')\n parser.add_argument('-f', '--filename', type=str, default='barcodes.txt', help='Name of file to search in. Defaults to barcodes.txt')\n args = parser.parse_args()\n \n\n barcode_queue = Queue()\n checkFile(args.filename)\n\n com_ports = serialPorts()\n \n\n print('Active COM ports: ', com_ports)\n if len(com_ports) == 0:\n print(Fore.LIGHTRED_EX+ \"No devices connected! Check USB connection of the scanner.\", Fore.RESET)\n sys.exit()\n\n if args.com_port is None and len(com_ports) > 0:\n com_port = com_ports[0]\n else:\n print('Forced COM port 1:', args.com_port)\n com_port = args.com_port\n\n if args.com_port2 is None and len(com_ports) > 1:\n com_port2 = com_ports[1]\n else:\n print('Forced COM port 2:', args.com_port2)\n com_port2 = args.com_port2\n\n threads = []\n threads.append(Thread(name=\"scanning_loop\",\n target=scanning_loop, \n kwargs={'queue_output': barcode_queue,\n 'com_port': com_port,\n 'baud':9600, \n 'timeout':10},\n daemon=True))\n\n if com_port2 is not None:\n threads.append(Thread(name=\"scanning_loop2\",\n target=scanning_loop, \n kwargs={'queue_output': barcode_queue,\n 'com_port': com_port2,\n 'baud':9600, \n 'timeout':10},\n daemon=True))\n\n\n threads.append(Thread(name=\"parse_and_send_loop\",\n target=parse_and_send_loop,\n kwargs={'queue_input': barcode_queue,\n 'ip_address_dest': [args.ip_address, args.ip_address2],\n 'station_nos': [args.station, args.station2],\n 'pipelines': [args.pipeline, args.pipeline2], \n 'filename': args.filename,\n 'period': args.period},\n daemon=True))\n\n threads.append(Thread(name=\"gui\",\n target=gui,\n kwargs={},\n daemon=True))\n\n for thread in threads:\n thread.start()\n s_print('Thread', thread.name, 'started!')\n\n try:\n while True:\n sleep(1)\n except KeyboardInterrupt:\n s_print(\"Exiting program\")\n\n #TODO close nicely\n\nif __name__ == \"__main__\":\n main() \n ","repo_name":"piotr-smarzynski-sr/Scanner_SW","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"14101186508","text":"import socket \r\n\r\nconnection = (\"10.0.2.15\", 9999)\r\nclientSocket = socket.socket()\r\nclientSocket.connect(connection)\r\ntry:\r\n while True:\r\n data = input(\"> \")\r\n clientSocket.send(str.encode(data))\r\n received = clientSocket.recv(2048)\r\n print(\"Server: {}\".format(received.decode('utf-8')))\r\nexcept KeyboardInterrupt:\r\n print(\"Exiting..\")\r\n\r\n \r\n","repo_name":"kratos1398/python_hacking_code","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"38582018564","text":"import csv\nimport getopt\nimport math\nimport os\nimport sys\n\nPROG = os.path.basename(sys.argv[0])\n\ndef main():\n opts, args = getopt.getopt(sys.argv[1:], \"s:h\")\n\n days = 253\n sep = \",\"\n for opt, arg in opts:\n if opt == \"-s\":\n sep = arg\n elif opt == \"-h\":\n usage()\n return 0\n\n if len(args) > 1:\n usage(f\"{PROG} accepts zero or one positional arguments\")\n return 1\n\n if args:\n days = int(args[0])\n\n fields = next(csv.reader(sys.stdin, delimiter=sep))\n\n mean = float(fields[1])\n std = float(fields[3])\n print(mean / std * math.sqrt(days))\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"smontanaro/csvprogs","sub_path":"data_filters/data_filters/sharpe.py","file_name":"sharpe.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"26268406370","text":"import argparse\nimport logging\nimport numpy as np\nimport pandas as pd\n\nimport arg_needle_lib\n\nlogging.basicConfig(\n format='%(asctime)s %(levelname)-8s %(message)s',\n level=logging.INFO,\n datefmt='%Y-%m-%d %H:%M:%S')\n\n\n# Disable default help, credit to https://stackoverflow.com/a/57582191/\nparser = argparse.ArgumentParser(description=\"Run association using the ARG.\", add_help=False)\nbasic = parser.add_argument_group(\"Basic arguments\")\noptional = parser.add_argument_group(\"Optional arguments\")\n\n# Basic options\nbasic.add_argument(\"--arg_path\", action=\"store\", default=\"files/chr1.chunk1.argn\",\n help=\"Path to .argn (ARG format) or .trees/.tsz (tskit/tszip format) file (default='files/chr1.chunk1.argn').\")\nbasic.add_argument(\"--arg_sample_path\", action=\"store\", default=\"files/example.sample\",\n help=\"Path to file listing diploid samples in the same order as haploid leaves of the ARG (default='files/example.sample').\")\nbasic.add_argument(\"--arg_id\", action=\"store\", default=\"chr1.chunk1\",\n help=\"Identifier for input ARG used for writing output.\" \\\n \" Must start with chromosome number followed by a period, e.g., chr1.* or chr22.* (default='chr1.chunk1').\")\nbasic.add_argument(\"--residualised_pheno_path\", action=\"store\", default=\"files/example.pheno\",\n help=\"Path to the phenotype, with any covariates residualised out.\" \\\n \" Should also residualise out the LOCO predictor for ARG-MLMA workflows (default='files/example.pheno').\")\nbasic.add_argument(\"--out_path\", action=\"store\", default=\"files/results\",\n help=\"Output path prefix for *.tab.gz and *.haps.gz output (default='files/results').\")\n\n# Add back help, credit to https://stackoverflow.com/a/57582191/\noptional.add_argument(\n \"-h\", \"--help\", action=\"help\", default=argparse.SUPPRESS, help=\"show this help message and exit\")\n\n# Advanced options\noptional.add_argument(\"--sampling_rate\", action=\"store\", default=0, type=float,\n help=\"Mutation rate-based testing.\" \\\n \" If positive, generates random mutations on the ARG, which are tested for association.\" \\\n \" If 0, tests all branches (default=0).\")\noptional.add_argument(\"--min_mac\", action=\"store\", default=-1, type=int,\n help=\"Minimum MAC to test (default=-1 which means no minimum). Cannot set both min_mac and min_maf.\")\noptional.add_argument(\"--min_maf\", action=\"store\", default=-1, type=float,\n help=\"Minimum MAF to test (default=-1 which means no minimum). Cannot set both min_mac and min_maf.\")\noptional.add_argument(\"--max_maf\", action=\"store\", default=-1, type=float,\n help=\"Maximum MAF to test (default=-1 which means no maximum).\")\noptional.add_argument(\"--haps_threshold\", action=\"store\", default=0, type=float,\n help=\"p-value threshold, variants with p-value lower than this threshold are written to .haps.gz output (default=0)\")\noptional.add_argument(\"--random_seed\", action=\"store\", default=1, type=int,\n help=\"Seed to use for mutation-based testing. If zero, seeds by time (default=1).\")\noptional.add_argument(\"--calibration_factor\", action=\"store\", default=1, type=float,\n help=\"Calibration factor. Used in ARG-MLMA workflows, can be set to 1 to instead run linear regression (default=1).\")\noptional.add_argument(\"--descendant_list_threshold\", action=\"store\", default=-1, type=int,\n help=\"Advanced parameter determining how ARG branch variants are represented in memory.\" \\\n \" Uses a vector of sample IDs below and a bitset above the threshold.\" \\\n \" If less than 0, always uses a vector of sample IDs (default).\" \\\n \" If memory is concern, setting to num_individuals/16 may reduce memory at the cost of greater runtime.\")\n\ndef main():\n args = parser.parse_args()\n logging.info(\"Command-line args:\")\n args_to_print = vars(args)\n for k in sorted(args_to_print):\n logging.info(k + \": \" + str(args_to_print[k]))\n\n # Set up parameters\n chromosome_field = args.arg_id.split(\".\")[0]\n chrom_num = int(chromosome_field[3:])\n snp_prefix = args.arg_id\n\n # Read in the residualised phenotype\n # Columns should be FID / IID / phenotype\n pheno_df = pd.read_csv(args.residualised_pheno_path, sep=\"\\s+|\\t+\", index_col=0, engine=\"python\")\n pheno_df = pheno_df.drop(pheno_df.columns[0], axis=1)\n pheno_df.rename(columns={pheno_df.columns[0]: \"PHENO\"}, inplace=True)\n pheno_df = pheno_df.dropna()\n residual_dict = dict(zip(pheno_df.index, pheno_df[\"PHENO\"]))\n\n # Load sample IDs\n sample_ids = []\n with open(args.arg_sample_path, \"r\") as infile:\n for i, line in enumerate(infile):\n if i >= 2:\n sample_ids.append(int(line.strip(\"\\n\").split(\" \")[0].split(\"\\t\")[0]))\n\n # Make use_sample and residual lists\n use_sample = []\n residual = []\n for sample_id in sample_ids:\n if sample_id in residual_dict:\n residual.append(residual_dict[sample_id])\n use_sample.append(True)\n else:\n residual.append(-9) # The value here does not matter, it is ignored\n use_sample.append(False)\n\n logging.info(f\"Was able to find phenotype for {sum(use_sample)} of {len(use_sample)} diploid samples\")\n\n # Load ARG and possibly change DescendantList threshold\n if args.arg_path.endswith(\".argn\"):\n arg = arg_needle_lib.deserialize_arg(args.arg_path)\n elif args.arg_path.endswith(\".trees\"):\n import tskit\n ts = tskit.load(args.arg_path)\n arg = arg_needle_lib.tskit_to_arg(ts)\n elif args.arg_path.endswith(\".tsz\"):\n import tszip\n ts = tszip.decompress(args.arg_path)\n arg = arg_needle_lib.tskit_to_arg(ts)\n else:\n raise ValueError(f\"Expected .argn / .trees / .tsz file, found {args.arg_path} instead.\")\n arg.populate_children_and_roots()\n\n if args.descendant_list_threshold >= 0:\n arg_needle_lib.DescendantList.set_threshold(args.descendant_list_threshold)\n arg_needle_lib.DescendantList.print_threshold()\n\n if args.min_maf != -1 and args.min_mac != -1:\n raise ValueError(\"Can't set both min_maf and min_mac\")\n elif args.min_mac != -1:\n min_maf = args.min_mac / (2 * np.sum(use_sample))\n else:\n min_maf = args.min_maf\n max_maf = args.max_maf\n\n logging.info(f\"Using minimum MAF = {min_maf} (note: -1 means no minimum)\")\n logging.info(f\"Using maximum MAF = {max_maf} (note: -1 means no maximum)\")\n logging.info(\"Starting to run association\")\n if args.sampling_rate == 0:\n logging.info(\"Testing all clades of the ARG\")\n max_chi2 = arg_needle_lib.association_diploid_all(\n arg, residual, use_sample, args.out_path,\n chrom_num, snp_prefix, min_maf=min_maf, max_maf=max_maf,\n write_bitset_threshold=args.haps_threshold,\n calibration_factor=args.calibration_factor,\n concise_pvalue=True)\n else:\n assert args.sampling_rate > 0\n logging.info(f\"Testing sampled mutations with rate {args.sampling_rate} and seed {args.random_seed} (note: seed 0 means use system time to seed)\")\n max_chi2 = arg_needle_lib.association_diploid_mutation(\n arg, residual, use_sample, args.out_path,\n [args.sampling_rate], args.random_seed,\n chrom_num, snp_prefix, min_maf=min_maf, max_maf=max_maf,\n write_bitset_threshold=args.haps_threshold,\n calibration_factor=args.calibration_factor,\n concise_pvalue=True)[0]\n logging.info(\"Done running association\")\n logging.info(\"Check {}.tab.gz and {}.haps.gz for output.\".format(\n args.out_path, args.out_path))\n\n logging.info(\"Finished!\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PalamaraLab/arg-needle-lib","sub_path":"example/arg_mlma/scripts/association.py","file_name":"association.py","file_ext":"py","file_size_in_byte":7622,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"73997134975","text":"import os\nimport sys\nimport json\nimport gzip\nimport tqdm\nimport collections\n\n\ndef count_dialog(rootdirpath, file_name):\n # type dialog\n types = os.listdir(rootdirpath)\n cnt_typs = collections.defaultdict(int)\n failed_file = []\n for data_type in types:\n filedirs = [os.path.join(rootdirpath, data_type)]\n while not [x for x in os.listdir(filedirs[0]) if file_name in x]:\n filedirs = [os.path.join(subdir, x) for subdir in filedirs for x in os.listdir(subdir) if\n os.path.isdir(os.path.join(subdir, x))]\n\n for thisdir in tqdm.tqdm(filedirs):\n path = os.path.join(thisdir, file_name)\n try:\n if os.path.exists(path):\n with open(path) as f:\n for x in f.readlines():\n if x.strip():\n try:\n line = json.loads(x)\n cnt_typs[data_type] += 1\n except:\n cnt_typs[data_type + \"_failed_line\"] += 1\n elif os.path.exists(path + \".gz\"):\n with gzip.open(path + \".gz\", \"rb\") as f:\n for x in f.readlines():\n if x.strip():\n try:\n line = json.loads(x)\n cnt_typs[data_type] += 1\n except:\n cnt_typs[data_type + \"_failed_line\"] += 1\n else:\n cnt_typs[\"wrong_file_type\"] += 1\n print(\"wrong data type\", thisdir)\n continue\n except:\n failed_file.append(thisdir)\n continue\n print(cnt_typs)\n print(\"failed_file:\", failed_file)\n print(\"statistic over\", file_name)\n\n\n\n\nif __name__ == '__main__':\n # \"/home/data/tripartite/aminer/yyq_scp/zhihu/\", \"zhihu\"\n # \"/home/data/tripartite/aminer/yyq_scp/baidu/\", \"baidu\"\n count_dialog(sys.argv[1], sys.argv[2])\n","repo_name":"lemon234071/data_nanny","sub_path":"task/eva/aminer/count_dialog.py","file_name":"count_dialog.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"17083293612","text":"import torch\n\nimport math\nimport os\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.cuda.amp import autocast\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\nfrom ..modules import *\nfrom ..linear import *\nfrom ..activations import *\n\n\n\n\nclass ActivationForward (nn.Module):\n def __init__ (self, config, din, projection_matrix=None, memory_index=-1):\n super(ActivationForward, self).__init__()\n \n self.din=din\n self.config=config\n self.projection_matrix = projection_matrix\n self.memory_index = memory_index\n \n \n if projection_matrix is not None:\n self.dout = projection_matrix.shape[0]\n else:\n self.dout = din\n \n \n assert memory_index == -1 or memory_index >= self.dout,\\\n \"Memory interacts with final signal\"\n \n assert memory_index == -1 or memory_index <= config.hidden_size - self.din, \\\n \"not enough space to store memory\"\n \n if projection_matrix is not None:\n head_dim = self.dout\n num_channels = config.hidden_size // head_dim\n else:\n num_channels = config.num_attention_heads\n head_dim = config.hidden_size // num_channels\n \n self.mlp_module = MLP (config.hidden_size, \\\n config, \\\n conv2d=True, \\\n transpose_intermediate=True, \\\n transpose_proj=False, \\\n conv_proj_features=num_channels, \\\n )\n \n self.mlp_gates = Gates (config)\n self.projection_ = None\n \n \n if projection_matrix is not None:\n \n assert projection_matrix.shape[1] == din,\\\n \"Projection matrix must have 'din' in second coordinate\"\n assert projection_matrix.shape[1] >= head_dim, \\\n \"Currently, this projection only works when we project down to a lower dimension\"\n assert projection_matrix.shape[1] % head_dim == 0, \\\n \"Perfect division into channels\"\n \n c_proj_init = torch.zeros((num_channels, head_dim, head_dim), dtype=self.mlp_module.c_proj.weight.dtype)\n num_useful_channels = projection_matrix.shape[1] // head_dim\n for i in range (num_useful_channels):\n c_proj_init[i] = torch.tensor(projection_matrix[:, i*head_dim: (i+1)*head_dim], dtype=self.mlp_module.c_proj.weight.dtype)\n self.mlp_module.initialize_weights(c_proj_init=c_proj_init) \n \n self.projection_ = Conv2D( nf=num_channels, nx=head_dim, transpose=True, use_einsum=self.config.use_einsum )\n with torch.no_grad(): \n self.projection_.weight.copy_(torch.zeros(head_dim, num_channels, num_channels))\n self.projection_.weight[:, :num_useful_channels, 0] = 1.\n \n else:\n c_proj_init = torch.zeros((num_channels, head_dim, head_dim), dtype=self.mlp_module.c_proj.weight.dtype)\n \n if self.memory_index != -1:\n assert memory_index % head_dim == 0, \\\n \"Memory should be divisible by the number of channels!\"\n\n mem_head_start = memory_index // head_dim\n\n c_proj_init[:mem_head_start] = torch.eye(head_dim)\n self.mlp_module.initialize_weights(c_proj_init=c_proj_init) \n else:\n c_proj_init[:] = torch.eye(head_dim)\n self.mlp_module.initialize_weights(c_proj_init=c_proj_init) \n \n #Initialize Gates\n #Ignore the changes for the prefixes!\n #w, u, v, w_bias, u_bias, v_bias\n w = torch.zeros((1, 2*config.hidden_size))\n u = torch.zeros((1, 2*config.hidden_size))\n v = torch.zeros((1, 2*config.position_dim))\n w_bias = torch.zeros(2)\n u_bias = torch.zeros(2)\n v_bias = torch.zeros(2)\n\n #Input Gate is 1 on prefixes and 0 for non-prefixes\n v [0, config.seq_length: config.position_dim] = config.gate_scale * torch.ones(config.position_dim-config.seq_length)\n\n\n #Change Gate is 0 on prefixes and 1 for non-prefixes\n v [0, config.position_dim+config.seq_length: 2*config.position_dim] = -config.gate_scale * torch.ones(config.position_dim-config.seq_length)\n v_bias [1] += config.gate_scale\n\n self.mlp_gates.initialize_weights (w, u, v, w_bias, u_bias, v_bias)\n\n \n def forward(self, hidden_states, position_embeddings):\n mlp_out = self.mlp_module.forward(hidden_states)\n if self.projection_ is not None:\n mlp_out = self.projection_(mlp_out)\n \n if self.memory_index != -1:\n assert torch.sum(torch.absolute(mlp_out[:, self.config.num_prefixes:, self.memory_index:])).item() < 1e-10,\\\n \"Memory portion not empty!\"\n\n mlp_out[:, self.config.num_prefixes:, self.memory_index: self.memory_index+self.din] += hidden_states[:, self.config.num_prefixes:, :self.din]\n\n gate_out = self.mlp_gates.forward(hidden_states, mlp_out, position_embeddings)\n \n return gate_out\n \n\n \n","repo_name":"abhishekpanigrahi1996/transformer_in_transformer","sub_path":"tint_main/utils/activation/forward.py","file_name":"forward.py","file_ext":"py","file_size_in_byte":5439,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"79"} +{"seq_id":"18987291837","text":"#Kunal Gautam\n#Codewars : @Kunalpod\n#Problem name: Get Planet Name By ID\n#Problem level: 8 kyu\n\ndef get_planet_name(id):\n if id==1: return \"Mercury\"\n if id==2: return \"Venus\"\n if id==3: return \"Earth\"\n if id==4: return \"Mars\"\n if id==5: return \"Jupiter\"\n if id==6: return \"Saturn\"\n if id==7: return \"Uranus\"\n if id==8: return \"Neptune\"\n","repo_name":"Kunalpod/codewars","sub_path":"get_planet_name_by_id.py","file_name":"get_planet_name_by_id.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"32250753858","text":"\"\"\"\nAutocomplete\n\nFor this question, we first give you a series of n words. For every word, we first add it to our dictionary, and then we type out \nthe word using the minimum number of strokes to autocomplete the word. What is the minimum total number of strokes needed to type\nout all the words?\nConstraints\n\n1 <= n <= 100001\n\nSum of the lengths of all the strings will not exceed 100001.\n\nWords will only have lowercase letters.\nExamples:\nExample 1:\nInput 1: words = [\"hi\", \"hello\", \"bojack\", \"hills\", \"hill\"]\nOutput 1: 11\nExplanation:\n\nWe put \"hi\" in our dictionary and then we only need to type out \"h\", which is 1 stroke, before it autocompletes to \"hi\". We put \"hello\"\nin our dictionary and then we only need to type out \"he\", which is 2 strokes, before it autocompletes to \"hello\". We put \"bojack\" in our\ndictionary and then we only need to type out \"b\" which is 1 stroke, before it autocompletes to \"bojack\". We put \"hills\" in our dictionary\nand then we only need to type out \"hil\"(since we have \"hi\") which is 3 strokes, before it autompletes to \"hills\". Lastly, we put \"hill\" \nin our dictionary and we need to type out \"hill\" which is 4 strokes. Adding these strokes up we have 1 + 2 + 1 + 3 + 4 = 11 which we then\noutput.\n\"\"\"\n\nclass Trie:\n def __init__(self):\n self.root = {}\n\n def insert(self, word: str) -> None:\n node = self.root\n for char in word:\n if char not in node:\n node[char] = [1, {}]\n else:\n node[char][0] += 1\n node = node[char][1]\n node[\"*\"] = \"*\" \n return\n\n def count_strokes(self, word: str) -> int:\n node = self.root\n count = 0\n for char in word:\n count += 1\n if char not in node:\n return -1\n if node[char][0] == 1:\n return count\n node = node[char][1] \n return count\n\n \n\ndef autocomplete(words: list[int]) -> int:\n trie = Trie()\n count = 0\n for word in words:\n trie.insert(word)\n count += trie.count_strokes(word)\n return count \n\n\nif __name__ == \"__main__\":\n words = [\"hi\", \"hello\", \"bojack\", \"hills\", \"hill\"]\n print(autocomplete(words))\n","repo_name":"astitwlathe/questions_prep","sub_path":"codes/Trie/auto_comp.py","file_name":"auto_comp.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"42708230915","text":"#!/usr/bin/python3\n\"\"\"\nScript to retrieve and display states and their associated cities using\nSQLAlchemy.\n\"\"\"\n\nfrom sys import argv\nfrom relationship_state import Base, State\nfrom relationship_city import City\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\nif __name__ == \"__main__\":\n # check for the correct number of command-line arguments\n if len(argv) != 4:\n print(\"Usage: {} \".format(argv[0]))\n exit(1)\n\n # create a database engine and establish a connection\n db_connection_url = 'mysql+mysqldb://{}:{}@localhost/{}'.format(\n argv[1], argv[2], argv[3])\n engine = create_engine(db_connection_url, pool_pre_ping=True)\n\n # create the tables if they do not exist\n Base.metadata.create_all(engine)\n\n # create a session to interact with the database\n session = Session(engine)\n\n # cquery and display all states and their associated cities\n states = session.query(State).order_by(State.id).all()\n\n for state in states:\n print(\"State ID: {} - Name: {}\".format(state.id, state.name))\n for city in state.cities:\n print(\" City ID: {} - Name: {}\".format(city.id, city.name))\n\n # commit the changes to the database and close the session\n session.commit()\n session.close()\n","repo_name":"sakhi-4096/alx-higher_level_programming","sub_path":"0x0F-python-object_relational_mapping/101-relationship_states_cities_list.py","file_name":"101-relationship_states_cities_list.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"71603032894","text":"import math\nimport time\nimport tensorflow as tf\nfrom tensorflow.contrib.session_bundle import exporter\nfrom tensorflow.python.saved_model import builder as saved_model_builder\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import signature_def_utils\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.saved_model import utils\nfrom tensorflow.python.util import compat\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\ntf.app.flags.DEFINE_string(\"ps_hosts\", \"\", \"Comma-separated list of hostname:port pairs\")\n\ntf.app.flags.DEFINE_string(\"worker_hosts\", \"\", \"Comma-separated list of hostname:port pairs\")\n\ntf.app.flags.DEFINE_string(\"job_name\", \"\", \"One of 'ps', 'worker'\")\n\ntf.app.flags.DEFINE_integer(\"task_index\", 0, \"Index of task within the job\")\n\ntf.app.flags.DEFINE_integer(\"hidden_units\", 100, \"Number of units in the hidden layer of the NN\")\n\ntf.app.flags.DEFINE_string(\"data_dir\", \"MNIST_data\", \"Directory for storing mnist data\")\n\ntf.app.flags.DEFINE_integer(\"batch_size\", 100, \"Training batch size\")\n\ntf.app.flags.DEFINE_string(\"model_dir\", \"trained_model\", \"Directory for storing the trained model\")\n\ntf.app.flags.DEFINE_string(\"log_dir\", \"training_log\", \"Directory for storing the training log\")\n\nFLAGS = tf.app.flags.FLAGS\n\nIMAGE_PIXELS = 28\n\n\n\ndef main(_):\n ps_hosts = FLAGS.ps_hosts.split(\",\")\n\n worker_hosts = FLAGS.worker_hosts.split(\",\")\n cluster = tf.train.ClusterSpec({\"ps\": ps_hosts, \"worker\": worker_hosts})\n server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\n\n if FLAGS.job_name == \"ps\":\n server.join()\n\n elif FLAGS.job_name == \"worker\":\n start_time = time.time()\n with tf.device(\n tf.train.replica_device_setter(worker_device=\"/job:worker/task:%d\" % FLAGS.task_index,\n cluster=cluster)):\n hid_w = tf.Variable(\n tf.truncated_normal([IMAGE_PIXELS * IMAGE_PIXELS, FLAGS.hidden_units], stddev=1.0 / IMAGE_PIXELS),\n name=\"hid_w\")\n\n hid_b = tf.Variable(tf.zeros([FLAGS.hidden_units]), name=\"hid_b\")\n\n sm_w = tf.Variable(tf.truncated_normal([FLAGS.hidden_units, 10], stddev=1.0 / math.sqrt(FLAGS.hidden_units)),\n name=\"sm_w\")\n\n sm_b = tf.Variable(tf.zeros([10]), name=\"sm_b\")\n\n x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS])\n\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)\n\n hid = tf.nn.relu(hid_lin)\n\n y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))\n\n loss = -tf.reduce_sum(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))\n\n global_step = tf.Variable(0)\n\n train_op = tf.train.AdagradOptimizer(0.01).minimize(loss, global_step=global_step)\n\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n saver = tf.train.Saver()\n\n summary_op = tf.summary.merge_all()\n\n init_op = tf.global_variables_initializer()\n\n sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0), logdir=FLAGS.log_dir, init_op=init_op,\n summary_op=summary_op, saver=saver, global_step=global_step, save_model_secs=600)\n mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)\n with sv.managed_session(server.target) as sess:\n step = 0\n\n while not sv.should_stop() and step < 100000:\n batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)\n train_feed = {x: batch_xs, y_: batch_ys}\n\n _, step = sess.run([train_op, global_step], feed_dict=train_feed)\n\n if step % 100 == 0:\n print(\"global step: {}, accuracy:{}\".format(step, sess.run(accuracy,\n feed_dict={x: mnist.test.images,\n y_: mnist.test.labels})))\n\n if sv.is_chief:\n sess.graph._unsafe_unfinalize()\n classification_inputs = utils.build_tensor_info(x)\n classification_outputs_classes = utils.build_tensor_info(y)\n \n classification_signature = signature_def_utils.build_signature_def(\n inputs={signature_constants.CLASSIFY_INPUTS: classification_inputs},\n outputs={\n signature_constants.CLASSIFY_OUTPUT_CLASSES: classification_outputs_classes,\n signature_constants.CLASSIFY_OUTPUT_SCORES: classification_outputs_classes\n },\n method_name=signature_constants.CLASSIFY_METHOD_NAME)\n \n tensor_info_x = utils.build_tensor_info(x)\n tensor_info_y = utils.build_tensor_info(y)\n \n prediction_signature = signature_def_utils.build_signature_def(\n inputs={'images': tensor_info_x},\n outputs={'scores': tensor_info_y},\n method_name=signature_constants.PREDICT_METHOD_NAME)\n \n builder = saved_model_builder.SavedModelBuilder(FLAGS.model_dir)\n legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')\n \n builder.add_meta_graph_and_variables(sess,\n [tag_constants.SERVING],\n signature_def_map={\n 'predict_images':\n prediction_signature,\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:\n classification_signature,\n },\n clear_devices=True,\n legacy_init_op=legacy_init_op)\n sess.graph.finalize()\n builder.save()\n\n end_time = time.time()\n print('waste time:{}'.format(end_time - start_time))\n sv.stop()\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"yarntime/machine-learning","sub_path":"tensorflow/distributed_mnist/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":6769,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"20999909398","text":"import cv2, threading\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nimg = cv2.imread('cropped.jpg',0)\n\nclass Order:\n def __init__(self, points=None):\n self.selected = None\n \n fig = self.fig = plt.figure()\n ax = self.ax = fig.add_subplot(111)\n ax.imshow(img, cmap=\"gray\")\n plt.gca().invert_yaxis()\n xlim = self.xlim = ax.get_xlim()\n ylim = self.ylim = ax.get_ylim()\n\n if points != None:\n self.points = points\n else:\n samples = range(int(xlim[0]), int(xlim[1]), 5)\n self.points = [[x, y] for x, y in zip(samples, [int(ylim[1]/2) for i in samples])]\n self.xs = []\n self.ys = []\n for p in self.points:\n self.xs.append(p[0])\n self.ys.append(p[1])\n\n cid1 = fig.canvas.mpl_connect('button_press_event', self.onclick)\n cid2 = fig.canvas.mpl_connect('button_release_event', self.onrelease)\n cid3 = fig.canvas.mpl_connect('motion_notify_event', self.onmove)\n\n self.ani = animation.FuncAnimation(fig, self.animate, interval=50)\n plt.show()\n \n def onclick(self, event):\n x = event.xdata\n y = event.ydata\n\n if x != None and y != None:\n for i, p in enumerate(self.points):\n if (x-p[0])**2 + (y-p[1])**2 < 25:\n self.selected = i\n return\n\n def onmove(self, event):\n y = event.ydata\n if y != None and self.selected != None:\n self.points[self.selected][1] = int(y)\n self.ys[self.selected] = int(y)\n\n def onrelease(self, event):\n y = event.ydata\n if y != None and self.selected != None:\n if event.button == 3:\n del self.points[self.selected]\n del self.xs[self.selected]\n del self.ys[self.selected]\n else:\n self.points[self.selected][1] = int(y)\n self.ys[self.selected] = int(y)\n\n self.selected = None\n\n def animate(self, i):\n self.ax.clear()\n self.ax.imshow(img, cmap=\"gray\")\n self.ax.scatter(self.xs, self.ys, s=100)\n self.ax.set_xlim(self.xlim)\n self.ax.set_ylim(self.ylim)\n\nfilename = raw_input(\"Filename to load(empty for new file): \")\npoints = None\nif len(filename) > 0:\n points = np.load(filename)\n\nm = Order(points)\n\nfilename = raw_input(\"Filename to save(without extension): \")\nif len(filename) > 0:\n np.save(filename, m.points)\n\n","repo_name":"smithy545/tattoo-transform","sub_path":"order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"39505124339","text":"import random\nfrom collections import defaultdict\n\nimport numpy as np\n\nfrom amplification.tasks.core import idk, uniform, Task, sequences\n\ndef matches(patterns, xs):\n return np.all((patterns[:,np.newaxis,:] == SumTask.wild) |\n (patterns[:,np.newaxis,:] == xs[np.newaxis, :, :]), axis=2)\n\nclass SumTask(Task):\n wild = 1\n answer_length = 1\n fixed_vocab = 2\n\n def repr_symbol(self, x):\n if x == self.wild: return '*'\n if x in self.differences:\n return str(x - self.zero)\n if x in self.alphabet:\n return 'abcdef'[x - self.alphabet[0]]\n if x == idk: return '?'\n raise ValueError(x)\n\n def __init__(self, length=6, size=float('inf'), nchars=2, modulus=None):\n self.nvocab = self.fixed_vocab\n self.size = min(size, nchars**length)\n self.alphabet = self.allocate(nchars)\n self.interaction_length = nchars\n self.alphabet_plus = np.concatenate([[self.wild], self.alphabet])\n self.modulus = modulus\n if modulus is None:\n self.max_d = (self.size + nchars - 1) // nchars\n self.differences = self.allocate(2 * self.max_d + 1)\n self.zero = self.differences[self.max_d]\n else:\n self.differences = self.allocate(self.modulus)\n self.zero = self.differences[0]\n self.all_strings = [np.array(x) for x in sequences(self.alphabet, length)]\n self.length = length\n self.question_length = length\n self.fact_length = length + 1\n\n def make_dbs(self, difficulty=float('inf')):\n used_strings = min(self.size, difficulty+8)\n strings = np.stack(random.sample(self.all_strings, used_strings))\n values = np.random.choice([-1, 1], used_strings)\n fast_db = {\"strings\": strings, \"values\": values}\n facts = np.concatenate([strings, self.encode_n(values[:,np.newaxis])], axis=1)\n return facts, fast_db\n\n def answers(self, Qs, fast_db):\n all_matches = matches(Qs, fast_db[\"strings\"])\n raw_As = np.dot(all_matches, fast_db[\"values\"])\n As = self.encode_n(raw_As)\n return As[:, np.newaxis]\n\n def make_q(self, fast_db):\n Q = np.random.choice(self.alphabet, self.length, replace=True)\n num_wilds = np.random.randint(1, self.length + 1)\n indices = np.random.choice(self.length, num_wilds, replace=False)\n Q[indices] = self.wild\n return Q\n\n def encode_n(self, x):\n if self.modulus is None:\n return self.zero + np.maximum(-self.max_d, np.minimum(self.max_d, x))\n else:\n return self.zero + np.mod(x, self.modulus)\n\n def are_simple(self, Qs):\n return np.all(Qs != self.wild, axis=-1)\n\n def recursive_answer(self, Q):\n Q = np.asarray(Q)\n if not np.all(np.isin(Q, self.alphabet_plus)):\n yield self.pad(self.zero), None\n return\n if not np.any(Q == self.wild):\n yield (yield None, Q), None\n return\n wild_index = np.argmax(Q == self.wild)\n result = 0\n for c in self.alphabet:\n new_Q = np.copy(Q)\n new_Q[wild_index] = c\n d = (yield None, new_Q)\n if d not in self.differences:\n yield self.pad(idk), None\n return\n result += d - self.zero\n result = self.encode_n(result)\n yield self.pad(result), None\n\n def all_questions(self, fast_db):\n yield from sequences(self.alphabet_plus, self.length)\n\n def classify_question(self, Q, fast_db):\n n = len([x for x in Q if x == self.wild])\n return \"wilds{}\".format(n)\n","repo_name":"paulfchristiano/amplification","sub_path":"amplification/tasks/sum.py","file_name":"sum.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"79"} +{"seq_id":"39276826663","text":"###general binary search\n\ndef binary_search(lo,hi,condition):\n \n while lo <= hi:\n mid = (lo+hi)//2\n result = condition(mid)\n\n if result == 'found':\n return mid\n \n elif result == 'left':\n hi = mid-1\n \n elif result == 'right':\n lo = mid+1\n \n return -1\n\n\n## calculating starting position of the given number using general binary search \n\ndef start_position(nums,target):\n \n def condition(mid):\n mid_num = nums[mid]\n \n if mid_num == target:\n if mid > 0 and nums[mid-1] == target:\n return 'left'\n else:\n return 'found'\n \n elif mid_num > target:\n return 'left'\n \n elif mid_num < target:\n return 'right' \n \n return binary_search(0,len(nums)-1,condition)\n\n\n## calculating ending position of the given number using general binary search \n\ndef end_position(nums,target):\n \n def condition(mid):\n mid_num = nums[mid]\n \n if mid_num == target:\n if mid < (len(nums)-1) and nums[mid+1] == target:\n return 'right'\n else:\n return 'found'\n \n elif mid_num > target:\n return 'left'\n \n elif mid_num < target:\n return 'right' \n \n return binary_search(0,len(nums)-1,condition)\n\n\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n return (start_position(nums,target),end_position(nums,target))\n \n","repo_name":"Gomathi-Murugesan/code-challenges","sub_path":"Leetcode-Python/first and last position of a number.py","file_name":"first and last position of a number.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"3653194227","text":"from rest_framework import serializers\nfrom rest_framework.relations import SlugRelatedField\n\nfrom products.models import (Articles, Category, Favorite, ProductReview,\n Products)\n\n\nclass CategoriesSerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('title', )\n\n\nclass CategoryDetailSerializer(serializers.ModelSerializer):\n sub_categories = CategoriesSerializer(read_only=True, many=True)\n\n class Meta:\n model = Category\n fields = ('sub_categories', )\n\n\nclass ProductSerializer(serializers.ModelSerializer):\n class Meta:\n model = Products\n fields = (\n 'name',\n 'price',\n 'description',\n 'quantity',\n )\n\n \nclass ProductReviewSerializer(serializers.ModelSerializer):\n product = serializers.SlugRelatedField(\n slug_field='name',\n queryset=Products.objects.all(),\n required=False\n )\n author = SlugRelatedField(\n default=serializers.CurrentUserDefault(),\n read_only=True,\n slug_field='username'\n )\n\n class Meta:\n fields = ('id', 'product', 'text', 'author', 'score', 'created')\n model = ProductReview\n def validate_score(self, value):\n if 0 > value > 5:\n raise serializers.ValidationError('Выберите оценку от 1 до 5')\n return value\n\n\nclass ArticlesSerializer(serializers.ModelSerializer):\n class Meta:\n model = Articles\n fields = (\n 'title',\n 'text',\n 'created_at',\n )\n\n\nclass FavoriteInfoSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Products\n fields = (\n 'name',\n 'price',\n 'size',\n 'picture',\n 'description',\n )\n\n\nclass FavoriteSerializer(serializers.ModelSerializer):\n is_favorited = serializers.BooleanField(read_only=True)\n\n class Meta:\n model = Favorite\n fields = (\n 'user',\n 'products',\n 'is_favorited',\n )\n\n def to_representation(self, instance):\n context = {'request': self.context.get('request')}\n return FavoriteInfoSerializer(instance.products, context=context).data\n","repo_name":"Alfrederick888/project_x","sub_path":"silver_unicorn/backend/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"4282398844","text":"from ClaseViajeroFrecuente import ViajeroFrecuente\r\nimport csv\r\nfrom ManejadorViajero import Manejador\r\n\r\nif __name__==\"__main__\":\r\n\r\n objeto=Manejador()\r\n objeto.TestLista()\r\n print(\"COMPARAR LA CANTIDAD DE MILLAS ACUMULADAS\")\r\n objeto.mayor()\r\n\r\n print(\"________________________________________________________\")\r\n\r\n print(\"ACUMULAR MILLAS\")\r\n print (\"Ingrese numero de viajero que desee acumular millas\")\r\n numero=int (input())\r\n indice = objeto.buscar(numero)\r\n objeto.acumular(indice)\r\n\r\n print(\"________________________________________________________\")\r\n\r\n print(\"CANJEAR MILLAS\")\r\n print (\"Ingrese numero de viajero que desee canjear millas\")\r\n num=int (input())\r\n indice= objeto.buscar(num)\r\n objeto.canjear(indice)\r\n","repo_name":"SosaCristina/Ejercicio-7-Unidad2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"43103897802","text":"from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\n\nfrom flask import Flask, render_template, request\nimport pandas as pd\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"

Hello, World!

\"\n\n@app.route(\"/search\", methods=['post','get'])\ndef search():\n return render_template('search_form.html')\n\n@app.route(\"/search/api\")\ndef search_api():\n loc = request.args['fname']\n # print(loc)\n url = \"https://www.openrice.com/zh/hongkong\"\n options = Options()\n options.add_argument('--headless')\n options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36')\n driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)\n driver.get(url)\n\n elem = driver.find_elements(By.CLASS_NAME, \"quick-search-input-field\")\n elem[1].send_keys(loc)\n driver.find_element(By.CSS_SELECTOR, \".quick-search-button\").click()\n\n lis = driver.find_elements(By.CSS_SELECTOR, \".sr1-listing-content-cell.pois-restaurant-list-cell\")\n\n temp = []\n for li in lis:\n id = li.find_element(By.CSS_SELECTOR, 'section.js-openrice-bookmark.openrice-bookmark').get_attribute('data-poi-id')\n name = li.find_element(By.CLASS_NAME, \"title-name\").text\n address = li.find_element(By.CLASS_NAME, \"address\").text\n temp.append([id, name, address])\n\n op_df = pd.DataFrame(temp, columns=['ID', 'Name','Address'])\n\n driver.quit()\n\n if temp == []:\n return 'No result. Please search again.'\n else:\n return render_template('result.html', column_names=op_df.columns.values, row_data=list(op_df.values.tolist()), zip=zip)\n\n\n\n # print(list(op_df.values.tolist()))\n # print(op_df.columns.values)\n\n # df = pd.DataFrame({'Patient Name': [\"Some name\", \"Another name\"],\n # \"Patient ID\": [123, 456],\n # \"Misc Data Point\": [8, 53]})","repo_name":"Mikafar/web_scraping-openrice-","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"28704177092","text":"import asyncio\n\nfrom ...config import DREAMS_CHANNEL_ID\nfrom aiogram.types import Message\nfrom ..core import Command\n\n\nclass PostDream(Command):\n \"\"\"\n get help\n if using with args, it searches for help for a specific command\n\n Important: not main commands as, for example, /stop which is needed for /fwd_to_text, won't appear here, in similar cases you'll need to check help for the main command, for example: /help fwd_to_text\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n @classmethod\n async def execute(cls, m: Message):\n member = await m.bot.get_chat_member(m.chat.id, m.from_user.id)\n if member.status not in ['administrator', 'creator']:\n msg = await m.answer(\"Эта команда только для админов :p\")\n await asyncio.sleep(15)\n await m.delete()\n await msg.delete()\n return\n args = m.get_args()\n msg = m.reply_to_message\n if not msg:\n msg = await m.answer(\"Отправьте команду реплаем на сообщение со сном\")\n await asyncio.sleep(15)\n await m.delete()\n await msg.delete()\n return\n if not msg.text:\n msg = await m.answer(\"Сообщение со сном должно быть текстовым\")\n await asyncio.sleep(15)\n await m.delete()\n await msg.delete()\n return\n if args:\n dream_sender = args\n elif msg.forward_from:\n dream_sender = msg.forward_from.full_name\n elif msg.forward_sender_name:\n dream_sender = msg.forward_sender_name\n elif msg.from_user:\n dream_sender = msg.from_user.full_name\n else:\n msg = await m.answer(\"Отправитель сна не определен, напишите его имя в аргументах, пожалуйста (/post_dream Имя)\")\n await asyncio.sleep(15)\n await m.delete()\n await msg.delete()\n return\n try:\n await m.bot.send_message(\n DREAMS_CHANNEL_ID, f\"От {dream_sender}\\n\\n{msg.html_text}\", parse_mode=\"html\")\n msg = await m.reply(\"Готово\")\n except Exception as e:\n await m.answer(f\"@dr_fxrse че за дела бля\\n{e}\")\n await asyncio.sleep(15)\n await m.delete()\n await msg.delete()\n","repo_name":"drforse/BotDaddy","sub_path":"bot_daddy_bot/bot/user_commands/post_dream.py","file_name":"post_dream.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"6487402442","text":"# Teste1 - Versao que vai ser usada no final, Hough transform\n\n\nimport cv2\nimport numpy as np\nimport time\n\ndef no():\n pass\n\ncam = cv2.VideoCapture()\ncam.open(0)\ncam.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)\ncam.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)\n# cam.set(cv2.CAP_PROP_FRAME_COUNT, 1)\n\ncv2.namedWindow('sliders')\ncv2.createTrackbar('param1','sliders',50,100,no)\ncv2.createTrackbar('param2','sliders',50,100,no)\ncv2.createTrackbar('blur window','sliders',5,10,no)\ncv2.createTrackbar('blur p1','sliders',100,200,no)\ncv2.createTrackbar('blur p2','sliders',100,200,no)\n\n\nwhile 1:\n ret, img = cam.read()\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = cv2.medianBlur(img, (2*cv2.getTrackbarPos('blur window','sliders')+1))\n circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 90,\n param1=cv2.getTrackbarPos('param1','sliders'),\n param2=cv2.getTrackbarPos('param2','sliders'),\n minRadius=2,\n maxRadius=150)\n print(circles)\n if not (circles is None):\n circles = np.uint16(np.around(circles))\n for i in circles[0,:]:\n cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)\n cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)\n cv2.imshow('circles', img)\n # time.sleep(.1)\n if cv2.waitKey(1) == 27:\n break\ncv2.destroyAllWindows()\n","repo_name":"developedby/Robo-Sugador","sub_path":"codigo/testes/teste_imagem5.py","file_name":"teste_imagem5.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"73108710656","text":"import json\nimport logging\nimport time\nimport traceback\nimport zlib\n\nimport msgpack\nfrom retrying import retry\n\nfrom .exceptions import TestException\n\nlog = logging.getLogger(__name__)\n\n\ndef retry_on_exception(exception):\n log.error(traceback.format_exc())\n for etype in (KeyboardInterrupt, TestException):\n if isinstance(exception, etype):\n return False\n return True\n\n\nclass MsgProcessorHandlers(object):\n def __init__(self, encoding=None, decompress=None, msgformat=None):\n if decompress:\n self.decompress_fun = zlib.decompress\n else:\n self.decompress_fun = self.dummy_decompress\n self.consumer = None\n self.__next_messages = 0\n self.__encoding = encoding\n self.deserialize_fun = self.get_deserializer(msgformat)\n\n def get_deserializer(self, msg_format):\n msg_deserializers = {\n 'msgpack': self.deserialize_msgpack,\n 'json': self.deserialize_json\n }\n return msg_deserializers[msg_format]\n\n def set_consumer(self, consumer):\n self.consumer = consumer\n\n def set_next_messages(self, next_messages):\n if next_messages != self.__next_messages:\n self.__next_messages = next_messages\n log.info('Next messages count adjusted to {}'.format(next_messages))\n\n @property\n def next_messages(self):\n return self.__next_messages\n\n @retry(wait_fixed=60000, retry_on_exception=retry_on_exception)\n def _get_message_from_consumer(self):\n for m in self.consumer:\n return m\n\n def _get_messages_from_consumer(self):\n count = 0\n while True:\n m = self._get_message_from_consumer()\n if m:\n yield m\n count += 1\n if count == self.__next_messages:\n break\n else:\n break\n\n def consume_messages(self, max_next_messages):\n \"\"\" Get messages batch from Kafka (list at output) \"\"\"\n # get messages list from kafka\n if self.__next_messages == 0:\n self.set_next_messages(min(1000, max_next_messages))\n self.set_next_messages(min(self.__next_messages, max_next_messages))\n mark = time.time()\n for record in self._get_messages_from_consumer():\n yield record.partition, record.offset, record.key, record.value\n newmark = time.time()\n if newmark - mark > 30:\n self.set_next_messages(self.__next_messages / 2 or 1)\n elif newmark - mark < 5:\n self.set_next_messages(min(self.__next_messages + 100, max_next_messages))\n\n def decompress_messages(self, partitions_offmsgs):\n \"\"\" Decompress pre-defined compressed fields for each message. \"\"\"\n\n for pomsg in partitions_offmsgs:\n if pomsg['message']:\n pomsg['message'] = self.decompress_fun(pomsg['message'])\n yield pomsg\n\n def unpack_messages(self, partitions_msgs):\n \"\"\" Deserialize a message to python structures \"\"\"\n\n for pmsg in partitions_msgs:\n key = pmsg['_key']\n partition = pmsg['partition']\n offset = pmsg['offset']\n msg = pmsg.pop('message')\n if msg:\n try:\n record = self.deserialize_fun(msg)\n except Exception as e:\n log.error('Error unpacking record at partition:offset {}:{} (key: {} : {})'.format(partition, offset, key, repr(e)))\n continue\n else:\n if isinstance(record, dict):\n pmsg['record'] = record\n yield pmsg\n else:\n log.info('Record {} has wrong type'.format(key))\n else:\n yield pmsg\n\n def deserialize_msgpack(self, msg):\n return msgpack.unpackb(msg, encoding=self.__encoding)\n\n def deserialize_json(self, msg):\n return json.loads(msg.decode(encoding=self.__encoding))\n\n def dummy_decompress(self, data):\n return data\n","repo_name":"scrapinghub/kafka-scanner","sub_path":"kafka_scanner/msg_processor_handlers.py","file_name":"msg_processor_handlers.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"79"} +{"seq_id":"74593917695","text":"import numpy as np\n\nfrom activations import Sigmoid, Softmax\nfrom dense import Dense\n\n\nclass NeuralNetwork:\n\n def __init__(self):\n self.network = [\n Dense(28 * 28, 50),\n Sigmoid(),\n Dense(50, 10),\n Sigmoid()\n ]\n self.epochs = 1000\n self.learning_rate = 0.12\n self.verbose = True\n self.loss = mse\n self.loss_prime = mse_prime\n self.train_loss = []\n self.test_score = 0\n\n def fit(self, X, Y):\n for e in range(self.epochs):\n error = 0\n for x, y in zip(X, Y):\n #forward\n output = self.predict(x)\n\n #error\n error += self.loss(y, output)\n\n #backward\n grad = self.loss_prime(y, output)\n for layer in reversed(self.network):\n grad = layer.backward(grad, self.learning_rate)\n\n error /= len(X)\n self.train_loss.append(error)\n if e % 100 == 0:\n if self.verbose:\n print(f\"{e + 1}/{self.epochs}, error={error}\")\n\n def predict(self, X):\n output = X\n for layer in self.network:\n output = layer.forward(output)\n return output\n\n def score(self, X, Y):\n matches = 0\n for x, y in zip(X, Y):\n output = self.predict(x)\n if np.argmax(output) == np.argmax(y):\n matches += 1\n\n self.test_score = (matches / X.shape[0] * 100)\n print((matches / X.shape[0] * 100))\n\n\ndef mse(y_true, y_pred):\n return np.mean(np.power(y_true - y_pred, 2))\n\n\ndef mse_prime(y_true, y_pred):\n return 2 * (y_pred - y_true) / np.size(y_true)\n","repo_name":"idanmorem/MNIST-digit-recognition","sub_path":"neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"18244668994","text":"__all__ = ['replace']\n\n\ndef replace(source, replacement):\n \"\"\"replace multiple elements/substrings and return result\"\"\"\n if isinstance(source, (list, set, tuple)):\n for old, new in replacement.items():\n if old in source:\n source = [new if el == old else el for el in source]\n if isinstance(source, str):\n for old, new in replacement.items():\n source = source.replace(old, new)\n return source\n","repo_name":"andrewp-as-is/replace.py","sub_path":"replace/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"79"} +{"seq_id":"72426068414","text":"import os.path\n\nfrom .main import calculate_move_from_outcome, calculate_score, part_1, part_2\n\n\ndef test_part_1():\n with open(f\"../../common/{os.path.split(os.path.split(__file__)[0])[-1]}/sample_input.txt\", \"r\") as fp:\n sample_input = fp.read()\n\n with open(f\"../../common/{os.path.split(os.path.split(__file__)[0])[-1]}/sample_output_1.txt\", \"r\") as fp:\n expected_output = fp.read()\n\n returned_output = part_1(sample_input)\n assert returned_output == int(expected_output)\n\n\ndef test_part_2():\n with open(f\"../../common/{os.path.split(os.path.split(__file__)[0])[-1]}/sample_input.txt\", \"r\") as fp:\n sample_input = fp.read()\n\n with open(f\"../../common/{os.path.split(os.path.split(__file__)[0])[-1]}/sample_output_2.txt\", \"r\") as fp:\n expected_output = fp.read()\n\n returned_output = part_2(sample_input)\n assert returned_output == int(expected_output)\n\n\ndef test_outcome_predictor():\n outcomes = [[0, 0, 2], [0, 1, 0], [0, 2, 1], [1, 0, 0], [1, 1, 1], [1, 2, 2], [2, 0, 1], [2, 1, 2], [2, 2, 0]]\n for enemy_move, desired_outcome, expected_outcome in outcomes:\n assert calculate_move_from_outcome(enemy_move, desired_outcome) == expected_outcome\n\n\ndef test_score_calculator():\n scores = [ # opponent move, my move, my score\n [1, 0, 1],\n [2, 1, 2],\n [0, 2, 3],\n [0, 0, 4],\n [1, 1, 5],\n [2, 2, 6],\n [2, 0, 7],\n [0, 1, 8],\n [1, 2, 9],\n ]\n for enemy_move, my_move, expected_score in scores:\n assert calculate_score(enemy_move, my_move) == expected_score\n","repo_name":"issy/Advent-Of-Code-2022","sub_path":"src/python/day_2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"6482471832","text":"def checkString(st):\n stack = []\n for l in st:\n if l in ['(', '[', '{']:\n stack.append(l)\n else:\n if stack:\n if l == ')' and stack[-1] == '(':\n stack.pop()\n elif l == ']' and stack[-1] == '[':\n stack.pop()\n elif l == '}' and stack[-1] == '{':\n stack.pop()\n else:\n return False\n if stack:\n return False\n else:\n return True\n\ndef solution(s):\n answer = 0\n \n for i in range(len(s)):\n ss = s[i:]+s[:i]\n if checkString(ss):\n answer += 1\n return answer","repo_name":"maltepoo/algorithm","sub_path":"프로그래머스/lv2/76502. 괄호 회전하기/괄호 회전하기.py","file_name":"괄호 회전하기.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"10461901648","text":"'''''\nresearch tests.\n'''''\n\nimport unittest\nimport aguaclara.research.environmental_processes_analysis as epa\nfrom aguaclara.core.units import u\nimport numpy as np\n\n\nclass TestEPA(unittest.TestCase):\n '''''\n Test research's Environmental_Processes_Analysis\n '''''\n def assertAlmostEqualSequence(self, a, b, places=7):\n for elt_a, elt_b in zip(a, b):\n self.assertAlmostEqual(elt_a, elt_b, places)\n\n def test_Hplus_concentration_from_pH(self):\n '''''\n Test function that converts pH to molarity of H+\n '''''\n output = epa.invpH(8.25)\n self.assertEqual(output, 5.623413251903491e-09*u.mol/u.L)\n\n output = epa.invpH(10)\n self.assertEqual(output, 1e-10*u.mol/u.L)\n\n def test_E_Advective_Dispersion(self):\n output = epa.E_Advective_Dispersion(0.5, 5)\n self.assertAlmostEqual(output, 0.4774864115)\n\n output = epa.E_Advective_Dispersion(0, 5)\n self.assertAlmostEqual(output, 0)\n\n output = epa.E_Advective_Dispersion(np.array([0, 0.5, 1, 1.5, 2]), 5)\n answer = np.array([0, 0.477486411, 0.630783130, 0.418173418, 0.238743205])\n self.assertAlmostEqualSequence(output, answer)\n","repo_name":"AguaClara/aguaclara","sub_path":"tests/research/test_EPA.py","file_name":"test_EPA.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"79"} +{"seq_id":"5977978474","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom datetime import datetime, timedelta\nimport json\nimport time\nimport logging\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import View\nfrom cerf.models import Interview\n\n__author__ = 'tchen'\nlogger = logging.getLogger(__name__)\n\n'''\n{\n \"success\": 1,\n \"result\": [\n {\n \"id: 293,\n \"title\": \"Event 1\",\n \"url\": \"http://someurl.com\",\n \"class\": 'event-important',\n start: 12039485678,\n end: 1234576967\n },\n ...\n ]\n}\n'''\n\n\nclass EventListAPIView(View):\n model = Interview\n\n def get_queryset(self):\n\n today = datetime.today()\n weekstart = today - timedelta(today.weekday())\n #weekstart = datetime(today.year, today.month, today.day - today.weekday())\n return self.model.objects.filter(scheduled__gte=weekstart)\n\n def get(self, request, *args, **kwargs):\n results = self.get_queryset()\n\n count = len(results)\n data = {}\n if count > 0:\n data['success'] = 1\n data['result'] = [{'id': i.id,\n 'title': i.get_reserve_info(),\n 'url': i.get_absolute_url(),\n 'class': 'event-info',\n 'start': int(time.mktime(i.scheduled.timetuple())) * 1000,\n 'end': int(time.mktime((i.scheduled + timedelta(hours=1)).timetuple())) * 1000\n } for i in results]\n else:\n data['success'] = 1\n data['result'] = []\n\n return HttpResponse(json.dumps(data))\n\n def post(self, request, *args, **kwargs):\n return self.get(request, *args, **kwargs)\n\n @csrf_exempt\n def dispatch(self, request, *args, **kwargs):\n return super(EventListAPIView, self).dispatch(request, *args, **kwargs)\n","repo_name":"tyrchen/cerf","sub_path":"cerf/views/api/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"26058040228","text":"# **************BLACKJACK**************\n# To play a hand of Blackjack the following steps must be followed:\n# 1) Create a deck of 52 cards\n# 2) Shuffle the deck\n# 3) Ask the Player for their bet/define their chips\n# 4) Make sure that the Player's bet does not exceed their available chips\n# 5) Deal two cards to the Dealer and two cards to the Player\n# 6) Show only one of the Dealer's cards, the other remains hidden\n# 7) Show both of the Player's cards\n# 8) Ask the Player if they wish to Hit, and take another card\n# 9) If the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again.\n# 10) If a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17\n# 11) Determine the winner and adjust the Player's chips accordingly\n# 12) Ask the Player if they'd like to play again\n\nfrom locale import delocalize\nimport random\n\nsuits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\nranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\nvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,\n 'Queen':10, 'King':10, 'Ace':11}\n\nplaying = True\n\nclass Card():\n\n def __init__(self,suit,rank):\n self.suit=suit\n self.rank=rank\n\n def __str__(self):\n return self.rank + \" of \" + self.suit\n\nclass Deck():\n\n def __init__(self):\n self.deck = [] #Start with an empty list\n for suit in suits:\n for rank in ranks:\n self.deck.append(Card(suit,rank))\n \n def __str__(self):\n deck_comp = \"\"\n for card in self.deck:\n deck_comp += \"\\n\" + card.__str__()\n return \"The deck has: \" + deck_comp\n \n def shuffle(self):\n random.shuffle(self.deck)\n\n def deal(self):\n single_card = self.deck.pop()\n return single_card\n\nclass Hand():\n def __init__(self):\n self.cards = [] # start with an empty list as we did in the Deck class\n self.value = 0 # start with zero value\n self.aces = 0 # add an attribute to keep track of aces\n\n def add_card(self,card):\n # The card object that is passed in, is from the Deck class and specifically \n # from Deck.deal() -> which yields a single Card(suit,rank) object\n self.cards.append(card) # We're then appending the card object in the self.cards empty list\n self.value += values[card.rank] # Then we're adjusting the total value of the hand (self.value)\n # with the value of the card that was added to the list - and \n # we know that if self.value>21 -> lose\n # track aces\n if card.rank == \"Ace\":\n self.aces += 1\n \n def adjust_for_ace(self):\n \n # First we check if self.value>21 check because we won't adjust an ace=1 if the self.value<21\n # (by default from the global dictionary, we consider an Ace of value = 11 )\n # Then, we also check if we *do* have an ace. If both checks are passed \n # then we subtract 10 (which) is the adjustment for the ace, \n # *AND* remove a count from self.aces (in order to break out of the while loop)\n while self.value > 21 and self.aces>0:\n self.value -= 10\n self.aces -= 1\n\nclass Chips():\n \n def __init__(self):\n self.total = 100 # Here this is a default value but we can opt in to have it passed\n self.bet = 0\n \n def win_bet(self):\n self.total += self.bet\n \n def lose_bet(self):\n self.total -= self.bet\n\n# Functions #\n\n# Function for taking bets:\ndef take_bet(chips:Chips): # We are taking some chips objects from the Chips class (that has a .total and .bet attribute)\n while True:\n try:\n chips.bet = int(input(\"How many chips do you want to bet? \")) # We set the bet to what the player wants\n except:\n print(\"Sorry, please provide an integer!\") # We check if the player is providing an integer\n else:\n if chips.bet > chips.total: # Even if they are providing an int, we check if they have enough chips\n print(\"Sorry, you don't have enough chips! You have: {} \".format(chips.total))\n else:\n break\n\n# Function for taking hits:\ndef hit(deck:Deck,hand:Hand): # Takes the deck instance of Deck (however many cards left in it) and someone's \n # instance of Hand,\n single_card = deck.deal() # grabs a single card from the deck instance,\n hand.add_card(single_card)# adds it to the hand instance,\n hand.adjust_for_ace() # and then checks for an ace adjustment\n\n# Function prompting the player to Hit or Stand:\ndef hit_or_stand(deck:Deck,hand:Hand):\n # Takes in the deck instance and hand instance as arguments and assigns playing as a GLOBAL variable;\n # if the player hits, then we employ the hit() function, if the player stands then we set\n # the global playing variable to False which will act as a flag.\n global playing # This is for controlling the while loop later on (not the one below)\n\n while True:\n x = input(\"Hit or Stand? Enter 'h' or 's': \")\n\n if x[0].lower() == 'h':\n hit(deck,hand)\n \n elif x[0].lower() == 's':\n print(\"Player stands! Dealer's turn\")\n playing = False\n\n else:\n print(\"Sorry, I didn't understand that. Please enter 'h' or 's' only\")\n continue\n break\n\n# Functions to display cards:\ndef show_some(player:Hand,dealer:Hand): \n # We want to show only ONE of the dealer's cards from their hand\n print(\"\\n Dealer's Hand: \")\n print(\"First card hidden!\")\n print(dealer.cards[1]) # Shows only the card at index 1, ommitting the card at index 0\n\n # We want to show ALL (2 cards at the start of the game) from the player's hand\n # so we will go with a for loop for the entirety of the list .cards for the player instance \n print(\"\\n Player's hand:\")\n for card in player.cards:\n print(card)\n\ndef show_all(player:Hand,dealer:Hand):\n # Show all the dealer's cards\n print(\"\\n Dealer's hand:\")\n for card in dealer.cards:\n print(card)\n #**ALTERNATIVE WAY: #print(\"\\n Dealer's hand: \",*dealer.cards,sep='\\n') --- avoids the for loop\n # Calculate and display the dealer's cards' value (since it happens at the end)\n print(f\"Value of Dealer's hand is: {dealer.value}\")\n\n # Show all the player's cards\n print(\"\\n Player's hand:\")\n for card in player.cards:\n print(card)\n # Calculate and display the player's cards' value\n print(f\"Value of Player's hand is: {player.value}\")\n\n# Write functions to handle end of game scenarios:\ndef player_busts(player:Hand,dealer:Hand,chips:Chips):\n print(\"BUST PLAYER!\")\n chips.lose_bet()\n\ndef player_wins(player:Hand,dealer:Hand,chips:Chips):\n print(\"PLAYER WINS!\")\n chips.win_bet()\n\ndef dealer_busts(player:Hand,dealer:Hand,chips:Chips):\n print(\"BUST DEALER! PLAYER WINS!\")\n chips.win_bet() # Note that when dealer busts player wins, so the player wins chips!\n\ndef dealer_wins(player:Hand,dealer:Hand,chips:Chips):\n print(\"DEALER WINS! PLAYER LOSES!\")\n chips.lose_bet()# Note that when dealer wins player loses, so the player loses chips!\n\ndef push(player:Hand,dealer:Hand): # When both player and dealer get 21\n print(\"Dealer and player tie! PUSH!\")\n\n# ----------------- GAME LOGIC ----------------- #\n\nwhile True:\n # Print an opening statement\n print('Welcome to BlackJack! Get as close to 21 as you can without going over!\\n\\\n Dealer hits until she reaches 17. Aces count as 1 or 11.')\n \n # Create & shuffle the deck, deal two cards to each player\n deck = Deck()\n deck.shuffle()\n \n player_hand = Hand()\n player_hand.add_card(deck.deal())\n player_hand.add_card(deck.deal())\n \n dealer_hand = Hand()\n dealer_hand.add_card(deck.deal())\n dealer_hand.add_card(deck.deal())\n \n # Set up the Player's chips\n player_chips = Chips() # remember the default value is 100 \n \n # Prompt the Player for their bet\n take_bet(player_chips)\n \n # Show cards (but keep one dealer card hidden)\n show_some(player_hand,dealer_hand)\n \n while playing: # recall this variable from our hit_or_stand function\n \n # Prompt for Player to Hit or Stand\n hit_or_stand(deck,player_hand) \n \n # Show cards (but keep one dealer card hidden)\n show_some(player_hand,dealer_hand) \n \n # If player's hand exceeds 21, run player_busts() and break out of loop\n if player_hand.value > 21:\n player_busts(player_hand,dealer_hand,player_chips)\n break \n\n\n # If Player hasn't busted, play Dealer's hand until Dealer reaches 17 \n if player_hand.value <= 21:\n \n while dealer_hand.value < 17:\n hit(deck,dealer_hand) \n \n # Show all cards\n show_all(player_hand,dealer_hand)\n \n # Run different winning scenarios\n if dealer_hand.value > 21:\n dealer_busts(player_hand,dealer_hand,player_chips)\n\n elif dealer_hand.value > player_hand.value:\n dealer_wins(player_hand,dealer_hand,player_chips)\n\n elif dealer_hand.value < player_hand.value:\n player_wins(player_hand,dealer_hand,player_chips)\n\n else:\n push(player_hand,dealer_hand) \n \n # Inform Player of their chips total \n print(\"\\nPlayer's winnings stand at\",player_chips.total)\n \n # Ask to play again\n new_game = input(\"Would you like to play another hand? Enter 'y' or 'n' \")\n \n if new_game[0].lower()=='y':\n playing=True\n continue\n else:\n print(\"Thanks for playing!\")\n break\n","repo_name":"DimitriosChiras/python_milestone_project_2","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":9884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"2215117704","text":"import math\nimport numpy as np\nimport scipy as sp\n\nalpha = 45.\naxvec = np.asarray([1,0,0],float)\nvertvec = np.asarray([0,1.8,0],float)\n\nclass tdvector(np.matrix):\n\n def __new__(cls, input_array):\n obj = np.asarray(input_array, float).view(cls)\n return obj.T\n\n\nclass rotate_matrix(np.matrix):\n\n def __new__(cls, alpha_angle, axis_vector, vertex_vector):\n obj = np.matrix(np.zeros((3,3), float)).view(cls)\n obj.alpha_angle = alpha_angle\n obj.axis_vector = axis_vector\n obj.vertex_vector = vertex_vector\n return obj\n\n def __array_finalize__(self, obj):\n if obj is None: return\n self.alpha_angle = getattr(obj, 'alpha_angle', None)\n self.axis_vector = getattr(obj, 'axis_vector', None)\n self.vertex_vector = getattr(obj, 'vertex_vector', None)\n\n def matrix_rotate(self):\n c = math.cos(math.pi/180*self.alpha_angle)\n s = math.sin(math.pi/180*self.alpha_angle)\n\n ax = self.axis_vector[0]\n ay = self.axis_vector[1]\n az = self.axis_vector[2]\n\n self[0,0] = c+(1-c)*(ax)**2\n self[0,1] = (1-c)*ax*ay-s*az\n self[0,2] = (1-c)*ax*az+s*ay\n\n self[1,0] = (1-c)*ax*ay+s*az\n self[1,1] = c+(1-c)*ay**2\n self[1,2] = (1-c)*ay*az-s*ax\n\n self[2,0] = (1-c)*ax*az-s*ay\n self[2,1] = (1-c)*ay*az+s*ax\n self[2,2] = c+(1-c)*az**2\n\n return self\n \n\n def translate_rotate(self):\n uni_matrix = self.matrix_rotate()\n\n return uni_matrix.dot(self.vertex_vector)\n\n\n","repo_name":"JoergReinhardt/python_kinematic","sub_path":"robot.0.6.py","file_name":"robot.0.6.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"23367862689","text":"def get(inp):\n cur, ma = 0, -10 ** 10\n l, r, prev = 0, 0, 0\n for i in range(len(inp)):\n if inp[i] == 0:\n cur += 1\n else:\n cur -= 1\n if cur > ma:\n l = prev\n ma = cur\n r = i\n if cur < 0:\n cur = 0\n prev = i + 1\n return l, r, ma\n\n\nif __name__ == '__main__':\n n = int(input().strip())\n cur, ma = 0, 0\n st, en = 0, 0\n arr = [int(__) for __ in input().strip().split()]\n l, r, maa = get(arr)\n ans = arr.count(1)\n for i in range(l, r + 1):\n if arr[i] == 1:\n ans -= 1\n else:\n ans += 1\n print(ans)\n","repo_name":"bvsbrk/Algos","sub_path":"src/Codeforces/adhoc_300/flipping_game.py","file_name":"flipping_game.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"10523938594","text":"# series 8\nimport cv2 as cv\nimport numpy as np\n\n# read the image\nimg = cv.imread('photos/img_2.jpg')\n\n# display the image\ncv.imshow('assassins creed', img)\n\n# split the channels\nb, g, r = cv.split(img)\ncv.imshow('blue', b)\ncv.imshow('green', g)\ncv.imshow('red', r)\n\n# 3 channels\nprint(img.shape)\n\n# 1 channel of images\nprint(r.shape)\nprint(g.shape)\nprint(b.shape)\n\n# get back the image\nmerged = cv.merge([b,g,r])\ncv.imshow('merged', merged)\n\n# colourful versions of each channel\nblank = np.zeros(img.shape[:2], dtype='uint8')\nblue = cv.merge([b, blank, blank])\ngreen = cv.merge([blank, g, blank])\nred = cv.merge([blank, blank, r])\ncv.imshow('blueee', blue)\ncv.imshow('greeen', green)\ncv.imshow('reeeed', red)\n\n# wait infinitely\ncv.waitKey(0)","repo_name":"OnurcanKoken/Image_Processing_OpenCV","sub_path":"Color_Channels.py","file_name":"Color_Channels.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"43534192816","text":"class Book:\r\n def __init__(self,name,id ,price,language,species):\r\n self.name=name\r\n self.id=id\r\n self.price=price\r\n self.language=language\r\n self.species=species\r\n\r\ndef showinfo(x):\r\n print(x.name,\"\\t\",x.id,\"\\t\",x.price,\"\\t\",x.language,\"\\t\",x.species)\r\n\r\nx1=Book(\"美食通\",\"102959269\",\"180\",\"中文\",\"工具類\")\r\nx2=Book(\"冒險王\",\"165115168\",\"500\",\"中文\",\"科幻類\")\r\nx3=Book(\"One Night\",\"19491649\",\"760\",\"英文\",\"浪漫類\")\r\n\r\nprint(showinfo(x1))\r\nprint(showinfo(x2))\r\nprint(showinfo(x3))\r\n","repo_name":"kentsai0606/109021038-20210305","sub_path":"3月12作業2.py","file_name":"3月12作業2.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"31903547417","text":"\"\"\"\nCLI\n\"\"\"\nimport sys\nimport warnings\n\nfrom geopy.geocoders import Nominatim\n\nfrom .core import LOC_DEFAULT\n\n\nif len(sys.argv) > 1:\n LOC_ARG = sys.argv[1]\n OUTPUT = sys.argv[2]\nelse:\n LOC_ARG = \"Rio de Janeiro Brazil\"\n OUTPUT = 0\n\ngeolocator = Nominatim()\ntry:\n loc = geolocator.geocode(LOC_ARG)\nexcept: # no internet connection or server request failed\n loc = LOC_DEFAULT\n warnings.warn(f\"Geolocation failed. Using {loc.address} instead.\")\n\n","repo_name":"milankl/prob_meteogram","sub_path":"prob_meteogram/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"79"} +{"seq_id":"24217894695","text":"def hex_to_int(hex_string, signed=True):\n \"\"\"Returns hex_string converted to int. Method can work with signed 2's complement any length.\n\n :param hex_string: hex string. Example 'DEADBEEF' or 'deadbeef'.\n :param signed: boolean. True or False, indicating if hex signed. Default True\n :return: int representation of hex_string\n \"\"\"\n if signed:\n # get total number of bits to be able to extract MSB. If MSB=1 number is signed\n bits = len(bytearray.fromhex(hex_string)) * 8\n val = int('0x' + hex_string, 16)\n # get MSB and if MSB = 1 (means number is signed) - take 2's compliment\n if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255\n val = val - (1 << bits) # compute negative value\n return val\n else:\n return int(hex_string, 16)\n\n\ndef digital_input_output_presence_illuminance(data):\n \"\"\"Digital Output/Input/Presence/Illuminance | Data Resolution per bit = 1, Unsigned\n All these values are the same in decoding.\n\n :param data: hex string of sensor value\n :return: int decoded value\n \"\"\"\n return hex_to_int(data, False)\n\n\ndef analog_input_output(data):\n \"\"\"Analog Input/Output | Data Resolution per bit = 0.01 Signed\n\n :param data: hex string of sensor value\n :return: int decoded value\n \"\"\"\n return hex_to_int(data) / 100.0\n\n\ndef temperature(data):\n \"\"\"Temperature | Data Resolution per bit = 0.1 degC Signed MSB\n\n :param data: hex string of sensor value\n :return: int decoded value\n \"\"\"\n return hex_to_int(data) / 10.0\n\n\ndef humidity(data):\n \"\"\"Humidity | Data Resolution per bit = 0.5 % Unsigned\n\n :param data: hex string of sensor value\n :return: int decoded value\n \"\"\"\n return hex_to_int(data, False) / 2.0\n\n\ndef accelerometer(data):\n \"\"\"Accelerometer | \tData Resolution per bit = 0.001 G Signed MSB per axis\n Data Size: 6 bytes. x axis value = 2 bytes, y axis value = 2 bytes, z axis value = 2 bytes.\n Example: 04 D2 FB 2E 00 00 --> 04D2 - x, FB2E - y, 0000 - z.\n\n :param data: hex string of sensor value\n :return: dictionary of x,y,z axis as keys and their values\n \"\"\"\n return {'x': hex_to_int(data[:4]) / 1000.0, 'y': hex_to_int(data[4:8]) / 1000.0, 'z': hex_to_int(data[8:]) / 1000.0}\n\n\ndef barometer(data):\n \"\"\"Barometer | Data Resolution per bit = 0.1 hPa Unsigned MSB\n\n :param data: hex string of sensor value\n :return: int decoded value\n \"\"\"\n return hex_to_int(data, False) / 10.0\n\n\ndef gyrometer(data):\n \"\"\"Gyrometer | \tData Resolution per bit = 0.01 deg/s Signed MSB per axis\n Data Size: 6 bytes. x axis value = 2 bytes, y axis value = 2 bytes, z axis value = 2 bytes.\n Example: 04 D2 FB 2E 00 00 --> 04D2 - x, FB2E - y, 0000 - z.\n\n :param data: hex string of sensor value\n :return: dictionary of x,y,z axis as keys and their values\n \"\"\"\n return {'x': hex_to_int(data[:4]) / 100.0, 'y': hex_to_int(data[4:8]) / 100.0, 'z': hex_to_int(data[8:]) / 100.0}\n\n\ndef gps_location(data):\n \"\"\"GPS Location | Data Resolution per bit below\n\n * Latitude : 0.0001 deg Signed MSB\n * Longitude : 0.0001 deg Signed MSB\n * Altitude : 0.01 meter Signed MSB\n\n :param data: hex string of sensor value\n :return: dictionary of lat,long,alt as key and their values\n \"\"\"\n return {'lat': hex_to_int(data[:6]) / 10000.0, 'long': hex_to_int(data[6:12]) / 10000.0, 'alt': hex_to_int(data[12:]) / 100.0}\n\n\nhex_library = {\n \"00\": {\n \"name\": \"Digital Input\",\n \"size\": 2,\n \"action\": digital_input_output_presence_illuminance\n },\n \"01\": {\n \"name\": \"Digital Output\",\n \"size\": 2,\n \"action\": digital_input_output_presence_illuminance\n },\n \"02\": {\n \"name\": \"Analog Input\",\n \"size\": 4,\n \"action\": analog_input_output\n },\n \"03\": {\n \"name\": \"Analog Output\",\n \"size\": 4,\n \"action\": analog_input_output\n },\n \"65\": {\n \"name\": \"Illuminance Sensor\",\n \"size\": 4,\n \"action\": digital_input_output_presence_illuminance\n },\n \"66\": {\n \"name\": \"Presence Sensor\",\n \"size\": 2,\n \"action\": digital_input_output_presence_illuminance\n },\n \"67\": {\n \"name\": \"Temperature Sensor\",\n \"size\": 4,\n \"action\": temperature\n },\n \"68\": {\n \"name\": \"Humidity Sensor\",\n \"size\": 2,\n \"action\": humidity\n },\n \"71\": {\n \"name\": \"Accelerometer\",\n \"size\": 12,\n \"action\": accelerometer\n },\n \"73\": {\n \"name\": \"Barometer\",\n \"size\": 4,\n \"action\": barometer\n },\n \"86\": {\n \"name\": \"Gyrometer\",\n \"size\": 12,\n \"action\": gyrometer\n },\n \"88\": {\n \"name\": \"GPS Location\",\n \"size\": 18,\n \"action\": gps_location\n }\n}\n","repo_name":"OlegZv/Python-CayenneLPP","sub_path":"python_cayennelpp/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"79"} +{"seq_id":"14207508848","text":"answers = open(\"input.txt\", \"r\").read().split(\"\\n\")\n\ngroupyes = []\nyes = 0\n\nfor i in answers:\n if not i:\n uniqueyes = set(groupyes)\n yes += len(uniqueyes)\n\n groupyes = []\n for u in i:\n groupyes.append(u)\n\nprint(yes)","repo_name":"Sebbern/Advent-of-Code","sub_path":"2020/day06/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"79"} +{"seq_id":"15995654145","text":"\r\nfrom multiprocessing.dummy import active_children\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nfrom os.path import exists\r\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler, normalize,LabelEncoder, RobustScaler\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score, fowlkes_mallows_score\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.cluster import AgglomerativeClustering, KMeans\r\nfrom sklearn.feature_selection import VarianceThreshold\r\nfrom sklearn import mixture as mx\r\nfrom sklearn.base import BaseEstimator, TransformerMixin, clone\r\nfrom numpy.random import randint\r\nfrom sympy import denom, numer\r\nfrom statsmodels.distributions.empirical_distribution import ECDF\r\n# Classes\r\n#--------------------------------------------------------------------------------------------------------#\r\nclass VarianceFilter(BaseEstimator, TransformerMixin):\r\n def __init__(self, thrshld):\r\n self.thrshld = thrshld\r\n\r\n\r\n def fit(self, X, y = None):\r\n return self\r\n\r\n def transform(self, X, y=None):\r\n X_copy = X.copy()\r\n X_norm = RobustScaler().fit_transform(X.copy())\r\n X_var = X_norm.var(axis=0)\r\n X_ = X_copy[:,(X_var < self.thrshld)]\r\n _,m = np.shape(X_)\r\n print(f\"VF returns observations of dim {m}\")\r\n return X_\r\n\r\n\r\n#--------------------------------------------------------------------------------------------------------# \r\n# python -m cProfile -o temp.dat main.py\r\ndef main():\r\n\r\n\r\n ## Question 1 ##\r\n q1_plot = {\r\n \"hist_plot\": False,\r\n \"scree_plot\": False,\r\n \"metrics_plot\": True, \r\n \"pair_plot\": True\r\n }\r\n\r\n question_1(q1_plot)\r\n \r\n ## Question 2 ##\r\n #question_2()\r\n \r\n ## Question 3 ## \r\n\r\n plt.show()\r\n\r\ndef question_1(plot):\r\n ## Data ## \r\n label_df, feature_df = load_SEQ_data();\r\n X = feature_df.to_numpy()\r\n preprocessor = pre_processing()\r\n X = preprocessor.fit_transform(X)\r\n true_labels = LabelEncoder().fit_transform(label_df)\r\n ## Models ## \r\n n_inits = 1000\r\n clusters = list(range(3,8))\r\n cases = [\r\n (KMeans, \"n_clusters\", {\"n_init\": n_inits, \"init\": \"k-means++\"}),\r\n (mx.GaussianMixture, \"n_components\", {\"n_init\" : n_inits}),\r\n (AgglomerativeClustering, \"n_clusters\", {\"affinity\":\"cosine\",\"linkage\": \"average\"})\r\n ]\r\n cl_metrics = [silhouette_score, davies_bouldin_score, calinski_harabasz_score]\r\n\r\n ## Feature pre - visualisation ##\r\n #if plot[\"hist_plot\"]:\r\n # col_hist(feature_df,1000)\r\n ## Initial vizualisation ## \r\n # if plot[\"scree_plot\"]:\r\n # scree_plot(preprocessor[\"PCA\"])\r\n if plot[\"pair_plot\"]:\r\n pair_plot(X, 3, {\"True_labels\": true_labels})\r\n\r\n ## Run clustering ##\r\n metrics_df, predicted_labels = run_clustering(X,cases, clusters, cl_metrics)\r\n if plot[\"metrics_plot\"]:\r\n metrics_plot(metrics_df)\r\n for key in predicted_labels.keys():\r\n preds = predicted_labels[key]\r\n print(key,adjusted_rand_score(true_labels, preds), fowlkes_mallows_score(true_labels, preds))\r\n ## Visualize clustering:\r\n # model = models[15]\r\n # pred_labels = predicted_labels[model]\r\n # if plot[\"pair_plot\"]:\r\n # pair_plot(X, 3, {\"Predicted_labels\": pred_labels})\r\n # pair_plot(X, 3, {\"True_labels\":true_labels})\r\n # print(f\"Rand score for {model}: \",adjusted_rand_score(true_labels,pred_labels))\r\n ## \"Best\" metrics + visualize ##\r\n #pair_plot(X_, 5, true_labels)\r\n\r\n plt.show()\r\n return \r\n\r\ndef question_2():\r\n _, feature_df = load_SEQ_data();\r\n n_inits = 100\r\n clusters = list(range(2,10))\r\n cases = [\r\n #(KMeans, \"n_clusters\", {\"n_init\": n_inits, \"init\": \"k-means++\"}),\r\n # (mx.GaussianMixture, \"n_components\", {\"n_init\" : n_inits}),\r\n (AgglomerativeClustering, \"n_clusters\", {\"linkage\": \"ward\"})\r\n ]\r\n preprocessor = pre_processing()\r\n ms = consensus_clustering(feature_df, cases, clusters, preprocessor, verbose = True)\r\n for _, m in ms.items():\r\n ecdf = ECDF(m.flatten())\r\n plt.plot(ecdf.x, ecdf.y)\r\n plt.legend(ms.keys())\r\n return\r\n\r\ndef consensus_clustering(df, \r\n cases,\r\n clusters,\r\n pipeline, \r\n k = 100, \r\n p = 0.8, \r\n verbose = False):\r\n \"\"\"\r\n inputs:\r\n df - dataframe\r\n cases - initialized sklearn model\r\n pipeline - the given preprocessing pipeline\r\n k - number of subsamples\r\n p - proportion of samples \r\n Q - tuple of ecdf thresholds\r\n ecdf_plot - whether to make an ECDF plot\r\n\r\n outputs: \r\n PACs - PAC_k values for specificed Q\r\n ECDFs - empirical cumulative distribution for each cluster count\r\n Mk - Connectivity matrix for each cluster count\r\n\r\n\r\n Aim: Test cluster stability for different variance thresholds, models and numbers of PCA components, \r\n return the consensus matrix for use as a similarity matrix for Agg. Hier. Clustering\r\n \r\n\r\n \"\"\"\r\n print(\"Testing stability\")\r\n def update_numerator(numerator,j, labels, subsample_indices):\r\n \"\"\"\r\n inputs:\r\n numerator - matrix dim n*n; sum of connectivity matrices\r\n pred_labels - vector of dim ~0.8n of labels, remember that this is a subsample¨\r\n connect - connectivity matrix for current subsample run\r\n\r\n output: - added 1 to all (i,j) where labels(i) = labels(j)\r\n \r\n \"\"\" \r\n connect = np.zeros((n,n), dtype = float)\r\n for label, ind in zip(labels, subsample_indices):\r\n # For a given label and index we add one if the prediction of i,j is the same\r\n active_subsample_indices = subsample_indices[np.nonzero(labels == label)] # The rows of X where pred. is label\r\n connect[ind,active_subsample_indices] = 1.0 \r\n np.add(numerator[:,:,j], connect, numerator[:,:,j])\r\n return numerator\r\n\r\n def update_denominator(denominator,j, subsample_indices):\r\n \"\"\"\r\n inputs: \r\n denominator - matrix dim n*n; sum of indication matrices\r\n ss_indices - vector of dim ~pn of choses indices for current subsample\r\n indicator - indicator matrix for current subsample\r\n\r\n output: - added ones to all (i,j) in ss_indices \r\n \r\n \"\"\"\r\n indicator = np.zeros((n,n), dtype = float)\r\n for ind in subsample_indices: \r\n indicator[ind,subsample_indices] = 1.0 \r\n np.add(denominator[:,:,j], indicator, denominator[:,:,j]) # Sum the indicator matrices\r\n return denominator\r\n\r\n\r\n models = list()\r\n # Create the list of models\r\n for model, comp_param, params in cases:\r\n for i in clusters:\r\n params[comp_param] = i\r\n models.append(model(**params))\r\n \r\n X = df.to_numpy()\r\n X = pipeline.fit_transform(X)\r\n n,_ = np.shape(X)\r\n\r\n consensus_matrices = {}\r\n\r\n no_models = len(models)\r\n numerator = np.zeros((n,n,no_models), dtype = float) # We calculate the consensus matrix from the numerator \r\n denominator = np.zeros((n,n,no_models), dtype = float) # and denominator matrices i.e the sums of the connectivity \r\n # and identicator matrices, respectively\r\n subsample_size = int(np.floor(p*n)) \r\n for j in range(k):\r\n # For a given subsample, we update the denominator, we fit all models and update the numerator \r\n subsample_indices = np.random.choice(n, subsample_size, replace = False)\r\n X_ = X[subsample_indices,:] # Our subsampled data\r\n if verbose:\r\n print(f'At iteration: {j}') \r\n for i, model in enumerate(models):\r\n model_ = clone(model) # Clone model and if possible set a random_state\r\n \r\n model_.fit(X_) # Fit the clusterer to the data\r\n try: \r\n pred_labels = model_.labels_\r\n except AttributeError:\r\n try: \r\n pred_labels = model_.predict(X_)\r\n except AttributeError:\r\n print(\"Model has neither predict nor labels_ attr.\") \r\n raise AttributeError\r\n\r\n # Now to update the numerator and denominator matrices\r\n numerator = update_numerator(numerator,i, pred_labels,subsample_indices)\r\n denominator = update_denominator(denominator,i,subsample_indices)\r\n\r\n assert(np.all(numerator<=denominator))\r\n \r\n assert(np.all(denominator != 0))\r\n consensus = np.divide(numerator, denominator)\r\n for i, model in enumerate(models):\r\n consensus_matrices[model] = consensus[:,:,i]\r\n \r\n return consensus_matrices\r\n\r\ndef run_clustering(X_,cases, clusters, cl_metrics):\r\n \"\"\"\r\n inputs: \r\n X_ - data arrays, preprocessed\r\n cases - dict of models and their parameters\r\n clusters - list of clusters\r\n cl_metrics - list of metric objects\r\n \r\n \r\n output: \r\n metrics_df - dataframe of metrics for a certain model and cluster\r\n predicted_labels - dict of the predictions\r\n \"\"\"\r\n \r\n predicted_labels = {}\r\n models = list()\r\n model_names = list()\r\n clusters_ = list()\r\n columns = ['Clusters','Model']\r\n columns.extend(str(metric.__name__) for metric in cl_metrics)\r\n \r\n # Create the list of models and clusters\r\n for model, comp_param, params in cases:\r\n for i in clusters:\r\n params[comp_param] = i\r\n models.append(model(**params))\r\n model_names.append(model.__name__)\r\n clusters_.extend(clusters)\r\n\r\n # Initialize dataframe with clusters and model names\r\n metrics_df = pd.DataFrame(columns = columns)\r\n shape = (len(model_names),len(columns)-2)\r\n metrics_df['Clusters'] = pd.Series(clusters_, dtype= int)\r\n metrics_df['Model'] = pd.Series(model_names, dtype= \"string\")\r\n metrics = np.ndarray(shape)\r\n\r\n # Fit the model to the data and return the predicted clusters, evaluate these using the specified clustering metrics\r\n for i,model in enumerate(models):\r\n model.fit(X_)\r\n pred_labels = predict_cluster(model, X_)\r\n\r\n metrics[i,:] = [m(X_,pred_labels) for m in cl_metrics]\r\n predicted_labels[model] = pred_labels\r\n\r\n # Add our metrics to the dataframe\r\n for i,metric in enumerate(cl_metrics):\r\n metrics_df[metric.__name__] = metrics[:,i]\r\n return (metrics_df, predicted_labels)\r\n\r\ndef pre_processing(thrshld = 2.2, percent_variance = 0.8):\r\n # Return our preprocessing pipeline\r\n preprocessor = Pipeline(steps=[\r\n ('variance_filter', VarianceThreshold(thrshld)),\r\n ('scaler', MinMaxScaler()),\r\n ('PCA', PCA(n_components=percent_variance, svd_solver = 'full'))])\r\n return preprocessor\r\n\r\ndef load_SEQ_data():\r\n # Reading .h5 files seem faster in this case\r\n if exists('data/data.h5'):\r\n feature_df = pd.read_hdf('data/data.h5')\r\n label_df = pd.read_csv('data/labels.csv')\r\n feature_df = feature_df.iloc[:,1:]\r\n return label_df[\"Class\"], feature_df.iloc[:,1:] \r\n else:\r\n feature_df = pd.read_csv(\"data/data.csv\")\r\n label_df = pd.read_csv('data/labels.csv')\r\n feature_df.to_hdf('data/data.h5',key = 'df', mode='w') \r\n return label_df[\"Class\"], feature_df.iloc[:,1:] \r\n\r\ndef col_hist(df: pd.DataFrame, no_bins: int):\r\n # Plots histograms of the different features\r\n fontsize = 30\r\n plt.figure()\r\n df_mean = df.mean(axis=0).transpose()\r\n df_var = df.var(axis=0).transpose()\r\n ecdf_mean = ECDF(df_mean)\r\n ecdf_var = ECDF(df_var)\r\n plt.subplot(221)\r\n plt.hist(df_mean, bins = no_bins)\r\n plt.title(\"Feature means\", fontdict={'fontsize': fontsize})\r\n\r\n plt.subplot(222)\r\n plt.hist(df_var, bins = no_bins)\r\n plt.title(\"Feature variances\", fontdict={'fontsize': fontsize})\r\n\r\n plt.subplot(223)\r\n plt.plot(ecdf_mean.x, ecdf_mean.y)\r\n plt.title(\"ECDF of feature means\",fontdict={'fontsize': fontsize})\r\n\r\n plt.subplot(224)\r\n plt.plot(ecdf_var.x, ecdf_var.y)\r\n plt.title(\"ECDF of feature variances\",fontdict={'fontsize': fontsize})\r\n\r\ndef scree_plot(pca):\r\n fontsize = 25\r\n ratios = pca.explained_variance_ratio_\r\n ratio_sums = np.cumsum(ratios)\r\n comps = np.arange(1,len(ratios)+1)\r\n ratios = ratios/np.max(ratios)\r\n plt.plot(comps, ratios)\r\n plt.plot(np.concatenate(([0],comps)), np.concatenate(([0],ratio_sums)))\r\n plt.legend([\"Standardised explained variance\",\"Cumulative percentage explained variance\"], fontsize = fontsize)\r\n plt.xlabel(\"No. of PCA components\", fontsize = fontsize)\r\n plt.xticks(fontsize = fontsize)\r\n plt.yticks(fontsize = fontsize)\r\n return\r\n\r\ndef pair_plot(X,no_comps, labels = None):\r\n \"\"\"\r\n labels is a dict with the name we want in the plot\r\n \"\"\"\r\n sns.set(font_scale = 2)\r\n X_ = X[:,:no_comps]\r\n cols = [\"PC%s\" % _ for _ in range(1,no_comps+1)]\r\n df = pd.DataFrame(X_,columns=cols)\r\n if not isinstance(labels, type(None)):\r\n name = list(labels)[0]\r\n df[\"labels\"] = labels[name]\r\n g = sns.pairplot(df, hue = \"labels\")\r\n g.map_lower(sns.kdeplot, levels=4)\r\n if name == \"True_labels\":\r\n plt.subplots_adjust(top=0.9)\r\n g.fig.suptitle(\"True labels\")\r\n elif name == \"Predicted_labels\":\r\n plt.subplots_adjust(top=0.9)\r\n g.fig.suptitle(\"Predicted labels\")\r\n else:\r\n pass\r\n else: \r\n g = sns.pairplot(df)\r\n g.title(name)\r\n return\r\n \r\ndef predict_cluster(model, X):\r\n try: \r\n prediction = model.labels_\r\n except AttributeError:\r\n try: \r\n prediction = model.predict(X)\r\n except AttributeError:\r\n print(\"Model has neither predict nor labels_ attr.\") \r\n raise AttributeError\r\n return prediction\r\n \r\ndef metrics_plot(metrics: pd.DataFrame):\r\n fig = plt.figure(constrained_layout=True)\r\n no_models = metrics['Model'].nunique()\r\n models = metrics['Model'].unique().to_numpy()\r\n metric_cols = metrics.iloc[:,2:].columns\r\n # Plot the different metrics\r\n no_cols = metrics.shape[1]-2\r\n # Create a row of figures for each model\r\n subfigs = fig.subfigures(nrows=no_models, ncols=1)\r\n # Iterate over subfigs & models\r\n for row, subfig in enumerate(subfigs):\r\n model = models[row]\r\n subfig.suptitle(f'{model}')\r\n model_metrics = metrics[metrics['Model']==model]\r\n clusters = model_metrics['Clusters']\r\n axs = subfig.subplots(nrows=1, ncols=no_cols)\r\n for i, ax in enumerate(axs):\r\n col = metric_cols[i]\r\n metric_col = model_metrics[col]\r\n ax.plot(clusters, metric_col)\r\n ax.set_title(f'{col}')\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"filipwestberg/mve441-project2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"74089738176","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# sys.path.insert(0, os.path.abspath('.'))\nimport os\nimport sys\n\n# @jpchen's hack to get rtd builder to install latest pytorch\n# @anguelos: why did kornia had this at the end of conf.py?\nif 'READTHEDOCS' in os.environ:\n os.system('pip install torch kornia')\n\ncurrent_path = os.path.abspath(os.path.join(__file__, \"..\", \"..\", \"..\"))\nsys.path.append(current_path)\n\nimport os\nimport sys\n\nimport torch\nimport tormentor\n\nimport sphinx_gallery\nimport sphinx_rtd_theme\n\n\n\n# -- Project information -----------------------------------------------------\n\nproject = 'Tormentor'\ncopyright = '2020, Anguelos Nicolaou'\nauthor = 'Anguelos Nicolaou'\n\n# The full version, including alpha/beta/rc tags\nrelease = '0.1.1'\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.doctest',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.githubpages',\n 'nbsphinx',\n 'sphinxcontrib.bibtex',\n# 'sphinx_gallery.gen_gallery',\n]\n\nbibtex_bibfiles = ['refs.bib']\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = []\n\nsource_suffix = ['.rst', '.ipynb']\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'alabaster'\nhtml_theme = 'agogo'\n\nhtml_theme = 'sphinx_rtd_theme'\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3/', None),\n 'numpy': ('http://numpy.org/doc/stable/', None),\n 'torch': ('http://pytorch.org/docs/stable/', None),\n}\n\n\n# ugly hack to generate image samples inside read the docs\n#import os\n#os.system(\"cd docs; make all_images\")\n","repo_name":"anguelos/tormentor","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":116,"dataset":"github-code","pt":"79"} +{"seq_id":"4765143391","text":"import json\n\nfrom django.views.generic import CreateView, TemplateView\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect\nfrom django.contrib import messages\nfrom django.utils.html import strip_tags\n\nfrom braces.views import LoginRequiredMixin\n\nfrom core.decorators import (\n handle_exceptions_for_ajax, handle_exceptions_for_admin\n)\n\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\nfrom projects.models import Project\nfrom categories.models import Category\n\nfrom .base import STATUS\nfrom .forms import GroupingCreateForm\nfrom .models import Grouping, Rule\nfrom .serializers import GroupingSerializer\n\n\n# ############################################################################\n#\n# Administration views\n#\n# ############################################################################\n\nclass GroupingList(LoginRequiredMixin, TemplateView):\n template_name = 'datagroupings/grouping_list.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n user = self.request.user\n\n context = super(GroupingList, self).get_context_data()\n context['project'] = Project.objects.as_admin(user, project_id)\n\n return context\n\n\nclass GroupingCreate(LoginRequiredMixin, CreateView):\n \"\"\"\n Displays the create view page\n \"\"\"\n form_class = GroupingCreateForm\n template_name = 'datagroupings/grouping_create.html'\n\n def get_success_url(self):\n project_id = self.kwargs['project_id']\n return reverse(\n 'admin:grouping_overview',\n kwargs={'project_id': project_id, 'grouping_id': self.object.id}\n )\n\n @handle_exceptions_for_admin\n def get_context_data(self, form, **kwargs):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n project_id = self.kwargs['project_id']\n\n context = super(\n GroupingCreate, self).get_context_data(**kwargs)\n\n context['project'] = Project.objects.as_admin(\n self.request.user, project_id\n )\n return context\n\n def form_valid(self, form):\n \"\"\"\n Is called when the POSTed data is valid and creates the observation\n type.\n \"\"\"\n project_id = self.kwargs['project_id']\n project = Project.objects.as_admin(self.request.user, project_id)\n\n form.instance.project = project\n form.instance.creator = self.request.user\n messages.success(self.request, \"The data grouping has been created.\")\n return super(GroupingCreate, self).form_valid(form)\n\n\nclass GroupingOverview(LoginRequiredMixin, TemplateView):\n template_name = 'datagroupings/grouping_overview.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id, grouping_id):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n user = self.request.user\n grouping = Grouping.objects.as_admin(user, project_id, grouping_id)\n return super(GroupingOverview, self).get_context_data(\n grouping=grouping\n )\n\n\nclass GroupingSettings(LoginRequiredMixin, TemplateView):\n template_name = 'datagroupings/grouping_settings.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id, grouping_id):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n user = self.request.user\n grouping = Grouping.objects.as_admin(user, project_id, grouping_id)\n return {'grouping': grouping, 'status_types': STATUS}\n\n def post(self, request, project_id, grouping_id):\n context = self.get_context_data(project_id, grouping_id)\n grouping = context.pop('grouping')\n data = request.POST\n\n grouping.name = strip_tags(data.get('name'))\n grouping.description = strip_tags(data.get('description'))\n grouping.save()\n\n messages.success(self.request, \"The data grouping has been updated.\")\n context['grouping'] = grouping\n return self.render_to_response(context)\n\n\nclass GroupingPermissions(LoginRequiredMixin, TemplateView):\n template_name = 'datagroupings/grouping_permissions.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id, grouping_id):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n user = self.request.user\n grouping = Grouping.objects.as_admin(user, project_id, grouping_id)\n return super(GroupingPermissions, self).get_context_data(\n grouping=grouping\n )\n\n\nclass GroupingDelete(LoginRequiredMixin, TemplateView):\n template_name = 'base.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id, grouping_id):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n user = self.request.user\n grouping = Grouping.objects.as_admin(user, project_id, grouping_id)\n return super(GroupingDelete, self).get_context_data(grouping=grouping)\n\n def get(self, request, project_id, grouping_id):\n context = self.get_context_data(project_id, grouping_id)\n grouping = context.pop('grouping', None)\n\n if grouping is not None:\n grouping.delete()\n\n messages.success(self.request, 'The data grouping has been deleted')\n\n return redirect('admin:grouping_list', project_id=project_id)\n\n\nclass RuleCreate(LoginRequiredMixin, CreateView):\n \"\"\"\n Displays the rule create page\n \"\"\"\n template_name = 'datagroupings/rule_create.html'\n model = Rule\n\n @handle_exceptions_for_admin\n def get_context_data(self, form, **kwargs):\n \"\"\"\n Returns the context data for creating the view.\n \"\"\"\n project_id = self.kwargs['project_id']\n grouping_id = self.kwargs['grouping_id']\n\n context = super(\n RuleCreate, self).get_context_data(**kwargs)\n\n context['grouping'] = Grouping.objects.as_admin(\n self.request.user, project_id, grouping_id\n )\n return context\n\n @handle_exceptions_for_admin\n def post(self, request, project_id, grouping_id):\n \"\"\"\n Creates a new Rule with the POSTed data.\n \"\"\"\n grouping = Grouping.objects.as_admin(\n self.request.user,\n project_id,\n grouping_id\n )\n category = Category.objects.as_admin(\n self.request.user, project_id, request.POST.get('category'))\n\n rules = None\n min_date = None\n max_date = None\n\n try:\n rules = json.loads(request.POST.get('rules', None))\n min_date = rules.pop('min_date')\n max_date = rules.pop('max_date')\n except ValueError:\n pass\n\n Rule.objects.create(\n grouping=grouping,\n category=category,\n min_date=min_date,\n max_date=max_date,\n filters=rules\n )\n messages.success(self.request, 'The filter has been created.')\n return redirect('admin:grouping_overview',\n project_id=project_id, grouping_id=grouping_id)\n\n\nclass RuleSettings(LoginRequiredMixin, TemplateView):\n \"\"\"\n Displays the settings page\n \"\"\"\n template_name = 'datagroupings/rule_settings.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id, grouping_id, rule_id, **kwargs):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n view = Grouping.objects.as_admin(\n self.request.user,\n project_id,\n grouping_id\n )\n context = super(RuleSettings, self).get_context_data(**kwargs)\n\n context['rule'] = view.rules.get(pk=rule_id)\n return context\n\n @handle_exceptions_for_admin\n def post(self, request, project_id, grouping_id, rule_id):\n view = Grouping.objects.as_admin(\n self.request.user,\n project_id,\n grouping_id\n )\n rule = view.rules.get(pk=rule_id)\n\n rules = None\n\n try:\n rules = json.loads(request.POST.get('rules'))\n rule.min_date = rules.pop('min_date')\n rule.max_date = rules.pop('max_date')\n except ValueError:\n pass\n\n rule.filters = rules\n rule.save()\n messages.success(self.request, 'The filter has been updated.')\n return redirect('admin:grouping_overview',\n project_id=project_id, grouping_id=grouping_id)\n\n\nclass FilterDelete(LoginRequiredMixin, TemplateView):\n template_name = 'base.html'\n\n @handle_exceptions_for_admin\n def get_context_data(self, project_id, grouping_id, filter_id, **kwargs):\n \"\"\"\n Creates the request context for rendering the page\n \"\"\"\n grouping = Grouping.objects.as_admin(\n self.request.user, project_id, grouping_id)\n context = super(FilterDelete, self).get_context_data(**kwargs)\n\n context['filter'] = grouping.rules.get(pk=filter_id)\n return context\n\n def get(self, request, project_id, grouping_id, filter_id):\n context = self.get_context_data(project_id, grouping_id, filter_id)\n data_filter = context.pop('filter', None)\n\n if data_filter is not None:\n data_filter.delete()\n\n messages.success(self.request, 'The filter has been deleted')\n\n return redirect('admin:grouping_overview',\n project_id=project_id, grouping_id=grouping_id)\n\n\n# ############################################################################\n#\n# AJAX API views\n#\n# ############################################################################\n\nclass GroupingUpdate(APIView):\n \"\"\"\n API Endpoints for a view in the AJAX API.\n /ajax/projects/:project_id/views/:grouping_id\n \"\"\"\n @handle_exceptions_for_ajax\n def put(self, request, project_id, grouping_id, format=None):\n \"\"\"\n Updates a view\n \"\"\"\n view = Grouping.objects.as_admin(request.user, project_id, grouping_id)\n serializer = GroupingSerializer(\n view, data=request.DATA, partial=True,\n fields=('id', 'name', 'description', 'status', 'isprivate')\n )\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"sfwatergit/geokey","sub_path":"datagroupings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"79"} +{"seq_id":"23072530189","text":"#!/usr/bin/env python3.8\n\nfrom xml.etree import ElementTree\nfrom typing import Type\nfrom zipfile import ZipFile\nimport re\nimport sys\n\ndef lines_from_xml(tree: ElementTree):\n for node in tree.findall('.//*'):\n text = node.text\n if text:\n yield text\n\n\ndef msoffice_document(path: str):\n PPTX_SLIDES = r'^ppt/slides/.*\\.xml$'\n DOCX_DOCUMENT = r'^word/document.xml$'\n ext_matches = re.search(r'.*\\.([a-z]+)$', path)\n if ext_matches is None:\n raise ValueError(f\"Path \\\"{path}\\\" doesn't have an extension\")\n ext = ext_matches[1]\n if ext in ['docx', 'DOCX']:\n document_path_re = DOCX_DOCUMENT\n elif ext in ['pptx', 'PPTX']:\n document_path_re = PPTX_SLIDES\n with ZipFile(path) as archive:\n for member in archive.namelist():\n if re.search(document_path_re, member):\n with archive.open(member) as f:\n tree = ElementTree.fromstring(f.read())\n for line in lines_from_xml(tree):\n yield line\n\n\nclass Tokens:\n def __init__(self):\n self.tokens = set()\n\n\n def add(self, line):\n for token in re.findall(r'(\\w+)', line):\n self.tokens.add(token.lower())\n\n def __iter__(self):\n return self.tokens.__iter__()\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 1:\n sys.exit(1)\n tokens = Tokens()\n for document_path in sys.argv[1:]:\n for line in msoffice_document(document_path):\n tokens.add(line)\n for token in tokens:\n print(token)\n","repo_name":"proprietary/msoffice-document-tokenizer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"19442563584","text":"import logging\nfrom savu.plugins.unregistered.fluo_fitters.base_fluo_fitter \\\n import BaseFluoFitter\nfrom flupy.xrf_data_handling import XRFDataset\nimport numpy as np\nfrom savu.plugins.utils import register_plugin\n\n\n#@register_plugin\nclass FastxrfFitting(BaseFluoFitter):\n def __init__(self):\n logging.debug(\"Starting fast fitter\")\n super(FastxrfFitting, self).__init__(\"FastxrfFitting\")\n\n def base_pre_process(self):\n pass\n\n def pre_process(self):\n \"\"\"\n This method is called after the plugin has been created by the\n pipeline framework as a pre-processing step.\n \"\"\"\n in_meta_data = self.get_in_meta_data()[0]\n self.xrfd = self.prep_xrfd(in_meta_data)\n\n def process_frames(self, data):\n logging.debug(\"Running azimuthal integration\")\n xrfd = self.xrfd\n# print np.squeeze(data).shape\n xrfd.datadict['data'] = np.squeeze(data)\n# print \"I'm here\"\n xrfd.fitbatch()\n characteristic_curves = xrfd.matrixdict[\"Total_Matrix\"]\n weights = xrfd.fitdict['parameters']\n full_curves = characteristic_curves*weights\n areas = full_curves.sum(axis=0)\n# print \"the shape is :\" + str(characteristic_curves.shape)\n return [weights, areas, xrfd.fitdict['resid']]\n\n def setPositions(self, in_meta_data):\n '''\n overload this to get the right setup method\n '''\n xrfd = self.prep_xrfd(in_meta_data)\n numcurves = xrfd.matrixdict['Total_Matrix'].shape[1]\n idx = np.ones((numcurves,))\n return idx\n \n \n def prep_xrfd(self, in_meta_data):\n self.axis = in_meta_data.get(\"energy\")\n xrfd = XRFDataset()\n # now to overide the experiment\n xrfd.paramdict[\"Experiment\"] = {}\n xrfd.paramdict[\"Experiment\"][\"incident_energy_keV\"] = \\\n self.parameters[\"mono_energy\"]\n# print xrfd.paramdict[\"Experiment\"][\"incident_energy_keV\"]\n xrfd.paramdict[\"Experiment\"][\"collection_time\"] = 1\n xrfd.paramdict[\"Experiment\"]['Attenuators'] = \\\n self.parameters['sample_attenuators']\n xrfd.paramdict[\"Experiment\"]['detector_distance'] = \\\n self.parameters['detector_distance']\n xrfd.paramdict[\"Experiment\"]['elements'] = \\\n self.parameters['elements']\n xrfd.paramdict[\"Experiment\"]['incident_angle'] = \\\n self.parameters['incident_angle']\n xrfd.paramdict[\"Experiment\"]['exit_angle'] = \\\n self.parameters['exit_angle']\n xrfd.paramdict[\"Experiment\"]['photon_flux'] = self.parameters['flux']\n\n # overide the fitting parameters\n xrfd.paramdict[\"FitParams\"][\"background\"] = 'strip'\n xrfd.paramdict[\"FitParams\"][\"fitted_energy_range_keV\"] = self.parameters[\"fitted_energy_range_keV\"]\n xrfd.paramdict[\"FitParams\"][\"include_pileup\"] = self.parameters[\"include_pileup\"]\n xrfd.paramdict[\"FitParams\"][\"include_escape\"] = self.parameters[\"include_escape\"]\n datadict = {}\n datadict[\"rows\"] = self.get_max_frames()\n datadict[\"cols\"] = 1 # we will just treat it as one long row\n datadict[\"average_spectrum\"] = np.zeros_like(self.axis)\n datadict[\"Detectors\"] = {}\n datadict[\"Detectors\"][\"type\"] = 'Vortex_SDD_Xspress'\n xrfd.xrfdata(datadict)\n xrfd._createSpectraMatrix()\n if xrfd.paramdict['FitParams']['mca_energies_used']==self.axis:\n pass\n else:\n self.axis = xrfd.paramdict['FitParams']['mca_energies_used']\n return xrfd","repo_name":"DiamondLightSource/Savu","sub_path":"savu/plugins/unregistered/fluo_fitters/fastxrf_fitting.py","file_name":"fastxrf_fitting.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"79"} +{"seq_id":"4695429443","text":"def solution(s):\r\n temp_list = s[2:-2].split('},{')\r\n temp_list2 = []\r\n arr = []\r\n for i in range(len(temp_list)):\r\n temp_list2.append(list(map(int,temp_list[i].split(','))))\r\n for i in range(len(temp_list2)):\r\n for j in range(0,len(temp_list2)):\r\n if len(temp_list2[j]) == i+1:\r\n arr.append(temp_list2[j])\r\n\r\n temp_dict = dict(enumerate(arr))\r\n answer = [temp_dict[0][0]]\r\n for key,string in temp_dict.items():\r\n if key != len(arr)-1:\r\n a = set(string)\r\n b = set(temp_dict[key+1])\r\n answer.append((b-a).pop())\r\n return answer\r\n# s = s.replace('{','',1000000).replace('}','',1000000)\r\n# replace 사용해서 리팩토링해보기\r\n \r\nprint(solution(\"{{2},{2,1},{2,1,3},{2,1,3,4}}\"))\r\nprint(solution(\"{{20,111},{111}}\"))\r\nprint(solution(\"{{123}}\"))\r\nprint(solution(\"{{4,2,3},{3},{2,3,4,1},{2,3}}\"))","repo_name":"asooso1/algorithm","sub_path":"Programmers/prg_튜플.py","file_name":"prg_튜플.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"37004747749","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom apps.role import models as mysql_db\nfrom public import public_methods\n\n\n@csrf_exempt\ndef user_info(request):\n\n if request.method == 'POST':\n\n message = {}\n\n post = request.POST\n user_id = post[\"userId\"]\n user_type = post[\"userType\"]\n message_type = post[\"messageType\"]\n\n get_user_info = mysql_db.Person.objects.get(user_id=user_id)\n\n if message_type == \"loginSearch\":\n\n if user_type == \"0\" or user_type == \"1\":\n\n get_teacher_info = mysql_db.Teacher.objects.get(user_id=user_id)\n\n phone = get_user_info.phone\n status = get_user_info.status\n sex = get_user_info.sex\n teach_type = get_teacher_info.teach_type\n age = get_teacher_info.age\n salary = get_teacher_info.salary\n school = get_teacher_info.school\n level = get_teacher_info.level\n name = get_teacher_info.name\n\n message = {\"phone\": phone,\n \"sex\": sex,\n \"teachType\": teach_type,\n \"age\": age,\n \"school\": school,\n \"name\": name\n }\n\n elif user_type == \"2\":\n\n get_student_info = mysql_db.Student.objects.get(user_id=user_id)\n phone = get_user_info.phone\n status = get_user_info.status\n sex = get_user_info.sex\n study_type = get_student_info.study_type\n age = get_student_info.age\n price = get_student_info.price\n school = get_student_info.school\n periods = get_student_info.periods\n left_periods = get_student_info.left_periods\n name = get_student_info.name\n\n message = {\"phone\": phone,\n \"status\": status,\n \"sex\": sex,\n \"age\": age,\n \"school\": school,\n \"name\": name,\n \"studyType\": study_type,\n \"periods\": periods,\n \"leftPeriods\": left_periods\n }\n message.setdefault('userId', user_id)\n message.setdefault('userType', user_type)\n\n response_message = {\"message\": message}\n response = public_methods.response_message(\"success\", response_message, \"100001\")\n return JsonResponse(response)\n","repo_name":"swlim5427/MysSchool","sub_path":"apps/role/views/user_info.py","file_name":"user_info.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"25009150124","text":"import sys\r\nimport pygame\r\nfrom raindrop import Raindrop\r\n\r\nfrom settings import Settings\r\nfrom random import randint\r\n\r\nclass Rain:\r\n \"\"\"Overall class to manage assets and behavior.\"\"\"\r\n\r\n def __init__(self):\r\n \"\"\"Initialize and create resources.\"\"\"\r\n pygame.init()\r\n self.settings = Settings()\r\n self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))\r\n pygame.display.set_caption(\"Rain Simulator\")\r\n \r\n self.raindrops = pygame.sprite.Group()\r\n\r\n \r\n def run_game(self):\r\n \"\"\"Start the main loop for the program.\"\"\"\r\n while True:\r\n self._check_events()\r\n self._update_screen()\r\n # self._add_raindrop()\r\n self._update_raindrops()\r\n \r\n keys = pygame.key.get_pressed()\r\n if keys[pygame.K_SPACE]:\r\n if len(self.raindrops) < 12:\r\n self._change_x_coordinate()\r\n self._add_raindrop()\r\n \r\n\r\n\r\n def _add_raindrop(self):\r\n \"\"\"Create a new raindrop and add it to the raindrops group.\"\"\"\r\n if len(self.raindrops) < self.settings.raindrops_allowed:\r\n new_raindrop = Raindrop(self)\r\n self.raindrops.add(new_raindrop)\r\n\r\n def _update_raindrops(self):\r\n \"\"\"Update position of raindrops and get rid of old raindrops.\"\"\"\r\n # Update raindrop positions.\r\n self.raindrops.update()\r\n\r\n # Get rid of raindrops that have been disappeared.(hit the bottom)\r\n for raindrop in self.raindrops.copy():\r\n if raindrop.rect.top >= self.settings.screen_height:\r\n self.raindrops.remove(raindrop)\r\n self._change_x_coordinate()\r\n \r\n def _change_x_coordinate(self):\r\n self.settings.raindrop_x_coordinate = randint(0, float(self.settings.screen_width))\r\n\r\n def _check_events(self):\r\n \"\"\"Respond to keypresses and mouse events.\"\"\"\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN:\r\n self._check_keydown_events(event)\r\n def _check_keydown_events(self,event):\r\n \"\"\"Respond to keypresses.\"\"\"\r\n if event.key == pygame.K_q:\r\n sys.exit()\r\n elif event.key == pygame.K_SPACE:\r\n self._add_raindrop()\r\n self._change_x_coordinate()\r\n\r\n def _update_screen(self):\r\n \"\"\"Update images on the screen, and flip to the new screen.\"\"\"\r\n self.screen.fill(self.settings.bg_color)\r\n for raindrop in self.raindrops.sprites():\r\n raindrop.draw_raindrop()\r\n # print(self.settings.raindrop_x_coordinate)\r\n print(len(self.raindrops))\r\n # print(rain._update_raindrops())\r\n pygame.display.flip()\r\n \r\nif __name__ == \"__main__\":\r\n # make a program instance, and run the program\r\n rain = Rain()\r\n rain.run_game()","repo_name":"bajco10/all-code","sub_path":"vacsie_projekty/raindrops/rain.py","file_name":"rain.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"40705426478","text":"T = int(input())\n\ndef postorder(pos):\n if pos >= N:\n return 0\n if tree[pos] == 0:\n lc = postorder(pos*2+1)\n rc = postorder(pos*2+2)\n tree[pos] = lc + rc\n return tree[pos]\n\nfor i in range(T):\n N, M, L = map(int, input().split())\n tree = [0] * N\n\n for j in range(M):\n idx, num = map(int, input().split())\n tree[idx - 1] = num\n\n postorder(0)\n\n print(\"#%d %d\" % (i+1, tree[L-1]))\n","repo_name":"JaeHeee/algorithm","sub_path":"SW Expert Academy/5178.py","file_name":"5178.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"21035557442","text":"class TwoWayNode(object):\r\n def __init__(self, data = None, next = None, previous = None):\r\n self.data = data\r\n self.next = next\r\n self.previous = previous\r\n\r\n\r\nclass Queue:\r\n def __init__(self):\r\n self.head = None\r\n self.tail = None\r\n self.count = 0\r\n\r\n\r\n def addSong(self, song):\r\n if self.head == None:\r\n self.head = TwoWayNode(song)\r\n self.tail = self.head\r\n else:\r\n current = self.head\r\n while current.next != None:\r\n current = current.next\r\n current.next = TwoWayNode(song)\r\n current.next.previous = current\r\n self.tail = current.next\r\n self.count += 1\r\n\r\n\r\n def playSongs(self):\r\n current = self.head\r\n while current != None:\r\n print(f'Song playing: {current.data} \\n')\r\n current = current.next\r\n\r\n","repo_name":"Mike-droid/estructuras-datos-lineales-python","sub_path":"playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"16452978275","text":"# -*- coding: utf-8 -*-\n\nimport re\n\ndef countWords(a_list):\n words = {}\n for i in range(len(a_list)):\n item = a_list[i]\n count = a_list.count(item)\n words[item] = count\n return sorted(words.items(), key = lambda item: item[1], reverse=True)\n\ncontent = \"\"\"\nThis is a test of the program, what it can do, and what it can't do.\n\"\"\"\n\nnew_content = content.replace(\"'\",\"\")\ncleanContent = re.sub('[^a-zA-Z]',' ', new_content)\n\nwordList = cleanContent.lower().split()\n\nresult = countWords(wordList)\n\nprint(result)\n\nprint(len(result))\n\n","repo_name":"nmaggiulli/of-dollars-and-data","sub_path":"analysis/xxxx_unique_word_count.py","file_name":"xxxx_unique_word_count.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":377,"dataset":"github-code","pt":"79"} +{"seq_id":"24764868530","text":"from random import randint\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom torch.utils.data.dataset import Dataset\r\n\r\nfrom .utils import cvtColor, preprocess_input\r\n\r\n# 训练时,输入的高分辨率图像一般为很大的图片。需要将其随机裁剪为预设的大小。再将裁剪的图像,下采样作为低分辨率图像。\r\n\r\n# 重设图片尺寸为正方形\r\ndef get_new_img_size(width, height, img_min_side=600):\r\n if width <= height:\r\n f = float(img_min_side) / width\r\n resized_height = int(f * height)\r\n resized_width = int(img_min_side)\r\n else:\r\n f = float(img_min_side) / height\r\n resized_width = int(f * width)\r\n resized_height = int(img_min_side)\r\n\r\n return resized_width, resized_height\r\n\r\n# 定义数据读取类\r\nclass SRGANDataset(Dataset):\r\n # 类构造函数\r\n def __init__(self, train_lines, lr_shape, hr_shape):\r\n # 继承父类\r\n super(SRGANDataset, self).__init__()\r\n # 数据集的长度\r\n self.train_lines = train_lines\r\n # 总batch数量\r\n self.train_batches = len(train_lines)\r\n\r\n self.lr_shape = lr_shape\r\n self.hr_shape = hr_shape\r\n # 获取数据集大小\r\n def __len__(self):\r\n # 返回数据集大小\r\n return self.train_batches\r\n # 根据索引提取数据\r\n def __getitem__(self, index):\r\n index = index % self.train_batches\r\n # Python中split是一个内置函数,用来对字符串进行分割,分割后的字符串以列表形式返回\r\n # 将train_line按空格分割为line列表, 并根据索引获取原始图像\r\n image_origin = Image.open(self.train_lines[index].split()[0])\r\n if self.rand()<.5:\r\n img_h = self.get_random_data(image_origin, self.hr_shape)\r\n else:\r\n img_h = self.random_crop(image_origin, self.hr_shape[1], self.hr_shape[0])\r\n # 利用双三次插值对HR图像进行下采样,得到LR图像\r\n img_l = img_h.resize((self.lr_shape[1], self.lr_shape[0]), Image.BICUBIC)\r\n # 对HR,LR图像标准化,���对通道进行调换\r\n img_h = np.transpose(preprocess_input(np.array(img_h, dtype=np.float32), [0.5,0.5,0.5], [0.5,0.5,0.5]), [2,0,1])\r\n img_l = np.transpose(preprocess_input(np.array(img_l, dtype=np.float32), [0.5,0.5,0.5], [0.5,0.5,0.5]), [2,0,1])\r\n # 返回HR,LR图像\r\n return np.array(img_l), np.array(img_h)\r\n\r\n # 返回0-1之间随机数\r\n def rand(self, a=0, b=1):\r\n # np.random.rand()返回0-1之间的随机数\r\n return np.random.rand()*(b-a) + a\r\n\r\n def get_random_data(self, image, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5, random=True):\r\n #------------------------------#\r\n # 读取图像并转换成RGB图像\r\n #------------------------------#\r\n image = cvtColor(image)\r\n #------------------------------#\r\n # 获得图像的高宽与目标高宽\r\n #------------------------------#\r\n # 真实输入图像大小\r\n # 图片的宽和高,iw和ih\r\n iw, ih = image.size\r\n # 网络输入大小\r\n # 输入尺寸的高和宽,h和w\r\n h, w = input_shape\r\n # 如果是非随机的,将图片等比例转化为网络输入大小\r\n if not random:\r\n # 保证长或宽,符合目标图像的尺寸\r\n scale = min(w/iw, h/ih)\r\n nw = int(iw*scale)\r\n nh = int(ih*scale)\r\n dx = (w-nw)//2\r\n dy = (h-nh)//2\r\n\r\n #---------------------------------#\r\n # 将图像多余的部分加上灰条\r\n #---------------------------------#\r\n # 采用双三次插值算法缩小图像\r\n image = image.resize((nw,nh), Image.BICUBIC)\r\n # 创建一个新的灰度图像,缩放后的图像可能不能满足网络大小,所以可以给周边补充一些灰度条。\r\n # 其余用灰色填充,即(128, 128, 128)\r\n new_image = Image.new('RGB', (w,h), (128,128,128))\r\n # 将灰度条和裁剪后图合在一起\r\n new_image.paste(image, (dx, dy))\r\n image_data = np.array(new_image, np.float32)\r\n\r\n return image_data\r\n\r\n \"\"\"\r\n \r\n 计算机视觉方面,计算机视觉的主要问题是没有办法得到充足的数据。\r\n 对大多数机器学习应用,这不是问题,但是对计算机视觉,数据就远远不够。\r\n 所以这就意味着当你训练计算机视觉模型的时候,数据增强会有所帮助,这是可行的。\r\n \r\n 一般的数据增强方式:\r\n 1、对图像进行缩放并进行长和宽的扭曲\r\n 2、对图像进行翻转\r\n 3、对图像进行色域扭曲\r\n \r\n \"\"\"\r\n\r\n #------------------------------------------#\r\n # 对图像进行缩放并且进行长和宽的扭曲\r\n #------------------------------------------#\r\n\r\n # 调整图片大小\r\n new_ar = w/h * self.rand(1-jitter,1+jitter)/self.rand(1-jitter,1+jitter)\r\n scale = self.rand(1, 1.5)\r\n if new_ar < 1:\r\n nh = int(scale*h)\r\n nw = int(nh*new_ar)\r\n else:\r\n nw = int(scale*w)\r\n nh = int(nw/new_ar)\r\n image = image.resize((nw,nh), Image.BICUBIC)\r\n\r\n #------------------------------------------#\r\n # 将图像多余的部分加上灰条\r\n #------------------------------------------#\r\n # 放置图片\r\n\r\n \"\"\"\r\n \r\n 放置图片这一步其实还有一个叫法叫添加灰条,其目的是让所有的输入图片都是同样大小的正方形图片,\r\n 因为上面的图片是做个缩放的,所以大小不能确定,大小不够的就需要添加灰条,\r\n 这里就可以简单理解为放了一张正方形白纸在那里,你可以在纸上随便画你想要的东西,填不满的就保留白纸,\r\n 最终训练的时候也是将这张白纸直接输入,这样就能实现输入图像都是一样大的,但是图内物体的大小却不同。\r\n \r\n \"\"\"\r\n\r\n dx = int(self.rand(0, w-nw))\r\n dy = int(self.rand(0, h-nh))\r\n new_image = Image.new('RGB', (w,h), (128,128,128))\r\n new_image.paste(image, (dx, dy))\r\n image = new_image\r\n\r\n #------------------------------------------#\r\n # 翻转图像\r\n #------------------------------------------#\r\n flip = self.rand()<.5\r\n if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)\r\n \r\n rotate = self.rand()<.5\r\n if rotate: \r\n angle = np.random.randint(-15,15)\r\n a,b = w/2,h/2\r\n M = cv2.getRotationMatrix2D((a,b),angle,1)\r\n image = cv2.warpAffine(np.array(image), M, (w,h), borderValue=[128,128,128]) \r\n\r\n #------------------------------------------#\r\n # 色域扭曲\r\n #------------------------------------------#\r\n hue = self.rand(-hue, hue)\r\n sat = self.rand(1, sat) if self.rand()<.5 else 1/self.rand(1, sat)\r\n val = self.rand(1, val) if self.rand()<.5 else 1/self.rand(1, val)\r\n x = cv2.cvtColor(np.array(image,np.float32)/255, cv2.COLOR_RGB2HSV)\r\n x[..., 1] *= sat\r\n x[..., 2] *= val\r\n x[x[:,:, 0]>360, 0] = 360\r\n x[:, :, 1:][x[:, :, 1:]>1] = 1\r\n x[x<0] = 0\r\n image_data = cv2.cvtColor(x, cv2.COLOR_HSV2RGB)*255\r\n return Image.fromarray(np.uint8(image_data))\r\n\r\n def random_crop(self, image, width, height):\r\n #--------------------------------------------#\r\n # 如果图像过小无法截取,先对图像进行放大\r\n #--------------------------------------------#\r\n if image.size[0] < self.hr_shape[1] or image.size[1] < self.hr_shape[0]:\r\n resized_width, resized_height = get_new_img_size(width, height, img_min_side=np.max(self.hr_shape))\r\n image = image.resize((resized_width, resized_height), Image.BICUBIC)\r\n\r\n #--------------------------------------------#\r\n # 随机截取一部分\r\n #--------------------------------------------#\r\n width1 = randint(0, image.size[0] - width)\r\n height1 = randint(0, image.size[1] - height)\r\n\r\n width2 = width1 + width\r\n height2 = height1 + height\r\n\r\n image = image.crop((width1, height1, width2, height2))\r\n return image\r\n \r\ndef SRGAN_dataset_collate(batch):\r\n images_l = []\r\n images_h = []\r\n for img_l, img_h in batch:\r\n images_l.append(img_l)\r\n images_h.append(img_h)\r\n return np.array(images_l), np.array(images_h)\r\n","repo_name":"CaiMingQiang/CMQQ_SRGAN","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":8798,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"22687505109","text":"s = 'sim'\nsoma = cont = med = maior = menor = 0\nwhile s in 'sim':\n num = int(input('Digite um num: '))\n s = str(input('Deseja Continuar Sim ou Nao: ')).strip().lower()\n if s != 'sim' and s != 'nao':\n s = str(input('''Digitou comando incorreto, digite novamente!\n Deseja Continuar Sim ou Nao: ''')).strip().lower()\n soma += num\n cont += 1\n if cont == 1:\n maior = menor = num\n elif cont != 1:\n if num >= maior:\n maior = num\n elif num <= menor:\n menor = num\nmed = soma/cont\nprint('Vc digitou {} numeros e a media e {}, o maior entre eles e {} e o menor entre eles {}'.format(cont,med,maior,menor))","repo_name":"marcelucasales/Treinamento-para-o-curso-de-extensao-de-python","sub_path":"py_c++/24.py","file_name":"24.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"70661096257","text":"from typing import List, NamedTuple, Tuple\nfrom unittest.util import _MAX_LENGTH\n\nW = 7\nRock = NamedTuple(\"Rock\", [(\"width\", int), (\"bitmap\", List[int])])\nPos = NamedTuple(\"Pos\", [(\"x\", int), (\"y\", int)])\n\nROCKS = [Rock(4, [15]), Rock(3, [2, 7, 2]), Rock(3, [7, 4, 4]), Rock(1, [1, 1, 1, 1]), Rock(2, [3, 3])]\nMAX_LEN = 500\n\n\nclass Chamber:\n def __init__(self, jet: str) -> None:\n self.jet = jet\n self.chamber: List[int] = [] # list of bitmaps\n self.jet_index: int = 0\n self.rock_index: int = 0\n self.clipped: int = 0\n\n def drop_next_rock(self) -> None:\n pos: Pos = Pos(2, 3 + len(self.chamber))\n rock = ROCKS[self.rock_index]\n self.rock_index = (self.rock_index + 1) % len(ROCKS)\n while True:\n # Jet push\n dir: int = 1 if self.jet[self.jet_index] == \">\" else -1\n self.jet_index = (self.jet_index + 1) % len(self.jet)\n if pos.x + dir >= 0 and pos.x + dir + rock.width <= W:\n next_pos = Pos(pos.x + dir, pos.y)\n if self._fits(next_pos, rock):\n pos = next_pos\n # Fall 1 down\n next_pos = Pos(pos.x, pos.y - 1)\n if self._fits(next_pos, rock):\n pos = next_pos\n else:\n self._drop(pos, rock)\n return\n\n def clip(self) -> None:\n \"\"\"Keeps the chamber small\"\"\"\n l = len(self.chamber)\n if l > MAX_LEN:\n self.clipped += l - MAX_LEN\n self.chamber = self.chamber[-MAX_LEN:]\n\n def height(self) -> int:\n return len(self.chamber) + self.clipped\n\n def _fits(self, pos: Pos, rock: Rock) -> bool:\n if pos.y < 0:\n return False\n for y in range(len(rock.bitmap)):\n if pos.y + y >= len(self.chamber):\n return True\n if self.chamber[pos.y + y] & (rock.bitmap[y] << pos.x) != 0:\n return False\n return True\n\n def _drop(self, pos: Pos, rock: Rock) -> None:\n for y in range(len(rock.bitmap)):\n if pos.y + y >= len(self.chamber):\n self.chamber.append(0)\n self.chamber[pos.y + y] += rock.bitmap[y] << pos.x\n\n def draw(self):\n for y in range(len(self.chamber) - 1, len(self.chamber) - 10, -1):\n print(\"{:07b}\".format(self.chamber[y])[::-1].replace(\"0\", \".\"))\n print(\"Height:\", self.height())\n\n\njet = open(\"17_input.txt\", \"r\").read().strip()\n\n\ndef part1():\n chamber = Chamber(jet)\n for _ in range(2022):\n chamber.drop_next_rock()\n print(\"Part 1:\", chamber.height())\n\n\ndef part2():\n N = 1000000000000\n\n chamber = Chamber(jet)\n key0 = None\n height0 = 0\n period0 = len(jet) * len(ROCKS)\n for i in range(N):\n for _ in range(period0):\n chamber.drop_next_rock()\n chamber.clip()\n curr_height = chamber.height()\n key = tuple(chamber.chamber[-1 - a] for a in range(30))\n print(\"Iteration\", i, \" -> \", period0 * (i + 1), \"rocks, height:\", chamber.height())\n if i == 0:\n key0 = key\n height0 = curr_height\n elif key == key0:\n print(\"Periodicity found! height0:\", height0, \"curr height\", curr_height)\n height_delta = curr_height - height0\n rounds_left = (N - period0) % (i * period0)\n big_periods_left = (N - period0) // (i * period0) - 1\n print(\"Left rounds: \", rounds_left)\n for _ in range(rounds_left):\n chamber.drop_next_rock()\n chamber.clip()\n chamber.draw()\n print(\"Part 2:\", chamber.height() + big_periods_left * height_delta)\n break\n\n\npart1()\npart2()\n","repo_name":"eiisolver/adventofcode2022","sub_path":"17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"28734412596","text":"import cv2\n\n\ndef preprocess_image(image):\n # Resize the image\n new_weight = 240\n new_height = 80\n\n # Convert the image to grayscale\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n ret, candidate_bw = cv2.threshold(\n gray_image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\n resized_image = cv2.resize(candidate_bw, (new_weight, new_height))\n\n # Reshape the image to match the input shape of the model\n preprocessed_image = resized_image.reshape(-1, new_height, new_weight, 1)\n\n return preprocessed_image\n","repo_name":"Ahasanhossen/BD-HDR","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"72246521216","text":"# Write your solution here\ndef squared(str1, num):\n\tx = 0\n\ty = 0\n\trow = 0\n\tw_len = len(str1)\n\ti = 0\n\twhile row < num:\n\t\tx = 0\n\t\twhile x < num:\n\t\t\tprint(f\"{str1[i]}\", end= '')\n\t\t\ti += 1\n\t\t\tif i == w_len:\n\t\t\t\ti = 0\n\t\t\tx += 1\n\t\trow += 1\n\t\tprint()\n\nif __name__ == \"__main__\":\n\tsquared(\"ab\", 5)","repo_name":"azajay08/MOOC_Introduction-Advanced_Programming_in_Python","sub_path":"Intro/part03/word_squared.py","file_name":"word_squared.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"25908433191","text":"#!/usr/bin/env python3\n\n# Usage:\n#\n# ./$0 path-to-nessus.xml\n# \n# This emits the paths, and hosts, for log4j findings, as CSV. Getting \n# the final output of responsible users is a few more steps.\n# \n# At that point I suggest you take the output, and paste it into a google sheet\n# then copy all the instance guids, and be ready to paste them into a file\n# called `instance_guids` on a deigo cell:\n# \n# Then, on a diego cell, run the following to echo as more CSV the\n# instance_guid and the app_guid.\n# \n# cat instance_guids | while read i; do\n# if ( echo $i | grep -q -- - ); then\n# jqcmd=\"jq '.LRPs[] | select (.instance_guid == \\\"$i\\\") | .process_guid'\"\n# echo -n \"\\\"$i\\\", \"\n# cfdot cell-states | eval $jqcmd | cut -c1-36\n# else\n# echo \"\\\"$i\\\", \\\"-\\\"\"\n# fi\n# done\n#\n# Now, paste all your app_guids, one per line, into another file, and set up\n# to run the report with:\n# \n# pip3 install cloudfoundry-client\n# cf login --sso\n# cloudfoundry-client import_from_cf_cli`\n#\n# Finally:\n# ./log4j-report-users.py\n#\n# DO NOT email the list of vulns directly to customer. Determine what medium\n# they want to use for vuln reports.\n#\n# - Peter Burkholder\n# \n\n\n\nimport nessus_file_reader as nfr\nimport sys\nimport re\nimport csv\nfrom collections import defaultdict\n\nfrom datetime import date\ntoday = date.today()\nmmddYY = today.strftime(\"%m/%d/%Y\")\n\nif len(sys.argv) == 1:\n print('please provide a path to an XML ZAP report')\n sys.exit(-1)\n \nnessus_scan_file = sys.argv[1]\n\nroot = nfr.file.nessus_scan_file_root_element(nessus_scan_file)\n\nl4j_plugins = [ 155999, 156032, 156057, 156103, 156183, 156860, 156327 ]\npath_report = {}\n\nfor report_host in nfr.scan.report_hosts(root):\n report_host_name = nfr.host.report_host_name(report_host)\n for report_item in nfr.host.report_items(report_host):\n plugin_id = int(nfr.plugin.report_item_value(report_item, 'pluginID'))\n plugin_output = nfr.plugin.report_item_value(report_item, 'plugin_output')\n\n if plugin_id in l4j_plugins:\n for line in plugin_output.splitlines():\n m = re.match(r'^ Path\\s+: (\\/.*)', line)\n if m:\n path = m.group(1)\n path_info = path_report.get(path, defaultdict(list))\n if plugin_id not in path_info[\"plugins\"]:\n path_info[\"plugins\"].append(plugin_id)\n if report_host_name not in path_info[\"hosts\"]:\n path_info[\"hosts\"].append(report_host_name)\n path_report[path] = path_info\n\n\n# Path\tNode 0\tInstance GUID\tCustomer Path Name\tPlugin Ids\tApp GUID\tApp Name\tSpace Name\tOrg Name\tOrg Manager\tSpace Developers\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\ncsvwriter = csv.writer(sys.stdout,quoting=csv.QUOTE_ALL)\ncsvwriter.writerow([\"Path\",\"Node_0\",\"Instance_GUID\",\"Customer_Path\",\"Plugin_URLS\",\"App_GUID\",\"App_Name\",\"Space_Name\",\"Org_Name\",\"Org_Managers\",\"Space_Devs\"])\nfor p in sorted(path_report):\n if re.match(r'/var/vcap/data/grootfs', p ):\n m = re.match(r'/var/vcap/data/grootfs/store/unprivileged/(images|volumes)/([^/]+)/(diff|root)?/?(fs)?(.*)$', p)\n instance_guid = m.group(2)\n customer_path = m.group(5)\n urls = \"\"\n for plugin_id in sorted(path_report[p][\"plugins\"]):\n urls += \"https://www.tenable.com/plugins/nessus/{} \".format(plugin_id)\n \n csvwriter.writerow(\n [ p, \n sorted(path_report[p][\"hosts\"])[0],\n instance_guid,\n f\"/{customer_path}\",\n urls,\n ])\n","repo_name":"cloud-gov/cg-scripts","sub_path":"audit/log4j-nessus-parser.py","file_name":"log4j-nessus-parser.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"79"} +{"seq_id":"2349509941","text":"import torch\nfrom torch import nn\n\nimport string\nimport numpy as np\n\nimport keras \nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Model\nfrom keras.layers import LSTM, Input, TimeDistributed, Dense, Activation, RepeatVector, Embedding\nfrom keras.optimizers import Adam\nfrom keras.losses import sparse_categorical_crossentropy\n\n\ndef clean_sentence(sentence):\n # Lower case the sentence\n lower_case_sent = sentence.lower()\n # Strip punctuation\n string_punctuation = string.punctuation + \"¡\" + '¿'\n clean_sentence = lower_case_sent.translate(str.maketrans('', '', string_punctuation))\n \n return clean_sentence\n\ndef tokenize(sentences):\n # Create tokenizer\n text_tokenizer = Tokenizer()\n # Fit texts\n text_tokenizer.fit_on_texts(sentences)\n return text_tokenizer.texts_to_sequences(sentences), text_tokenizer\n\ndef read_inflection_data(inf_file):\n f = open(inf_file)\n inf_features = []\n vocab = []\n sent = []\n word_indices = []\n for line in f:\n if len(line.strip()) > 0:\n fields = line.split(\"\\t\")\n \n # fields = line.split()\n\n word = fields[0]\n if word not in vocab:\n vocab.append(word)\n\n feat = \" \".join(fields[1: -1])\n feat = feat.split(\";\")\n feat.insert(0,word)\n inf_features.append(feat)\n sent.append(fields[-1])\n rep = []\n for s in sent:\n rep.append(s.replace(\"\\n\", \"\"))\n sent = rep\n\n word_indices.append(vocab.index(word))\n\n f.close()\n\n sentences = [clean_sentence(pair) for pair in sent]\n \n return (inf_features,vocab,sentences,word_indices)\n\n # print(sent)\n\n\n\n\n\ninf_features,vocab,sentences,word_indices = read_inflection_data(\"/inf/eng.trn\")\n\n# print(sentences)\n\nsent_tokenized, sent_tokenizer = tokenize(sentences)\nmax_sent_len = int(len(max(sent_tokenized,key=len)))\n\n# inf_features = torch.FloatTensor(inf_features)\n# # print(inf_features)\n\n# emb_dim = len(word_indices)\n# hidden_dim = 300\n# encoder = Encoder(len(vocab), emb_dim, hidden_dim)\n\n# initial_state = encoder.init_states(1)\n\n# output, hidden_state = encoder.forward(inf_features, initial_state)\n\n# print(output)\n\n\n\ninput_sequence = Input(shape=(len(inf_features[0]),))\nembedding = Embedding(input_dim=len(vocab), output_dim=128,)(input_sequence)\nencoder = LSTM(64, return_sequences=False)(embedding)\n\ninput_sequence = Input(shape=(len(inf_features[0]),))\nembedding = Embedding(input_dim=len(vocab), output_dim=128,)(input_sequence)\nencoder = LSTM(64, return_sequences=False)(embedding)\nr_vec = RepeatVector(max_sent_len)(encoder)\ndecoder = LSTM(64, return_sequences=True, dropout=0.2)(r_vec)\nlogits = TimeDistributed(Dense(vocab))(decoder)\n\n\nenc_dec_model = Model(input_sequence, Activation('softmax')(logits))\nenc_dec_model.compile(loss=sparse_categorical_crossentropy,\n optimizer=Adam(1e-3),\n metrics=['accuracy'])\nenc_dec_model.summary()\n\n\nmodel_results = enc_dec_model.fit(inf_features, sentences, batch_size=30, epochs=100)\n\ndef logits_to_sentence(logits, tokenizer):\n\n index_to_words = {idx: word for word, idx in tokenizer.word_index.items()}\n index_to_words[0] = '' \n\n return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)])\n\nindex = 14\nprint(\"The english sentence is: {}\".format(sentences[index]))\nprint(\"The spanish sentence is: {}\".format(inf_features[index]))\nprint('The predicted sentence is :')\nprint(logits_to_sentence(enc_dec_model.predict(inf_features[index:index+1])[0], sent_tokenizer))\n\n","repo_name":"sidballack13/multilingual-clause-level-morphology","sub_path":"new folder/inflection.py","file_name":"inflection.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"10111983847","text":"def solution(sizes):\n answer = 0\n tmp1 = []\n tmp2 = []\n\n for i in range(len(sizes)):\n tmp1.append(max(sizes[i]))\n\n for i in range(len(sizes)):\n tmp2.append(min(sizes[i]))\n\n answer = max(tmp1) * max(tmp2)\n return answer","repo_name":"hallu0317/Python_Study","sub_path":"Programmers/Lv1/최소직사각형.py","file_name":"최소직사각형.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"75028494656","text":"#https://www.acmicpc.net/problem/2193\n#If you draw tree structure, you can find recurrence relation\nn = int(input())\ndp = [0 for _ in range(n)]\ndp[0] = 1\nif n >= 2:\n dp[1] = 1\n for i in range(2,n):\n dp[i] = dp[i-1] + dp[i-2]\nprint(dp[n-1])\n","repo_name":"DevJIYUL/AlgorithmStudy","sub_path":"Codeup/DP/pinary_number.py","file_name":"pinary_number.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"6099622793","text":"file = open('input.txt', 'r')\n\nline = file.read().strip()[13:]\nx,y = line.split(', ')\nmin_x, max_x = [int(val) for val in x[2:].split('..')]\nmin_y, max_y = [int(val) for val in y[2:].split('..')]\n\nresult = 0\nfor v_x in range(-500, 500):\n for v_y in range(500):\n x,y = (0,0)\n highest_y = 0\n found = False\n dx = v_x\n dy = v_y\n for _ in range(200):\n x += dx\n y += dy\n highest_y = max(highest_y, y)\n if min_x <= x <= max_x and min_y <= y <= max_y:\n found = True\n dx += -1 if dx > 0 else 1 if dx < 0 else 0\n dy -= 1\n if found:\n result = max(result, highest_y)\nprint(result)\nfile.close()","repo_name":"dolatapatryk/advent-of-code-2021","sub_path":"day17/day17_1.py","file_name":"day17_1.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"28584052353","text":"\"\"\"\n给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def removeElements(self, head: ListNode, val: int) -> ListNode:\n dummy_head = ListNode(0)\n dummy_head.next, p = head, dummy_head\n while p.next:\n # 当前节点 不符合删除条件。\n if p.next.val != val:\n p = p.next\n # 当前节点 满足删除条件。\n else:\n p.next = p.next.next\n\n return dummy_head.next\n\n\nhead = ListNode(2)\np1 = ListNode(2)\nhead.next = p1\nss = Solution()\nss.removeElements(head, 2)","repo_name":"zcPasser/leetcode_python","sub_path":"first_leetcode/py203_remove-linked-list-elements.py","file_name":"py203_remove-linked-list-elements.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"16439052220","text":"import mysql.connector\nfrom faker import Faker\nfake_data = Faker()\n\nadapter = mysql.connector.connect(user= \"root\", password= \"testing123\", database=\"practice_sql_db\")\nclient = adapter.cursor()\n\nclass Product:\n\n def __init__(self):\n self.id = None\n self.product_name = fake_data.random_elements(elements=(\"flour\",\"sugar\", \"shirts\",\n \"TV\",\"mobile\",\"books\", \"coat\",\"jeans\",\"dresses\",\"hard disk\"\n \"table\", \"chair\",\"bottle\",\"cosmetics\"), length=1, unique=True)\n self.category = self.product_name\n self.quantity = fake_data.random_digit_not_null()\n self.title = fake_data.lexify(text='???? ????? ???? ???',\n letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n self.product_description = fake_data.lexify(text='???? ????? ???? ???', \n letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')\n self.price = fake_data.random_digit_not_null()\n\n def save(self):\n sql_form = \"INSERT INTO \\\n product \\\n (\\\n product_name, category, quantity, title,product_description, price \\\n )\\\n VALUES \\\n (%s, %s, %s, %s, %s, %s)\"\n client.execute(sql_form, \n [\n self.product_name[0], self.category[0], self.quantity, \n self.title, self.product_description , self.price\n ])\n adapter.commit()\n\n @classmethod\n def random(cls):\n client.execute(\"Select * from product ORDER BY RAND() limit 1\")\n result = client.fetchone()\n # print(result)\n columns = client.column_names\n product_object = {}\n for i in range(0, len(columns)):\n product_object[columns[i]] = result[i] \n return product_object\n\n @classmethod\n def last(cls):\n client.execute(\"Select * from product order by id desc limit 1\")\n result = client.fetchone()\n columns = client.column_names\n product_object = {}\n for i in range(0, len(columns)):\n product_object[columns[i]] = result[i] \n return product_object\n\n\n\n\n\n# for i in range(0, 2000):\n# product = Product() \n# product.save()\n\n\n# product1 = Product.random_product()\n# print(product1)\n\n\n\n","repo_name":"vandanagarg/sql_practice","sub_path":"many_to_many_relationship/ecommerce_db/python_code/Product.py","file_name":"Product.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"1805788305","text":"\"\"\"Utilities for views.\"\"\"\nfrom .exception import FlexToolException\nfrom .models import Project, ScenarioExecution\nfrom .utils import get_and_validate\n\n\ndef resolve_project(request, body):\n \"\"\"Resolves target project according to client request.\n\n Args:\n request (HttpRequest): request object\n body (dict): request body\n\n Returns:\n Project: target project\n \"\"\"\n project_id = get_and_validate(body, \"projectId\", int)\n try:\n # pylint: disable=no-member\n project = Project.objects.get(id=project_id, user=request.user.id)\n except Project.DoesNotExist as error: # pylint: disable=no-member\n raise FlexToolException(\"Project does not exist.\") from error\n return project\n\n\ndef resolve_scenario_execution(project, body_or_id):\n \"\"\"Resolves scenario execution.\n\n Args:\n project (Project): a project\n body_or_id (dict or int): request body or scenario execution id\n\n Returns:\n ScenarioExecution: scenario execution\n \"\"\"\n if not isinstance(body_or_id, int):\n scenario_execution_id = get_and_validate(body_or_id, \"scenarioExecutionId\", int)\n else:\n scenario_execution_id = body_or_id\n try:\n # pylint: disable=no-member\n scenario_execution = ScenarioExecution.objects.get(id=scenario_execution_id)\n except ScenarioExecution.DoesNotExist as error: # pylint: disable=no-member\n raise FlexToolException(\n f\"Scenario execution with id {scenario_execution_id} doesn't exist.\"\n ) from error\n if scenario_execution.scenario.project.id != project.id:\n raise FlexToolException(\n f\"Scenario execution with id {scenario_execution_id} doesn't exist.\"\n )\n return scenario_execution\n","repo_name":"irena-flextool/flextool-web-interface","sub_path":"flextool3/view_utils.py","file_name":"view_utils.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"71057052096","text":"import requests\nimport credential\nfrom datetime import datetime\nimport json\n\nexercise_url: str = \"https://trackapi.nutritionix.com/v2/natural/exercise\"\ngoogle_sheet_url: str = \"https://api.sheety.co/b3e23f917dcbc032b319d52cb90c0b39/myWorkoutData/workouts\"\n\nGENDER = \"male\"\nWEIGHT_KG = \"77\"\nHEIGHT_CM = \"181\"\nAGE = \"30\"\n\nexercise_input: str = input(\"Tell which exercise you did today? \")\n\n# Authentication data, so API gives user access.\nheaders = {\n \"x-app-id\": credential.API_ID,\n \"x-app-key\": credential.API_KEY,\n \"Content-Type\": \"application/json\"\n}\n\n# Data to be uploaded to API base\nparameters = {\n 'query': exercise_input,\n \"gender\": GENDER,\n \"weight_kg\": WEIGHT_KG,\n \"height_cm\": HEIGHT_CM,\n \"age\": AGE,\n}\n\nresponse = requests.post(exercise_url, json=parameters, headers=headers)\nresult = response.json()\nwith open(\"text.json\", \"w\") as f:\n json.dump(result, f, indent=4)\n\ntoday_date = datetime.now().strftime(\"%Y/%m/%d\")\ncurrent_time = datetime.now().strftime(\"%X\")\n\nfor content in result[\"exercises\"]:\n sheet_content = {\n \"workout\": {\n \"date\": today_date,\n \"time\": current_time,\n \"exercise\": content[\"name\"].title(),\n \"duration\": content[\"duration_min\"],\n \"calories\": content[\"nf_calories\"]\n\n }\n }\n # Basic Authorization for sheety\n headers = {\n \"Authorization\": \"Basic RG9sYW11OlBva2FodW50ZXJAOQ==\"\n }\n\n sheet_response = requests.post(google_sheet_url, json=sheet_content, headers=headers)\n print(sheet_response.text)\n","repo_name":"Dolamu-TheDataGuy/Py_Codes","sub_path":"Workout_Tracker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"34439125282","text":"import numpy as np\nimport cv2\n\ncap = cv2.VideoCapture(0)\n\nfourcc = cv2.VideoWriter_fourcc(*'DIVX')\nout = cv2.VideoWriter('output.avi',fourcc, 30.0, (640,480))\n\nwhile(cap.isOpened()):\n flag, cadre = cap.read()\n out.write(cadre)\n cv2.imshow('cadre',cadre)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncv2.destroyWindow('cadre')\ncap = cv2.VideoCapture('output.avi')\n\nwhile(cap.isOpened()):\n \n flag, cadre = cap.read()\n if flag:\n gray = cv2.cvtColor(cadre, cv2.COLOR_BGR2GRAY)\n gray = cv2.cvtColor(gray,cv2.COLOR_GRAY2BGR)\n cv2.rectangle(gray,(200,100),(400,200),(0,255,0),3)\n cv2.line(gray,(0,0),(640,300),(100,10,200),5)\n\n cv2.imshow('gray',gray)\n cv2.waitKey(44)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n\ncap.release()\nout.release()\ncv2.destroyAllWindows()","repo_name":"ArgentumPWNZ/CV_l","sub_path":"CV_lab0.py","file_name":"CV_lab0.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"1353470185","text":"from osgeo import gdal, ogr\n\nfrom tathu.constants import KM_PER_DEGREE\n\ndef copyImage(image):\n driver = gdal.GetDriverByName('MEM')\n return driver.CreateCopy('image', image, 0)\n\ndef polygonize(image, minArea=None, progress=None):\n # Create layer in memory\n driver = ogr.GetDriverByName('MEMORY')\n ds = driver.CreateDataSource('systems')\n layer = ds.CreateLayer('geom', srs=None)\n\n # Get first band\n band = image.GetRasterBand(1)\n\n # Poligonize using GDAL method\n gdal.Polygonize(band, band.GetMaskBand(), layer, -1, options=['8CONNECTED=8'], callback=progress)\n\n polygons = []\n\n for feature in layer:\n # Get polygon representation (detail: using Buffer(0) to fix self-intersections)\n p = feature.GetGeometryRef().Buffer(0)\n # Verify minimum area\n if minArea is None:\n polygons.append(p)\n elif p.GetArea() > minArea:\n polygons.append(p)\n\n return polygons\n\ndef area2degrees(km2):\n return km2/(KM_PER_DEGREE * KM_PER_DEGREE)\n","repo_name":"uba/tathu","sub_path":"tathu/tracking/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"79"} +{"seq_id":"17619214402","text":"import argparse\nimport os.path\nimport sys\n\n\n# Get genes with TSS for hg19 used by GREAT 3.0:\n# Website: http://bejerano.stanford.edu/help/display/GREAT/Genes\n# Download command:\n# wget -O data/hregulatory_domains/g19.great3.0.genes.txt 'http://bejerano.stanford.edu/help/download/attachments/2752609/hg19.great3.0.genes.txt?version=1&modificationDate=1443465966000&api=v2'\ndefault_genes_tss_filename = os.path.join(os.path.dirname(__file__),\n 'data',\n 'regulatory_domains',\n 'hg19.great3.0.genes.txt')\ndefault_chrom_sizes_filename = os.path.join(os.path.dirname(__file__),\n 'data',\n 'genomic_fasta',\n 'hg19.chrom.sizes')\ndefault_assembly = 'hg19'\n\ndefault_maximum_extension = 1000000\ndefault_basal_up = 5000\ndefault_basal_down = 1000\n\n\nclass ChromSizes:\n \"\"\"\n Set and get chromosome lengths.\n \"\"\"\n\n def __init__(self, chrom_sizes_dict):\n \"\"\"\n Define chromosome sizes.\n\n :param chrom_sizes_dict: dictionary with chromosome names as key and chromosome lengths as values.\n\n :return: ChromSizes object\n \"\"\"\n self.chrom_sizes_dict = chrom_sizes_dict\n\n @staticmethod\n def load_chrom_sizes_file(chrom_sizes_filename):\n \"\"\"\n Create a ChromSizes object by reading chromosome sizes from a chromosome sizes file.\n\n Example of a chromosome sizes file:\n # Chromosome name Chromosome length\n chr1 249250621\n chr2 243199373\n chr3 198022430\n chr4 191154276\n chr5 180915260\n \"\"\"\n chrom_sizes_dict = dict()\n\n with open(chrom_sizes_filename, 'r') as fh:\n for line in fh:\n if line.startswith('#'):\n continue\n\n columns = line.rstrip('\\n').split()\n if len(columns) == 2:\n # Save chromosome name and chromosome size in dictionary.\n chrom_sizes_dict[columns[0]] = int(columns[1])\n\n return ChromSizes(chrom_sizes_dict)\n\n def get_chrom_size_for_chrom(self, chrom):\n \"\"\"\n Get chromosome length for specified chromosome name.\n\n :param chrom: chromosome name for which you want to know the length.\n\n :return: chromosome length (or None if chromosome name was not found).\n \"\"\"\n return self.chrom_sizes_dict.get(chrom, None)\n\n\nclass GeneTSS:\n \"\"\"\n Create a GeneTSS object.\n \"\"\"\n\n def __init__(self, chrom, tss, strand, name):\n \"\"\"\n Create a GeneTSS object.\n\n :param chrom: chromosome name\n :param tss: TSS\n :param strand: strand\n :param name: gene name\n\n :return: GeneTSS object\n \"\"\"\n self.chrom = chrom\n self.tss = int(tss)\n self.strand = strand\n self.name = name\n\n def __lt__(self, other):\n \"\"\"\n When sorting different GeneTSS objects, sort them by:\n - chromosome name\n - TSS\n - strand\n - gene name\n \"\"\"\n if self.chrom == other.chrom:\n # It the chromosome is the same, check the TSS.\n if self.tss == other.tss:\n # If the TSS is the same check the strand.\n if self.strand == other.strand:\n # If the stand is the same, check the gene name.\n return self.name < other.name\n elif self.strand == '+':\n # If the strand was different, take the one with the positive strand first.\n return True\n else:\n return False\n else:\n # If the TSS is different, take the smallest one first.\n return self.tss < other.tss\n else:\n # If the chromosome name is not the same, check which one is comes first.\n return self.chrom < other.chrom\n\n\nclass GenesTSSList:\n \"\"\"\n Create a list of GeneTSS objects sorted by chromosome name, TSS, strand and gene name.\n \"\"\"\n\n def __init__(self, genes_tss_list):\n \"\"\"\n Create a list of GeneTSS objects sorted by chromosome name, TSS, strand and gene name.\n\n :param genes_tss_list: list of GeneTSS objects.\n\n :return: sorted (by chromosome, TSS, strand and gene name.) list of GeneTSS objects.\n \"\"\"\n self.genes_tss_list = sorted(genes_tss_list)\n\n @staticmethod\n def load_genes_tss_file(genes_tss_filename):\n \"\"\"\n Create a list of GeneTSS objects sorted by chromosome name, TSS, strand and gene name\n from a TAB-separated file in one of the following formats:\n - Chromosome name, TSS, strand, gene name.\n - ENSEMBL gene ID, chromosome name, TSS, strand, gene name.\n\n :param genes_tss_filename: Filename with TSS info for each gene.\n\n :return: GenesTSSList object which contains a sorted list of GeneTSS objects\n by chromosome name, TSS, strand and gene name.\n \"\"\"\n genes_tss_list = list()\n\n with sys.stdin if genes_tss_filename in ('-', 'stdin') else open(genes_tss_filename, 'r') as fh:\n for line in fh:\n if line.startswith('#'):\n continue\n\n columns = line.rstrip('\\n').split('\\t')\n if len(columns) == 4:\n # Chromosome name, TSS, strand, gene name.\n genes_tss_list.append(GeneTSS(columns[0], columns[1], columns[2], columns[3]))\n elif len(columns) == 5:\n # ENSEMBL gene ID, chromosome name, TSS, strand, gene name.\n genes_tss_list.append(GeneTSS(columns[1], columns[2], columns[3], columns[4]))\n\n return GenesTSSList(genes_tss_list)\n\n def __iter__(self):\n return self.genes_tss_list.__iter__()\n\n\nclass RegDom:\n \"\"\"\n Create a regulatory domain.\n \"\"\"\n\n def __init__(self, chrom, chrom_start, chrom_end, name, tss, strand, basal_up, basal_down, chrom_sizes):\n \"\"\"\n Create a regulatory domain.\n\n :param chrom: chromosome name\n :param chrom_start: chromosome start\n :param chrom_end: chromosome end\n :param name: gene name\n :param tss: TSS\n :param strand: strand\n :param basal_up: number of bases upstream of TSS to create a basal domain region.\n :param basal_down: number of bases downstream of TSS to create a basal domain region.\n :param chrom_sizes: ChromSizes object with chromosome lengths for each chromosome\n\n :return: regulatory domain object with:\n - chrom: chromosome name on which the regulatory domain is located\n - chrom_start: regulatory domain start\n - chrom_end: regulatory domain end\n - name: gene name\n - tss: TSS\n - strand: strand\n - basal_start: start of basal domain region\n - basal_end: end of basal domain region\n\n If basal_up and basal_down are both None:\n - basal_start = chrom_start\n - basal_end = chrom_end.\n This is useful when creating a RegDom for a curated regulatory domain.\n\n If chrom_start and chrom_end are both None:\n - chrom_start = basal_start\n - chrom_end = basal_end.\n This is useful when creating a RegDom for genes for which you want to\n create a basal domain based on TSS and basal_up and basal_down values.\n \"\"\"\n self.chrom = chrom\n self.chrom_start = chrom_start\n self.chrom_end = chrom_end\n self.name = name\n self.tss = tss\n self.strand = strand\n\n if basal_up and basal_down:\n if self.strand == '+':\n self.basal_start = max(0, self.tss - basal_up)\n self.basal_end = min(chrom_sizes.get_chrom_size_for_chrom(self.chrom), self.tss + basal_down)\n elif self.strand == '-':\n self.basal_start = max(0, self.tss - basal_down)\n self.basal_end = min(chrom_sizes.get_chrom_size_for_chrom(self.chrom), self.tss + basal_up)\n\n if self.chrom_start is None:\n self.chrom_start = self.basal_start\n\n if self.chrom_end is None:\n self.chrom_end = self.basal_end\n elif self.chrom_start and self.chrom_end:\n self.basal_start = self.chrom_start\n self.basal_end = self.chrom_end\n\n def __str__(self):\n return '{0:s}\\t{1:d}\\t{2:d}\\t{3:s}\\t{4:d}\\t{5:s}\\t{6:d}\\t{7:d}'.format(\n self.chrom,\n self.chrom_start,\n self.chrom_end,\n self.name,\n self.tss,\n self.strand,\n self.basal_start,\n self.basal_end)\n\n\nclass CuratedRegDoms:\n \"\"\"\n List of curated regulatory domains.\n \"\"\"\n\n def __init__(self, chrom_sizes, assembly):\n self.curated_reg_doms_dict = dict()\n self.chrom_sizes = chrom_sizes\n self.assembly = assembly\n\n if assembly == 'hg19':\n self._add_curated_reg_doms_hg19()\n elif assembly == 'hg38':\n self._add_curated_reg_doms_hg38()\n\n def _add_curated_reg_doms_hg19(self):\n \"\"\"\n Add list of curated regulatory domains for hg19:\n http://bejerano.stanford.edu/help/display/GREAT/Association+Rules#AssociationRules-CuratedRegulatoryDomains\n\n Sonic hedgehog long-range enhancer:\n SHH: chr7:155438203-156584569\n\n HOXD global control region:\n KIAA1715 (= LNP): chr2:176714855-176947690\n EVX2: chr2:176714855-176953690\n HOXD13: chr2:176714855-176959529\n HOXD12: chr2:176714855-176967083\n HOXD11: chr2:176714855-176976491\n HOXD10: chr2:176714855-176982491\n\n Beta-globin locus control region:\n HBB: chr11:5226931-5314124\n HBD: chr11:5253302-5314124\n HBG1: chr11:5260859-5314124\n HBE1: chr11:5276088-5314124\n \"\"\"\n\n # Sonic hedgehog long-range enhancer.\n self.curated_reg_doms_dict['SHH'] = RegDom(\n chrom='chr7',\n chrom_start=155438203,\n chrom_end=156584569,\n name='SHH',\n tss=155604967,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n\n # HOXD global control region.\n self.curated_reg_doms_dict['KIAA1715'] = RegDom(\n chrom='chr2',\n chrom_start=176714855,\n chrom_end=176947690,\n name='KIAA1715',\n tss=176867073,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['EVX2'] = RegDom(\n chrom='chr2',\n chrom_start=176714855,\n chrom_end=176953690,\n name='EVX2',\n tss=176948641,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD13'] = RegDom(\n chrom='chr2',\n chrom_start=176714855,\n chrom_end=176959529,\n name='HOXD13',\n tss=176957618,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD12'] = RegDom(\n chrom='chr2',\n chrom_start=176714855,\n chrom_end=176967083,\n name='HOXD12',\n tss=176964457,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD11'] = RegDom(\n chrom='chr2',\n chrom_start=176714855,\n chrom_end=176976491,\n name='HOXD11',\n tss=176972013,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD10'] = RegDom(\n chrom='chr2',\n chrom_start=176714855,\n chrom_end=176982491,\n name='HOXD10',\n tss=176981306,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n\n # Beta-globin locus control region.\n self.curated_reg_doms_dict['HBB'] = RegDom(\n chrom='chr11',\n chrom_start=5226931,\n chrom_end=5314124,\n name='HBB',\n tss=5248427,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HBD'] = RegDom(\n chrom='chr11',\n chrom_start=5253302,\n chrom_end=5314124,\n name='HBD',\n tss=5255878,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HBG1'] = RegDom(\n chrom='chr11',\n chrom_start=5260859,\n chrom_end=5314124,\n name='HBG1',\n tss=5271122,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HBE1'] = RegDom(\n chrom='chr11',\n chrom_start=5276088,\n chrom_end=5314124,\n name='HBE1',\n tss=5526834,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n\n def _add_curated_reg_doms_hg38(self):\n \"\"\"\n Add list of curated regulatory domains for hg38 (lifted over from hg19):\n http://bejerano.stanford.edu/help/display/GREAT/Association+Rules#AssociationRules-CuratedRegulatoryDomains\n\n Sonic hedgehog long-range enhancer:\n SHH: chr7:155130964-156277330\n\n HOXD global control region:\n LNPK: chr2:176423101-176655936\n EVX2: chr2:176423101-176661936\n HOXD13: chr2:176423101-176667775\n HOXD12: chr2:176423101-176675329\n HOXD11: chr2:176423101-176684737\n HOXD10: chr2:176423101-176690737\n\n Beta-globin locus control region:\n HBB: chr11:5183507-5270700\n HBD: chr11:5209878-5270700\n HBG1: chr11:5217435-5270700\n HBE1: chr11:5232664-5270700\n \"\"\"\n\n # Sonic hedgehog long-range enhancer.\n self.curated_reg_doms_dict['SHH'] = RegDom(\n chrom='chr7',\n chrom_start=155130964,\n chrom_end=156277330,\n name='SHH',\n tss=155812272,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n\n # HOXD global control region.\n self.curated_reg_doms_dict['LNPK'] = RegDom(\n chrom='chr2',\n chrom_start=176423101,\n chrom_end=176655936,\n name='LNPK',\n tss=176002344,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['EVX2'] = RegDom(\n chrom='chr2',\n chrom_start=176423101,\n chrom_end=176661936,\n name='EVX2',\n tss=176083912,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD13'] = RegDom(\n chrom='chr2',\n chrom_start=176423101,\n chrom_end=176667775,\n name='HOXD13',\n tss=176092890,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD12'] = RegDom(\n chrom='chr2',\n chrom_start=176423101,\n chrom_end=176675329,\n name='HOXD12',\n tss=176099729,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD11'] = RegDom(\n chrom='chr2',\n chrom_start=176423101,\n chrom_end=176684737,\n name='HOXD11',\n tss=176104215,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HOXD10'] = RegDom(\n chrom='chr2',\n chrom_start=176423101,\n chrom_end=176690737,\n name='HOXD10',\n tss=176116578,\n strand='+',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n\n # Beta-globin locus control region.\n self.curated_reg_doms_dict['HBB'] = RegDom(\n chrom='chr11',\n chrom_start=5183507,\n chrom_end=5270700,\n name='HBB',\n tss=5227196,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HBD'] = RegDom(\n chrom='chr11',\n chrom_start=5209878,\n chrom_end=5270700,\n name='HBD',\n tss=5243656,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HBG1'] = RegDom(\n chrom='chr11',\n chrom_start=5217435,\n chrom_end=5270700,\n name='HBG1',\n tss=5249858,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n self.curated_reg_doms_dict['HBE1'] = RegDom(\n chrom='chr11',\n chrom_start=5232664,\n chrom_end=5270700,\n name='HBE1',\n tss=5505651,\n strand='-',\n basal_up=None,\n basal_down=None,\n chrom_sizes=self.chrom_sizes\n )\n\n def get_curated_reg_doms_for_gene(self, gene):\n \"\"\"\n Get the curated regulatory domain for a gene.\n\n :param gene: gene name\n\n :return: RegDom object if gene name has a curated regulatory domain or None if it does not have one.\n \"\"\"\n return self.curated_reg_doms_dict.get(gene, None)\n\n\ndef create_basal_plus_extension_regdoms(genes_tss_list,\n maximum_extension,\n basal_up,\n basal_down,\n chrom_sizes,\n assembly):\n \"\"\"\n Create regulatory domains from a sorted GenesTSSList object.\n\n The creation of regulatory domains is based on the Basal plus extension approach of GREAT:\n http://bejerano.stanford.edu/help/display/GREAT/Association+Rules#AssociationRules-Approach1Basalplusextension\n\n Each gene is assigned a basal regulatory domain of a minimum distance\n upstream and downstream of the TSS (regardless of other nearby genes).\n\n The gene regulatory domain is extended in both directions to the nearest\n gene's basal domain but no more than a maximum extension in one direction.\n\n When extending the regulatory domain of gene G beyond its basal domain,\n the extension to the \"left\" extends until it reaches the first basal domain\n of any gene whose transcription start site is \"left\" of G's transcription\n start site (and analogously for extending \"right\").\n\n When the TSS start site and strand are the same, both genes will have the\n same regulatory domain (regulatory domain size is then determined by the\n next closest gene).\n\n :param genes_tss_list:\n GenesTSSList object with all genes which you want to consider\n for making regulatory domains.\n :param maximum_extension:\n maximum extension size in base pairs a regulatory domain can be\n extended if it did not encounter a basal domain of the nearest gene.\n :param basal_up:\n # bp upstream of TSS for setting the basal start of the basal domain.\n :param basal_down:\n # bp downstream of TSS for setting the basal end of the basal domain.\n :param chrom_sizes:\n ChromSizes object with chromosome lengths.\n :param assembly:\n Assembly name: hg19, hg38, ...\n\n :return: List of RegDom objects per chromosome.\n \"\"\"\n\n # Store all regulatory domains in a per chromosome list.\n reg_doms_list_per_chrom = {chrom: list() for chrom in chrom_sizes.chrom_sizes_dict}\n\n # Store basal regulatory domain starts and ends per chromosome.\n basal_starts_per_chrom_dict = {chrom: list() for chrom in chrom_sizes.chrom_sizes_dict}\n basal_ends_per_chrom_dict = {chrom: list() for chrom in chrom_sizes.chrom_sizes_dict}\n\n # Store gene index for each gene in basal_starts_per_chrom_dict and basal_ends_per_chrom_dict.\n gene_idx_in_per_chrom_dicts_dict = dict()\n\n # List of curated regulatory domains to add at the end of the reg_doms_list_per_chrom.\n curated_reg_doms_list_to_add_per_chrom = {chrom: list() for chrom in chrom_sizes.chrom_sizes_dict}\n\n # Get all curated regulatory domains.\n curated_reg_doms = CuratedRegDoms(chrom_sizes, assembly)\n\n # Loop over GenesTSSList.\n for curr_gene_tss in genes_tss_list:\n if chrom_sizes.chrom_sizes_dict.get(curr_gene_tss.chrom):\n # Only include regulatory domains for genes for which the chromosome name is listed in the chromosome file.\n\n if curated_reg_doms.get_curated_reg_doms_for_gene(curr_gene_tss.name):\n # If the current GeneTSS has a curated regulatory domain, do not add them to the reg_doms_list_per_chrom\n # yet. They will be added after all genes with non-curated regulatory domains are added.\n curr_regdom = curated_reg_doms.get_curated_reg_doms_for_gene(curr_gene_tss.name)\n curated_reg_doms_list_to_add_per_chrom[curr_gene_tss.chrom].append(curr_regdom)\n else:\n # Create a regulatory domain based on the current GeneTSS.\n curr_regdom = RegDom(chrom=curr_gene_tss.chrom,\n chrom_start=None,\n chrom_end=None,\n name=curr_gene_tss.name,\n tss=curr_gene_tss.tss,\n strand=curr_gene_tss.strand,\n basal_up=basal_up,\n basal_down=basal_down,\n chrom_sizes=chrom_sizes)\n\n reg_doms_list_per_chrom[curr_gene_tss.chrom].append(curr_regdom)\n\n # Store basal regulatory domain start and end for the current regulatory domain per chromosome.\n basal_starts_per_chrom_dict[curr_gene_tss.chrom].append(curr_regdom.basal_start)\n basal_ends_per_chrom_dict[curr_gene_tss.chrom].append(curr_regdom.basal_end)\n\n # Store the gene index for the current GeneTSS in the per chromosome list\n # in basal_starts_per_chrom_dict and basal_ends_per_chrom_dict, so later\n # we will be able to get all basal start locations before a certain TSS of\n # a gene and all basal end locations of a certain TSS, so we do not extend\n # a regulatory domain to far.\n gene_idx_in_per_chrom_dicts_dict[\n (curr_gene_tss.name,\n curr_gene_tss.chrom,\n curr_gene_tss.tss,\n curr_gene_tss.strand)] = len(basal_starts_per_chrom_dict[curr_gene_tss.chrom]) - 1\n\n # Loop over all regulatory domains per chromosome.\n for chrom in reg_doms_list_per_chrom:\n for idx, curr_regdom in enumerate(reg_doms_list_per_chrom[chrom]):\n # Get the previous regulatory domain if this is not the first regulatory domain of the list.\n prev_regdom = (reg_doms_list_per_chrom[chrom][idx - 1]\n if idx > 0\n else None)\n\n # Get the next regulatory domain if this is not the last regulatory domain of the list.\n next_regdom = (reg_doms_list_per_chrom[chrom][idx + 1]\n if idx < (len(reg_doms_list_per_chrom[chrom]) - 1)\n else None)\n\n # Extend regulatory domain as much as possible to the left.\n tmp_start = min(curr_regdom.basal_start,\n max(0, curr_regdom.tss - maximum_extension))\n\n if prev_regdom:\n if (prev_regdom.tss, prev_regdom.strand) == (curr_regdom.tss, curr_regdom.strand):\n # The previous regulatory domain had the same TSS and strand.\n tmp_start = min(curr_regdom.basal_start, prev_regdom.chrom_start)\n else:\n # Get the gene index of the current gene in the per chromosome list of the basal_ends_per_chrom_dict\n # and substract one.\n prev_gene_idx_in_per_chrom_dicts = gene_idx_in_per_chrom_dicts_dict[(curr_regdom.name,\n curr_regdom.chrom,\n curr_regdom.tss,\n curr_regdom.strand)] - 1\n\n if prev_gene_idx_in_per_chrom_dicts >= 1:\n # This is the third or higher gene on this chromosome.\n\n # Adapt the start site of the current regulatory domain by taking the lowest genomic coordinate\n # of:\n # - the current regulatory basal domain start.\n # - the highest genomic coordinate of:\n # - the previous regulatory basal domain end.\n # - the extend regulatory domain as much as possible to the left.\n # - the highest basal end of all previous genes on the current chromosome\n # (which is not always the previous gene, as strandness plays a role in the basal domain\n # creation).\n tmp_start = min(curr_regdom.basal_start,\n max(prev_regdom.basal_end,\n tmp_start,\n max(basal_ends_per_chrom_dict[curr_regdom.chrom][\n 0:prev_gene_idx_in_per_chrom_dicts\n ])\n )\n )\n else:\n # This is the second gene on this chromosome.\n tmp_start = min(curr_regdom.basal_start,\n max(prev_regdom.basal_end, tmp_start))\n\n # Extend regulatory domain as much as possible to the right.\n tmp_end = max(curr_regdom.basal_end,\n min(chrom_sizes.get_chrom_size_for_chrom(curr_regdom.chrom),\n curr_regdom.tss + maximum_extension)\n )\n\n if next_regdom:\n # The next regulatory domain was on the same chromosome as the current one.\n\n # Get the gene index of the current gene in the per chromosome list of the basal_starts_per_chrom_dict\n # and add one.\n next_gene_idx_in_per_chrom_dicts = gene_idx_in_per_chrom_dicts_dict[(curr_regdom.name,\n curr_regdom.chrom,\n curr_regdom.tss,\n curr_regdom.strand)] + 1\n\n # Adapt the end site of the current regulatory domain by taking the highest genomic coordinate of:\n # - the current regulatory basal domain end.\n # - the lowest genomic coordinate of:\n # - the next regulatory basal domain start.\n # - the extend regulatory domain as much as possible to the right.\n # - the lowest basal start of all next genes on the current chromosome\n # (which is not always the next gene, as strandness plays a role in the basal domain creation).\n tmp_end = max(curr_regdom.basal_end,\n min(next_regdom.basal_start,\n tmp_end,\n min(basal_starts_per_chrom_dict[curr_regdom.chrom][next_gene_idx_in_per_chrom_dicts:])\n )\n )\n\n # Update the regulatory domain start and end in the reg_doms_list_per_chrom.\n reg_doms_list_per_chrom[chrom][idx].chrom_start = tmp_start\n reg_doms_list_per_chrom[chrom][idx].chrom_end = tmp_end\n\n if prev_regdom and (\n (prev_regdom.tss, prev_regdom.strand) ==\n (curr_regdom.tss, curr_regdom.strand)\n ):\n # The previous regulatory domain has the same chromosome name, TSS and strand.\n\n prev_idx = idx - 1\n\n # Fix previous regulatory domain starts and current regulatory domain start as long as\n # TSS and strand are the same as for the current regulatory domain.\n while prev_idx >= 0 and (\n (reg_doms_list_per_chrom[chrom][prev_idx].tss,\n reg_doms_list_per_chrom[chrom][prev_idx].strand) ==\n (curr_regdom.tss,\n curr_regdom.strand)\n ):\n reg_doms_list_per_chrom[chrom][prev_idx].chrom_end = max(\n reg_doms_list_per_chrom[chrom][prev_idx].chrom_end,\n curr_regdom.chrom_end\n )\n reg_doms_list_per_chrom[chrom][idx].chrom_start = \\\n reg_doms_list_per_chrom[chrom][prev_idx].chrom_start\n\n prev_idx -= 1\n\n # Add curated regulatory domains at the end.\n for chrom in curated_reg_doms_list_to_add_per_chrom:\n reg_doms_list_per_chrom[chrom].extend(curated_reg_doms_list_to_add_per_chrom[chrom])\n\n return reg_doms_list_per_chrom\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Create BED file with regulatory domains from file with TSS information for each gene.'\n )\n\n parser.add_argument('-u',\n '--basal-up',\n dest='basal_up',\n action='store',\n type=int,\n required=False,\n default=default_basal_up,\n help='Number of bases upstream of TSS to create a basal domain region '\n '(default: \"{0:d}\").'.format(default_basal_up)\n )\n parser.add_argument('-d',\n '--basal-down',\n dest='basal_down',\n action='store',\n type=int,\n required=False,\n default=default_basal_down,\n help='Number of bases downstream of TSS to create a basal domain region '\n '(default: \"{0:d}\").'.format(default_basal_down)\n )\n parser.add_argument('-e',\n '--max-ext',\n dest='maximum_extension',\n action='store',\n type=int,\n required=False,\n default=default_maximum_extension,\n help='Maximum extension size in base pairs a regulatory domain can be '\n 'extended if it did not encounter a basal domain of the nearest gene. '\n '(default: \"{0:d}\").'.format(default_maximum_extension)\n )\n parser.add_argument('-c',\n '--chrom-sizes',\n dest='chrom_sizes_filename',\n action='store',\n type=str,\n required=False,\n default=default_chrom_sizes_filename,\n help='TAB-separated file with chromosome names and chromosome sizes. '\n '(default: \"{0:s}\").'.format(default_chrom_sizes_filename)\n )\n parser.add_argument('-a',\n '--assembly',\n dest='assembly',\n action='store',\n type=str,\n required=False,\n default='hg19',\n help='Assembly name. (default: \"{0:s}\").'.format(default_assembly)\n )\n parser.add_argument('-i',\n '--genes-tss',\n dest='genes_tss_filename',\n action='store',\n type=str,\n required=False,\n default=default_genes_tss_filename,\n help='TAB-separated file with 4 (chromosome name, TSS, strand, gene name) or '\n '5 (ENSEMBL gene ID, chromosome name, TSS, strand, gene name) columns '\n 'which is used as input to create the regulatory domains. '\n '(default: \"{0:s}\").'.format(default_genes_tss_filename)\n )\n parser.add_argument('-o',\n '--regdoms',\n dest='regulatory_domains_bed_filename',\n action='store',\n type=str,\n required=False,\n default='-',\n help='Regulatory domains BED output file (default: \"stdout\").'\n )\n\n args = parser.parse_args()\n\n # Create a list of GeneTSS objects sorted by chromosome name, TSS, strand and gene name from a TAB-separated file.\n genes_tss_list = GenesTSSList.load_genes_tss_file(\n genes_tss_filename=args.genes_tss_filename\n )\n\n # Calculate the regulatory domains for each gene.\n # See \"create_basal_plus_extension_regdoms\" for more information.\n reg_doms_list_per_chrom = create_basal_plus_extension_regdoms(\n genes_tss_list=genes_tss_list,\n maximum_extension=args.maximum_extension,\n basal_up=args.basal_up,\n basal_down=args.basal_down,\n chrom_sizes=ChromSizes.load_chrom_sizes_file(args.chrom_sizes_filename),\n assembly=args.assembly\n )\n\n if args.regulatory_domains_bed_filename in ('-', 'stdout'):\n regulatory_domains_output_bed_fh = sys.stdout\n else:\n regulatory_domains_output_bed_fh = open(args.regulatory_domains_bed_filename, 'w')\n\n # Print the regulatory domain output to standard output.\n print('# chrom',\n 'chrom_start',\n 'chrom_end',\n 'name',\n 'tss',\n 'strand',\n 'basal_start',\n 'basal_end',\n sep='\\t',\n file=regulatory_domains_output_bed_fh)\n\n for chrom in sorted(reg_doms_list_per_chrom):\n for reg_dom in reg_doms_list_per_chrom[chrom]:\n print(reg_dom, file=regulatory_domains_output_bed_fh)\n\n regulatory_domains_output_bed_fh.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"aertslab/mucistarget","sub_path":"create_regulatory_domains.py","file_name":"create_regulatory_domains.py","file_ext":"py","file_size_in_byte":36721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"71204330174","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Maximum string borders by Knuth-Morris-Pratt\n# jill-jênn vie et christoph dürr et louis abraham - 2014-2018\n# inspired from a practical lesson (TP) from Yves Lemaire\n# in linear time with Knuth-Morris-Pratt\n\n\n# Find the length of maximal borders of u in linear time.\n\n# snip{\ndef maximum_border_length(w):\n \"\"\"Maximum string borders by Knuth-Morris-Pratt\n\n :param w: string\n :returns: table l such that l[i] is the longest border length of w[:i + 1]\n :complexity: linear\n \"\"\"\n n = len(w)\n L = [0] * n\n k = 0\n for i in range(1, n):\n while w[k] != w[i] and k > 0:\n k = L[k - 1]\n if w[k] == w[i]:\n k += 1\n L[i] = k\n else:\n L[i] = 0\n return L\n# snip}\n\n\n# snip{ powerstring_by_border\ndef powerstring_by_border(u):\n \"\"\"Power string by Knuth-Morris-Pratt\n\n :param x: string\n :returns: largest k such that there is a string y with x = y^k\n :complexity: O(len(x))\n \"\"\"\n L = maximum_border_length(u)\n n = len(u)\n if n % (n - L[-1]) == 0:\n return n // (n - L[-1])\n return 1\n# snip}\n","repo_name":"yaominzh/moocview","sub_path":"cp128/knuth_morris_pratt_border.py","file_name":"knuth_morris_pratt_border.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"36742628681","text":"from odoo import models, api, fields\nfrom odoo.addons.queue_job.job import job, related_action\n\n\nclass AccountInvoice(models.Model):\n _inherit = \"account.invoice\"\n\n @api.multi\n @job(default_channel='root.cms_form_compassion')\n @related_action('related_action_invoice')\n def pay_transaction_invoice(\n self, transaction, invoice_vals, journal_id, method_id, auto_post):\n \"\"\"Make a payment to reconcile transaction invoice.\n\n :param transaction: The originating transaction\n :param invoice_vals: Values to write into invoice\n :param journal_id: account.journal to use\n :param method_id: payment.method to use\n :param auto_post: True if invoice should be validated and payment\n directly posted.\n :return: True\n \"\"\"\n if self.state == 'paid':\n return True\n\n # Write values about payment\n self.write(invoice_vals)\n # Look for existing payment\n payment = self.env['account.payment'].search([\n ('invoice_ids', '=', self.id)\n ])\n if payment:\n return True\n\n payment_vals = {\n 'journal_id': journal_id,\n 'payment_method_id': method_id,\n 'payment_date': fields.Date.today(),\n 'communication': self.reference,\n 'invoice_ids': [(6, 0, self.ids)],\n 'payment_type': 'inbound',\n 'amount': self.amount_total,\n 'currency_id': self.currency_id.id,\n 'partner_id': self.partner_id.id,\n 'partner_type': 'customer',\n 'payment_difference_handling': 'reconcile',\n 'payment_difference': self.amount_total,\n }\n account_payment = self.env['account.payment'].create(payment_vals)\n if auto_post:\n # Validate self and post the payment.\n if self.state == 'draft':\n self.action_invoice_open()\n account_payment.post()\n self._after_transaction_invoice_paid(transaction)\n return True\n\n def _after_transaction_invoice_paid(self, transaction):\n \"\"\" Hook for doing post-processing after transaction was paid. \"\"\"\n pass\n","repo_name":"Grazia976/compassion-modules","sub_path":"cms_form_compassion/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"79"} +{"seq_id":"16780596140","text":"\r\ndef solve_grid(bo):\r\n find = find_empty_spot(bo)\r\n if not find:\r\n return True\r\n else:\r\n row, col = find\r\n for i in range(1,10):\r\n if check(bo, i, (row, col)):\r\n bo[row][col] = i\r\n if solve_grid(bo):\r\n return True\r\n bo[row][col] = 0\r\n return False\r\n\r\n#function to check whether the assigned entry matches with the given number\r\ndef check(bo, num, pos):\r\n # Check row\r\n for i in range(len(bo[0])):\r\n if bo[pos[0]][i] == num and pos[1] != i:\r\n return False\r\n # Check column\r\n for i in range(len(bo)):\r\n if bo[i][pos[1]] == num and pos[0] != i:\r\n return False\r\n # Check box\r\n box_x = pos[1] // 3\r\n box_y = pos[0] // 3\r\n for i in range(box_y*3, box_y*3 + 3):\r\n for j in range(box_x * 3, box_x*3 + 3):\r\n if bo[i][j] == num and (i,j) != pos:\r\n return False\r\n return True\r\n\r\n# function to print the grid\r\ndef print_grid(bo):\r\n for i in range(len(bo)):\r\n if i % 3 == 0 and i != 0:\r\n print(\"- - - - - - - - - - - - - \")\r\n for j in range(len(bo[0])):\r\n if j % 3 == 0 and j != 0:\r\n print(\" | \", end=\"\")\r\n if j == 8:\r\n print(bo[i][j])\r\n else:\r\n print(str(bo[i][j]) + \" \", end=\"\")\r\n\r\n#search the grid to find an entry that is still unassigned \r\ndef find_empty_spot(bo):\r\n for i in range(len(bo)):\r\n for j in range(len(bo[0])):\r\n if bo[i][j] == 0:\r\n return (i, j) # row, col\r\n return None\r\n","repo_name":"r1p2/sudoku-game","sub_path":"sudokuSolver.py","file_name":"sudokuSolver.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"16285286279","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 13 15:11:10 2020\n\n@author: Ted\n\"\"\"\nimport numpy as np\nimport librosa\nimport glob\n#%% utility methods\ndef get_wavlist(dir):\n \"\"\"\n find .wav file and make wavlist from the specified dir\n \"\"\"\n get_list = glob.glob(dir)\n return get_list\n\ndef make_spectrogram(pathname, fftsize, hopsize, nbit, istest=False):\n \"\"\"\n make spectrogram from pathname\n making it easy for network to train data, compress-normalize with \"nbit\"\n \"\"\"\n x,_ = librosa.core.load(pathname, sr=16000) #audioread\n X = librosa.core.stft(x, n_fft=fftsize, hop_length=hopsize)\n absX = np.abs(X)\n phsX = np.exp(1.j*np.angle(X))\n maxval, minval = np.max(absX), np.min(absX)\n absXn_int= np.floor(((absX-minval)/(maxval-minval))*(2**nbit-1) + 0.5)\n absXn = absXn_int/(2**nbit-1) #0-1\n if istest:\n return absXn, phsX, maxval, minval\n else:\n return absXn, phsX\n\ndef make_dataset(wavlist, fftsize, hopsize, nbit):\n \"\"\"\n find .wav file and make spectrogram\n \"\"\"\n Xbox = []\n for path in wavlist:\n X,_ = make_spectrogram(path, fftsize, hopsize, nbit)\n Xbox.append(X)\n return np.array(Xbox)[...,np.newaxis]","repo_name":"ted-17/gensound","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"40327118399","text":"\"\"\" 对于一个数组arr, 每次进行后缀删除, 删除第i个数字的概率为 a[i]/sum, 问期望删除的次数\n限制: n 100\n\n思路1: #DP\n 定义 f[i] 表示从开始删除到位置i的期望操作次数. 则有递推\n f[i] = 1 + sum{ prob[j] * f[j-1], j=0...i }\n\"\"\"\n# n = int(input())\n# arr = list(map(int, input().split()))\n# # from itertools import accumulate\n# # acc = list(accumulate(arr, initial=0))\n# from functools import lru_cache\n# @lru_cache(None)\n# def f(i):\n# if i==-1: return 0\n# s = sum(arr[:i+1])\n# ans = 1\n# for j in range(0,i+1):\n# ans += arr[j]/s * f(j-1)\n# return ans\n# print(f(n-1))\n\n\nfrom itertools import accumulate\n\nn = int(input())\narr = list(map(int, input().split()))\n\nacc = list(accumulate(arr, initial=0))\nf = [0] * (n+1)\nfor i in range(n):\n s = acc[i+1]\n tmp = 1\n for j in range(0,i+1):\n tmp += arr[j]/s * f[j]\n f[i+1] = tmp\nprint(f[n])\n \n","repo_name":"Lightblues/Leetcode","sub_path":"interview-list/230722-oppo/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"79"} +{"seq_id":"25299196518","text":"import os\nimport argparse\nimport tensorflow as tf\n\nfrom model import simple\nfrom hooks import signal\n\nclass Run(object):\n\n def __init__(self, model, conv1, conv2):\n self._model = model\n self._conv1 = conv1\n self._conv2 = conv2\n\n def build(self):\n self.re = self._model.interference(self._conv1, self._conv2, self.mr)\n self.df = (self.us-self.re)**2\n self.loss = tf.reduce_sum(self.df, name='l2norm')\n\n def summarize(self):\n tf.summary.scalar('loss', self.loss)\n tf.summary.image('mr', self.mr, max_outputs=1)\n tf.summary.image('us', self.us, max_outputs=1)\n tf.summary.image('re', self.re, max_outputs=1)\n tf.summary.image('df', self.df, max_outputs=1)\n\nclass PatchesRun(Run):\n\n def build(self, filename, epochs=0, train=False):\n if epochs > 0:\n filename = tf.train.limit_epochs(tf.convert_to_tensor(filename),\n epochs)\n\n self.mr, self.us = self._model.patches(filename)\n\n super().build()\n\n if train:\n self.train = self._model.train(self.loss)\n\nclass ImagesRun(Run):\n\n def build(self, filename):\n self.mr, self.us = self._model.images(filename)\n\n super().build()\n\n self.re = tf.where(tf.equal(self.us, 0),\n tf.zeros_like(self.re), self.re)\n\ndef main(args):\n model = simple.Model(\n filter_num=args.filter_num,\n filter_size=args.filter_size)\n\n conv1 = model.conv1()\n conv2 = model.conv2()\n\n with tf.name_scope('train'):\n with tf.name_scope('patches'):\n patches_train_run = PatchesRun(model, conv1, conv2)\n patches_train_run.build(args.train, args.epochs, train=True)\n patches_train_run.summarize()\n with tf.name_scope('images'):\n images_train_run = ImagesRun(model, conv1, conv2)\n images_train_run.build(args.train)\n images_train_run.summarize()\n\n with tf.name_scope('valid'):\n with tf.name_scope('patches'):\n patches_valid_run = PatchesRun(model, conv1, conv2)\n patches_valid_run.build(args.valid)\n patches_valid_run.summarize()\n with tf.name_scope('images'):\n images_valid_run = ImagesRun(model, conv1, conv2)\n images_valid_run.build(args.valid)\n images_valid_run.summarize()\n\n with tf.name_scope('test'):\n with tf.name_scope('patches'):\n patches_test_run = PatchesRun(model, conv1, conv2)\n patches_test_run.build(args.test)\n patches_test_run.summarize()\n with tf.name_scope('images'):\n images_test_run = ImagesRun(model, conv1, conv2)\n images_test_run.build(args.test)\n images_test_run.summarize()\n\n with tf.Session() as session:\n session.run([\n tf.local_variables_initializer(),\n tf.global_variables_initializer(),\n ])\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(session, coord)\n\n writer = tf.summary.FileWriter(args.logdir, session.graph)\n merged = tf.summary.merge_all()\n\n try:\n step = 0\n\n while not coord.should_stop():\n session.run([\n patches_train_run.train,\n images_train_run.loss,\n patches_valid_run.loss,\n images_valid_run.loss,\n patches_test_run.loss,\n images_test_run.loss,\n ])\n\n if step % 10 == 0:\n writer.add_summary(session.run(merged), step)\n if step % 100 == 0:\n print('step: {}'.format(step))\n\n step += 1\n except tf.errors.OutOfRangeError as error:\n coord.request_stop(error)\n finally:\n coord.request_stop()\n coord.join(threads)\n\n writer.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='evaluate model on a given dataset')\n parser.add_argument('--epochs', type=int,\n help='number of epochs to run')\n parser.add_argument('--test', nargs='+',\n help='tfrecords to use for testing')\n parser.add_argument('--train', nargs='+',\n help='tfrecords to use for training')\n parser.add_argument('--valid', nargs='+',\n help='tfrecords to use for validation')\n parser.add_argument('--logdir',\n help='directory to write events to')\n parser.add_argument('--filter_num',\n help='number of filters')\n parser.add_argument('--filter_size',\n help='height and width of filters')\n parser.set_defaults(epochs=30, filter_num=3, filter_size=7,\n train=['data/train.tfrecord'],\n valid=['data/valid.tfrecord'],\n test=['data/test.tfrecord'],\n logdir='/tmp/mrtous')\n\n main(parser.parse_args())","repo_name":"bodokaiser/tensorflow-example","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"72168582655","text":"\"\"\"Classes for using images with BananaGUI.\"\"\"\n\nimport os\n\nfrom bananagui import _get_wrapper\n\n__all__ = ['Image']\n\n\ndef _guess_filetype(path, default):\n \"\"\"Extract the filetype from filename.\n\n >>> _guess_filetype('a/b/c/coolpic.PNg', None)\n 'png'\n >>> _guess_filetype('whatever', 'Png')\n 'png'\n >>> _guess_filetype('whatever', None)\n Traceback (most recent call last):\n ...\n ValueError: cannot guess filetype from 'whatever'\n \"\"\"\n if default is None:\n filename = os.path.basename(path)\n if '.' not in filename:\n raise ValueError(\"cannot guess filetype from %r\" % path)\n return filename.rsplit('.', 1)[1].lower()\n return default.lower()\n\n\n# TODO: resize() and flip() methods.\n# TODO: methods for accessing pixels one by one?\nclass Image:\n \"\"\"A mutable image.\n\n Calling the Image class constructs a new image from a path to a\n file. For example, ``Image('banana.png')`` creates a new image of\n the file ``banana.png`` in the current working directory.\n\n The filetype is typically also the file the file extension without a\n dot. Not all filetypes work with all GUI toolkits, but ``'gif'`` and\n ``'png'`` should be valid filetype values with all GUI toolkits. The\n filetype must be given explicitly if it can't be guessed from the\n file extension, like ``Image('magic-banana', 'gif')``.\n\n You can use :class:`bananagui.widgets.ImageLabel` for displaying an\n image to the user.\n \"\"\"\n\n def __init__(self, path: str, filetype: str = None):\n \"\"\"Load an Image from a file.\"\"\"\n filetype = _guess_filetype(path, filetype)\n wrapperclass = _get_wrapper('images:Image')\n self._wrapper, self._size = wrapperclass.from_file(path, filetype)\n self._path = path\n\n def save(self, path: str, filetype: str = None):\n \"\"\"Save the image to a file.\"\"\"\n filetype = _guess_filetype(path, filetype)\n self._wrapper.save(path, filetype)\n self._path = path\n\n @classmethod\n def from_size(cls, width: int, height: int):\n \"\"\"Create a new, fully transparent Image of the given size.\"\"\"\n if width < 0 or height < 0:\n raise ValueError(\"negative width or height\")\n wrapperclass = _get_wrapper('images:Image')\n self = cls.__new__(cls) # Don't run __init__.\n self._wrapper = wrapperclass.from_size(width, height)\n self._size = (width, height)\n self._path = None\n return self\n\n def __repr__(self):\n # Adding both path and size would make the repr awfully long,\n # but adding one of them seems good.\n cls = type(self)\n result = \"%s.%s object\" % (cls.__module__, cls.__name__)\n if self._path is None:\n result += \", size=%r\" % (self.size,)\n else:\n result += \" from %r\" % self._path\n return '<' + result + '>'\n\n @property\n def real_image(self):\n \"\"\"The real GUI toolkit's image object.\"\"\"\n return self._wrapper.real_image\n\n @property\n def size(self):\n \"\"\"Two-tuple of width and height in pixels.\"\"\"\n return self._size\n\n def copy(self):\n \"\"\"Return a copy of this image.\n\n This image and the copy don't affect each other in any way when\n mutated.\n \"\"\"\n cls = type(self)\n copy = cls.__new__(cls) # Don't run __init__.\n copy._wrapper = self._wrapper.copy()\n copy._size = self._size\n copy._path = self._path\n return copy\n","repo_name":"Akuli/BananaGUI","sub_path":"bananagui/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"17001176139","text":"\"\"\"Functions related to reading and writing data.\"\"\"\r\nimport logging\r\nimport io\r\nfrom collections import Counter\r\nfrom pathlib import Path\r\nfrom sys import path as sys_path\r\nimport requests\r\nfrom . import psize\r\nfrom . import inputgen\r\nfrom . import cif\r\nfrom . import pdb\r\nfrom . import definitions as defns\r\nfrom .config import FORCE_FIELDS, TITLE_FORMAT_STRING, VERSION\r\nfrom .config import FILTER_WARNINGS_LIMIT, FILTER_WARNINGS\r\nfrom .config import AA_DEF_PATH, NA_DEF_PATH, PATCH_DEF_PATH\r\n\r\n\r\n_LOGGER = logging.getLogger(__name__)\r\n\r\n\r\nclass DuplicateFilter(logging.Filter):\r\n \"\"\"Filter duplicate messages.\"\"\"\r\n def __init__(self):\r\n super().__init__()\r\n self.warn_count = Counter()\r\n\r\n def filter(self, record):\r\n \"\"\"Filter current record.\"\"\"\r\n if record.levelname == \"WARNING\":\r\n for fwarn in FILTER_WARNINGS:\r\n if record.getMessage().startswith(fwarn):\r\n self.warn_count.update([fwarn])\r\n if self.warn_count[fwarn] > FILTER_WARNINGS_LIMIT:\r\n return False\r\n elif self.warn_count[fwarn] == FILTER_WARNINGS_LIMIT:\r\n _LOGGER.warning(\"Suppressing further '%s' messages\", fwarn)\r\n return False\r\n else:\r\n return True\r\n return True\r\n\r\n\r\ndef print_protein_atoms(atomlist, chainflag=False, pdbfile=False):\r\n \"\"\"Get text lines for specified atoms\r\n\r\n Args:\r\n atomlist: The list of atoms to include (list)\r\n chainflag: Flag whether to print chainid or not\r\n Returns:\r\n text: list of (stringed) atoms (list)\r\n \"\"\"\r\n text = []\r\n currentchain_id = None\r\n for atom in atomlist:\r\n # Print the \"TER\" records between chains\r\n if currentchain_id is None:\r\n currentchain_id = atom.chain_id\r\n elif atom.chain_id != currentchain_id:\r\n currentchain_id = atom.chain_id\r\n text.append(\"TER\\n\")\r\n\r\n if pdbfile is True:\r\n text.append(\"%s\\n\" % atom.get_pdb_string())\r\n else:\r\n text.append(\"%s\\n\" % atom.get_pqr_string(chainflag=chainflag))\r\n text.append(\"TER\\nEND\")\r\n return text\r\n\r\n\r\ndef get_old_header(pdblist):\r\n \"\"\"Get old header from list of PDBs.\r\n\r\n Args:\r\n pdblist: list of PDBs\r\n Returns:\r\n Old header as string.\r\n \"\"\"\r\n old_header = io.StringIO()\r\n header_types = (pdb.HEADER, pdb.TITLE, pdb.COMPND, pdb.SOURCE, pdb.KEYWDS,\r\n pdb.EXPDTA, pdb.AUTHOR, pdb.REVDAT, pdb.JRNL, pdb.REMARK,\r\n pdb.SPRSDE, pdb.NUMMDL)\r\n for pdb_obj in pdblist:\r\n if not isinstance(pdb_obj, header_types):\r\n break\r\n old_header.write(str(pdb_obj))\r\n old_header.write('\\n')\r\n return old_header.getvalue()\r\n\r\n\r\ndef print_pqr_header(pdblist, atomlist, reslist, charge, force_field, ph_calc_method,\r\n ph, ffout, include_old_header=False):\r\n \"\"\"Print the header for the PQR file\r\n\r\n Args:\r\n pdblist: list of lines from original PDB with header\r\n atomlist: A list of atoms that were unable to have charges assigned (list)\r\n reslist: A list of residues with non-integral charges (list)\r\n charge: The total charge on the protein (float)\r\n ff: The forcefield name (string)\r\n ph: pH value, if any. (float)\r\n ffout: ff used for naming scheme (string)\r\n Returns\r\n header: The header for the PQR file (string)\r\n \"\"\"\r\n if force_field is None:\r\n force_field = 'User force field'\r\n else:\r\n force_field = force_field.upper()\r\n head = \"\\n\".join([\"REMARK 1 PQR file generated by PDB2PQR\",\r\n \"REMARK 1 %s\" % TITLE_FORMAT_STRING.format(version=VERSION),\r\n \"REMARK 1\",\r\n \"REMARK 1 Forcefield Used: %s\" % force_field, \"\"])\r\n if not ffout is None:\r\n head += \"REMARK 1 Naming Scheme Used: %s\\n\" % ffout\r\n head += head + \"REMARK 1\\n\"\r\n\r\n if ph_calc_method is not None:\r\n head += \"\\n\".join([(\"REMARK 1 pKas calculated by %s and assigned \"\r\n \"using pH %.2f\\n\") % (ph_calc_method, ph),\r\n \"REMARK 1\", \"\"])\r\n\r\n if len(atomlist) != 0:\r\n head += \"\\n\".join([\"REMARK 5 WARNING: PDB2PQR was unable to assign charges\",\r\n \"REMARK 5 to the following atoms (omitted below):\", \"\"])\r\n for atom in atomlist:\r\n head += \"REMARK 5 %i %s in %s %i\\n\" % (atom.serial, atom.name,\r\n atom.residue.name,\r\n atom.residue.res_seq)\r\n head += \"\\n\".join([\"REMARK 5 This is usually due to the fact that this residue is not\",\r\n \"REMARK 5 an amino acid or nucleic acid; or, there are no parameters\",\r\n \"REMARK 5 available for the specific protonation state of this\",\r\n \"REMARK 5 residue in the selected forcefield.\",\r\n \"REMARK 5\", \"\"])\r\n if len(reslist) != 0:\r\n head += \"\\n\".join([\"REMARK 5 WARNING: Non-integral net charges were found in\",\r\n \"REMARK 5 the following residues:\", \"\"])\r\n for residue in reslist:\r\n head += \"REMARK 5 %s - Residue Charge: %.4f\\n\" % (residue, residue.charge)\r\n head += \"REMARK 5\\n\"\r\n head += \"\\n\".join([\"REMARK 6 Total charge on this protein: %.4f e\\n\" % charge,\r\n \"REMARK 6\", \"\"])\r\n\r\n if include_old_header:\r\n head += \"\\n\".join([\"REMARK 7 Original PDB header follows\",\r\n \"REMARK 7\", \"\"])\r\n head += get_old_header(pdblist)\r\n return head\r\n\r\n\r\ndef print_pqr_header_cif(atomlist, reslist, charge, force_field,\r\n ph_calc_method, ph, ffout, include_old_header=False):\r\n \"\"\"Print the header for the PQR file in cif format.\r\n\r\n Args:\r\n atomlist: A list of atoms that were unable to have charges assigned (list)\r\n reslist: A list of residues with non-integral charges (list)\r\n charge: The total charge on the protein (float)\r\n force_field: The forcefield name (string)\r\n ph: pH value, if any. (float)\r\n ffout: ff used for naming scheme (string)\r\n Returns\r\n header: The header for the PQR file (string)\r\n \"\"\"\r\n if force_field is None:\r\n force_field = \"User force field\"\r\n else:\r\n force_field = force_field.upper()\r\n\r\n header = \"\\n\".join([\"#\", \"loop_\", \"_pdbx_database_remark.id\",\r\n \"_pdbx_database_remark.text\", \"1\", \";\",\r\n \"PQR file generated by PDB2PQR\",\r\n TITLE_FORMAT_STRING.format(version=VERSION), \"\",\r\n \"Forcefield used: %s\\n\" % force_field, \"\"])\r\n if ffout is not None:\r\n header += \"Naming scheme used: %s\\n\" % ffout\r\n header += \"\\n\"\r\n if ph_calc_method is not None:\r\n header += \"pKas calculated by %s and assigned using pH %.2f\\n\" % (ph_calc_method,\r\n ph)\r\n header += \"\\n\".join([\";\", \"2\", \";\", \"\"])\r\n if len(atomlist) > 0:\r\n header += \"\\n\".join([\"Warning: PDB2PQR was unable to assign charges\",\r\n \"to the following atoms (omitted below):\", \"\"])\r\n for atom in atomlist:\r\n header += \" %i %s in %s %i\\n\" % (atom.serial, atom.name,\r\n atom.residue.name, atom.residue.res_seq)\r\n header += \"\\n\".join([\"This is usually due to the fact that this residue is not\",\r\n \"an amino acid or nucleic acid; or, there are no parameters\",\r\n \"available for the specific protonation state of this\",\r\n \"residue in the selected forcefield.\", \"\"])\r\n if len(reslist) > 0:\r\n header += \"\\n\".join([\"Warning: Non-integral net charges were found in\",\r\n \"the following residues:\", \"\"])\r\n for residue in reslist:\r\n header += \" %s - Residue Charge: %.4f\\n\" % (residue, residue.charge)\r\n header += \"\\n\".join([\";\", \"3\", \";\",\r\n \"Total charge on this protein: %.4f e\" % charge, \";\", \"\"])\r\n if include_old_header:\r\n _LOGGER.warning(\"Including original CIF header not implemented.\")\r\n header += \"\\n\".join([\"#\", \"loop_\", \"_atom_site.group_PDB\", \"_atom_site.id\",\r\n \"_atom_site.label_atom_id\", \"_atom_site.label_comp_id\",\r\n \"_atom_site.label_seq_id\", \"_atom_site.Cartn_x\",\r\n \"_atom_site.Cartn_y\", \"_atom_site.Cartn_z\",\r\n \"_atom_site.pqr_partial_charge\", \"_atom_site.pqr_radius\", \"\"])\r\n return header\r\n\r\n\r\ndef dump_apbs(output_pqr, output_path):\r\n \"\"\"Generate and dump APBS input files related to output_pqr.\r\n\r\n Args:\r\n output_pqr: path to PQR file used to generate APBS input file\r\n output_path: path for APBS input file output\r\n \"\"\"\r\n method = \"mg-auto\"\r\n size = psize.Psize()\r\n size.parse_input(output_pqr)\r\n size.run_psize(output_pqr)\r\n input_ = inputgen.Input(output_pqr, size, method, 0, potdx=True)\r\n input_.print_input_files(output_path)\r\n\r\n\r\ndef test_for_file(name, type_):\r\n \"\"\"Test for the existence of a file with a few name permutations.\r\n\r\n Args:\r\n name: name of file\r\n type_: type of file\r\n Returns:\r\n path to file or None\r\n \"\"\"\r\n if name is None:\r\n return ''\r\n test_names = [name, name.upper(), name.lower()]\r\n test_suffixes = [\"\", \".%s\" % type_.upper(), \".%s\" % type_.lower()]\r\n\r\n test_dirs = [Path(p).joinpath(\"pdb2pqr\", \"dat\") for p in sys_path + [Path.cwd()]]\r\n\r\n if name.lower() in FORCE_FIELDS:\r\n name = name.upper()\r\n\r\n for test_dir in test_dirs:\r\n test_dir = Path(test_dir)\r\n for test_name in test_names:\r\n for test_suffix in test_suffixes:\r\n test_path = test_dir / (test_name + test_suffix)\r\n if test_path.is_file():\r\n _LOGGER.debug(\"Found %s file %s\", type_, test_path)\r\n return test_path\r\n _LOGGER.warning(\"Unable to find %s file for %s\", type_, name)\r\n return \"\"\r\n\r\n\r\ndef test_names_file(name):\r\n \"\"\"Test for the *.names file that contains the XML mapping.\r\n\r\n Args:\r\n name: The name of the forcefield (string)\r\n Returns\r\n path: The path to the file (string)\r\n \"\"\"\r\n return test_for_file(name, \"NAMES\")\r\n\r\n\r\ndef test_dat_file(name):\r\n \"\"\"Test for the existence of the forcefield file with a few name permutations.\r\n\r\n Args:\r\n name of forcefield\r\n Returns:\r\n filename or empty string\r\n \"\"\"\r\n return test_for_file(name, \"DAT\")\r\n\r\ndef test_xml_file(name):\r\n \"\"\"Test for the existence of the forcefield file with a few name permutations.\r\n\r\n Args:\r\n name of the xml file\r\n Returns:\r\n filename or empty string\r\n \"\"\"\r\n return test_for_file(name, \"xml\")\r\n\r\n\r\ndef get_pdb_file(name):\r\n \"\"\"Obtain a PDB file.\r\n\r\n First check the path given on the command line - if that file is not\r\n available, obtain the file from the PDB webserver at http://www.rcsb.org/pdb/\r\n\r\n TODO - this should be a context manager (to close the open file)\r\n\r\n Args:\r\n name: Name of PDB file to obtain (string)\r\n\r\n Returns\r\n file: File object containing PDB file (file object)\r\n \"\"\"\r\n path = Path(name)\r\n if path.is_file():\r\n return open(path, \"rt\", encoding=\"utf-8\")\r\n else:\r\n url_path = \"https://files.rcsb.org/download/\" + path.stem + \".pdb\"\r\n _LOGGER.debug(\"Attempting to fetch PDB from %s\", url_path)\r\n resp = requests.get(url_path)\r\n if resp.status_code != 200:\r\n errstr = \"Got code %d while retrieving %s\" % (resp.status_code, url_path)\r\n raise IOError(errstr)\r\n return io.StringIO(resp.text)\r\n\r\n\r\ndef get_molecule(input_path):\r\n \"\"\"Get molecular structure information.\r\n\r\n Args:\r\n input_path: structure file PDB ID or path\r\n Returns:\r\n list of molecule records (lines)\r\n Boolean indicating whether entry is CIF\r\n Raises:\r\n RuntimeError: problems with structure file\r\n \"\"\"\r\n path = Path(input_path)\r\n input_file = get_pdb_file(input_path)\r\n is_cif = False\r\n\r\n if path.suffix.lower() == \"cif\":\r\n pdblist, errlist = cif.read_cif(input_file)\r\n is_cif = True\r\n else:\r\n pdblist, errlist = pdb.read_pdb(input_file)\r\n\r\n if len(pdblist) == 0 and len(errlist) == 0:\r\n raise RuntimeError(\"Unable to find file %s!\" % path)\r\n\r\n if len(errlist) != 0:\r\n if is_cif:\r\n _LOGGER.warning(\"Warning: %s is a non-standard CIF file.\\n\", path)\r\n else:\r\n _LOGGER.warning(\"Warning: %s is a non-standard PDB file.\\n\", path)\r\n _LOGGER.error(errlist)\r\n\r\n return pdblist, is_cif\r\n\r\n\r\ndef get_definitions(aa_path=AA_DEF_PATH, na_path=NA_DEF_PATH,\r\n patch_path=PATCH_DEF_PATH):\r\n \"\"\"Get topology definition files.\r\n\r\n Args:\r\n aa_path: likely location of amino acid topology definitions\r\n na_path: likely location of nucleic acid topology definitions\r\n patch_path: likely location of patch topology definitions\r\n\r\n Returns:\r\n Definitions object.\r\n \"\"\"\r\n aa_path_ = test_xml_file(aa_path)\r\n if not aa_path_:\r\n raise FileNotFoundError(\"Unable to locate %s\" % aa_path)\r\n na_path_ = test_xml_file(na_path)\r\n if not na_path_:\r\n raise FileNotFoundError(\"Unable to locate %s\" % na_path)\r\n patch_path_ = test_xml_file(patch_path)\r\n if not patch_path_:\r\n raise FileNotFoundError(\"Unable to locate %s\" % patch_path)\r\n with open(aa_path_, \"rt\") as aa_file:\r\n with open(na_path_, \"rt\") as na_file:\r\n with open(patch_path_, \"rt\") as patch_file:\r\n definitions = defns.Definition(aa_file=aa_file, na_file=na_file,\r\n patch_file=patch_file)\r\n return definitions\r\n","repo_name":"broadinstitute/pdb2pqr","sub_path":"pdb2pqr/input_output.py","file_name":"input_output.py","file_ext":"py","file_size_in_byte":14338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"2120609933","text":"\n\nimport csv\nfrom typing import Dict\n\nmy_dictionary = { }\n\n\"\"\"\nkeys and values\n\nexample:\nkeys = some country\nvalues = their population\n{\n 'ghana': 50000\n}\n\n\nDictionaries\n\nRead the NBA finals CSV data into one more more dictionaries as needed to complete the following:\n\n\n[x] Write a function that takes as an argument a year and returns the winner of the NBA finals that year.\n[ ] Write a function that takes as an argument a team name and returns an array of all of the years the team has won the NBA finals.\n[ ] Which teams have made it to the NBA finals but have never won?\n[ ] Print out a ranking of who has won the MVP more than once, by times one, e.g. this output:\n - 6 times: Michael Jordan\n - 3 times: Shaquille O'Neal, LeBron James\n - 2 times: \n\"\"\"\n\n\n\ndef read_csv() -> Dict:\n year_winner = {}\n with open('nba_finals.csv', 'r') as file:\n index = 0\n for line in file.readlines():\n if index == 0:\n index += 1\n continue\n items = line.split(',')\n year_winner[items[0]] = items[1]\n index += 1\n\n \n return year_winner\n\nyear_winner = read_csv()\n\ndef winner(year) -> str:\n return year_winner[year]\n\nprint(winner('1995'))\n","repo_name":"SergioB-dev/python_bootcamp","sub_path":"dictionary_practice.py","file_name":"dictionary_practice.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"21823070914","text":"from course1.week_04.Test.building_your_deep_neural_network.testCases_v2 import *\nfrom course1.week_04.Test.building_your_deep_neural_network.dnn_utils_v2 import *\n\n\n# GRADED FUNCTION: linear_backward# GRADED\n\ndef linear_backward(dZ, cache):\n \"\"\"\n Implement the linear portion of backward propagation for a single layer (layer l)\n\n Arguments:\n dZ -- Gradient of the cost with respect to the linear output (of current layer l)\n cache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n\n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n A_prev, W, b = cache\n m = A_prev.shape[1]\n\n ### START CODE HERE ### (≈ 3 lines of code)\n dW = 1 / m * np.dot(dZ, A_prev.T)\n db = 1 / m * np.sum(dZ, axis=1, keepdims=True)\n dA_prev = np.dot(W.T, dZ)\n ### END CODE HERE ###\n\n assert (dA_prev.shape == A_prev.shape)\n assert (dW.shape == W.shape)\n assert (db.shape == b.shape)\n\n return dA_prev, dW, db\n\n\n# GRADED FUNCTION: linear_activation_backward\n\ndef linear_activation_backward(dA, cache, activation):\n \"\"\"\n Implement the backward propagation for the LINEAR->ACTIVATION layer.\n\n Arguments:\n dA -- post-activation gradient for current layer l\n cache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n activation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\n Returns:\n dA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n dW -- Gradient of the cost with respect to W (current layer l), same shape as W\n db -- Gradient of the cost with respect to b (current layer l), same shape as b\n \"\"\"\n linear_cache, activation_cache = cache\n\n if activation == \"relu\":\n ### START CODE HERE ### (≈ 2 lines of code)\n dZ = relu_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n ### END CODE HERE ###\n\n elif activation == \"sigmoid\":\n ### START CODE HERE ### (≈ 2 lines of code)\n dZ = sigmoid_backward(dA, activation_cache)\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n ### END CODE HERE ###\n\n return dA_prev, dW, db\n\n\n# GRADED FUNCTION: L_model_backward\n\ndef L_model_backward(AL, Y, caches):\n \"\"\"\n Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n\n Arguments:\n AL -- probability vector, output of the forward propagation (L_model_forward())\n Y -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n caches -- list of caches containing:\n every cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n the cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n\n Returns:\n grads -- A dictionary with the gradients\n grads[\"dA\" + str(l)] = ...\n grads[\"dW\" + str(l)] = ...\n grads[\"db\" + str(l)] = ...\n \"\"\"\n grads = {}\n L = len(caches) # the number of layers\n m = AL.shape[1]\n Y = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n\n # Initializing the backpropagation\n ### START CODE HERE ### (1 line of code)\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n ### END CODE HERE ###\n\n # Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"AL, Y, caches\". Outputs: \"grads[\"dAL\"], grads[\"dWL\"], grads[\"dbL\"]\n ### START CODE HERE ### (approx. 2 lines)\n current_cache = caches[L - 1]\n grads[\"dA\" + str(L)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL, current_cache,\n 'sigmoid')\n ### END CODE HERE ###\n\n for l in reversed(range(L - 1)):\n # lth layer: (RELU -> LINEAR) gradients.\n # Inputs: \"grads[\"dA\" + str(l + 2)], caches\". Outputs: \"grads[\"dA\" + str(l + 1)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)]\n ### START CODE HERE ### (approx. 5 lines)\n current_cache = caches[l]\n dA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads[\"dA\" + str(l + 2)], current_cache, 'relu')\n grads[\"dA\" + str(l + 1)] = dA_prev_temp\n grads[\"dW\" + str(l + 1)] = dW_temp\n grads[\"db\" + str(l + 1)] = db_temp\n ### END CODE HERE ###\n\n return grads\n\n\n# GRADED FUNCTION: update_parameters\n\ndef update_parameters(parameters, grads, learning_rate):\n \"\"\"\n Update parameters using gradient descent\n\n Arguments:\n parameters -- python dictionary containing your parameters\n grads -- python dictionary containing your gradients, output of L_model_backward\n\n Returns:\n parameters -- python dictionary containing your updated parameters\n parameters[\"W\" + str(l)] = ...\n parameters[\"b\" + str(l)] = ...\n \"\"\"\n\n L = len(parameters) // 2 # number of layers in the neural network\n\n # Update rule for each parameter. Use a for loop.\n ### START CODE HERE ### (≈ 3 lines of code)\n for l in range(L):\n parameters[\"W\" + str(l + 1)] = parameters[\"W\" + str(l + 1)] - learning_rate * grads[\"dW\" + str(l + 1)]\n parameters[\"b\" + str(l + 1)] = parameters[\"b\" + str(l + 1)] - learning_rate * grads[\"db\" + str(l + 1)]\n ### END CODE HERE ###\n\n return parameters\n\nif __name__ == '__main__':\n # Set up some test inputs\n dZ, linear_cache = linear_backward_test_case()\n\n dA_prev, dW, db = linear_backward(dZ, linear_cache)\n print(\"dA_prev = \" + str(dA_prev))\n print(\"dW = \" + str(dW))\n print(\"db = \" + str(db))\n\n AL, linear_activation_cache = linear_activation_backward_test_case()\n\n dA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation=\"sigmoid\")\n print(\"sigmoid:\")\n print(\"dA_prev = \" + str(dA_prev))\n print(\"dW = \" + str(dW))\n print(\"db = \" + str(db) + \"\\n\")\n\n dA_prev, dW, db = linear_activation_backward(AL, linear_activation_cache, activation=\"relu\")\n print(\"relu:\")\n print(\"dA_prev = \" + str(dA_prev))\n print(\"dW = \" + str(dW))\n print(\"db = \" + str(db))\n\n AL, Y_assess, caches = L_model_backward_test_case()\n grads = L_model_backward(AL, Y_assess, caches)\n print(\"dW1 = \" + str(grads[\"dW1\"]))\n print(\"db1 = \" + str(grads[\"db1\"]))\n print(\"dA1 = \" + str(grads[\"dA1\"]))\n\n parameters, grads = update_parameters_test_case()\n parameters = update_parameters(parameters, grads, 0.1)\n\n print(\"W1 = \" + str(parameters[\"W1\"]))\n print(\"b1 = \" + str(parameters[\"b1\"]))\n print(\"W2 = \" + str(parameters[\"W2\"]))\n print(\"b2 = \" + str(parameters[\"b2\"]))\n","repo_name":"cxmhfut/DeepLearning.ai","sub_path":"course1/week_04/Test/building_your_deep_neural_network/backward_propagation.py","file_name":"backward_propagation.py","file_ext":"py","file_size_in_byte":6990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"34954868131","text":"# LINK: https://leetcode.com/problems/climbing-stairs/\n\nclass Solution(object):\n def climbStairs(self, n):\n # Constraints\n # - 1 <= n <= 45\n\n # Topic: Dynamic Programming\n # This could also be a Math, Dynamic Programming, or Memoization problem.\n\n # Approach 1 (dynamic programming):\n # - Define a results array that will host the answer.\n # - Treat the n == 1 case and n >= 2 case.\n # - Loop from 2..n.\n # - Update the results array.\n # - Return the right most element in the results array.\n\n # TC: O(N)\n # SC: O(N)\n\n \"\"\"\n res = [0]*n\n if n == 1:\n res[0] = 1\n elif n >= 2:\n res[0] = 1\n res[1] = 2\n \n for i in range(2,n):\n res[i] = res[i-1]+res[i-2]\n \n return res[n-1]\n \"\"\"\n\n # Approach 2 (iterative):\n # - Treat the n == 1 case.\n # - Define first and second and set them to 1,2.\n # - Loop from 3..n+1.\n # - Create a variable third that's first+second.\n # - Update first; update second.\n # - Return second.\n\n # TC: O(N)\n # SC: O(1)\n\n if n == 1:\n return 1\n \n first = 1\n second = 2\n\n for i in range(3,n+1):\n third = first+second\n first = second\n second = third\n \n return second\n","repo_name":"yli12313/Technology-Grand-Challenge","sub_path":"Interview-Prep-2021/Leetcode/70_climbing_stairs.py","file_name":"70_climbing_stairs.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"39759374905","text":"class Solution:\n def longestValidParentheses(self, s: str) -> int:\n stack = [-1]\n max_len = 0\n for ind in range(len(s)):\n if stack[-1] == -1 or s[ind] == \"(\":\n stack.append(ind)\n elif s[stack[-1]] == \"(\":\n stack.pop()\n max_len = max(max_len, ind - stack[-1])\n else:\n stack.append(ind)\n return max_len\n \n ","repo_name":"Natnael16/competitiveprogramming","sub_path":"0032-longest-valid-parentheses/0032-longest-valid-parentheses.py","file_name":"0032-longest-valid-parentheses.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"5366683881","text":"import stop_list\r\nimport math\r\nimport re\r\nimport sys\r\n\r\n# NOTE: for tokenization I used the built in .split(' ') method\r\n\r\nregex = re.compile(r'([0-9]+)|([\\.,\\?\\!\\(\\)\\[\\]\\/])')\t# regex used to remove numbers and punctuation\r\nstoplist = stop_list.closed_class_stop_words\t# list of stop words\r\n\r\n###########################################################################\r\n# FORMULAE\r\n###########################################################################\r\n\r\n# INVERSE DOCUMENT FREQUENCY\r\ndef idf(i, c):\r\n\tn = len(c)\t# total number of documents in collection c\r\n\tn_i = 0\t\t# number of documents where term i occurs\r\n\r\n\tfor (k, j) in c.items():\r\n\t\tif i in j:\r\n\t\t\tn_i += 1\t# add to n_i the number of times term i occurs in the current document (j)\r\n\r\n\tif n_i == 0 or n == 0:\r\n\t\treturn 0\r\n\r\n\tres = math.log(n / n_i)\r\n\treturn res\r\n\r\n# TERM FREQUENCY\r\ndef tf(i, j):\t# find frequency of term i in document j\r\n\treturn j.count(i)\r\n\r\n# COSINE SIMILARITY: following the tf-idf weighted cosine (equation 23.12 in Jurafsky and Martin)\r\ndef cosine_similarity(qFeature, dFeature, comp):\r\n\r\n\tnumerator = 0\r\n\tdenomQ = 0\r\n\tdenomD = 0\r\n\r\n\tfor (term, score) in qFeature.items():\r\n\t\tdenomQ += (score * score)\r\n\r\n\tif denomQ == 0:\t# short circuit\r\n\t\treturn 0\r\n\r\n\tfor (term, score) in dFeature.items():\r\n\t\tdenomD += (score * score)\r\n\r\n\tif denomD == 0:\t# short circuit\r\n\t\treturn 0\r\n\r\n\tfor (term, score) in comp.items():\r\n\t\tif score == 0:\r\n\t\t\tcontinue\r\n\t\tnumerator += (score * dFeature[term])\t# summation (tf(w, q) * tf(w, d) * idf(w)^2)\r\n\r\n\r\n\tdenominator = math.sqrt(denomQ) * math.sqrt(denomD)\r\n\r\n\treturn numerator / denominator\r\n\r\n\r\n\r\n###########################################################################\r\n\r\n\r\n# generate collection of documents from input file\r\ndef generate_collection(filepath):\r\n\tcollection = dict()\r\n\tlines = []\r\n\r\n\twith open(filepath, 'r') as f:\r\n\t\tfor line in f:\r\n\t\t\tlines.append(line)\r\n\r\n\r\n\tisContent = False\r\n\tcurrentDoc = None\r\n\r\n\tfor line in lines:\r\n\t\tif \".I\" in line:\r\n\t\t\tisContent = False\r\n\t\t\tlst = line.split(' ')\r\n\t\t\tcurrentDoc = int(lst[1].replace('\\n', ''))\r\n\t\t\tcollection[currentDoc] = []\r\n\t\t\tcontinue\r\n\t\tif \".W\" in line:\r\n\t\t\tisContent = True\r\n\t\t\tcontinue\r\n\t\tif isContent:\r\n\t\t\tif \".I\" not in line:\r\n\t\t\t\tline = regex.sub('', line)\r\n\t\t\t\tcollection[currentDoc].append(line)\r\n\t\t\tcontinue\r\n\r\n\tfor k in collection.iterkeys():\r\n\t\tcollection[k] = (' ').join(collection[k])\r\n\r\n\treturn collection\r\n\r\n\r\n# 2. For each query, create a feature vector representing the words in the query:\r\ndef generate_feature_vector(tfScores, idfScores):\t# generate map of unique words (and their corresponding tf-idf values) in the document given by docID\r\n\r\n\tfeature_vec = dict()\r\n\r\n\tfor (docid, docvec) in tfScores.items():\r\n\t\tfeature_vec[docid] = dict()\r\n\t\tfor (term, score) in docvec.items():\r\n\t\t\tfeature_vec[docid][term] = score * idfScores[term]\r\n\r\n\treturn feature_vec\r\n\r\n\r\n# 3. Compute the IDF scores for each word in the collection of abstracts\r\ndef idf_dict(collection):\r\n\r\n\tscores = dict()\t# map of idf scores\r\n\r\n\tfor doc in collection.values():\r\n\r\n\t\tfor term in doc.split(' '):\r\n\t\t\tif term == '' or term in stoplist or term in scores:\r\n\t\t\t\tcontinue\t# don't add any empty strings, stop words or words that are already present\r\n\t\t\tscores[term] = idf(term, collection)\r\n\r\n\treturn scores\r\n\r\n# 4. Count the number of instances of each non-stop-word in each abstract\r\ndef tf_dict(collection):\r\n\r\n\tscores = dict()\r\n\r\n\tfor (i, w) in collection.items():\r\n\t\tscores[i] = dict()\r\n\r\n\t\tfor term in w.split(' '):\r\n\t\t\tif term == '' or term in stoplist or term in scores[i]:\r\n\t\t\t\tcontinue\r\n\t\t\tscores[i][term] = tf(term, w)\r\n\r\n\treturn scores \t# return nested dictionary mapping a dictionary of unique words and their tf scores to each document id in collection\r\n\r\n\r\n# run the final program, returns output dict\r\ndef final_scores(queryfile, abstractfile):\r\n\tabstracts = generate_collection(abstractfile)\r\n\tqueries = generate_collection(queryfile)\r\n\r\n\tqTF = tf_dict(queries)\r\n\tqIDF = idf_dict(queries)\r\n\r\n\taTF = tf_dict(abstracts)\r\n\taIDF = idf_dict(abstracts)\r\n\r\n\tqueryvec = generate_feature_vector(qTF, qIDF)\r\n\tabstractvec = generate_feature_vector(aTF, aIDF)\r\n\r\n\tfinalvec = dict()\r\n\r\n\tfor (i, q) in queryvec.items():\t\t# for each query in queryvec\r\n\r\n\t\tfinalvec[i] = []\r\n\r\n\t\tfor (j, a) in abstractvec.items():\t# for each abstract in abstractvec\r\n\t\t\tcomp = compare_vector(qTF[i], a, aIDF)\t# tfidf scores of all common words in both abstract a and query q\r\n\t\t\tsimilarity = cosine_similarity(q, a, comp)\r\n\r\n\t\t\tfinalvec[i].append((j, similarity))\r\n\t\tfinalvec[i] = sorted(finalvec[i], key=lambda x: x[1], reverse=True)\r\n\r\n\treturn finalvec\r\n\r\n\r\n# generate vector of term scores by comparing a query to an abstract\r\ndef compare_vector(qtf, aVec, aidf):\t# compare feature vec and abstract vec\r\n\tnew_vec = dict()\t\t\t\t# query vec should just be list of words??\r\n\tfor (word, score) in qtf.items():\r\n\t\tif word in aVec.keys():\r\n\t\t\tnew_vec[word] = score * aidf[word]\r\n\t\t\tcontinue\r\n\t\tnew_vec[word] = 0\r\n\r\n\treturn new_vec\r\n\r\n\r\n####################################################################\r\n\r\nqueryfile = sys.argv[1]\r\nabstractfile = sys.argv[2]\r\n\r\noutputfile = sys.argv[3]\r\n\r\nvector = final_scores(queryfile, abstractfile)\r\n\r\nwith open(outputfile, 'w') as f:\r\n\tfor (q, vec) in vector.items():\r\n\t\tfor (a, sim) in vec:\r\n\t\t\tf.write(\"%d %d %f\\n\" % (q, a, sim))\r\n\r\n\r\n\r\n\r\n","repo_name":"annabfenske/Natural-Language-Processing-FA16","sub_path":"homework 5/information_retrieval.py","file_name":"information_retrieval.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"3609992994","text":"#! /usr/bin/python3\n# Author: Wayne Robinson\n# Number: 21205974\n# Python Script Assignment1\n# Script: Question1.py\n\n# Gunners list containing players second names declared\ngunners = ['ljungberg', 'pires', 'vieira', 'bergkamp', 'henri',\n'wright', 'adams', 'overmars', 'campbell', 'kanu', 'petit', 'cole', 'anelka']\n\ndef display_anwers():\n print(\"\\n===================================================\")\n\n#=================== Question 1 Part A =========================\n# Function declaration to find the required letter.\ndef find_item_number(gunners):\n # Initilise counter variable.\n counter = 0\n # For loop to interate through list the lenght of gunners list.\n for item in range(len(gunners)):\n\n # use counter function to count the occurances of letter 'e'.\n counter = counter + gunners[item].count('e')\n\n # Print resulting count value to the user.\n print(\"The gunners list has\", counter ,\"items with an \\'e'\")\n\n#=================== Question 1 Part B =========================\n# Function declaration to print each item on a seprate line with the lenght.\ndef count_length_of_each_item(gunners):\n display_anwers()\n # For loop to interate through list,\n # interating through each item counting each letter.\n for item in range(len(gunners)):\n print(gunners[item], \"has\", len(gunners[item]), \"letters\")\n\n#=================== Question 1 Part C =========================\n# Function declaration to print each item on a seprate line with the lenght.\n\ndef new_list_less_then_6(gunners):\n\n newgunners = []\n # For loop to interate through list,\n # interating through each item counting each letter.\n for item in range(len(gunners)):\n\n count = len(gunners[item])\n if(count < 6 ):\n newgunners.append(gunners[item])\n else:\n pass\n\n display_anwers()\n print(newgunners)\n\n#=================== Question 1 Part D =========================\n# Function declaration to filter names >= 8, and remove the last letter.\n\ndef length_greater_than_equal(gunners):\n display_anwers()\n i = 0\n while i < len(gunners):\n count = len(gunners[i])\n name = gunners[i]\n i = i + 1\n\n if(count >= 8 ):\n print(name[0:count-1])\n else:\n pass\n\n#=================== Question 1 Part E =========================\n# Function declaration to find the longest and shortest names in list.\n\ndef longest_Shortest_Words(gunners):\n display_anwers()\n longest_Names = len(gunners[0])\n longest_Word = []\n\n shortest_Names = len(gunners[0])\n shortest_Word = []\n\n for item in gunners:\n\n if len(item) > longest_Names:\n longest_Names = len(item)\n longest_Names = [item]\n\n elif len(item) == longest_Names:\n longest_Word.append(item)\n\n if len(item) < shortest_Names:\n shortest_Names = len(item)\n shortest_Word = [item]\n\n elif len(item) == shortest_Names:\n shortest_Word.append(item)\n\n print(\"The longest words are: \", longest_Word)\n print(\"The shortest words are: \", shortest_Word)\n display_anwers()\n#=================== Question 1 Complete =========================\ndisplay_anwers()\n\n# Function call to find item occurances (Question 1 part A)\nfind_item_number(gunners)\n\n# Function call to find item letters (Question 1 part B)\ncount_length_of_each_item(gunners)\n\n# Function call to find items with less then 6 letters (Question 1 part C)\nnew_list_less_then_6(gunners)\n\n# Function call to find items with greater 8 (Question 1 part D)\nlength_greater_than_equal(gunners)\n\n# Function call to find longest and shortest items (Question 1 part E)\nlongest_Shortest_Words(gunners)\n","repo_name":"WayneRobbo/Robinson_Wayne_21205974_Comp40120_Assignment1","sub_path":"Question1.py","file_name":"Question1.py","file_ext":"py","file_size_in_byte":3703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"33520880236","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"Test Dataframe extension.\"\"\"\n\nfrom hdfs.util import HdfsError, temppath\nfrom json import loads\nfrom test.util import _IntegrationTest\nimport os.path as osp\n\ntry:\n from hdfs.ext.avro import AvroReader\n from hdfs.ext.dataframe import read_dataframe, write_dataframe\n from pandas.testing import assert_frame_equal\n import pandas as pd\nexcept ImportError:\n SKIP = True\nelse:\n SKIP = False\n\n\nclass _DataFrameIntegrationTest(_IntegrationTest):\n\n dpath = osp.join(osp.dirname(__file__), 'dat')\n records = None\n df = None\n\n @classmethod\n def setup_class(cls):\n if SKIP:\n return\n super(_DataFrameIntegrationTest, cls).setup_class()\n with open(osp.join(cls.dpath, 'weather.jsonl')) as reader:\n cls.records = [loads(line) for line in reader]\n cls.df = pd.DataFrame.from_records(cls.records)\n\n\nclass TestReadDataFrame(_DataFrameIntegrationTest):\n\n def test_read(self):\n self.client.upload('weather.avro', osp.join(self.dpath, 'weather.avro'))\n assert_frame_equal(\n read_dataframe(self.client, 'weather.avro'),\n self.df\n )\n\n\nclass TestWriteDataFrame(_DataFrameIntegrationTest):\n\n def test_write(self):\n write_dataframe(self.client, 'weather.avro', self.df)\n with AvroReader(self.client, 'weather.avro') as reader:\n assert list(reader) == self.records\n\n\nclass TestReadWriteDataFrame(_DataFrameIntegrationTest):\n\n def test_column_order(self):\n # Column order should be preserved, not just alphabetical.\n df = self.df[['temp', 'station', 'time']]\n write_dataframe(self.client, 'weather-ordered.avro', df)\n assert_frame_equal(\n read_dataframe(self.client, 'weather-ordered.avro'),\n df\n )\n","repo_name":"mtth/hdfs","sub_path":"test/test_ext_dataframe.py","file_name":"test_ext_dataframe.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":259,"dataset":"github-code","pt":"79"} +{"seq_id":"23072796494","text":"from datetime import date\nimport random\nclass Bank(object):\n def __init__(self, CID):\n self.TID = 0\n self.CID = CID\n self.AccountName = ''\n self.BSB = '123-456'\n self.AccountNo = ''\n self.Balance = 0\n\n def create_account(self):\n \"\"\"This function extract customer details in customer.txt to generate a new bank account\"\"\"\n # extract information from customer.txt into a dict\n dict = {}\n dict_string = \"\"\n dict['ID'] = []\n dict['Name'] = []\n dict['Age'] = []\n dict['Gender']=[]\n dict['Password']=[]\n dict['NationalID']=[]\n with open('customer.txt', 'r') as customer_file:\n for line in customer_file:\n dict_string += line\n dict_list = dict_string.split('\\n')\n dict_list.remove('')\n for el in dict_list:\n list_el = el.split()\n dict['ID'].append(list_el[0])\n dict['Name'].append(list_el[1])\n dict['Age'].append(list_el[2])\n dict['Gender'].append(list_el[3])\n dict['Password'].append(list_el[4])\n dict['NationalID'].append(list_el[5])\n # find account name in dict base on provided Customer ID (CID) via ID input when customer signing in\n self.AccountName = dict['Name'][int(self.CID)-1]\n # Define transactionID & AccountNo\n # AccountNo has 9 number which consist of TID as very first numbers and the remaining is randomly generated\n try:\n with open('Account.txt', 'r') as account_file:\n self.TID = len(account_file.readlines()) + 1\n self.AccountNo = (str(self.TID) + str(random.randint(10**7,10**8-1)))[0:10]\n except FileNotFoundError:\n self.TID = 1\n self.AccountNo = str(self.TID) + str(random.randint(10**7,10**8-1))\n\n def view_account(self):\n \"\"\"View all accounts of the same Customer ID\"\"\"\n\n dict2_string = \"\"\n dict2['ACID'] = []\n dict2['CID'] = []\n dict2['Name'] = []\n dict2['Type'] = []\n dict2['BSB']=[]\n dict2['AccountNo']=[]\n dict2['Balance']=[]\n try:\n account_file = open('Account.txt', 'r')\n account_file.close()\n except FileNotFoundError:\n account_file = open('Account.txt', 'a+')\n account_file.close()\n with open('Account.txt', 'r') as account_file:\n for line in account_file:\n dict2_string += line\n dict2_list = dict2_string.split('\\n')\n dict2_list.remove('')\n\n for el in dict2_list:\n list2_el = el.split()\n dict2['ACID'].append(list2_el[0])\n dict2['CID'].append(list2_el[1])\n dict2['Name'].append(list2_el[2])\n dict2['Type'].append(list2_el[3])\n dict2['BSB'].append(list2_el[4])\n dict2['AccountNo'].append(list2_el[5])\n dict2['Balance'].append(list2_el[6])\n\n dict3['Type'] = []\n dict3['BSB'] = []\n dict3['AccountNo'] =[]\n dict3['Balance']=[]\n dict3['OrderNo']=[]\n dict3['ACID']=[]\n\n print(\"{0:-^20s}{1:-^15s}{2:-^15s}{3:-^15s}{4:-^15s}---\".format('Select Options', 'Account Type','BSB','AccountNo','Balance'))\n count = 1\n for index,CID in enumerate(dict2['CID']):\n if CID == self.CID:\n\n dict3['Type'].append(dict2['Type'][index])\n dict3['BSB'].append(dict2['BSB'][index])\n dict3['AccountNo'].append(dict2['AccountNo'][index])\n dict3['Balance'].append(dict2['Balance'][index])\n dict3['OrderNo'].append(count)\n dict3['ACID'].append(dict2['ACID'][index])\n print(\"{0:^20}{1:^15s}{2:^15s}{3:^15s}{4:^15s}\".format(count, dict2['Type'][index], dict2['BSB'][index], dict2['AccountNo'][index], dict2['Balance'][index]))\n\n count+=1\n return dict2, dict3,count\n def view_transaction(self,option):\n \"\"\"View transaction history of the same CustomerID(CID) and Account CreationID(ACID)\"\"\"\n try:\n transaction_file = open('transaction.txt','r')\n transaction_file.close()\n except FileNotFoundError:\n transaction_file = open('transaction.txt','w')\n print('This is transaction history',file = transaction_file)\n transaction_file.close()\n with open('transaction.txt','r+') as transaction_file:\n dict4_string = ''\n for line in transaction_file:\n dict4_string += line\n dict4_list = dict4_string.split('\\n')\n dict4_list.remove('')\n if 'This is transaction history' in dict4_list:\n dict4_list.remove('This is transaction history')\n print(\"{0:-^15s}{1:-^15s}{2:-^15s}{3:-^15s}{4:-^15s}{5:-^15s}{6:-^15s}{7:-^15s}{8:-^15s}---\".format('TransactionID', 'AccountID','Date','CustomerID','Activity','BSB','AccountNo','Amount','Balance'))\n for el in dict4_list:\n if dict3['ACID'][option -1] == el.split()[1]:\n\n el1,el2,el3,el4,el5,el6,el7,el8,el9 = el.split()\n print(\"{0:^15s}{1:^15s}{2:^15s}{3:^15s}{4:^15s}{5:^15s}{6:^15s}{7:^15s}{8:^15s}\".format(el1,el2,el3,el4,el5,el6,el7,el8,el9))\n\n\n def withdraw_transaction_update(self,type,request_amount,select_account):\n \"\"\"Update withdrawal transactions on transaction.txt and account.txt\"\"\"\n # only withdraw within daily limit $100 (balance +withdraw amount <=100) for checking account if balance = 0\n # saving account: only withdraw or transfer once per month\n # transaction.txt: TID,date, CID,type,BSB,AccountNo,amount,balance\n try:\n with open('transaction.txt','r') as transaction_file:\n TID = len(transaction_file.readlines()) + 1\n except FileNotFoundError:\n TID = 1\n\n with open('transaction.txt','a+') as transaction_file:\n withdraw_amount = request_amount\n CID = self.CID\n ACID = dict3['ACID'][select_account-1]\n BSB = dict3['BSB'][select_account-1]\n AccountNo = dict3['AccountNo'][select_account-1]\n Balance = int(dict3['Balance'][select_account-1]) - withdraw_amount\n transaction_date = date.today()\n print(TID,ACID,transaction_date,CID,type,BSB,AccountNo,withdraw_amount,Balance,file = transaction_file)\n\n #update account.txt balance: update dict2 then rewrite dict2 on account.txt as the original order\n #TID,CID,AccountName,Type,BSB,AccountNo,Balance\n dict2['Balance'][int(ACID)-1] = Balance\n n = 0\n with open('Account.txt','w') as account_file:\n while True:\n if n in range (0,len(dict2['ACID'])):\n print(dict2['ACID'][n],dict2['CID'][n],dict2['Name'][n],dict2['Type'][n],dict2['BSB'][n],dict2['AccountNo'][n],dict2['Balance'][n],file = account_file)\n n+=1\n else:\n break\n print( type +\" successfully!\")\n def deposit_transaction_update(self,request_amount,select_account):\n \"\"\"Update deposit transaction on transaction.txt and account.txt \"\"\"\n try:\n with open('transaction.txt','r') as transaction_file:\n TID = len(transaction_file.readlines()) + 1\n except FileNotFoundError:\n TID = 1\n with open('transaction.txt','a+') as transaction_file:\n deposit_amount = request_amount\n CID = self.CID\n type = \"deposit\"\n ACID = dict3['ACID'][select_account-1]\n BSB = dict3['BSB'][select_account-1]\n AccountNo = dict3['AccountNo'][select_account-1]\n Balance = int(dict3['Balance'][select_account-1]) + deposit_amount\n transaction_date = date.today()\n print(TID,ACID,transaction_date,CID,type,BSB,AccountNo,deposit_amount,Balance,file = transaction_file)\n\n #update account.txt balance: update dict2 then rewrite dict2 on account.txt as the original order\n #TID,CID,AccountName,Type,BSB,AccountNo,Balance\n dict2['Balance'][int(ACID)-1] = Balance\n n = 0\n with open('Account.txt','w') as account_file:\n while True:\n if n in range (0,len(dict2['ACID'])):\n print(dict2['ACID'][n],dict2['CID'][n],dict2['Name'][n],dict2['Type'][n],dict2['BSB'][n],dict2['AccountNo'][n],dict2['Balance'][n],file = account_file)\n n+=1\n else:\n break\n print(\"Deposit successfully!\")\n def transfer_transaction_update(self,request_amount,transfer_from,transfer_to):\n \"\"\"Update transfer transaction on account.txt and transaction.txt\"\"\"\n try:\n with open('transaction.txt','r') as transaction_file:\n TID = len(transaction_file.readlines()) + 1\n except FileNotFoundError:\n TID = 1\n with open('transaction.txt','a+') as transaction_file:\n transfer_amount = request_amount\n CID = self.CID\n type1 = \"transfer-from\"\n type2 ='transfer-to'\n ACID1 = dict3['ACID'][transfer_from-1]\n ACID2 = dict3['ACID'][transfer_to-1]\n BSB1 = dict3['BSB'][transfer_from-1]\n BSB2 = dict3['BSB'][transfer_to-1]\n AccountNo1 = dict3['AccountNo'][transfer_from-1]\n AccountNo2 = dict3['AccountNo'][transfer_to-1]\n Balance1 = int(dict3['Balance'][transfer_from-1]) - transfer_amount\n Balance2 = int(dict3['Balance'][transfer_to-1]) + transfer_amount\n transaction_date = date.today()\n print(TID,ACID1,transaction_date,CID,type1,BSB1,AccountNo1,transfer_amount,Balance1,file = transaction_file)\n print(TID+1,ACID2,transaction_date,CID,type2,BSB2,AccountNo2,transfer_amount,Balance2,file = transaction_file)\n #update account.txt balance: update dict2 then rewrite dict2 on account.txt as the original order\n #TID,CID,AccountName,Type,BSB,AccountNo,Balance\n dict2['Balance'][int(ACID1)-1] = Balance1\n dict2['Balance'][int(ACID2)-1] = Balance2\n n = 0\n with open('Account.txt','w') as account_file:\n while True:\n if n in range (0,len(dict2['ACID'])):\n print(dict2['ACID'][n],dict2['CID'][n],dict2['Name'][n],dict2['Type'][n],dict2['BSB'][n],dict2['AccountNo'][n],dict2['Balance'][n],file = account_file)\n n+=1\n else:\n break\n print(\"Transfer successfully!\")\n\n def __str__(self):\n return \" TID:{} \\n CID:{} \\n AccountName:{} \\n BSB:{}\\n AccountNo:{}\\n Balance:{}\\n\".format(self.TID,self.CID,self.AccountName,self.BSB,self.AccountNo,self.Balance)\n\nclass SavingAccount(Bank):\n def __init__(self,CID):\n Bank.__init__(self,CID)\n self.Type = 'SA'\n\n def create_account(self):\n \"\"\"Creating saving account\"\"\"\n Bank.create_account(self)\n with open('Account.txt', 'a+') as account_file:\n print(self.TID,self.CID,self.AccountName,self.Type,self.BSB,self.AccountNo,self.Balance,file=account_file)\n\n def withdraw(self,request_amount,select_account):\n \"\"\"withdraw from a saving account. Transaction is restricted for only once per month, account need balance >o\"\"\"\n if dict3['Type'][select_account-1]=='SA':\n # check the account balance\n if int(dict3['Balance'][select_account -1]) = the amount requested\n # open transaction history and check the past transactions of the relevant account\n else:\n try:\n transaction_file = open('transaction.txt','r')\n transaction_file.close()\n except FileNotFoundError:\n transaction_file = open('transaction.txt','w')\n print('This is transaction history',file = transaction_file)\n transaction_file.close()\n with open('transaction.txt','r+') as transaction_file:\n dict4_string = ''\n for line in transaction_file:\n dict4_string += line\n dict4_list = dict4_string.split('\\n')\n dict4_list.remove('')\n if 'This is transaction history' in dict4_list:\n dict4_list.remove('This is transaction history')\n countloop = 0\n for el in dict4_list:\n list4_el = el.split()\n countloop +=1\n if list4_el[1] == dict3['ACID'][select_account -1] and (list4_el[4] in ['withdraw','transfer-from','send']) and int(list4_el[2].split('-')[1]) == date.today().month and int(list4_el[2].split('-')[0])==date.today().year:\n print('Request is declined.Withdrawal limit of the month has been reached ')\n break\n else:\n if countloop == len(dict4_list):\n type = 'withdraw'\n Bank.withdraw_transaction_update(self,type,request_amount,select_account)\n break\n if countloop == 0:\n type = 'withdraw'\n Bank.withdraw_transaction_update(self,type,request_amount,select_account)\n\n def send(self,request_amount,select_account):\n \"\"\"send money to other person from a saving account\"\"\"\n if dict3['Type'][select_account-1]=='SA':\n # check the account balance\n if int(dict3['Balance'][select_account -1]) = the amount requested\n # open transaction history and check the past transactions of the relevant account\n else:\n try:\n transaction_file = open('transaction.txt','r')\n transaction_file.close()\n except FileNotFoundError:\n transaction_file = open('transaction.txt','w')\n print('This is transaction history',file = transaction_file)\n transaction_file.close()\n with open('transaction.txt','r+') as transaction_file:\n dict4_string = ''\n for line in transaction_file:\n dict4_string += line\n dict4_list = dict4_string.split('\\n')\n dict4_list.remove('')\n\n if 'This is transaction history' in dict4_list:\n dict4_list.remove('This is transaction history')\n\n countloop = 0\n for el in dict4_list:\n list4_el = el.split()\n countloop +=1\n if list4_el[1] == dict3['ACID'][select_account -1] and (list4_el[4] in ['withdraw','transfer-from','send']) and int(list4_el[2].split('-')[1]) == date.today().month and int(list4_el[2].split('-')[0])==date.today().year:\n print('Request is declined.Send limit of the month has been reached ')\n break\n else:\n if countloop == len(dict4_list):\n type = 'send'\n Bank.withdraw_transaction_update(self,type,request_amount,select_account)\n break\n if countloop == 0:\n type = 'send'\n Bank.withdraw_transaction_update(self,type,request_amount,select_account)\n\n\n\n def __str__(self):\n return \" TID:{} \\n CID:{} \\n AccountName:{} \\n BSB:{}\\n AccountNo:{}\\n Balance:{}\\n Type:{}\\n\".format(self.TID,self.CID,self.AccountName,self.BSB,self.AccountNo,self.Balance,self.Type)\n\nclass CheckingAccount(Bank):\n def __init__(self,CID):\n Bank.__init__(self,CID)\n self.Type = 'CA'\n\n def create_account(self):\n \"\"\"Creating a checking account\"\"\"\n Bank.create_account(self)\n with open('Account.txt', 'a+') as account_file:\n print(self.TID,self.CID,self.AccountName,self.Type,self.BSB,self.AccountNo,self.Balance,file=account_file)\n\n def withdraw(self,request_amount,select_account):\n \"\"\"Withdraw from a checking account\"\"\"\n if request_amount - int(dict3['Balance'][select_account -1]) >100:\n print('Request is declined.Credit limit has been reached, please top up to avoid fees')\n else:\n type = 'withdraw'\n Bank.withdraw_transaction_update(self,type,request_amount,select_account)\n\n def send(self,request_amount,select_account):\n \"\"\"send money from a checking account. Credit limit is $100\"\"\"\n\n if request_amount - int(dict3['Balance'][select_account -1]) >100:\n print('Request is declined.Credit limit has been reached, please top up to avoid fees')\n else:\n type = 'send'\n Bank.withdraw_transaction_update(self,type,request_amount,select_account)\n\n def __str__(self):\n return \" TID:{} \\n CID:{} \\n AccountName:{} \\n BSB:{}\\n AccountNo:{}\\n Balance:{}\\n Type:{}\\n\".format(self.TID,self.CID,self.AccountName,self.BSB,self.AccountNo,self.Balance,self.Type)\n\nclass Customer(object):\n def __init__(self,Name,Age,Gender,Pass,NationalID):\n self.Name = Name\n self.Age = Age\n self.Gender = Gender\n self.Pass = Pass\n self.ID = 0\n self.NationalID = NationalID\n def register_customer(self):\n \"\"\"registering a new customer\"\"\"\n try: # check if NationalID is exit in customer.txt or not\n with open('customer.txt', 'r') as customer_file:\n self.ID = len(customer_file.readlines()) + 1\n except FileNotFoundError:\n\n self.ID = 1\n with open('customer.txt', 'a+') as customer_file:\n dict = {}\n dict_string = \"\"\n dict['NationalID']=[]\n with open('customer.txt', 'r') as customer_file:\n for line in customer_file:\n dict_string += line\n dict_list = dict_string.split('\\n')\n dict_list.remove('')\n\n for el in dict_list:\n list_el = el.split()\n dict['NationalID'].append(list_el[5])\n\n if str(self.NationalID) in dict['NationalID']:\n print('You arealdy registered with CatBank.Please sign in with your ID and password')\n else:\n with open('customer.txt', 'a+') as customer_file:\n print(self.ID,self.Name,self.Age,self.Gender,self.Pass,self.NationalID,file=customer_file)\n print('Your userID is:',self.ID)\n print('Register successful')\n def sign_in(self,IDinput,passinput):\n \"\"\"sigining in a customer with provided ID and password\"\"\"\n # extract details from customer.txt to validate ID and password\n dict = {}\n dict_string = \"\"\n dict['ID'] = []\n dict['Name']=[]\n dict['Password']=[]\n dict['Age']=[]\n #avoiding FileNotFoundError\n try:\n customer_file = open('customer.txt', 'r')\n customer_file.close()\n except FileNotFoundError:\n customer_file = open('customer.txt','a+')\n customer_file.close()\n with open('customer.txt', 'r') as customer_file:\n for line in customer_file:\n dict_string += line\n dict_list = dict_string.split('\\n')\n dict_list.remove('')\n for el in dict_list:\n list_el = el.split()\n dict['ID'].append(list_el[0])\n dict['Name'].append(list_el[1])\n dict['Age'].append(list_el[2])\n dict['Password'].append(list_el[4])\n if IDinput in dict['ID']: # ID found\n if passinput == dict[\"Password\"][int(IDinput)-1]: #password found\n print(\"Wellcome \"+dict[\"Name\"][int(IDinput)-1].split('-')[0]+\". Login successful!\") # successful login\n while True: # bank functions start: list of options\n prompt2 = input(\"PLEASE SELECT OPTIONS:\"\"\\n\"\"1.Open a new account\"\"\\n\"\"2.View your account\"\"\\n\"\"3.Make a deposit\"\"\\n\"\"4.Withdraw\"\"\\n\"\"5.Transfer\"\"\\n\"\"6.Send money\"\"\\n\"\"7.Quit\"\"\\n\")\n if prompt2 == str(1):\n\n if int(dict[\"Age\"][int(IDinput)-1]) > 18: #If customer age is > 18, eligible to open either saving or check accounts\n while True: # options to either open saving or checking account\n prompt3 = input(\"PLEASE CHOOSE TYPE OF ACCOUNT:\"\"\\n\"\"1.Checking Account\"\"\\n\"\"2.Savings Account\"\"\\n\"\"3.Quit\"\"\\n\")\n if prompt3 == str(1):\n while True: # checking account condition - seeking consent from customer to proceed\n prompt4 = input(\"Checking account has a credit limit and overdraft fees of $5 each transaction, interest rate = 0. Happy to proceed?(Y/N):\")\n if prompt4 == \"N\" or prompt4 == 'n':\n print(\"Returning to the main screen\")\n break\n elif prompt4 ==\"Y\" or prompt4=='y': # create new checking account under the customer ID\n CID = IDinput\n customer1 = CheckingAccount(CID) # Call to Checking Account class\n customer1.create_account() # inherited functions of Bank class - parent of Checking Account\n print(\"Your checking account is successfully created!\")\n break\n\n elif prompt3 == str(2): # customer select to open saving account\n while True: # saving account condition. seek for customer consent\n prompt5 = input(\"Savings account pays 4% interest annually and you are only allowed to withdraw or transfer once per month. Happy to procceed?(Y/N):\")\n if prompt5 == \"Y\" or prompt5 =='y': # create a saving account under customer ID\n\n CID = IDinput\n customer1 = SavingAccount(CID)\n customer1.create_account()\n print(\"Your savings account is successfully created!\")\n break\n elif prompt5 == \"N\" or prompt5=='n':\n print(\"Returning to the main screen\")\n break\n else:\n print(\"Please enter again\")\n else:\n break\n\n elif int(dict[\"Age\"][int(IDinput)-1]) in range (14,19): # if cutomer age is greater than 14 but less than or equal 18\n while True: # let customer know the bank's age restriction. Seek for consent to create saving account only\n prompt6 = input(\"Since you are over 14 year old and under 18 year old, you can only open Savings Account. Happy to procceed? (Y/N):\")\n if prompt6 == 'Y' or prompt6 == 'y':\n\n while True: # seeking consent on saving account conditions\n prompt5 = input(\"Savings account pays 4% interest annually and you are only allowed to withdraw or transfer once per month. Happy to procceed?(Y/N):\")\n if prompt5 == 'Y' or prompt5 =='y': # customer said yes, creating a saving account\n CID = IDinput\n account1 = SavingAccount(CID)\n account1.create_account()\n print(\"Your savings account is successfully created!\")\n break\n elif prompt5 == 'N' or prompt5 == 'n':\n print(\"returning to the main screen\")\n break\n\n else: # if customer entering anything but Y or N\n print('value entered is not valid.Please try again')\n break\n elif prompt6 =='N'or prompt6 =='n':\n break\n else:\n print('value entered is not valid.Please try again')\n\n else: # customer age does not meet minimum threshold to create an account\n print(\"You need to be over 14 year old to open a bank account under your name.Please contact CATBANK for more information.\")\n elif prompt2 == str(2): # view bank account and their transaction history\n CID = IDinput\n account1 = Bank(CID)\n account1.view_account() # view bank accounts\n while True: # from the list of viewed accounts, select one to view transaction history\n try:\n option = int(input('Select account you want to view or press any key to quit:'))\n if option in dict3['OrderNo']:\n account1.view_transaction(option)\n except ValueError:\n break\n elif prompt2 == str(3):# deposit money\n\n CID=IDinput\n account1=Bank(CID)\n account1.view_account() # view account to select which account to deposit to\n if len(dict3['OrderNo']) > 0: # if there is account(s) created under provided customer ID\n while True:\n try:\n select_account = int(input('please select which account you want to deposit to:'))\n if select_account in dict3['OrderNo']: # check if the selection is on the viewed account list\n while True:\n try:\n request_amount = int(input ('how much you want to deposit :'))\n # deposit money and update on transaction.txt and account.txt\n CID = IDinput\n account1=Bank(CID)\n account1.deposit_transaction_update(request_amount,select_account)\n break\n except ValueError:\n print('the value entered is invalid. Try again')\n break\n\n else:\n print('selection is not in the list. Please try again!')\n except ValueError: # if customer entered a value not an integer\n answer_to = input('Do you want to quit?(Y/N):') # customer may want to quit\n if answer_to == 'Y'or answer_to =='y':\n break\n else: # if there is no account recorded under provided customer ID\n print('No account available to deposit')\n\n\n elif prompt2 == str(4): # withdraw function\n # view accounts under the same provided Customer ID to see which one to withdraw\n CID=IDinput\n account1=Bank(CID)\n account1.view_account()\n\n if len(dict3['OrderNo']) > 0: # if at least one account exist\n while True:\n try: # prompt customer to select one of the account on the list to withdraw from\n select_account = int(input('please select which account you want to withdraw:'))\n if select_account in dict3['OrderNo']: # check if selection is on the list\n request_amount = int(input ('how much you want to withdraw :'))\n if dict3['Type'][select_account-1]=='CA': #check if the account is checking account\n CID = IDinput\n account1=CheckingAccount(CID) # call CheckingAccount class and its function\n account1.withdraw(request_amount,select_account)\n break\n else: # if the selected account is saving account\n CID = IDinput\n account1=SavingAccount(CID) # call SavingAccount class and its function\n account1.withdraw(request_amount,select_account)\n break\n else: # selection is not on the list\n print('selection is not in the list. Please try again!')\n except ValueError: # customer entered something other than an integer\n answer_to = input('Do you want to quit?(Y/N):') # customer might want to exit?\n if answer_to == 'Y'or answer_to =='y':\n break\n else:\n print('No account available to withdraw')\n\n elif prompt2 == str(5):# transfer to other account under the same customer ID\n # view all account to perform transfer\n CID = IDinput\n account1 = Bank(CID)\n account1.view_account()\n while True: # select transfer to and from accounts\n try:\n transfer_from = int(input('Please select account you want to transfer from:'))\n if transfer_from in dict3['OrderNo']: # if selected transfer-from account is on the list\n\n if int(dict3['Balance'][transfer_from-1]) > 0: # balance must be >0 to continue\n while True:\n try:\n request_amount = int(input('How much you want to transfer:'))\n # transfering amount must not exceed current account balance to continue\n if request_amount <= int(dict3['Balance'][transfer_from-1]):\n account1.view_account() # view accounts once more to select transfer-to account\n while True:\n transfer_to = int(input('Please select account you want to transfer to:'))\n if transfer_to in dict3['OrderNo']:# check if account is on the list\n # calling function of Bank class to perform transfer transaction\n account1.transfer_transaction_update(request_amount,transfer_from,transfer_to)\n break\n else: # customer entered something out of the list\n print('selection is not in the list')\n answer_to = input('Do you want to cancel transaction?(Y/N):')\n if answer_to == 'Y' or answer_to =='y':\n break\n break\n else: # transfering amount exceed current balance\n print('Not enough money to transfer')\n\n\n except ValueError: # in case customer entered something else rather than amount of money to transfer\n print('invalid amount, try again')\n answer_to = input('Do you want to cancel transaction?(Y/N):')\n if answer_to == 'Y' or answer_to =='y':\n break\n else: # transfering amount is greater than current balance\n print('Not enough money to transfer')\n else: # in case customer entered something else not on the list\n print('selection is not in the list, try again')\n answer_to = input('Do you want to cancel transaction?(Y/N):')\n if answer_to == 'Y' or answer_to =='y':\n break\n except ValueError:\n print('invalid entry. Please try again')\n answer_to = input('Do you want to cancel transaction?(Y/N):')\n if answer_to == 'Y' or answer_to =='y':\n break\n elif prompt2 ==str(6):# send money to other person\n # view all accounts\n CID=IDinput\n account1=Bank(CID)\n account1.view_account()\n if len(dict3['OrderNo']) > 0:# check if at least one account recorded under provided ID\n while True: # select an account from the above list\n try:\n select_account = int(input('please select which account you want to send money:'))\n if select_account in dict3['OrderNo']:\n request_amount = int(input ('how much you want to send:'))\n if dict3['Type'][select_account-1]=='CA':\n # the selected account is checking account\n print('Please enter details of recipient:')\n while True: # recepient's details need to be entered before continue\n try:\n RBSB = int(input('BSB:'))\n RAccountNo =int(input('AccountNo:'))\n RName =str(input('Account Name:'))\n Reference =str(input('Reference:'))\n if len(str(RBSB)) == 6 and len(str(RAccountNo))==9: # check for length of BSB and AccountNo\n CID = IDinput\n account1=CheckingAccount(CID)\n account1.send(request_amount,select_account)\n break\n else:\n print('BSB or Account Number has incorrect length.Check again!')\n\n break\n except ValueError:\n print('Values entered are invalid. Try again!')\n\n break\n else: # the selected account is ssaving account\n CID = IDinput\n account1=SavingAccount(CID)\n account1.send(request_amount,select_account)\n\n else:\n print('selection is not in the list. Please try again!')\n except ValueError:\n answer_to = input('Do you want to quit?(Y/N):')\n if answer_to == 'Y'or answer_to =='y':\n break\n else:\n print('No account available to send money')\n break\n else:\n print(\"See you again!\")\n break\n\n else: # Password is not found in customer.txt file\n print(\"Please try again!Pass is incorrect\")\n else: # ID provided is not found in customer.txt file\n print(\"You have not registed with KatBank. Please register first!\")\n def __str__(self):\n return \" ID:{} \\n Name:{} \\n Age:{} \\n Gender:{}\\n Password:{}\\n NationalID:{}\\n \".format(self.ID,self.Age,self.Gender,self.Pass,self.NationalID)\n\n# main code:\nwhile True:\n # prompt user a list of options to choose from\n prompt1 = input(\"WELLCOME TO KATBANK!! PLEASE SELECT OPTIONS:\"\"\\n\"\"1. Register\"\"\\n\"\"2. Sign In\"\"\\n\"\"3. Quit Program\"\"\\n\")\n if prompt1 == str(1): # register a new account\n dict = {}\n while True:\n try:\n FName = str(input(\"First Name: \"))\n LName = str(input(\"Last Name:\"))\n NationalID = int(input('Your national identity number(9 digit):'))\n Age = int(input(\"Age: \"))\n Gender = str(input(\"Gender(M/F): \"))\n Pass = input(\"Password: \")\n FName = FName.split()[0] # take the first name if first name input has space in between\n LName = LName.split()[-1] # take the last name if last name input has space in between\n Name = FName +'-'+LName # name to be recorded on customer.txt\n if Gender in ['M','m','F','f']:\n customer1 = Customer(Name,Age,Gender,Pass,NationalID)\n customer1.register_customer()\n else:\n print('mistake made at entering value for Gender')\n\n break\n except ValueError:\n print('Value entered is invalid.Please try again')\n\n elif prompt1 == str(2): # sign in by entering ID and password\n IDinput = input(\"ID: \")\n passinput = input(\"Password: \")\n dict2={}\n dict3={}\n count = 1\n ID = IDinput\n Name = \"\"\n Age = \"\"\n Gender = \"\"\n Pass = 0\n NationalID =0\n customer1=Customer(Name,Age,Gender,Pass,NationalID)\n customer1.sign_in(IDinput,passinput)\n\n else:\n break\n\n","repo_name":"ThuyKat/Final-CA","sub_path":"FinalProgram.py","file_name":"FinalProgram.py","file_ext":"py","file_size_in_byte":41093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"70676786816","text":"import unittest\nfrom logic import delaunay_triangulation\nfrom datatypes.rooms import Rooms\nfrom datatypes.coordinates import Coordinates\nfrom datatypes.triangle import Triangle\n\nclass TestDelaunayTriangulation(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.rooms = [Rooms(Coordinates(8,11), [], [], None),\n\t\tRooms(Coordinates(10,7), [], [], None),\n\t\tRooms(Coordinates(4,15), [], [], None),\n\t\tRooms(Coordinates(16,7), [], [], None)]\n\t\tself.coordinates = [Coordinates(8,11), Coordinates(10,7), Coordinates(4,15), Coordinates(16,7)]\n\n\tdef test_edge_not_in_when_not_in(self):\n\t\town_triangle = Triangle(Coordinates(1,1),Coordinates(2,2),Coordinates(3,3))\n\t\tedge = (Coordinates(1,1),Coordinates(2,2))\n\t\tbad_triangles = [own_triangle, Triangle(Coordinates(2,2), Coordinates(3,3), Coordinates(4,4))]\n\t\tnot_in = delaunay_triangulation.edge_not_in_other_bad_triangles(own_triangle, edge, bad_triangles)\n\t\tself.assertEqual(not_in, True)\n\n\tdef test_edge_not_in_when_in(self):\n\t\town_triangle = Triangle(Coordinates(1,1),Coordinates(2,2),Coordinates(3,3))\n\t\tedge = (Coordinates(1,1),Coordinates(2,2))\n\t\tbad_triangles = [own_triangle, Triangle(Coordinates(1,1), Coordinates(2,2), Coordinates(4,4))]\n\t\tnot_in = delaunay_triangulation.edge_not_in_other_bad_triangles(own_triangle, edge, bad_triangles)\n\t\tself.assertEqual(not_in, False)\n\n\tdef test_delaunay(self):\n\t\t\"\"\"Tests delaunay with a set of rooms that did not result in a correct\n\t\ttriangulation before, due to a circumcircle not fitting on the the checking area.\"\"\"\n\t\ttriangulation = delaunay_triangulation.delaunay_triangulation(self.coordinates, 20, 20)\n\t\tt1 = [Coordinates(10,7),Coordinates(8,11),Coordinates(4,15)]\n\t\tt2 = [Coordinates(8,11),Coordinates(10,7),Coordinates(16,7)]\n\t\tt3 = [Coordinates(8,11),Coordinates(4,15),Coordinates(16,7)]\n\n\t\tfor i in range(len(triangulation)):\n\t\t\ttriangulation[i] = triangulation[i].corners\n\n\t\tself.assertEqual(triangulation, [t1,t2,t3])\n\t\n\tdef test_delaunay2(self):\n\t\t\"\"\"Tests delaunay with a set of rooms that I calculated by hand\"\"\"\n\t\tcoordinates = [Coordinates(2,3),Coordinates(7,2),Coordinates(5,5),Coordinates(7,6),Coordinates(3,7),Coordinates(11,2),Coordinates(11,5),Coordinates(9,8),Coordinates(4,1),\n\t\t\t\t Coordinates(1,6),Coordinates(6,8),Coordinates(11,7),]\n\t\ttriangulation = delaunay_triangulation.delaunay_triangulation(coordinates, 20, 20)\n\t\ttriangles = [[Coordinates(5,5),Coordinates(7,2),Coordinates(7,6)],[Coordinates(5,5),Coordinates(2,3),Coordinates(3,7)],[Coordinates(7,6),Coordinates(7,2),Coordinates(11,5)],\n\t\t\t [Coordinates(7,2),Coordinates(11,2),Coordinates(11,5)],[Coordinates(7,6),Coordinates(11,5),Coordinates(9,8)],[Coordinates(7,2),Coordinates(5,5),Coordinates(4,1)],\n\t\t\t [Coordinates(5,5),Coordinates(2,3),Coordinates(4,1)],[Coordinates(11,2),Coordinates(7,2),Coordinates(4,1)],[Coordinates(3,7),Coordinates(2,3),Coordinates(1,6)],\n\t\t\t [Coordinates(7,6),Coordinates(5,5),Coordinates(6,8)],[Coordinates(5,5),Coordinates(3,7),Coordinates(6,8)],[Coordinates(9,8),Coordinates(7,6),Coordinates(6,8)],\n\t\t\t [Coordinates(9,8),Coordinates(11,5),Coordinates(11,7)]]\n\n\t\tfor i in range(len(triangulation)):\n\t\t\ttriangulation[i] = triangulation[i].corners\n\n\t\tself.assertEqual(triangulation, triangles)\n\n\tdef test_with_degenerate_points(self):\n\t\t\"\"\"The Bowyer-Wattson algorithm does not work with degenerate point set\"\"\"\n\t\tcoordinates = [Coordinates(8,1), Coordinates(10,1), Coordinates(4,1)]\n\t\ttriangulation = delaunay_triangulation.delaunay_triangulation(coordinates, 20, 20)\n\t\tself.assertEqual(triangulation, [])\n","repo_name":"Robomarti/Tiralabra","sub_path":"src/tests/delaunay_triangulation_test.py","file_name":"delaunay_triangulation_test.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"17605161842","text":"from curses import meta\nimport os\nimport cv2\nimport pickle\nimport random\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nimport librosa\nimport torch\nfrom torch.utils.data import Dataset\nfrom copy import deepcopy\nfrom PIL import Image\n\nfrom .icbhi_util import get_annotations, save_image, generate_fbank, get_individual_cycles_librosa, split_pad_sample, generate_mel_spectrogram, concat_augmentation\nfrom .icbhi_util import get_individual_cycles_torchaudio, cut_pad_sample_torchaudio\nfrom .augmentation import augment_raw_audio\n\nimport librosa\nimport torch\nimport torchaudio\nfrom torchaudio import transforms as T\n\n\nclass COUGHVIDdataset(Dataset):\n def __init__(self, train_flag, transform, args, metadata_path, print_flag=True, mean_std=False):\n \n self.data_folder = os.path.join(\"public_dataset\")\n self.train_flag = train_flag\n self.split = 'train' if train_flag else 'test'\n self.transform = transform\n self.args = args\n self.mean_std = mean_std\n\n # parameters for spectrograms\n self.sample_rate = args.sample_rate\n self.desired_length = args.desired_length\n self.pad_types = args.pad_types\n self.nfft = args.nfft\n self.hop = self.nfft // 2\n self.n_mels = args.n_mels\n self.f_min = 50\n self.f_max = 2000\n self.dump_images = False\n\n # ==========================================================================\n data_pandas = pd.read_csv(metadata_path, sep='\\t')\n sample_data = []\n for index, row in tqdm(data_pandas.iterrows(), total=data_pandas.shape[0]):\n fpath = os.path.join(self.data_folder, row['uuid'] + '.wav')\n \n sr = librosa.get_samplerate(fpath)\n data, _ = torchaudio.load(fpath)\n \n if sr != self.sample_rate:\n resample = T.Resample(sr, self.sample_rate)\n data = resample(data)\n\n fade_samples_ratio = 16\n fade_samples = int(self.sample_rate / fade_samples_ratio)\n\n fade = T.Fade(fade_in_len=fade_samples, fade_out_len=fade_samples, fade_shape='linear')\n data = fade(data)\n\n sample_data.append((data, row['status']))\n \n padded_sample_data = []\n for data, label in sample_data:\n data = cut_pad_sample_torchaudio(data, args)\n padded_sample_data.append((data, label))\n \n self.audio_data = padded_sample_data # each sample is a tuple with (audio_data, label, filename)\n self.labels = []\n \n self.class_nums = np.zeros(args.n_cls)\n for sample in self.audio_data:\n self.class_nums[sample[1]] += 1\n self.labels.append(sample[1])\n self.class_ratio = self.class_nums / sum(self.class_nums) * 100\n \n if print_flag:\n print('[Preprocessed {} dataset information]'.format(self.split))\n print('total number of audio data: {}'.format(len(self.audio_data)))\n for i, (n, p) in enumerate(zip(self.class_nums, self.class_ratio)):\n print('Class {} {:<9}: {:<4} ({:.1f}%)'.format(i, '('+args.cls_list[i]+')', int(n), p)) \n # ==========================================================================\n \"\"\" convert mel-spectrogram \"\"\"\n self.audio_images = []\n for index in tqdm(range(len(self.audio_data))):\n audio, label = self.audio_data[index][0], self.audio_data[index][1]\n\n audio_image = []\n # self.aug_times = 1 + 5 * self.args.augment_times # original + five naa augmentations * augment_times (optional)\n for aug_idx in range(self.args.raw_augment+1): \n if aug_idx > 0:\n if self.train_flag and not mean_std:\n audio = augment_raw_audio(audio, self.sample_rate, self.args)\n \n # \"RespireNet\" version: pad incase smaller than desired length\n # audio = split_pad_sample([audio, 0,0], self.desired_length, self.sample_rate, types=self.pad_types)[0][0]\n\n # \"SCL\" version: cut longer sample or pad sample\n audio = cut_pad_sample_torchaudio(torch.tensor(audio), args)\n else:\n audio_image.append(None)\n continue\n \n image = generate_fbank(audio, self.sample_rate, n_mels=self.n_mels)\n # image = generate_mel_spectrogram(audio.squeeze(0).numpy(), self.sample_rate, n_mels=self.n_mels, f_max=self.f_max, nfft=self.nfft, hop=self.hop, args=self.args) # image [n_mels, 251, 1]\n\n # blank region clipping from \"RespireNet\" paper..\n if self.args.blank_region_clip: \n image_copy = deepcopy(generate_fbank(audio, self.sample_rate, n_mels=self.n_mels))\n # image_copy = deepcopy(generate_mel_spectrogram(audio.squeeze(0).numpy(), self.sample_rate, n_mels=self.n_mels, f_max=self.f_max, nfft=self.nfft, hop=self.hop, args=self.args)) # image [n_mels, 251, 1] \n\n image_copy[image_copy < 10] = 0\n for row in range(image_copy.shape[0]):\n black_percent = len(np.where(image_copy[row,:] == 0)[0]) / len(image_copy[row,:])\n # if there is row that is filled by more than 20% regions, stop and remember that `row`\n if black_percent < 0.80:\n break\n\n # delete black percent\n if row + 1 < image.shape[0]:\n image = image[row+1:,:,:]\n image = cv2.resize(image, (image.shape[1], self.n_mels), interpolation=cv2.INTER_LINEAR)\n image = image[..., np.newaxis]\n\n audio_image.append(image)\n self.audio_images.append((audio_image, label))\n \n if self.dump_images:\n save_image(audio_image, './')\n self.dump_images = False\n\n self.h, self.w, _ = self.audio_images[0][0][0].shape\n # ==========================================================================\n\n def __getitem__(self, index):\n audio_images, label = self.audio_images[index][0], self.audio_images[index][1]\n\n if self.args.raw_augment and self.train_flag and not self.mean_std:\n aug_idx = random.randint(0, self.args.raw_augment)\n audio_image = audio_images[aug_idx]\n else:\n audio_image = audio_images[0]\n \n if self.transform is not None:\n audio_image = self.transform(audio_image)\n \n return audio_image, label\n\n def __len__(self):\n return len(self.audio_data)","repo_name":"arkiven4/batuk_detect_server","sub_path":"util/coughvit_dataset.py","file_name":"coughvit_dataset.py","file_ext":"py","file_size_in_byte":6838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"12401023209","text":"\"\"\"\n어떠한 수 N이 1이 될 때까지 다음 두 과정 중 하나를 반복적으로 선택하여 수행한다.\n단, 두번째 연산은 N이 K로 나누어 떨어질 때만 선택할 수 있다.\n 1. N에서 1을 뺀다.\n 2. N을 K로 나눈다.\n첫쨰 줄에 N과 K(= 1:\n if N % K == 0:\n N = N // K\n count = count + 1\n\n else:\n N = N - 1\n count = count + 1\nend_ = time.time()\nprint(end_ - start_)\n\nprint(count)\n\n\"\"\"\n\n\"\"\"\n--- 책에 있는 답 1 ---\n\nimport time\nstart_ = time.time()\n\nn ,k = map(int, input().split())\nresult = 0\n\n# N이 k 이상이라면 K로 계속 나누기\nwhile n>=k:\n # N이 K로 나누어 떨어지지 않는다면 N에서 1씩 빼기\n while n % k != 0:\n n -= 1\n result += 1\n # K로 나누기\n n //= k\n result += 1\n\n# 마지막으로 남은 수에 대하여 1씩 빼기\nwhile n > 1:\n n -= 1\n result += 1\n\nend_ = time.time()\n\nprint(end_ - start_)\n\nprint(result)\n\n\"\"\"\n\n# --- 책에 있는 답 2 ---\n\nn, k = map(int, input().split())\nresult = 0\n\nwhile True:\n # N == K로 나누어떨어지는 수가 될 때까지 1씩 빼기\n target = (n // k ) * k\n result += (n - target)\n n = target\n # N이 K보다 작을때(더 이상 나눌 수 없을 때) 반복문 탈출\n if n < k:\n break\n # k로 나누기\n result += 1\n n //= k\n\n# 마지막으로 남은 수에 대하여 1씩 빼기\nresult += (n - 1)\nprint(result)","repo_name":"kimhyeongju/coding_practice","sub_path":"Chapter3(Greedy)/1이 될 때까지.py","file_name":"1이 될 때까지.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"18451739737","text":"import json\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\n\r\nclass Decoder(nn.Module):\r\n def __init__(self, input_token_size, output_channel_nums, output_img_size):\r\n super(Decoder, self).__init__()\r\n self.fc = nn.Linear(input_token_size, 128 * 16 * 16)\r\n self.conv_layers = nn.Sequential(\r\n nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1),\r\n nn.ReLU(),\r\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1),\r\n nn.ReLU(),\r\n nn.ConvTranspose2d(32, output_channel_nums, kernel_size=3, stride=2, padding=1, output_padding=1)\r\n )\r\n self.output_img_size = output_img_size\r\n\r\n def forward(self, tokens):\r\n out = self.fc(tokens)\r\n out = out.view(-1, 128, 16, 16)\r\n out = self.conv_layers(out)\r\n out = nn.functional.interpolate(out, size=(\r\n self.output_img_size, self.output_img_size))\r\n return out\r\n\r\n\r\nclass PartD(nn.Module):\r\n def __init__(self, model, optimizer, criterion, learning_rate):\r\n super(PartD, self).__init__()\r\n self.model = model\r\n self.optimizer = optimizer(self.model.parameters(), lr=learning_rate)\r\n self.criterion = criterion\r\n return\r\n\r\n def train(self, inputs, targets):\r\n outputs = self.model(inputs)\r\n self.optimizer.zero_grad()\r\n loss = self.criterion(outputs, targets)\r\n loss.backward()\r\n self.optimizer.step()\r\n return loss.cpu().item(), outputs\r\n\r\n def forward(self, tokens):\r\n out = self.model(tokens)\r\n return out\r\n\r\n\r\nTEST_BATCH_SIZE = 2\r\nCONFIG_PATH = \"config.json\"\r\n\r\n\r\ndef load_config():\r\n with open(CONFIG_PATH, \"r\", encoding=\"utf-8\") as file:\r\n config = json.load(file)\r\n return config\r\n\r\n\r\ndef get_PartD():\r\n PART_D_CONFIG = load_config()[\"model\"][\"PartD\"]\r\n model = Decoder(\r\n input_token_size=PART_D_CONFIG[\"input_token_size\"],\r\n output_channel_nums=PART_D_CONFIG[\"output_channel_nums\"],\r\n output_img_size=PART_D_CONFIG[\"output_img_size\"],\r\n )\r\n part_d = PartD(\r\n model=model,\r\n optimizer=torch.optim.Adam,\r\n criterion=torch.nn.MSELoss(),\r\n learning_rate=PART_D_CONFIG[\"learning_rate\"],\r\n )\r\n return part_d\r\n\r\nif __name__ == \"__main__\":\r\n tokens = torch.rand(TEST_BATCH_SIZE, 128)\r\n targets = torch.rand(TEST_BATCH_SIZE, 3, 256, 256)\r\n\r\n partd = get_PartD()\r\n\r\n num_epochs = 10\r\n for epoch in range(num_epochs):\r\n loss = partd.train(tokens, targets)\r\n print(f\"Epoch {epoch + 1}, Loss: {loss}\")\r\n\r\n outputs = partd(tokens)\r\n print(\"outputs.shape\", outputs.shape)\r\n","repo_name":"Tokisakix/Rural-road-division-model","sub_path":"networks/partD.py","file_name":"partD.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"10522179259","text":"import PySimpleGUI as sg\r\nfrom Files import Files\r\nimport noteWindow\r\n\r\n\r\ndef openWindow(**kwargs):\r\n searchText = kwargs.get(\"searchText\", \"\")\r\n savedFiles = kwargs.get(\"savedFiles\", [])\r\n config = kwargs.get(\"config\", {})\r\n saveLocation = kwargs.get(\"saveLocation\", None)\r\n fontSetting = kwargs.get(\"fontSetting\", \"Helvetica 16\")\r\n\r\n fontSettings = fontSetting.split() # Splits fontSetting into a list with the font-family and font size as separate items\r\n fontFamily = fontSettings[0]\r\n fontSize = fontSettings[1]\r\n smallerFont = f\"{fontFamily} {round(int(fontSize) * 0.75)}\"\r\n\r\n static_content = [ # Layout of the buttons and searchbar\r\n [sg.Text(\"Saved files\", font=fontSetting, justification=\"center\", size=(80, 2))],\r\n [sg.Button(button_text=\"Browse\", font=smallerFont, key=\"browse\"), sg.Button(button_text=\"New file\", font=smallerFont, key=\"newFile\"), sg.Button(button_text=\"Refresh\", font=smallerFont, key=\"refresh\")],\r\n [sg.Button(\"Clear search\", font=smallerFont, key=\"searchClear\"), sg.InputText(key=\"search\", default_text=searchText, size=(60,2), enable_events=True), sg.Button(\"Search\", font=smallerFont, key=\"searchBtn\", bind_return_key=True)],\r\n [sg.Text(\"\", font=fontSetting, justification=\"center\", size=(20, 2))] # Empty row in between the search and saved files\r\n ]\r\n\r\n dynamic_content = [] # This list will contain all saved files or \"No files found\"\r\n if savedFiles: # If savedFiles is not empty\r\n for i in range(len(savedFiles)):\r\n if i == 0 or i % 2 == 0:\r\n if len(savedFiles) > i + 1: # More than 1 file left\r\n dynamic_content.append([ # Add a row with these elements in it\r\n sg.Text(savedFiles[i], font=fontSetting, justification=\"center\", size=(40, 2), enable_events=True), # Left file\r\n sg.Text(savedFiles[i+1], font=fontSetting, justification=\"center\", size=(40, 2), enable_events=True) # Right file\r\n ])\r\n elif len(savedFiles) == i + 1: # Only 1 file left\r\n dynamic_content.append([ # Add a row with these elements in it\r\n sg.Text(savedFiles[i], font=fontSetting, justification=\"center\", size=(40, 2), enable_events=True) # Centered file\r\n ])\r\n else:\r\n dynamic_content.append([sg.Text(\"No files found\", font=fontSetting, justification=\"center\", size=(40, 2))])\r\n \r\n finalLayout = [[sg.Column(static_content + dynamic_content, element_justification=\"center\", scrollable=True, vertical_scroll_only=True, size=(1000,600))]] # Layout as a column to allow centering elements\r\n window = sg.Window(\"Files\", layout=finalLayout)\r\n\r\n while True: # Main window event loop\r\n event, values = window.read() # Read events and values from window\r\n if event == sg.WIN_CLOSED:\r\n break # Break out of the loop when the window is closed\r\n elif event == \"browse\":\r\n window.close()\r\n saveLocation = Files.changeSaveLocation(config)\r\n openWindow(searchText=values[\"search\"], savedFiles=Files.search(saveLocation=saveLocation), config=config, saveLocation=saveLocation, fontSetting=fontSetting)\r\n elif event == \"searchBtn\":\r\n # values[\"search\"] means whatever text is inside the search bar\r\n window.close()\r\n openWindow(searchText=values[\"search\"], savedFiles=Files.search(searchWord=values[\"search\"], config=config, saveLocation=saveLocation), saveLocation=saveLocation)\r\n elif event == \"searchClear\":\r\n window.close()\r\n openWindow(savedFiles=Files.search(saveLocation=saveLocation), config=config, saveLocation=saveLocation, fontSetting=fontSetting)\r\n elif event == \"newFile\":\r\n newFileName = sg.popup_get_text(\"Enter a name for the new text file\", font=fontSetting, keep_on_top=True)\r\n if not (newFileName == None or len(newFileName) <= 0):\r\n Files.new(fileName=newFileName, saveLocation=saveLocation)\r\n elif event == \"refresh\":\r\n window.close()\r\n openWindow(searchText=values[\"search\"], savedFiles=Files.search(searchWord=values[\"search\"], saveLocation=saveLocation), config=config, saveLocation=saveLocation, fontSetting=fontSetting) # Refresh by reopening window (Files.search returns an updated list of files)\r\n elif event != \"search\": # Search event occurs whenever something is being typed in the search bar\r\n window.close()\r\n noteWindow.openNote(file=event, savedFiles=savedFiles, config=config, saveLocation=saveLocation, fontSetting=fontSetting) # Event is the name of the clicked file\r\n \r\n window.close() # Make sure the window is closed \r\n","repo_name":"IamNanjo/Simple-Python-Text-Editor","sub_path":"src/mainWindow.py","file_name":"mainWindow.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"33331178910","text":"import time\nfrom threading import Thread, Lock\n\nmoney = 100\nt_list = []\nmutex = Lock() # 锁机制\n\n\ndef task():\n global money\n temp = money\n time.sleep(0.1)\n money = temp - 1\n\n\ndef taskWithLock():\n global money\n mutex.acquire()\n temp = money\n time.sleep(0.1)\n money = temp - 1\n mutex.release()\n\n\nif __name__ == '__main__':\n for i in range(100):\n t = Thread(target=taskWithLock)\n t_list.append(t)\n\n for t in t_list:\n t.start()\n for t in t_list:\n t.join()\n print(money)\n","repo_name":"golamby/lamby-pythonstudy","sub_path":"base-grammer/并发编程(进程线程协程)/线程/06-线程互斥锁.py","file_name":"06-线程互斥锁.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"37847323069","text":"from pack_graph import *\nfrom pack_target import *\nfrom pack_collect import *\nfrom pack_storage import *\nimport config as conf\n\n# 读取数据\ndef onGetData(code):\n db = storageStockA.storageStockA(conf.PATH_DB_STOCKA)\n # data = db.readData(code, '2016-01-01')\n data = db.readData(code)\n print(\"read %s success, data length = %d\" % (code, len(data)))\n # return db.toWeek(data)\n return data\n\n# K线叠加图像\ndef onGetDataEx(index, data):\n if data is None : return None\n nm = target.norm()\n if index == 0:\n MA5 = nm.getMA(data, 5, target.COLOR_BLUE)\n MA30 = nm.getMA(data, 30, target.COLOR_PURPLE)\n MA250 = nm.getMA(data, 250, target.COLOR_ORANGE)\n return (MA5, MA30, MA250)\n if index == 1:\n MAVOL5 = nm.getMAVOL(data, 5, target.COLOR_BLUE)\n MAVOL10 = nm.getMAVOL(data, 15, target.COLOR_PURPLE)\n return (MAVOL5, MAVOL10)\n \n# 参数图像\ndef onGetNorm(label, data):\n if data is None : return None\n nm = target.norm()\n if label == target.MACD: return nm.getMACD(data)\n if label == target.KDJ: return nm.getKDJ(data)\n if label == target.RSI: return nm.getRSI(data)\n return None\n\nif __name__ == \"__main__\":\n\n config = conf.config()\n collect = collectStockA.collectStockA(config.public(), config.private(), conf.PATH_DB_STOCKA)\n\n db = storageStockA.storageStockA(conf.PATH_DB_STOCKA)\n nm = target.norm()\n \n updateList = []\n for item in collect.public['stockA']['list']:\n updateList.append(db.readContents(item)[0])\n\n if collect.public['stockA']['all'] is True:\n collect.update()\n else:\n collect.update(updateList)\n\n dataList = []\n normList = nm.getAllList()\n\n for item in updateList:\n dataList.append((item[0], item[2]))\n\n gp = graph.graph(dataList, normList, onGetData, onGetNorm, onGetDataEx)\n gp.show()","repo_name":"reseen/K-Line","sub_path":"src/stockA.py","file_name":"stockA.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"28192732681","text":"\ndef divided(data):\n\tfor i in data:\n\t\tfor j in data:\n\t\t\tif i!=j and i%j == 0:\n\t\t\t\treturn int(i/j)\n\nchecksum1 = 0\nchecksum2 = 0\n\nwith open('input') as f:\n\tfor l in f.readlines():\n\t\tlinedata = list(map(int,l.split()))\n\t\tchecksum1 += max(linedata) - min(linedata)\n\t\tchecksum2 += divided(linedata)\n\nprint(checksum1)\t\t\nprint(checksum2)\n","repo_name":"michalicekmilan/adventofcode2017","sub_path":"02/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"36440670799","text":"import pdb\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\n\nimport fastestimator as fe\nfrom fastestimator.architecture.tensorflow import LeNet\nfrom fastestimator.dataset import LabeledDirDataset\nfrom fastestimator.op.numpyop import NumpyOp\nfrom fastestimator.op.numpyop.multivariate import Resize\nfrom fastestimator.op.numpyop.univariate import ReadImage\nfrom fastestimator.op.tensorop.loss import CrossEntropy\nfrom fastestimator.op.tensorop.model import ModelOp, UpdateOp\nfrom fastestimator.pipeline import Pipeline\nfrom fastestimator.trace.metric import Accuracy\n\n\ndef my_inceptionv3():\n inputs = layers.Input(shape=(299, 299, 3))\n backbone = tf.keras.applications.InceptionV3(weights=None, include_top=False, pooling='avg', input_tensor=inputs)\n x = backbone.outputs[0]\n x = layers.Dense(1000)(x)\n outputs = layers.Activation('softmax', dtype='float32')(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\ndef my_resnet50():\n inputs = layers.Input(shape=(224, 224, 3))\n backbone = tf.keras.applications.ResNet50(weights=None, include_top=False, pooling='avg', input_tensor=inputs)\n x = backbone.outputs[0]\n outputs = layers.Dense(1000, activation='softmax')(x)\n # outputs = layers.Activation('softmax', dtype='float32')(x)\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\nclass Scale(NumpyOp):\n def forward(self, data, state):\n data = data / 255\n return np.float32(data)\n\n\ndef get_estimator():\n pipeline = Pipeline(\n train_data=LabeledDirDataset(\"/data/data/public/ImageNet/train\"),\n eval_data=LabeledDirDataset(\"/data/data/public/ImageNet/val\"),\n batch_size=1024,\n ops=[\n ReadImage(inputs=\"x\", outputs=\"x\"),\n Resize(height=224, width=224, image_in=\"x\", image_out=\"x\"),\n Scale(inputs=\"x\", outputs=\"x\")\n ])\n\n # step 2\n model = fe.build(model_fn=my_resnet50, optimizer_fn=\"adam\", mixed_precision=True)\n network = fe.Network(ops=[\n ModelOp(model=model, inputs=\"x\", outputs=\"y_pred\"),\n CrossEntropy(inputs=(\"y_pred\", \"y\"), outputs=\"ce\"),\n UpdateOp(model=model, loss_name=\"ce\")\n ])\n # step 3\n estimator = fe.Estimator(pipeline=pipeline,\n network=network,\n epochs=2,\n traces=Accuracy(true_key=\"y\", pred_key=\"y_pred\"))\n return estimator\n\n\nif __name__ == \"__main__\":\n est = get_estimator()\n est.fit()\n","repo_name":"vbvg2008/benchmarks","sub_path":"imagenet_fe/imagenet_tensorflow.py","file_name":"imagenet_tensorflow.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"13189150239","text":"from django.db import models\n\nfrom account.models import Account\nfrom group.models import Group, SubGroup\nfrom data.message.models import Message\n\nclass Counter(models.Model):\n group = models.ForeignKey(Group,on_delete=models.CASCADE)\n subgroup = models.ForeignKey(SubGroup,on_delete=models.CASCADE,null=True,blank=True)\n\n account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True, blank=False)\n\n is_reading = models.BooleanField(default=False)\n last_read= models.ForeignKey(Message, on_delete=models.CASCADE, null=True, blank=True)\n\n class Meta:\n verbose_name = \"Counter\"\n verbose_name_plural = \"Counter\"\n ordering = [\"-last_read__id\"]\n unique_together = [[\"group\",\"subgroup\", \"account\"]]\n","repo_name":"ds1sqe/Copy-Chat","sub_path":"copy_chat_be/data/meta/readcounter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"9393778058","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 29 16:32:02 2019\n\n@author: misiak\n\"\"\"\nimport sys\nimport os\nimport json\nimport matplotlib.pyplot as plt\nplt.close('all')\n\nfrom _true_data import data_selection\n\n# getting arguments from command line\nif len(sys.argv) != 3:\n raise Exception('Expecting 3 arguments: stream, detector')\n \nstream, detector = sys.argv[1:]\n\n# hard coding the DATA and SAVE directories\nDATA_DIR_LOCAL = '/home/misiak/Data/data_run57'\nLIB_DIR_LOCAL = '/home/misiak/Analysis/pulse_fitting/event_library_test'\nDATA_DIR_CC = '/sps/edelweis/CRYO_IPNL/BatchOUTPUT'\nLIB_DIR_CC = '/sps/edelweis/dmisiak/Analysis/pulse_fitting/event_library'\n\n# priority to local path, then CC, then raise exception of paths not found.\nif os.path.isdir(LIB_DIR_LOCAL):\n LIB_DIR = LIB_DIR_LOCAL\nelif os.path.isdir(LIB_DIR_CC):\n LIB_DIR = LIB_DIR_CC\nelse:\n raise Exception(\n (\n 'The directories {} could not be found. LIB_DIR cannot be assigned.'\n ).format(LIB_DIR_LOCAL, LIB_DIR_CC)\n )\n\n# priority to local path, then CC, then raise exception of paths not found.\nif os.path.isdir(DATA_DIR_LOCAL):\n DATA_DIR = DATA_DIR_LOCAL\nelif os.path.isdir(DATA_DIR_CC):\n DATA_DIR = DATA_DIR_CC\nelse:\n raise Exception(\n (\n 'The directories {} could not be found. DATA_DIR cannot be assigned'\n ).format(DATA_DIR_LOCAL, DATA_DIR_CC)\n )\n\n\nlabel = '_'.join((stream, detector))\nsave_dir = '/'.join((LIB_DIR, label))\n\n# super mkdir for the save directories\npath_list = (save_dir,)\nfor path in path_list:\n try:\n os.makedirs(path)\n except OSError:\n if not os.path.isdir(path):\n raise\n\n# data selection from true_data.py\ndata_selection(stream, detector, DATA_DIR, save_dir)\n\n# creating the config_file for the mcmc\nconfig = dict()\nconfig['Data'] = {\n 'true_data': True,\n 'directory': DATA_DIR,\n 'stream': stream,\n 'detector': detector, \n}\nconfig['Selection'] = {\n 'directory': LIB_DIR,\n}\n\nconfigpath = '/'.join((save_dir, 'config.json'))\nwith open(configpath, 'w') as cfg:\n json.dump(config, cfg, indent=4)\n \n","repo_name":"DimitriMisiak/pulse_fitting","sub_path":"event_selection.py","file_name":"event_selection.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"5952261909","text":"\nfrom tkinter import*\nfrom tkinter.ttk import*\nfrom time import strftime\n\ntop = Tk()\ntop.title(\"clock\")#tao ten\n\ndef clock():\n string=strftime('%H:%M:%S:%p')\n label.config(text=string)\n label.after(1000,clock)\n\nlabel= Label(top , font= (\"digital-7\",100), background = \"black\", foreground=\"white\")\nlabel.pack(anchor='center')\nclock()\ntop.mainloop()#tao vong lap (bat buoc)","repo_name":"lebang3/python3","sub_path":"Tkinter/New folder/clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"72105418815","text":"import re\nimport dbus\nfrom twisted.internet.defer import inlineCallbacks\nfrom tx_g15.g15_screen import G15TextScreen\nfrom tx_g15.util.misc import squeeze, truncate, xhtml_unescape\nfrom tx_g15.util.tx_dbus import deferFromDbus\n\nclass Pidgin(G15TextScreen):\n \"\"\"\n A screen that updates when buddies sign on / off, or if an IM is received.\n \"\"\"\n def __init__(self, parent = None):\n G15TextScreen.__init__(self, parent)\n\n bus = dbus.SessionBus()\n self.pidgin = dbus.Interface(\n bus.get_object(\"im.pidgin.purple.PurpleService\", \"/im/pidgin/purple/PurpleObject\"),\n \"im.pidgin.purple.PurpleInterface\"\n )\n\n self.appendText(\"Pidgin Screen Loaded. Waiting for events.\", center = True)\n\n bus.add_signal_receiver(self.buddySignedOn, 'BuddySignedOn', self.pidgin.dbus_interface)\n bus.add_signal_receiver(self.buddySignedOff, 'BuddySignedOff', self.pidgin.dbus_interface)\n bus.add_signal_receiver(self.receivedImMessage, 'ReceivedImMsg', self.pidgin.dbus_interface)\n\n @inlineCallbacks\n def buddySignedOn(self, e):\n name = yield deferFromDbus(self.pidgin.PurpleBuddyGetAlias, e)\n with self.context():\n self.appendLine(\"online: %s\" % name, center = True)\n\n @inlineCallbacks\n def buddySignedOff(self, e):\n name = yield deferFromDbus(self.pidgin.PurpleBuddyGetAlias, e)\n with self.context():\n self.appendLine(\"offline: %s\" % name, center = True)\n\n def receivedImMessage(self, _, who, message, time, __):\n with self.context():\n self.appendText(truncate(\"%s: %s\" % (who, squeeze(xhtml_unescape(re.sub(r'<[^>]*?>', '', message)))), min_pos = 27, max_pos = 27 * 2))\n\n","repo_name":"e000/tx_g15","sub_path":"screens/Pidgin.py","file_name":"Pidgin.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"23927619412","text":"sentStatus = 'sent'\n\n# manager called callback to sciflomanager\ncalledBackStatus = 'called back'\n\n# work unit is waiting for dependencies to be resolved\nwaitingStatus = 'waiting'\n\n# work unit has dependencies resolved and is ready to run\nreadyStatus = 'ready'\n\n# work unit is staging files prior to execution\nstagingStatus = 'staging'\n\n# work unit is executing\nworkingStatus = 'working'\n\n# work unit finished successfully\ndoneStatus = 'done'\n\n# work unit finished with an exception\nexceptionStatus = 'exception'\n\n# work unit resolved to a previously run work unit\ncachedStatus = 'cached'\n\n# post execution of work unit\npostExecutionStatus = 'finalizing'\n\n# work unit was cancelled\ncancelledStatus = 'cancelled'\n\n# work unit is paused\npausedStatus = 'paused'\n\n# work unit is retrying\nretryStatus = 'retry'\n\n# list of statuses that indicate work unit is not working any more\nfinishedStatusList = [doneStatus, exceptionStatus,\n cachedStatus, cancelledStatus]\n","repo_name":"hysds/sciflo","sub_path":"sciflo/grid/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"8668403327","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import Flask, url_for\nfrom flask import request\nimport json\nimport sqlite3\nimport time\nimport datetime\nfrom help import helper\n\n\n\n\napp = Flask(__name__)\n\n@app.route('/')\ndef HomePage():\n return render_template('records.html')\n\n@app.route('/templates/records.html')\ndef index1():\n return render_template('records.html')\n\n@app.route('/templates/correction.html')\ndef index2():\n return render_template('correction.html')\n\n@app.route('/templates/update.html')\ndef index3():\n return render_template('update.html')\n\n@app.route('/templates/settings.html')\ndef index4():\n return render_template('settings.html')\n\n\noptions = [{'value':1, 'label':\"陈柱良\"},\n {'value':2, 'label':\"吴俊峰\"},\n {'value':3, 'label':\"李艳雄\"},\n {'value':4, 'label':\"吴小兰\"},\n {'value':5, 'label':\"王亚楼\"},\n {'value':6, 'label':\"庞文丰\"}\n]\n\n\n\nrecords = [ { 'src' : \"../records/face_images/20180518-101634_8_lilihan.jpg\", 'id' : 1, 'time' : \"2018-03-05\", 'second' : \"16:13:45\", \\\n'person' : \"陈柱良\", 'corrected_name':\"陈柱良\",'isChecked':False},\n{ 'src' : \"/static/images/2.jpg\", 'id' : 2, 'time' : \"2018-03-05\", 'second' : \"16:15:45\", \\\n'person' : \"吴俊峰\", 'corrected_name':\"吴俊峰\", 'isChecked':False},\n{ 'src' : \"/static/images/3.jpg\", 'id' : 3, 'time' : \"2018-03-05\", 'second' : \"16:16:41\", \\\n'person' : \"李艳雄\", 'corrected_name':\"李艳雄\", 'isChecked':False},\n{ 'src' : \"/static/images/4.jpg\", 'id' : 4, 'time' : \"2018-03-05\", 'second' : \"17:05:12\", \\\n'person' : \"陈柱良\", 'corrected_name':\"\", 'isChecked':False},\n{ 'src' : \"/static/images/5.jpg\", 'id' : 5, 'time' : \"2018-03-05\", 'second' : \"17:05:45\", \\\n'person' : \"陈柱良\", 'corrected_name':\"\",'isChecked':False},\n{ 'src' : \"/static/images/6.jpg\", 'id' : 6 ,'time' : \"2018-03-05\", 'second' : \"17:26:41\", \\\n'person' : \"吴小兰\", 'corrected_name':\"\", 'isChecked':False},\n{ 'src' : \"/static/images/7.jpg\", 'id' : 7, 'time' : \"2018-03-05\", 'second' : \"17:38:44\", \\\n'person' : \"陈柱良\", 'corrected_name':\"\", 'isChecked':False},\n{ 'src' : \"/static/images/8.jpg\", 'id' : 8, 'time' : \"2018-03-05\", 'second' : \"18:16:45\", \\\n'person' : \"吴俊峰\", 'corrected_name':\"\", 'isChecked':False}\n\n ]\na = [{'second': '10:16:46', 'corrected_name': '',\n'isChecked': False, 'id': 1,\n'src': '/home/chilam/workspace/Face_V4/records/face_images/20180518-101634_8_lilihan.jpg',\n'time': '2018-05-18', 'person': 'wuxiaolan'},]\n\nsetting = [{'start':'', 'end':'', 'mode':''}]\n\n\ndata_return = [{'length':49, 'options':options, 'records':records}]\n\n\n\n# 页面加载时发起请求,获取全部数据\n@app.route('/get_database_data',methods=['GET', 'POST'])\ndef return_records():\n print(\"get the request\")\n return_data = {}\n if request.method == 'POST':\n data = request.get_json()\n print(print(\"len of str:\",len(data['startTime'])))\n starttime = helper.transforn_time(data['startTime'])\n endtime = helper.transforn_time(data['endTime'])\n # 请求的参数,是字符形式的.\n # starttime: \"2018-05-14T16:00:00.000Z\"\n # endtime: \"2018-05-14T16:00:00.000Z\"\n # person: \"陈柱良\"\n print(\"person:\", data['person'])\n print(\"starttime:\", starttime)\n print(\"endtime:\", endtime)\n print()\n database = helper.database(\"../DB/Face_SYS_Log.sqlite\")\n values = database.get_log(starttime, endtime, data['person'])\n print(\"length of get_log database: \", len(values))\n # if(data[''])\n records = helper.get_return_data(database_data = values, page = int(data['page']))\n # print(records)\n return_data = {}\n return_data['records'] = records\n return_data['length'] = int(len(values)/8)\n return_data['options'] = options\n # return_data = [return_data]\n return json.dumps(return_data)\n\n\n@app.route('/WebApplication1/Home/Test4',methods=['GET'])\ndef return_all_getrecords():\n print(\"get the request\")\n return json.dumps(data_return)\n\n@app.route('/change_page',methods=['POST'])\ndef return_next_page():\n print(\"get the request\")\n if request.method == 'POST':\n data = request.get_json()\n starttime = helper.transforn_time(data['startTime'])\n endtime = helper.transforn_time(data['endTime'])\n print(\"person:\", data['person'])\n print(\"starttime:\", starttime)\n print(\"endtime:\", endtime)\n print(\"page:\", data['page'])\n database = helper.database(\"../DB/Face_SYS_Log.sqlite\")\n values = database.get_log(starttime, endtime, data['person'])\n print(\"length of get_log database: \", len(values))\n records = helper.get_return_data(database_data = values, page = data['page'])\n # print(records)\n return_data = {}\n return_data['records'] = records\n return_data['length'] = int(len(values)/8)\n return_data['options'] = options\n # return_data = [return_data]\n return json.dumps(return_data)\n\n\n@app.route('/correct_8records',methods=['POST'])\ndef get_corrected_records():\n print(\"get the request\")\n if request.method == 'POST':\n data = request.get_json()\n return json.dumps(data_return)\n\n\n@app.route('/update_model',methods=['POST'])\ndef update_model():\n print(\"get the request\")\n if request.method == 'POST':\n data = request.get_json()\n print(data['select_datas'])\n print(\"updatePerson_name:\",data['updatePerson_name'])\n return json.dumps(data_return)\n\n@app.route('/update_settings',methods=['POST'])\ndef settings():\n print(\"get the request\")\n if request.method == 'POST':\n setting = request.get_json()\n print(\"start:\", setting['start'])\n print(\"end:\", setting['end'])\n print(\"mode:\",setting['mode'])\n return json.dumps(setting)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')","repo_name":"Limeimay/Flask-CCTV-data-system","sub_path":"page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"20447674079","text":"#Radioactive Decay\r\n#Tyler Hegewald\r\n\r\ndecay = .12\r\ncobalt = 10\r\n\r\nfor x in range(5):\r\n decayed = float(decay * cobalt)\r\n cobalt = float(cobalt - decayed)\r\nprint(\"The amount of cobalt-60 remaining after five years is\",format(\"%.2f\"%cobalt), \"grams.\")\r\n","repo_name":"hurshy/CoDecay","sub_path":"coDecay.py","file_name":"coDecay.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"40689851291","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .str_functions import calificate_lines, flujo \n\n# cambiar la salida por un texto que sirva\ndef index(request):\n context = {'inp_value': ''}\n if request.method == \"POST\":\n inp_value = request.POST['input']\n context = {'inp_value': inp_value}\n out_value = flujo(inp_value)\n # Calcular respuesta\n \n context['out_value'] = out_value\n elif request.method == 'GET':\n inp_value = 'Ingrese aqui su texto'\n out_value = 'aqui se mostraran las respuestas'\n context['inp_value'] = inp_value\n return render(request, 'index.html', {'response': context})\n","repo_name":"ticastro/tcg-problem","sub_path":"tcg_work/tcg_app/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"8037541837","text":"import numpy as np\nfrom scipy.stats import gamma\nfrom scipy.special import gamma as gamma_func\nimport matplotlib.pyplot as plt\n\n# Target distribution\ndef p(theta):\n return np.sqrt(2/np.pi) * (theta**2 * np.exp(-theta**2 / 8) / 8)\n\n# Proposal distribution: Gamma distribution\na, scale = 2, 2 # example parameters, you may need to adjust these\ndef q(theta):\n return gamma.pdf(theta, a=a, scale=scale)\n\n# Number of samples\nN = 50000\n\nx = np.linspace(0, 50, 1000)\nplt.plot(x, p(x))\nplt.plot(x, q(x))\nplt.show()\n\n# Importance Sampling\nsamples = gamma.rvs(a=a, scale=scale, size=N)\nweights = p(samples) / q(samples)\nV_est = np.mean(weights)\nV_std = np.std(weights)\n\n# 95% Confidence Interval\nconf_int = [V_est - 1.96 * V_std / np.sqrt(N), V_est + 1.96 * V_std / np.sqrt(N)]\n\nprint(\"Estimated V:\", V_est)\nprint(\"95% Confidence Interval:\", conf_int)\n","repo_name":"alexjilkin/comp-stats","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"23119398056","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom kappa_utils import f_M, f_CH, f_kappa\n\nenergy = np.logspace(-2, 2, 500)\n\nfig, ax = plt.subplots(1, 1)\nax.plot(energy, 1e7*f_M(energy), lw=7, alpha=0.1, color='k', label='Maxwellian, $10^{7} f_M$')\nfor kappa in 1.75, 3.0, 5.0, 10.0, 20.0, 100.0:\n ax.plot(energy, f_kappa(energy, kappa)/f_M(energy), lw=3, alpha=0.5, label=r'$\\kappa = {:.1f}$'.format(kappa))\nfor a, b in (2, 0.05), (5, 0.05), (18, 0.2):\n ax.plot(energy, f_CH(energy, a, b)/f_M(energy), ls='--', lw=1.5, label='$T_C/T_H = {}$; $n_C/n_H = {:.2f}$'.format(int(a), b))\n\nax.set_xscale('log')\nax.set_yscale('log')\nax.set_ylim(0.1, 3e7)\nax.legend(fontsize='small', loc='middle left', ncol=2)\nax.set_xlabel(r'$E\\, /\\, k T$')\nax.set_ylabel(r'Excess over Maxwellian: $f\\, /\\, f_M$')\nfigname = sys.argv[0].replace('.py', '.pdf')\nfig.set_size_inches(7, 5)\nfig.tight_layout()\nfig.savefig(figname)\nprint(figname)\n","repo_name":"will-henney/kappa-paper","sub_path":"non-maxwell-distros.py","file_name":"non-maxwell-distros.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"7995400301","text":"N = 101\n\nclass Solution(object):\n def smallestTrimmedNumbers(self, nums, queries):\n ms = [ [] for i in xrange(N) ]\n for i in xrange(1, N):\n for j, num in enumerate(nums):\n item = (num[-i:], j)\n ms[i].append(item)\n ms[i].sort()\n # print ms[1]\n res = []\n for (a, b) in queries:\n res.append(ms[b][a - 1][1])\n return res\n \n \n","repo_name":"Wizmann/ACM-ICPC","sub_path":"Leetcode/Algorithm/python/3000/02343-Query Kth Smallest Trimmed Number.py","file_name":"02343-Query Kth Smallest Trimmed Number.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"79"} +{"seq_id":"15873514530","text":"import unittest\n\n\ndef longest_composite_word(word_list):\n mapping = {}\n\n for word in word_list:\n mapping[word] = True\n\n for original_word in sorted(word_list, key=len, reverse=True):\n if contains_subwords(original_word, True, mapping):\n return original_word\n\n return None\n\n\ndef contains_subwords(word, is_original_word, mapping):\n if (word in mapping) and (not is_original_word):\n return mapping[word]\n\n for i in range(1, len(word)):\n left = word[0:i]\n right = word[i:]\n\n if (\n (left in mapping)\n and (mapping[left] is True)\n and (contains_subwords(right, False, mapping))\n ):\n return True\n\n mapping[word] = False\n return False\n\n\nclass Test(unittest.TestCase):\n def test_lcw(self):\n word_list = [\"cat\", \"banana\", \"dog\", \"nana\", \"walk\", \"walker\", \"dogwalker\"]\n result = longest_composite_word(word_list)\n self.assertEqual(result, \"dogwalker\")\n\n def test_lcw_returns_none_for_no_match(self):\n word_list = [\"cat\", \"banana\", \"dog\"]\n result = longest_composite_word(word_list)\n self.assertEqual(result, None)\n\n def test_lcw_checks_alphabetically(self):\n word_list = [\n \"cat\",\n \"banana\",\n \"dog\",\n \"nana\",\n \"catbanana\",\n \"walk\",\n \"walker\",\n \"dogwalker\",\n ]\n result = longest_composite_word(word_list)\n self.assertEqual(result, \"catbanana\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ritwik12/CtCI-6th-Edition-Python","sub_path":"chapter_17/p15_longest_word.py","file_name":"p15_longest_word.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"79"} +{"seq_id":"43468656345","text":"from src.Binance import Binance\nfrom src.Blockchain import Blockchain\nfrom src.Bitmex import Bitmex\nfrom src.Bybit import Bybit\nimport time\nimport os\nimport asyncio\nimport websockets\n# from src.components.SocketServer import handler\nfrom sys import exit, argv, exc_info\n\n\n# Vars\nvalidArgs = ['binance', 'blockchain', 'bitmex', 'bybit']\n\n\ntry:\n if len(argv) <= 1:\n raise Exception('Please define source.')\n else:\n if argv[1] not in validArgs:\n raise Exception('Source is not valid. [binance, blockchain]')\n\n PATH = \"src/bin/chromedriver\"\n if os.name == 'nt':\n PATH = \"src/bin/chromedriver.exe\"\n\n print(\"Starting getting\", argv[1], \"btc value.\")\n\n # Defining per class is the easiest way to implement expantion of the scraping class.\n if argv[1] == 'binance':\n # Binance - Pattern\n binance = Binance(\"https://www.binance.com/en/trade/BTC_USDT\")\n binance.scrape(PATH)\n\n elif argv[1] == 'blockchain':\n # Blockchain - Pattern\n blockChain = Blockchain(\"https://exchange.blockchain.com/trade\")\n blockChain.scrape(PATH)\n\n elif argv[1] == 'bitmex':\n # Blockchain - Pattern\n blockChain = Bitmex(\"https://www.bitmex.com/app/trade/XBTUSD\")\n blockChain.scrape(PATH)\n\n elif argv[1] == 'bybit':\n # Bybit - Pattern\n byBit = Bybit(\"https://www.bybit.com/trade/inverse/BTCUSD\")\n byBit.scrape(PATH)\n\nexcept Exception as error:\n print(\"Oops! Error Caught:\", error)\n exit(0)\n\n","repo_name":"nnocsupnn/python-webscraper","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"5037123912","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\nimport os\r\nfrom os import path\r\nfrom os.path import join\r\n\r\nimport covid_tools as ct\r\n\r\nbasepath = os.path.abspath(os.path.join(path.dirname(__file__), '..', 'tmp',))\r\nif not os.path.exists(basepath): os.makedirs(basepath)\r\n\r\nworld = ct.fetchWorld()\r\nct.simplePlot(world, 'Global COVID-19', path.abspath(path.join(basepath, 'global1.png')), usedates = True)\r\nct.simplePlot(world, 'Global COVID-19', path.abspath(path.join(basepath, 'global2.png')), yscale = 'linear', xaxis='Day', usedates = False)\r\narea = world.getArea('US').getArea('Virginia') #.getArea('Chesapeake')\r\nct.simplePlot(area, area.a['name'] + ' COVID-19', path.abspath(path.join(basepath, 'test1.png')), 10, overlay=['avg','sum'], usedates = True)\r\nct.simplePlot(area, area.a['name'] + ' COVID-19', path.abspath(path.join(basepath, 'test2.png')), 1, overlay=['avg','sum'])\r\nct.simplePlot(area, area.a['name'] + ' COVID-19', path.abspath(path.join(basepath, 'test3.png')), 1, yscale = 'linear', usedates = True)\r\n\r\nset = {}\r\nfor k in ['Virginia', 'Michigan', 'Louisiana']:\r\n\tarea = world.getArea('US').getArea(k)\r\n\tset[area.key()] = area\r\nct.multiPlot(set, '3 States - Confirmed', path.abspath(path.join(basepath, 'test4.png')), 'CONFIRMED', 1)\r\nct.multiPlot(set, '3 States - Confirmed', path.abspath(path.join(basepath, 'test5.png')), 'CONFIRMED', 10)\r\nct.multiPlot(set, '3 States - Confirmed', path.abspath(path.join(basepath, 'test6.png')), 'CONFIRMED', 1, overlay=['avg','sum'], usedates = True)\r\nct.multiPlot(set, '3 States - Confirmed', path.abspath(path.join(basepath, 'test7.png')), 'CONFIRMED', 1, overlay=['avg','sum'], yscale='linear', usedates = True)\r\n\r\nset = {}\r\narea = world.getArea('China')\r\nset[area.key()] = area\r\n#set[world.key()] = world\r\narea = world.getArea('US')\r\nset[area.key()] = area\r\narea = world.getArea('United Kingdom')\r\nset[area.key()] = area\r\narea = world.getArea('Italy')\r\nset[area.key()] = area\r\narea = world.getArea('Spain')\r\nset[area.key()] = area\r\narea = world.getArea('France')\r\nset[area.key()] = area\r\narea = world.getArea('Iran')\r\nset[area.key()] = area\r\narea = world.getArea('Austria')\r\nset[area.key()] = area\r\n#areas = ct.generateGuides(world, 'DEATHS', 10)\r\n#for k, area in areas.items():\r\n#\tset[k] = area\r\nct.multiPlot(set, 'Plot', path.abspath(path.join(basepath, 'world_us.png')), 'DEATHS', 3, usedates = False)\r\n\r\n","repo_name":"mezcalhead/covid-19-tools","sub_path":"code/test_plotting_example.py","file_name":"test_plotting_example.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"79"} +{"seq_id":"12884978494","text":"\"\"\" Space invaders v 0.0.2 | \"\"\"\r\nimport pygame, controller\r\nfrom gun import Gun\r\nfrom pygame.sprite import Group\r\nfrom controller import WIDTH, HEIGHT\r\nfrom stats import Stats\r\nfrom scores import Scores\r\n\r\n\r\ndef run():\r\n pygame.init()\r\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\r\n pygame.display.set_caption('Космические защитники')\r\n bg_color = (0, 0, 0)\r\n gun = Gun(screen)\r\n bullets = Group()\r\n inos = Group()\r\n controller.create_army(screen, inos)\r\n stats = Stats()\r\n sc = Scores(screen, stats)\r\n # life = Life(screen)\r\n\r\n while True:\r\n controller.events(screen, gun, bullets)\r\n if stats.run_game:\r\n gun.update_gun()\r\n controller.update_bullets(screen, stats, sc, inos, bullets)\r\n controller.update_screen(bg_color, screen, stats, sc, gun, inos, bullets)\r\n controller.update_inos(stats, screen, sc, gun, inos, bullets)\r\n\r\n\r\nrun()\r\n","repo_name":"s-evg/space_invaders","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"70000944576","text":"from django.db import models\nfrom modelcluster.fields import ParentalKey\nfrom wagtail.admin.panels import FieldPanel, InlinePanel, MultipleChooserPanel\nfrom wagtail.api import APIField\nfrom wagtail.fields import RichTextField, StreamField\nfrom wagtail.models import Page, Orderable\nfrom wagtail import blocks\nfrom wagtail.images.blocks import ImageChooserBlock\n\n\nclass CardBlock(blocks.StructBlock):\n title = blocks.CharBlock(required=True, help_text='Введите ваше название')\n\n cards = blocks.ListBlock(\n blocks.StructBlock(\n [\n ('image', ImageChooserBlock(required=True)),\n ('title', blocks.CharBlock(required=True, max_length=40),),\n ('text', blocks.TextBlock(required=True, max_length=1000)),\n ('button_page', blocks.PageChooserBlock(required=False)),\n (\n 'button_url',\n blocks.URLBlock(required=False, help_text='If button above used,this button comes first'))\n ],\n\n )\n )\n\n\nclass MainPageCarousel(Orderable):\n page = ParentalKey('MainPage', related_name='Slider')\n carousel_image = models.ForeignKey(\n 'wagtailimages.Image',\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name='+',\n verbose_name='Слайдер'\n )\n panels = [\n\n FieldPanel('carousel_image')\n ]\n\n\nclass MainPage(Page):\n template = 'index.html'\n banner_title = models.CharField(max_length=100, blank=True, null=True)\n banner_subtitle = RichTextField(features=[\"bold\", \"italic\", \"h1\", \"h2\"])\n banner_image = models.ForeignKey(\n 'wagtailimages.Image',\n on_delete=models.SET_NULL,\n null=True,\n blank=True,\n related_name='+',\n verbose_name='Изображение'\n )\n content = StreamField([\n ('cards', CardBlock())\n\n ], use_json_field=True, null=True, blank=True, verbose_name='Карточки'\n )\n\n api_fields = [\n APIField('banner_title'),\n APIField('banner_subtitle'),\n APIField('banner_image')\n ]\n\n content_panels = Page.content_panels + [\n FieldPanel('banner_title'),\n FieldPanel('banner_subtitle'),\n FieldPanel('banner_image'),\n MultipleChooserPanel(\n 'Slider', label='Слайдер', chooser_field_name='carousel_image'\n\n ),\n\n FieldPanel('content')\n ]\n\n class Meta:\n verbose_name = 'Главная страница'\n","repo_name":"KyotoDalex/project1","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"10738589671","text":"#coding:utf8\nimport numpy as np\nfrom scipy.stats import norm\n\n\nfrom bokeh.plotting import figure, output_file, show, curdoc, ColumnDataSource\nfrom bokeh.layouts import row, column, widgetbox, layout, gridplot\nfrom bokeh import palettes\n\nsize = 20\nX = norm.rvs(size=(size, 3), random_state=42) * 2\n# import ipdb; ipdb.set_trace()\nX = np.dot(X, np.linalg.cholesky([[2, -1, 0], [-1, 2, -1], [0, -1, 2]]))\n\n\nx = X[:, 0]\ny = X[:, 1]\nz = X[:, 2]\n\nindex = np.argsort(x)\n\nx = x[index]\ny = y[index]\nz = z[index]\n# 创建网格点\ngrid_x, grid_y = np.meshgrid(x, y)\nvalue = np.nan * np.zeros(size)\n\nspace_colors = np.nan * np.zeros(size) # palettes.OrRd3[:2] # 超平面分隔颜色\ndot_colors = np.nan * np.zeros(size) # palettes.Paired3[:2] # 区分正负例的颜色\n# create datasource\nsource = ColumnDataSource(data=dict(x=x, y=y, z=z, value=value, grid_x=grid_x, \\\n grid_y=grid_y, space_colors=space_colors, dot_colors=dot_colors))\n\n\n# 创建制图对象\nplot = figure(plot_height=800, plot_width=800, title=\"不同参数变化残差变化\", \\\n x_range=[min(min(x)*.1, min(x) * 1.5), max(max(x) * .2, max(x)*1.5)], \\\n y_range=[min(min(y)*.1, min(y) * 1.5), max(max(y) * .2, max(y)*1.5)], \\\n tooltips=[(\"x\", \"$x\"), (\"y\", \"$y\"), (\"value\", \"@contour\")])\n\nplot.scatter(x=\"x\", y=\"y\", color=\"navy\", size=3, source=source)\n\n# setup widgets\nslope_slider = Slider(start=0, end=180, value=0, step=.05, title=\"斜率调整(角度)\")\n\nintercept_slider = Slider(title=\"截距\", start=-10, end=10, value=0, step=.25)\n\ndef update_data(attrname, old, new):\n slope_angle = float(slope_slider.value)\n slope = np.tan(slope_angle / 180 * np.pi)\n intercept = intercept_slider.value\n x = source.data['x']\n y = source.data['y']\n \n error_colors = source.data['color']\n # print(slope)\n\n # 更新预测信息和残差线\n pred = slope * x + intercept\n error_0s = list(zip(x, x))\n error_1s = list(zip(y, pred))\n\n # 更新方差信息\n error_index = range(len(X))\n error_value = np.power((pred - y), 2)\n\n source.data.update(dict(x=x, y=y, pred=pred, error_0s=error_0s, \\\n error_1s=error_1s, error_index=error_index, error_value=error_value, \\\n color=error_colors))\n\nfor w in [slope_slider, intercept_slider]:\n w.on_change(\"value\", update_data)\n\n# N = 500\n# x = np.linspace(0, 10, N)\n# y = np.linspace(0, 10, N)\n# xx, yy = np.meshgrid(x, y)\n# d = np.sin(xx)*np.cos(yy)\n\n# p = figure(tooltips=[(\"x\", \"$x\"), (\"y\", \"$y\"), (\"value\", \"@image\")])\n# p.x_range.range_padding = p.y_range.range_padding = 0\n\n# must give a vector of image data for image parameter\n# p.image(image=[d], x=0, y=0, dw=10, dh=10, palette=\"Spectral11\", level=\"image\")\n# p.grid.grid_line_width = 0.5\n\n# output_file(\"image.html\", title=\"image.py example\")\n\ncurdoc().add_root(row(plot, width=800))","repo_name":"ZenRay/Python4Fun","sub_path":"MachineLearning/perceptron/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"18646974634","text":"'''\nProblem:\n\nGiven a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.\n\nExample:\n\nInput: The root of a Binary Search Tree like this:\n 5\n / \\\n 2 13\n\nOutput: The root of a Greater Tree like this:\n 18\n / \\\n 20 13\n\n'''\n\n# Solution:“右 - 根 - 左”顺序遍历BST\n\nclass Solution(object):\n def convertBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n self.total = 0\n def traverse(root):\n if not root: return\n traverse(root.right)\n root.val += self.total\n self.total = root.val # new root value\n traverse(root.left)\n traverse(root)\n return root\n\n","repo_name":"HalfMoonFatty/Interview-Questions","sub_path":"538. Convert BST to Greater Tree.py","file_name":"538. Convert BST to Greater Tree.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"37673376841","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^dashboard/$', views.dashboard, name='dashboard'),\n url(r'^profile/$', views.profile, name='profile'),\n url(r'^reports/$', views.reports, name='reports'),\n url(r'^report_detail/(?P[0-9]+)$', views.report_details, name='report_detail'),\n]","repo_name":"elishaking/i-witness","sub_path":"officers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"3890113451","text":"#!/usr/bin/python3\nif __name__ == \"__main__\":\n from sys import argv\n from calculator_1 import add, sub, mul, div\n if len(argv) != 4:\n print(\"Usage:\", argv[0], \" \")\n exit(1)\n\n a, operand, b = int(argv[1]), argv[2], int(argv[3])\n arith = {'+': add, '-': sub, '*': mul, '/': div}\n if operand not in arith:\n print(\"Unknown operator. Only: +, -, * and / available\")\n exit(1)\n print('{:d} {} {:d} = {:d}'.format(a, operand, b, arith[operand](a, b)))\n","repo_name":"ianliu-johnston/holbertonschool-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":510,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"79"} +{"seq_id":"10646642781","text":"import pickle\nimport os\nimport time\nimport configparser\nimport shutil\n\nconfig = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())\nconfig.read('config.ini')\n\nATTRIBUTE_PATH = config.get('PATH','ATTRIBUTE_PATH') # 특징정보가 저장되어 있는 폴더\nBIPARTITE_GRAPH_PATH = config.get('PATH','BIPARTITE_GRAPH_PATH') # 이분그래프가 저장되어 있는 폴더\nATTRIBUTE_LIST = config.get('PARAMETER','ATTRIBUTE_LIST').split(',') # 유사도 분석 및 파일 전처리를 통한 특징정보 추출을 할 경우 추출할 특징정보들을 입력해준다 (입력은 각각의 특징정보에 해당하는 확장자를 입력하고 \",\" 로 구분된다.)\n\n\"\"\"\n 특징정보에 대한 이분 그래프 생성\n\"\"\"\ndef make_attribute_set():\n if not os.path.isdir(BIPARTITE_GRAPH_PATH):\n os.path.mkdir(BIPARTITE_GRAPH_PATH)\n for attribute in ATTRIBUTE_LIST:\n print(attribute + '에 대한 bipartite 그래프를 생성합니다.')\n start_time = time.time()\n make_att_set(ATTRIBUTE_PATH,attribute) # 해당 특징정보에 대한 이분 그래프 생성\n end_time = time.time()\n print('total time: {}s'.format(int(end_time - start_time)))\n print('완료')\n\n\n\"\"\"\n 특징정보에 대한 이분 그래프 생성\n path : 특징정보가 저장되어있는 폴더경로\n attribute : 이분그래프를 생성할 특징정보종류\n\"\"\"\ndef make_att_set(path,attribute):\n group_list = os.listdir(path)\n file_att_list = dict() # 키: 파일 값: 특징정보인 사전생성\n att_file_list = dict() # 키: 특징정보 값: 파일인 사전생성\n file_label_list = dict() # 키: 파일 값: 레이블인 사전생성\n for group in group_list:\n group_att_path = path + \"/\" + group + \"/\" + attribute\n if not os.path.exists(group_att_path): # 해당 특징정보가 없으면 넘어간다\n continue\n file_list = os.listdir(group_att_path)\n for file in file_list:\n file_path = file.split('.')\n with open(group_att_path + \"/\" + file, 'rb') as f:\n maldata = pickle.load(f) # 해당 특징정보 불러온다 특징정보는 1차원 list 형태로 되어있다.\n if maldata.__len__() < 1: # 빈파일은 필터링\n continue\n file_label_list[file_path[0]] = group # 그룹 정보를 저장하는 사전을 생성한다.\n for func in maldata:\n if not func in att_file_list: # {function : { filename : num1,filename2 : num2 ..} function2 : {} ...}\n att_file_list[func] = dict()\n att_file_list[func][file_path[0]] = 1\n else:\n if file_path[0] in att_file_list[func]:\n att_file_list[func][file_path[0]] += 1\n else:\n att_file_list[func][file_path[0]] = 1\n\n if not file_path[0] in file_att_list: # {filename : { function : num1,function2 : num2 ..} filename2 : {} ...}\n file_att_list[file_path[0]] = dict()\n file_att_list[file_path[0]][func] = 1\n else:\n if func in file_att_list[file_path[0]]:\n file_att_list[file_path[0]][func] += 1\n else:\n file_att_list[file_path[0]][func] = 1\n\n with open(BIPARTITE_GRAPH_PATH + '\\\\' + attribute+'_label_dict.pickle', 'wb') as handle: # 다음 사전을 pickle 파일로 저장한다.\n pickle.dump(file_label_list, handle)\n with open(BIPARTITE_GRAPH_PATH + '\\\\' + attribute+'_file_dict.pickle', 'wb') as handle: # 다음 사전을 pickle 파일로 저장한다.\n pickle.dump(att_file_list, handle)\n print(\"특징개수\",att_file_list.__len__())\n with open(BIPARTITE_GRAPH_PATH + '\\\\' + 'file_' + attribute + '_dict.pickle', 'wb') as handle2: # 다음 사전을 pickle 파일로 저장한다.\n pickle.dump(file_att_list, handle2)\n print(\"파일개수:\", file_att_list.__len__())\n\n\nif __name__ == \"__main__\":\n make_attribute_set()","repo_name":"seeklee/smuff","sub_path":"code/make_bipartite.py","file_name":"make_bipartite.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"6184409004","text":"def solution(food):\n answer = ''\n for i in range(1,len(food)):\n if food[i] == 1:\n continue\n cnt = food[i] // 2\n answer += cnt * str(i)\n answer += '0'\n for j in range(len(food)-1,0,-1):\n if food[j] == 1:\n continue\n cnt2 = food[j] // 2\n answer += cnt2 * str(j)\n return answer\n","repo_name":"shgusgh12/Python-practice","sub_path":"github/programmers/푸드파이트대회.py","file_name":"푸드파이트대회.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"4097663022","text":"import logging\nimport json\n\nfrom django.conf import settings\nfrom django.db.models import Q\nimport django_filters\nfrom rest_framework import filters\n\nfrom .models import Ticket\n\nlogger = logging.getLogger(__name__)\n\n\nclass IsNullFilter(django_filters.BooleanFilter):\n def filter(self, qs, value):\n if value is not None:\n return qs.filter(**{'{}__isnull'.format(self.name): value})\n return qs\n\n\nclass IsNotNullFilter(IsNullFilter):\n def filter(self, qs, value):\n if value is not None:\n value = not value\n return super(IsNotNullFilter, self).filter(qs, value)\n\n\nclass HoldingFilterSet(django_filters.FilterSet):\n liu_card = django_filters.CharFilter(name='person__liu_card_rfid')\n liu_id = django_filters.CharFilter(name='person__liu_id')\n purchased = IsNotNullFilter(name='cart__purchased')\n\n class Meta:\n model = Ticket\n fields = [\n 'id',\n 'liu_card',\n 'liu_id',\n 'purchased'\n ]\n\n\nclass TicketPermissionFilter(filters.BaseFilterBackend):\n def filter_queryset(self, request, queryset, view):\n if request.user.is_anonymous:\n return queryset.none()\n return queryset.owned_by(user=request.user, only_current=False)\n\n\nclass TicketOwnershipFilter(filters.BaseFilterBackend):\n def filter_queryset(self, request, queryset, view):\n if view.action == 'search':\n search_term = request.query_params['query'].strip()\n query = (\n Q(pk__icontains=search_term) |\n Q(code__icontains=search_term) |\n Q(user__nin__contains=search_term.replace('-', '')) |\n Q(user__email__icontains=search_term)\n )\n\n if search_term.isdigit():\n try:\n sesam_response = settings.SESAM_STUDENT_SERVICE_CLIENT.get_student(\n mifare_id=search_term)\n except:\n pass\n else:\n query |= Q(user__email=sesam_response.email)\n\n if search_term.startswith('{'):\n try:\n json_payload = json.loads(search_term)\n query = Q(id=json_payload['id'], code=json_payload['code'])\n except:\n pass\n\n return queryset.filter(query)\n\n if request.user.is_staff:\n return queryset\n\n if request.user.is_anonymous:\n return queryset.none()\n\n query = Q(user=request.user)\n\n code = request.query_params.get('code', None)\n if view.action != 'list' and code:\n query |= Q(code=code)\n return queryset.filter(query)\n\n\nclass UserPermissionFilter(filters.BaseFilterBackend):\n def filter_queryset(self, request, queryset, view):\n return queryset.filter(pk=request.user.pk)\n","repo_name":"ovidner/bitket","sub_path":"bitket/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"69991193855","text":"from bs4 import BeautifulSoup\nimport pandas as pd\nimport requests\nimport time\n\nlaptops = []\n\nfor x in range(1, 31):\n headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63'}\n url = 'https://www.flipkart.com/search?q=laptops&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&page='\n\n uclient = requests.get(url + str(x), headers = headers).text\n soup = BeautifulSoup(uclient, 'lxml')\n product_content = soup.find_all('div', class_ = '_3pLy-c row')\n for product in product_content:\n product_name = product.find('div', class_ = '_4rR01T').text\n product_feature = product.find('ul', class_ = '_1xgFaf').text\n product_price = product.find('div', class_ = '_30jeq3 _1_WHN1').text\n\n product_info = {\n 'Name' : product_name,\n 'Feature' : product_feature,\n 'Price' : product_price\n }\n laptops.append(product_info)\n time.sleep(2)\n\ndf = pd.DataFrame(laptops)\ndf.to_csv('laptops.csv')","repo_name":"Maheshaswin/web-scraping","sub_path":"flipkart.py","file_name":"flipkart.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"17605562654","text":"from Crypto.Cipher import AES\nimport sys, os\n\nfrom secret import flag\n\niv = os.urandom(16)\nkey = os.urandom(32)\n\ndef encrypt(plain, key, iv):\n assert (len(plain) % 16) == 0\n aes = AES.new(key, AES.MODE_CBC, iv)\n return aes.encrypt(plain)\n\ndef decrypt(cipher, key, iv):\n assert (len(cipher) % 16) == 0\n aes = AES.new(key, AES.MODE_CBC, iv)\n return aes.decrypt(cipher)\n\ndef main():\n for i in range(100):\n plain = os.urandom(48)\n new_plain_block = os.urandom(16)\n\n print(f'Cipher : {encrypt(plain, key, iv).hex()}')\n print(f'Last Block Of Plain : {plain[-16:].hex()}')\n print(f'Last Block Of New Plain : {new_plain_block.hex()}')\n new_cipher = bytes.fromhex(input('New Cipher > '))\n assert len(new_cipher) == len(plain)\n if decrypt(new_cipher, key, iv)[-16:] != new_plain_block:\n print('Wrong!')\n sys.exit()\n print(f'Flag : {flag}')\n\ntry:\n main()\nexcept:\n sys.exit()","repo_name":"Curious-Lucifer/TaiwanHolyYoung_Crypto","sub_path":"Lab/Bit_Flipping1/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"14393436180","text":"from collections import Counter\nfrom typing import List\n\n\ndef single_number(nums: List[int]) -> int:\n \"\"\"\n Time: O(n)\n Space: O(n)\n \"\"\"\n c = Counter(x for x in nums)\n for k, v in c.items():\n if v == 1:\n return k\n\n\ndef single_number_bitwise(nums: List[int]) -> int:\n \"\"\"\n Time: O(n)\n Space: O(1)\n \"\"\"\n once = twice = 0\n for i in nums:\n once = (i ^ once) & ~twice\n twice = (i ^ twice) & ~once\n return once\n","repo_name":"tuvo1106/1337code","sub_path":"0137_single_number_II/single_number.py","file_name":"single_number.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"79"} +{"seq_id":"12414739524","text":"\"\"\"\nMake buildout.dumppickedversion's features work in buildout 2\n\"\"\"\nimport os\nimport zc.buildout.easy_install\nfrom zc.buildout.buildout import print_\ntry:\n from zc.buildout.buildout import _format_picked_versions\nexcept ImportError:\n _format_picked_versions = None # buildout < 2.2\n\nFILE_NAME = 'dump-picked-versions-file'\nOVERWRITE = 'overwrite-picked-versions-file'\nTRUE = ['yes', 'true', 'on']\n\n\ndef dump_picked_versions(old_print_picked_versions, file_name, overwrite):\n \"\"\"\n Create and return a monkey patched version of print_picked_versions.\n \"\"\"\n def overwrite_picked_versions():\n \"\"\"\n Altered behavior for print_picked_versions. Basically,\n print_picked_versions is called unless the version files exists.\n\n If the version file exists and overwrite is enabled the file will\n be removed before calling print_picked_versions.\n\n If overwriting is disabled print_picked_versions is not called and\n a message is printed.\n \"\"\"\n if os.path.isfile(file_name):\n if overwrite:\n os.unlink(file_name)\n old_print_picked_versions()\n else:\n print_('Skipped: File %s already exists.' % file_name)\n else:\n old_print_picked_versions()\n return overwrite_picked_versions\n\n\ndef _file_name_and_overwrite(section):\n file_name = (FILE_NAME in section and section[FILE_NAME].strip() or None)\n overwrite = (OVERWRITE not in section or section[OVERWRITE].lower() in TRUE)\n return (file_name, overwrite)\n\n\ndef install(buildout):\n \"\"\"\n Hook into buildout and alter it's version dumping behavior.\n \"\"\"\n file_name, overwrite = _file_name_and_overwrite(buildout['buildout'])\n if hasattr(zc.buildout.easy_install , 'store_required_by'):\n store_required_by = zc.buildout.easy_install.store_required_by\n else: # buildout < 2.2\n store_required_by = zc.buildout.easy_install.store_picked_versions\n store_required_by(True)\n if file_name is None:\n # Simply enable buildout's show-picked-versions feature \n buildout.show_picked_versions = True\n elif _format_picked_versions is None: # buildout < 2.2\n # Monkey patch buildout to enable overwriting behaviour\n buildout.update_versions_file = file_name\n buildout._print_picked_versions = dump_picked_versions(\n buildout._print_picked_versions, file_name, overwrite)\n\n\ndef uninstall(buildout):\n if _format_picked_versions:\n file_name, overwrite = _file_name_and_overwrite(buildout['buildout'])\n\n if file_name is None:\n return\n if os.path.isfile(file_name) and not overwrite:\n print_('Skipped: File %s already exists.' % file_name)\n else:\n picked_versions, required_by = (zc.buildout.easy_install\n .get_picked_versions())\n output = _format_picked_versions(picked_versions, required_by)\n f = open(file_name, 'wb')\n f.write('\\n'.join(output))\n f.close()\n print_('Picked versions have been written to %s' % file_name)\n\n","repo_name":"jaap3/buildout.dumppickedversions2","sub_path":"buildout/dumppickedversions2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"72499973054","text":"import os\nimport subprocess\n\ndef execute_shell_command(cmd):\n subprocess.run([\"sh\", \"-c\", cmd])\n\ndef find_folders_with_extension(root_path, target_extension):\n folders_with_extension = []\n\n for filename in os.listdir(root_path):\n if filename.endswith(target_extension):\n folders_with_extension.append(os.path.join(root_path, filename))\n\n return folders_with_extension\n\ndef find_app_bundle(working_dir):\n payload_dir = os.path.join(working_dir, \"Payload\")\n for filename in os.listdir(payload_dir):\n if filename.endswith(\".app\"):\n return os.path.join(payload_dir, filename)\n return None\n\ndef zip_payload(working_dir, dest,):\n print(\"Zipping to {}\".format(dest))\n execute_shell_command(\"rm -rf {}\".format(dest))\n execute_shell_command(\"cd {} && zip -qr {} {}\".format(working_dir, \"tmp.ipa\", \"Payload\"))\n execute_shell_command(\"mv {}/tmp.ipa {}\".format(working_dir, dest))\n\ndef unzip_ipa(ipa, dest):\n print(\"Unzipping {}\".format(ipa))\n execute_shell_command(\"unzip -q {} -d {}\".format(ipa, dest))\n\ndef get_original_bundle_id(bundle):\n plist_path = \"{}/Info.plist\".format(bundle)\n try:\n command = [\n \"/usr/libexec/PlistBuddy\",\n \"-c\", \"Print :CFBundleIdentifier\",\n plist_path\n ]\n result = subprocess.run(command, capture_output=True, text=True, check=True)\n return result.stdout.strip()\n except (subprocess.CalledProcessError, FileNotFoundError) as e:\n print(f\"Error: {e}\")\n return None\n\ndef get_binary_name(bundle):\n plist_path = \"{}/Info.plist\".format(bundle)\n try:\n command = [\n \"/usr/libexec/PlistBuddy\",\n \"-c\", \"Print :CFBundleExecutable\",\n plist_path\n ]\n result = subprocess.run(command, capture_output=True, text=True, check=True)\n return result.stdout.strip()\n except (subprocess.CalledProcessError, FileNotFoundError) as e:\n print(f\"Error: {e}\")\n return None","repo_name":"vikage/ipa-resigner","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"3537309120","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: azure_rm_sqlsyncagent_facts\nversion_added: \"2.5\"\nshort_description: Get Sync Agent facts.\ndescription:\n - Get facts of Sync Agent.\n\noptions:\n resource_group:\n description:\n - The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n required: True\n server_name:\n description:\n - The name of the server on which the sync agent is hosted.\n required: True\n sync_agent_name:\n description:\n - The name of the sync agent.\n\nextends_documentation_fragment:\n - azure\n\nauthor:\n - \"Zim Kalinowski (@zikalino)\"\n\n'''\n\nEXAMPLES = '''\n - name: Get instance of Sync Agent\n azure_rm_sqlsyncagent_facts:\n resource_group: resource_group_name\n server_name: server_name\n sync_agent_name: sync_agent_name\n\n - name: List instances of Sync Agent\n azure_rm_sqlsyncagent_facts:\n resource_group: resource_group_name\n server_name: server_name\n'''\n\nRETURN = '''\nsync_agents:\n description: A list of dict results where the key is the name of the Sync Agent and the values are the facts for that Sync Agent.\n returned: always\n type: complex\n contains:\n syncagent_name:\n description: The key is the name of the server that the values relate to.\n type: complex\n contains:\n id:\n description:\n - Resource ID.\n returned: always\n type: str\n sample: \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/Default-SQL-Onebox/providers/Microsoft.Sql/servers/syncagentc\n rud-8475/syncAgents/syncagentcrud-3187\"\n name:\n description:\n - Resource name.\n returned: always\n type: str\n sample: syncagent\n type:\n description:\n - Resource type.\n returned: always\n type: str\n sample: Microsoft.Sql/servers/syncAgents\n state:\n description:\n - \"State of the sync agent. Possible values include: 'Online', 'Offline', 'NeverConnected'\"\n returned: always\n type: str\n sample: NeverConnected\n version:\n description:\n - Version of the sync agent.\n returned: always\n type: str\n sample: 4.2.0.0\n'''\n\nfrom ansible.module_utils.azure_rm_common import AzureRMModuleBase\n\ntry:\n from msrestazure.azure_exceptions import CloudError\n from msrestazure.azure_operation import AzureOperationPoller\n from azure.mgmt.sql import SqlManagementClient\n from msrest.serialization import Model\nexcept ImportError:\n # This is handled in azure_rm_common\n pass\n\n\nclass AzureRMSyncAgentsFacts(AzureRMModuleBase):\n def __init__(self):\n # define user inputs into argument\n self.module_arg_spec = dict(\n resource_group=dict(\n type='str',\n required=True\n ),\n server_name=dict(\n type='str',\n required=True\n ),\n sync_agent_name=dict(\n type='str'\n )\n )\n # store the results of the module operation\n self.results = dict(\n changed=False,\n ansible_facts=dict()\n )\n self.mgmt_client = None\n self.resource_group = None\n self.server_name = None\n self.sync_agent_name = None\n super(AzureRMSyncAgentsFacts, self).__init__(self.module_arg_spec)\n\n def exec_module(self, **kwargs):\n for key in self.module_arg_spec:\n setattr(self, key, kwargs[key])\n self.mgmt_client = self.get_mgmt_svc_client(SqlManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n\n if (self.resource_group is not None and\n self.server_name is not None and\n self.sync_agent_name is not None):\n self.results['sync_agents'] = self.get()\n elif (self.resource_group is not None and\n self.server_name is not None):\n self.results['sync_agents'] = self.list_by_server()\n return self.results\n\n def get(self):\n '''\n Gets facts of the specified Sync Agent.\n\n :return: deserialized Sync Agentinstance state dictionary\n '''\n response = None\n results = {}\n try:\n response = self.mgmt_client.sync_agents.get(resource_group_name=self.resource_group,\n server_name=self.server_name,\n sync_agent_name=self.sync_agent_name)\n self.log(\"Response : {0}\".format(response))\n except CloudError as e:\n self.log('Could not get facts for SyncAgents.')\n\n if response is not None:\n results[response.name] = response.as_dict()\n\n return results\n\n def list_by_server(self):\n '''\n Gets facts of the specified Sync Agent.\n\n :return: deserialized Sync Agentinstance state dictionary\n '''\n response = None\n results = {}\n try:\n response = self.mgmt_client.sync_agents.list_by_server(resource_group_name=self.resource_group,\n server_name=self.server_name)\n self.log(\"Response : {0}\".format(response))\n except CloudError as e:\n self.log('Could not get facts for SyncAgents.')\n\n if response is not None:\n for item in response:\n results[item.name] = item.as_dict()\n\n return results\n\n\ndef main():\n AzureRMSyncAgentsFacts()\nif __name__ == '__main__':\n main()\n","repo_name":"AlexanderYukhanov/ansible-hatchery","sub_path":"library/azure_rm_sqlsyncagent_facts.py","file_name":"azure_rm_sqlsyncagent_facts.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"2387667680","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 15 15:16:47 2022\n\n@author: cdiet\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Import necessary modules\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\n\nfrom SyntheticData import UniformSythetic\n\nUniformSythetic(500, 150, 2)\n\nfrom UniformAugmentation import RandUnit\n\n# Run the function\nprint(RandUnit('synthetic_data_with_labels.txt', 500, 0.1)) \n \n\nfrom LogisticRegressionReal import LogReg\n\nfeature_cols = []\nfor i in range(0, 149, 1):\n feature_cols.append(i)\nprint(LogReg(dataset = 'augmented_original_label.txt',\n feature_cols = feature_cols, target = 'status', split = 500,\n save = 'augmented_data_labels.txt'))\n\n# Take the labels from the original data, append the predicted labels\n# Add that column to original and augmented data\n\ndata = pd.read_table('augmented_original.txt', delimiter = \" \", header = None)\noriginal_label = pd.read_table('synthetic_data_labels.txt', delimiter = \" \", header = None)\n\naugmented_label = pd.read_table('augmented_data_labels.txt', delimiter = \" \", header = None)\n\nlabels = pd.concat([original_label, augmented_label])\n\n# data['status'] = labels\n\n# # Output to txt\n# np.savetxt('all_data.txt', data)\n\n#KNN\n \n# Loading data\ndfknn = pd.read_table('augmented_original.txt', delimiter = \" \", header = None)\n\n# Create feature and target arrays\nX = dfknn\ny = labels\n \n# Split into training and test set\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size = 0.2, random_state=42)\n \nknn = KNeighborsClassifier(n_neighbors=7)\n \nknn.fit(X_train, y_train)\n\n# Predict on dataset which model has not seen before\npredicted_values = (knn.predict(X_test))\n\n# ACCURACY\n\nimport sklearn.metrics as skm\n\n\naccuracy = skm.accuracy_score(y_test, predicted_values)\nprint(accuracy)\n\name_accuracy = skm.mean_absolute_error(y_test, predicted_values)\nprint(ame_accuracy)\n\nrmse_accuracy = skm.mean_squared_error(y_test, predicted_values)\nprint(rmse_accuracy)\n\n\n\n\n","repo_name":"myvl17/BryanProgram2022","sub_path":"Christina/AugmentWorkflow.py","file_name":"AugmentWorkflow.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"11025717739","text":"\"\"\"\ntest tv denoising and CS recon, algrithm using ADMM\n\"\"\"\nimport numpy as np\nimport pics.proximal_func as pf\nimport pics.CS_MRI_solvers_func as solvers\nimport pics.operators_class as opts\nimport utilities.utilities_func as ut\nfrom espirit.espirit_func import espirit_2d, espirit_3d\nimport scipy.io as sio\n\npathdat = '/working/larson/UTE_GRE_shuffling_recon/20170718_voluteer_ir_fulksp/exp2_ir_fulksp/'\n\ndef test():\n ft = opts.FFT2d() \n mat_contents = sio.loadmat(pathdat + 'rawdata.mat')\n x = mat_contents[\"da\"].squeeze(axis = 0).squeeze(axis = 3)\n mask = mat_contents[\"mask\"].squeeze(axis = 0).squeeze(axis = 3)\n Vim = mat_contents[\"calib\"][40,...]\n #ut.plotim3(np.absolute(x[:,:,:,0]))\n im = ft.backward(x)\n ut.plotim3(np.absolute(im[:,:,im.shape[2]//2,:]))\n #get shape\n nx,ny,nc,nd = x.shape\n #create espirit operator\n esp = opts.espirit(Vim)\n\n #FTm = opts.FFTnd_kmask(mask)\n FTm = opts.FFTW2d_kmask(mask, threads = 5)\n #ut.plotim1(np.absolute(mask))#plot the mask\n Aopt = opts.joint2operators(esp, FTm)\n #create image\n im = FTm.backward(x)\n #ut.plotim3(np.absolute(im[:,:,:]))\n #wavelet operator\n dwt = opts.DWT2d(wavelet = 'haar', level=4)\n # undersampling in k-space\n b = FTm.forward(im)\n scaling = ut.optscaling(FTm,b)\n b = b/scaling\n #ut.plotim3(np.absolute(Aopt.backward(b))) #undersampled imag\n\n #do tv cs mri recon\n #Nite = 20 #number of iterations\n #step = 0.5 #step size\n #tv_r = 0.002 # regularization term for tv term\n #rho = 1.0\n #xopt = solvers.ADMM_l2Afxnb_tvx( Aopt.forward, Aopt.backward, b, Nite, step, tv_r, rho )\n\n #do wavelet l1 soft thresholding\n Nite = 50 #number of iterations\n step = 1 #step size\n th = 0.1 # theshold level\n xopt = solvers.FIST_3( Aopt.forward, Aopt.backward, dwt.backward, dwt.forward, b, Nite, step, th )\n sio.savemat(pathdat + 'mripy_recon_l1wavelet.mat', {'xopt':xopt})\n ut.plotim3(np.absolute(xopt[:,:,:]))\n\n#if __name__ == \"__main__\":\n #test()\n","repo_name":"peng-cao/mripy","sub_path":"test/CS_MRI/pics_IST_3d_wavelet_L1_shuffledmprage.py","file_name":"pics_IST_3d_wavelet_L1_shuffledmprage.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-code","pt":"79"} +{"seq_id":"71187800574","text":"import os \n\nclass IterFileList(object):\n\tdef __init__(self,param):\n\t\tself.__filelist = param.get('file_list')\n\t\tself.__folder = param.get('folder')\n\t\twith open(self.__filelist) as f:\n\t\t\tself.__files = [x for x in f.read().splitlines() if os.path.isfile(x)]\n\t\t\n\tdef next(self):\n\t\tif len(self.__files)==0:\n\t\t\traise StopIteration\n\t\n\t\tpath=self.__files.pop(0)\n\t\tif self.__folder:\n\t\t\tpath=os.path.join(self.__folder, path)\t\t\n\n\t\treturn {'value':path}\n\n\tdef\tlength(self):\n\t\treturn None\n","repo_name":"jsubpy/jsub","sub_path":"jsub/exts/jobvar/iter_file_list.py","file_name":"iter_file_list.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"21170746080","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Created by FFJ on 2017-10-11\n#\n# 依赖 lxml 库: pip install lxml\n#\n# 多进程广度优先的抓取百度百科纯文本的脚本\n# 通过种子网页(主页)抓取正文文本以及所有符合要求的URL进链接库\n# 逐一访问并递归以上过程\n#\n# 修改 get_html() 中的 decode() 编码方式以获取HTML (一般是 utf-8 或 gbk )\n# 修改 get_content() 以匹配需要爬取的网站的正文所在标签\n# 修改 get_all_links() 的 matches 以匹配需要的特定URL\n#\n# 参数\n# -n 多进程数量(默认为1)\n# --log log文件名\n\n\nimport os\nimport argparse\nfrom bs4 import BeautifulSoup\nfrom utils import *\n\n# 多进程的锁\nm_lock = multiprocessing.Lock()\n\n\ndef get_content(html):\n # 获取HTML中需要的正文文本\n # 根据每个网站的源码规则来定制\n try:\n soup = BeautifulSoup(html, 'lxml')\n raw_content = soup.find_all('div', {'class': 'para'})\n content = ''\n for i in raw_content:\n i = remove_html_tag(str(i))\n i = re.sub('\\n', '', i)\n i = re.sub('\\[[0-9]+-*[0-9]*]', '', i)\n if i:\n content += '\\n{}'.format(i.strip())\n if content:\n return content\n else:\n return ''\n except Exception as e:\n logging.error('Get content: {}'.format(e))\n return ''\n\n\nclass Spider(object):\n\n def __init__(self):\n # 多进程数量\n self.process_num = args.n\n\n # 种子URL\n self.seed_url = 'https://baike.baidu.com'\n\n # 链接库文件\n self.links_base_file = args.output + '/temp_links_base.txt'\n # 已经爬过的链接库文件\n self.crawled_link_file = args.output + '/temp_crawled_links.txt'\n # 输出文件\n self.output_file = args.output + '/baidu_baike.txt'\n\n # 等待爬取的链接队列\n # 因为 multiprocessing.Queue() 最大容量只有三万多条,用 Manager().list() 代替\n self.link_queue = multiprocessing.Manager().list()\n\n # 爬过的链接列表,用于去重\n self.crawled_links_list = multiprocessing.Manager().list()\n\n def load_links(self):\n # 载入link到内存\n try:\n if os.path.exists(self.crawled_link_file):\n with open(self.crawled_link_file, 'r') as fr:\n count = 0\n for line in fr:\n count += 1\n line = line.strip()\n self.crawled_links_list.append(line)\n if count % 1000 == 0:\n logging.warning('已载入已爬链接{}条'.format(count))\n except Exception as e:\n logging.error('Load links to crawled list: {}'.format(e))\n\n try:\n if os.path.exists(self.links_base_file):\n with open(self.links_base_file, 'r') as fr:\n count = 0\n for line in fr:\n line = line.strip()\n if line not in self.crawled_links_list:\n if line not in self.link_queue:\n count += 1\n self.link_queue.append(line)\n if count % 1000 == 0:\n logging.warning('已载入待爬链接{}条'.format(count))\n except Exception as e:\n logging.error('Load links to Queue: {}'.format(e))\n\n if not self.link_queue:\n self.link_queue.append(self.seed_url)\n logging.warning(\"Load links success\")\n\n def save_content(self, html):\n # 保存正文文本到 ./output_file\n try:\n content = get_content(html)\n if content:\n with open(self.output_file, 'a', encoding='utf-8') as fw:\n fw.write('{}\\n\\n'.format(content))\n return True\n return False\n except Exception as e:\n logging.error('Save content: {}'.format(e))\n return False\n\n def save_crawled_links(self, link):\n # 保存已经抓取的link到 ./crawled_link_file\n try:\n with open(self.crawled_link_file, 'a', encoding='utf-8') as fw:\n fw.write(link + '\\n')\n except Exception as e:\n logging.error('Save crawled link:{}'.format(e))\n\n def save_all_links(self, html):\n # 获取页面所有匹配的link并保存到 ./links_base_file\n try:\n matches = re.findall('/item/[%A-Z0-9/]+', html)\n all_links = []\n for i in matches:\n i = self.seed_url + i\n all_links.append(i)\n with open(self.links_base_file, 'a', encoding='utf-8') as fw:\n for link in all_links:\n if link not in self.crawled_links_list:\n if link not in self.link_queue:\n self.link_queue.append(link)\n fw.write(link + '\\n')\n return True\n except Exception as e:\n logging.error('Save all links:{}'.format(e))\n return False\n\n def is_special_pattern_url(self, url):\n # 检测是否为指定网站的网页\n if self.seed_url in url[:40]:\n return True\n return False\n\n def run(self):\n # 多进程主循环\n while True:\n try:\n if not self.link_queue:\n time.sleep(20 + random.randint(1, 20))\n if not self.link_queue:\n with m_lock:\n self.load_links()\n url = self.link_queue.pop(0)\n\n if url in self.crawled_links_list and url != self.seed_url:\n continue\n\n self.crawled_links_list.append(url)\n self.save_crawled_links(url)\n\n html = get_html(url)\n if not html:\n continue\n\n check_save_content = self.save_content(html)\n check_save_all_links = self.save_all_links(html)\n\n if check_save_content and check_save_all_links:\n logging.warning('ok: {}'.format(url))\n\n except Exception as e:\n logging.critical('尚未预料的错误: {}'.format(e))\n continue\n\n def start(self):\n # 载入链接到内存并启动多进程\n logging.warning('Start load links')\n self.load_links()\n time.sleep(3)\n processes = []\n for i in range(self.process_num):\n t = multiprocessing.Process(target=self.run, args=())\n t.start()\n processes.append(t)\n\n for t in processes:\n t.join()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('output', help='输出文件夹路径,末尾不要带斜杠')\n parser.add_argument('-n', help='多进程数量(默认为1)', type=int, default=1)\n parser.add_argument('--log', help='输出log到文件,否则输出到控制台', action='store_true')\n args = parser.parse_args()\n\n log_flag = args.log\n if log_flag:\n log_flag = args.output + '/log.txt'\n\n logging.basicConfig(format='%(asctime)s|PID:%(process)d|%(levelname)s: %(message)s',\n level=logging.WARNING, filename=log_flag)\n\n spider = Spider()\n spider.start()\n","repo_name":"patrick-fu/spider","sub_path":"baidu_baike.py","file_name":"baidu_baike.py","file_ext":"py","file_size_in_byte":7498,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"43110447784","text":"# BM25 model to retrieve documents for queries in the Cranfield dataset and output a model scores file in trec_eval format\nfrom google.colab import drive\ndrive.mount('/content/drive')\nimport os\nos.chdir(\"/content/drive/My Drive/CA6005_Mechanics_of_Search\")\nfrom nltk.tokenize import word_tokenize\nimport xml.etree.ElementTree as ETree\nimport pandas as pd\nimport logging\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nlogger.disabled = True # to disable logging\n\n# Path to the Cranfield dataset\ndataset_path = '/content/drive/My Drive/CA6005_Mechanics_of_Search/document'\n# FIX: to parse the xml file for the document id and doc text, a fix is required to add a parent \"newroot\" to top and bottom of document XML file\ndocs_data_xml=\"/content/drive/My Drive/CA6005_Mechanics_of_Search/document/cran.all.1400.xml\"\n\nprstree = ETree.parse(docs_data_xml)\nroot = prstree.getroot()\ndoc_items = []\nall_doc_items = []\nfor doc_data in root.iter('doc'):\n docid = doc_data.find('docno').text\n doctext = doc_data.find('text').text\n \n doc_items = [docid,\n doctext]\n all_doc_items.append(doc_items)\n\n# convert the list to a dictionary\nall_doc_items_dict = dict(all_doc_items)\n\nall_doc_items_df = pd.DataFrame(all_doc_items, columns=[\n 'doc_id',\n 'doc_text'])\n\ndoc_id_text_df = all_doc_items_df[['doc_id','doc_text']].copy()\n# Load the queries from the dataset\nqueries_data_xml=\"/content/drive/My Drive/CA6005_Mechanics_of_Search/document/cran.qry.xml\"\n# parse the xml file for the query id and query text, to fix the query file, remove the last top in the file\nprstree = ETree.parse(queries_data_xml)\nroot = prstree.getroot()\nquery_items = []\nall_query_items = []\nfor query_data in root.iter('top'):\n queryid = query_data.find('num').text\n querytitle = query_data.find('title').text\n \n query_items = [queryid,querytitle]\n all_query_items.append(query_items)\n\n# convert the list to a dictionary\nall_query_items_dict = dict(all_query_items)\n\nall_query_items_df = pd.DataFrame(all_query_items, columns=[\n 'query_id','query_text'])\n \nquery_id_text_df = all_query_items_df[['query_id','query_text']].copy()\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import SnowballStemmer\n\nnltk.download('stopwords')\nnltk.download('punkt')\n\ndef preprocess(text):\n # Tokenize the text\n words = nltk.word_tokenize(text.lower())\n\n # Remove stop words\n stop_words = set(stopwords.words('english'))\n words = [word for word in words if word not in stop_words]\n\n # Stem the words\n stemmer = SnowballStemmer('english')\n words = [stemmer.stem(word) for word in words]\n\n return words\n\n#Indexing\n#using Python's built-in defaultdict and Counter classes to create an inverted index\nfrom collections import defaultdict, Counter\n\ndef build_index(docs):\n index = defaultdict(list)\n doc_lengths = {}\n\n for doc_id, doc in enumerate(docs):\n if doc is not None:\n terms = preprocess(doc)\n doc_lengths[doc_id] = len(terms)\n\n term_freqs = Counter(terms)\n else:\n logging.info('doc not processed as it is None is:'+str(doc))\n if doc is not None:\n for term, freq in term_freqs.items():\n index[term].append((doc_id, freq))\n else:\n logging.info('index not created for doc as its text is None is:'+str(doc))\n\n return index, doc_lengths\n# To calculate the BM25 score, need to calculate the values below\n\n# f: term frequency in the document\n# qf: term frequency in the query\n# df: document frequency of the term\n# N: total number of documents in the collection\n# dl: length of the document in terms\n# avdl: average length of documents in the collection\n# k1 and b: tuning parameters\n#the following formula to calculate the BM25 score:\n\n# score(d, q) = ∑ (idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avdl)) * (qf * (k2 + 1)) / (qf + k2))\n\nimport math\n\ndef bm25_score(query, index, doc_lengths, k1=1.2, b=0.75, k2=100):\n logging.info('query input to bm25_score function is:'+str(query))\n logging.info('index input to bm25_score function is:'+str(index))\n logging.info('doc_lengths input to bm25_score function is:'+str(doc_lengths))\n scores = defaultdict(float)\n query_terms = preprocess(query)\n logging.info('query_terms after preporcessing in the bm25_score function is:'+str(query_terms))\n\n N = len(doc_lengths)\n avdl = sum(doc_lengths.values()) / N\n\n for term in query_terms:\n if term not in index:\n continue\n\n df = len(index[term])\n logging.info('df is:'+str(df))\n logging.info('N is:'+str(N))\n idf = math.log((N - df + 0.5) / (df + 0.5))\n # Calculate the term frequency in the query\n qf = query_terms.count(term)\n logging.info('The term frequency (qf) in the query is:'+str(qf))\n \n for doc_id, freq in index[term]:\n f = freq\n dl = doc_lengths[doc_id]\n logging.info('idf in bm25_score function is:'+str(idf))\n logging.info('term in bm25_score function is:'+str(term))\n logging.info('doc_id in bm25_score function is:'+str(doc_id))\n logging.info('freq in bm25_score function is:'+str(freq))\n logging.info('doc_lengths in bm25_score function is:'+str(doc_lengths))\n logging.info('dl in bm25_score function is:'+str(dl))\n logging.info('doc_id in bm25_score function is:'+str(doc_id))\n score = idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avdl)) * (qf * (k2 + 1)) / (qf + k2)\n scores[doc_id] += score\n\n return scores\n# format the output file as follows\n\n# query_id Q0 doc_id rank score run_id\n\nimport os\nimport subprocess\n\nindex, doc_lengths = build_index(all_doc_items_dict.values())\n\nresults = {}\nfor query_id, query_text in all_query_items_dict.items():\n query_scores = bm25_score(query_text, index, doc_lengths)\n for doc_id, score in sorted(query_scores.items(), key=lambda x: x[1], reverse=True)[:100]:\n results.setdefault(query_id, []).append((doc_id, score))\n \nos.chdir(\"/content/drive/My Drive/CA6005_Mechanics_of_Search/result\")\n\nwith open('bm25_all_results.txt', 'w') as f:\n for query_id, doc_scores in results.items():\n for i, (doc_id, score) in enumerate(doc_scores):\n f.write(f'{query_id} Q0 {doc_id} {i+1} {score:.6f} BM25\\n')\n","repo_name":"robertquinn45/CA6005_Mechanics_of_search_assignment_1","sub_path":"python/bm25_cranfield_trec_eval.py","file_name":"bm25_cranfield_trec_eval.py","file_ext":"py","file_size_in_byte":6388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"22574788815","text":"from PIL import Image\nimport streamlit as st\nimport easyocr as oc\nimport pandas as pd\nimport time\nimport os\nimport io\n\nst.set_page_config(page_title='Business Card',\n page_icon='🎴',\n layout='centered')\n\nst.markdown('',unsafe_allow_html=True)\n\nfil=Image.open('./1.png')\n\ncol1,col2=st.columns([1,2])\n\n# Initialize EasyOCR reader\nreader = oc.Reader(['en'], gpu=False)\n\n# File upload section\nst.markdown(\"# Welcome to the File Reader\")\n\n#f1 = st.file_uploader(':file_folder: **Upload a file** ', type=[\"jpg\", \"png\", \"jpeg\"])\n\n\n# Display a label and file uploader widget\nuploaded_file = st.file_uploader(\"Upload a file\", type=[\"jpg\", \"png\", \"jpeg\"])\n \n\nif uploaded_file is not None:\n st.image(uploaded_file)\n n=uploaded_file.name\n result=reader.readtext(n)\n\n name=tuple(result[0])\n role=tuple(result[1])\n phone_number=tuple(result[2])\n email=tuple(result[3])\n website=tuple(result[4])\n with st.expander(\" # Click to see the details \"):\n st.write( \" Name :\",name ) \n st.write(\"# Role :\",role) \n st.write(\"# Phone_number :\",phone_number) \n st.write(\"# Email :\",email)\n st.write(\"# Website :\",website) \nelse:\n st.write('Please upload the image')\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n\n\n\n\n\n\n\n\n# my_bar=st.progress(0,r=result)\n\n#for r in range(100):\n # time.sleep(0.1)\n # my_bar.progress(r+1,r=result)\n # st.success(\"File uploded sucessfully\")\n\n\n# st.expander(\"click Here to see the details of the card\")\n\n","repo_name":"dineshkannandk/project__easyocr","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"12533285126","text":"# Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.\n\n# Assume the environment does not allow you to store 64-bit integers (signed or unsigned).\n\nclass Solution:\n def reverse(self, x: int) -> int:\n digs = []\n\n state = 1\n if x < 0:\n state = -1\n x = abs(x)\n while x > 0:\n digs.append(x%10)\n x = x//10\n power = len(digs) - 1\n ans = 0\n for dig in digs:\n ans += dig * 10**power\n power = power - 1\n ans = state * ans\n if state == 1 and ans > 2**31 -1:\n return 0\n elif state == -1 and ans < -2**31:\n return 0\n else:\n return ans\n ","repo_name":"atharvamm/programming_notes","sub_path":"python/prac/leetcode/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"24360367778","text":"import os\nfrom configparser import ConfigParser\nimport time\nfrom dateutil.parser import parse as date_parse\nfrom datetime import date,timezone,datetime \nimport json\n\nimport google.oauth2.credentials\n\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom google_auth_oauthlib.flow import InstalledAppFlow\n\nfrom youtube import SubscriptionsList,Channel,get_subscriptions, load_local_videos\nfrom setup import Setup\nfrom google_chromecast import Chromecast\n\nfrom PyInquirer import prompt\nfrom examples import custom_style_2\n\n# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains\n# the OAuth 2.0 information for this application, including its client_id and\n# client_secret.\nCLIENT_SECRETS_FILE = \"client_secret.json\"\n\n# This OAuth 2.0 access scope allows for full read/write access to the\n# authenticated user's account and requires requests to use an SSL connection.\nSCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']\nAPI_SERVICE_NAME = 'youtube'\nAPI_VERSION = 'v3'\n\n#Class for google authentication\nclass Authentication:\n def __init__(self):\n \"\"\"Create the authentication object and save load all that is necessary\n \"\"\"\n exist = os.path.isfile('./user.ini')\n if exist:\n config = ConfigParser()\n config.read('./user.ini')\n self.token = config['YouTube']['token']\n self.refresh_token = config['YouTube']['refresh_token']\n self.id_token = config['YouTube']['id_token']\n self.token_uri = config['YouTube']['token_uri']\n self.client_id = config['YouTube']['client_id']\n self.client_secret = config['YouTube']['client_secret']\n else:\n self.get_authenticated_service()\n \n def get_authenticated_service(self):\n \"\"\"Get the first authentication from Google if the user.ini file does not exist\n or if something in the user.ini is not working\n \"\"\"\n flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)\n credentials = flow.run_console()\n authentication.save_auth_info(credentials)\n return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) \n \n #Check if token expired and get a new one\n def check_auth_token(self):\n config = ConfigParser()\n config.read('./user.ini')\n\n #Setup the credentials\n credentials = google.oauth2.credentials.Credentials(\n token=config['YouTube']['token'],\n refresh_token=config['YouTube']['refresh_token'],\n id_token=config['YouTube']['id_token'],\n token_uri=config['YouTube']['token_uri'],\n client_id=config['YouTube']['client_id'],\n client_secret=config['YouTube']['client_secret'],\n scopes=SCOPES\n )\n \n #Get a new token\n if(time.time() > float(config['YouTube']['token_received']) + 3600):\n #Refresh the token\n request = google.auth.transport.requests.Request()\n credentials.refresh(request)\n\n #Set all of our new variables\n self.token = credentials.token\n self.refresh_token = credentials.refresh_token\n self.id_token = credentials.id_token\n self.token_uri = credentials.token_uri\n self.client_id = credentials.client_id\n self.client_secret = credentials.client_secret\n\n #Save the new variables to the file\n self.save_auth_info(credentials)\n return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)\n \n else:\n return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) \n\n def save_auth_info(self,credentials : google.oauth2.credentials.Credentials):\n #Check if file exists\n exist = os.path.isfile('./user.ini')\n\n #This may need to check the user.ini for any problems\n if exist is not True:\n open('./user.ini','a').close()\n\n config = ConfigParser()\n cfgfile = open('./user.ini','w')\n\n config.add_section('YouTube')\n config.set('YouTube','token',credentials.token)\n config.set('YouTube','refresh_token',credentials._refresh_token)\n config.set('YouTube','id_token',str(credentials.id_token))\n config.set('YouTube','token_uri',credentials.token_uri)\n config.set('YouTube','client_id',str(credentials.client_id))\n config.set('YouTube','client_secret',credentials.client_secret)\n config.set('YouTube','token_received',str(time.time()))\n config.write(cfgfile)\n cfgfile.close() \n\nauthentication : Authentication\n\ndef save_to_json(outfile, jsonfile):\n with open(outfile,'w') as out:\n json.dump(jsonfile,out)\n\ndef cmd(videos):\n while(True):\n uInput = input('> ')\n if uInput == 'exit':\n exit(1)\n if uInput == 'help':\n print('\"exit\" = exit from program\\n\\\n \"new\" without args = fetch new videos with defined filter before launching program\\n \\\n \"new\" with same way filter is used = fetch new videos with new defined filter arg')\n \n #Get new videos from subscriptions\n if uInput == 'ls':\n try:\n channel.get_channel_videos(service,setup.args.filter.date())\n except AttributeError:\n channel.check_uploads_playlist_refresh()\n channel.get_channel_videos(service,setup.args.filter.date())\n \n i = 0\n for video in videos:\n print(str(i) + ') ' + video)\n i += 1\n\n #Get a new set of uploads\n if uInput == 'new':\n channel.get_channel_videos(service,setup.args.filter.date())\n videos = load_local_videos()\n\n i = 0\n for video in videos:\n print(str(i) + ') ' + video)\n i += 1\n\n if 'new' in uInput and len(uInput) > 1:\n filter_date = datetime.fromtimestamp(time.time() - float(uInput.split()[1]) * 86400).date() \n print('Getting a new set of uploads with the filter date of ' + str(filter_date))\n channel.get_channel_videos(service,filter_date)\n\n #Cast to Google Chromecast the video that should be played \n elif uInput.isdigit(): \n chromecast.play_youtube_video(videos[int(uInput)])\n\nif __name__ == '__main__':\n authentication = Authentication()\n channel = Channel()\n setup = Setup()\n chromecast = Chromecast()\n \n service = authentication.check_auth_token()\n subs = None\n if setup.args.new is True:\n print('Getting new subscription channels')\n subs = get_subscriptions(service=service,maxResults=50)\n channel.get_uploads_playlist(service,subs)\n \n else:\n print(\"Using local subscription channels\")\n subs = channel.get_subscriptions_from_txt()\n \n videos = {}\n if setup.args.list is True:\n channel.check_uploads_playlist_refresh()\n videos = channel.get_channel_videos(service,setup.args.filter.date())\n \n #Get on the new line from when updating the same line-\n print('\\n')\n i = 0\n for video in videos.keys():\n print(str(i) + ') ' + str(video))\n i += 1\n else:\n videos = load_local_videos()\n\n i = 0\n for video in videos:\n print(str(i) + ') ' + video)\n i += 1\n\n #Video Selection\n upload_videos = [\n {\n 'type':'list',\n 'name':'videos',\n 'message':'Select a video to cast',\n 'choices':videos.keys()\n }\n ]\n\n while(True):\n try : \n video_choice = prompt(upload_videos,style=custom_style_2)\n os.system('clear')\n chromecast.play_youtube_video(videos[video_choice['videos']])\n \n #When ctrl+c is pressed, prevent chromecast from spewing out this \n except KeyError: exit(1)","repo_name":"Christopher876/BetterYTSubBox","sub_path":"BetterYTSubBox.py","file_name":"BetterYTSubBox.py","file_ext":"py","file_size_in_byte":8070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"17644201737","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom builtins import *\n\n# pragma pylint: enable=redefined-builtin\n# pragma pylint: enable=unused-wildcard-import\n# pragma pylint: enable=wildcard-import\n\nimport logging\nimport sys\n\nimport eta.core.annotations as etaa\nfrom eta.core.config import Config\nimport eta.core.module as etam\nimport eta.core.objects as etao\nimport eta.core.video as etav\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ModuleConfig(etam.BaseModuleConfig):\n \"\"\"Module configuration settings.\n\n Attributes:\n data (DataConfig)\n parameters (ParametersConfig)\n \"\"\"\n\n def __init__(self, d):\n super(ModuleConfig, self).__init__(d)\n self.data = self.parse_object_array(d, \"data\", DataConfig)\n self.parameters = self.parse_object(d, \"parameters\", ParametersConfig)\n\n\nclass DataConfig(Config):\n \"\"\"Data configuration settings.\n\n Inputs:\n video_path (eta.core.types.Video): A video\n video_labels_path (eta.core.types.VideoLabels): [None] A JSON file\n containing the video labels\n objects_path (eta.core.types.DetectedObjects): [None] A JSON file\n containing the detected objects\n\n Outputs:\n output_path (eta.core.types.VideoFile): The labeled video\n \"\"\"\n\n def __init__(self, d):\n self.video_path = self.parse_string(d, \"video_path\")\n self.video_labels_path = self.parse_string(\n d, \"video_labels_path\", default=None\n )\n self.objects_path = self.parse_string(d, \"objects_path\", default=None)\n self.output_path = self.parse_string(d, \"output_path\")\n\n\nclass ParametersConfig(Config):\n \"\"\"Parameter configuration settings.\n\n Parameters:\n annotation_config (eta.core.types.Config): [None] an\n `eta.core.annotations.AnnotationConfig` describing how to render\n the annotations on the video. If omitted, the default settings are\n used\n \"\"\"\n\n def __init__(self, d):\n self.annotation_config = self.parse_object(\n d, \"annotation_config\", etaa.AnnotationConfig, default=None\n )\n\n\ndef _visualize_labels(config):\n annotation_config = config.parameters.annotation_config\n\n for data in config.data:\n _process_video(data, annotation_config)\n\n\ndef _process_video(data, annotation_config):\n # Load labels\n if data.video_labels_path:\n logger.info(\"Reading labels from '%s'\", data.video_labels_path)\n labels = etav.VideoLabels.from_json(data.video_labels_path)\n elif data.objects_path:\n logger.info(\"Reading objects from '%s'\", data.objects_path)\n objects = etao.DetectedObjectContainer.from_json(data.objects_path)\n labels = etav.VideoLabels.from_objects(objects)\n else:\n logger.info(\"No labels found; rendering raw video\")\n labels = etav.VideoLabels()\n\n # Annotate video\n logger.info(\"Writing annotated video to '%s'\", data.output_path)\n etaa.annotate_video(\n data.video_path,\n labels,\n data.output_path,\n annotation_config=annotation_config,\n )\n\n\ndef run(config_path, pipeline_config_path=None):\n \"\"\"Run the visualize_labels module.\n\n Args:\n config_path: path to a ModuleConfig file\n pipeline_config_path: optional path to a PipelineConfig file\n \"\"\"\n config = ModuleConfig.from_json(config_path)\n etam.setup(config, pipeline_config_path=pipeline_config_path)\n _visualize_labels(config)\n\n\nif __name__ == \"__main__\":\n run(*sys.argv[1:]) # pylint: disable=no-value-for-parameter\n","repo_name":"voxel51/eta","sub_path":"eta/modules/visualize_labels.py","file_name":"visualize_labels.py","file_ext":"py","file_size_in_byte":3654,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"79"} +{"seq_id":"28688849467","text":"from __future__ import division\nfrom math import radians, cos, sin, asin, sqrt, exp\nfrom datetime import datetime\nfrom pyspark import SparkContext\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.tree import DecisionTree, DecisionTreeModel, RandomForest, RandomForestModel\nfrom pyspark.mllib.linalg import Vectors\n\nsc = SparkContext(appName=\"lab_kernel\")\ntemperature_file = sc.textFile(\"BDA/input/temperature-readings.csv\")\nstations_file = sc.textFile(\"BDA/input/stations.csv\")\n\ndef haversine(lon1, lat1, lon2, lat2):\n \"\"\"\n Calculate the great circle distance between two points\n on the earth (specified in decimal degrees)\n \"\"\"\n\n # convert decimal degrees to radians\n lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])\n # haversine formula\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\n c = 2 * asin(sqrt(a))\n km = 6367 * c\n return km\n\nh_distance = 100\nh_date = 10\nh_time = 2\n#latitude and longitude for Danderyd\na = 59.4113 #latitude\nb = 18.0578 #longitude\npredDate = datetime(2013,7,4) # Up to you\n\n# Your code here\n\ntemp_lines = temperature_file.map(lambda line: line.split(\";\"))\nstation_lines = stations_file.map(lambda line: line.split(\";\"))\nstations_rdd = station_lines.map(lambda x: (x[0], (float(x[3]), float(x[4]))))\n\n#Use broadcast to filter the stations\nstations_bc = stations_rdd.collectAsMap()\nstations_bc = sc.broadcast(stations_bc)\n\n# rdd(Station, (date, time, temp, latitude, longitude))\nrdd = temp_lines.map(lambda x: (x[0], (datetime(int(x[1][0:4]), int(x[1][5:7]), int(x[1][8:10])), int(x[2][0:2]), float(x[3]),\n stations_bc.value[x[0]][0], stations_bc.value[x[0]][1])))\n\nrdd = rdd.sample(False, 0.05) #only take 10%\n\n# Creating the distance kernel\ndef distanceKernel(predLat, predLong, dataLat, dataLong, h):\n u = haversine(predLong, predLat, dataLong, dataLat)/h\n return(exp(-u**2))\n\n# Creating the day kernel\ndef dayKernel(predDate, dataDate, h):\n d = (predDate-dataDate).days % 365\n if (d>365/2):\n d = 365-d\n u = d/h\n return(exp(-u**2))\n\n# Creating the time kernel\ndef timeKernel(predHour, dataHour, h):\n d = abs(predHour-dataHour)\n if(d>12):\n d = 24-d\n u = d/h\n return(exp(-u**2))\n\n#filter out dates before our prediction dates\nrdd = rdd.filter(lambda x: (x[1][0] < predDate))\nrdd.cache()\n\n##----------------ML---------------------------##\n\n# RDD = (Temp, [year, month, day, time, latitude, longitude])\nrdd_ml = rdd.map(lambda x: (x[1][2], (x[1][0].year, x[1][0].month, x[1][0].day, x[1][1], x[1][3], x[1][4])))\niterations = 100\nstep_size = 1.0\nnumTrees=5\nmaxDepth=10\ncat = {}\ntrain_data = rdd_ml.map(lambda x: LabeledPoint(x[0], x[1]))\nran_reg_model = RandomForest.trainRegressor(train_data, categoricalFeaturesInfo={}, numTrees=numTrees, maxDepth=maxDepth)\ndec_tree_model = DecisionTree.trainRegressor(train_data, categoricalFeaturesInfo={}, maxDepth = maxDepth)\n\nresult_ran = []\nresult_dec = []\n\nfor time in [\"24:00:00\", \"22:00:00\", \"20:00:00\", \"18:00:00\", \"16:00:00\", \"14:00:00\",\n\"12:00:00\", \"10:00:00\", \"08:00:00\", \"06:00:00\", \"04:00:00\"]:\n time_int = int(time[0:2])\n data = [predDate.year, predDate.month, predDate.day, time_int, a,b]\n result_ran.append((time, ran_reg_model.predict(data)))\n result_dec.append((time, dec_tree_model.predict(data)))\n\nresult_ran = sc.parallelize(result_ran)\nresult_dec = sc.parallelize(result_dec)\nresult_ran.coalesce(1).saveAsTextFile(\"BDA/output_3_ran\")\nresult_dec.coalesce(1).saveAsTextFile(\"BDA/output_3_dec\")\n\n##------------------Kernels--------------------##\n\n#run kernel functions, save rdd(time, temp, sumKernel, sumKernel*temp, prodKernel, prodKernel*temp)\n\nrdd = rdd.map(lambda x: (x[1][1], x[1][2],\n (distanceKernel(a, b, x[1][3], x[1][4], h_distance)+dayKernel(predDate, x[1][0], h_date)),\n ((distanceKernel(a, b, x[1][3], x[1][4], h_distance)+dayKernel(predDate, x[1][0], h_date))*x[1][2]),\n (distanceKernel(a, b, x[1][3], x[1][4], h_distance)*dayKernel(predDate, x[1][0], h_date)),\n ((distanceKernel(a, b, x[1][3], x[1][4], h_distance)*dayKernel(predDate, x[1][0], h_date))*x[1][2])))\n\nnewMap = True\n\nfor time in [\"24:00:00\", \"22:00:00\", \"20:00:00\", \"18:00:00\", \"16:00:00\", \"14:00:00\",\n\"12:00:00\", \"10:00:00\", \"08:00:00\", \"06:00:00\", \"04:00:00\"]:\n time_int = int(time[0:2])\n rdd_temp = rdd.filter(lambda x: (x[0] < time_int))\n rdd_temp.cache()\n #run kernel functions, save rdd(1, temp, sumKernel, prodKernel)\n rdd_temp = rdd_temp.map(lambda x:(1,\n ((x[2]+timeKernel(time_int, x[0], h_time)),\n (x[3]+(timeKernel(time_int, x[0], h_time)*x[1])),\n (x[4]*timeKernel(time_int, x[0], h_time)),\n (x[5]*timeKernel(time_int, x[0], h_time)))))\n\n# Make sure sum of kernels equals 1\n rdd_temp = rdd_temp.reduceByKey(lambda x,y: ((x[0]+y[0]),(x[1]+y[1]),(x[2]+y[2]),(x[3]+y[3])))\n rdd_temp = rdd_temp.mapValues(lambda x: ((x[1]/x[0]), (x[3]/x[2])))\n predictions.append(rdd_temp.collect())\n\n if (newMap):\n kernel_sum = rdd_temp.map(lambda x: (time, x[1][0]))\n kernel_prod = rdd_temp.map(lambda x: (time, x[1][1]))\n newMap = False\n else:\n kernel_sum = kernel_sum.union(rdd_temp.map(lambda x: (time, x[1][0])))\n kernel_prod = kernel_prod.union(rdd_temp.map(lambda x: (time, x[1][1])))\n\n#Save the results to text file\nkernel_sum.coalesce(1).saveAsTextFile(\"BDA/output_3_sum\")\nkernel_prod.coalesce(1).saveAsTextFile(\"BDA/output_3_prod\")\n","repo_name":"snallfot8/TDDE31_Labs","sub_path":"lab3-ml/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":5489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"512097531","text":"import numpy as np\n\nN = 100\n\neuler = 360.0 * (np.random.uniform(size=(N, 3)) - 0.5)\nquaternion = np.random.uniform(size=(N, 4))\n\nnp.savetxt(\"euler.out\", euler, delimiter=\",\" )\nnp.savetxt(\"quaternion.out\", quaternion, delimiter=\",\" )\n\ner = np.loadtxt(\"euler.out\", delimiter=\",\")\nqr = np.loadtxt(\"quaternion.out\", delimiter=\",\")\n\nassert (euler == er).all()\nassert (quaternion == qr).all()\n","repo_name":"RaviRongali/SSL","sub_path":"Outlab 4- Python Advanced/Outlab 4- Python Advanced/P7/lsref.py","file_name":"lsref.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"34627255813","text":"# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:\n#\n# 1/2\t= \t0.5\n# 1/3\t= \t0.(3)\n# 1/4\t= \t0.25\n# 1/5\t= \t0.2\n# 1/6\t= \t0.1(6)\n# 1/7\t= \t0.(142857)\n# 1/8\t= \t0.125\n# 1/9\t= \t0.(1)\n# 1/10\t= \t0.1\n# Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.\n#\n# Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.\nimport math\n\n\ndef count_recurring_cycle(n, m):\n result = \"\"\n list_of_divisors = [10]\n current_divide = n*10\n current_result = math.floor(current_divide / m)\n result = result + str(current_result)\n rest = current_divide % m\n while rest*10 not in list_of_divisors and rest != 0:\n current_divide = rest * 10\n list_of_divisors.append(current_divide)\n current_result = math.floor(current_divide / m)\n result = result + str(current_result)\n rest = current_divide % m\n\n if rest == 0:\n return 0\n for i in range(len(list_of_divisors)):\n if list_of_divisors[i] == rest*10:\n return len(result) - i\n\n\nhighest_cycle = 6\ncorrect_number = 7\nfor n in range(1, 1000):\n current_cycle = count_recurring_cycle(1, n)\n if current_cycle > highest_cycle:\n highest_cycle = current_cycle\n correct_number = n\nprint(correct_number)","repo_name":"Tunesius/ProjectEuler","sub_path":"Problems/26.py","file_name":"26.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"14260897278","text":"class Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n low,high=0,len(nums)-1\n while low<=high:\n mid=low+(high-low)//2\n if mid==0 or mid==len(nums)-1: break\n if nums[mid]==nums[mid-1]:\n if (mid-low+1)%2!=0: high=mid\n else: low=mid+1\n elif nums[mid]==nums[mid+1]:\n if ((mid-1)-low-1)%2!=0: high=mid-1\n else: low=mid\n else: break\n return nums[mid] ","repo_name":"a-ma-n/Leetcode_Solutions","sub_path":"0540-single-element-in-a-sorted-array/0540-single-element-in-a-sorted-array.py","file_name":"0540-single-element-in-a-sorted-array.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"79"} +{"seq_id":"36353068418","text":"from GNN_word_saliency import computer_best_substitution, computer_word_saliency_cos\nfrom models import Model # main return encoder vector\nfrom eval import Test\nfrom gensim.models.word2vec import Word2Vec\nimport torch\nfrom encoder.rnnModel import Seq2Seq\n\ntorch.cuda.current_device()\nimport warnings\n\nwarnings.filterwarnings('ignore')\nimport pandas as pd\nimport time\nimport numpy as np\n\n\ndef softmax(x):\n exp_x = np.exp(x)\n softmax_x = exp_x / np.sum(exp_x)\n return softmax_x\n\n\ndef get_topk_index(k, arr):\n top_k = k\n array = arr\n top_k_index = array.argsort()[::-1][0:top_k]\n return top_k_index\n\n \ndef rank_variable(test,code,ast,summary,variable_list,nearest_k_dict,vocab,embeddings,max_token,\n model_encoder,vocab_src,vocab_trg,max_token_src,max_token_trg):\n\n\n word_saliency_list = computer_word_saliency_cos(model_encoder, code, summary, variable_list,\n vocab,embeddings,max_token,\n vocab_src, vocab_trg, max_token_src, max_token_trg)\n best_substitution_list = computer_best_substitution(test, code, ast, edg,summary, variable_list, nearest_k_dict)\n unk_delta_bleu = []\n best_delta_bleu = []\n best_sub_list = []\n for item in word_saliency_list:\n unk_delta_bleu.append(item[1])\n for item in best_substitution_list:\n best_delta_bleu.append(item[2])\n best_sub_list.append(item[1])\n\n np_unk_delta_bleu = np.array(unk_delta_bleu)\n np_best_delta_bleu = np.array(best_delta_bleu)\n np_unk_delta_bleu_soft = softmax(np_unk_delta_bleu)\n sorce = np_unk_delta_bleu_soft * np_best_delta_bleu\n for i in range(len(sorce)):\n if sorce[i] == 0 and np_unk_delta_bleu_soft[i] != 0:\n sorce[i] = np_unk_delta_bleu_soft[i] * 0.5\n if sorce[i] == 0 and np_best_delta_bleu[i] != 0:\n sorce[i] = np_best_delta_bleu[i]\n\n descend_index = get_topk_index(len(sorce), sorce)\n descend_variable = {}\n for item in descend_index:\n var = variable_list[item]\n sub = best_sub_list[item]\n descend_variable[var] = sub\n print(descend_variable)\n return descend_variable\n\n\nif __name__ == '__main__':\n print('start at time:')\n print(time.strftime(' %H:%M:%S', time.localtime(time.time())))\n \n data_root='/dataset/java/test/'\n \n code_path=data_root+'code.original'\n ast_node_path=data_root+'node.token'\n summ_path=data_root+'javadoc.original'\n\n f_code=open(code_path, 'r')\n f_ast=open(ast_node_path,'r')\n f_summ=open(summ_path,'r')\n \n edg_df=pd.read_pickle('/dataset/java/test/adj.pkl')\n edg_list=edg_df['edge'].tolist()\n\n \n \n nearest_k_data = pd.read_pickle(\n '/dataset/java/test/nearest_k_for_everyVar.pkl')\n var_everyCode_data = pd.read_pickle(\n '/dataset/java/test/var_for_everyCode.pkl')\n nearest_k_list = nearest_k_data['nearest_k'].tolist()\n var_everyCode_list = var_everyCode_data['variable'].tolist()\n \n\n model_path=''\n\n print('-----------------create Test class------------:')\n model=torch.load(model_path)\n test = Test(model)\n\n print('read embedding....')\n root = ' '\n word2vec = Word2Vec.load('./embedding/java/train/node_w2v_64').wv\n vocab = word2vec.vocab\n max_token = word2vec.syn0.shape[0]\n embedding_dim = word2vec.syn0.shape[1]\n embeddings = np.zeros((max_token + 1, embedding_dim))\n embeddings[:max_token] = word2vec.syn0\n print('end read embedding..')\n\n\n print('read embedding of src and trg....')\n word2vec_src = Word2Vec.load(\n '/encoder/vocab/train/node_w2v_code_64').wv\n vocab_src = word2vec_src.vocab\n max_token_src = word2vec_src.syn0.shape[0]\n embedding_dim = word2vec_src.syn0.shape[1]\n embeddings_src = np.zeros((max_token_src + 1, embedding_dim))\n embeddings_src[:max_token_src] = word2vec_src.syn0\n\n word2vec_trg = Word2Vec.load( \n '/encoder/vocab/train/node_w2v_summ_64').wv\n vocab_trg = word2vec_trg.vocab\n max_token_trg = word2vec_trg.syn0.shape[0]\n embedding_dim = word2vec_trg.syn0.shape[1]\n embeddings_trg = np.zeros((max_token_trg + 1, embedding_dim))\n embeddings_trg[:max_token_trg] = word2vec_trg.syn0\n\n print('load encoder model:')\n model_encoder = Seq2Seq(embeddings_src,embeddings_trg)\n model_encoder.load_state_dict(torch.load(\n '/encoder/model.pkl'))\n \n count = 0\n \n \n best_descend_var_list = []\n \n for code,ast,summ in zip(f_code, f_ast, f_summ):\n \n edg=edg_list[count]\n \n variable_list = var_everyCode_list[count]\n nearest_k_dict = nearest_k_list[count]\n descend_variable_dict = rank_variable(test, code,ast,summ,variable_list,nearest_k_dict,vocab,embeddings,max_token,\n model_encoder,vocab_src,vocab_trg,max_token_src,max_token_trg)\n best_descend_var_list.append(descend_variable_dict)\n count = count + 1\n print('ok' + str(count))\n\n\n\n \n index = [i for i in range(len(best_descend_var_list))]\n data_descend_best_var = pd.DataFrame({'id': index, 'var_sub': best_descend_var_list})\n data_descend_best_var.to_pickle(\n '/dataset/java/test/gnn_best_descend_data.pkl')\n print('end...')\n\n\n","repo_name":"Zhangxq-1/ACCENT-repository","sub_path":"adversarial examples generation/gnn/GNN_substitution.py","file_name":"GNN_substitution.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"79"} +{"seq_id":"17287674589","text":"from sqlalchemy import Column, DateTime, Float, Integer, String, Table\r\nfrom sqlalchemy.sql import func\r\n\r\nfrom model import Base\r\n\r\n\r\nclass Anuncio(Base):\r\n __table__ = Table('anuncio', Base.metadata,\r\n Column('id', Integer, primary_key=True),\r\n Column('id_veiculo', Integer, nullable=False),\r\n Column('modelo', String, nullable=False),\r\n Column('valor_diaria', Float, nullable=False),\r\n Column('data_inclusao', DateTime, server_default=func.now()),\r\n sqlite_autoincrement=True)\r\n\r\n def __init__(\r\n self,\r\n id: int,\r\n id_veiculo: int,\r\n modelo: str,\r\n valor_diaria: float):\r\n \"\"\"\r\n Instancia um Anúncio\r\n\r\n Arguments:\r\n id: ID do Anúncio\r\n id: ID do Veículo\r\n modelo: Modelo do Veículo\r\n valor_diaria: Valor da Diária\r\n \"\"\"\r\n self.id = id\r\n self.id_veiculo = id_veiculo\r\n self.modelo = modelo\r\n self.valor_diaria = valor_diaria\r\n","repo_name":"elantunes/mvp-api-anuncios","sub_path":"model/anuncio.py","file_name":"anuncio.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"15214389374","text":"sequence = input(\"Enter binary sequence: \")\nmax0 = 0\nmax1 = 0\ncounter0 = 0\ncounter1 = 0\nfor x in sequence:\n if x == \"1\":\n counter1 += 1\n if counter1 > max1:\n max1 = counter1\n counter0 = 0\n else:\n counter0 += 1\n if counter0 > max0:\n max0 = counter0\n counter1 = 0\nif max0 > max1:\n print (\"Longest run was zeros with length:\",max0)\nelif max1 > max0:\n print (\"Longest run was ones with length:\",max1)\nelse:\n print (\"Equal longest run of ones and zeros with length:\",max0)\n","repo_name":"quickeee/Coding-Bootcamp","sub_path":"Prepatory weeks/28_09_2016_Python/exercise_10.py","file_name":"exercise_10.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"41737372422","text":"\r\nimport numpy as np \r\nimport cv2\r\nimport sys \r\nsys.path.append('./models')\r\nimport keras\r\nfrom keras.models import Model\r\nfrom models import AttentionResNetCifar10\r\nfrom feature_visualize import get_row_col,visualize_feature_map\r\n\r\n\r\ndef rotate(image, angle, center=None, scale=1.0):\r\n\t(h, w) = image.shape[:2] \r\n\tif center is None: \r\n\t\tcenter = (w // 2, h // 2) \r\n\tM = cv2.getRotationMatrix2D(center, angle, scale) \r\n\trotated = cv2.warpAffine(image, M, (w, h)) \r\n\treturn rotated \r\n\r\n\r\ndef predict(image_path,TTA=True):\r\n\t# build a model\r\n\tmodel = AttentionResNetCifar10(n_classes=10)\r\n\tmodel.load_weights('logs/weights/residual_attention_71_0.89.h5')\r\n\t#model = Model(inputs=model.input, outputs=model.get_layer('residual_attention_stage1').output)\r\n\tlabels = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']\r\n\r\n\timage = cv2.imread(image_path)\r\n\r\n\tif(TTA):\r\n\t\th_flip = cv2.flip(image, 1)\t\t# 水平翻转\r\n\t\tv_flip = cv2.flip(image, 0)\t\t# 垂直翻转\r\n\t\trotated45 = rotate(image, 45)\t#旋转\r\n\t\trotated90 = rotate(image, 90)\r\n\t\trotated180 = rotate(image, 180)\r\n\t\trotated270 = rotate(image, 270)\r\n\t\timage_list = []\r\n\t\timage_list.append(h_flip)\r\n\t\timage_list.append(v_flip)\r\n\t\timage_list.append(rotated45)\r\n\t\timage_list.append(rotated90)\r\n\t\timage_list.append(rotated180)\r\n\t\timage_list.append(rotated270)\r\n\r\n\t\tpred_list = []\r\n\t\tfor i in range(len(image_list)):\r\n\t\t\ttest = cv2.resize(image_list[i], (32, 32))\t#将测试图片转化为model需要的大小\r\n\t\t\ttest = np.array(test, np.float32) / 255\t#归一化送入,float/255\r\n\t\t\ttest = test.reshape(1,32,32,3)\t#model需要的是1张input_size*input_size得3通道rgb图片,所以转化为(1,input_size,input_size,3)\r\n\r\n\t\t\tpred = model.predict(test)\r\n\t\t\tpred_list.append(pred)\r\n\r\n\t\tTTA_pred = np.zeros(shape=(1,10))\r\n\t\tfor i in range(len(pred_list)):\r\n\t\t\tTTA_pred = TTA_pred+pred_list[i]\r\n\r\n\t\tprint('TTA_pred:',TTA_pred,'pred_shape:',TTA_pred.shape)\r\n\t\tmax_score = np.where(TTA_pred==np.max(TTA_pred))\r\n\t\tlabel = labels[int(max_score[1])]\r\n\t\tprint(label)\r\n\r\n\telse:\r\n\t\ttest = cv2.resize(image, (32, 32))\t#将测试图片转化为model需要的大小\r\n\t\ttest = np.array(test, np.float32) / 255\t#归一化送入,float/255\r\n\t\ttest = test.reshape(1,32,32,3)\t#model需要的是1张input_size*input_size得3通道rgb图片,所以转化为(1,input_size,input_size,3)\r\n\r\n\t\tpred = model.predict(test)\r\n\t\tprint('prediction:',pred,'pred_shape:',pred.shape)\r\n\r\n\t\tmax_score = np.where(pred==np.max(pred))\r\n\t\tprint(max_score)\r\n\t\tlabel = labels[int(max_score[1])]\r\n\t\tprint(label)\r\n\r\n\r\ndef visuable(image_path,name):\r\n\t# build a model\r\n\tmodel = AttentionResNetCifar10(n_classes=10)\r\n\tmodel.load_weights('logs/weights/residual_attention_71_0.89.h5')\r\n\tmodel = Model(inputs=model.input, outputs=model.get_layer('residual_attention_stage1').output)\r\n\tlabels = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']\r\n\r\n\ttest = cv2.imread(image_path)\r\n\ttest = cv2.resize(test, (32, 32))\t#将测试图片转化为model需要的大小\r\n\ttest = np.array(test, np.float32) / 255\t#归一化送入,float/255\r\n\ttest = test.reshape(1,32,32,3)\t#model需要的是1张input_size*input_size得3通道rgb图片,所以转化为(1,input_size,input_size,3)\r\n\tblock_pool_features = model.predict(test)\r\n\tprint(block_pool_features.shape)\r\n\r\n\tfeature = block_pool_features.reshape(block_pool_features.shape[1:])\r\n\tvisualize_feature_map(feature,name)\r\n\r\nif __name__ == '__main__':\r\n\timport tensorflow as tf\r\n\tfrom keras.backend.tensorflow_backend import set_session\r\n\tconfig = tf.ConfigProto()\r\n\tconfig.gpu_options.per_process_gpu_memory_fraction = 0.5\r\n\tset_session(tf.Session(config=config))\r\n\r\n\timport os\r\n\timport random\r\n\tos.environ['CUDA_VISIBLE_DEVICES'] = '0'\r\n\r\n\tfile_names = next(os.walk('test_images'))[2]\r\n\tfile_names = random.choice(file_names)\r\n\tfilepath = os.path.join('test_images',file_names)\r\n\tprint(filepath)\r\n\tpredict(image_path=filepath,TTA=True)\r\n\tvisuable(image_path=filepath,name=file_names.split('.')[0])\r\n\r\n\r\n\r\n","repo_name":"Be997398715/residual-attention-network","sub_path":"predict_and_visuable.py","file_name":"predict_and_visuable.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"79"} +{"seq_id":"13038641883","text":"def new_string(symbol, count = 3):\n return symbol * count\n\n# print(new_string('!', 5)) -> !!!!!\n# print(new string('!')) -> !!!\n#print(new_string(4)) -> 12\n\ndef collection(*symbols): # * - помогает вводить неограниченное число аргументов\n res: str = ''\n for item in symbols:\n res += item\n return res\n\n# print(collection('a', 's', 'd', 'w')) # asdw\n# print(collection('a', '1', 'd', '2')) # a1d2\n# print(ccollection(1, 2, 3, 4)) # TypeError: ...\n\n# Рекурсия\ndef fib(n):\n if n in [1, 2]:\n return 1\n else:\n return fib(n-1) + fib(n-2)\nlist = []\nfor e in range(1, 11):\n list.append(fib(e))\nprint(list) # 1 1 2 3 5 8 13 21 34\n\n\n# Кортеж – это неизменяемый “список”\na = [3, 4]\nprint(a)\nprint(a[-1])\nt = ()\nprint(type(t)) # tuple\nt = (1,)\nprint(type(t)) # tuple\nt = (1)\nprint(type(t)) # int\nt = (28, 9, 1990)\nprint(type(t)) # tuple\ncolors = ['red', 'green', 'blue']\nprint(colors) # ['red', 'green', 'blue']\nt = tuple(colors)\nprint(t) # ('red', 'green', 'blue')\n\nprint(t[0]) # red\nprint(t[2]) # blue\n# print(t[10]) # IndexError: tuple index out of range\n\nprint(t[-2]) # green\n\n# print(t[-200]) # IndexError: tuple index out of range\n\nfor e in t:\n print(e) # red green blue\n\n# t[0] = 'black' # TypeError: 'tuple\n\nt = tuple(['red', 'green', 'blue']) # список в кортеж\nred, green, blue = t # кортеж в переменные (двойное преобразование)\nprint('r:{} g:{} b:{}'.format(red, green, blue))\n# r:red g:green b:blue\n\n\n# Словари\n# Неупорядоченные коллекции произвольных\n# объектов с доступом по ключу\n\ndictionary = {} \n# \\ чтобы не писать в одну строку\ndictionary = \\\n {\n 'up': '↑',\n 'left': '←',\n 'down': '↓',\n 'right': '→'\n }\nprint(dictionary) # {'up':'↑', 'left':'←', 'down':'↓', 'right':'→'}\nprint(dictionary['left']) # ←\nprint(dictionary['up']) # ↑\n# типы ключей могут отличаться\ndictionary['left'] = '⇐'\nprint(dictionary['left']) # ⇐\n#print(dictionary['type']) # KeyError: 'type'\ndel dictionary['left'] # удаление элемента\n\nfor k in dictionary.values():\n print(k) \n# будут только значения ключей\n\nfor m in dictionary.keys():\n print(m) \n# будут сами ключи только\n\nfor item in dictionary: # for (k,v) in dictionary.items():\n print('{}: {}'.format(item, dictionary[item]))\n# up: ↑\n# down: ↓\n# right: →\n\n\n# Множества\n# Неупорядоченная совокупность элементов\n\na = {1, 2, 3, 5, 8}\nb = {'2', '5', 8, 13, 21}\nprint(type(a)) # set\nprint(type(b)) # set\n\na = {1, 2, 3, 5, 8}\nb = set([2, 5, 8, 13, 21])\nc = set((2, 5, 8, 13, 21))\nprint(type(a)) # set\nprint(type(b)) # set\nprint(type(c)) # set\na = {1, 1, 1, 1, 1}\nprint(a) # {1}\n\ncolors = {'red', 'green', 'blue'}\nprint(colors) # {'red', 'green', 'blue'}\ncolors.add('red')\nprint(colors) # {'red', 'green', 'blue'}\ncolors.add('gray')\nprint(colors) # {'red', 'green', 'blue','gray'}\ncolors.remove('red')\nprint(colors) # {'green', 'blue','gray'}\n# colors.remove('red') # KeyError: 'red'\ncolors.discard('red') # ok\nprint(colors) # {'green', 'blue','gray'}\ncolors.clear() # { }\nprint(colors) # set()\n\na = {1, 2, 3, 5, 8}\nb = {2, 5, 8, 13, 21}\nc = a.copy() # c = {1, 2, 3, 5, 8}\nu = a.union(b) # u = {1, 2, 3, 5, 8, 13, 21} объединение множеств\ni = a.intersection(b) # i = {8, 2, 5} пересечение\ndl = a.difference(b) # dl = {1, 3} разница а с b\ndr = b.difference(a) # dr = {13, 21} разница b с a\nq = a \\\n .union(b) \\\n .difference(a.intersection(b))\n# {1, 21, 3, 13} выполнялось по действиям: в скобках а пересечение с b,\n# потом первое а объединение с b, потом разница между объединённым и пересечённым.\n\n# Неизменяемое множество, нельзя добавить/удалить элемент\na = {1, 2, 3, 5, 8}\nb = frozenset(a)\nprint(b) # frozenset({1, 2, 3, 5, 8)\n\n# Списки \nlist1 = [1,2,3,4,5]\nlist2 = list1\nlist2[0] = 333 #изменится и в 1, и во 2 ( аналогично для list1[0]=222)\n# аккуратно с копированием данных\nprint(list1) # 333, 2, 3, 4, 5\nprint()\nprint(list2)\nprint()\nprint(list1.pop(2)) #удалю элемент 2 индекс, выведет его: 3\nprint(list1) # [333, 2, 4, 5]\nprint(len(list1))\n\nlist1.insert(2,11) # на 2 позицию поставлю число 11, без удалений др. элементов\nprint(list1) # вместо 4, стало 5 элементов [333, 2, 11, 4, 5]\n\nlist1.append(11) # добавить 11 в КОНЕЦ СПИСКА\nprint(list1) # [333, 2, 11, 4, 5, 11]","repo_name":"rovictoria/Python3","sub_path":"example_functions_tuple.py","file_name":"example_functions_tuple.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"31903797587","text":"## VARIANCE OF HIGH VS LOW\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nexec(open('python/ecco2/colormap.py').read())\nimport scipy.stats as stats\n\n## load data\n\nthi = np.load('python/gyres/temp_highres_sfc.npy')\ntlo = np.load('python/gyres/temp_lowres_sfc.npy')\nrandfield = np.load('python/gyres/patterns/randpattern_ar5_0-100+900-1000_high.npy')\n(time,lat,lon) = np.load('python/gyres/temp_lowres_dim.npy')\n\n## variances\nvarhi = thi.var(axis=0)\nvarlo = tlo.var(axis=0)\nvarrand = randfield.var(axis=0)\n\n\"\"\"\ntlodt,tlody,tlodx = np.gradient(tlo)\n\nx1 = abs(tlodt).mean(axis=0).flatten()\nx2 = abs(tlodx).mean(axis=0).flatten()\nx3 = tlodt.var(axis=0).flatten()\nx4 = varlo.flatten()\nx5 = stats.skew(tlo,axis=0).flatten()\nx6 = stats.kurtosis(tlo,axis=0).flatten()\n\nX = np.vstack((x1,x2,x3,x4,x5,x6))\nX = X.T / X.std(axis=1)\n\nb = np.linalg.lstsq(X,varhi.flatten())[0]\n\nvarest = np.dot(b,X.T).reshape((128,128))\n\"\"\"\n\n##\nplt.figure(1)\nplt.pcolormesh(lon,lat,varhi)\nplt.xlim(lon.min(),lon.max())\nplt.ylim(lat.min(),lat.max())\nplt.colorbar()\nplt.clim(0,8)\nplt.title('Var(T_high)')\n\nplt.figure(2)\nplt.pcolormesh(lon,lat,varlo)\nplt.xlim(lon.min(),lon.max())\nplt.ylim(lat.min(),lat.max())\nplt.colorbar()\nplt.clim(0,8)\nplt.title('Var(T_low)')\n\n\nplt.figure(3)\nplt.pcolormesh(lon,lat,varhi-varlo)\nplt.xlim(lon.min(),lon.max())\nplt.ylim(lat.min(),lat.max())\nplt.colorbar()\nplt.clim(0,8)\nplt.title('Var(T_high) - Var(T_low)')\n\nplt.figure(4)\nplt.pcolormesh(lon,lat,varrand)\nplt.xlim(lon.min(),lon.max())\nplt.ylim(lat.min(),lat.max())\nplt.colorbar()\nplt.clim(0,8)\nplt.title('Var_rand')\n\nplt.show()\n","repo_name":"milankl/misc","sub_path":"gyres_scripts/gyres_variance.py","file_name":"gyres_variance.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"14617653056","text":"from core.bbox_utils import bbox_overlaps_iou\nimport numpy as np\n\ndef test_iou_simple():\n bboxes = np.array([[0, 0, 1, 1], [0, 0, 1, 1]])\n expected = np.array([[1, 1], [1, 1]])\n result = bbox_overlaps_iou(bboxes, bboxes)\n assert np.all(expected == result)\n\ndef test_iou_overlaps():\n bboxes = np.array([[0, 0, 1, 1], [0, 0, 2, 2]])\n expected = np.array([[1, 0.25], [0.25, 1]])\n result = bbox_overlaps_iou(bboxes, bboxes)\n assert np.all(expected == result)\n\ndef test_iou_not_overlaps():\n bboxes = np.array([[0, 0, 1, 1], [-1, -1, 0, 0]])\n expected = np.array([[1, 0], [0, 1]])\n result = bbox_overlaps_iou(bboxes, bboxes)\n assert np.all(expected == result)\n","repo_name":"Godis715/Markup-Tool","sub_path":"result-inference-service/test/test_bbox_utils.py","file_name":"test_bbox_utils.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"11899039696","text":"\n# from .db import get_db, insert, commit\n# from .utils import slots_in_range, datetime_from_str\nimport json\nfrom sqlite3 import IntegrityError\nfrom datetime import datetime\nfrom flask import Blueprint, request, session, render_template\nfrom .auth import superuser_required\nfrom .db import select_all, select_one, get_appointments, remove, insert\nfrom .utils import date_format\n\nbp = Blueprint('admin', __name__, url_prefix='/admin')\n\n@bp.route('/list', methods=['GET', 'POST'])\n@superuser_required\ndef list():\n if request.method == 'POST':\n name = request.form.get('name')\n from_str = request.form.get('from')\n to_str = request.form.get('to')\n from_stamp = datetime.strptime(from_str, '%d/%m/%y').timestamp() if from_str and from_str != '' else None\n to_stamp = datetime.strptime(to_str, '%d/%m/%y').timestamp() if to_str and to_str != '' else None\n\n user = select_one('user', 'name', name) if name else None\n user_id = user['id'] if user else None\n raw_appointments = get_appointments(user_id=user_id, from_stamp=from_stamp, to_stamp=to_stamp)\n else:\n raw_appointments = get_appointments()\n\n appointments = []\n for item in raw_appointments:\n appointment = {\n 'id': item['id'],\n 'name': item['name'],\n 'date': datetime.strftime(datetime.fromtimestamp(item['date']), '%d/%m/%Y %H:%M'),\n 'phone': item['phone'],\n 'email': item['email'],\n }\n appointments.append(appointment)\n context = {\n 'appointments': appointments\n }\n return render_template('admin/list.html', context=context)\n\n\n@bp.route('/delete_appointment', methods=['DELETE'])\n@superuser_required\ndef delete_appointment():\n result = {'removed': 0}\n if request.method == 'DELETE':\n id = request.form.get('id')\n slot = select_one('appointments', 'id', id)['date_time']\n res = remove('appointments', 'id', id)\n result['removed'] = res\n try:\n insert('slots', slot=slot)\n except IntegrityError:\n pass\n\n return json.dumps(result)\n\n\n# def test_add_slots():\n# year = 2019\n# month = 2\n# days = [1, 3, 5, 8]\n# time_from = '9-00'\n# time_to = '12-00'\n# duration = 30\n#\n# # add_slots(year, month, days, time_from, time_to, duration)\n\n\n# def test_get_slots():\n# date_from = '01-02-2019'\n# date_to = '05-03-2019'\n# from datetime import datetime\n# slots = get_slots(date_from, date_to)\n# for slot in slots:\n# print(datetime.fromtimestamp(slot['slot']))\n\n\n\n","repo_name":"vsurguch/NextProject","sub_path":"Next/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"39642494409","text":"import speech_recognition as sr\nimport moviepy.editor as me\nfrom denoise2 import denoise\n#from pydub import AudioSegment\nfrom sentence_transformers import SentenceTransformer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport math\n\nmodel_name = 'bert-base-nli-mean-tokens'\nmodel = SentenceTransformer(model_name)\n\nclass recomm:\n y = 0.0\n def __init__(self,path,keywords):\n video_clip = me.VideoFileClip(r\"{}\".format(path))\n #path2 = path.replace(\"mp4\", \"wav\")\n path2 = \"y2.wav\"\n video_clip.audio.write_audiofile(r\"{}\".format(path2), nbytes=2)\n recognizer = sr.Recognizer()\n d = denoise(path2)\n \"\"\"a = AudioSegment.from_wav(path2)\n a = a + 5\n a.export(path2, \"wav\")\"\"\"\n audio_clip = sr.AudioFile(\"{}\".format(path2))\n with audio_clip as source:\n #recognizer.adjust_for_ambient_noise(source)\n audio_file = recognizer.record(source)\n sent = []\n result = \"\"\n try:\n result = recognizer.recognize_google(audio_file)\n except sr.UnknownValueError:\n print(\"Can not process audio \")\n if not result:\n self.y = 0\n else:\n print(result)\n sent.append(result)\n sent = sent + keywords\n sent_vec3 = model.encode(sent)\n x = cosine_similarity(\n [sent_vec3[0]],\n sent_vec3[1:]\n )\n for i in range(len(x)):\n self.y = self.y + x[0][i]\n self.y = (self.y / (len(sent) - 1)) * 1000.0\n def res(self):\n if self.y < 0:\n self.y = 0\n return self.y","repo_name":"nabil-rady/Smart-remote-interviewing-system","sub_path":"models/models/recommendation.py","file_name":"recommendation.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"79"} +{"seq_id":"41686988556","text":"import json\nenv = json.load(open(\"env.json\", 'r'))\n\n#OCR related values\nDB2_CONN_URL = env['DB2_CONN_URL']\nPORT = env['PORT']\nDB2_CS_CONN = env['DB2_CS_CONN']\nDB2_CR_CONN = env['DB2_CR_CONN']\n\nqrycache = json.load(open(\"querycache.json\", 'r'))\nQUERY_CACHE = qrycache['QUERY_CACHE']\n","repo_name":"SathishKumar0407/MutationApp","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"73168853695","text":"# 1, 1, 2, 3, 5, 8, 13, 21, 34, ...\n\nn = int(input())\ndp = [0]*(n+1)\n\ndef calc(n):\n global dp\n for i in range(n+1):\n if i == 0:\n dp[i] = 1\n elif i == 1:\n dp[i] = 1\n else:\n dp[i] = dp[i-1] + dp[i-2]\n\ndef fibonacci(n):\n if n == 0:\n return 1\n if n == 1:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\n\n#print(fibonacci(n))\ncalc(n)\nprint(dp[n])\n\n\n","repo_name":"maeda-kazuya/aoj","sub_path":"10a.py","file_name":"10a.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"32468460941","text":"import numpy as np \nimport sys \n\nreadline = sys.stdin.readline\n\nN, K = map(int, readline().split())\nA = list(map(int, readline().split()))\n\n# 愚直にやると計算量O(K)でTLEになる\n# 同じ街にいったら操作打ち切りで配列を完結させる\n\n# Teleport順の配列を作る\nteleport = {1: True}\nnext_town = 1\nroop_exist = False\nfor i in range(K):\n next_town = A[next_town - 1] # next_townがintで与えられる\n try: # 辞書を使用してO[1]で判定する\n teleport[next_town]\n dupulicate_town = next_town\n # 辞書をリストに変換\n teleport = list(teleport.keys())\n dupulicate_index = teleport.index(dupulicate_town)\n dupulicate_list = teleport[dupulicate_index:]\n roop_exist = True\n break\n except KeyError:\n teleport[next_town] = True\n\n\n# 最後の処理の前にリストに変換してしまう\nif not roop_exist:\n teleport = list(teleport.keys())\n\nif len(teleport) - 1 == K:\n print(teleport[-1])\nelse: # ループに入る場合\n consumption = len(teleport) - 1\n roop_num = K - consumption\n roop_index = roop_num % len(dupulicate_list)\n if roop_index == 0:\n print(dupulicate_list[-1])\n else:\n print(dupulicate_list[roop_index - 1])\n\n","repo_name":"Ry-Kurihara/AtCoder","sub_path":"abc167wrap/abc167/d/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"16546310429","text":"from typing import List\n\n\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n return self.pointers(height)\n\n # O(n^2)\n def naive(self, height: List[int]) -> int:\n max_area = 0\n for i in range(len(height)):\n for j in range(1, len(height)):\n h = min(height[i], height[j])\n w = j - i\n max_area = max(max_area, h * w)\n return max_area\n\n # we are always limited by the shorter height\n # we take a gamble and say that reducing length with the shorter height might be beneficial\n # proof by contradiction:\n # Suppose result is not optimal, so there is an l and r that are optimal.\n # Since we only stop when two pointers meet, we must have visited one of them but not the other.\n # let's say we visited l but not r.\n # the pointer at l stops and won't move until\n # the other pointer is pointing to l, in which case iteration ends and we must have visited r.\n # there is a better rr which caused l to move. But that means l and r are not optimal.\n # both cases arrive at contradiction\n # O(n) time complexity\n def pointers(self, height: List[int]) -> int:\n def area(l, r):\n return min(height[l], height[r]) * (r - l)\n\n l = 0\n r = len(height) - 1\n max_area = 0\n while l != r:\n max_area = max(max_area, area(l, r))\n if height[l] < height[r]:\n l += 1\n else:\n r -= 1\n return max_area\n\n\nsol = Solution()\nheight = [1, 8, 6, 2, 5, 4, 8, 3, 7]\nprint(sol.maxArea(height))\n","repo_name":"sshkel/progchal","sub_path":"random/maxArea.py","file_name":"maxArea.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"8153018161","text":"import re\nfrom argparse import ArgumentParser, ArgumentTypeError\n\nfrom flexget import options\nfrom flexget.event import event\nfrom flexget.terminal import TerminalTable, console, table_parser\nfrom flexget.utils.database import Session\n\nfrom . import db\n\n\ndef do_cli(manager, options):\n \"\"\"Handle regexp-list cli\"\"\"\n action_map = {\n 'all': action_all,\n 'list': action_list,\n 'add': action_add,\n 'del': action_del,\n 'purge': action_purge,\n }\n\n action_map[options.regexp_action](options)\n\n\ndef action_all(options):\n \"\"\"Show all regexp lists\"\"\"\n lists = db.get_regexp_lists()\n header = ['#', 'List Name']\n table = TerminalTable(*header, table_type=options.table_type)\n for regexp_list in lists:\n table.add_row(str(regexp_list.id), regexp_list.name)\n console(table)\n\n\ndef action_list(options):\n \"\"\"List regexp list\"\"\"\n with Session() as session:\n regexp_list = db.get_list_by_exact_name(options.list_name)\n if not regexp_list:\n console(f'Could not find regexp list with name {options.list_name}')\n return\n table = TerminalTable('Regexp', table_type=options.table_type)\n regexps = db.get_regexps_by_list_id(\n regexp_list.id, order_by='added', descending=True, session=session\n )\n for regexp in regexps:\n table.add_row(regexp.regexp or '')\n console(table)\n\n\ndef action_add(options):\n with Session() as session:\n regexp_list = db.get_list_by_exact_name(options.list_name)\n if not regexp_list:\n console(f'Could not find regexp list with name {options.list_name}, creating')\n regexp_list = db.create_list(options.list_name, session=session)\n\n regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regexp, session=session)\n if not regexp:\n console(f\"Adding regexp {options.regexp} to list {regexp_list.name}\")\n db.add_to_list_by_name(regexp_list.name, options.regexp, session=session)\n console(\n f'Successfully added regexp {options.regexp} to regexp list {regexp_list.name} '\n )\n else:\n console(f\"Regexp {options.regexp} already exists in list {regexp_list.name}\")\n\n\ndef action_del(options):\n with Session() as session:\n regexp_list = db.get_list_by_exact_name(options.list_name)\n if not regexp_list:\n console(f'Could not find regexp list with name {options.list_name}')\n return\n regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regexp, session=session)\n if regexp:\n console(f'Removing regexp {options.regexp} from list {options.list_name}')\n session.delete(regexp)\n else:\n console(f'Could not find regexp {options.movie_title} in list {options.list_name}')\n return\n\n\ndef action_purge(options):\n with Session() as session:\n regexp_list = db.get_list_by_exact_name(options.list_name)\n if not regexp_list:\n console(f'Could not find regexp list with name {options.list_name}')\n return\n console('Deleting list %s' % options.list_name)\n session.delete(regexp_list)\n\n\ndef regexp_type(regexp):\n try:\n re.compile(regexp)\n return regexp\n except re.error as e:\n raise ArgumentTypeError(e)\n\n\n@event('options.register')\ndef register_parser_arguments():\n # Common option to be used in multiple subparsers\n regexp_parser = ArgumentParser(add_help=False)\n regexp_parser.add_argument('regexp', type=regexp_type, help=\"The regexp\")\n\n list_name_parser = ArgumentParser(add_help=False)\n list_name_parser.add_argument(\n 'list_name', nargs='?', help='Name of regexp list to operate on', default='regexps'\n )\n # Register subcommand\n parser = options.register_command('regexp-list', do_cli, help='View and manage regexp lists')\n # Set up our subparsers\n subparsers = parser.add_subparsers(title='actions', metavar='', dest='regexp_action')\n subparsers.add_parser('all', parents=[table_parser], help='Shows all existing regexp lists')\n subparsers.add_parser(\n 'list', parents=[list_name_parser, table_parser], help='List regexp from a list'\n )\n subparsers.add_parser(\n 'add', parents=[list_name_parser, regexp_parser], help='Add a regexp to a list'\n )\n subparsers.add_parser(\n 'del', parents=[list_name_parser, regexp_parser], help='Remove a regexp from a list'\n )\n subparsers.add_parser(\n 'purge', parents=[list_name_parser], help='Removes an entire list. Use with caution!'\n )\n","repo_name":"Flexget/Flexget","sub_path":"flexget/components/managed_lists/lists/regexp_list/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","stars":1638,"dataset":"github-code","pt":"79"} +{"seq_id":"206548431","text":"###########################################\n# Imports\n###########################################\n\nimport re\nimport os, sys\nimport traceback\nimport random\nimport base64\n\nimport json\nimport csv, io\nimport xml.etree.ElementTree as XML\nimport string\n\nimport wsgiref\nfrom urllib.request import urlopen\nfrom urllib.parse import parse_qs\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\n\nfrom functools import wraps\n\nrootRelativePath = '..'\nrootAbsolutePath = os.path.abspath(rootRelativePath)\nsys.path.append(rootAbsolutePath)\n\nfrom CH3.ch03_ex4 import create_pairs, remove_headings, read_rows, Pair\n\n###########################################\n# The HTTP request-response model\n###########################################\n\n# An HTTP client executes something similar to the following:\n\nurl = 'http://slott-softwarearchitect.blogspot.com'\n\nwith urlopen(url) as response:\n print(response.read())\n\n# At the other end of the protocol, a static content server \n# should also be stateless.\n# For that end, we can use the http.server library as follows:\n\n\nrunning = True\nhttpd = HTTPServer(\n ('localhost',8080), \n SimpleHTTPRequestHandler\n )\n\nwhile running:\n httpd.handle_request()\n httpd.shutdown()\n\n#-----------------\n# Considering a server with a functional design\n#-----------------\n\n# Conceptually, a web service should have a top-level implementation \n# that can be summarized as follows:\n\nrequest = 'some_request'\nresponse = httpd(request)\n\n#-----------------\n# Looking more deeply into the functional view\n#-----------------\n\n# We can think of a web server like this:\n\nheaders = 'some_headers'\nuploads = 'some_uploads'\n\nheaders, content = httpd(headers, request, [uploads])\n\n#-----------------\n# Nesting the services\n#-----------------\n\n# A conceptual view of the functions that compose a web service\n# is something like this:\n\ndef check_authentication():\n pass\n\ndef check_csrf():\n #Cross-site request forgery\n pass\n\ndef check_session():\n pass\n\ndef send_content():\n pass\n\nforms = {}\n\nresponse = send_content(\\\n check_authentication(\\\n check_csrf(\\\n check_session(headers, request, [forms])\n )))\n\n'''\n* The problem with the nested function view is that each nested context \nmay also need to tweak the response instead of \nor in addition to tweaking the request.\n'''\n# Instead, we want something more like this:\n\ndef check_session(headers, request, forms):\n # pre-process: determine session\n # content = csrf(headers, request, forms)\n # post-processes the content\n # return the content\n pass\n\ndef check_csrf(headers, request, forms):\n # pre-process: validate csrf tokens\n # content= check_authentication(headers, request, forms)\n # post-processes the content\n # return the content\n pass\n\n###########################################\n# The WSGI standard\n###########################################\n\n# Each WSGI \"application\" has the same interface:\n\ndef some_app(environ, start_response):\n return content\n\n'''\n* The environ is a dictionary that contains all of the arguments \nof the request in a single, uniform structure\n* The start_response is a function that must be used \nto send the status and headers of a response.\n'''\n\n# Here's a very simple routing application:\n\ndef demo_app():\n pass\n\ndef static_app():\n pass\n\ndef welcome_app():\n pass\n\nSCRIPT_MAP = {\n 'demo': demo_app,\n 'static': static_app,\n '': welcome_app,\n}\n\ndef routing(environ, start_response):\n top_level = wsgiref.util.shift_path_info(environ)\n app = SCRIPT_MAP.get(top_level, SCRIPT_MAP[''])\n content = app(environ, start_response)\n return content\n\n#-----------------\n# Throwing exceptions during WSGI processing\n#-----------------\n\n# We can define a WSGI application that provides static content \n# as follows:\n\ndef index_app():\n pass\n\nCONTENT_HOME = '/home/dir'\n\ndef static_app(environ, start_response):\n try:\n with open(CONTENT_HOME + environ['PATH_INFO']) as static:\n content = static.read().encode('utf-8')\n headers = [\n ('Content-Type', 'text/plain; charset =\"utf-8\"'),\n ('Content-Length', str(len(content))),\n ]\n start_response('200 OK', headers)\n return [content]\n except IsADirectoryError as e:\n return index_app(environ, start_response)\n except FileNotFoundError as e:\n start_response('404 NOT FOUND', [])\n return([repr(e).encode('utf-8')])\n\n'''\n* In this case, we tried to open the requested path as a text file. \n* There are two common reasons why we can't open a given file, \nboth of which are handled as exceptions:\n • If the file is a directory, we'll use a different application \n to present directory contents\n • If the file is simply not found, we'll return \n an HTTP 404 NOT FOUND response\n'''\n\n#-----------------\n# Defining web services as functions\n#-----------------\n\n'''\n* We'll split our application into two tiers: \n - A web tier, which will be a simple WSGI application.\n - The rest of the processing, which will be \n more typical functional programming. \n \n* We need to provide two pieces of information to the web service:\n - The quartet that we want. \n - The output format we want.\n\n* A URL we can use will look like this:\nhttp://localhost:8080/anscombe/III/?form=csv\n'''\n\n#-----------------\n# Defining web services as functions\n#-----------------\n\n# First, we'll use a URL pattern-matching expression to define \n# the one and only routing in our application:\n\nurlPathPattern = re.compile(r'^/anscombe/(?P.*?)/?$')\n\n# Here's the unit test that demonstrates how this pattern works:\n\ntestPattern = \"\"\"\n >>> m1 = urlPathPattern.match(\"\"/anscombe/I\"\")\n >>> m1.groupdict()\n {'dataset': 'I'}\n >>> m2 = urlPathPattern.match(\"\"/anscombe/II/\"\")\n >>> m2.groupdict()\n {'dataset': 'II'}\n >>> m3 = urlPathPattern.match(\"\"/anscombe/\"\")\n >>> m3.groupdict()\n {'dataset': ''}\n\"\"\"\n\n# We can include the three previously mentioned examples a\n# s part of the overall doctest:\n\n__test__ = {\n \"test_pattern\": testPattern,\n}\n\n#-----------------\n# Getting raw data\n#-----------------\n\n# The read_raw_data() function is copied from Chapter 3, \n# with some important changes, as follows:\n\ndef read_raw_data():\n \"\"\"\n >>> read_raw_data()['I'] #doctest: +ELLIPSIS\n (Pair(x=10.0, y=8.04), Pair(x=8.0, y=6.95), ...\n \"\"\"\n with open(\"../Anscombe.txt\") as fh:\n dataset = tuple(remove_headings(read_rows(fh)))\n mapping = dict(\n (id_str, tuple(create_pairs(_id, dataset)))\n for _id, id_str in enumerate(['I', 'II', 'III', 'IV'])\n )\n return mapping\n\n#-----------------\n# Applying a filter\n#-----------------\n\n# The entire filter process is embodied in the following function:\n\ndef anscombe_filter(set_id, raw_data):\n \"\"\"\n >>> anscombe_filter(\"\"II\"\", raw_data()) #doctest: +ELLIPSIS\n (Pair(x=10.0, y=9.14), Pair(x=8.0, y=8.14), Pair(x=13.0, y=8.74),\n ...\n \"\"\"\n return raw_data[set_id]\n\n#-----------------\n# Serializing the results\n#-----------------\n\n'''\nThe serializers fall into two groups, those that produce strings \nand those that produce bytes. \n* A serializer that produces a string will need \nto have the string encoded as bytes. \n* A serializer that produces bytes doesn't need any further work.\n'''\n\n# Here's how we can standardize the conversion to bytes\n# using a decorator, as follows:\n\ndef to_bytes(function):\n @wraps(function)\n def decorated(*args, **kw):\n text = function(*args, **kw)\n return text.encode('utf-8')\n return decorated\n\n#-----------------\n# Serializing data into the JSON or CSV format\n#-----------------\n\n# The JSON serializer is implemented as follows:\n\n@to_bytes\ndef serialize_json(series, data):\n \"\"\"\n >>> data = [Pair(2,3), Pair(5,7)]\n >>> serialize_json(\"\"test\"\", data)\n b'[{\"x\": 2, \"y\": 3}, {\"x\": 5, \"y\": 7}]'\n \"\"\"\n obj = list(\n dict(x=row.x, y=row.y) \n for row in data\n )\n text = json.dumps(obj, sort_keys=True)\n return text\n\n# The CSV serializer is implemented as follows:\n\n@to_bytes\ndef serialize_csv(series, data):\n \"\"\"\n >>> data = [Pair(2,3), Pair(5,7)]\n >>> serialize_csv(\"\"test\"\", data)\n b'x,y\\\\r\\\\n2,3\\\\r\\\\n5,7\\\\r\\\\n'\n \"\"\"\n buffer = io.StringIO()\n writer = csv.DictWriter(buffer, Pair._fields)\n writer.writeheader()\n writer.writerows(row._asdict() for row in data)\n return buffer.getvalue()\n\n#-----------------\n# Serializing data into XML\n#-----------------\n\n# The XML serializer is implemented as follows:\n\ndef serialize_xml(series, data):\n \"\"\"\n >>> data = [Pair(2,3), Pair(5,7)]\n >>> serialize_xml(\"test\", data)\n b'\n \n 2\n 3\n \n \n 5\n 7\n \n '\n \"\"\"\n doc = XML.Element(\"series\", name=series)\n for row in data:\n row_xml = XML.SubElement(doc, \"row\")\n x = XML.SubElement(row_xml, \"x\")\n x.text = str(row.x)\n y = XML.SubElement(row_xml, \"y\")\n y.text = str(row.y)\n return XML.tostring(doc, encoding='utf-8')\n\n#-----------------\n# Serializing data into HTML\n#-----------------\n\n# The HTML serializer is implemented as follows:\n\ndata_page = string.Template(\n \"\"\"\n \n \n Series ${title}\n \n \n

Series ${title}

\n \n \n \n \n \n \n \n ${rows}\n
xy
\n \n \"\"\")\n\nerror_page = string.Template('Some_HTML_template')\n\n@to_bytes\ndef serialize_html(series, data):\n \"\"\"\n >>> data = [Pair(2,3), Pair(5,7)]\n >>> serialize_html(\"\"test\"\", data) #doctest: +ELLIPSIS\n b'...23\\\\n5\n 7...\n \"\"\"\n htmlRows = (\n '\\\n {0.x}\\\n {0.y}\\\n '.format(row) \n for row in data\n )\n text = data_page.substitute(\n title=series,\n rows='\\n'.join(htmlRows)\n )\n return text\n\n# Now the generic serializer function can pick \n# from the list of specific serializers. \n\n# The collection of serializers are as follows:\n\nserializers = {\n 'xml': ('application/xml', serialize_xml),\n 'html': ('text/html', serialize_html),\n 'json': ('application/json', serialize_json),\n 'csv': ('text/csv', serialize_csv),\n}\n\n# The generic serializer function is implemented as follows:\n\ndef write_serialized_data(format, title, data):\n \"\"\"json/xml/csv/html serialization.\n >>> data = [Pair(2,3), Pair(5,7)]\n >>> write_serialized_data(\"\"json\"\", \"\"test\"\", data)\n (b'[{\"\"x\"\": 2, \"\"y\"\": 3}, {\"\"x\"\": 5, \"\"y\"\": 7}]', 'application/json')\n \"\"\"\n mime, function = serializers.get(\n format.lower(), \n ('text/html', serialize_html))\n return function(title, data), mime\n\n# And the overall WSGI application is implemented as follows:\n\ndef wsgi_anscombe_app(environ, start_response):\n log = environ['wsgi.errors']\n try:\n match = urlPathPattern\\\n .match(environ['PATH_INFO']) # Which set to extract\n setID = match\\\n .group('dataset')\\\n .upper()\n query = parse_qs(environ['QUERY_STRING']) # Which output format to use\n print(\n environ['PATH_INFO'], \n environ['QUERY_STRING'],\n match.groupdict(), \n file=log\n )\n log.flush()\n dataset = anscombe_filter(setID, read_raw_data())\n content, mime = write_serialized_data(\n query['form'][0], \n setID, \n dataset\n )\n headers = [\n ('Content-Type', mime),\n ('Content-Length', str(len(content))),\n ]\n start_response(\"200 OK\", headers)\n return [content]\n except Exception as e:\n traceback.print_exc(file =log)\n tb = traceback.format_exc()\n page = error_page.substitute(\n title=\"Error\",\n message=repr(e), \n traceback=tb\n )\n content = page.encode(\"utf-8\")\n headers = [\n ('Content-Type', \"text/html\"),\n ('Content-Length', str(len(content))),\n ]\n start_response(\"404 NOT FOUND\", headers)\n return [content]\n\n###########################################\n# Tracking usage\n###########################################\n\n'''\nMany publicly available APIs require the use of an API Key. \n* The API Key is used to authenticate access. \n* It's also be used to authorize specific features. \n* It's also used to track usage. \n'''\n\n# To create API Keys, a cryptographic random number can be used\n# to generate a difficult-to-predict key string, as follows:\n\nrng = random.SystemRandom()\ndef make_key_1(rng=rng, size=1):\n key_bytes = bytes(\n rng.randrange(0,256) \n for i in range(18*size)\n )\n return base64.urlsafe_b64encode(key_bytes)\n","repo_name":"will-i-amv-books/Functional-Python-Programming","sub_path":"CH15/ch15_ex01.py","file_name":"ch15_ex01.py","file_ext":"py","file_size_in_byte":13208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"79"} +{"seq_id":"30848217453","text":"from .crosscompileproject import CrossCompileAutotoolsProject, GitRepository\nfrom .curl import BuildCurl\nfrom .expat import BuildExpat\nfrom ...config.compilation_targets import FreeBSDTargetInfo\n\n\n# CMake build system in contrib/buildsystems sadly doesn't have all the\n# configure checks needed for non-Windows, and is itself broken on Windows\n# (though that breakage is trivially fixable). Have to use the sort-of\n# autotools build system that doesn't support out-of-tree builds.\nclass BuildGit(CrossCompileAutotoolsProject):\n repository = GitRepository(\"https://github.com/git/git\")\n build_via_symlink_farm = True\n builds_docbook_xml = True\n dependencies = (\"curl\", \"libexpat\")\n\n def check_system_dependencies(self) -> None:\n super().check_system_dependencies()\n self.check_required_system_tool(\"asciidoc\")\n\n def setup(self):\n super().setup()\n if self.compiling_for_cheri():\n # Ancient obstack code is actually ok; the places where these\n # warnings fire are all dead due to using an AS/400 code path,\n # which is chosen based on a constant run-time expression and so\n # still diagnosed.\n self.cross_warning_flags.append(\"-Wno-error=cheri-capability-misuse\")\n if not self.compiling_for_host():\n assert isinstance(self.target_info, FreeBSDTargetInfo)\n # Various configure checks that require execution\n self.configure_environment.update(\n ac_cv_iconv_omits_bom=\"no\",\n ac_cv_fread_reads_directories=\"yes\",\n ac_cv_snprintf_returns_bogus=\"no\",\n )\n # Doesn't use pkg-config\n self.configure_args.extend([\n \"--with-curl=\" + str(BuildCurl.get_install_dir(self)),\n \"--with-expat=\" + str(BuildExpat.get_install_dir(self)),\n ])\n # Build-time detection of uname to determine more properties\n # Only S and R seem to be used currently, but provide sensible\n # values or, for V, a dummy kernconf (and format it like a release\n # kernel rather than providing a dummy date/time and build path).\n self.make_args.set(\n uname_S=\"FreeBSD\",\n uname_M=self.target_info.freebsd_target,\n uname_O=\"FreeBSD\",\n uname_R=\"14.0-CURRENT\",\n uname_P=self.target_info.freebsd_target_arch,\n uname_V=\"FreeBSD 14.0-CURRENT GENERIC \",\n )\n\n def configure(self):\n self.run_make(\"configure\", cwd=self.source_dir)\n super().configure()\n\n def compile(self, **kwargs):\n super().compile(**kwargs)\n self.run_make(\"man\", cwd=self.build_dir / \"Documentation\")\n\n def install(self, **kwargs):\n super().install(**kwargs)\n self.run_make_install(target=\"install-man\", cwd=self.build_dir / \"Documentation\")\n","repo_name":"CTSRD-CHERI/cheribuild","sub_path":"pycheribuild/projects/cross/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"79"} +{"seq_id":"13797507032","text":"#Uses python3\n\nimport sys\nimport queue\n\n\ndef shortest_paths(adj, cost, s, distance, reachable, shortest):\n prev = [-1 for _ in range(len(adj))]\n distance[s] = 0\n reachable[s] = 1\n q = queue.Queue()\n for i in range(len(adj)):\n for u in range(len(adj)):\n for j, v in enumerate(adj[u]):\n d = distance[u] + cost[u][j]\n if distance[v] > d:\n reachable[v] = 1\n distance[v] = d\n prev[v] = u\n if i == len(adj) - 1: # we have a negative weight cyclecycle\n shortest[v] = 0\n q.put(v)\n\n while not q.empty():\n u = q.get()\n for v in adj[u]:\n if shortest[v] == 1: # not visited in BFS to find infinite\n q.put(v)\n shortest[v] = 0\n\n\ndef solve_shortest(input):\n data = list(map(int, input.split()))\n n, m = data[0:2]\n data = data[2:]\n edges = list(zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3]))\n data = data[3 * m:]\n adj = [[] for _ in range(n)]\n cost = [[] for _ in range(n)]\n for ((a, b), w) in edges:\n adj[a - 1].append(b - 1)\n cost[a - 1].append(w)\n s = data[0]\n s -= 1\n distance = [10**19] * n\n reachable = [0] * n\n shortest = [1] * n\n shortest_paths(adj, cost, s, distance, reachable, shortest)\n rep = \"\"\n for x in range(n):\n if reachable[x] == 0:\n rep += '*'\n elif shortest[x] == 0:\n rep += '-'\n else:\n rep += str(distance[x])\n rep += \"\\n\"\n return rep\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n print(solve_shortest(input))\n\n","repo_name":"javathought/learnPy","sub_path":"src/main/python/coursera/graphs/shortest_paths.py","file_name":"shortest_paths.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"22432506724","text":"from data_transfer import DataTransfer\nimport csv\nimport psycopg2\n\n\ndef table_list(connect_par):\n tbls = []\n with psycopg2.connect(connect_par) as con:\n with con.cursor() as cur:\n # Получаем список таблиц из исходной БД :\n cur.execute(\"\"\"SELECT table_name \n FROM information_schema.tables \n WHERE table_schema = 'public'\"\"\")\n for row in cur.fetchall():\n tbls.append(row[0])\n return tbls\n\n\n\nclass DataTransferPostgres(DataTransfer):\n def __init__(\n self, config,\n source_pg_conn_str,\n pg_conn_str,\n pg_meta_conn_str,\n query, *args, **kwargs\n ):\n super(DataTransferPostgres, self).__init__(\n config=config,\n # source_pg_conn_str=source_pg_conn_str,\n pg_conn_str=pg_conn_str,\n pg_meta_conn_str=pg_meta_conn_str,\n query=query, *args, **kwargs\n )\n self.source_pg_conn_str = source_pg_conn_str\n self.query = query\n\n def provide_data(self, csv_file, context):\n pg_conn = psycopg2.connect(self.source_pg_conn_str)\n pg_cursor = pg_conn.cursor()\n query_to_execute = self.query\n self.log.info(\"Executing query: {}\".format(query_to_execute))\n pg_cursor.execute(query_to_execute)\n csvwriter = csv.writer(\n csv_file,\n delimiter=\"\\t\",\n quoting=csv.QUOTE_NONE,\n lineterminator=\"\\n\",\n escapechar='\\\\'\n )\n\n while True:\n rows = pg_cursor.fetchmany(size=1000)\n if rows:\n for row in rows:\n _row = list(row)\n csvwriter.writerow(_row)\n else:\n break\n pg_conn.close()\n","repo_name":"aandrey5/DWH_ETL","sub_path":"ETL_7DZ/postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"79"} +{"seq_id":"23708045375","text":"import hydralit as st\n\n# streamlit imports\n# from streamlit.runtime.scriptrunner import script_run_context\n\n# streamlit components section\nfrom streamlit_server_state import server_state, server_state_lock\n\n# from streamlitextras.threader import lock, trigger_rerun, \\\n# streamlit_thread, get_thread, \\\n# last_trigger_time\n\n# other imports\n\nimport warnings\n\nimport os, time, toml\nimport torch\nimport mimetypes\nimport pynvml\nimport threading\nimport torch\nfrom omegaconf import OmegaConf\n\n# from abc import ABC, abstractmethod\nfrom packaging import version\nimport shutup\n\n# import librosa\nfrom nataili.util.logger import logger\n\n\n# try:\n# from realesrgan import RealESRGANer\n# from basicsr.archs.rrdbnet_arch import RRDBNet\n# except ImportError as e:\n# logger.error(\"You tried to import realesrgan without having it installed properly. To install Real-ESRGAN, run:\\n\\n\"\n# \"pip install realesrgan\")\n\n# Temp imports\n# from basicsr.utils.registry import ARCH_REGISTRY\n\n\n# end of imports\n# ---------------------------------------------------------------------------------------------------------------\n\n# remove all the annoying python warnings.\nshutup.please()\n\n# the following lines should help fixing an issue with nvidia 16xx cards.\nif \"defaults\" in st.session_state:\n if st.session_state[\"defaults\"].general.use_cudnn:\n torch.backends.cudnn.benchmark = True\n torch.backends.cudnn.enabled = True\n\ntry:\n # this silences the annoying \"Some weights of the model checkpoint were not used when initializing...\" message at start.\n from transformers import logging\n\n logging.set_verbosity_error()\nexcept:\n pass\n\n# disable diffusers telemetry\nos.environ[\"DISABLE_TELEMETRY\"] = \"YES\"\n\n# remove some annoying deprecation warnings that show every now and then.\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n\n# this is a fix for Windows users. Without it, javascript files will be served with text/html content-type and the bowser will not show any UI\nmimetypes.init()\nmimetypes.add_type(\"application/javascript\", \".js\")\n\n# some of those options should not be changed at all because they would break the model, so I removed them from options.\nopt_C = 4\nopt_f = 8\n\n# The model manager loads and unloads the SD models and has features to download them or find their location\n# model_manager = ModelManager()\n\n\ndef load_configs():\n if \"defaults\" not in st.session_state:\n st.session_state[\"defaults\"] = {}\n\n st.session_state[\"defaults\"] = OmegaConf.load(\"configs/webui/webui_streamlit.yaml\")\n\n if os.path.exists(\"configs/webui/userconfig_streamlit.yaml\"):\n user_defaults = OmegaConf.load(\"configs/webui/userconfig_streamlit.yaml\")\n\n if \"version\" in user_defaults.general:\n if version.parse(user_defaults.general.version) < version.parse(\n st.session_state[\"defaults\"].general.version\n ):\n logger.error(\n \"The version of the user config file is older than the version on the defaults config file. \"\n \"This means there were big changes we made on the config.\"\n \"We are removing this file and recreating it from the defaults in order to make sure things work properly.\"\n )\n os.remove(\"configs/webui/userconfig_streamlit.yaml\")\n st.experimental_rerun()\n else:\n logger.error(\n \"The version of the user config file is older than the version on the defaults config file. \"\n \"This means there were big changes we made on the config.\"\n \"We are removing this file and recreating it from the defaults in order to make sure things work properly.\"\n )\n os.remove(\"configs/webui/userconfig_streamlit.yaml\")\n st.experimental_rerun()\n\n try:\n st.session_state[\"defaults\"] = OmegaConf.merge(\n st.session_state[\"defaults\"], user_defaults\n )\n except KeyError:\n st.experimental_rerun()\n else:\n OmegaConf.save(\n config=st.session_state.defaults,\n f=\"configs/webui/userconfig_streamlit.yaml\",\n )\n loaded = OmegaConf.load(\"configs/webui/userconfig_streamlit.yaml\")\n assert st.session_state.defaults == loaded\n\n if os.path.exists(\".streamlit/config.toml\"):\n st.session_state[\"streamlit_config\"] = toml.load(\".streamlit/config.toml\")\n\n # if st.session_state[\"defaults\"].daisi_app.running_on_daisi_io:\n # if os.path.exists(\"scripts/modeldownload.py\"):\n # import modeldownload\n # modeldownload.updateModels()\n\n if \"keep_all_models_loaded\" in st.session_state.defaults.general:\n with server_state_lock[\"keep_all_models_loaded\"]:\n server_state[\"keep_all_models_loaded\"] = st.session_state[\n \"defaults\"\n ].general.keep_all_models_loaded\n else:\n st.session_state[\"defaults\"].general.keep_all_models_loaded = False\n with server_state_lock[\"keep_all_models_loaded\"]:\n server_state[\"keep_all_models_loaded\"] = st.session_state[\n \"defaults\"\n ].general.keep_all_models_loaded\n\n\nload_configs()\n\n#\n# if st.session_state[\"defaults\"].debug.enable_hydralit:\n# navbar_theme = {'txc_inactive': '#FFFFFF','menu_background':'#0e1117','txc_active':'black','option_active':'red'}\n# app = st.HydraApp(title='Stable Diffusion WebUI', favicon=\"\", use_cookie_cache=False, sidebar_state=\"expanded\", layout=\"wide\", navbar_theme=navbar_theme,\n# hide_streamlit_markers=False, allow_url_nav=True , clear_cross_app_sessions=False, use_loader=False)\n# else:\n# app = None\n\n#\ngrid_format = st.session_state[\"defaults\"].general.save_format\ngrid_lossless = False\ngrid_quality = st.session_state[\"defaults\"].general.grid_quality\nif grid_format == \"png\":\n grid_ext = \"png\"\n grid_format = \"png\"\nelif grid_format in [\"jpg\", \"jpeg\"]:\n grid_quality = int(grid_format) if len(grid_format) > 1 else 100\n grid_ext = \"jpg\"\n grid_format = \"jpeg\"\nelif grid_format[0] == \"webp\":\n grid_quality = int(grid_format) if len(grid_format) > 1 else 100\n grid_ext = \"webp\"\n grid_format = \"webp\"\n if grid_quality < 0: # e.g. webp:-100 for lossless mode\n grid_lossless = True\n grid_quality = abs(grid_quality)\n\n#\nsave_format = st.session_state[\"defaults\"].general.save_format\nsave_lossless = False\nsave_quality = 100\nif save_format == \"png\":\n save_ext = \"png\"\n save_format = \"png\"\nelif save_format in [\"jpg\", \"jpeg\"]:\n save_quality = int(save_format) if len(save_format) > 1 else 100\n save_ext = \"jpg\"\n save_format = \"jpeg\"\nelif save_format == \"webp\":\n save_quality = int(save_format) if len(save_format) > 1 else 100\n save_ext = \"webp\"\n save_format = \"webp\"\n if save_quality < 0: # e.g. webp:-100 for lossless mode\n save_lossless = True\n save_quality = abs(save_quality)\n\n# this should force GFPGAN and RealESRGAN onto the selected gpu as well\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(st.session_state[\"defaults\"].general.gpu)\n\n\n# functions to load css locally OR remotely starts here. Options exist for future flexibility. Called as st.markdown with unsafe_allow_html as css injection\n# TODO, maybe look into async loading the file especially for remote fetching\ndef local_css(file_name):\n with open(file_name) as f:\n st.markdown(f\"\", unsafe_allow_html=True)\n\n\ndef remote_css(url):\n st.markdown(f'', unsafe_allow_html=True)\n\n\ndef load_css(isLocal, nameOrURL):\n if isLocal:\n local_css(nameOrURL)\n else:\n remote_css(nameOrURL)\n\n\ndef set_page_title(title):\n \"\"\"\n Simple function to allows us to change the title dynamically.\n Normally you can use `st.set_page_config` to change the title but it can only be used once per app.\n \"\"\"\n\n st.sidebar.markdown(\n unsafe_allow_html=True,\n body=f\"\"\"\n